text:
Q: Enumerating Enum class from type parameter Hi I'm trying to provide an enum to a generic class so I can iterate over the a set of members defined by the supplied Enum type parameter.  I found a way to do this, but in order for it to work, I need to supply an arbitrary instance of the enum.
public enum suits {
        spades,
        hearts,
        diamonds,
        clubs;
}

public static class Card<E extends Enum<E>> {
  public final EnumSet<E> suits;

  public Card(E instance) {
     EnumSet<E> mySet = EnumSet.allOf(instance.getDeclaringClass());
     this.suits = mySet;
  }
}

Now I can do something like this:
Card<Suits> myCard = new Card<Suits>(Suits.clubs);
String names = "";
for (Suit s : myCard.suits) {names += s.name + "|";} // "spades|hears|diamonds|clubs|

Here is the question:    Can I do this without supplying an instance of the enum in the Card object constructor?
What I would think ought to work is to replace instance.getDeclaringClass() with the type parameter when creating the enum, as in:
EnumSet<E> mySet = EnumSet.allOf(E);

but that gives a syntax error.  Somehow it seems like it should be possible to get type type parameter without having to resort to supplying an enum instance and then calling getDeclaringClass().

A: You can pass in Suits.class, but you need one or the other -- either an instance of the enum type, or a Class object for the enum type.


text:
Q: Rare behavior with mongodb cursor (DBCursor) in java, even though last element is already reached I have a collection called MyCollection that contains 200 elements in the bd MyDB in mongodb
> use MyDB
switched to db MyDB
> db.MyCollection.count()
200

I'm getting a really rare behavior, even in the different ways I have used to load the cursor and iterate on it, this is my code:
DBCollection collection = getCollection("MyBD", "MyCollection");
DBCursor cursor = collection.find();
//DBCursor cursor = collection.find().limit(200);
System.out.println("Cursor length: "+cursor.length());
Iterator<DBObject> itrc = cursor.iterator();
//while(cursor.hasNext()){
while (itrc.hasNext()) {
    //DBObject obj = (DBObject)cursor.next();
    DBObject obj = (DBObject)itrc.next();
    //BSONObject obj2 = (BSONObject)obj.get("scores");
    Integer intg = (Integer) obj.get("_id");
    System.out.println("_id:"+intg.toString());

    // operations remove and insert  on the collection
    // that affect the cursor behavior
    BasicDBList bl = (BasicDBList) obj.get("fieldArray");
    BasicDBObject bdo = new BasicDBObject();
    bdo.put("fieldArray", bl);
    Integer intid = (Integer) obj.get("_id");
    bdo.put("_id", intid);
    String str = (String) obj.get("fieldString");
    bdo.put("fieldString", str);
    collection.remove(obj);
    obj=null;
    collection.insert(bdo);

    if(intg.intValue()==199){
        System.out.println("Reached: "+intg.intValue());
    }
}

This is the output:
Cursor length: 200
_id:0 _id:1 _id:2 _id:3 _id:4 _id:5 _id:6 _id:7 _id:8 _id:9 _id:10 _id:11 _id:12 _id:13 _id:14 _id:15 _id:16 _id:17 _id:18 _id:19 _id:20 _id:21 _id:22 _id:23 _id:24 _id:25 _id:26 _id:27 _id:28 _id:29 _id:30 _id:31 _id:32 _id:33 _id:34 _id:35 _id:36 _id:37 _id:38 _id:39 _id:40 _id:41 _id:42 _id:43 _id:44 _id:45 _id:46 _id:47 _id:48 _id:49 _id:50 _id:51 _id:52 _id:53 _id:54 _id:55 _id:56 _id:57 _id:58 _id:59 _id:60 _id:61 _id:62 _id:63 _id:64 _id:65 _id:66 _id:67 _id:68 _id:69 _id:113 _id:101 _id:102 _id:103 _id:104 _id:105 _id:106 _id:107 _id:108 _id:109 _id:110 _id:111 _id:112 _id:114 _id:115 _id:116 _id:117 _id:118 _id:119 _id:120 _id:121 _id:122 _id:123 _id:124 _id:125 _id:126 _id:127 _id:128 _id:129 _id:130 _id:131 _id:132 _id:133 _id:134 _id:135 _id:136 _id:137 _id:138 _id:139 _id:140 _id:141 _id:142 _id:143 _id:144 _id:145 _id:146 _id:147 _id:148 _id:149 _id:150 _id:151 _id:152 _id:153 _id:154 _id:155 _id:156 _id:157 _id:158 _id:159 _id:160 _id:161 _id:162 _id:163 _id:164 _id:165 _id:166 _id:167 _id:168 _id:169 _id:170 _id:171 _id:172 _id:173 _id:174 _id:175 _id:176 _id:177 _id:178 _id:179 _id:180 _id:181 _id:182 _id:183 _id:184 _id:185 _id:186 _id:187 _id:188 _id:189 _id:190 _id:191 _id:192 _id:193 _id:194 _id:195 _id:196 _id:197 _id:198 _id:199
***************************
Reached: 199
***************************
 _id:70 _id:71 _id:72 _id:73 _id:74 _id:75 _id:76 _id:77 _id:78 _id:79 _id:80 _id:81 _id:82 _id:83 _id:84 _id:85 _id:86 _id:87 _id:88 _id:89 _id:90 _id:91 _id:92 _id:93 _id:94 _id:95 _id:96 _id:97 _id:98 _id:99 _id:100_id:96 _id:97 _id:98 _id:99 _id:100

