问:
Can't Disable Offline Data In Firestore
After deleting data from my Firestore Database, it takes my Android app some time to realize that the data was deleted, and I assume that it's happening due the auto data cache. My app has nothing to do with offline usage and I'd like to disable this feature...

I have added this in my custom Application Class:

```<code>import android.app.Application;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreSettings;

public class ApplicationClass extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        FirebaseFirestore db=FirebaseFirestore.getInstance();
        FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
                .setPersistenceEnabled(false)
                .build();
        db.setFirestoreSettings(settings);
    }
}
</code>```

The problem occurs after turning off the internet connection and than turning it back on (while the app is still running, in the background or not)- the Firestore module seems to lose connection to the server, and it makes the opposite operation than the intended one - instead of stop taking data from the cache, it takes data from the cache only.

For example, debugging this code will always show that isFromCache is true and documentSnapshot is empty (even though that on the server side - it's not empty):

```<code>usersRef.document(loggedEmail).collection("challenges_received").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
    @Override
    public void onSuccess(QuerySnapshot documentSnapshots) {
        boolean isFromCache=documentSnapshots.getMetadata().isFromCache();
        if (!documentSnapshots.isEmpty()) {
        }
    }
});
</code>```

Is this normal behavior?

Is there another way to disable the data cache in Cloud Firestore?

EDIT:

Adding: FirebaseFirestore.setLoggingEnabled(flase); (instead of the code above) in the custom Application Class gives the same result.

答:
I just ran a few tests in an Android application to see how this works. Because Firestore is currently still in beta release and the product might suffer changes any time, i cannot guarantee that this behaviour will still hold in the future.

```<code>db.collection("tests").document("fOpCiqmUjAzjnZimjd5c").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        DocumentSnapshot documentSnapshot = task.getResult();
        System.out.println("isFromCache: " + documentSnapshot.getMetadata().isFromCache());
    }
});
</code>```

Regarding the code, is the same no matter if we're getting the data from the cache or you are connected to the servers.

When I'm online it prints:

```<code>isFromCache: false
</code>```

When I'm offline, it prints:

```<code>isFromCache: true
</code>```

So, for the moment, there is no way to stop the retrieval of the data from the cache while you are not connected to the server, as you cannot force the retrieval of the data from the cache while you're connected to the server.

If instead I use a listener:

```<code>db.collection("tests").document("fOpCiqmUjAzjnZimjd5c").addSnapshotListener(new DocumentListenOptions().includeMetadataChanges(), new EventListener<DocumentSnapshot>() {
    @Override
    public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
        System.out.println("listener.isFromCache: " + documentSnapshot.getMetadata().isFromCache());
    }
});
</code>```

I get two prints when I'm online:

```<code>listener.isFromCache: true
listener.isFromCache: false
</code>```

Firestore is desinged to retrieve data from the chache when the device is permanently offline or while your application temporarily loses its network connection and for the moment you cannot change this behaviour.

As a concusion, an API that does something like this, currently doesn't exist yet.

Edit: Unlike in Firebase, where to enable the offline persistence you need use this line of code:

```<code>FirebaseDatabase.getInstance().setPersistenceEnabled(true);
</code>```

In Firestore, for Android and iOS, offline persistence is enabled by default.

Using the above line of code, means that you tell Firebase to create a local (internal) copy of your database so that your app can work even if it temporarily loses its network connection.

In Firestore we find the opposite, to disable persistence, we need to set the PersistenceEnabled option to false. This means that you tell Firestore not to create a local copy of your database on user device, which in term means that you'll not be able to query your database unless your are connected to Firebase servers. So without having a local copy of your database and if beeing disconected, an Exception will be thrown. That's why is a good practice to use the OnFailureListener.

Update (2018-06-13): As also @TalBarda mentioned in his answer this is now possible starting with the 16.0.0 SDK version update. So we can achieve this with the help of the DocumentReference.get(Source source) and Query.get(Source source) methods.

By default, get() attempts to provide up-to-date data when possible by waiting for data from the server, but it may return cached data or fail if you are offline and the server cannot be reached. This behavior can be altered via the Source parameter.

So we can now pass as an argument to the DocumentReference or to the Query the source so we can force the retrieval of data from the server only, chache only or attempt server and fall back to the cache.

So something like this is now possible:

```<code>FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference docIdRef = db.collection("tests").document("fOpCiqmUjAzjnZimjd5c");
docIdRef.get(Source.SERVER).addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
    @Override
    public void onSuccess(DocumentSnapshot documentSnapshot) {
        //Get data from the documentSnapshot object
    }
});
</code>```

In this case, we force the data to be retrieved from the server only. If you want to force the data to be retrieved from the cache only, you should pass as an argument to the get() method, Source.CACHE. More informations here.

Title: Can't Disable Offline Data In Firestore

Body:
After deleting data from my Firestore Database, it takes my Android app some time to realize that the data was deleted, and I assume that it's happening due the auto data cache. My app has nothing to do with offline usage and I'd like to disable this feature...

I have added this in my custom Application Class:

import android.app.Application;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreSettings;

public class ApplicationClass extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        FirebaseFirestore db=FirebaseFirestore.getInstance();
        FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
                .setPersistenceEnabled(false)
                .build();
        db.setFirestoreSettings(settings);
    }
}

The problem occurs after turning off the internet connection and than turning it back on (while the app is still running, in the background or not)- the Firestore module seems to lose connection to the server, and it makes the opposite operation than the intended one - instead of stop taking data from the cache, it takes data from the cache only.

For example, debugging this code will always show that isFromCache is true and documentSnapshot is empty (even though that on the server side - it's not empty):

usersRef.document(loggedEmail).collection("challenges_received").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
    @Override
    public void onSuccess(QuerySnapshot documentSnapshots) {
        boolean isFromCache=documentSnapshots.getMetadata().isFromCache();
        if (!documentSnapshots.isEmpty()) {
        }
    }
});

Is this normal behavior?

Is there another way to disable the data cache in Cloud Firestore?

EDIT:

Adding: FirebaseFirestore.setLoggingEnabled(flase); (instead of the code above) in the custom Application Class gives the same result.

Body:
I just ran a few tests in an Android application to see how this works. Because Firestore is currently still in beta release and the product might suffer changes any time, i cannot guarantee that this behaviour will still hold in the future.

db.collection("tests").document("fOpCiqmUjAzjnZimjd5c").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        DocumentSnapshot documentSnapshot = task.getResult();
        System.out.println("isFromCache: " + documentSnapshot.getMetadata().isFromCache());
    }
});

Regarding the code, is the same no matter if we're getting the data from the cache or you are connected to the servers.

When I'm online it prints:

isFromCache: false

When I'm offline, it prints:

isFromCache: true

So, for the moment, there is no way to stop the retrieval of the data from the cache while you are not connected to the server, as you cannot force the retrieval of the data from the cache while you're connected to the server.

If instead I use a listener:

db.collection("tests").document("fOpCiqmUjAzjnZimjd5c").addSnapshotListener(new DocumentListenOptions().includeMetadataChanges(), new EventListener<DocumentSnapshot>() {
    @Override
    public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
        System.out.println("listener.isFromCache: " + documentSnapshot.getMetadata().isFromCache());
    }
});

I get two prints when I'm online:

listener.isFromCache: true
listener.isFromCache: false

Firestore is desinged to retrieve data from the chache when the device is permanently offline or while your application temporarily loses its network connection and for the moment you cannot change this behaviour.

As a concusion, an API that does something like this, currently doesn't exist yet.

Edit: Unlike in Firebase, where to enable the offline persistence you need use this line of code:

FirebaseDatabase.getInstance().setPersistenceEnabled(true);

In Firestore, for Android and iOS, offline persistence is enabled by default.

Using the above line of code, means that you tell Firebase to create a local (internal) copy of your database so that your app can work even if it temporarily loses its network connection.

In Firestore we find the opposite, to disable persistence, we need to set the PersistenceEnabled option to false. This means that you tell Firestore not to create a local copy of your database on user device, which in term means that you'll not be able to query your database unless your are connected to Firebase servers. So without having a local copy of your database and if beeing disconected, an Exception will be thrown. That's why is a good practice to use the OnFailureListener.

Update (2018-06-13): As also @TalBarda mentioned in his answer this is now possible starting with the 16.0.0 SDK version update. So we can achieve this with the help of the DocumentReference.get(Source source) and Query.get(Source source) methods.

By default, get() attempts to provide up-to-date data when possible by waiting for data from the server, but it may return cached data or fail if you are offline and the server cannot be reached. This behavior can be altered via the Source parameter.

So we can now pass as an argument to the DocumentReference or to the Query the source so we can force the retrieval of data from the server only, chache only or attempt server and fall back to the cache.

So something like this is now possible:

FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference docIdRef = db.collection("tests").document("fOpCiqmUjAzjnZimjd5c");
docIdRef.get(Source.SERVER).addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
    @Override
    public void onSuccess(DocumentSnapshot documentSnapshot) {
        //Get data from the documentSnapshot object
    }
});

In this case, we force the data to be retrieved from the server only. If you want to force the data to be retrieved from the cache only, you should pass as an argument to the get() method, Source.CACHE. More informations here.


来源: stackexchange

问:
Does RxJava's Observable.subscriber()'s onNext callback have to use threadsafe objects?
This is what my code looks like:

```<code>ArrayList<T> result = new ArrayList<T>();
observable.subscribe(result::add, <something here>, <something here>);
</code>```

Is this not recommended? Should result be a thread-safe structure?

答:
It is important that you understand what thread safety means.

One type of thread safety arises from compartmentalization, from only performing operations on an object in one thread. In that case, the object you working on does not have special thread safety issues.

The other type of thread safety comes about when you use synchronize, volatile, etc, to ensure the serial nature of access and modification.

In your example, result is not thread-safe, but we can't tell if it is properly compartmentalised, making thread-safety a non-issue. Examples of safety violations:

your observable could have values emitted through it from different threads. You need to make sure your are using a SerializedSubject or similar to ensure that the observable contract is maintaned.

any code that uses result while the observer chain is active runs the risk of making the use unsafe.

Here is how to compartmentalize the access to result:

```<code>Scheduler myScheduler; // have a known, single-threaded scheduler.
...
List<String> result;
...
observer
  .observeOn( myScheduler )
  .subscribe( List::add, err -> {},
     () -> { // do end of processing here
   });
</code>```

