Friday, August 30, 2019

jQuery same click event for multiple elements



Is there any way to execute same code for different elements on the page?




$('.class1').click(function() {
some_function();
});

$('.class2').click(function() {
some_function();
});


instead to do something like:




$('.class1').$('.class2').click(function() {
some_function();
});


Thanks


Answer



$('.class1, .class2').on('click', some_function);



Or:



$('.class1').add('.class2').on('click', some_function);


This also works with existing objects:



const $class1 = $('.class1');
const $class2 = $('.class2');

$class1.add($class2).on('click', some_function);

Will a single USB 3.0 port power two 2.5" hard drives?


Will a single USB 3.0 port have sufficient power (via a non-powered hub) to run two external 2.5" platter hard drives (the type that don't require an AC power adapter)?


The hub is a Sabrent 4-Port USB 3.0 Hub with Individual Power Switches and LEDs (HB-UM43).


The hard drives are Western Digital "My Passport" 1TB USB 3.0 drives (several years old), product # WDBBEP0010BBK-01. Plugging either drive into a USB 3.0 port, does not show any power consumption via Win7's Device Manager (strange). Plugging a drive into a USB 2.0 port shows 500ma. The labels on the hard drives do not reveal power consumption information.


Answer



If you had some ultra low power mechanical drives (I'm not sure they exist), you could, but not two of your drives or any I'm aware of.


The hub, itself, uses some power, then the drives would have to share what's left from the 900 ma connection to the laptop. At 500 ma for each drive, you would exceed what's available.


This would not work even with a special laptop charging port designed to deliver high charging current to an attached device. USB power is in "unit loads" (each unit load for USB 3.0 is 150 ma). USB devices have to negotiate for power beyond the first unit load. Hubs make a standard USB connection, which carries a maximum of 6 unit loads (900 ma) for USB 3.0 drawn from the laptop's port. USB 2.0 has a unit load of 100 ma, and a maximum of five, for a 500 ma limit.


With a powered hub, you could connect both of your drives. The combined data transfer rate for two USB 3.0 mechanical hard drives should still be well within the bandwidth of the hub's USB 3.0 connection.


c++ - Do the parentheses after the type name make a difference with new?



If 'Test' is an ordinary class, is there any difference between:




Test* test = new Test;


and



Test* test = new Test();

Answer



Let's get pedantic, because there are differences that can actually affect your code's behavior. Much of the following is taken from comments made to an "Old New Thing" article.




Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a POD (plain old data), or if it's a class that contains POD members and is using a compiler-generated default constructor.




  • In C++1998 there are 2 types of initialization: zero and default

  • In C++2003 a 3rd type of initialization, value initialization was added.



Assume:




struct A { int m; }; // POD
struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m


In a C++98 compiler, the following should occur:




  • new A - indeterminate value

  • new A() - zero-initialize



  • new B - default construct (B::m is uninitialized)


  • new B() - default construct (B::m is uninitialized)


  • new C - default construct (C::m is zero-initialized)


  • new C() - default construct (C::m is zero-initialized)



In a C++03 conformant compiler, things should work like so:




  • new A - indeterminate value


  • new A() - value-initialize A, which is zero-initialization since it's a POD.


  • new B - default-initializes (leaves B::m uninitialized)


  • new B() - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.


  • new C - default-initializes C, which calls the default ctor.


  • new C() - value-initializes C, which calls the default ctor.



So in all versions of C++ there's a difference between new A and new A() because A is a POD.



And there's a difference in behavior between C++98 and C++03 for the case new B().




This is one of the dusty corners of C++ that can drive you crazy. When constructing an object, sometimes you want/need the parens, sometimes you absolutely cannot have them, and sometimes it doesn't matter.


java - Sort ArrayList of custom Objects by property



I read about sorting ArrayLists using a Comparator but in all of the examples people used compareTo which according to some research is a method for Strings.



I wanted to sort an ArrayList of custom objects by one of their properties: a Date object
(getStartDay()). Normally I compare them by item1.getStartDate().before(item2.getStartDate()) so I was wondering whether I could write something like:




public class CustomComparator {
public boolean compare(Object object1, Object object2) {
return object1.getStartDate().before(object2.getStartDate());
}
}

public class RandomName {
...
Collections.sort(Database.arrayList, new CustomComparator);

...
}

Answer



Since Date implements Comparable, it has a compareTo method just like String does.



So your custom Comparator could look like this:



public class CustomComparator implements Comparator {
@Override

public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}
}


The compare() method must return an int, so you couldn't directly return a boolean like you were planning to anyway.



Your sorting code would be just about like you wrote:




Collections.sort(Database.arrayList, new CustomComparator());


A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:



Collections.sort(Database.arrayList, new Comparator() {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}

});







You can now write the last example in a shorter form by using a lambda expression for the Comparator:



Collections.sort(Database.arrayList, 

(o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));


And List has a sort(Comparator) method, so you can shorten this even further:



Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));


This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:




Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));


All of these are equivalent forms.


java - Hashmap converting to JSONObject every `/` in the hashmap item value is replacing with this `/`

When converting HashMap to JSONObject, every / in the string will replacing with this \/why is like this?? any solution for this?
my string is



 String sumValue= "mZftaLXj7UN19zxc/7n/UZdf....";


but i'm getting like this



D/b: getBody{"****":"*****","*****":"***",SUMHASH":"mZftaLXj7UN19zxc\/7n\/UZdf****"}



I'm tried like this



 public byte[] getBody() {

String sumValue= "mZftaLXj7UN19zxc/7n/UZdf.....";

HashMap params2 = new HashMap();
params2.put("***", "*****");
params2.put("***", "*****");

params2.put("SUMHASH", sumValue);

Log.d(TAG, "getBody" + new JSONObject(params2));

try {
return new JSONObject(params2).toString().getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}}



Given below is the output while doing



System.out.println("getBody" + new JSONObject(params2)); 


enter image description here

How do I empty an array in JavaScript?




Is there a way to empty an array and if so possibly with .remove()?



For instance,



A = [1,2,3,4];


How can I empty that?


Answer



Ways to clear an existing array A:



Method 1



(this was my original answer to the question)



A = [];


This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.



This is also the fastest solution.



This code sample shows the issue you can encounter when using this method:



var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1; // Reference arr1 by another variable
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']


Method 2 (as suggested by Matthew Crumley)



A.length = 0


This will clear the existing array by setting its length to 0. Some have argued that this may not work in all implementations of JavaScript, but it turns out that this is not the case. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.



Method 3 (as suggested by Anthony)



A.splice(0,A.length)


Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.



Method 4 (as suggested by tanguy_k)



while(A.length > 0) {
A.pop();
}


This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.



Performance



Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this benchmark.



As pointed out by Diadistis in their answer below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty.



The following benchmark fixes this flaw: http://jsben.ch/#/hyj65. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array).






This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here. If you vote for this answer, please upvote the other answers that I have referenced as well.


linux - Print single quotes in shell script using option -c

This may sound novice but I tried everything to get this to work.
I want to print a word with single quotes : 'John' in shell script. I cant replace /bin/bash -l -c as this part of code is run by Java and I have to pass the shell command as a string. I tried with echo -e option as well.




/bin/bash -l -c 'echo "'John'"'


The output I want is:



'John'


I tried escaping the single quotes but nothing helped so far. Any ideas?

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...