As it can see , once the limit of 200 elements is reached (element _id:199), it jumps to  the element with _id:70, then it repeats 31 additional iterations until the element _id:100 is reached, instead than finished in the right time that would be at the 200 iteration.
The alternatives: the one is commented in the code (using the cursor's method: hasNext()) and the other one that is running (using an Iterator) both have the same output.
If I remove the operations part  on the collection (remove/insert in my case), then the rare behavior does not happen.
This is the expected output:
Cursor length: 200
_id:0 _id:1 _id:2 _id:3 _id:4 _id:5 _id:6 _id:7 _id:8 _id:9 _id:10 _id:11 _id:12 _id:13 _id:14 _id:15 _id:16 _id:17 _id:18 _id:19 _id:20 _id:21 _id:22 _id:23 _id:24 _id:25 _id:26 _id:27 _id:28 _id:29 _id:30 _id:31 _id:32 _id:33 _id:34 _id:35 _id:36 _id:37 _id:38 _id:39 _id:40 _id:41 _id:42 _id:43 _id:44 _id:45 _id:46 _id:47 _id:48 _id:49 _id:50 _id:51 _id:52 _id:53 _id:54 _id:55 _id:56 _id:57 _id:58 _id:59 _id:60 _id:61 _id:62 _id:63 _id:64 _id:65 _id:66 _id:67 _id:68 _id:69 _id:113 _id:101 _id:102 _id:103 _id:104 _id:105 _id:106 _id:107 _id:108 _id:109 _id:110 _id:111 _id:112 _id:114 _id:115 _id:116 _id:117 _id:118 _id:119 _id:120 _id:121 _id:122 _id:123 _id:124 _id:125 _id:126 _id:127 _id:128 _id:129 _id:130 _id:131 _id:132 _id:133 _id:134 _id:135 _id:136 _id:137 _id:138 _id:139 _id:140 _id:141 _id:142 _id:143 _id:144 _id:145 _id:146 _id:147 _id:148 _id:149 _id:150 _id:151 _id:152 _id:153 _id:154 _id:155 _id:156 _id:157 _id:158 _id:159 _id:160 _id:161 _id:162 _id:163 _id:164 _id:165 _id:166 _id:167 _id:168 _id:169 _id:170 _id:171 _id:172 _id:173 _id:174 _id:175 _id:176 _id:177 _id:178 _id:179 _id:180 _id:181 _id:182 _id:183 _id:184 _id:185 _id:186 _id:187 _id:188 _id:189 _id:190 _id:191 _id:192 _id:193 _id:194 _id:195 _id:196 _id:197 _id:198 _id:199
***************************
Reached: 199
***************************

I had found a similar SO question, but it is not clear to me:

*

*how can the operations remove/insert affect the cursor behavior in the way I have exposed before?

*how  can I use the snapshot option?

*thinking ahead, what about if I need to work with the ordered collection?

BTW, if I use the option without iterator, like this:
while(cursor.hasNext()){
    DBObject obj = (DBObject)cursor.next();

*

*Why do I have to delete the next line?
System.out.println("Cursor length: "+cursor.length());
In order to avoid the next exception:
Exception in thread "main" java.lang.IllegalArgumentException: can't switch cursor access methods
    at com.mongodb.DBCursor._checkType(DBCursor.java:412)
    at com.mongodb.DBCursor.hasNext(DBCursor.java:483)
    at tasks.UpdateRemoveHW.main(Test.java:56)

A: Just throw the Exception IllegalArgumentException, then you get that use of DBCursor.length()  will already converted curser into an array.So after that using hasnext(), next is illegegal. If you want to use hasnext() or next() better to remove length() before iteration.

A: I'm not sure what is happening with your rare behaviour in the first part of your question, however in general it is unsafe to modify any data structure while you are iterating over it except via the Iterator.remove() method.

The last part of your question is indirectly answered by the following Warning at the top of the API Documentation for DBCursor:

Warning: Calling toArray or length on a DBCursor will irrevocably turn it into an array. This means that, if the cursor was iterating over ten million results (which it was lazily fetching from the database), suddenly there will be a ten-million element array in memory. Before converting to an array, make sure that there are a reasonable number of results using skip() and limit().

If you read the source code for DBCursor (line 483) where it is throwing the IllegalArgumentException you can see that any call to DBCursor.length() turns the cursor into an array, after which time all calls to DBCursor.next() or DBCursor.hasNext() become Illegal.
I think this behaviour definately violates the Principle of Least Surprise.  Arrays can still have Iterators, so it would be better if the internal data structure was hidden and the Iterator methods continue to work.  Also, calling DBCursor.length() does not have to fetch any the records from the DB, I think it should behave similar to DBCursor.count() but somehow take into account limit() and skip() and then cache the result.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to dynamically register the bean specific properties on bean initialization I want to register the bean specific properties on bean creation if not exists in the application. For example
public class BeanOne {
    @Value("${prop1}")
    private String property1;
}

public class BeanTwo {
    @Value("${prop2}")
    private String property2;
}

I want to register the property 'prop1' and 'prop2' to instantiate the above two beans successfully.
My application is configured with spring-cloud-consul-config. By default consul is not configured with these properties in that time, application will automatically register these properties into consul through ecwid/consul-api
Currently the application throws "IllegalArgumentException" with message "Could not resolve placeholder 'prop1' in string value "${prop1}"
Any Suggestions to avoid the above error.

A: There are various ways you can do this.
My preferred approach is to set the properties in one or more files externally and then use the @PropertySource("file:///full-path-to-property-file") annotation in a @Configuration class.
This approach, combined with Spring Profiles is very powerful.
Example if you are not using profiles:

*

*Create an application.properties file somewhere on your PC. A good
place to put this is ${user.home}/.somefolder/application.properties

*Add the values for prop1 and prop2

*Change the permissions on that folder and file. For example you can
run chmod u on .somefolder and chmod 600 on the properties file

*Create a Spring Java Configuration class and annotate it with
@Configuration. For example you can create an ApplicationConfig
class in a sub package of your Spring Boot application and annotate
it with @Configuration

*Add the @PropertySource annotations as follows:
@PropertySource("file:///${user.home}/.somefolder/application.properties")

An example from my course on Spring Boot, AWS, Bootstrap and Stripe:
@Configuration
@EnableJpaRepositories(basePackages = "com.devopsbuddy.backend.persistence.repositories")
@EntityScan(basePackages = "com.devopsbuddy.backend.persistence.domain.backend")
@EnableTransactionManagement
@PropertySource("file:///${user.home}/.devopsbuddy/application-common.properties")
public class ApplicationConfig {
}

That's it!


text:
Q: Paper.js vector operation I'm new to paper.js and ran into some troubles.
<script type="text/paperscript" canvas="canvas">
        function onMouseDrag(event) {
            // The radius is the distance between the position
            // where the user clicked and the current position
            // of the mouse.
            var path = new Path.Circle({
                center: event.downPoint,
                radius: (event.downPoint - event.point).length,
                fillColor: 'white',
                strokeColor: 'black'
            });

            // Remove this path on the next drag event:
            path.removeOnDrag();
        };
</script>

In this code the (event.downPoint - event.point).length works well but i want to use javascript directly so i did:
<script type="text/javascript">
paper.install(window);
// Keep global references to both tools, so the HTML
// links below can access them.
var line_tool, circle_tool;

window.onload = function() {
    paper.setup('myCanvas');

    line_tool = new Tool();
    line_tool.onMouseDrag = function (event) {
                var path = new Path.Line({
                    from: event.downPoint,
                    to: event.point,
                    strokeColor: 'black'
                });

            path.removeOnDrag();

        };

    circle_tool = new Tool();
    circle_tool.onMouseDrag = function (event) {
            var path = new Path.Circle({
                center: event.downPoint,
                radius: (event.downPoint - event.point).length,
                fillColor: 'white',
                strokeColor: 'black'
            });
            path.removeOnDrag();

        };
    }
   </script>

The 'line tool' works as expected but here in the 'circle tool' (event.downPoint - event.point) returns NaN. I suppose it's trying to do "{ x: 110, y: 200 }-{ x: 100, y: 300 }" and failing because obviously it's expecting two numbers, but in Paper.js documentation says it can handle vectors in this format (and it actually works in the first piece of code). Should I call someway paper.js to calculate this type of operations? Probably it's a silly thing but i couldn't find anything about this kind of situation. Is there something like paper( //do this piece of code like it was part of a 'text/paperscript' script) ?
Thanks!

A: Paper.js operator overloading for vector operations only works when you include the library with type="text/paperscript". Otherwise you have to use: add, subtract, multiply, divide, modulo, equals for +, -, *, /, % and ==.
like so:
point1.add([ 200, -50 ]);

or for your example:
radius: event.downPoint.subtract(event.point).length,

Here is your example with subtract and here are some more examples and tests.


text:
Q: Merge sort same output C++ I wrote the below code for merge sort but it's not working, And I am unable to find out problem!
Every time the output becomes same as input, I think that problem may occur due to vector reference.
I think mergeSort is not creating a new vector for sub array. But I am still confused.
input vector: 5, 4, 3, 2, 1
output: 5, 4, 3, 2, 1
Req output: 1, 2, 3, 4, 5
#include <iostream>
#include <vector>

using namespace std;

void merge(vector<int> &la, vector<int> &ra, vector<int> &A) {

    int i = 0, j = 0, k = 0;

    //  overwriting A using its solved sub arrays i.e la, ra
    while (i < la.size() && j < ra.size()) {
        if (la[i] <= ra[j]) {
            A[k] = la[i];
            i++;
            k++;
        } else {
            A[k] = ra[j];
            j++;
            k++;
        }
    }

    //  if any subarray left then
    while (i < la.size()) {
        A[k] = la[i];
        k++;
        i++;
    }
    while (j < ra.size()) {
        A[k] = ra[j];
        k++;
        j++;
    }
}

mergeSort function:
void mergeSort(vector<int> &A) {

    if (A.size() < 2)
        return;

    int len = A.size();
    vector<int> la, ra;

    for (int i = 0; i < len / 2; i++)
        la.push_back(A[i]);

    for (int i = len / 2; i < len; i++)
        ra.push_back(A[i]);

    //  dividing the proble into subproblem
    mergeSort(la);
    mergeSort(ra);

    //  merging the solved subproblem
    merge(la, ra, A);
}

Driver function:
int main(void) {
    int arr[] = { 5, 4, 3, 2, 1 };
    vector<int> A(arr, arr + 5);
    for (int i = 0; i < A.size(); i++)
        cout << A[i] << " ";
    cout << endl;

    mergeSort(A);

    for (int i = 0; i < A.size(); i++)
        cout << A[i] << " ";
    return 0;
}

A: The code posted does not seem to have a problem.
Executing it produces the expected output: 1 2 3 4 5, so there is something else going on that could cause your observations: you might be running an executable produced by a previous or at least different version of the code.


text:
Q: Why won't jsontool parse my array? I'm having trouble parsing this json, which contains an array as its outermost element:
response=[ { "__type": "File", "name": "...tfss-ea51ec70-d3a8-45e5-abbf-294f2c2c81f0-myPicture.jpg", "url": "http://files.parse.com/ac3f079b-cacb-49e9-bd74-8325f993f308/...tfss-ea51ec70-d3a8-45e5-abbf-294f2c2c81f0-myPicture.jpg" } ]

for blob in $response
do
    url=$(echo $blob | json url)
done

But this last json parsing gives a bunch of errors:
json: error: input is not JSON: Bad object at line 2, column 1:

    ^

Do I need to do something special to turn a JSON array into a bash array, or vice versa?

A: You should quote the value of reponse to protect it from the shell trying to interpret it:
response='[ { "__type": "File", "name": "...tfss-ea51ec70-d3a8-45e5-abbf-294f2c2c81f0-myPicture.jpg", "url": "http://files.parse.com/ac3f079b-cacb-49e9-bd74-8325f993f308/...tfss-ea51ec70-d3a8-45e5-abbf-294f2c2c81f0-myPicture.jpg" } ]'

And you can't expect the shell to be able to parse JSON, so for blob in $response isn't going to work out. According to http://trentm.com/json/, using -a should handle the array:
while read url ; do
   # use $url here...
done < <(echo "$response" | json -a url)

A: After putting your json in a file and piping it through jsontool it works just fine, so I'm guessing your file has some weird whitespace which is breaking in jsontool.
Try this instead:
cat your_file.json | sed 's/[[:space:]]\+$//' | json


text:
Q: Question on a solution from Google python class day Hey,
I'm trying to learn a bit about Python so I decided to follow Google's tutorial. Anyway I had a question regarding one of their solution for an exercise.
Where I did it like this way.
# E. Given two lists sorted in increasing order, create and return a merged
# list of all the elements in sorted order. You may modify the passed in lists.
# Ideally, the solution should work in "linear" time, making a single
# pass of both lists.
def linear_merge(list1, list2):
  # +++your code here+++
  return sorted(list1 + list2)

However they did it in a more complicated way. So is Google's solution quicker? Because I noticed in the comment lines that the solution should work in "linear" time, which mine probably isn't?
This is their solution
def linear_merge(list1, list2):
  # +++your code here+++
  # LAB(begin solution)
  result = []
  # Look at the two lists so long as both are non-empty.
  # Take whichever element [0] is smaller.
  while len(list1) and len(list2):
    if list1[0] < list2[0]:
      result.append(list1.pop(0))
    else:
      result.append(list2.pop(0))

  # Now tack on what's left
  result.extend(list1)
  result.extend(list2)
  return result

A: this could be another soln?
#
    def linear_merge(list1, list2):
            tmp = []
            while len(list1) and len(list2):
                    #print list1[-1],list2[-1]
                    if list1[-1] > list2[-1]:
                            tmp.append(list1.pop())
                    else:
                            tmp.append(list2.pop())
                    #print "tmp = ",tmp

            #print list1,list2
            tmp = tmp + list1
            tmp = tmp + list2
            tmp.reverse()
            return tmp

A: Yours is not linear, but that doesn't mean it's slower.  Algorithmic complexity ("big-oh notation") is often only a rough guide and always only tells one part of the story.
However, theirs isn't linear either, though it may appear to be at first blush.  Popping from a list requires moving all later items, so popping from the front requires moving all remaining elements.
It is a good exercise to think about how to make this O(n).  The below is in the same spirit as the given solution, but avoids its pitfalls while generalizing to more than 2 lists for the sake of exercise.  For exactly 2 lists, you could remove the heap handling and simply test which next item is smaller.
import heapq

def iter_linear_merge(*args):
  """Yield non-decreasing items from sorted a and b."""
  # Technically, [1, 1, 2, 2] isn't an "increasing" sequence,
  # but it is non-decreasing.

  nexts = []
  for x in args:
    x = iter(x)
    for n in x:
      heapq.heappush(nexts, (n, x))
      break

  while len(nexts) >= 2:
    n, x = heapq.heappop(nexts)
    yield n
    for n in x:
      heapq.heappush(nexts, (n, x))
      break

  if nexts:  # Degenerate case of the heap, not strictly required.
    n, x = nexts[0]
    yield n
    for n in x:
      yield n

Instead of the last if-for, the while loop condition could be changed to just "nexts", but it is probably worthwhile to specially handle the last remaining iterator.
If you want to strictly return a list instead of an iterator:
def linear_merge(*args):
  return list(iter_linear_merge(*args))

A: With mostly-sorted data, timsort approaches linear. Also, your code doesn't have to screw around with the lists themselves. Therefore, your code is possibly just a bit faster.
But that's what timing is for, innit?

A: I think the issue here is that the tutorial is illustrating how to implement a well-known algorithm called 'merge' in Python. The tutorial is not expecting you to actually use a library sorting function in the solution.
sorted() is probably O(nlgn); then your solution cannot be linear in the worst case.
It is important to understand how merge() works because it is useful in many other algorithms. It exploits the fact the input lists are individually sorted, moving through each list sequentially and selecting the smallest option. The remaining items are appended at the end.
The question isn't which is 'quicker' for a given input case but about which algorithm is more complex.
There are hybrid variations of merge-sort which fall back on another sorting algorithm once the input list size drops below a certain threshold.


text:
Q: Setting up a Database in-house for whole company use I started exploring Databases and PostgreSQL not long ago, my goal is to create a database for my company, in which I can upload data and other people can access it through ODBC connections and explore it in Excel. I managed to create a test database in my PC and everything worked properly.
I then moved to the next step, which would be sharing this test database with my colleagues.
I guess that the database could not be stored in my own PC (as it is today) , because people need to be able to access it even when it is turned off.
We have a Network Drive, where currently all our data is stored. Is it possible to host my database in there? What else should I know for this project I'm conducting?
I'm quite new to the subject and I'm just trying to explore some possibilities.
(We all run Windows)


text:
Q: Shared preference and SQLite I want to confirm my understanding about sharedPreference and SQLite. Please help me.
shared preference

*

*store private primitive data in key-value pair.

*Useful for store small amount of data

*Data stored in xml file, and without encryption. Thus it is not secure.

*Able to access by other apps. Not secure.

SQLite

*

*Does not require any server, it store locally in the mobile device.

*Useful for store small or large amount of data.

*Data stored is encrypted. Thus more secure.

*Not accessible outside the app. Thus more secure.

Please correct me if anything wrong. Thank you.

A: SP-1. is Correct. So is SQLite-1. However SQLite cannot directly store Boolean, the minimum is 1 byte which can be used as a Boolean. SQLite can store byte arrays as BLOBs other than that the type of data that can be stored is very much the same.
SP-2. Is basically correct and so is SQLite-2. However, you could argue that you could usefully save large amounts of data in shared preferences. When it boils down to it they are both files.
3/4. The data is stored with the same protection (using the default for SQLite) which is private to the App. However, there is an option to encrypt the database. Access by other App's has to be given. Obviously rooted devices are an exception.
In short they are quite similar except when it comes to the data being structured when SQLite leaps ahead of shared preferences in manageability capabilities.

A: You are somewhere correct, so I want to add some more points.
Shared Preference:

*

*Shared preference is also secure. If you set shared preference as a private_mode.

*Storing the data in cache memory..

*Shared preferences can only store key-value pairings whilst an SQLite database is much more flexible.

SQLite

*

*SQlite provides database at mobile/device just like another RDBMS. If you uninstall the application. The database will also get deleted.

*We can't see our database directly, for this you need some applications (needs ROOT permissions).

For more information you can visit here.

A: That's not true because we can't tell the deference between Shared Preference and SQLite.
Shared preferences is something like windows registry and we use share preferences when we want to store some small configuration data and it's safe and has many ways to close access from other applications.
But SQLite is a database and the main data that you are working with , should be there and it's safe and has good speed and saving and retrieving data is very fast and easily.
Good Luck


text:
Q: IE charset encoding issue with JavaScript Date functions Could someone please explain why IE has a bug when trying to use String functions on a Date function that uses the "Locale"? I think it has something to do with encoding of the characters.
Check this out  jsFiddle in both IE and Chrome and you will see that in Chrome we get 4 (the correct index) and in IE we get 8. Does this have to do with ascii vs. unicode? If so, should this be a bug in IE?
var date = new Date();

var str = date.toLocaleTimeString();
jQuery('#a').text(str);

jQuery('#b').text(str.lastIndexOf(":"));

str = date.toTimeString();
jQuery('#c').text(str);
jQuery('#d').text(str.lastIndexOf(":"));

Screen shot of IE 11 jsFiddle output

A: Here's a modified fiddle. For whatever reason, the IE 11 string has a bunch of extra Unicode "left-to-right mark" characters embedded in it.
The code I added was
var s = '';
for (var i = 0; i < str.length; ++i)
    s  += str.charCodeAt(i) + ' ';
$('#c').text(s);

and an accompanying <h4> like the others.
Also see this other Stackoverflow question on the topic.

A: By definition Date.toLocaleTimeString() produces output according to user's preferences/defaults.
So the result (position of : ) can vary on different platforms, locales and even time of the day.
This is how Korean time looks like for example:
"오후 12:00:00"

Apparently in your case Chrome and IE have different opinion on default locale formatting.
If you have any code that relies on position of : in toLocaleTimeString() it must be refactored to something more reliable.
In some locales/settings toLocaleTimeString() may not contain : at all.


text:
Q: Why use "self" and what does it mean? So, I just started learning Objective-C and I've come across this "self" thing.  I've only ever used C, but I think it's used in java too maybe?  Can someone explain?  Here's an example:
- (IBAction)digitPressed:(UIButton *)sender
{
    NSString *digit = [sender currentTitle];
    UILabel *myDisplay = [self display];  //why this?
}

Why isn't it just this?
- (IBAction)digitPressed:(UIButton *)sender
{
        NSString *digit = [sender currentTitle];
        UILabel *myDisplay = display;  //why not like this?
}

display is a UILabel *

A: [self display], or self.display, refers to a property / method (property is just a shortcut for get/set method anyway) if you have something like this in the .h file
@property (weak, nonatomic) UILabel* display;

or
-(UILabel*)display;

Just display, or self->display refers to an instance variable. This is valid when you have declared an instance var like this:
@implementation MyClass {
    UILabel* display;
}

If you have declared the property display in the .h file and haven't changed its default, the corresponding instance var will be _display (note the underscore), in which case the following will be the same:
self.display and self->_display

A: In this case it's an objective C messaging thing. When you see the brackets it's doing this:
[Object Message]

Basically self is the object and display is the message your sending it. Sending it a message is like a method call in another language, but a little different under the hood. So something like this:
[self doSomethingCool];

in objective C would translate to something like this in another language:
this.doSomethingCool();

of course if running a method on another object you'll replace self with that object like:
[myObject doSomethingCool];

in a lot of languages you don't really need to have the "this" in front of your method call, it's implied that if you don't include it you're running the method in the object you're working with. I got burned pretty early on when I started with something similar. I had a call to a datalayer method where you could save an object and it would give you an integer back. When I was saving the object I didn't put the self in front of the method call and it was essentially generating a new object and saving it and I wasn't getting the right integer back.
Using "self" just explicitly tells it "I'm using THIS object". Same thing with properties, I always use "self.MyProperty" instead of "MyProperty" because I want to be explicit and make sure I'm using the MyProperty of the object I'm working in. It's semi rare for a defect like that to hit you, where you expect to be using a certain object and the environment thinks you're using another, but man when you run into one it's a head scratcher because everything looks right.

A: The word self refers to the current object, which is your view controller instance in this case, and combining it with a method name, which is display, means you are sending the message display to self which is the view controller. This will invoke the method display declared in your view controller instance.
You might declare the display method in your view controller, for example:
- (UILabel)display
{
    //your display method implementation returning UILabel instance
}

For the second one, it means you are referring to display variable. For example:
UILabel *display = [[UILabel alloc] init];

A: display is not a UILabel * - it might be a property with that type, or a method which returns a value of that type, but these a rather different things.
You need to go an read something about object oriented programming. The self in Objective-C is the current object reference, other OO languages call it this - both Java and C++ use that name. Understanding objects and methods is fundamental to using any of these languages.

A: There's a very good explanation of this here:
http://useyourloaf.com/blog/2011/02/08/understanding-your-objective-c-self.html
The key section for your question is the section on Objective-C 2.0 dot syntax:

Objective-C Dot Syntax
The dot syntax was introduced with Objective-C 2.0 and generates a lot
  of debate. A number of experienced and long time Cocoa programmers
  recommend avoiding it completely. Others such as Chris Hanson have a
  different view about when to use properties and dot notation.
  Whichever side of the argument you fall I guess the main thing is to
  be consistent.
Anyway the main thing to understand about the dot syntax is that the
  following two statements are doing the same thing:

self.timestamp = [NSDate date];
[self setTimestamp:[NSDate date]];

The dot is just a shortcut for the more traditional Objective-C method
  call. Any time you see a dot you can replace it with the equivalent
  square bracket method call syntax. It is important to understand
  however that this is not the same as writing the following:
timestamp = [NSDate date]; Without the self object and the dot we are
  no longer sending an object a message but directly accessing the ivar
  named timestamp. Since this bypasses the setter method we will
  overwrite the timestamp ivar without first releasing the old NSDate
  object. We will also not retain the new object that we are assigning.
  Both of these situations are bad!

Keep in mind that the examples were written without using ARC, so there's a lot of references to memory management, retain, release etc. It is however useful to see these examples so that you have some idea of what ARC is doing in the background.
In your example, you are not referring to the actual display property with [self display] you are in fact referring to an instance method of the "self" object which in this case is your UIViewController.


text:
Q: New pandas dataframe with an existing column as input to a function that maps to another value I am creating a database of Currencies that I need to be mapped to a different code that will help me manipulate them in an easier fashion understandable by my IT system.
My database is loaded as below:
url = "My RawData csv"

The csv has the below format:
Underlying    Notional
AUDBRL        50,000
AUDCAD        100,000
AUDNZD        20,000
USDJPY        15,000
AUDKRW        12,000

etc

data = pd.read_csv(url)
data = data.dropna() $

I am also loading a Mapping guide that I attach and I access the values there via:
url2 = "My Mapping csv"
Which has a format as below:
Unique CCY Pairs      CCYs
USDJPY            JPY
EURAUD            ADEU
USDRUB            RUB
AUDKRW            KWAD
EURUSD            EUR
AUDJPY            JYAD
EURJPY            JYEU

mapp = pd.read_csv(url2)
mapp = mapp.set_index('Unique CCY Pairs')
mapp.loc[CCY].values[0] $

where CCY is whatever currency is there at each point in time.
Now based on this I want to create a loop in my existing database that will give me the mapped value in the new CCY value column in my dataframe:
I have started with something like the below that obviously did not work and then got stuck in between lambda and map functions.
for CCY in data.Underlying:
 data["new"] = mapp.loc[CCY].values[0]

The above did not work as the data["new"] is not getting looped while the new inputs are assigned so there is only one unique value added in the new created column.
I am looking for ways to make this as effective as possible as my database will be quite big.
Thank you in advance for your help.

A: Its not very clear as to what is the expected output, but in general you can map without loop
data['New'] = data['Underlying'].map(mapp['CCYs'])

    Underlying  Notional    New
0   AUDBRL      50,000      NaN
1   AUDCAD      100,000     NaN
2   AUDNZD      20,000      NaN
3   USDJPY      15,000      JPY
4   AUDKRW      12,000      KWAD


text:
Q: Imagebutton layout_center_inparent problem i am having a problem with my imagebutton it does not align right when i specify the centerinparent.
<LinearLayout
        android:layout_width="match_parent" android:layout_marginTop="4dp"
        android:layout_marginLeft="4dp" android:layout_marginRight="4dp"
        android:layout_height="50dp" android:background="#FF0000">

        <RelativeLayout android:layout_height="match_parent"
            android:layout_width="40dp" android:background="#0000FF">
            <ImageView android:id="@+id/imgType"
                android:layout_centerInParent="true" android:layout_width="wrap_content"
                android:src="@drawable/type_text" android:layout_height="wrap_content" />
        </RelativeLayout>

        <RelativeLayout android:layout_height="match_parent"
            android:layout_width="match_parent" android:layout_weight="1">
            <LinearLayout android:orientation="vertical"
                android:layout_height="match_parent" android:layout_width="match_parent">
                <TextView android:layout_width="match_parent"
                    android:textColor="#686a68" android:layout_height="match_parent"
                    android:textSize="15dp" android:text="Manifest : Text"
                    android:ellipsize="end" android:singleLine="true"
                    android:layout_weight="1" />

                <TextView android:layout_width="match_parent"
                    android:textColor="#686a68" android:layout_height="match_parent"
                    android:textSize="15dp" android:id="@+id/txtTitle" android:text="[TEXT NAME]"
                    android:layout_weight="1" android:singleLine="true"
                    android:ellipsize="end" />
            </LinearLayout>
        </RelativeLayout>

        <RelativeLayout android:layout_height="match_parent"
            android:layout_width="60dp" android:background="#00FF00">
            <ImageButton android:src="@drawable/type_text"
                android:layout_height="48dp" android:layout_centerInParent="true"
                android:layout_width="48dp" android:id="@+id/butEdit" />
        </RelativeLayout>

    </LinearLayout>

image
As you can see the vertical alignment of the imagebutton is not right.
why is it doing this.

A: Have you tried running this on the emulator and using the hierarchyviewer tool (in the "tools" folder of the SDK. Click on your app in the list and select "Load View Hierarchy" ) to inspect the elements in question? Have a look at the margins and padding of both the problem control & its container. Also look at the widths of the various components and it may give you a clue as to where the problem is occurring.
Also check that your drawable in @drawable/type_text does not contain any space around it which could be causing a perceived offset (unlikely, I think).
I have occasionally seen odd problems scaling images, so if @drawable/type_text is not 48x48 pixels, try manually scaling the image to the desired size in Photoshop / GIMP / PSP and see if that makes a difference.
Alternatively try using gravity to try to centre your control:
<LinearLayout android:layout_height="match_parent" android:gravity="center"
    android:layout_width="60dp" android:background="#00FF00">
    <ImageButton android:src="@drawable/type_text"
        android:layout_height="48dp"
        android:layout_width="48dp" android:id="@+id/butEdit" />
</LinearLayout>

Or maybe:
<LinearLayout android:layout_height="match_parent" android:gravity="center"
    android:layout_width="wrap_content" android:background="#00FF00">
    <ImageButton android:src="@drawable/type_text"
        android:layout_height="48dp" android:layout_width="48dp"
        android:layout_margin="12dp" android:id="@+id/butEdit" />
</LinearLayout>

If all else fails, try tweaking the individual android:layout_margin* attributes of the ImageButton to try and force things.
I hope that some of this helps.


text:
Q: Post a bookdown folder to microsoft teams Create a Teams tab whose web content is a folder of linked html/aspx documents, where the "landing page" is index.html/aspx.
I want the web content(referenced below) to be a folder of linked html/aspx documents I upload to teams.  (Not an externally hosted web page.)
Tabs are Teams-aware webpages embedded in Microsoft Teams. They are simple
 HTML <iframe> tags that point to domains declared in the app manifest and
can be added as part of a channel inside a team, group chat, or personal
app for an individual user. You can include custom tabs with your app to
embed your own web content in Teams or add Teams-specific functionality to
your web content.

Here I document what I have tried to solve this problem, pointers, even if to a tutorial, would be welcome.
I would like to include a "book" created by RStudio Bookdown https://bookdown.org/ in a Teams tab.  Bookdown creates an index.html HTML document and other HTML documents connected with relative links. The r package is created by Yihui Xie.  Microsoft has advise about creating a content page:  https://learn.microsoft.com/en-us/microsoftteams/platform/tabs/how-to/create-tab-pages/content-page  This page states that
A content page is a webpage that is rendered within the Teams client

That seems to hint that this can be done.
For your page to display in Teams, you must include the Microsoft Teams
JavaScript client SDK and include a call to microsoftTeams.initialize()
after your page loads. That is how your page and the Teams client
communicate:

The MS document indicates that the ending should be aspx not html.  There should be the line <script src= 'https://statics.teams.cdn.office.net/sdk/v1.6.0/js/MicrosoftTeams.min.js'></script> in the <head> section.  This is for the " Teams client JavaScript SDK"  Also the line microsoftTeams.initialize(); needs to be in the script section.
I created a Hello World document with the content listed in the example:
<!DOCTYPE html>
<html>
<head>

    <script src= 'https://statics.teams.cdn.office.net/sdk/v1.6.0/js/MicrosoftTeams.min.js'></script>

</head>

<body>

    <script>
    microsoftTeams.initialize();
    </script>

</body>

If you can load that page to a tab in Teams and have it active without the user having to "download,"  please tell me how you did it.
There is one other piece that is beyond my ability:
Ensure that the all URL domains used in your tabs are included in the validDomains array in your manifest. For more information, see validDomains in the manifest schema reference. However, be mindful that the core functionality of your tab exists within Teams and not outside of Teams.

Has anyone done this? and can you tell me how to do it?
Of course if the idea is going in the wrong direction and there is a better way, please let me know that as well.
Thanks.

A: You can create a config tab and deep link concept will help you to render html pages in tab
Teams does not allow other tenant domains. To allow, you need to add those domains in Manifest Valid Domains array.
 "validDomains": [ "contoso.com", "mysite.someplace.com", "othersite.someplace.com" ].


text:
Q: Generalized Conditional Probability proof. Suppose that $P(\bigcap_{i=1}^{n-1}A_i) > 0$ for any $n>1$. Prove that
$$P(\bigcap_{i=1}^{n}A_i)=P(A_1)\prod_{i=1}^{n-1} P(A_{i+1} |\bigcap_{k=1}^{i}A_k)$$
My attempt:
I tried to prove this by induction. So I first showed that it is true for $n=2$.
$$P(\bigcap_{i=1}^{2}A_i)=P(A_1)\prod_{i=1}^{1} P(A_{i+1} |\bigcap_{k=1}^{i}A_k)$$
$$P(A_1\cap A_2)=P(A_1)P(A_{2} |A_1)$$
By definition of conditional probability, this is true. I will now assume this is true for all $n = j$. Now I wish to solve this for $n = j + 1$
$$P(\bigcap_{i=1}^{j+1}A_i)=P(A_1)\prod_{i=1}^{j} P(A_{i+1} |\bigcap_{k=1}^{i}A_k)$$
I am unsure on how to proceed for here. My uncertainty lies in what end goal I can reach to prove it is true for all $n$. This notation is also intimidating and I do not know what sort of manipulation I can do, considering most if it is intersections and not unions. Any help would be appreciated.

A: You are close with your induction. Let $B := \bigcap_{i=1}^j A_i$ so that $\bigcap_{i=1}^{j+1} A_i = B \cap A_{j+1}$.
Then note $P(B \cap A_{j+1}) = P(A_{j+1} \mid B) P(B)$ and use the induction hypothesis to handle $P(B)$.


text:
Q: jQuery - Alter URL on Click I've grabbing the URL of a thumbnail when clicking on it and adding it to another image in the HTML:
$('#result .thumb').live('click', function() {
    var newImgSrc = this.src;
    $("#thumbnail").attr("src", newImgSrc);
});

However I want to alter the URL that gets sent, it currently looks something like:
...com/4100/5412955054_45ce3a897e_s.jpg

I want to remove _s from the very end of the URL. Can I do this in jQuery or Javascript?

A: Yes, use replace() function.
newImgSrc = newImgSrc.replace(/_s\.jpg/,'.jpg');

A: JavaScript's replace method + regex. Or slicing two last chars before dot and extension.


text:
Q: How do you connect to an EPP server (domain registry) in Node JS? I'm building a project to manage my own domain names (just for learning purposes). The standard for interfacing with the registry API is to use their EPP server on port 700 with your username, password, and an SSL cert on the client side.
How do I connect to this in node js? Should I open a TLS connection? Their documentation is vague, at best, so if anyone has had any experience doing this, that would help out.
It's also hard testing because I'm not sure if my ip was properly whitelisted. Would like to see a sample code snippet connecting to an EPP server with username, password, and SSL cert, or perhaps just point me in the right direction as I'm most likely overthinking it :p.
Here's where I've started found from the only example online I can find in node.
var fs = require('fs')
var tls = require('tls')

var options = {
  cert: fs.readFileSync('cert.pem'),
  passphrase: 'passphrase',
  username: 'username', // ?
}

var stream = tls.connect(700, 'example.com', options);
  stream.setEncoding('utf8')
  stream.on('secureConnect', function() {
  console.log('client connected')
})
stream.on('data', function(data) {
  console.log(data)
})

But that doesn't do anything and won't make the connection.

A: If I understand it right RFC EPP can be connected by TCP.
I would use Node.JS API net to create client.
And by EPP documentation after connect you need send command in this format for example login.
var host = 'example.com';
var port = 700;
var command = '{{xml_command}}';

var client = new net.Socket();
client.connect(port, host, function() {
    console.log('Connected');
    client.write(command);
});

client.on('data', function(data) {
    console.log('Received: ' + data);
    client.destroy();
});

client.on('close', function() {
    console.log('Connection closed');
});

As an alternative I'd try node-epp and epp-reg.
Maybe I helped where to go next.


text:
Q: Branch removal from history I have this situation:

*

*The main branch is Develop

*I created a new branch from Develop called Task1

*I made changes in Task1 and made a commit

*I made further changes in Task1 and made another commit

*It turned out that the task should not be called Task1 (for some reasons). A subtask called Task2 had to be created

*Task2 was created from Task1 branch (in Task2 needed changes were made in Task1)

*In Task2, I made further code changes

Now I would like to delete Task1 branch from the history
Changes made in Task1 must remain in Task2
Now is:
Develop - Task1 : (commit1, commit2) - Task2 : (commit1, commit2 etc.)
It should look like this:
Develop - Task2 : (commit1, commit2, commit3 etc.)
EDIT:
Task1 with commits must be removed but changes made remain in Task2

A: A branch is just a pointer to a commit, so if Task2 is ahead or at the same level of Task1, you can just delete Task1:
# delete the branch locally
git branch -d Task1
# delete the branch remotely (if you remote is not called origin, change that with your remote name)
git push origin :Task1

The commits accessible from Task1 will still be in Task2.


text:
Q: Bivariate normal MLE confidence interval question Consider a random sample $(L_1, R_1), . . . ,(L_n, R_n)$ of eye pressure measurements in the left and
right eyes of n patients.
a) Suppose that $L_j$ and $R_j$ are independent and normally distributed with unknown mean µ
and known variance $\sigma^2$, for j = 1, . . . , n. Obtain the likelihood function of the sample and derive the maximum likelihood estimator of µ. Construct a 100(1 − α)% confidence
interval for µ.
b) Suppose now that for each j, we do not assume that Lj and Rj are independent. Instead
we assume that
Lj = Mj + Dj and Rj = Mj − Dj
for independent Mj and Dj , where Mj ∼ N(µ, $\sigma_1^2$) and Dj ∼ N(0, $\sigma_1^2$), with $\sigma_1^2$ $\geq$ $\sigma_2^2$ and $\sigma_1^2 + \sigma_2^2 = \sigma^2$. Here µ is unknown but $\sigma_1^2$
and $\sigma_2^2$
are known.
Find the distribution of $L_j$ and the distribution of $R_j$ , and find the maximum likelihood
estimator for µ in terms of $L_j$ and $R_j$.
c) Assuming that $\sigma_1^2 = \sigma_2^2 = \sigma^2/2$, find a 100(1 − α)% confidence interval for µ.
d) Assuming now that $\sigma_1^2 > \sigma_2^2$, state qualitatively, without calculations, how this change
will affect (i) the maximum likelihood estimator and (ii) the confidence interval.
So far I have attempted part (a) and obtained the maximum likelihood estimator $\hat{\mu}=\sum (L_j + R_j)/2n$ but I'm stuck on the later parts. Any help would be greatly appreciated!