Using observeOn() will ensure a single thread is responsible for adding elements to result.

To access the contents of result, you need to a) wait until the observer chain is done, which can be signalled in the onCompleted() processing, or b) you need to run on the same thread as the observer chain.

ContentLicense: CC BY-SA 3.0

Body:
This is what my code looks like:

ArrayList<T> result = new ArrayList<T>();
observable.subscribe(result::add, <something here>, <something here>);

Is this not recommended? Should result be a thread-safe structure?

Body:
It is important that you understand what thread safety means.

One type of thread safety arises from compartmentalization, from only performing operations on an object in one thread. In that case, the object you working on does not have special thread safety issues.

The other type of thread safety comes about when you use synchronize, volatile, etc, to ensure the serial nature of access and modification.

In your example, result is not thread-safe, but we can't tell if it is properly compartmentalised, making thread-safety a non-issue. Examples of safety violations:

your observable could have values emitted through it from different threads. You need to make sure your are using a SerializedSubject or similar to ensure that the observable contract is maintaned.

any code that uses result while the observer chain is active runs the risk of making the use unsafe.

Here is how to compartmentalize the access to result:

Scheduler myScheduler; // have a known, single-threaded scheduler.
...
List<String> result;
...
observer
  .observeOn( myScheduler )
  .subscribe( List::add, err -> {},
     () -> { // do end of processing here
   });

Using observeOn() will ensure a single thread is responsible for adding elements to result.

To access the contents of result, you need to a) wait until the observer chain is done, which can be signalled in the onCompleted() processing, or b) you need to run on the same thread as the observer chain.


答:
Please provide the code that produced the working plot. Any warning messages?

As for your last questions: to select the rows you want, you can simply use > and < operators to compare two datetimes in conditional statements.

For vertical lines, you can use plt.axvline(x=date, color = 'r')

Title: why a non-zero value is plotted as zero in matplotlib in python?

Body:
I plotted a data frame like this:

           Date  Quote-Spread
  0   2013-11-17           2.0
  1   2013-12-10           8.0
  2   2013-12-11           8.0
  3   2014-06-01           5.0
  4   2014-06-23          15.0
  5   2014-06-24          45.0
  6   2014-06-25          10.0
  7   2014-06-28          20.0
  8   2014-09-13       50000.0
  9   2015-03-30      250000.0
  10  2016-04-02      103780.0
  11  2016-04-03      119991.0
  12  2016-04-04       29994.0
  13  2016-04-05       69993.0
  14  2016-04-06       39997.0
  15  2016-04-09      490321.0
  16  2016-04-10       65485.0
  17  2016-04-11      141470.0
  18  2016-04-12      109939.0
  19  2016-04-13       29983.0
  20  2016-04-16       39964.0
  21  2016-04-17       39964.0
  22  2016-04-18       79920.0
  23  2016-04-19       29997.0
  24  2016-04-20      108414.0
  25  2016-04-23      126849.0
  26  2016-04-24      206853.0
  27  2016-04-25       37559.0
  28  2016-04-26       22817.0
  29  2016-04-27       37506.0
  30  2016-04-30       37597.0
  31  2016-05-01       18799.0
  32  2016-05-02       18799.0
  33  2016-05-03        9400.0
  34  2016-05-07       29890.0
  35  2016-05-08       29193.0
  36  2016-05-09        7792.0
  37  2016-05-10        3199.0
  38  2016-05-11        8538.0
  39  2016-05-14       49937.0

I use this command to plot them in ipython:

  df2.plot(x= 'Date', y='Quote-Spread')

  plt.show()

But my figure is plotted like this:

As you can see in day 2014-04-23, the Quote-Spread has a value about 126,000. But in plot it is just zero.

my whole plot is like this:

Here is my code of original data:

  Sachad = df.loc[df['SID']== 40065016131938148]
  #Drop rows with any zero
  df1 = df1[~(df1 == 0).any(axis = 1)]
  df1['Quote-Spread'] = (df1['SellPrice'].mask(df1['SellPrice'].eq(0))-
  df1['BuyPrice'].mask(df1['BuyPrice'].eq(0))).abs()
  df2 = df1.groupby('Date' , as_index = False )['Quote-Spread'].mean()
  df2.plot(x= 'Date', y='Quote-Spread')
  plt.show()

Another question is how i can plot for specific dates like between 2014-04-01 up to 2016-06-01.  and draw vertical red lines for dates 2014-06-06 and 2016-01-06?


问:
NSTextView monitor caret position change
How can i get a callback on the caret position change for a NSTextView?

I tried KVO

```<code>[textView addObserver:self forKeyPath:@"selectedRange" options:NSKeyValueObservingOptionNew context:NULL];
</code>```

But i don't get the callback when i move with arrow keys, or mouse... probably because the range is a struct, which gets its members modified (i get only callback when the text changes)

But how to monitor a caret position change?

答:
Swift 4 version:</p>

```<code>public func textViewDidChangeSelection(_ notification: Notification) {
   guard let textView = notification.object as? NSTextView,
         let string = textView.textStorage?.string else {
      return
   }

   if let nsRange = textView.selectedRanges.first as? NSRange,
      let range = Range(nsRange, in: string) {
      print(nsRange)
      print(range.lowerBound.encodedOffset, range.upperBound.encodedOffset)
   }
}
</code>```

Body:
How can i get a callback on the caret position change for a NSTextView?

I tried KVO

[textView addObserver:self forKeyPath:@"selectedRange" options:NSKeyValueObservingOptionNew context:NULL];

But i don't get the callback when i move with arrow keys, or mouse... probably because the range is a struct, which gets its members modified (i get only callback when the text changes)

But how to monitor a caret position change?

Body:
Swift 4 version:

public func textViewDidChangeSelection(_ notification: Notification) {
   guard let textView = notification.object as? NSTextView,
         let string = textView.textStorage?.string else {
      return
   }

   if let nsRange = textView.selectedRanges.first as? NSRange,
      let range = Range(nsRange, in: string) {
      print(nsRange)
      print(range.lowerBound.encodedOffset, range.upperBound.encodedOffset)
   }
}


问:
how to check if next record exists in an msi file?
With MsiViewFetch we are able to get the record from the sql query to msi.
But is there any constant or function to check whether next record exists or number of rows/records in a file table msi?</p>

答:
No. Windows Installer's implementation of SQL is fairly limited. All that's available is the option to call MsiViewFetch repeatedly until it returns ERROR_NO_MORE_ITEMS. Once you have retrieved all the records, it will do so. It is up to you to track the count along the way, and also properly handle all returned objects. (For example, each successfully returned record must be closed with MsiCloseHandle, and in unusual circumstances the view itself may need to be closed with MsiViewClose.)

As noted, this may be expressed differently in different languages that wrap it. For example, the Windows Installer Automation Interface's View.Fetch method returns Nothing if you have already retrieved all the records. Cleaning up resources will typically have been altered to use the conventions of the language in question as well.

In particular, Python's msilib is a wrapper of Windows Installer functionality that was implemented specifically to support creating Python's own installers. Because it wasn't intended for general purpose use, it lacks some of the creature comforts of other wrappers. You can see that the implementation of View.Fetch turns any non-success return code into an MSIError, and ERROR_NO_MORE_ITEMS is not ERROR_SUCCESS. So for your usage, you will have to catch MSIError and either hope it's for ERROR_NO_MORE_ITEMS, or check the exception's string for the 103 embedded within.


问:
Incompatible types: String cannot be converted to Word
I know why the compatibility error occurs, but I want to know how you can add a String to an ArrayList of type < Word > which is a class in the program.

In OO principles, a "WordContainer" is a type of "Container", and it contains "Words", which is what I'm trying to implement here, but how do you add a String to a WordContainer that has a list of words of type Word?

```<code>public class Word {
  private String word;
  public String getWord() {
    return this.word;
  }
  public void setWord(String word) {
    this.word = word;
  }
  public Word() {
    this.word = "";
  }
}
</code>```

Container class which contains a list of words that are of type Word:

```<code>import java.util.*;
public class WordContainer {
  private List < Word > words = new ArrayList < Word > ();
  public List < Word > getWords() {
    return this.words;
  }
  public void setWords(List < Word > words) {
    this.words = words;
  }

  public void addWord(Word word) {

    this.words.add(word);
  }

  public void display() {

    words.forEach((word) - > {
      System.out.println(word);
    });

  }

  public WordContainer() {

  }
}
</code>```

Main class:

```<code>public static void main(String[] args) {
  Scanner naughty = new Scanner(System.in);
  WordContainer container1 = new WordContainer();

  while (true) {
    String nextLine = naughty.nextLine();
    if (nextLine.equals("")) {

      container1.display();
      System.exit(0);
    }

    container1.addWord(nextLine); // this bit doesn't work :(
  }

}
</code>```

答:
Your addWord() method expects a Word as parameter, but you were passing a String to it in this line:

```<code>container1.addWord(nextLine);
</code>```

That's why you got the Exception: Incompatible types: String cannot be converted to Word

Solution:

It needs to be:

```<code>container1.addWord(new Word(nextLine));
</code>```

And you need to implement a constructor with a String argument:

```<code>public Word(String word) {
    this.word = word;
}
</code>```

Alternative:

Or you can keep your actual main class code and implement a method that accespts a String and add a new Wordobject to your list:

```<code>public void addWord(String text) {
    this.words.add(new Word(text));
}
</code>```

Body:
I know why the compatibility error occurs, but I want to know how you can add a String to an ArrayList of type < Word > which is a class in the program.

In OO principles, a "WordContainer" is a type of "Container", and it contains "Words", which is what I'm trying to implement here, but how do you add a String to a WordContainer that has a list of words of type Word?

public class Word {
  private String word;
  public String getWord() {
    return this.word;
  }
  public void setWord(String word) {
    this.word = word;
  }
  public Word() {
    this.word = "";
  }
}

Container class which contains a list of words that are of type Word:

import java.util.*;
public class WordContainer {
  private List < Word > words = new ArrayList < Word > ();
  public List < Word > getWords() {
    return this.words;
  }
  public void setWords(List < Word > words) {
    this.words = words;
  }

  public void addWord(Word word) {

    this.words.add(word);
  }

  public void display() {

    words.forEach((word) - > {
      System.out.println(word);
    });

  }

  public WordContainer() {

  }
}

