Sunday, 26 June 2016

oop - How to get a JavaScript object's class?



I created a JavaScript object, but how I can determine the class of that object?



I want something similar to Java's .getClass() method.


Answer



There's no exact counterpart to Java's getClass() in JavaScript. Mostly that's due to JavaScript being a prototype-based language, as opposed to Java being a class-based one.




Depending on what you need getClass() for, there are several options in JavaScript:





A few examples:



function Foo() {}
var foo = new Foo();


typeof Foo; // == "function"
typeof foo; // == "object"

foo instanceof Foo; // == true
foo.constructor.name; // == "Foo"
Foo.name // == "Foo"

Foo.prototype.isPrototypeOf(foo); // == true

Foo.prototype.bar = function (x) {return x+x;};

foo.bar(21); // == 42


Note: if you are compiling your code with Uglify it will change non-global class names. To prevent this, Uglify has a --mangle param that you can set to false is using gulp or grunt.


r - Opposite of %in%




A categorical variable V1 in a data frame D1 can have values represented by the letters from A to Z. I want to create a subset D2, which excludes some values, say, B, N and T. Basically, I want a command which is the opposite of %in%



D2 = subset(D1, V1 %in% c('B','N',T'))

Answer



You can use the ! operator to basically make any TRUE FALSE and every FALSE TRUE. so:



D2 = subset(D1, !(V1 %in% c('B','N','T')))



EDIT:
You can also make an operator yourself:



'%!in%' <- function(x,y)!('%in%'(x,y))

c(1,3,11)%!in%1:10
[1] FALSE FALSE TRUE

numbers in string come out as "not numbers" or fals - Python

So, I have a list of strings in python, and I am trying to find which keys are numbers.
I am trying to use list.[key].isdigit() but it only works with '0'
For instance:




list = ['0', '0', '0', '0.450000000000000', '0', '0', '0', '0.550000000000000']


will only determine that '0' is a digit, but '0.45' and '0.55' are not.
How can I fix this problem?



Thank you very much

javascript - Scoping Issue inside a function




I am having an issue with the scope of a variable. The first two return the correct value but when I subscribe to an event (the event is working) it returns this._id as undefined. I have also tried it as MyFunction._id;



 var i = 0;


var func = new MyFunction();
func.init();

function MyFunction(i){
this._id = i;
}

MyFunction.prototype.init = function(){

Debugger.log("A : " + this._id); //displays the result of i

this.myTest; //displays the result of i
Event.subscribe("UPDATE", this.myTest);// is undefined
}

MyFunction.prototype.myTest = function(){
Debugger.log("B : " + this._id);
}


Thx.



Answer



You have to do:



 Event.subscribe("UPDATE", this.myTest.bind(this));

php - Grabbing the href attribute of an A element



Trying to find the links on a page.




my regex is:



/]*href=(\"\'??)([^\"\' >]*?)[^>]*>(.*)<\/a>/


but seems to fail at



what?



How would I change my regex to deal with href not placed first in the a tag?


Answer



Reliable Regex for HTML are difficult. Here is how to do it with DOM:



$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $node) {
echo $dom->saveHtml($node), PHP_EOL;
}



The above would find and output the "outerHTML" of all A elements in the $html string.



To get all the text values of the node, you do



echo $node->nodeValue; 


To check if the href attribute exists you can do




echo $node->hasAttribute( 'href' );


To get the href attribute you'd do



echo $node->getAttribute( 'href' );


To change the href attribute you'd do




$node->setAttribute('href', 'something else');


To remove the href attribute you'd do



$node->removeAttribute('href'); 


You can also query for the href attribute directly with XPath




$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//a/@href');
foreach($nodes as $href) {
echo $href->nodeValue; // echo current attribute value
$href->nodeValue = 'new value'; // set new attribute value
$href->parentNode->removeAttribute('href'); // remove attribute
}



Also see:





On a sidenote: I am sure this is a duplicate and you can find the answer somewhere in here


Saturday, 25 June 2016

java - Array Index Out Of Bounds Exception





Been looking around to see if anything could help me out but I don't understand much of what people are answering and anything I do understand doesn't seem to solve the issue! So basically as the title says, I'm getting an array index out of bounds exception and I have no idea why. Any help is greatly appreciated.



Code:



import javax.swing.*;

public class Array {
public static void main(String[] args) {
double height[] = new double[10];
String heightAsString;

int i, over18 = 0, under16 = 0;

for(i = 1; i <= height.length; i++){
heightAsString = JOptionPane.showInputDialog("Please Enter The Height Of Person " + i);
height[i] = Double.parseDouble(heightAsString);

if(height[i] > 1.8){
over18 += 1;
}


if(height[i] < 1.6){
under16 += 1;
}
}

JOptionPane.showMessageDialog(null,"The Total Number Of People Over 1.8m Is: " + over18 +
"\nThe Total Number Of People Under 1.6m Is: " + under16);
}
}


Answer



for(i = 1; i <= height.length; i++){
heightAsString = JOptionPane.showInputDialog("Please Enter The Height Of Person " + i);
height[i-1] = Double.parseDouble(heightAsString);

if(height[i-1] > 1.8){
over18 += 1;
}

if(height[i-1] < 1.6){

under16 += 1;
}
}


use height[i-1], because array index starts from 0.


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


c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...