A: Here's what I would do. To find your confidence interval in (a), first set $$\bar{X}:=\frac{1}{2n}\sum_{j=1}^{n}(L_j+R_j)$$ and observe how $\bar{X} \sim N(\mu,\frac{\sigma^2}{2n})$. This implies $\frac{\bar{X}-\,u}{\sigma/\sqrt{2n}} \sim N(0,1)$ and so $$-z_{\alpha/2}<\frac{\bar{X}-\,u}{\sigma/\sqrt{2n}}<z_{\alpha/2} \iff \mu\in\Big(\bar{X}-z_{\alpha/2}\frac{\sigma}{\sqrt{2n}},\bar{X}+z_{\alpha/2}\frac{\sigma}{\sqrt{2n}}\Big)$$ Replacing $\bar{X}$ with your MLE for $\mu$ should provide you with your desired confidence interval. For (b) its relatively easy to see how $L,R \sim N(\mu,\sigma^2)$. You can get the joint density for $(L,R)$, namely $f_{LR}$, by using the fact that $$f_{LR}(l,r)=f_{MD}\Bigg(\frac{l+r}{2},\frac{l-r}{2}\Bigg)\left|\frac{\partial(m,d)}{\partial(l,r)} \right|=\frac{1}{2}f_{M}\Bigg(\frac{l+r}{2}\Bigg)f_{D}\Bigg(\frac{l-r}{2}\Bigg)$$ Now that we have the joint density for $(L,R)$ we can compute the likelihood function and get the MLE for $\mu$. Let me know how these suggestions serve you.