Main class:

public static void main(String[] args) {
  Scanner naughty = new Scanner(System.in);
  WordContainer container1 = new WordContainer();

  while (true) {
    String nextLine = naughty.nextLine();
    if (nextLine.equals("")) {

      container1.display();
      System.exit(0);
    }

    container1.addWord(nextLine); // this bit doesn't work :(
  }

}

Body:
Your addWord() method expects a Word as parameter, but you were passing a String to it in this line:

container1.addWord(nextLine);

That's why you got the Exception: Incompatible types: String cannot be converted to Word

Solution:

It needs to be:

container1.addWord(new Word(nextLine));

And you need to implement a constructor with a String argument:

public Word(String word) {
    this.word = word;
}

Alternative:

Or you can keep your actual main class code and implement a method that accespts a String and add a new Wordobject to your list:

public void addWord(String text) {
    this.words.add(new Word(text));
}


问:
Can I use strcmp without pointers?
I have to make a program which takes a file of DNA sequences and a DNA subsequence from command arguments and find each time the subsequence and how many times it occurs. I'm having troubles with strcmp in line 36 and 42. Currently the way I have it I figured out through GDB that I am comparing the address of the strings and not the actual strings. But if I remove the & I get an error. I'm not sure what is the correct way to go about this is. TIA

```<code>#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    // place subsequence in string
    char *subsequence = argv[2];
    // get length of subsequence
    int seqLength = strlen(subsequence);
    // define file type and open for reading
    FILE *inputFile = fopen(argv[1], "r");
    // get each line using while loop
    char inputLine[200]; // string variable to store each line
    int i, j, lineLength, counter = 0, flag = -1;

    while (fgets(inputLine, 200, inputFile) != NULL) { // loop through each line
        lineLength = strlen(inputLine);

        for (i = 0; i < lineLength; i++) { // loop through each char in the line
            if (strcmp(&inputLine[i], &subsequence[0]) == 0) {
            // if current char matches beginning of sequence loop through
            // each of the remaining chars and check them against
            // corresponding chars in the sequence

                flag = 0;

                for (j = i + 1; j - i < seqLength; j++) {
                    if (strcmp(&inputLine[j], &subsequence[j - i]) != 0) {
                        flag = 1;
                        break;
                    }
                }

                if (flag == 0) {
                    counter++;
                }
            }
        }
    }

    fclose(inputFile);
    printf("%s appears %d time(s)\n", subsequence, counter);
    return 0;
}
</code>```

dna.txt:

```<code>GGAAGTAGCAGGCCGCATGCTTGGAGGTAAAGTTCATGGTTCCCTGGCCC
</code>```

input:

```<code>./dnaSearch dna.txt GTA
</code>```

expected output:

```<code>GTA appears 2 times
</code>```

答:
Your string inputLine is a pointer to an array of characters and terminated in character '\0'.

strcmp expects a '\0' terminated string.

Passing &inputLine[i] is passing the address of character in position 'i' to the pointer argument and the string will be read until the '\0' character.

As suggested in the comments, you either use the ordinary operators to compare the strings characters:

```<code>if (inputLine[i] == subsequence[0]) {
    flag = 0;
    for (j = i + 1; j - i < seqLength; j++) {// loop
        if (inputLine[j] != subsequence[j - i]) {
            flag = 1;
            break;
        }
    }
</code>```

Or use strncmp, which compares substrings:

```<code>if (strncmp(&inputLine[i], subsequence, seqLength) == 0) {
    counter++;
}
</code>```

Title: Can I use strcmp without pointers?

Body:
I have to make a program which takes a file of DNA sequences and a DNA subsequence from command arguments and find each time the subsequence and how many times it occurs. I'm having troubles with strcmp in line 36 and 42. Currently the way I have it I figured out through GDB that I am comparing the address of the strings and not the actual strings. But if I remove the & I get an error. I'm not sure what is the correct way to go about this is. TIA

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    // place subsequence in string
    char *subsequence = argv[2];
    // get length of subsequence
    int seqLength = strlen(subsequence);
    // define file type and open for reading
    FILE *inputFile = fopen(argv[1], "r");
    // get each line using while loop
    char inputLine[200]; // string variable to store each line
    int i, j, lineLength, counter = 0, flag = -1;

    while (fgets(inputLine, 200, inputFile) != NULL) { // loop through each line
        lineLength = strlen(inputLine);

        for (i = 0; i < lineLength; i++) { // loop through each char in the line
            if (strcmp(&inputLine[i], &subsequence[0]) == 0) {
            // if current char matches beginning of sequence loop through
            // each of the remaining chars and check them against
            // corresponding chars in the sequence

                flag = 0;

                for (j = i + 1; j - i < seqLength; j++) {
                    if (strcmp(&inputLine[j], &subsequence[j - i]) != 0) {
                        flag = 1;
                        break;
                    }
                }

                if (flag == 0) {
                    counter++;
                }
            }
        }
    }

    fclose(inputFile);
    printf("%s appears %d time(s)\n", subsequence, counter);
    return 0;
}

dna.txt:

GGAAGTAGCAGGCCGCATGCTTGGAGGTAAAGTTCATGGTTCCCTGGCCC

input:

./dnaSearch dna.txt GTA

expected output:

GTA appears 2 times

Body:
Your string inputLine is a pointer to an array of characters and terminated in character '\0'.

strcmp expects a '\0' terminated string.

Passing &inputLine[i] is passing the address of character in position 'i' to the pointer argument and the string will be read until the '\0' character.

As suggested in the comments, you either use the ordinary operators to compare the strings characters:

if (inputLine[i] == subsequence[0]) {
    flag = 0;
    for (j = i + 1; j - i < seqLength; j++) {// loop
        if (inputLine[j] != subsequence[j - i]) {
            flag = 1;
            break;
        }
    }

Or use strncmp, which compares substrings:

if (strncmp(&inputLine[i], subsequence, seqLength) == 0) {
    counter++;
}


问:
ASP.NET Web API programmatic way of applying IQueryable to an Entity Framework query
We can accept an OData query from the URL with web API and that is as simple as:

```<code>[EnableQuery]
public IQueryable<EFType> GetBuiltInTypes()
{
    return db.EFTypes;
}
</code>```

The data is restricted in the database as the OData query is added to the Entity Framework database query.

Let's say I want to do some work with the data before returning it:

```<code>[EnableQuery]
public IQueryable<SomePOCO> GetBuiltInTypes()
{
    var dbQuery = from obj in FncCall() select obj;

    //Do something with the data and put the result into a
    //List<SomePOCO>

    var list = DoSomeWork(dbQuery) //whatever

    return list.AsQueryable();
}
</code>```

Note: FncCall() returns a generic DbSet and not a DbSet<SomeType>

It will still work but it will restrict the results and apply the OData query to my list in memory and not the dbQuery being applied to the database? Any simple way of doing it?

From the Microsoft documentation at:

we can do

```<code>public IQueryable<Product> Get(ODataQueryOptions opts) {
    var settings = new ODataValidationSettings() {
        // Initialize settings as needed.
        AllowedFunctions = AllowedFunctions.AllMathFunctions
    };

    opts.Validate(settings);

    IQueryable results = opts.ApplyTo(products.AsQueryable());
    return results as IQueryable<Product>;
}
</code>```

but I don't know the type, in this case, Product at compile time as what I have to work with is a DbType.

答:
Yes, do not call ToList/ToArray/AsEnumerable/etc. or anything else that would cause your IQueryable instance to call the database. </p>

<p>For example: </p>

```<code>[EnableQuery]
public IQueryable<SomePOCO> GetBuiltInTypes()
{
    var dbQuery = from obj in FncCall() select obj;
    // at this point the database has not yet been called
    IQueryable<SomePOCO> result = DoSomeWork(dbQuery);
    return result;
}

private IQueryable<SomePOCO> DoSomeWork(IQueryable<SomePOCO> dbQuery)
{
   // still not executed against db
   return dbQuery.Where(x => x.something == "something");
}
</code>```

Body:
We can accept an OData query from the URL with web API and that is as simple as:

[EnableQuery]
public IQueryable<EFType> GetBuiltInTypes()
{
    return db.EFTypes;
}

The data is restricted in the database as the OData query is added to the Entity Framework database query.

Let's say I want to do some work with the data before returning it:

[EnableQuery]
public IQueryable<SomePOCO> GetBuiltInTypes()
{
    var dbQuery = from obj in FncCall() select obj;

    //Do something with the data and put the result into a
    //List<SomePOCO>

    var list = DoSomeWork(dbQuery) //whatever

    return list.AsQueryable();
}

Note: FncCall() returns a generic DbSet and not a DbSet<SomeType>

It will still work but it will restrict the results and apply the OData query to my list in memory and not the dbQuery being applied to the database? Any simple way of doing it?

From the Microsoft documentation at:

we can do

public IQueryable<Product> Get(ODataQueryOptions opts) {
    var settings = new ODataValidationSettings() {
        // Initialize settings as needed.
        AllowedFunctions = AllowedFunctions.AllMathFunctions
    };

    opts.Validate(settings);

    IQueryable results = opts.ApplyTo(products.AsQueryable());
    return results as IQueryable<Product>;
}

but I don't know the type, in this case, Product at compile time as what I have to work with is a DbType.

Body:
Yes, do not call ToList/ToArray/AsEnumerable/etc. or anything else that would cause your IQueryable instance to call the database.

For example:

[EnableQuery]
public IQueryable<SomePOCO> GetBuiltInTypes()
{
    var dbQuery = from obj in FncCall() select obj;
    // at this point the database has not yet been called
    IQueryable<SomePOCO> result = DoSomeWork(dbQuery);
    return result;
}

private IQueryable<SomePOCO> DoSomeWork(IQueryable<SomePOCO> dbQuery)
{
   // still not executed against db
   return dbQuery.Where(x => x.something == "something");
}


问:
Underlying explanation of simple calc benchmark
The following benchmarks performs best on the one with a function operating the calculation. Even if it inlines, why does it perform better?

```<code>func add1(i int) int {
    return i + 1
}

var x = 0

func BenchmarkAdd1(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x = x + 1
    }
}

func BenchmarkAdd1ForceType(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x = x + int(1)
    }
}

func BenchmarkIncrement(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x++
    }
}

func BenchmarkAdd1WithFunction(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x = add1(x)
    }
}

 BenchmarkAdd1-8                         1000000000               1.99 ns/op
 BenchmarkAdd1ForceType-8                2000000000               1.96 ns/op
 BenchmarkIncrement-8                    2000000000               2.02 ns/op
 BenchmarkAdd1WithFunction-8             2000000000               0.44 ns/op
</code>```

CPU is Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz

Go version 1.9.2 darwin/amd64

答:
It gets optimized away. If you do something with x after the loop, you'll find they all perform about the same:

```<code>var buf = new(bytes.Buffer)

func add1(i int) int {
    return i + 1
}

func BenchmarkAdd1(b *testing.B) {
    var x = 0
    for i := 0; i < b.N; i++ {
        x = x + 1
    }
    fmt.Fprintln(buf, x)
}

func BenchmarkAdd1ForceType(b *testing.B) {
    var x = 0
    for i := 0; i < b.N; i++ {
        x = x + int(1)
    }
    fmt.Fprintln(buf, x)
}

func BenchmarkIncrement(b *testing.B) {
    var x = 0
    for i := 0; i < b.N; i++ {
        x++
    }
    fmt.Fprintln(buf, x)
}

func BenchmarkAdd1WithFunction(b *testing.B) {
    var x = 0
    for i := 0; i < b.N; i++ {
        x = add1(x)
    }
    fmt.Fprintln(buf, x)
}
</code>```

This yields:

```<code>BenchmarkAdd1-4                 2000000000           0.34 ns/op
BenchmarkAdd1ForceType-4        2000000000           0.33 ns/op
BenchmarkIncrement-4            2000000000           0.34 ns/op
BenchmarkAdd1WithFunction-4     2000000000           0.35 ns/op
</code>```

Body:
The following benchmarks performs best on the one with a function operating the calculation. Even if it inlines, why does it perform better?

func add1(i int) int {
    return i + 1
}

var x = 0

func BenchmarkAdd1(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x = x + 1
    }
}

func BenchmarkAdd1ForceType(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x = x + int(1)
    }
}

func BenchmarkIncrement(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x++
    }
}

func BenchmarkAdd1WithFunction(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x = add1(x)
    }
}

 BenchmarkAdd1-8                         1000000000               1.99 ns/op
 BenchmarkAdd1ForceType-8                2000000000               1.96 ns/op
 BenchmarkIncrement-8                    2000000000               2.02 ns/op
 BenchmarkAdd1WithFunction-8             2000000000               0.44 ns/op

CPU is Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz

Go version 1.9.2 darwin/amd64

Body:
It gets optimized away. If you do something with x after the loop, you'll find they all perform about the same:

var buf = new(bytes.Buffer)

func add1(i int) int {
    return i + 1
}

func BenchmarkAdd1(b *testing.B) {
    var x = 0
    for i := 0; i < b.N; i++ {
        x = x + 1
    }
    fmt.Fprintln(buf, x)
}

func BenchmarkAdd1ForceType(b *testing.B) {
    var x = 0
    for i := 0; i < b.N; i++ {
        x = x + int(1)
    }
    fmt.Fprintln(buf, x)
}

func BenchmarkIncrement(b *testing.B) {
    var x = 0
    for i := 0; i < b.N; i++ {
        x++
    }
    fmt.Fprintln(buf, x)
}

func BenchmarkAdd1WithFunction(b *testing.B) {
    var x = 0
    for i := 0; i < b.N; i++ {
        x = add1(x)
    }
    fmt.Fprintln(buf, x)
}

This yields:

BenchmarkAdd1-4                 2000000000           0.34 ns/op
BenchmarkAdd1ForceType-4        2000000000           0.33 ns/op
BenchmarkIncrement-4            2000000000           0.34 ns/op
BenchmarkAdd1WithFunction-4     2000000000           0.35 ns/op


问:
Footable: change row position in phone screen
I have a footable as the below:

The column starts with Status, followed by Title, I, II, III, IV, V, VI, VII, Date.

When switch to mobile new, it also follow the order to show as picture below.

I want to rearrange column Status and show it after VII column.

I tried by searching online and footable documentation, but seems no similar solution.

Appreciate any help! Thanks!

```<code><table class="footable" cellspacing="0" border="0" id="dnn_ctr538_list_gvList" style="border-collapse:collapse;">
  <thead>
    <tr class="Head nodrag nodrop" style="font-weight:normal;">
      <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 5%; display: table-cell;">Status</th>
      <th align="center" valign="middle" scope="col" style="width:40%;">Title</th>
      <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">I</th>
      <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">II</th>
      <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">III</th>
      <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">IV</th>
      <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">V</th>
      <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">VI</th>
      <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">VII</th>
      <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 10%; display: table-cell;">Date</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td align="left" valign="middle" style="display: table-cell;">
        <div style="padding-left: 10px">

        </div>
      </td>
      <td align="left" valign="middle">
        <div style="padding-left: 10px">
          test
        </div>
      </td>
      <td align="center" valign="middle" style="display: table-cell;">
        <img src="http://www.clker.com/cliparts/a/L/I/b/q/o/green-check-mark.svg" style="border-width:0px; width:70px; height: 70px;">
      </td>
      <td align="center" valign="middle" style="display: table-cell;">

      </td>
      <td align="center" valign="middle" style="display: table-cell;">
        <img src="http://www.clker.com/cliparts/a/L/I/b/q/o/green-check-mark.svg" style="border-width:0px; width:70px; height: 70px;">
      </td>
      <td align="center" valign="middle" style="display: table-cell;">

      </td>
      <td align="center" valign="middle" style="display: table-cell;">

      </td>
      <td align="center" valign="middle" style="display: table-cell;">

      </td>
      <td align="center" valign="middle" style="display: table-cell;">

      </td>
      <td align="center" valign="middle" style="display: table-cell;">
        11/07/2013
      </td>
    </tr>
  </tbody>
</table>
</code>```

答:
I wasn't able to reproduce the code completely, but what about adding two "Status" rows and displaying only one of them at different resolutions?

JSFiddle here. I used Footable with Bootstrap.

HTML

```<code><table class="footable" cellspacing="0" border="0" id="dnn_ctr538_list_gvList" style="border-collapse:collapse;">
<thead>
<tr class="Head nodrag nodrop" style="font-weight:normal;">
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 5%;" class="hide_small">Status</th>
  <th align="center" valign="middle" scope="col" style="width:40%;">Title</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">I</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">II</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">III</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">IV</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">V</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">VI</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">VII</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 5%;" class="hide_big">Status</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 10%; display: table-cell;">Date</th>
</tr>
</thead>
<tbody>
<tr>
  <td align="left" valign="middle" style="display: table-cell;">
    <div style="padding-left: 10px"></div>
  </td>
  <td align="left" valign="middle">
    <div style="padding-left: 10px">test</div>
  </td>
  <td align="center" valign="middle" style="display: table-cell;">
    <img src="http://www.clker.com/cliparts/a/L/I/b/q/o/green-check-mark.svg" style="border-width:0px; width:70px; height: 70px;">
  </td>
  <td align="center" valign="middle" style="display: table-cell;">

  </td>
  <td align="center" valign="middle" style="display: table-cell;">
    <img src="http://www.clker.com/cliparts/a/L/I/b/q/o/green-check-mark.svg" style="border-width:0px; width:70px; height: 70px;">
  </td>
  <td align="center" valign="middle" style="display: table-cell;">

  </td>
  <td align="center" valign="middle" style="display: table-cell;">

  </td>
  <td align="center" valign="middle" style="display: table-cell;">

  </td>
  <td align="center" valign="middle" style="display: table-cell;">

  </td>
  <td align="center" valign="middle" style="display: table-cell;">
    11/07/2013
  </td>
</tr>
</code>```

CSS

```<code>.hide_small {display: table-cell;}
.hide_big {display: table-cell;}

@media (min-width: 476px) {
   .hide_small {display: table-cell;}
   .hide_big {display: none;}
}

@media (max-width: 476px) {
   .hide_small {display: none;}
   .hide_big {
       display: table-cell;
    }
</code>```

}

Body:
I have a footable as the below:

The column starts with Status, followed by Title, I, II, III, IV, V, VI, VII, Date.

When switch to mobile new, it also follow the order to show as picture below.

I want to rearrange column Status and show it after VII column.

I tried by searching online and footable documentation, but seems no similar solution.

Appreciate any help! Thanks!

      Status
      Title
      I
      II
      III
      IV
      V
      VI
      VII
      Date

          test

        11/07/2013

Body:
I wasn't able to reproduce the code completely, but what about adding two "Status" rows and displaying only one of them at different resolutions?

JSFiddle here. I used Footable with Bootstrap.

HTML

<table class="footable" cellspacing="0" border="0" id="dnn_ctr538_list_gvList" style="border-collapse:collapse;">
<thead>
<tr class="Head nodrag nodrop" style="font-weight:normal;">
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 5%;" class="hide_small">Status</th>
  <th align="center" valign="middle" scope="col" style="width:40%;">Title</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">I</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">II</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">III</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">IV</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">V</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">VI</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 4%; display: table-cell;">VII</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 5%;" class="hide_big">Status</th>
  <th align="center" valign="middle" data-hide="phone" scope="col" style="width: 10%; display: table-cell;">Date</th>
</tr>
</thead>
<tbody>
<tr>
  <td align="left" valign="middle" style="display: table-cell;">
    <div style="padding-left: 10px"></div>
  </td>
  <td align="left" valign="middle">
    <div style="padding-left: 10px">test</div>
  </td>
  <td align="center" valign="middle" style="display: table-cell;">
    <img src="http://www.clker.com/cliparts/a/L/I/b/q/o/green-check-mark.svg" style="border-width:0px; width:70px; height: 70px;">
  </td>
  <td align="center" valign="middle" style="display: table-cell;">

  </td>
  <td align="center" valign="middle" style="display: table-cell;">
    <img src="http://www.clker.com/cliparts/a/L/I/b/q/o/green-check-mark.svg" style="border-width:0px; width:70px; height: 70px;">
  </td>
  <td align="center" valign="middle" style="display: table-cell;">

  </td>
  <td align="center" valign="middle" style="display: table-cell;">

  </td>
  <td align="center" valign="middle" style="display: table-cell;">

  </td>
  <td align="center" valign="middle" style="display: table-cell;">

  </td>
  <td align="center" valign="middle" style="display: table-cell;">
    11/07/2013
  </td>