text:
Q: Return value from javascript object literel I have two file a.js and b.js, I need to return value from a.js. This is the program which I wrote, please correct it thanks!
a.js
var a = (function(){
   var some = function(aa) {
        aa + 10;
   }
   var init = function(aa) {
      some(aa);
   }
   return {
       init : init
   }
})();

b.js
console.log(a.init(5));

A: It's a chain. three functions are calling here:

*

*call init from b.js: a.init( 5 )

*call init from a.js: init = function( aa ) { ... }

*call some from a.js: some = function( aa ) { ... }
every function return undefined by default, so if u want to pass your calculated value through all of this, you need to return it in every function.
new a.js
var a = (function(){

    var some = function(aa) {
        return aa + 10;
    }

    var init = function(aa) {
       return some(aa);
    }

    return {
        init : init
    }

})();

now call your b.js file, and it will work as expected.
Update:
if you would like to get rid of those return values, you can use arrow-functions like this:
var a = (function(){

    var some = aa => aa + 10;

    var init = aa => some(aa);

    return {
        init : init
    }

})();

they will return calculated value by default ( instead of undefined ).


text:
Q: Finding the different elements between two ArrayLists in Java How can I know the different element between 2 array list in java? I need the exact element not a Boolean value which can be retrieved using removeAll().