</tr>

CSS

.hide_small {display: table-cell;}
.hide_big {display: table-cell;}

@media (min-width: 476px) {
   .hide_small {display: table-cell;}
   .hide_big {display: none;}
}

@media (max-width: 476px) {
   .hide_small {display: none;}
   .hide_big {
       display: table-cell;
    }

}


问:
AppiumLibrary: Element Should Not Be Visible Keyword?
In AppiumLibrary, as of version 1.4.5, a very handy keyword called Element Should Be Visible has been introduced. But I am looking for the opposite version of that keyword too, which would be something like Element Should Not Be Visible. Since AppiumLibrary doesn't have that yet, is there any way we could achieve this?

答:
Thanks to Verv for the guidelines. I tried both approaches that he suggested, and both seem to be super easy. For future reference, I'm explaining both methods here.

Method 1:

Under AppiumeLibrary/keywords directory, there's a file called _element.py, which defines the Element Should Be Visible keyword. I was able to clone it to create the new keyword I was looking for.

Below is the code snippet that defines Element Should Be Visible

```<code>    def element_should_be_visible(self, locator, loglevel='INFO'):
        """Verifies that element identified with locator is visible.

        Key attributes for arbitrary elements are `id` and `name`. See
        `introduction` for details about locating elements.

        New in AppiumLibrary 1.4.5
        """
        if not self._element_find(locator, True, True).is_displayed():
            self.log_source(loglevel)
            raise AssertionError("Element '%s' should be visible "
                             "but did not" % locator)
</code>```

Next to the above code snippet, you can add the following code snippet to define a new keyword Element Should Not Be Visible

```<code>    def element_should_not_be_visible(self, locator, loglevel='INFO'):
        """Verifies that element identified with locator is visible.

        Key attributes for arbitrary elements are `id` and `name`. See
        `introduction` for details about locating elements.

        New in AppiumLibrary 1.4.5
        """
        if self._element_find(locator, True, True).is_displayed():
            self.log_source(loglevel)
            raise AssertionError("Element '%s' should not be visible "
                                 "but did" % locator)
</code>```

Method 2

If you don't want to expand the existing library, you could just use the combination of existing keywords as follows:

```<code>${isVisible}=  Run Keyword And Return Status   Element Should Be Visible   'someElementSelector'

Should Be Equal  ${isVisible}    ${FALSE}
</code>```

Body:
Thanks to Verv for the guidelines. I tried both approaches that he suggested, and both seem to be super easy. For future reference, I'm explaining both methods here.

Method 1:

Under AppiumeLibrary/keywords directory, there's a file called _element.py, which defines the Element Should Be Visible keyword. I was able to clone it to create the new keyword I was looking for.

Below is the code snippet that defines Element Should Be Visible

    def element_should_be_visible(self, locator, loglevel='INFO'):
        """Verifies that element identified with locator is visible.

        Key attributes for arbitrary elements are `id` and `name`. See
        `introduction` for details about locating elements.

        New in AppiumLibrary 1.4.5
        """
        if not self._element_find(locator, True, True).is_displayed():
            self.log_source(loglevel)
            raise AssertionError("Element '%s' should be visible "
                             "but did not" % locator)

Next to the above code snippet, you can add the following code snippet to define a new keyword Element Should Not Be Visible

    def element_should_not_be_visible(self, locator, loglevel='INFO'):
        """Verifies that element identified with locator is visible.

        Key attributes for arbitrary elements are `id` and `name`. See
        `introduction` for details about locating elements.

        New in AppiumLibrary 1.4.5
        """
        if self._element_find(locator, True, True).is_displayed():
            self.log_source(loglevel)
            raise AssertionError("Element '%s' should not be visible "
                                 "but did" % locator)

Method 2

If you don't want to expand the existing library, you could just use the combination of existing keywords as follows:

${isVisible}=  Run Keyword And Return Status   Element Should Be Visible   'someElementSelector'

Should Be Equal  ${isVisible}    ${FALSE}


问:
How to define a Header to all request using Retrofit?
I'm looking for a solution to define a unique Header to use in all requests. Today I use @Header to each request did pass like parameter but I want define only header that works in all requests without to need pass like a parameter, for example fixing this Header on my requests @GET and @POST

Today I use this. Note that each request @GET I need define Header as parameter.

```<code>//interface
@GET("/json.php")
void getUsuarioLogin(
                        @Header("Authorization") String token,
                        @QueryMap Map<String, String> params,
                        Callback<JsonElement> response
                    );

//interface
@GET("/json.php")
void addUsuario(
                        @Header("Authorization") String token,
                        @QueryMap Map<String, String> params,
                        Callback<JsonElement> response
                    );

//using
public void getUsuarioLogin(){
        Map<String, String> params = new HashMap<String, String>();
        params.put("email", "me@mydomain.com");
        params.put("senha", ConvertStringToMD5.getMD5("mypassword"));

        RestAdapter adapter = new RestAdapter.Builder()
                                .setLogLevel(RestAdapter.LogLevel.FULL)
                                .setEndpoint(WebServiceURL.getBaseWebServiceURL())
                                .build();

        UsuarioListener listener = adapter.create(UsuarioListener.class);
        listener.getUsuarioLogin(
                                      //header
                                      "Basic " + BasicAuthenticationRest.getBasicAuthentication(),
                                      params,
                                      new Callback<JsonElement>() {
            @Override
            public void success(JsonElement arg0, Response arg1) {
                Log.i("Usuario:", arg0.toString() + "");
            }

            @Override
            public void failure(RetrofitError arg0) {
                Log.e("ERROR:", arg0.getLocalizedMessage());

            }
        });

    }

//using
    public void addUsuario(){
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", "Fernando");
            params.put("lastName", "Paiva");

            RestAdapter adapter = new RestAdapter.Builder()
                                    .setLogLevel(RestAdapter.LogLevel.FULL)
                                    .setEndpoint(WebServiceURL.getBaseWebServiceURL())
                                    .build();

            UsuarioListener listener = adapter.create(UsuarioListener.class);
            listener.addUsuario(
                                          //header
                                          "Basic " + BasicAuthenticationRest.getBasicAuthentication(),
                                          params,
                                          new Callback<JsonElement>() {
                @Override
                public void success(JsonElement arg0, Response arg1) {
                    Log.i("Usuario:", arg0.toString() + "");
                }

                @Override
                public void failure(RetrofitError arg0) {
                    Log.e("ERROR:", arg0.getLocalizedMessage());

                }
            });

        }
</code>```

答:
As the other answers have described, you need a RequestInterceptor. Luckily, this interface has a single method, so Java 8 and above will treat it as a functional interface and let you implement it with a lambda. Simple!

For example, if you're wrapping a specific API and need a header for each endpoint, you might do this when you build your adapter:

```<code>RestAdapter whatever = new RestAdapter.Builder().setEndpoint(endpoint)
                                                .setRequestInterceptor(r -> r.addHeader("X-Special-Vendor-Header", "2.0.0"))
                                                .build()
</code>```

Body:
I'm looking for a solution to define a unique Header to use in all requests. Today I use @Header to each request did pass like parameter but I want define only header that works in all requests without to need pass like a parameter, for example fixing this Header on my requests @GET and @POST

Today I use this. Note that each request @GET I need define Header as parameter.

//interface
@GET("/json.php")
void getUsuarioLogin(
                        @Header("Authorization") String token,
                        @QueryMap Map<String, String> params,
                        Callback<JsonElement> response
                    );

//interface
@GET("/json.php")
void addUsuario(
                        @Header("Authorization") String token,
                        @QueryMap Map<String, String> params,
                        Callback<JsonElement> response
                    );

//using
public void getUsuarioLogin(){
        Map<String, String> params = new HashMap<String, String>();
        params.put("email", "me@mydomain.com");
        params.put("senha", ConvertStringToMD5.getMD5("mypassword"));

        RestAdapter adapter = new RestAdapter.Builder()
                                .setLogLevel(RestAdapter.LogLevel.FULL)
                                .setEndpoint(WebServiceURL.getBaseWebServiceURL())
                                .build();

        UsuarioListener listener = adapter.create(UsuarioListener.class);
        listener.getUsuarioLogin(
                                      //header
                                      "Basic " + BasicAuthenticationRest.getBasicAuthentication(),
                                      params,
                                      new Callback<JsonElement>() {
            @Override
            public void success(JsonElement arg0, Response arg1) {
                Log.i("Usuario:", arg0.toString() + "");
            }

            @Override
            public void failure(RetrofitError arg0) {
                Log.e("ERROR:", arg0.getLocalizedMessage());

            }
        });

    }

//using
    public void addUsuario(){
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", "Fernando");
            params.put("lastName", "Paiva");

            RestAdapter adapter = new RestAdapter.Builder()
                                    .setLogLevel(RestAdapter.LogLevel.FULL)
                                    .setEndpoint(WebServiceURL.getBaseWebServiceURL())
                                    .build();

            UsuarioListener listener = adapter.create(UsuarioListener.class);
            listener.addUsuario(
                                          //header
                                          "Basic " + BasicAuthenticationRest.getBasicAuthentication(),
                                          params,
                                          new Callback<JsonElement>() {
                @Override
                public void success(JsonElement arg0, Response arg1) {
                    Log.i("Usuario:", arg0.toString() + "");
                }

                @Override
                public void failure(RetrofitError arg0) {
                    Log.e("ERROR:", arg0.getLocalizedMessage());

                }
            });

        }

Body:
As the other answers have described, you need a RequestInterceptor. Luckily, this interface has a single method, so Java 8 and above will treat it as a functional interface and let you implement it with a lambda. Simple!

For example, if you're wrapping a specific API and need a header for each endpoint, you might do this when you build your adapter:

RestAdapter whatever = new RestAdapter.Builder().setEndpoint(endpoint)
                                                .setRequestInterceptor(r -> r.addHeader("X-Special-Vendor-Header", "2.0.0"))
                                                .build()


问:
JavaFX ListView color the text
I have this simple code:

```<code>public class ControllerList {
@FXML ListView listView;
@FXML Button btnSend;
@FXML ColorPicker colorPicker;
@FXML TextField textField;

  public void clickSend() {
      listView.getItems().add(textField.getText());
  }
}
</code>```

I need to color the text added to the ListView using the color picker.
How can i do that?

答:
Create a class to encapsulate the text and color:

```<code>public class ColoredText {

    private final String text ;
    private final Color color ;

    public ColoredText(String text, Color color) {
        this.text = text ;
        this.color = color ;
    }

    public String getText() {
        return text ;
    }

    public Color getColor() {
        return color ;
    }
}
</code>```

and then use a ListView<ColoredText> with a cell factory:

```<code>public class ControllerList {

    @FXML ListView<ColoredText> listView;
    @FXML Button btnSend;
    @FXML ColorPicker colorPicker;
    @FXML TextField textField;

    public void initialize() {
        listView.setCellFactory(lv -> new ListCell<ColoredText>() {
            @Override
            protected void updateItem(ColoredText item, boolean empty) {
                super.updateItem(item, empty);
                if (item == null) {
                    setText(null);
                    setTextFill(null);
                } else {
                    setText(item.getText());
                    setTextFill(item.getColor());
                }
            }
        });
    }

    public void clickSend() {
        listView.getItems().add(new ColoredText(textField.getText(), colorPicker.getValue()));
    }

}
</code>```

Title: JavaFX ListView color the text

Body:
I have this simple code:

public class ControllerList {
@FXML ListView listView;
@FXML Button btnSend;
@FXML ColorPicker colorPicker;
@FXML TextField textField;

  public void clickSend() {
      listView.getItems().add(textField.getText());
  }
}

I need to color the text added to the ListView using the color picker.
How can i do that?

Body:
Create a class to encapsulate the text and color:

public class ColoredText {

    private final String text ;
    private final Color color ;

    public ColoredText(String text, Color color) {
        this.text = text ;
        this.color = color ;
    }

    public String getText() {
        return text ;
    }

    public Color getColor() {
        return color ;
    }
}

and then use a ListView<ColoredText> with a cell factory:

public class ControllerList {

    @FXML ListView<ColoredText> listView;
    @FXML Button btnSend;
    @FXML ColorPicker colorPicker;
    @FXML TextField textField;

    public void initialize() {
        listView.setCellFactory(lv -> new ListCell<ColoredText>() {
            @Override
            protected void updateItem(ColoredText item, boolean empty) {
                super.updateItem(item, empty);
                if (item == null) {
                    setText(null);
                    setTextFill(null);
                } else {
                    setText(item.getText());
                    setTextFill(item.getColor());
                }
            }
        });
    }

    public void clickSend() {
        listView.getItems().add(new ColoredText(textField.getText(), colorPicker.getValue()));
    }

}


问:
ERROR at line 2: PL/SQL: Statement ignored; Error(2,17): PL/SQL: ORA-00913: too many values
I am having this error on oracle SQL developer

```<code>create table loan_audit (
employee_id number not null,
tool_no number not null,
tool_out_date date not null,
due_date date not null);
</code>```

This is the trigger i created

```<code>    CREATE OR REPLACE TRIGGER loan_audit_trigger
AFTER INSERT OR UPDATE OR DELETE
ON loan_02
FOR EACH ROW
BEGIN
  IF INSERTING THEN
    INSERT INTO loan_audit VALUES
    (:new.employee_id, :new.tool_no, :new.tool_out_date, :new.due_date, 'INSERTED', SYSDATE);
  ELSIF UPDATING THEN
    INSERT INTO loan_audit VALUES
    (:old.employee_id,  :old.tool_no,  :old.tool_out_date, :old.due_date, 'UPDATED', SYSDATE);
  ELSIF DELETING THEN
    INSERT INTO loan_audit VALUES
    (:old.employee_id,  :old.tool_no, :old.tool_out_date, :old.due_date, 'DELETED', SYSDATE);
  END IF;
END;
</code>```

I am getting these error

```<code>Error(2,5): PL/SQL: SQL Statement ignored
Error(2,17): PL/SQL: ORA-00913: too many values
Error(5,5): PL/SQL: SQL Statement ignored
Error(5,17): PL/SQL: ORA-00913: too many values
Error(8,5): PL/SQL: SQL Statement ignored
Error(8,17): PL/SQL: ORA-00913: too many values
</code>```

what am i doing wrong? I been trying to get this to work but keep getting this error! Thanks for all the help in advance.

答:
List the columns explicit in any insert:

```<code>  IF INSERTING THEN
    INSERT INTO loan_audit (employee_id, tool_no, tool_out_date, due_date)
        VALUES ( :new.tool_no, :new.tool_out_date, :new.due_date );
  ELSIF UPDATING THEN
    INSERT INTO loan_audit (employee_id, tool_no, tool_out_date, due_date)
       VALUES (  :old.tool_no,  :old.tool_out_date, :old.due_date );
  ELSIF DELETING THEN
    INSERT INTO loan_audit (employee_id, tool_no, tool_out_date, due_date)
        VALUES (  :old.tool_no, :old.tool_out_date, :old.due_date );
  END IF;
</code>```

Oh, look.  The table has four columns, but you are inserting 5.  You need to decide if you want four or five and declare the table appropriately.

It also looks like you don't have an employee_id . . . perhaps you intend:

```<code>  IF INSERTING THEN
    INSERT INTO loan_audit (tool_no, tool_out_date, due_date)
        VALUES ( :new.tool_no, :new.tool_out_date, :new.due_date, 'INSERTED', SYSDATE);
  ELSIF UPDATING THEN
    INSERT INTO loan_audit (tool_no, tool_out_date, due_date)
       VALUES (  :old.tool_no,  :old.tool_out_date, :old.due_date, 'UPDATED', SYSDATE);
  ELSIF DELETING THEN
    INSERT INTO loan_audit (tool_no, tool_out_date, due_date)
        VALUES (  :old.tool_no, :old.tool_out_date, :old.due_date, 'DELETED', SYSDATE);
  END IF;
</code>```

Body:
I am having this error on oracle SQL developer

create table loan_audit (
employee_id number not null,
tool_no number not null,
tool_out_date date not null,
due_date date not null);

This is the trigger i created

    CREATE OR REPLACE TRIGGER loan_audit_trigger
AFTER INSERT OR UPDATE OR DELETE
ON loan_02
FOR EACH ROW
BEGIN
  IF INSERTING THEN
    INSERT INTO loan_audit VALUES
    (:new.employee_id, :new.tool_no, :new.tool_out_date, :new.due_date, 'INSERTED', SYSDATE);
  ELSIF UPDATING THEN
    INSERT INTO loan_audit VALUES
    (:old.employee_id,  :old.tool_no,  :old.tool_out_date, :old.due_date, 'UPDATED', SYSDATE);
  ELSIF DELETING THEN
    INSERT INTO loan_audit VALUES
    (:old.employee_id,  :old.tool_no, :old.tool_out_date, :old.due_date, 'DELETED', SYSDATE);
  END IF;
END;

I am getting these error

Error(2,5): PL/SQL: SQL Statement ignored
Error(2,17): PL/SQL: ORA-00913: too many values
Error(5,5): PL/SQL: SQL Statement ignored
Error(5,17): PL/SQL: ORA-00913: too many values
Error(8,5): PL/SQL: SQL Statement ignored
Error(8,17): PL/SQL: ORA-00913: too many values

what am i doing wrong? I been trying to get this to work but keep getting this error! Thanks for all the help in advance.

Body:
List the columns explicit in any insert:

  IF INSERTING THEN
    INSERT INTO loan_audit (employee_id, tool_no, tool_out_date, due_date)
        VALUES ( :new.tool_no, :new.tool_out_date, :new.due_date );
  ELSIF UPDATING THEN
    INSERT INTO loan_audit (employee_id, tool_no, tool_out_date, due_date)
       VALUES (  :old.tool_no,  :old.tool_out_date, :old.due_date );
  ELSIF DELETING THEN
    INSERT INTO loan_audit (employee_id, tool_no, tool_out_date, due_date)
        VALUES (  :old.tool_no, :old.tool_out_date, :old.due_date );
  END IF;

Oh, look.  The table has four columns, but you are inserting 5.  You need to decide if you want four or five and declare the table appropriately.

It also looks like you don't have an employee_id . . . perhaps you intend:

  IF INSERTING THEN
    INSERT INTO loan_audit (tool_no, tool_out_date, due_date)
        VALUES ( :new.tool_no, :new.tool_out_date, :new.due_date, 'INSERTED', SYSDATE);
  ELSIF UPDATING THEN
    INSERT INTO loan_audit (tool_no, tool_out_date, due_date)
       VALUES (  :old.tool_no,  :old.tool_out_date, :old.due_date, 'UPDATED', SYSDATE);
  ELSIF DELETING THEN
    INSERT INTO loan_audit (tool_no, tool_out_date, due_date)
        VALUES (  :old.tool_no, :old.tool_out_date, :old.due_date, 'DELETED', SYSDATE);
  END IF;


问:
How to create a Bundle in a Unit test
I want to test a method that deals with Bundles. I'm unable to create a (non-null) Bundle object in the test environment, though.

Given the following code:

```<code>Bundle bundle = new Bundle();
bundle.putString("key", "value");
boolean containsKey = bundle.containsKey("key");
</code>```

containsKey is true if the code is executed in the application context, but false if executed in a unit test.

I can't figure out why that's the case and how to create a Bundle for my tests.

答:
I ended up using Mockito:

```<code>Bundle extras = mock(Bundle.class);
</code>```

And since I didn't need to test a lot of parameters that passed within bundle, i mocked calls to them like this:

```<code>private void stubParameterNameExtras(Bundle extras, boolean value) {
    when(extras.getBoolean(KEY, false)).thenReturn(value);
}
</code>```

Suggestion to the team I made was to replace Bundle usage with Java analog.

Title: How to create a Bundle in a Unit test

Body:
I want to test a method that deals with Bundles. I'm unable to create a (non-null) Bundle object in the test environment, though.

Given the following code:

Bundle bundle = new Bundle();
bundle.putString("key", "value");
boolean containsKey = bundle.containsKey("key");

containsKey is true if the code is executed in the application context, but false if executed in a unit test.

I can't figure out why that's the case and how to create a Bundle for my tests.

Body:
I ended up using Mockito:

Bundle extras = mock(Bundle.class);

And since I didn't need to test a lot of parameters that passed within bundle, i mocked calls to them like this:

private void stubParameterNameExtras(Bundle extras, boolean value) {
    when(extras.getBoolean(KEY, false)).thenReturn(value);
}