A: It depends on what do you want to check.

*

*If you want to get all the unique elements for both lists (i.e. sum of all elements that are unique for the first list and all elements that unique for the second list) also known as symmetric difference you can use as mentioned above disjunction method from Apache Commons Collections 4.0:
CollectionUtils.disjunction(a, b);

*If you want to get all unique elements only from one list (i.e. elements that exist only in one list, but don't exist in the other) also known as relative complement you can subtract from this list the other one using subtract method from Apache Commons Collections 4.0:
CollectionUtils.subtract(a, b); //gives all unique elements of a that don't exist in b

A: import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CompareTwoList {
    public CompareTwoList() {
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) {
        List<String> ls1 = new ArrayList<String>();
        ls1.add("a");
        ls1.add("b");
        ls1.add("c");
        ls1.add("d");

        List<String> ls2 = new ArrayList<String>();
        ls2.add("a");
        ls2.add("b");
        ls2.add("c");
        ls2.add("d");
        ls2.add("e");

        Set<String> set1 = new HashSet<String>();
        set1.addAll(ls1);

        Set<String> set2 = new HashSet<String>();
        set2.addAll(ls2);
        set2.removeAll(set1);

        //set.addAll(ls1);
        //set.addAll(ls1);

        for (String diffElement : set2) {
            System.out.println(diffElement.toString());
        }
    }
}

A: If I understood your question correctly then following method nonOverLap in the code below should get you that:
<T> Collection<T> union(Collection<T> coll1, Collection<T> coll2) {
    Set<T> union = new HashSet<>(coll1);
    union.addAll(new HashSet<>(coll2));
    return union;
}

<T> Collection<T> intersect(Collection<T> coll1, Collection<T> coll2) {
    Set<T> intersection = new HashSet<>(coll1);
    intersection.retainAll(new HashSet<>(coll2));
    return intersection;
}

<T> Collection<T> nonOverLap(Collection<T> coll1, Collection<T> coll2) {
    Collection<T> result = union(coll1, coll2);
    result.removeAll(intersect(coll1, coll2));
    return result;
}

A: Use Apache Commons Collections (javadoc):
CollectionUtils.disjunction(a, b);

See also: Effective Java, 2nd edition, Item 47: Know and use the libraries (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)

A: LinkedHashMap table;
for each element e of array A
    if table.get(e) != null
        table.put( e, table.get(e) + 1 )
    else
       table.put( e, 0 )

//Do the same for array B
for each element e of array B
    if table.get(e) != null
        table.put( e, table.get(e) + 1 )
    else
       table.put( e, 0 )

At the end of the for loops elements in table with value=0 are the different ones.

A: Call the method ReturnArrayListDiffElements passing two array lists. An array list which is the difference between two passed array lists will be returned
public ArrayList ReturnArrayListDiffElements(ArrayList arrList1, ArrayList arrList2){
    ArrayList<String> List1 = new ArrayList<String>();
    ArrayList<String> List2 = new ArrayList<String>();
    ArrayList<String> List3 = new ArrayList<String>();
    ArrayList<String> List4 = new ArrayList<String>();

    List1.addAll(arrList1);
    List2.addAll(arrList2);

    List3 = ReturnArrayListCommonElements(List1,List2);

    List1.removeAll(List3);
    List2.removeAll(List3);
    if(List1.size() > 0){
        List4.add("Distinct elements in Array List 1");
        List4.addAll(List1);
    }
    if(List2.size() > 0){
        List4.add("Distinct elements in Array List 2");
        List4.addAll(List2);
    }

    return List4;
}

public ArrayList ReturnArrayListCommonElements(ArrayList arrList1, ArrayList arrList2){
    ArrayList<String> List1 = new ArrayList<String>();
    ArrayList<String> List2 = new ArrayList<String>();
    ArrayList<String> List1A = new ArrayList<String>();
    ArrayList<String> List2A = new ArrayList<String>();
    ArrayList<String> List1B = new ArrayList<String>();
    ArrayList<String> List3 = new ArrayList<String>();

    List1.addAll(arrList1);
    List2.addAll(arrList2);
    List1A.addAll(arrList1);
    List2A.addAll(arrList2);
    List1B.addAll(arrList1);

    int intList1Size, intList2Size;
    List1.removeAll(List2);
    intList1Size = List1.size();

    List2.removeAll(List1A);
    intList2Size = List2.size();

    if (intList1Size == 0 && intList2Size ==0) {
        List3.addAll(List1B);
        return List3;
    } else {
        List3.addAll(List1B);
        List1B.removeAll(List2A);
        List3.removeAll(List1B);
        return List3;
    }
}


text:
Q: Transpose multiple rows to single column Can't figure out how to transpose multiple rows into a single column.
Current layout:
| a | b | c | d |
| e | f | g | h |
| i | j | k | l |

Desired layout:
| a |
| b |
| c |
| d |
| e |
| f |
| g |
| h |
| i |
| j |
| k |
| l |

There are 214 rows, all with 4 columns, that I want to transpose into a single column. Starts from A2 and ends at D215.

A: Use FLATTEN() function like-
=FLATTEN(A2:D)


text:
Q: Reading from UART port I'm writing a simple UART driver in linux for ARM926EJ-S. Inside the read function of the driver. If enter key (carriage return) was pressed, I want it to return the no. of bytes read till that point.
uart_data = (unsigned char)ioread8((void*)UART_DR(uart0_addr));
printk(KERN_ERR " %d ",(unsigned int)uart_data ); //prints 13 when pressing enter key
if ((unsigned char)13 == uart_data) //if carriage return
{
    printk(KERN_ERR "Carriage Return\n");
    goto out;
}

When I press enter key on the UART terminal, it receives it as a carriage return, but the control flow never gets inside the if block. Please help.


text:
Q: android: volley keeps retrying when receiving 403 code I also modified the Retry policy but it isn't working. here's the code:
JsonObjectRequest getReq = new JsonObjectRequest(Request.Method.GET, GET_URL, null,

              new Response.Listener<JSONObject>() {
                  @Override
                  public void onResponse(JSONObject response) {
                     //bluh..

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Authorization", token);
                return headers;
            }
        };getReq.setRetryPolicy(new DefaultRetryPolicy(
                    0,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        AppController.getInstance().addToRequestQueue(getReq);

sometimes it retrys up to 6 times. how can I prevent that?

A: Problem is in "BasicNetwork" class (see commented out block)
  if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents,
                        responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
//                    if (statusCode == HttpStatus.SC_UNAUTHORIZED ||
//                            statusCode == HttpStatus.SC_FORBIDDEN) {
//                        attemptRetryOnException("auth",
//                                request, new AuthFailureError(networkResponse));
//                    } else
                        {
                        // TODO: Only throw ServerError for 5xx status codes.
                        throw new ServerError(networkResponse);
                    }
                } else {
                    throw new NetworkError(networkResponse);
                }

This implementation violates RFC and caused huge server traffic in my case!


text:
Q: bash: read a file content into a variable, the content contains special characters: `*` I have a file named content.txt:
$ cat content.txt

output:
*
1
2

In the same directory, I have a bash file: read.sh to read the content of content.txt
$ cat read.sh

output:
content=`cat content.txt`
echo $content

As we can see there is a * in the content.txt. So, when I run reah.sh:
$ sh read.sh

output:
content.txt read.sh 1 2

It seems that, * has been parsed.
How can a get the content of content.txt? Any help would be great.

A: The * character is a wildcard character for globbing that expands to file names in the current directory and must be quoted or escaped if you wish to echo only the character.
You can read from a file using the read builtin command.
while read content; do
    echo "$content"
done < content.txt

A: It seems that the variable expands when echo. So just changed read.sh to:
content=`cat content.txt`
echo "$content"

Then I got what I want. Thanks, everyone.
update
http://www.shellcheck.net/ this, can check the shell script and give some suggestion.


text:
Q: meta field for numerous links I'm currently trying to store something which looks like this.
[links] => array
    (
        [0] => examplelink.com/RANDOM-MD5
        [1] => examplelink1.com/RANDOM-MD5
        [2] => examplelink2.com/RANDOM-MD5
        [3] => examplelink3.com/RANDOM-MD5
        [4] => examplelink4.com/RANDOM-MD5
        [5] => examplelink5.com/RANDOM-MD5
    )

However the tracks field will display a different link in every single post on the website.
Currently, I'm storing every link in a database table and returning it via the_content portion and it's extremely messy and in some cases doesn't even actually work properly.
How would I create a meta table for this? And how would I return each result on my automation process page? Cause currently its just storing the array results into a database, and processes the actual post page with something that looks like this.
$content = $row['links'];
// Create post object
$my_post = array(
      'post_title'    => wp_strip_all_tags( trim( $row['title'] ) ),
      'post_content'  => $content,
      'post_status'   => 'publish',
      'post_author'   => 1,
      'post_category' => array(5),
      'post_date' => date('Y-m-d H:i:s')
);

here's an HTML demo of how I would like the links to display on the front end of my website.

Link 1

Link 2

Link 3

A: I an not entirely sure that I understood the question but I am guessing you need to publish an array of specific links on each post page.
The best option will be to save the links in a meta field for that post. Note that you can store the links separated by a comma. Something like this:
examplelink.com/RANDOM-MD5,examplelink1.com/RANDOM-MD5,examplelink2.com/RANDOM-MD5

You can then call this meta field in the single post page using the get_post_meta function. Then you can use the explode function where you can create an array of that comma separated links.
Suppose the custom field you create in your post is "random_links", your code will look something like this:
$post_links = get_post_meta(<your_post_id>,'random_links',TRUE);
$link_array = explode(" ", $post_links);

$link_array will have your array of the links you added. To display it in required format use the following code.

<?php foreach($link_array as $single_link) {?>
<a href="<?php echo $single_link; ?>">
Link 1

<?php } ?>

This will print the list in an unordered list.
Hope this helps. Thanks


text:
Q: Which sentence is the "main clause"? There is a long conditional sentence:

If he would just say he spoke too hastily, that of course he loves her
  and wants to make it work, that they've had things stacked against
  them, he knows that, it's been hard for both of them, and they have to
  somehow help each other, try harder to be content together—then she's
  sure they could love each other again.  (An Unwanted Guest by Shari Lapena)

So I lost the main clause.
Could you tell me please which one is the main clause? Is the phrase "he knows that...[up to the end]" the main clause?

A: In an "If..., (then)...." the main clause follows the conjuction "then". A shorter example would be:

If he apologises, then she will forgive him.

The main clause is "she will forgive him".  So in you longer example, the main clause is

she's sure [...]

The conditional clause (from if... to ... then) is actually a  complex list with lots of parallel structures:

If he would just say:

*

*he spoke too hastily

*that of course he
  ....a) loves her and
  ....b) wants to make it work,

*that they've had things stacked against them,

*he knows that,
  ... a) it's been hard for both of them, and
  ....b) they have to somehow help each other, try harder to be content together