Suggestion to the team I made was to replace Bundle usage with Java analog.


问:
Behind the scenes activity on python prompt load-up
What happens behind the scenes when we invoke the python prompt?

I am more interested in understanding how do the methods/functions like print, import and the likes load up in the interpreter?

EDIT: Some clarification on my question:

When we type python on our unix prompt/windows console and Hit enter, what are the libraries that get loaded. My specific interest is as to how the keywords like print and import are made available to the user.

答:
Like you , I am very interested by the underlying mechanisms of Python.
I think you'll love this series:
http://tech.blog.aknin.name/category/my-projects/pythons-innards/</p>

ContentLicense: CC BY-SA 2.5


问:
dyld: Library not loaded: @rpath with iOS8
I'm creating an iOS framework with Xcode6 and iOS8. When I link this with an iOS app and try running it on the device I get this error

```<code>dyld: Library not loaded: @rpath/FrameworkName.framework/FrameworkName
  Referenced from: /private/var/mobile/Containers/Bundle/Application/0F2C2461-A68B-4ABA-A604-B88E6E9D1BB1/AppName.app/AppName
  Reason: image not found
</code>```

The 'Runpath Search Paths' build setting for the framework is set by default to

```<code>'@executable_path/Frameworks', '@loader_path/Frameworks'
</code>```

I could not find any documentation related to this. This was something new introduced with Xcode6 and I would expect it to just work by simply including the framework into any app that needs it.

答:
I also had same kind of problem where I was not able to launch the app & app was crashing with above message :

dyld: Library not loaded: @rpath/FrameworkName.framework/FrameworkName
  Referenced from: /private/var/mobile/Containers/Bundle/Application/xxxxxxxxxxxxxxxxxxx

Reason: image not found

Here is my approach that helped me to resolve this error:

1.Please delete your app from device, Clean the build and and rebuild and run on the device.

2.If above steps does not help you, then please check for below settings :

From "TARGET">"Build Settings">"Runpath Search Paths" & then check for values "$(inherited)" & "@executable_path/Frameworks", Feel free to add incase they don't exist.

Build your app and run it on device

Body:
I'm creating an iOS framework with Xcode6 and iOS8. When I link this with an iOS app and try running it on the device I get this error

dyld: Library not loaded: @rpath/FrameworkName.framework/FrameworkName
  Referenced from: /private/var/mobile/Containers/Bundle/Application/0F2C2461-A68B-4ABA-A604-B88E6E9D1BB1/AppName.app/AppName
  Reason: image not found

The 'Runpath Search Paths' build setting for the framework is set by default to

'@executable_path/Frameworks', '@loader_path/Frameworks'

I could not find any documentation related to this. This was something new introduced with Xcode6 and I would expect it to just work by simply including the framework into any app that needs it.


问:
What type of correlation should I choose in my BizTalk service?

Task: BizTalk service should get message from client (Receive_1) and send it to remote 1cServise (Send_1).
1cServise accepts messages, with such a structure:

empty POST request to address https://1Caddress.1cws

with Header - Content-type: text/xml

and Body - XML (plain text):

```<code><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                <soap:Body>
                    <m:Get xmlns:m="http://www.gis.com.ua">
                    </m:Get>
                </soap:Body>
</soap:Envelope>
</code>```

Then 1cService returns message to BizTalk (Receive_2), and than - to client (Send_2).

My project will not compile until I add Correlation Property to messages Send_1 and Receive_2.

But what type of correlation property should I choose for sending right request to 1cService?
Or even, how to send correct message to 1cServise to get response?

答:
I think that in your case you have to use a solicit-response send port:

Because seems that in your case is invoke a service, that returns a response. You use a correlation, when you have some property or data to correlate the request and the response when the transport used is not synchronous, for example.

Body:
Task: BizTalk service should get message from client (Receive_1) and send it to remote 1cServise (Send_1).
1cServise accepts messages, with such a structure:

empty POST request to address https://1Caddress.1cws

with Header - Content-type: text/xml

and Body - XML (plain text):

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                <soap:Body>
                    <m:Get xmlns:m="http://www.gis.com.ua">
                    </m:Get>
                </soap:Body>
</soap:Envelope>

Then 1cService returns message to BizTalk (Receive_2), and than - to client (Send_2).

My project will not compile until I add Correlation Property to messages Send_1 and Receive_2.

But what type of correlation property should I choose for sending right request to 1cService?
Or even, how to send correct message to 1cServise to get response?


问:
How to programmatically detect an application has crashed in Windows?
I am running a Python script that launches a number of apps. I need a way to detect if the app that's launched has crashed. Some apps have internal crash handling

How can I detect the crash?

答:
If they have internal crash handling, it's not possible to detect. The application will handle the error and exit normally. You can't even detect this if you would attach yourself as a debugger.

The reason is exception dispatching (MSDN):

the debugger gets informed about an exception. This is called the first chance exception. However, this might be "normal", e.g. FileNotFound, which is expected by the application.

Windows is looking for someone who wants to handle the exception. This can be the except block of a Python application, a catch block in C# or C++ or even a general "unhandled exception handler".

If nobody wanted to handle the application, the debugger gets informed again. This time, the exception is marked as a second chance exception. This means that the application will crash next.

You're looking to become informed as part of step 3, however, the application has already stopped the process in step 2.

ContentLicense: CC BY-SA 4.0


问:
Java connect to FileMaker pro 16
I try to establish the connection between Eclipse and FileMaker - I want to access the database there, but I get this error message

```<code>(com.filemaker.jdbc.FMSQLException: [FileMaker][FileMaker JDBC] (802): Unable to open file
).
</code>```