A: Let's reverse the order of the clauses, and punctuate a little differently, and show where there's been a reduction or an ellipsis:

She's sure they could love each other again if he would just say
  (that) he spoke too hastily, that of course he loves her and wants to
  make it work, that they've had things stacked against them—he knows
  that—(that) it's been hard for both of them, and (that) they have to
  somehow help each other, (have to) try harder to be content together.

There's no need for then when the main clause begins such a sentence, and it isn't really required in the original either:

If he would just say (that) he spoke too hastily, that of course he
  loves her and wants to make it work, that they've had things stacked
  against them—he knows that—(that) it's been hard for both of them, and
  (that) they have to somehow help each other, (have to) try harder to be
  content together, she's sure they could love each other again.

Of course, putting those that's back in to show the parallelism of the clauses ends up making the passage seem more "measured" or slow-paced, when it is actually a little erratic and emotional.


text:
Q: Ionic2 Signature Pad resize image Am capturing an image through camera and saving it to signature pad. The image is occupying certain portion on signature pad. How to resize image to that of the size of signature pad.
Here is the screen shot of image after saving it to signature pad. Grey part is signature pad. Image is to the top left corner.
Can some body please tell how can I resize image or at least tell how to get height and width of image? Signature pad dimensions are statically given

A: people who want to edit the sign back again its not the good solution. I fixed by redrawing image into signPad.
    this.signaturePad.clear();
    //If it is already signed load sign into signPad.
    if(this.signatureData) {
        let canvas = document.getElementsByTagName('canvas')[0];
        let img = document.createElement("img");
        img.src = this.signatureData;
        canvas.getContext("2d").drawImage(img, 0, 0);
    }

A: I've got it resolved by doing some workaround. We need to change the device pixel ratio and not the canvas size. Something like the following.
var canvas = document.getElementsByTagName('canvas')[0];
this.resizeCanvas(canvas);

public resizeCanvas(canvas) {
 var ratio =  window.devicePixelRatio || 1;
 //canvas.width = canvas.offsetWidth * ratio;
 //canvas.height = canvas.offsetHeight * ratio;
 canvas.getContext("2d").scale(ratio, ratio);
}


text:
Q: Opening a batch file using SQL Server procedure Opening a batch file using SQL Server procedure....
For this, I took the example of opening a notepad. And able to open it with the following code :
start "c:\windows\system32" notepad.exe
--- saved as : note.bat

I tried to open it with following procedure :
ALTER procedure [dbo].[executebat]
as
begin
   EXEC master.dbo.xp_CMDShell 'D:\ducont\note.bat'
end

also I enabled the xp_cmdshell option with following code ::
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO

But when I try to execute the procedure, it showing continuously
" Query Executing..."

and no output !!
Guide me if I went wrong anywhere .

A: Simple answer.  When you run xp_cmdshell it is creating a shell to do any work you ask it to.  Your bat file is running inside that shell, and will open notepad, again inside the shell.  You just won't be able to see it.  Since it's expecting input (and can't get any) you are stuck with the " Query Executing..."
There really isn't a good way to do what you are asking for other than possibly using CLR.  Unfortunately I don't know enough about it to say for certain one way or another.  There may be an easier way in SQL 2012 or 2014 but I haven't seen it yet.


text:
Q: Designated initializers Apparently, designated initializers is not "correct" C++.
Are there any alternatives for this?
I like the use of this for structs because:

*

*Variables can be set optionally when creating the struct object.

*The order of initializing doesn't matter.

*Variables can be const.

*This can be used in c++17 in combination with base classes.

Thanks
Jelle

A: Given
struct S {
    int x, y, z;
}:

S s {
    .y = 1; // not standard until C++20
};

Are there any alternatives for this?

You can use positional list initialisation:
S s{0, 1};

It has the drawback (arguably a benefit, depending on situation) that the member names are not explicit, meaning depends on order of members and all members preceding the last explicitly initialised must also be there.
Another alternative: Assign the member later.
S s{};
s.y = 1;

This has the drawback that it cannot be used to initialize const members. Another drawback is that this is not a single initialisation-expression. That can be worked around by using a function:
S init(int y) {
    S s{};
    s.y = y;
    return s;
}
S s = init(1);

Yet another alternative: Use a constructor.
struct S {
    int x = 0, y = 0, z = 0;
    S(int y): y(y) {}
};

This can be much simpler in some cases, but not at all clear in others (such as this vector-like case). Another drawback is the lack of trivial constructor.


text:
Q: Existence of set Problem: Show that the following limit always exists:
Let $f:\mathbb{R}^+ \rightarrow \mathbb{R}$
$$\lim_{r \to 0}\inf \{ f(x): 0<x<r\}$$
This doesn't seem right to me, consider
$f(x)= \log x$, then $\inf \{f(x): 0<x<r\}=-\infty$ and so the limit does not exist. Am I missing something?


text:
Q: Disabling and enabling Textbox based on selection of RadioButton But It's working Once,again i click for enable it's not working,please help me this is my View Page

        @Html.RadioButtonFor(model => model.B_StopTube, false) No

        @Html.RadioButtonFor(model => model.B_StopTube, false) Yes

        @Html.TextBoxFor(model => model.Dub_StopTubeLength)

and this my model:
    public bool B_StopTube { get; set; }
    public double Dub_StopTubeLength { get; set; }

it's working at first time if i change the selection of radiobutton it's not enabling textbox.i am not getting idea how to solve this problem please help me...i am a new MVC programmer...

A: There is a typo use removeProp() instead of removeprop()
Use
$("#Dub_StopTubeLength").removeProp("disabled");

Your code can be improved as
$('#B_StopTube').change(function () {
    $("#Dub_StopTubeLength").prop("disabled", $(this).is(':checked'))
})

A: try this
$(function () {
    $('#B_StopTube').change(function () {
     if ($(this).is(':checked'))
     {
       $("#Dub_StopTubeLength").attr('disabled','disabled');
     }
     else
     {
       $("#Dub_StopTubeLength").removeAttr('disabled');
     }
    })
    });


text:
Q: How to get the size and duration of an mp3 file? I need to calculate the total length of an mp3 file.
Currently I am using a PHP class which I found @ http://www.zedwood.com/article/php-calculate-duration-of-mp3.
This is working perfectly if the mp3 file in same server.
but if I have a URL from other site it throwing error. Please help me.
Is there any JavaScript J-Query function to get the length of the mp3 file
<?php include("mp3.class.php");
$f = 'http://cdn.enjoypur.vc/upload_file/5570/5738/5739/7924/Blue%20Eyes%20-%20Yo%20Yo%20Honey%20Singh%20(PagalWorld.com)%20-192Kbps%20.mp3';
$m = new mp3file($f);
$a = $m->get_metadata();

if ($a['Encoding']=='Unknown')
    echo "?";
else if ($a['Encoding']=='VBR')
    print_r($a);
else if ($a['Encoding']=='CBR')
    print_r($a);
unset($a);
?>

A: Here's how you can get mp3 duration using Web Audio API:

const mp3file = 'https://raw.githubusercontent.com/prof3ssorSt3v3/media-sample-files/master/doorbell.mp3'
const audioContext = new (window.AudioContext || window.webkitAudioContext)()
const request = new XMLHttpRequest()
request.open('GET', mp3file, true)
request.responseType = 'arraybuffer'
request.onload = function() {
    audioContext.decodeAudioData(request.response,
        function(buffer) {
            let duration = buffer.duration
            console.log(duration)
            document.write(duration)
        }
    )
}
request.send()

A: There is actually a library that can run at client-side, attempting to fetch just enough of the MP3 to read the ID3 tags:
http://github.com/aadsm/JavaScript-ID3-Reader
or
Try
HTML File API.
http://lostechies.com/derickbailey/2013/09/23/getting-audio-file-information-with-htmls-file-api-and-audio-element/

A: Perhaps the simplest solution is to use the audio html element to get the time duration and to obtain the size directly from the file returned by the FileReader object. A code example of this approach is shown below.
One down side of this and all the other solutions presented so far is the 10-20 second delay it takes for the audio tag's durationchanged event to fire when loading large, eg > 200MB files. Clearly there is a faster way to get this info because the duration is shown immediately when the file is entered into the browser as a file:///.... URL.
function checkMp3SizeAndDuration()
{
    var files = document.getElementById('upload-file').files;
    var file = files[0];
    if (file.size > MAX_FILE_SIZE) {
        return;
    }

    var reader = new FileReader();
    var audio = document.createElement('audio');
    reader.onload = function (e) {
        audio.src = e.target.result
        audio.addEventListener('durationchange', function() {
            console.log("durationchange: " + audio.duration);
        },false);

        audio.addEventListener('onerror', function() {
            alert("Cannot get duration of this file.");
        }, false);
    };
    reader.readAsDataURL(file);
});

A: Having not been able to find something that was fast and didn't require a bunch of extra boilerplate code, I tweaked an existing server side javascript utility to run directly in the browser. Demo code is available at: https://github.com/eric-gilbertson/fast-mp3-duration

A: Use getID3() PHP library that works for VBR files as well.
This link help you sourceforge.net.
It's very much active in development.

A: A Famous and Very SPI that you can use MP3 SPI
and the code is also very simple
File file = new File("filename.mp3");
AudioFileFormat baseFileFormat = AudioSystem.getAudioFileFormat(file);
Map properties = baseFileFormat.properties();
Long duration = (Long) properties.get("duration");


text:
Q: Trendline not showing on Google graph I am trying to get an exponential trendline on the graph below.  From searching on here I understand that the issue may well be that the first column type is a string, but when I try changing it to 'date' or 'number', I get an error on the page.  What else do I need to change to get this working?
$rows = array();
$table = array();
$table['cols'] = array(
    array('label' => 'Date', 'type' => 'string'),
    array('label' => 'Amount', 'type' => 'number')
);

$sessions = $wpdb->get_results($wpdb->prepare("SELECT Due,Date from patient_sessions WHERE Type='Session' AND Date >= '2014-01-01'"));
$work_times = $wpdb->get_results($wpdb->prepare("SELECT Amount,Date from work_times AND Date >= '2014-01-01'"));
$expenses = $wpdb->get_results($wpdb->prepare("SELECT Amount,Date from expenses WHERE Client='Psychotherapy' AND Date >= '2014-01-01'"));
$i=1;
while($i<=53) {
    $week_start = new DateTime();
    $week_start->setISODate(2014,$i);
    $date_display = $week_start->format('j M Y');

    $session_total = 0;
    $work_time_total = 0;
    $expense_total = 0;

      foreach ($sessions as $session) {
    if (date("W", strtotime($session->Date)) == $i) {
    $session_total = ($session_total+$session->Due);
    }
    }

         foreach ($work_times as $work_time) {
    if (date("W", strtotime($work_time->Date)) == $i) {
    $work_time_total = ($work_time_total+$work_time->Amount);
    }
    }

          foreach ($expenses as $expense) {
    if (date("W", strtotime($expense->Date)) == $i) {
    $expense_total = ($expense_total+$expense->Amount);
    }
          }

    $balance = ($session_total + $work_time_total - $expense_total);

    $temp = array();

    $temp[] = array('v' => (string) $date_display);
    $temp[] = array('v' => (string) $balance);
    $rows[] = array('c' => $temp);
    $i++;
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;
?>

    <script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(<?=$jsonTable?>);
                                                    var formatter = new google.visualization.NumberFormat({fractionDigits:2,prefix:'\u00A3'});
      formatter.format(data, 1);
      var options = {
          pointSize: 5,
          legend: 'none',
          series: {0:{color:'2E838F',lineWidth:2}},
          chartArea: {left:50,width:"95%",height:"80%"},
          backgroundColor: '#F7FBFC',
          hAxis: {textStyle: {paddingTop: '50'},showTextEvery:4},
          height: 400,
          trendlines: {
              0: {
                type: 'exponential',
                color: 'green',
              }
            }
        };
      // Instantiate and draw our chart, passing in some options.
      //do not forget to check ur div ID
      var chart = new google.visualization.LineChart(document.getElementById('chart_div2'));
      chart.draw(data, options);
    }
    </script>

A: You can convert your string dates to Date objects like this:
$table['cols'] = array(
    array('label' => 'Date', 'type' => 'date'),
    array('label' => 'Amount', 'type' => 'number')
);

then in your while loop:
$week_start = new DateTime();
$week_start->setISODate(2014,$i);
$date_display = $week_start->format('j M Y');
$year = (int) $week_start->format('Y');
$month = ((int) $week_start->format('m')) - 1; // adjust for javascript's 0-indexed months
$day = (int) $week_start->format('d');

//...

$temp = array();

$temp[] = array('v' => "Date($year, $month, $day)", 'f' => $date_display);
$temp[] = array('v' => (string) $balance); // you should use (float) or (int) here, not (string)
$rows[] = array('c' => $temp);


text:
Q: Django Rest Framework: The 'image' attribute has no file associated with it I'm using Django Rest Framework to create REST endpoints for a frontend.
I have a model where there is the possibility of uploading 3 images (foto_1, foto_2, foto_3).
class Ocorrencia(TimeStampedModel):

(...)

foto_1 = models.ImageField("Foto 1", upload_to="ocorrencias/", blank=True)
foto_2 = models.ImageField("Foto 2", upload_to="ocorrencias/", blank=True)
foto_3 = models.ImageField("Foto 3", upload_to="ocorrencias/", blank=True)

My serializer is the following:
class OcorrenciaSerializer(GeoFeatureModelSerializer):

(...)

foto_1 = serializers.ImageField(allow_empty_file=True, allow_null=True, required=False, use_url=True)
foto_2 = serializers.ImageField(allow_empty_file=True, allow_null=True, required=False, use_url=True)
foto_3 = serializers.ImageField(allow_empty_file=True, allow_null=True, required=False, use_url=True)

class Meta:
    model = models.Ocorrencia
    geo_field = 'geometria'
    fields = ('foto_1', 'foto_2', 'foto_3')

If for example foto_3 has no file url associated in the database (it's saved as empty string when it's empty) then I get the following error when retrieving the associated endpoint:
Exception Value: The 'foto_3' attribute has no file associated with it.
Using allow_empty_file=True, allow_null=True, required=False when defining the serializer for the image fields seems to not do anything.
UPDATE 1
I found that this is related to using GeoFeatureModelSerializer, this is part of Django Rest Framework GIS. I'll have to seek a solution on that route. If I happen to use the default serializer class of DRF I have no issues. I was almost going insane with this issue. If I find a solution using GeoFeatureModelSerializer I'll post it here.
UPDATE 2
Updated Django-Rest-Framework-Gis to latest version and fixed it. Thank you all for your comments and suggestions.


text:
Q: skip line if output already exists I have a script running on a CentOS machine that for each line of a txt file does certain operations and at the end generates an output file for each line. The script has stopped and I should run it again but add an option not to repeat the operations for the lines of the file for which the output file has already been created. How can I do this?
This is the script:
while IFS=READ -r file; do
    dir1=${file: -5:1}
    dir2=${file#*_*_}
    protein=$dir2.pdb
    pock=$file.pdb
    output=$file.txt
    cd $dir1
    cd $dir2
    /path/to/executable -ps -i $protein -gl $pock -o /path/to/$output
    cd ..
    cd ..
done < /path/to/input.txt

A: First, as terdon pointed out in a comment, you need a space between IFS= and read (and the read command should be lowercase):
while IFS= read -r file; do

Now, as for your actual question: if the goal is to skip if the output file already exists, you can just add this in the loop after you set output but before the cd commands:
if [ -e "/path/to/$output" ]; then
    continue    # the output file already exists, so skip re-creating it
fi

The continue command will skip the rest of this iteration of the loop, going straight on to the next line/file in the list. BTW, note that I put double-quotes around the path, because it contains a variable reference. Double-quoting your variable references is almost always a good idea.
I'd also recommend avoiding cd in scripts if possible; if it fails for any reason, the rest of the script will get confused and run in the wrong directories. If you can, just use explicit paths:
/path/to/executable -ps -i "$dir1/$dir2/$protein" -gl "$dir1/$dir2/$pock" -o "/path/to/$output"

If that won't work for some reason (e.g. the executable's working directory actually has to be the directory the files are in), at least just do a single cd command and if it fails, don't try to execute or cd back, because it's not going to work:
if ! cd "$dir1/$dir2"; then
    echo "Error changing into $dir1/$dir2; we're going to have to skip this one." >&2
    continue    # skip ahead to the next line/file
fi

/path/to/executable -ps -i "$protein" -gl "$pock" -o "/path/to/$output"

if ! cd ../..; then
    echo "Error getting back to main directory. Unable to continue" >&2
    exit 1
fi

BTW, shellcheck.net is a good tool for sanity-checking scripts, and will point out common mistakes like not double-quoting variable references and not checking for errors on cd commands.


text:
Q: How to get predict label from a CNN text classification? I am new to CNN text classification. I want to classify text into one of two labels.
0 = tidak mengidap
1 = mengidap
My model only returns 0, no matter what sequence.
lstm_out = 150

model = Sequential()
model.add(embedding_layer)
model.add(Conv1D(filters=64, kernel_size=5, activation='relu', padding='causal'))
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.7))
model.add(LSTM(units=lstm_out))
model.add(Dropout(0.7))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

X_sample = tokenizer.texts_to_sequences(df['stemmed'])
X_sample = pad_sequences(X_sample, maxlen=maxlentweet)
y_sample = model.predict(X_sample).flatten().tolist()
result = np.argmax(y_sample)

print(result)