According to official document (https://fmhelp.filemaker.com/docs/16/en/fm16_odbc_jdbc_guide.pdf), I believe I import Jdbc.jar and fmjdbc.jar into my java path, as I do this when I connect to MySQL.

Here is part of my code for establishing the connection.

```<code>    Connection conn = null;
    try {

        Driver d = (Driver) Class.forName("com.filemaker.jdbc.Driver").newInstance();
        conn = DriverManager.getConnection(dbaseURL, username, password);
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

Could anyone give me some clues or hints about how to get the connection? My java version is 1.8 and I use FileMaker Pro 16.

答:
802 error means:

Unable to open file. This error can be caused by one or more of the
  following:

  • Invalid database name

  • File is closed in FileMaker Server

  • Invalid permission

If the file is definitely open, there's probably a missing permission. Enable XDBC access for the account you are using to connect.

Title: Java connect to FileMaker pro 16

Body:
I try to establish the connection between Eclipse and FileMaker - I want to access the database there, but I get this error message

(com.filemaker.jdbc.FMSQLException: [FileMaker][FileMaker JDBC] (802): Unable to open file
).

According to official document (https://fmhelp.filemaker.com/docs/16/en/fm16_odbc_jdbc_guide.pdf), I believe I import Jdbc.jar and fmjdbc.jar into my java path, as I do this when I connect to MySQL.

Here is part of my code for establishing the connection.

    Connection conn = null;
    try {

        Driver d = (Driver) Class.forName("com.filemaker.jdbc.Driver").newInstance();
        conn = DriverManager.getConnection(dbaseURL, username, password);
    } catch (Exception e) {
        e.printStackTrace();
    }

Could anyone give me some clues or hints about how to get the connection? My java version is 1.8 and I use FileMaker Pro 16.


问:
Button for a webview android
i was wondering is it possible to add a button below a webview such that on clicking it, it should flip and give another webpage and so on, maybe a back button to return to the previous webpage, Can we make such changes in the layout> if so how? Coz whenever I wrote TabHost program for webview, upon selecting the tab,it would fill the entire page hiding the tabs,

I want to create a combination of ViewFlipper, WebView and Button

答:
Make a layout with a flipper.
In your code, try

WebView myWebView1 = ...;

WebView myWebView2 = ...;

Flipper myFlipper = (Flipper)(findViewById(R.id_myflipper);

myFlipper.addView(myWevView1);

myFlipper.addView(myWebView2)

when you press your button, change the current view in the flipper by

```<code>myFlipper.setDisplayedChild(flipperID);
</code>```

Where flipperID is the index of the view you want to show.

Title: Button for a webview android

Body:
Make a layout with a flipper.
In your code, try

WebView myWebView1 = ...;

WebView myWebView2 = ...;

Flipper myFlipper = (Flipper)(findViewById(R.id_myflipper);

myFlipper.addView(myWevView1);

myFlipper.addView(myWebView2)

when you press your button, change the current view in the flipper by

myFlipper.setDisplayedChild(flipperID);

Where flipperID is the index of the view you want to show.


问:
How to test REST API google maps?
I want to test the google maps API so I can see the resources that the API have, i found the SoapUI REadyAPI, but I'm still confused.
Is there a way to make this REST API calls (gets) from console so i can see the JSON of Google maps?

Thanks in advance

答: chrome has an extension called rest client where you could test from and see the JSON response. You can also use postman to test. https://www.getpostman.com/ . Both will work very easily with google maps api.</p>

Title: How to test REST API google maps?


问:
setRecycledViewPool method in RecyclerView
I am trying to understand what the setRecycledViewPool method actually does along with the RecyclerView in the following line of code where mrecyclerView is a RecyclerView object:

```<code>mrecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
</code>```

I read the Android documentation link and I still don't understand what it does clearly. Can someone explain to me its use and when to use it?

答:
setRecycledViewPool(...) can be useful when we have a nested RecyclerView. See this blog post for details. A short description of the same link is added here.

Consider a case where you have a nested RecyclerViews and inner RecycleViews share the same view structure. RecycledViewPool provides a seemless way to share views between these inner (nested) RecyclerViews.

An example of such case could be seen in the following image:

As you can see the types of views for both lists are same.

Body:
I am trying to understand what the setRecycledViewPool method actually does along with the RecyclerView in the following line of code where mrecyclerView is a RecyclerView object:

mrecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());

I read the Android documentation link and I still don't understand what it does clearly. Can someone explain to me its use and when to use it?


问:
Navigate between Screens
In my application,I have complex navigation.

I have Shopping Details .Which is View Controller of Tab bar controller.

When I select the any Store Name from Shopping Details View Controller .It will pop to a Shopping List View Controller which is embed in Navigation Controller.

When Select the Edit Button from Shopping List View Controller .It will pop to another View controller which ADD Screen. It is also embed in Navigation Controller

When I click save from Add Screen .It will go to the Shopping List View Controller

When I click Done button from the Shopping List View Controller  .I have to navigate to  Shopping Details View Controller of Tab bar controller.

Please provide me input. How to traverse to Tab Bar Controller ?

I have tried below Code. It is navigate to StoreDetails View Controller.Not displaying Tab Bar Items

```<code>let storeDetails = self.storyboard?.instantiateViewController(withIdentifier: "StoreDetailsController") as! StoreDetailsController
        storeDetails.managedContext = managedContext
        storeDetails.coreData = coreData
        storeDetails.back = true
self.navigationController?.pushViewController(storeDetails, animated: false)
</code>```

答: If you do self.navigationController?.dismiss(animated: true) you should be back at the viewController that's just before the first one embedded in the navigation controller, which I believe is Shipping Details(the one where you "select the any Store Name").

Title: Navigate between Screens

Body:
In my application,I have complex navigation.

I have Shopping Details .Which is View Controller of Tab bar controller.

When I select the any Store Name from Shopping Details View Controller .It will pop to a Shopping List View Controller which is embed in Navigation Controller.

When Select the Edit Button from Shopping List View Controller .It will pop to another View controller which ADD Screen. It is also embed in Navigation Controller

When I click save from Add Screen .It will go to the Shopping List View Controller

When I click Done button from the Shopping List View Controller  .I have to navigate to  Shopping Details View Controller of Tab bar controller.

Please provide me input. How to traverse to Tab Bar Controller ?

I have tried below Code. It is navigate to StoreDetails View Controller.Not displaying Tab Bar Items

let storeDetails = self.storyboard?.instantiateViewController(withIdentifier: "StoreDetailsController") as! StoreDetailsController
        storeDetails.managedContext = managedContext
        storeDetails.coreData = coreData
        storeDetails.back = true
self.navigationController?.pushViewController(storeDetails, animated: false)


问:
Tic Tac Toe checking winner in boolean method
I'm playing a TicTacToe game where the user plays the computer. The user is always X and the computer is O. I have my code written to check every row, column, and diagonal to see if the user or computer wins. If neither then it just prints false. I would like the game to print out if the user win Human player won" or if the computer wins "Computer won". I just don't know how to add it to the boolean method.</p>

```<code>public static boolean checkWin()
{
    //checks for human win
    if ("X".equals(board[0][0]) && "X".equals(board[0][1]) && "X".equals(board[0][2]))
        return true;
    else if ("X".equals(board[1][0]) && "X".equals(board[1][1]) && "X".equals(board[1][2]))
        return true;
    else if ("X".equals(board[2][0]) && "X".equals(board[2][1]) && "X".equals(board[2][2]))
        return true;
    else if ("X".equals(board[0][0]) && "X".equals(board[1][0]) && "X".equals(board[2][0]))
        return true;
    else if ("X".equals(board[0][1]) && "X".equals(board[1][1]) && "X".equals(board[2][1]))
        return true;
    else if ("X".equals(board[0][2]) && "X".equals(board[1][2]) && "X".equals(board[2][2]))
        return true;
    else if ("X".equals(board[0][0]) && "X".equals(board[1][1]) && "X".equals(board[2][2]))
        return true;
    else if ("X".equals(board[0][2]) && "X".equals(board[1][1]) && "X".equals(board[2][0]))
        return true;
    //checks if computer has won
    else if ("O".equals(board[0][0]) && "O".equals(board[0][1]) && "O".equals(board[0][2]))
        return true;
    else if ("O".equals(board[1][0]) && "O".equals(board[1][1]) && "O".equals(board[1][2]))
        return true;
    else if ("O".equals(board[2][0]) && "O".equals(board[2][1]) && "O".equals(board[2][2]))
        return true;
    else if ("O".equals(board[0][0]) && "O".equals(board[1][0]) && "O".equals(board[2][0]))
        return true;
    else if ("O".equals(board[0][1]) && "O".equals(board[1][1]) && "O".equals(board[2][1]))
        return true;
    else if ("O".equals(board[0][2]) && "O".equals(board[1][2]) && "O".equals(board[2][2]))
        return true;
    else if ("O".equals(board[0][0]) && "O".equals(board[1][1]) && "O".equals(board[2][2]))
        return true;
    else if ("O".equals(board[0][2]) && "O".equals(board[1][1]) && "O".equals(board[2][0]))
        return true;
    else
        //it's a tie
        return false;
}
</code>```

答: The general rule of thumb is that each method should do one thing and do it well. In this case, checkWin() does exactly what its name implies: it checks if the human or computer won. If you add code to print a message, then it should real then it should be called checkWinAndPrintWinner(). Now it is obvious that you are trying to do two things in the function. Instead, you should write another method named printWinner() which calls checkWin() and then prints the appropriate message.

Body:
I'm playing a TicTacToe game where the user plays the computer. The user is always X and the computer is O. I have my code written to check every row, column, and diagonal to see if the user or computer wins. If neither then it just prints false. I would like the game to print out if the user win Human player won" or if the computer wins "Computer won". I just don't know how to add it to the boolean method.

public static boolean checkWin()
{
    //checks for human win
    if ("X".equals(board[0][0]) && "X".equals(board[0][1]) && "X".equals(board[0][2]))
        return true;
    else if ("X".equals(board[1][0]) && "X".equals(board[1][1]) && "X".equals(board[1][2]))
        return true;
    else if ("X".equals(board[2][0]) && "X".equals(board[2][1]) && "X".equals(board[2][2]))
        return true;
    else if ("X".equals(board[0][0]) && "X".equals(board[1][0]) && "X".equals(board[2][0]))
        return true;
    else if ("X".equals(board[0][1]) && "X".equals(board[1][1]) && "X".equals(board[2][1]))
        return true;
    else if ("X".equals(board[0][2]) && "X".equals(board[1][2]) && "X".equals(board[2][2]))
        return true;
    else if ("X".equals(board[0][0]) && "X".equals(board[1][1]) && "X".equals(board[2][2]))
        return true;
    else if ("X".equals(board[0][2]) && "X".equals(board[1][1]) && "X".equals(board[2][0]))
        return true;
    //checks if computer has won
    else if ("O".equals(board[0][0]) && "O".equals(board[0][1]) && "O".equals(board[0][2]))
        return true;
    else if ("O".equals(board[1][0]) && "O".equals(board[1][1]) && "O".equals(board[1][2]))
        return true;
    else if ("O".equals(board[2][0]) && "O".equals(board[2][1]) && "O".equals(board[2][2]))
        return true;
    else if ("O".equals(board[0][0]) && "O".equals(board[1][0]) && "O".equals(board[2][0]))
        return true;
    else if ("O".equals(board[0][1]) && "O".equals(board[1][1]) && "O".equals(board[2][1]))
        return true;
    else if ("O".equals(board[0][2]) && "O".equals(board[1][2]) && "O".equals(board[2][2]))
        return true;
    else if ("O".equals(board[0][0]) && "O".equals(board[1][1]) && "O".equals(board[2][2]))
        return true;
    else if ("O".equals(board[0][2]) && "O".equals(board[1][1]) && "O".equals(board[2][0]))
        return true;
    else
        //it's a tie
        return false;
}


问:
Service Fabric and Application Insights Performance Counters
Where can I find a list of performance counter names to be used with a Service Fabric cluster?  There is a list published here, but I would need the actual exact names to be used in the cluster's ARM template.  Currently I have the following configuration in the template :

```<code>"WadCfg": {
        "DiagnosticMonitorConfiguration": {
          "overallQuotaInMB": "1000",
          "sinks": "applicationInsights",
          "DiagnosticInfrastructureLogs": {},
          "PerformanceCounters": {
            "PerformanceCounterConfiguration": [
              {
                "counterSpecifier": "\\Processor(_Total)\\% Processor Time",
                "sampleRate": "PT3M"
              },
              {
                "counterSpecifier": "\\Memory\\Available MBytes",
                "sampleRate": "PT3M"
              }
            ]
          }
</code>```

But only the "Memory\Available MBytes" actually shows up in Application Insights.

答:
Those counters are the actual windows performance counters. So you just need to look for them. Some examples:

http://techgenix.com/Key-Performance-Monitor-Counters/

http://www.appadmintools.com/documents/windows-performance-counters-explained/

Judging by all this information, the performance counters all follow the same pattern:

```<code>first column\second column
\\Processor(_Total)\\% Processor Time
\\Memory\\Available MBytes
\\Network Interface(*)\\Bytes Received/sec
...
</code>```

You might be able to find some more counters by running typeperf directly on the service fabric VM and capturing the output. You can also run it locally to get an idea of what is possible.

http://defaultreasoning.com/2009/06/25/list-all-performance-counters-on-a-windows-computer-and-export-it-to-a-file/

```<code> C:>TypePerf.exe –q > counters.txt
</code>```

Body:
Where can I find a list of performance counter names to be used with a Service Fabric cluster?  There is a list published here, but I would need the actual exact names to be used in the cluster's ARM template.  Currently I have the following configuration in the template :

"WadCfg": {
        "DiagnosticMonitorConfiguration": {
          "overallQuotaInMB": "1000",
          "sinks": "applicationInsights",
          "DiagnosticInfrastructureLogs": {},
          "PerformanceCounters": {
            "PerformanceCounterConfiguration": [
              {
                "counterSpecifier": "\\Processor(_Total)\\% Processor Time",
                "sampleRate": "PT3M"
              },
              {
                "counterSpecifier": "\\Memory\\Available MBytes",
                "sampleRate": "PT3M"
              }
            ]
          }

But only the "Memory\Available MBytes" actually shows up in Application Insights.

Body:
Those counters are the actual windows performance counters. So you just need to look for them. Some examples:

http://techgenix.com/Key-Performance-Monitor-Counters/

http://www.appadmintools.com/documents/windows-performance-counters-explained/

Judging by all this information, the performance counters all follow the same pattern:

first column\second column
\\Processor(_Total)\\% Processor Time
\\Memory\\Available MBytes
\\Network Interface(*)\\Bytes Received/sec
...

You might be able to find some more counters by running typeperf directly on the service fabric VM and capturing the output. You can also run it locally to get an idea of what is possible.

http://defaultreasoning.com/2009/06/25/list-all-performance-counters-on-a-windows-computer-and-export-it-to-a-file/

 C:>TypePerf.exe –q > counters.txt