text:
Q: Bind datas from several tables to DataGridTextColumn by Entity Framework After having created my DataBase with Entity Framework, I have created 4 observable Collections containing the 4 tables I have, and a CompositeCollection to regroup'em, like this:
class ViewModel:INotifyPropertyChanged
{
private BDDInterneEntities _BDDInterneEntities;

public ViewModel()
{
    _BDDInterneEntities = new BDDInterneEntities();
    ResultatCollection = new ObservableCollection<Resultat>(_BDDInterneEntities.Resultat);
    D98EquipementsCollection = new ObservableCollection<D98Equipements>(_BDDInterneEntities.D98Equipements);
    D98DetailsCollection = new ObservableCollection<D98Details>(_BDDInterneEntities.D98Details);
    D675Collection = new ObservableCollection<D675>(_BDDInterneEntities.D675);
    cmpc = new CompositeCollection();

    CollectionContainer cc1 = new CollectionContainer();
    CollectionContainer cc2 = new CollectionContainer();
    CollectionContainer cc3 = new CollectionContainer();
    CollectionContainer cc4 = new CollectionContainer();
    cc1.Collection = ResultatCollection;
    cc2.Collection = D98EquipementsCollection;
    cc3.Collection = D98DetailsCollection;
    cc4.Collection = D675Collection;
    cmpc.Add(cc1);
    cmpc.Add(cc2);
    cmpc.Add(cc3);
    cmpc.Add(cc4);

}
public ObservableCollection<Resultat> ResultatCollection { get; set; }
public ObservableCollection<D98Equipements> D98EquipementsCollection { get; set; }
public ObservableCollection<D98Details> D98DetailsCollection { get; set; }
public ObservableCollection<D675> D675Collection { get; set; }
public CompositeCollection cmpc {get; set; }

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string property)
{
    if(PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }

}

}
What I look for is to bind some values of one ObservaleCollection to one DataGridTextColumn, some values of another ObservableCollection to one anotherDataGridTextColumn, etc.
This is the Datagrid, target of the binding:
<DataGrid x:Name="DonneesBrutes" IsReadOnly="True" ItemsSource="{Binding Path=.cmpc}" Margin="10,65,0,0" AutoGenerateColumns="False" EnableRowVirtualization="True" RowDetailsVisibilityMode="VisibleWhenSelected">
        <DataGrid.RowStyle>
            <Style TargetType="{x:Type DataGridRow}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding .Remarque}" Value="{x:Null}">
                        <Setter Property="Visibility" Value="Collapsed"></Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGrid.RowStyle>
            <DataGrid.Columns>
                <DataGridTextColumn x:Name="PMRQ" Width="*" Binding="{Binding Path=.PMID}" Header="PMID"></DataGridTextColumn>
                <DataGridTextColumn x:Name="LibellePMRQ" Width="*" Binding="{Binding Path=.LibelléTOTApres}" Header="Libellé PMRQ"></DataGridTextColumn>
                <DataGridTextColumn x:Name="Ligne" Width="*"     Binding="{Binding Path=.Remarque}" Header="Ligne" IsReadOnly="True"></DataGridTextColumn>
                <DataGridTextColumn x:Name="OTM" Width="*" Binding="{Binding Path=.TOTMPMRQ}" Header="OTM"></DataGridTextColumn>
                <DataGridTextColumn x:Name="TOTM" Width="*" Binding="{Binding Path=.SiModifie}" Header="TOTM"></DataGridTextColumn>
                <DataGridTextColumn x:Name="LibelleTOTM" Width="*" Binding="{Binding Path=.LibelléTOTApres}" Header="Libellé OTM"></DataGridTextColumn>
                <DataGridTextColumn x:Name="GA" Width="*" Binding="{Binding Path=.Groupe_D_alerte}" Header="GA"></DataGridTextColumn>
                <DataGridTextColumn x:Name="Discipline" Width="*" Binding="{Binding Path=.NomTable}" Header="Discipline"></DataGridTextColumn>
                <DataGridTextColumn x:Name="DisciplineSubstituee" Width="120" Binding="{Binding Path=.NomChamp}" Header="Discipline Substituée"></DataGridTextColumn>
            </DataGrid.Columns>
</DataGrid>

The first DataGridTextColumn is binded from the D98DetailsCollection, the second one is binded from the ResultatCollection, etc. As the following condition : The property TOTMPMRQ which is a common column of each ObservableCollection are equals.
For example, for a TOTMPMRQ like 123456789, I wand to bind the PMRQ value of the D98DetailsCollection in the first DataGridTextColumn where TOTMPMRQ equals 123456789, then bind the libellePMRQ value of the ResultatCollection in the second DataGridTextColumn where TOTMPMRQ still equals 123456789, etc for each DataGridTextColumn to get on one line values from severals ObservableCollections.
My main difficulty is to make this if condition. Currently, the DataGrid only print ObservableCollection after ObservableCollection, and not a combined result.
I hope I'm not too disordered on my explanations, I always can Edit my post if needed, don't hesitate to ask me more, or less...
Thanks in advance for your help.
EDIT1:
I have created a class TestCollectionList which inherit of an ObservableCollection called TestCollection, like this:
public class TestCollectionList : ObservableCollection<TestCollectionList.TestCollection>
    {
        public TestCollectionList() : base()
        {
            Add( new TestCollection());
        }
        public class TestCollection
        {
            private string pmid;
            private string libellepmrq;
            private string ligne;
            private string otm;
            private string totm;
            private string libelleotm;
            private string ga;
            private string discipline;
            private string disciplinesubstituee;

            public TestCollection(string pmid, string libellepmrq, string ligne, string otm, string totm, string libelleotm, string ga, string discipline, string disciplinesubstituee)
            {
                this.pmid = pmid;
                this.libellepmrq = libellepmrq;
                this.ligne = ligne;
                this.otm = otm;
                this.totm = totm;
                this.libelleotm = libelleotm;
                this.ga = ga;
                this.discipline = discipline;
                this.disciplinesubstituee = disciplinesubstituee;
            }

            public string Pmid
            {
                get { return pmid; }
                set { pmid = value; }
            }
            public string Libellepmrq
            {
                get { return libellepmrq; }
                set { pmid = value; }
            }
            public string Ligne
            {
                get { return ligne; }
                set { pmid = value; }
            }
            public string Otm
            {
                get { return otm; }
                set { pmid = value; }
            }
            public string Totm
            {
                get { return totm; }
                set { pmid = value; }
            }
            public string Libelleotm
            {
                get { return libelleotm; }
                set { pmid = value; }
            }
            public string Ga
            {
                get { return ga; }
                set { pmid = value; }
            }
            public string Discipline
            {
                get { return discipline; }
                set { pmid = value; }
            }
            public string Disciplinesubstituee
            {
                get { return disciplinesubstituee; }
                set { pmid = value; }
            }

        }
    }

I have created every properties I want to bind in my DataGridTextColumn and now I want to set them with their values of the differents valus of my DataBase. For example, pmid must be equal of the PMID property of the ObservableCollection D98DetailsCollection, ga must be set the GA property of the ObservableCollection ResultatCollection, etc.
Am I on the good way, Am I definitly wrong? Thanks in advance.


text:
Q: Add reference to AppFabric dll for custom caching I'm trying to add reference to the following dll so I can make use of AppFabric to cache some custom objects.
I've looked at this page
http://www.wictorwilen.se/Post/Improve-performance-of-your-SharePoint-2010-applications-using-Windows-Server-AppFabric-caching.aspx
and this ...
http://msdn.microsoft.com/en-us/library/ee790876.aspx
Which have been very helpful.  However, I cannot find

C:\Windows\SysNative\AppFabric

when trying to add a reference from VS.  I can open the SysNative directory, but there is no AppFabric folder ... if I try to simply type the name, it says it does not exist.
I have though found the two dll's in

'C:\Program Files\AppFabric 1.1 for Windows Server'

This is my first foray into AppFabric, so I don't know if these are the correct dll's to be using?
Any ideas?

A: If they have the namespaces you need, go for it.
You've tagged it with '2013', are you using SharePoint 2013? Make sure that the AppFabric Cache cluster you're using is not the one SharePoint 2013 using, make sure it's on a server that's not one of your SharePoint servers and one that you're maintaining on your own. It's unsupported to use the AbbFabric Distributed Cache for your own applications.
Reference: http://technet.microsoft.com/en-us/library/jj219572.aspx

If you are using custom applications in SharePoint Server 2013 which use the AppFabric client APIs, or are creating custom caches, you should create a separate AppFabric cache cluster to support your custom applications. Do not use the AppFabric cache cluster supporting your SharePoint Server 2013 farm. Run your separate AppFabric cache cluster for your custom applications on separate servers from the servers dedicated to your SharePoint Server 2013 farm.


text:
Q: Pseudo-element after not showing? I want to add a help logo at the end of some form fields which opens a tooltip.
Everything is working, but the .helptip icon (http://img1.wsimg.com/shared/img/1/small-help-icon.gif) is coming on the left(merged) with the text. I actually want in on the right of span text, so I did .help-tip:after. But then nothing shows up at all.
Can you spot what's wrong?

 Include Columns in Result Set

<select class="advancedSearchFormSelectBox" id="filters_include_columns" multiple="multiple" name="filters[include_columns][]">

<option value="x">X</option>
<option value="y">Y</option>
<option value="z">Z</option>
</select>

 Sort Column

<select class="advancedSearchFormSelectBox" id="filters_sort_columns" multiple="multiple" name="filters[sort_columns]">

<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>

.help-tip {
/* Merged text at the moment. .help-tip:after not working */
    cursor: pointer;
    width: 10px;
    height: 10px;
    background-repeat: no-repeat;
    background-image: url("/assets/small-help-icon.gif");
}

.advancedSearchFormSelectField{
    width:300px;
    margin: 5px;
    height: 60px;
    float:left;
}

A: You don't seem to be using a pseudo-element at the moment. Try this setting .help-tip to .help-tip::after and giving is content: "" and display: inline-block:
.help-tip::after {
    content: "";
    display: inline-block;
    cursor: pointer;
    width: 10px;
    height: 10px;
    background-repeat: no-repeat;
    background-image: url("/assets/small-help-icon.gif");
}


text:
Q: Sniff HTTP Requests from TV I'm trying to find a solution to sniff get requests of Smart TV when in request video from the service server. I'm trying to get m3u8 playlist.
My current setup is mac + tv (wifi) and router Asus with merlin firmware.
Does someone know how to find that request? Just interested on URL requests, not pockets.

A: First you have to see the traffic. For this, you have to either:

*

*Gain MitM position by routing the traffic through your PC.

*Be able to monitor the traffic, e.g.

*

*Using a switch with a monitoring / mirroring port that sends copy of everything to you. As this is a home network, you probably don't have one, but any old ethernet hub without the switching capabilities will work as well, if you happen to find one.

*Capturing the WiFi packets. Typically WiFi adapters are only interested in 802.11 frames that matches itself as destination and disregards everything else, so you may need a special driver that allows sniffing.

You also have to be sure the TV is using plain HTTP: you won't get the URLs out of HTTPS traffic.