问:
text-overflow in span element not cutting texta outside element width
I'm trying to make a div with 3 spans inside where the middle one should "compress", ie cut the extra text when the size of the div is small.

The result I'm looking for is

```<code>A Very lon... A
          ^ here it should get cut with "text-overflow: ellipsis;"
</code>```

Somehow the text-overflow: ellipsis; is not being applied to the span.

Any idea what I am missing?

Tried with width, display, overflow and nothing seems to work... tested both Chrome and Firefox.

div {
  border-radius: 5px;
  border: 1px solid #333;
  padding: 10px 20px;
  width: 100px;
}

div span {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

#long-text {
  width: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span>A</span>
  <span id="long-text">Very long text here....</span>
  <span>A</span>
</div></code>```

答:
span is an inline element. It has no width or height.so try display:inline-block for the span element.Then the text-overflow: ellipsis; will work

div {
  border-radius: 5px;
  border: 1px solid #333;
  padding: 10px 20px;
  width: 100px;
}

div span {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  display:inline-block;
}

#long-text {
  width: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
    <span>A</span>
    <span id="long-text">Very long text here....</span>
    <span>A</span>
</div></code>```

Body:
I'm trying to make a div with 3 spans inside where the middle one should "compress", ie cut the extra text when the size of the div is small.

The result I'm looking for is

A Very lon... A
          ^ here it should get cut with "text-overflow: ellipsis;"

Somehow the text-overflow: ellipsis; is not being applied to the span.

Any idea what I am missing?

Tried with width, display, overflow and nothing seems to work... tested both Chrome and Firefox.

div {
  border-radius: 5px;
  border: 1px solid #333;
  padding: 10px 20px;
  width: 100px;
}

div span {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

#long-text {
  width: 20px;
}

  A
  Very long text here....
  A

Body:
span is an inline element. It has no width or height.so try display:inline-block for the span element.Then the text-overflow: ellipsis; will work

div {
  border-radius: 5px;
  border: 1px solid #333;
  padding: 10px 20px;
  width: 100px;
}

div span {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  display:inline-block;
}

#long-text {
  width: 50px;
}

<div>
    <span>A</span>
    <span id="long-text">Very long text here....</span>
    <span>A</span>
</div>


来源: stackexchange

问:
JQuery - Why event.target doesn't work in this situation?
just wondering why when i click inside the container the alert popups despite the if statement for it to not show on click.

Also how would I test for the children inside?

https://jsfiddle.net/w8fd3m67/

$(window).on("click", function(event) {
  var container = $("#container");
  if ((event.target) !== container) {
    alert("clicked outside");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: 600px;
}

#container {
  padding: 2rem;
  background: grey;
}</code>```

```

Cheers

答:
You should use .is()

```<code>if($(event.target).is(container))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
just wondering why when i click inside the container the alert popups despite the if statement for it to not show on click.

Also how would I test for the children inside?

https://jsfiddle.net/w8fd3m67/

$(window).on("click", function(event) {
  var container = $("#container");
  if ((event.target) !== container) {
    alert("clicked outside");
  }
});

body {
  height: 600px;
}

#container {
  padding: 2rem;
  background: grey;
}

Cheers

Body:
You should use .is()

if($(event.target).is(container))


问:
Split string into array in Python
I have a string with the following structure.

string = "[abcd, abc, a, b, abc]"

I would like to convert that into an array. I keep using the split function in Python but I get spaces and the brackets on the start and the end of my new array. I tried working around it with some if statements but I keep missing letters in the end from some words.

Keep in mind that I don't know the length of the elements in the string. It could be 1, 2, 3 etc.

答:
If the values in this list are variables themselves (looks like it because they're not quoted) the easiest way to convert this string to the equivalent list is

```<code>string = eval(string)
</code>```

Caution: If the values in your list should be strings this will not work.

Title: Split string into array in Python

Body:
If the values in this list are variables themselves (looks like it because they're not quoted) the easiest way to convert this string to the equivalent list is

string = eval(string)

Caution: If the values in your list should be strings this will not work.


问:
Format date by provided time zone in java
I need to format date time in java for provided time zone. E.g. mm/dd/yyyy for US and dd/mm/yyyy for DE. I have time zone and i can get zoneId, can someone help me. Many thanks.</p>

答:
Hope this will help you,

```<code>import java.util.*;
import java.text.*;

public class DateDemo {

   public static void main(String args[]) {

        Date date1 = new Date();
        System.out.println(date1);

        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        Date date2 = new Date();
        System.out.println(date2);

        TimeZone.setDefault(TimeZone.getTimeZone("EST"));
        Date date3 = new Date();
        System.out.println(date3);

   }
}
</code>```

Output:

```<code>Tue Jun 06 14:02:51 IST 2017
Tue Jun 06 08:32:51 UTC 2017
Tue Jun 06 03:32:51 EST 2017
</code>```

Body:
Hope this will help you,

import java.util.*;
import java.text.*;

public class DateDemo {

   public static void main(String args[]) {

        Date date1 = new Date();
        System.out.println(date1);

        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        Date date2 = new Date();
        System.out.println(date2);

        TimeZone.setDefault(TimeZone.getTimeZone("EST"));
        Date date3 = new Date();
        System.out.println(date3);

   }
}

Output:

Tue Jun 06 14:02:51 IST 2017
Tue Jun 06 08:32:51 UTC 2017
Tue Jun 06 03:32:51 EST 2017


答:
I would suggest following.

```<code>[list_element.strip() for list_element in string.strip("[]").split(",")]
</code>```

First remove brackets and then split it accordingly.

Title: Split string into array in Python

Body:
I have a string with the following structure.

string = "[abcd, abc, a, b, abc]"

I would like to convert that into an array. I keep using the split function in Python but I get spaces and the brackets on the start and the end of my new array. I tried working around it with some if statements but I keep missing letters in the end from some words.

Keep in mind that I don't know the length of the elements in the string. It could be 1, 2, 3 etc.

Body:
I would suggest following.

[list_element.strip() for list_element in string.strip("[]").split(",")]

First remove brackets and then split it accordingly.


问:
SQLGrammarException: could not extract ResultSet
I want to execute following query:

@Query(value = "select * from wash_history w where w.wash_id IN \n"
        + "(select w.id from wash w where w.car_wash_id=?1) order BY w.time
?2", nativeQuery = true)
List<WashHistory> findDesc(Integer carWashId,String descOrAsc);
```

<p>But I have the following error</p>

<pre class="lang-none prettyprint-override"><code>Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
</code>```

How can I choose between desc or ac in this query?

答:
There is a way to use Pageable with native queries. Spring data will append to the end of your request " order by " if there is a Sort object in the Pageable.

```<code>List<WashHistory> findDesc(Integer carWashId,String descOrAsc, Pageable pageable);
</code>```

Body:
I want to execute following query:

@Query(value = "select * from wash_history w where w.wash_id IN \n"
        + "(select w.id from wash w where w.car_wash_id=?1) order BY w.time
?2", nativeQuery = true)
List<WashHistory> findDesc(Integer carWashId,String descOrAsc);

But I have the following error

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause

How can I choose between desc or ac in this query?

Body:
There is a way to use Pageable with native queries. Spring data will append to the end of your request " order by " if there is a Sort object in the Pageable.

List<WashHistory> findDesc(Integer carWashId,String descOrAsc, Pageable pageable);


问:
Adding fragment destroys activity
I have an Activity with a container being a FrameLayout. I need to add a fragment to that container, but doing so throws an IllegalStateException, destroying my Activity.

This is my container in the activity layout:

```<code><FrameLayout
    android:id="@+id/seeMoreContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>
</code>```

This is how I add the fragment to the activity

```<code>PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
Bundle bundle = new Bundle();
bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
placesSeeMoreFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer,
placesSeeMoreFragment).commit();
</code>```

And this is the logcat

```<code>java.lang.IllegalStateException: Activity has been destroyed
                                                                   at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1515)
                                                                   at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634)
                                                                   at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:613)
                                                                   at net.ilb.Activities.PlacesActivity.openPlaceSeeMore(PlacesActivity.java:140)
</code>```

What am I doing wrong here?

EDIT:

I add the fragment to the activity from a public method, which I call from onItemClickListener of a ListView

This is the whole method

```<code>public void openPlaceSeeMore(int poiID){
    PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
    Bundle bundle = new Bundle();
    bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
    placesSeeMoreFragment.setArguments(bundle);
    getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer, placesSeeMoreFragment).commit();
}
</code>```

And this is how the method is called

```<code>mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PlacesActivity placesActivity = new PlacesActivity();
            placesActivity.openPlaceSeeMore(poi.getId());
        }
    });
</code>```

答:
I guess you are calling this:

```<code>PlacesActivity placesActivity = new PlacesActivity();
</code>```

This is a very wrong approach to call a method declared in activity.
Which is creating new instance of your activity every time you click something on the list. Plus if you want to capture list clicks you should use an interface and not use activity objects anywhere.

Hope this helps.

Title: Adding fragment destroys activity

Body:
I have an Activity with a container being a FrameLayout. I need to add a fragment to that container, but doing so throws an IllegalStateException, destroying my Activity.

This is my container in the activity layout:

<FrameLayout
    android:id="@+id/seeMoreContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

This is how I add the fragment to the activity

PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
Bundle bundle = new Bundle();
bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
placesSeeMoreFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer,
placesSeeMoreFragment).commit();

And this is the logcat

java.lang.IllegalStateException: Activity has been destroyed
                                                                   at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1515)
                                                                   at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634)
                                                                   at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:613)
                                                                   at net.ilb.Activities.PlacesActivity.openPlaceSeeMore(PlacesActivity.java:140)

What am I doing wrong here?

EDIT:

I add the fragment to the activity from a public method, which I call from onItemClickListener of a ListView

This is the whole method

public void openPlaceSeeMore(int poiID){
    PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
    Bundle bundle = new Bundle();
    bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
    placesSeeMoreFragment.setArguments(bundle);
    getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer, placesSeeMoreFragment).commit();
}

And this is how the method is called

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PlacesActivity placesActivity = new PlacesActivity();
            placesActivity.openPlaceSeeMore(poi.getId());
        }
    });

Body:
I guess you are calling this:

PlacesActivity placesActivity = new PlacesActivity();

This is a very wrong approach to call a method declared in activity.
Which is creating new instance of your activity every time you click something on the list. Plus if you want to capture list clicks you should use an interface and not use activity objects anywhere.

Hope this helps.


问:
Erlang: Function for determining Prime Numbers, True or False
So I'm new to Erlang. I have already Googled my question quite a few times.

I'm creating a function that is supposed to take a number (N) and return true if it is a Prime number and false if it is not. I've been thinking about it for the last couple of days (like I said, I'm new to Erlang) and have done some Googling. Here's the code I have so far:

```<code> -module(isPrime).
 -export([isPrime/1]).

 isPrime(0)-> false;
 isPrime(1)-> false;
 isPrime(2)-> true;

 isPrime(N)->
  chPrime = N rem 2,
  if
    chPrime = 1 -> false; %% illegal guard expression
    true->isPrime(N-1)
end.
</code>```

It's not complete but I was just trying to run it to see how it would work but I keep getting:

isPrime.erl:11: illegal guard expression

I know if statements in Erlang have certain limitations that if statements in other programming languages do not (when I was Googling) but I'm not sure how else to write the if statement so N rem 2 is actually done.

Any suggestions as to how to rewrite my if statement to get N rem 2 working? Thank you very much.

答:
To complete the previous comment. This code will fix it for ya. After I debugged it, I realized that your if statement for chPrime must be 0 for saying false. Otherwise it will always say false.
And a guide: variables in erlang must be defined with uppercase letter at start.

```<code>    ChPrime == 0 -> false;
</code>```

If we want to use math here we can use this, too.

```<code>isPrime(N) -> isPrime(N,2).
isPrime(N,N) -> true;
isPrime(N,M)->
  ChPrime = N rem M,
  if
    ChPrime == 0 -> false;
    true -> isPrime(N,M+1)
end.
</code>```

Body:
So I'm new to Erlang. I have already Googled my question quite a few times.

I'm creating a function that is supposed to take a number (N) and return true if it is a Prime number and false if it is not. I've been thinking about it for the last couple of days (like I said, I'm new to Erlang) and have done some Googling. Here's the code I have so far:

 -module(isPrime).
 -export([isPrime/1]).

 isPrime(0)-> false;
 isPrime(1)-> false;
 isPrime(2)-> true;

 isPrime(N)->
  chPrime = N rem 2,
  if
    chPrime = 1 -> false; %% illegal guard expression
    true->isPrime(N-1)
end.

It's not complete but I was just trying to run it to see how it would work but I keep getting:

isPrime.erl:11: illegal guard expression

I know if statements in Erlang have certain limitations that if statements in other programming languages do not (when I was Googling) but I'm not sure how else to write the if statement so N rem 2 is actually done.

Any suggestions as to how to rewrite my if statement to get N rem 2 working? Thank you very much.

Body:
To complete the previous comment. This code will fix it for ya. After I debugged it, I realized that your if statement for chPrime must be 0 for saying false. Otherwise it will always say false.
And a guide: variables in erlang must be defined with uppercase letter at start.

    ChPrime == 0 -> false;

If we want to use math here we can use this, too.

isPrime(N) -> isPrime(N,2).
isPrime(N,N) -> true;
isPrime(N,M)->
  ChPrime = N rem M,
  if
    ChPrime == 0 -> false;
    true -> isPrime(N,M+1)
end.


问:
How do I acces localhost MySQL through command line from another pc?
As a follow-up question on this one:

Accessing localhost (xampp) from another computer over LAN network - how to?

I can access localhost in my browser and MySQL but not from the command-line

I can not figure out how to get from there. From the command-line I use:

```<code>mysql -u root -h "IP of remote localhost"
</code>```

And getting the following error "Error 2003(HY000): Can't connect to MySQL server on "

答:
Basically you need to enable remote access.

This is for mysql workbench

Clicking the [+] icon from the home screen launches the Setup New Connection wizard. The wizard provides a MySQL connection form to create a new MySQL connection, and includes a Configure Server Management option as a step-by-step approach to creating a new MySQL server connection. This can also be executed later (on remote connections) when from the home screen by clicking the top right corner of a MySQL connection tile:

Executing this wizard is required to perform tasks requiring shell access to the host. For example, starting/stopping the MySQL instance and editing the configuration file.

And here is a tutorial where you can peform it step by step:

https://dev.mysql.com/doc/workbench/en/wb-getting-started-tutorial-create-connection.html

This is to do it over xamp

You need to open up the configuration it will look something like this:

```<code># The MySQL server
[mysqld]
user=mysql
port=3308
socket      =/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
key_buffer=16M
max_allowed_packet=1M
table_open_cache=64
sort_buffer_size=512K
net_buffer_length=8K
read_buffer_size=256K
read_rnd_buffer_size=512K
myisam_sort_buffer_size=8M
bind-address = 0.0.0.0
</code>```

And you will need to specify the IP adress:

```<code>bind-address=192.xxx.xxx.xxx
</code>```

Body:
As a follow-up question on this one:

Accessing localhost (xampp) from another computer over LAN network - how to?

I can access localhost in my browser and MySQL but not from the command-line

I can not figure out how to get from there. From the command-line I use:

mysql -u root -h "IP of remote localhost"

And getting the following error "Error 2003(HY000): Can't connect to MySQL server on "

Body:
Basically you need to enable remote access.

This is for mysql workbench

Clicking the [+] icon from the home screen launches the Setup New Connection wizard. The wizard provides a MySQL connection form to create a new MySQL connection, and includes a Configure Server Management option as a step-by-step approach to creating a new MySQL server connection. This can also be executed later (on remote connections) when from the home screen by clicking the top right corner of a MySQL connection tile:

Executing this wizard is required to perform tasks requiring shell access to the host. For example, starting/stopping the MySQL instance and editing the configuration file.

And here is a tutorial where you can peform it step by step:

https://dev.mysql.com/doc/workbench/en/wb-getting-started-tutorial-create-connection.html

This is to do it over xamp

You need to open up the configuration it will look something like this:

# The MySQL server
[mysqld]
user=mysql
port=3308
socket      =/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
key_buffer=16M
max_allowed_packet=1M
table_open_cache=64
sort_buffer_size=512K
net_buffer_length=8K
read_buffer_size=256K
read_rnd_buffer_size=512K
myisam_sort_buffer_size=8M
bind-address = 0.0.0.0

And you will need to specify the IP adress:

bind-address=192.xxx.xxx.xxx


问:
Passing data to another UIViewController with buttons
so I have a UIScrollView with all of these buttons overlayed with images:

http://i.imgur.com/W6hagsa.png

and I need it so that if you click on a teacher, like Mr Edmondson for maths, In another UIViewController, an email screen pops up and it needs to set the email recipient to edmondson@gmail.com.

Basically you click on whatever teacher, and it sets the email recipient to that teacher. My current code in the recipients & message body is:

```<code>let toRecipients = ["placeholder@gmail.com"]
mc.setMessageBody("blah blah blah blah")
</code>```

How would I do this ?

答:
Have a look at the following instance method:

prepareForSegue:sender:

Use this method to let your end view controller know which teacher that you have selected and in the next view controller where you need to automatically load the teacher's email address you can do the following:

Save all your teachers data (including the names, email address etc.) into a CoreData model then load the selected teachers email address when required.

It's kind of hard to explain in detail as I have no idea how your code is structured and whatnot.

Body:
so I have a UIScrollView with all of these buttons overlayed with images:

http://i.imgur.com/W6hagsa.png

and I need it so that if you click on a teacher, like Mr Edmondson for maths, In another UIViewController, an email screen pops up and it needs to set the email recipient to edmondson@gmail.com.

Basically you click on whatever teacher, and it sets the email recipient to that teacher. My current code in the recipients & message body is:

let toRecipients = ["placeholder@gmail.com"]
mc.setMessageBody("blah blah blah blah")

How would I do this ?


问:
How to create oblique text (UILabel) in IB?
How to create oblique text (UILabel) in IB ?</p>

答: Select the label in IB, click the gray button next to "Font" label in Attributes Inspector (Cmd-1) and select the font.

ContentLicense: CC BY-SA 2.5


问:
How to make library for linked-list functions
I want to create static or dynamic library for linked list functions, but when I try to compile function files with gcc to get object file it gives me error ‘struct node’ declared inside parameter list
 int GetNth(struct node* head, int index) & dereferencing pointer to incomplete type ‘struct node’ if(i == index) return head->data;. Not sure what's going on, may be because I haven't declared the structure in the file

```<code>#include <stdlib.h>
int count(struct node* head, int n) //counts the occurrence of n in the list
{
  int c = 0;
  while(head != NULL){
    if(head->data == n) c+=1;
    head = head->next;
  }
  return c;
}
</code>```

But if I'll declare it inside this file, I think it'll violate 1 definition rule. What to do?

structure is declared in the main function as

```<code>struct node{
  int data;
  struct node *next;
}
</code>```

答:
The compiler tells you it does not recognize struct node. You need to Declare it first. Something like struct node; (decleration) or struct node{...}; (definition) and the error should go away. If you have already declared it in another file header.h, just add #include "header.h" in the start of your code

Since you want struct node to contain a field called data, you need to add it when you define the struct:

```<code>struct node{
    int data;
}
</code>```

Body:
I want to create static or dynamic library for linked list functions, but when I try to compile function files with gcc to get object file it gives me error ‘struct node’ declared inside parameter list
 int GetNth(struct node* head, int index) & dereferencing pointer to incomplete type ‘struct node’ if(i == index) return head->data;. Not sure what's going on, may be because I haven't declared the structure in the file

#include <stdlib.h>
int count(struct node* head, int n) //counts the occurrence of n in the list
{
  int c = 0;
  while(head != NULL){
    if(head->data == n) c+=1;
    head = head->next;
  }
  return c;
}

But if I'll declare it inside this file, I think it'll violate 1 definition rule. What to do?

structure is declared in the main function as

struct node{
  int data;
  struct node *next;
}

Body:
The compiler tells you it does not recognize struct node. You need to Declare it first. Something like struct node; (decleration) or struct node{...}; (definition) and the error should go away. If you have already declared it in another file header.h, just add #include "header.h" in the start of your code

Since you want struct node to contain a field called data, you need to add it when you define the struct:

struct node{
    int data;
}


问:
How to Transfer with minimum Balance Fee
Hello I'm trying to make my program run so that when you are transferring money a transfer fee of $2.0 is ONLY applied to accounts with a balance less than $10,000.

The issue I am having is that my code is charging me a transfer fee regardless of my balance. If I have a balance of $5,000,000 and I transfer $9,999 dollars it charges me a transfer fee of 2.0.

If I try to transfer > $10,000 there is NO transfer fee. Please spot my error. Thank you so much.

There are 5 classes so i'm going to paste all the relevant information below.

```<code>// CLASS 1
public class AccountConstants {
private final double CHECKING_BALANCE_THRESHOLD = 10000;
private final double TRANSFER_FEE = 2.0;

public double getFee(double amount){
    if (amount < CHECKING_BALANCE_THRESHOLD){
        return TRANSFER_FEE;
    }
    return 0.0;
}

public class CheckingAccount extends Account{
public CheckingAccount(String number, String name, GregorianCalendar
openDate, double balance){
    super(number,name,openDate,balance);
}

//CLASS 2
    @override
    public int transferTo(Account account, double amount) {
    AccountConstants ac = new AccountConstants();
    double fee = ac.getFee(amount);
    if (this.getBalance() < amount)
        return -2;
    else if (this.getBalance() < (amount+fee))
        return -1;
    else if (this.getBalance()>=(amount+fee)&& fee==2.0){
       this.setBalance(-(amount+fee));
       account.setBalance(amount);
       return 1;
    }
    else
        this.setBalance(-amount);
        account.setBalance(amount);
        return 0;
}

//CLASS 3
if (result == 0)
{
    au.setBalance(jComboBox1.getSelectedIndex(),
    accounts.getBalance());
    au.setBalance(index, accounts_to.getBalance());
    NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
    txtBalance.setText(defaultFormat.format(accounts.getBalance()));
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index),
    au.getCustomerName(index), au.getBalance(index));
    index = jComboBox1.getSelectedIndex();
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index), au.getCustomerName(index), au.getBalance(index));
    JOptionPane.showMessageDialog(this, defaultFormat.format(amount)+" was transfered to "+accountNumber,"Transfer successful", JOptionPane.INFORMATION_MESSAGE);
}

else if (result == 1)
{
    au.setBalance(jComboBox1.getSelectedIndex(), accounts.getBalance());
    au.setBalance(index, accounts_to.getBalance());
    NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
    txtBalance.setText(defaultFormat.format(accounts.getBalance()));
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index),au.getCustomerName(index), au.getBalance(index));
    index = jComboBox1.getSelectedIndex();
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index), au.getCustomerName(index), au.getBalance(index));
    JOptionPane.showMessageDialog(this, defaultFormat.format(amount)+" was transfered to "+accountNumber+"\n$2.0 transfer fee was applied", "Transfer successful", JOptionPane.INFORMATION_MESSAGE);
}
</code>```

答:
Ugg, can you please format the code properly? It gave me a sore head. But anyway:

```<code>double fee = ac.getFee(amount);
</code>```

Should be:

```<code>double fee = ac.getFee(this.getBalance());
</code>```

As the fee is calculated on the balance, not on the amount transferred.

Also, this is not causing a problem right now, but:

```<code>else
    this.setBalance(-amount);
    account.setBalance(amount);
    return 0;
</code>```

Should be:

```<code>else
{
    this.setBalance(-amount);
    account.setBalance(amount);
    return 0;
}
</code>```

Also, returning mysterious values of -2 to 1 doesn't help with understandability of the code.

Body:
Hello I'm trying to make my program run so that when you are transferring money a transfer fee of $2.0 is ONLY applied to accounts with a balance less than $10,000.

The issue I am having is that my code is charging me a transfer fee regardless of my balance. If I have a balance of $5,000,000 and I transfer $9,999 dollars it charges me a transfer fee of 2.0.

If I try to transfer > $10,000 there is NO transfer fee. Please spot my error. Thank you so much.

There are 5 classes so i'm going to paste all the relevant information below.

// CLASS 1
public class AccountConstants {
private final double CHECKING_BALANCE_THRESHOLD = 10000;
private final double TRANSFER_FEE = 2.0;

public double getFee(double amount){
    if (amount < CHECKING_BALANCE_THRESHOLD){
        return TRANSFER_FEE;
    }
    return 0.0;
}

public class CheckingAccount extends Account{
public CheckingAccount(String number, String name, GregorianCalendar
openDate, double balance){
    super(number,name,openDate,balance);
}

//CLASS 2
    @override
    public int transferTo(Account account, double amount) {
    AccountConstants ac = new AccountConstants();
    double fee = ac.getFee(amount);
    if (this.getBalance() < amount)
        return -2;
    else if (this.getBalance() < (amount+fee))
        return -1;
    else if (this.getBalance()>=(amount+fee)&& fee==2.0){
       this.setBalance(-(amount+fee));
       account.setBalance(amount);
       return 1;
    }
    else
        this.setBalance(-amount);
        account.setBalance(amount);
        return 0;
}

//CLASS 3
if (result == 0)
{
    au.setBalance(jComboBox1.getSelectedIndex(),
    accounts.getBalance());
    au.setBalance(index, accounts_to.getBalance());
    NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
    txtBalance.setText(defaultFormat.format(accounts.getBalance()));
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index),
    au.getCustomerName(index), au.getBalance(index));
    index = jComboBox1.getSelectedIndex();
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index), au.getCustomerName(index), au.getBalance(index));
    JOptionPane.showMessageDialog(this, defaultFormat.format(amount)+" was transfered to "+accountNumber,"Transfer successful", JOptionPane.INFORMATION_MESSAGE);
}

else if (result == 1)
{
    au.setBalance(jComboBox1.getSelectedIndex(), accounts.getBalance());
    au.setBalance(index, accounts_to.getBalance());
    NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
    txtBalance.setText(defaultFormat.format(accounts.getBalance()));
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index),au.getCustomerName(index), au.getBalance(index));
    index = jComboBox1.getSelectedIndex();
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index), au.getCustomerName(index), au.getBalance(index));
    JOptionPane.showMessageDialog(this, defaultFormat.format(amount)+" was transfered to "+accountNumber+"\n$2.0 transfer fee was applied", "Transfer successful", JOptionPane.INFORMATION_MESSAGE);
}

Body:
Ugg, can you please format the code properly? It gave me a sore head. But anyway:

double fee = ac.getFee(amount);

Should be:

double fee = ac.getFee(this.getBalance());

As the fee is calculated on the balance, not on the amount transferred.

Also, this is not causing a problem right now, but:

else
    this.setBalance(-amount);
    account.setBalance(amount);
    return 0;

Should be:

else
{
    this.setBalance(-amount);
    account.setBalance(amount);
    return 0;
}

Also, returning mysterious values of -2 to 1 doesn't help with understandability of the code.


问:
how to get latitude, longitude onclick of a map in google maps api v3 javascript?
how to know latitude, longitude on click of a map in google maps api v3.
i have done this in google maps api v2 with this code

```<code> GEvent.addListener(map, "click", function(overlay, latlng) {
          if (latlng) {
            marker = new GMarker(latlng, {draggable:true});
            GEvent.addListener(marker, "click", function() {
                //alert("hello");
              var html = "<table>" +
                         "<tr><td>Name:</td> <td><input type='text' id='name'/> </td> </tr>" +
                         "<tr><td>Time:</td> <td><input type='text' id='time'/> </td> </tr>" +
                         "<tr><td>Bus Id:</td> <td><input type='text' id='busId'/> </td> </tr>" +
                         "<tr><td>Device Id:</td> <td><input type='text' id='deviceId'/> </td> </tr>" +
                         "<tr><td></td><td><input type='button' value='Save & Close' onclick='saveData()'/></td></tr>";
              marker.openInfoWindow(html);
            });
            map.addOverlay(marker);
          }
        });
</code>```

how to do this same thing in v3?

i tried this but it didn't work.

```<code>google.maps.event.addListener(map, "click", function(overlay,latlng) {
        if (latlng) {
        marker = new google.maps.Marker(latlng);
           google.maps.event.addListener(marker, "click", function() {
              var html = "<table>" +
                         "<tr><td>Name:</td> <td><input type='text' id='name'/> </td> </tr>" +
                         "<tr><td>Time:</td> <td><input type='text' id='time'/> </td> </tr>" +
                         "<tr><td>Bus Id:</td> <td><input type='text' id='busId'/> </td> </tr>" +
                         "<tr><td>Device Id:</td> <td><input type='text' id='deviceId'/> </td> </tr>" +
                         "<tr><td></td><td><input type='button' value='Save & Close' onclick='saveData()'/></td></tr>";
              marker.openInfoWindow(html);
            });
            map.setMap(marker);

         }
        });
</code>```

答:
You have to use this.

```<code> google.maps.event.addListener(map, 'click', function(event) {
    alert("Latitude: " + event.latLng.lat() + " " + ", longitude: " + event.latLng.lng());
  });
</code>```

Body:
how to know latitude, longitude on click of a map in google maps api v3.
i have done this in google maps api v2 with this code

 GEvent.addListener(map, "click", function(overlay, latlng) {
          if (latlng) {
            marker = new GMarker(latlng, {draggable:true});
            GEvent.addListener(marker, "click", function() {
                //alert("hello");
              var html = "
" +
                         "
Name:	 <input type='text' id='name'/>
" +
                         "
Time:	 <input type='text' id='time'/>
" +
                         "
Bus Id:	 <input type='text' id='busId'/>
" +
                         "
Device Id:	 <input type='text' id='deviceId'/>
" +
                         "
	<input type='button' value='Save & Close' onclick='saveData()'/>
";
              marker.openInfoWindow(html);
            });
            map.addOverlay(marker);
          }
        });

how to do this same thing in v3?

i tried this but it didn't work.

google.maps.event.addListener(map, "click", function(overlay,latlng) {
        if (latlng) {
        marker = new google.maps.Marker(latlng);
           google.maps.event.addListener(marker, "click", function() {
              var html = "
" +
                         "
Name:	 <input type='text' id='name'/>
" +
                         "
Time:	 <input type='text' id='time'/>
" +
                         "
Bus Id:	 <input type='text' id='busId'/>
" +
                         "
Device Id:	 <input type='text' id='deviceId'/>
" +
                         "
	<input type='button' value='Save & Close' onclick='saveData()'/>
";
              marker.openInfoWindow(html);
            });
            map.setMap(marker);

         }
        });

Body:
You have to use this.

 google.maps.event.addListener(map, 'click', function(event) {
    alert("Latitude: " + event.latLng.lat() + " " + ", longitude: " + event.latLng.lng());
  });


问:
MS Access using function on onclick event of button
I have below function on form:

```<code>Function StringsHaveAMatchingCharacter(String1 As Variant, String2 As Variant) As Boolean

     ' Return True if the two strings have at least one character in common;
     ' otherwise return False.

     Dim lngX As Long

     If IsNull(String1) Or IsNull(String2) Then
         ' No point checking for a match.
     Else
         For lngX = 1 To Len(String1)
             If InStr(String2, Mid$(String1, lngX, 1)) <> 0 Then
                 StringsHaveAMatchingCharacter = True
                 Exit Function
             End If
         Next lngX
     End If

     StringsHaveAMatchingCharacter = False

 End Function
</code>```

I can call this function with commandbutton on form. But how to use specify on my event if function returns "false" or "true" as I want new dialog form to be open if function returns "True" else I want msgbox and cancel opening dialog form.

答:
Not sure I understand the problem. You simply call the function and use its return value.

Private Sub cmdOpenDialog_Click()

    Dim isMatch As Boolean

    isMatch = StringsHaveAMatchingCharacter(Me!Text1.Value, Me!Text2.Value)

    If isMatch Then
        DoCmd.OpenForm "myDialog"
    Else
        MsgBox "Nope."
    End If

End Sub
```

Body:
I have below function on form:

Function StringsHaveAMatchingCharacter(String1 As Variant, String2 As Variant) As Boolean

     ' Return True if the two strings have at least one character in common;
     ' otherwise return False.

     Dim lngX As Long

     If IsNull(String1) Or IsNull(String2) Then
         ' No point checking for a match.
     Else
         For lngX = 1 To Len(String1)
             If InStr(String2, Mid$(String1, lngX, 1)) <> 0 Then
                 StringsHaveAMatchingCharacter = True
                 Exit Function
             End If
         Next lngX
     End If

     StringsHaveAMatchingCharacter = False

 End Function

I can call this function with commandbutton on form. But how to use specify on my event if function returns "false" or "true" as I want new dialog form to be open if function returns "True" else I want msgbox and cancel opening dialog form.


问:
How to initialize a RemoteMessage object with a Json file?
I am dealing with FCM messages and I have the following function:

```<code>  public void onMessageReceived(final RemoteMessage remoteMessage)
  {
   final Map<String, String> data = remoteMessage.getData();
   //...
  }
</code>```

For testing purposes, I have a Json file containing data- and I want to send that Json file from my test method to onMessagereceived() . Hence I need to initialize a RemoteMessage object with the Json file and pass this RemoteMessage object to the function. How do I initialize this?

My JSON file:

```<code>{
    "data": {
        "id" : "4422",
        "type" : "1",
        "imageUrl" : "https://image.freepik.com/free-vector/android-boot-logo_634639.jpg",
        "smallTitle" : "DoJMA v2",
        "smallSubTitle" : "Update now from Google Play Store",
        "ticker" : "New update for DoJMA",
        "contentInfo" : "",
    "link" : "https://photo2.tinhte.vn/data/avatars/l/1885/1885712.jpg?1402763583",
        "className" : "HomeActivity",
        "page" : "2",
        "bigTitle" : "DoJMA Android app version 2 released!",
        "bigSubTitle" : "Hi folks! New DoJMA update is here! Major redesigning and improvements! This app was made by the Mobile App Club.They work really hard man...and get good products",
        "bigSummaryText" : "Update now"
     },
    "registration_ids": ["dQYmpLUACXQ:APA91bGl-NoIMJ2_DcctF5-OA8ghyWuyrMfsz3uhlj1BySl6axkAsmv5y_7YGfpQQJ2E0lP_fTcxpHpZdkJzY1tbcWA36e78ooxC_b0a1PAank9gFIAUHVZkHKmZT70MPZosCgvRlVfq","dfLXnRI36qY:APA91bFyjLblijVIjGLCGWVeB1B0z5j_3TYqRytJ-8hvuUESpDlX59gWF3hU-I-kA4VrRCPpEVFWl18ZarnPjqxxtZgFkVxoLr77HRex27VN7Mh3xupWykmKq_nnVIlVzrODKwKI7ktM"]
}
</code>```

答:
TL;DR: Initializing a RemoteMessage object is not possible.

Attempting to access initialize a RemoteMessage from your own class would return an error:

'RemoteMessage(android.os.Bundle)' is not public in 'com.google.firebase.messaging.RemoteMessage'. Cannot be accessed from outside package.

I presume you're attempting to do this for testing purposes (stubbing?). In general (not gonna say best practice, since I'm not that entirely sure that it is best practice), it is advisable to have a separate method that accepts a specific value that you need. Referring to the official example (onMessageReceived) (removed some stuff):

```<code>@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());

        if (/* Check if data needs to be processed by long running job */ true) {
            // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
            scheduleJob();
        } else {
            // Handle message within 10 seconds
            handleNow();
        }

    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.

}

/**
 * Schedule a job using FirebaseJobDispatcher.
 */
private void scheduleJob() {
    // [START dispatch_job]
    FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
    Job myJob = dispatcher.newJobBuilder()
            .setService(MyJobService.class)
            .setTag("my-job-tag")
            .build();
    dispatcher.schedule(myJob);
    // [END dispatch_job]
}

/**
 * Handle time allotted to BroadcastReceivers.
 */
private void handleNow() {
    Log.d(TAG, "Short lived task is done.");
}

/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 */
private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_ic_notification)
            .setContentTitle("FCM Message")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
</code>```

Focusing on the comment that mentions:

Also if you intend on generating your own notifications as a result of a received FCM message, here is where that should be initiated. See sendNotification method below.

This points out the sendNotification() method that accepts a String parameter. Depending on your case, instead of attempting to pass an initialized RemoteMessage (which sadly isn't possible, or at the very least is not advisable), you could simply pass an object that your method needs.

With that, you pretty much tested the method that handles the message without depending on an object that isn't a class you made in the first place.

 PS: Some of my explanations can be confusing, but I hope this made sense.

Body:
I am dealing with FCM messages and I have the following function:

  public void onMessageReceived(final RemoteMessage remoteMessage)
  {
   final Map<String, String> data = remoteMessage.getData();
   //...
  }

For testing purposes, I have a Json file containing data- and I want to send that Json file from my test method to onMessagereceived() . Hence I need to initialize a RemoteMessage object with the Json file and pass this RemoteMessage object to the function. How do I initialize this?

My JSON file:

{
    "data": {
        "id" : "4422",
        "type" : "1",
        "imageUrl" : "https://image.freepik.com/free-vector/android-boot-logo_634639.jpg",
        "smallTitle" : "DoJMA v2",
        "smallSubTitle" : "Update now from Google Play Store",
        "ticker" : "New update for DoJMA",
        "contentInfo" : "",
    "link" : "https://photo2.tinhte.vn/data/avatars/l/1885/1885712.jpg?1402763583",
        "className" : "HomeActivity",
        "page" : "2",
        "bigTitle" : "DoJMA Android app version 2 released!",
        "bigSubTitle" : "Hi folks! New DoJMA update is here! Major redesigning and improvements! This app was made by the Mobile App Club.They work really hard man...and get good products",
        "bigSummaryText" : "Update now"
     },
    "registration_ids": ["dQYmpLUACXQ:APA91bGl-NoIMJ2_DcctF5-OA8ghyWuyrMfsz3uhlj1BySl6axkAsmv5y_7YGfpQQJ2E0lP_fTcxpHpZdkJzY1tbcWA36e78ooxC_b0a1PAank9gFIAUHVZkHKmZT70MPZosCgvRlVfq","dfLXnRI36qY:APA91bFyjLblijVIjGLCGWVeB1B0z5j_3TYqRytJ-8hvuUESpDlX59gWF3hU-I-kA4VrRCPpEVFWl18ZarnPjqxxtZgFkVxoLr77HRex27VN7Mh3xupWykmKq_nnVIlVzrODKwKI7ktM"]
}

Body:
TL;DR: Initializing a RemoteMessage object is not possible.

Attempting to access initialize a RemoteMessage from your own class would return an error:

'RemoteMessage(android.os.Bundle)' is not public in 'com.google.firebase.messaging.RemoteMessage'. Cannot be accessed from outside package.

I presume you're attempting to do this for testing purposes (stubbing?). In general (not gonna say best practice, since I'm not that entirely sure that it is best practice), it is advisable to have a separate method that accepts a specific value that you need. Referring to the official example (onMessageReceived) (removed some stuff):

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());

        if (/* Check if data needs to be processed by long running job */ true) {
            // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
            scheduleJob();
        } else {
            // Handle message within 10 seconds
            handleNow();
        }

    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.

}

/**
 * Schedule a job using FirebaseJobDispatcher.
 */
private void scheduleJob() {
    // [START dispatch_job]
    FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
    Job myJob = dispatcher.newJobBuilder()
            .setService(MyJobService.class)
            .setTag("my-job-tag")
            .build();
    dispatcher.schedule(myJob);
    // [END dispatch_job]
}

/**
 * Handle time allotted to BroadcastReceivers.
 */
private void handleNow() {
    Log.d(TAG, "Short lived task is done.");
}

/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 */
private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_ic_notification)
            .setContentTitle("FCM Message")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

Focusing on the comment that mentions:

Also if you intend on generating your own notifications as a result of a received FCM message, here is where that should be initiated. See sendNotification method below.

This points out the sendNotification() method that accepts a String parameter. Depending on your case, instead of attempting to pass an initialized RemoteMessage (which sadly isn't possible, or at the very least is not advisable), you could simply pass an object that your method needs.

With that, you pretty much tested the method that handles the message without depending on an object that isn't a class you made in the first place.

 PS: Some of my explanations can be confusing, but I hope this made sense.


问:
Copy multiple local files to docker container
Similar to Copying files from host to Docker container, except docker cp doesn't seem to work for multiple files

```<code>$ docker cp data/a.txt sandbox_web_1:/usr/src/app/data/
</code>```

works fine, but

```<code>$ docker cp data/*txt sandbox_web_1:/usr/src/app/data/

docker: "cp" requires 2 arguments.
See 'docker cp --help'.

Usage:  docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH

Copy files/folders between a container and the local filesystem
Use '-' as the source to read a tar archive from stdin
and extract it to a directory destination in a container.
Use '-' as the destination to stream a tar archive of a
container source to stdout.
</code>```

Using docker 1.11.1 on Ubuntu 14.04x64

答:
The following command should copy whole directory data with its content of a data directory to your desired destination:

```<code>docker cp data/ sandbox_web_1:/usr/src/app/
</code>```

Tested on Docker version 1.12.1, but I haven't found any changes to a cp command in a the release 1.12.1

Body:
Similar to Copying files from host to Docker container, except docker cp doesn't seem to work for multiple files

$ docker cp data/a.txt sandbox_web_1:/usr/src/app/data/

works fine, but

$ docker cp data/*txt sandbox_web_1:/usr/src/app/data/

docker: "cp" requires 2 arguments.
See 'docker cp --help'.

Usage:  docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH

Copy files/folders between a container and the local filesystem
Use '-' as the source to read a tar archive from stdin
and extract it to a directory destination in a container.
Use '-' as the destination to stream a tar archive of a
container source to stdout.

Using docker 1.11.1 on Ubuntu 14.04x64

Body:
The following command should copy whole directory data with its content of a data directory to your desired destination:

docker cp data/ sandbox_web_1:/usr/src/app/

Tested on Docker version 1.12.1, but I haven't found any changes to a cp command in a the release 1.12.1


答:
Use the .is() function to compare the event target to your JQuery element :

$(window).on("click", function(event) {
  var container = $("#container");
  if ($(event.target).is(container)) {
    alert("clicked outside");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: 600px;
}

#container {
  padding: 2rem;
  background: grey;
}</code>```

```

Title: JQuery - Why event.target doesn't work in this situation?

Body:
just wondering why when i click inside the container the alert popups despite the if statement for it to not show on click.

Also how would I test for the children inside?

https://jsfiddle.net/w8fd3m67/

$(window).on("click", function(event) {
  var container = $("#container");
  if ((event.target) !== container) {
    alert("clicked outside");
  }
});

body {
  height: 600px;
}

#container {
  padding: 2rem;
  background: grey;
}

Cheers

Body:
Use the .is() function to compare the event target to your JQuery element :

$(window).on("click", function(event) {
  var container = $("#container");
  if ($(event.target).is(container)) {
    alert("clicked outside");
  }
});

body {
  height: 600px;
}

#container {
  padding: 2rem;
  background: grey;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">

</div>


答:
Compare the id. Here $("#container") is a jquery object

$(window).on("click", function(event) {
  if ((event.target.id) !== 'container') {
    alert("clicked outside");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: 600px;
}

#container {
  padding: 2rem;
  background: grey;
}</code>```

```

Body:
Compare the id. Here $("#container") is a jquery object

$(window).on("click", function(event) {
  if ((event.target.id) !== 'container') {
    alert("clicked outside");
  }
});

body {
  height: 600px;
}

#container {
  padding: 2rem;
  background: grey;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">

</div>


问:
How to Fetch the length of the column using a Instead of Trigger in SQL Server?
I am trying to fetch the length of a particular column in Instead of Trigger using LEN() function. I want to fetch the length of a column from inserted table and then compare the length using if else so that I can do the required actions. Here is what I am doing:

```<code>CREATE TRIGGER [tr_firstNameLength_signupTable]
ON [dbo].[signup_table]
INSTEAD OF INSERT
AS
BEGIN
    SET NOCOUNT ON
    Declare @length varchar(50)
    select  @length = i.first_name from inserted i where i.first_name != null
    if (LEN(@length) > 50)
    Raiserror('Invalid Firstname. Please try again', 16, 1)
    else
    insert into signup_table(first_name, surname, mobile_number, email_address, salt, password)
    select first_name, surname, mobile_number, email_address, salt, password from inserted
END
</code>```

or Should I user CHECK  CONSTRAINT?
I am open to suggestions. So feel free to suggest How I can achieve it in a better way. TIA... :)

答:
```<code>ALTER TABLE dbo.signup_table
ADD CONSTRAINT
CK_signup_table_first_name CHECK (len(first_name) <= 50)
</code>```

Body:
I am trying to fetch the length of a particular column in Instead of Trigger using LEN() function. I want to fetch the length of a column from inserted table and then compare the length using if else so that I can do the required actions. Here is what I am doing:

CREATE TRIGGER [tr_firstNameLength_signupTable]
ON [dbo].[signup_table]
INSTEAD OF INSERT
AS
BEGIN
    SET NOCOUNT ON
    Declare @length varchar(50)
    select  @length = i.first_name from inserted i where i.first_name != null
    if (LEN(@length) > 50)
    Raiserror('Invalid Firstname. Please try again', 16, 1)
    else
    insert into signup_table(first_name, surname, mobile_number, email_address, salt, password)
    select first_name, surname, mobile_number, email_address, salt, password from inserted
END

or Should I user CHECK  CONSTRAINT?
I am open to suggestions. So feel free to suggest How I can achieve it in a better way. TIA... :)


问:
how can we create scoring in iphone game
I want to create score when a target is hit...

whenever a target is hit

```<code>int targetHit=0;
targerhit=targethit+1;
</code>```

now I want to show that in label....

```<code>CCLabel* label2 = [CCLabel  labelWithString:@"null"   <-----i want to add score herer?and keep changing it ?how can i
                                         fontName:@"Marker Felt"
                                         fontSize:30];
        label2.position = ccp(400, 295);

        [self addChild:label2];
</code>```

答:
I didn't use cocos2d yet, but here is some info that i've found.

(void) setString:          (NSString *)     string

changes the string to render

Warning:
Changing the string is as expensive as creating a new CCLabel.

Body:
I want to create score when a target is hit...

whenever a target is hit

int targetHit=0;
targerhit=targethit+1;

now I want to show that in label....

CCLabel* label2 = [CCLabel  labelWithString:@"null"   <-----i want to add score herer?and keep changing it ?how can i
                                         fontName:@"Marker Felt"
                                         fontSize:30];
        label2.position = ccp(400, 295);

        [self addChild:label2];


问:
Reading a column value from more than one table based on some condition - postgreSQL
I am trying to create a view for one of the tables I have. For one of the columns in the view, I am trying to read the value from the tables I have:

Table A:

```<code>id   b_id   c_id    d_id
1     1
2            1
3                     1
</code>```

Table B:

```<code>id   code
1     64
</code>```

Table C:

```<code>id    code
1     98
</code>```

Table D:

```<code>id     code
1       26
</code>```

In the above tables, A is my main table which has two foreign key references to tables B and C(b_id and c_id) respectively. And for each row in table A, only one of the two references (b_id or c_id) will be populated.

My task is to create a view for table A, say v_A, which will have the following columns:

View v_A:

```<code>code      code_table
64           B
98           C
26           D
</code>```

In the above view, I have to first check for each row in table A, which of the foreign key references are populated, based on that I have to read the column 'code' and the column 'code_table' will have the name of the table I am populating the 'code' column.

I have been able to create simple views but this is a bit tricky for me. I was checking if I can use case ...when for the same but after a point that became a bit complicated too. I also can read the table name in postgres from the information_schema table. So I have bits and pieces of the solution but do not understand how to put it all together.

Can someone point me in the right direction?

Thanks!!

答:
Of course it will work only when you have EITHER one table filled OR the OTHER - it does not solve conflict when both tales have matching keys:</p>

```<code>t=# create view _a as select coalesce(b.code,c.code,d.code) code, case when b.id is not null then 'B' when c.id is not null then 'C' when d.id is not null then 'D' end from a
left outer join b on b.id = b_id
left outer join c on c.id = c_id
left outer join d on d.id = d_id;
CREATE VIEW
t=# select * from _a;
 code | case
------+------
   26 | D
   98 | C
   64 | B
(3 rows)
</code>```

Body:
I am trying to create a view for one of the tables I have. For one of the columns in the view, I am trying to read the value from the tables I have:

Table A:

id   b_id   c_id    d_id
1     1
2            1
3                     1

Table B:

id   code
1     64

Table C:

id    code
1     98

Table D:

id     code
1       26

In the above tables, A is my main table which has two foreign key references to tables B and C(b_id and c_id) respectively. And for each row in table A, only one of the two references (b_id or c_id) will be populated.

My task is to create a view for table A, say v_A, which will have the following columns:

View v_A:

code      code_table
64           B
98           C
26           D

In the above view, I have to first check for each row in table A, which of the foreign key references are populated, based on that I have to read the column 'code' and the column 'code_table' will have the name of the table I am populating the 'code' column.

I have been able to create simple views but this is a bit tricky for me. I was checking if I can use case ...when for the same but after a point that became a bit complicated too. I also can read the table name in postgres from the information_schema table. So I have bits and pieces of the solution but do not understand how to put it all together.

Can someone point me in the right direction?

Thanks!!

Body:
Of course it will work only when you have EITHER one table filled OR the OTHER - it does not solve conflict when both tales have matching keys:

t=# create view _a as select coalesce(b.code,c.code,d.code) code, case when b.id is not null then 'B' when c.id is not null then 'C' when d.id is not null then 'D' end from a
left outer join b on b.id = b_id
left outer join c on c.id = c_id
left outer join d on d.id = d_id;
CREATE VIEW
t=# select * from _a;
 code | case
------+------
   26 | D
   98 | C
   64 | B
(3 rows)


问:
Excel VBA: Transferring data from variable sheet name, run-time error '91'
What I want to do is to transfer data from the variable named sheet to a certain sheet ("SUMMARY"). Then, I want to consider a cell in the variable sheet. So if the cell > 0, then it will copy the line to SUMMARY. But I'm having an 'Object variable or With block variable not set' error. What am I doing wrong? </p>

```<code>        Sub transfer()

        Dim ws As String
        Dim n As Integer
        Dim i As Long

        Dim c As Range

        n = Sheets("Start").Range("c24").Value + 3

        If n > 0 Then
            For i = 3 To n

                Dim desrow As Integer
                desrow = i - 1
                Dim rng As Range

                rng = Range("AA11:AA40")

                    For Each c In rng
                        If c = 12 Then

                             Sheets("OFFLIMITS").Cells(desrow, 1).Value = Sheets(i).Range("C3")

                        End If
                    Next c
            Next i

        End If

        End Sub
</code>```

答:
You must Set objects, so you need to say:

```<code>Set rng = Range("AA11:AA40")
</code>```

Body:
What I want to do is to transfer data from the variable named sheet to a certain sheet ("SUMMARY"). Then, I want to consider a cell in the variable sheet. So if the cell > 0, then it will copy the line to SUMMARY. But I'm having an 'Object variable or With block variable not set' error. What am I doing wrong?

        Sub transfer()

        Dim ws As String
        Dim n As Integer
        Dim i As Long

        Dim c As Range

        n = Sheets("Start").Range("c24").Value + 3

        If n > 0 Then
            For i = 3 To n

                Dim desrow As Integer
                desrow = i - 1
                Dim rng As Range

                rng = Range("AA11:AA40")

                    For Each c In rng
                        If c = 12 Then

                             Sheets("OFFLIMITS").Cells(desrow, 1).Value = Sheets(i).Range("C3")

                        End If
                    Next c
            Next i

        End If

        End Sub

Body:
You must Set objects, so you need to say:

Set rng = Range("AA11:AA40")


问:
Ionic 2: login via keycloak won't store keycloak cookies
I am building Ionic 2 app and I want to use Keycloak for login/signup.

I have the following situation:

I am on Keycloak login page and when I login, I am redirect back to my app. I would expect that Keycloak will set cookies, but it didn't. I guess it is because of this: Can you use cookies in a Cordova application?.

Is there any way how to tell Keycloak to use local storage instead of cookies. Or any other solution?

I am using this implementation of keycloak & angular 2 colaboration.

答:
In the Keycloak there is a Javascript Adapter - keycloak.js, it already knows how to work with a Cordova application, it is only necessary to disable the token checking through the iframe.

I created a simple app Ionic2 with Keycloak integration https://github.com/sergeyrolich/ionic2-keycloak


问:
Why does Windows64 use a different calling convention from all other OSes on x86-64?
AMD has an ABI specification that describes the calling convention to use on x86-64. All OSes follow it, except for Windows which has it's own x86-64 calling convention. Why?

Does anyone know the technical, historical, or political reasons for this difference, or is it purely a matter of NIHsyndrome?

I understand that different OSes may have different needs for higher level things, but that doesn't explain why for example the register parameter passing order on Windows is rcx - rdx - r8 - r9 - rest on stack while everyone else uses rdi - rsi - rdx - rcx - r8 - r9 - rest on stack.

P.S. I am aware of how these calling conventions differ generally and I know where to find details if I need to. What I want to know is why.

Edit: for the how, see e.g. the wikipedia entry and links from there.

答:
Choosing four argument registers on x64 - common to UN*X / Win64

One of the things to keep in mind about x86 is that the register name to "reg number" encoding is not obvious; in terms of instruction encoding (the MOD R/M byte, see http://www.c-jump.com/CIS77/CPU/x86/X77_0060_mod_reg_r_m_byte.htm), register numbers 0...7 are - in that order - ?AX, ?CX, ?DX, ?BX, ?SP, ?BP, ?SI, ?DI.

Hence choosing A/C/D (regs 0..2) for return value and the first two arguments (which is the "classical" 32bit __fastcall convention) is a logical choice. As far as going to 64bit is concerned, the "higher" regs are ordered, and both Microsoft and UN*X/Linux went for R8 / R9 as the first ones.

Keeping that in mind, Microsoft's choice of RAX (return value) and RCX, RDX, R8, R9 (arg[0..3]) are an understandable selection if you choose four registers for arguments.

I don't know why the AMD64 UN*X ABI chose RDX before RCX.

Choosing six argument registers on x64 - UN*X specific

UN*X, on RISC architectures, has traditionally done argument passing in registers - specifically, for the first six arguments (that's so on PPC, SPARC, MIPS at least). Which might be one of the major reasons why the AMD64 (UN*X) ABI designers chose to use six registers on that architecture as well.

So if you want six registers to pass arguments in, and it's logical to choose RCX, RDX, R8 and R9 for four of them, which other two should you pick ?

The "higher" regs require an additional instruction prefix byte to select them and therefore have a bigger instruction size footprint, so you wouldn't want to choose any of those if you have options. Of the classical registers, due to the implicit meaning of RBP and RSP these aren't available, and RBX traditionally has a special use on UN*X (global offset table) which seemingly the AMD64 ABI designers didn't want to needlessly become incompatible with.

Ergo, the only choice were RSI / RDI.

So if you have to take RSI / RDI as argument registers, which arguments should they be ?

Making them arg[0] and arg[1] has some advantages. See cHao's comment.

?SI and ?DI are string instruction source / destination operands, and as cHao mentioned, their use as argument registers means that with the AMD64 UN*X calling conventions, the simplest possible strcpy() function, for example, only consists of the two CPU instructions repz movsb; ret because the source/target addresses have been put into the correct registers by the caller. There is, particularly in low-level and compiler-generated "glue" code (think, for example, some C++ heap allocators zero-filling objects on construction, or the kernel zero-filling heap pages on sbrk(), or copy-on-write pagefaults) an enormous amount of block copy/fill, hence it'll be useful for code so frequently used to save the two or three CPU instructions that'd otherwise load such source/target address arguments into the "correct" registers.

So in a way, UN*X and Win64 are only different in that UN*X "prepends" two additional arguments, in purposefully chosen RSI/RDI registers, to the natural choice of four arguments in RCX, RDX, R8 and R9.

Beyond that ...

There are more differences between the UN*X and Windows x64 ABIs than just the mapping of arguments to specific registers. For the overview on Win64, check:

http://msdn.microsoft.com/en-us/library/7kcdt6fy.aspx

Win64 and AMD64 UN*X also strikingly differ in the way stackspace is used; on Win64, for example, the caller must allocate stackspace for function arguments even though args 0...3 are passed in registers. On UN*X on the other hand, a leaf function  (i.e. one that doesn't call other functions) is not even required to allocate stackspace at all if it needs no more than 128 Bytes of it (yes, you own and can use a certain amount of stack without allocating it ... well, unless you're kernel code, a source of nifty bugs). All these are particular optimization choices, most of the rationale for those is explained in the full ABI references that the original poster's wikipedia reference points to.


问:
get char value in java
How can I get the UTF8 code of a char in Java ?
I have the char 'a' and I want the value 97
I have the char 'é' and I want the value 233

here is a table for more values

I tried Character.getNumericValue(a) but for a it gives me 10 and not 97, any idea why?

This seems very basic but any help would be appreciated!

答:
You can create a simple loop to list all the UTF-8 characters available like this:</p>

```<code>public class UTF8Characters {
    public static void main(String[] args) {
        for (int i = 12; i <= 999; i++) {
            System.out.println(i +" - "+ (char)i);
        }
    }
}
</code>```

Title: get char value in java

Body:
You can create a simple loop to list all the UTF-8 characters available like this:

public class UTF8Characters {
    public static void main(String[] args) {
        for (int i = 12; i <= 999; i++) {
            System.out.println(i +" - "+ (char)i);
        }
    }
}


问:
MYSQL / PHP TWO Multiselect Dropdown Filters (PDO)
The errors I am getting are the following: (Also i am echoing the query statement)

Notice: Array to string conversion in /home/fanati10/public_html/wp-content/themes/digital-pro/page-nflwranalyzer.php on line 75

Notice: Array to string conversion in /home/fanati10/public_html/wp-content/themes/digital-pro/page-nflwranalyzer.php on line 79

*SELECT * FROM WR_TeamAnalyzer WHERE TMID = ? AND WKID = ?*

HERE IS MY php file

```<code>  if(isset($_POST['submit']))
  {
      require_once( get_stylesheet_directory() . '/config/config.php' );
      if(isset($_POST['check'])) {
        $nflposs = "";
        foreach($_POST['check'] as $val => $text_field) {
          $nflposs.=$text_field.", ";
       }
          $nflpossint = rtrim($nflposs, ', ');
          $nflposs = explode(',', $nflpossint);
          $placeholders = rtrim(str_repeat('?, ', count($nflposs)), ', ');
          $filter[] = "TMID = $placeholders";
          $values[] = $nflpossint;
      }
       if(isset($_POST['wk'])) {
        $wkid = "";
        foreach($_POST['wk'] as $val => $text_field) {
          $wkid.=$text_field.", ";
       }
          $wkidint = rtrim($wkid, ', ');
          $wkid = explode(',', $wkidint);
          $placeholders2 = rtrim(str_repeat('?, ', count($wkid)), ', ');
          $filter[] = "WKID = $placeholders2";
          $values[] = $wkidint;
      }
      $sql="SELECT * FROM WR_TeamAnalyzer WHERE " . implode(' AND ', $filter);
      echo ($sql);
      $selectStmt = $dbcon->prepare($sql);
      $selectStmt->execute($values);
      $rows = $selectStmt->fetchAll();
  $tableContent = '';
  foreach ($rows as $row){
    $tableContent = $tableContent.'<tr>'.
</code>```

答:
This is what I came up with

change:

```<code>$filter[] = "TMID IN $placeholders";
$values = $nflpossint;
</code>```

&

```<code>$filter[] = "WKID IN $placeholders2";
$values2 = $wkidint;
</code>```

&

```<code>$sql="SELECT * FROM WR_TeamAnalyzer WHERE TMID IN ($values) AND WKID IN ($values2)";
$selectStmt = $dbcon->prepare($sql);
$selectStmt->execute();
</code>```

Body:
The errors I am getting are the following: (Also i am echoing the query statement)

Notice: Array to string conversion in /home/fanati10/public_html/wp-content/themes/digital-pro/page-nflwranalyzer.php on line 75

Notice: Array to string conversion in /home/fanati10/public_html/wp-content/themes/digital-pro/page-nflwranalyzer.php on line 79

*SELECT * FROM WR_TeamAnalyzer WHERE TMID = ? AND WKID = ?*

HERE IS MY php file

  if(isset($_POST['submit']))
  {
      require_once( get_stylesheet_directory() . '/config/config.php' );
      if(isset($_POST['check'])) {
        $nflposs = "";
        foreach($_POST['check'] as $val => $text_field) {
          $nflposs.=$text_field.", ";
       }
          $nflpossint = rtrim($nflposs, ', ');
          $nflposs = explode(',', $nflpossint);
          $placeholders = rtrim(str_repeat('?, ', count($nflposs)), ', ');
          $filter[] = "TMID = $placeholders";
          $values[] = $nflpossint;
      }
       if(isset($_POST['wk'])) {
        $wkid = "";
        foreach($_POST['wk'] as $val => $text_field) {
          $wkid.=$text_field.", ";
       }
          $wkidint = rtrim($wkid, ', ');
          $wkid = explode(',', $wkidint);
          $placeholders2 = rtrim(str_repeat('?, ', count($wkid)), ', ');
          $filter[] = "WKID = $placeholders2";
          $values[] = $wkidint;
      }
      $sql="SELECT * FROM WR_TeamAnalyzer WHERE " . implode(' AND ', $filter);
      echo ($sql);
      $selectStmt = $dbcon->prepare($sql);
      $selectStmt->execute($values);
      $rows = $selectStmt->fetchAll();
  $tableContent = '';
  foreach ($rows as $row){
    $tableContent = $tableContent.'
'.

Body:
This is what I came up with

change:

$filter[] = "TMID IN $placeholders";
$values = $nflpossint;

&

$filter[] = "WKID IN $placeholders2";
$values2 = $wkidint;

&

$sql="SELECT * FROM WR_TeamAnalyzer WHERE TMID IN ($values) AND WKID IN ($values2)";
$selectStmt = $dbcon->prepare($sql);
$selectStmt->execute();


问:
Unable to connect email Server on JDK 8
I am not able to connect IMAP mail server to fetch the mails from jdk8 but it works fine with jdk7.
Below is my code

```<code>private Properties getServerProperties(String protocol, String host, String port) {
    Properties properties = new Properties();
    properties.put(String.format("mail.%s.host", protocol), host);
    properties.put(String.format("mail.%s.port", protocol), port);
    properties.setProperty(String.format("mail.%s.socketFactory.class", protocol), "javax.net.ssl.SSLSocketFactory");
    properties.setProperty(String.format("mail.%s.socketFactory.fallback", protocol), "false");
    properties.setProperty(String.format("mail.%s.socketFactory.port", protocol), String.valueOf(port));
    return properties;
}

public void getNewEmails(String protocol, String host, String port, String userName, String password) {
    Properties properties = getServerProperties(protocol, host, port);
    Session session = Session.getDefaultInstance(properties);
    session.setDebug(true);

    try {
        Store store = session.getStore(protocol);
        store.connect(userName, password);

        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);

        int count = inbox.getMessageCount();
        Message[] messages = inbox.getMessages(1, count);
        for (Message message : messages) {

            Address[] fromAddresses = message.getFrom();
            System.out.println("...................");
            System.out.println("\t From: " + fromAddresses[0].toString());
            System.out.println("\t To: " + parseAddresses(message.getRecipients(RecipientType.TO)));
            System.out.println("\t CC: " + parseAddresses(message.getRecipients(RecipientType.CC)));
            System.out.println("\t Subject: " + message.getSubject());
            System.out.println("\t Sent Date:" + message.getSentDate().toString());
            System.out.println(message.getContent());
        }
        inbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        System.out.println("No provider for protocol: " + protocol);
        ex.printStackTrace();
    } catch (MessagingException ex) {
        System.out.println("Could not connect to  the message store");
        ex.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

private String parseAddresses(Address[] address) {

    String listOfAddress = "";
    if ((address == null) || (address.length < 1))
        return null;
    if (!(address[0] instanceof InternetAddress))
        return null;

    for (int i = 0; i < address.length; i++) {
        InternetAddress internetAddress = (InternetAddress) address[0];
        listOfAddress += internetAddress.getAddress() + ",";
    }
    return listOfAddress;
}
</code>```

When I try to run the above code it hangs on store.connect(userName, password);

Below is the link from where I tried the above code http://www.developer.com/java/data/monitoring-email-accounts-imap-in-java.html.
Here is a link which has no answer for the question
https://community.oracle.com/message/13244272#13244272

Below is the logs while running with both JDK.

JDK 7 LOGS :

```<code>    DEBUG:setDebug:

JavaMail version 1.5.0-
b01
DEBUG:

getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle]
DEBUG IMAP: mail.imap.fetchsize: 16384
DEBUG IMAP: mail.imap.ignorebodystructuresize: false
DEBUG IMAP: mail.imap.statuscachetimeout: 1000
DEBUG IMAP: mail.imap.appendbuffersize: -1
DEBUG IMAP: mail.imap.minidletime: 10
DEBUG IMAP: trying to connect to host "XXXXXXXXXXXXXXXXXXX", port 993, isSSL false
* OK server ready. Unauthorized Access Prohibited.
A0 CAPABILITY
* CAPABILITY IMAP4REV1 IDLE AUTH=PLAIN
A0 OK CAPABILITY completed
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: protocolConnect login, host=XXXXXXXXXXXXXXXXXXX, user=XXXXXXXXXXXXXXXXXXX, password=<non-null>
DEBUG IMAP: AUTHENTICATE PLAIN command trace suppressed
DEBUG IMAP: AUTHENTICATE PLAIN command result: A1 OK AUTHENTICATE completed
A2 CAPABILITY
* CAPABILITY IMAP4REV1 IDLE AUTH=PLAIN
A2 OK CAPABILITY completed
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: connection available -- size: 1
A3 SELECT INBOX
</code>```

JDK 8 LOGS :

```<code>    DEBUG:setDebug:

JavaMail version 1.5.0-
b01
DEBUG:

getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle]
DEBUG IMAP: mail.imap.fetchsize: 16384
DEBUG IMAP: mail.imap.ignorebodystructuresize: false
DEBUG IMAP: mail.imap.statuscachetimeout: 1000
DEBUG IMAP: mail.imap.appendbuffersize: -1
DEBUG IMAP: mail.imap.minidletime: 10
DEBUG IMAP: trying to connect to host "XXXXXXXXXXXXXXXXXXX", port 993, isSSL false
* OK server ready. Unauthorized Access Prohibited.
A0 CAPABILITY
* CAPABILITY IMAP4REV1 IDLE AUTH=PLAIN
A0 OK CAPABILITY completed
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: protocolConnect login, host=XXXXXXXXXXXXXXXXXXX, user=XXXXXXXXXXXXXXXXXXX, password=<non-null>
DEBUG IMAP: AUTHENTICATE PLAIN command trace suppressed
</code>```

After the above line it hangs and did not respond.

答:
```<code>After Bill Shannon comment I tried below configuration and it start working with below configuration with JDK-8.

`<dependency>
 <groupId>com.sun.mail</groupId>
 <artifactId>javax.mail</artifactId>
 <version>1.5.5</version>
 </dependency>`
</code>```

Title: Unable to connect email Server on JDK 8

Body:
I am not able to connect IMAP mail server to fetch the mails from jdk8 but it works fine with jdk7.
Below is my code

private Properties getServerProperties(String protocol, String host, String port) {
    Properties properties = new Properties();
    properties.put(String.format("mail.%s.host", protocol), host);
    properties.put(String.format("mail.%s.port", protocol), port);
    properties.setProperty(String.format("mail.%s.socketFactory.class", protocol), "javax.net.ssl.SSLSocketFactory");
    properties.setProperty(String.format("mail.%s.socketFactory.fallback", protocol), "false");
    properties.setProperty(String.format("mail.%s.socketFactory.port", protocol), String.valueOf(port));
    return properties;
}

public void getNewEmails(String protocol, String host, String port, String userName, String password) {
    Properties properties = getServerProperties(protocol, host, port);
    Session session = Session.getDefaultInstance(properties);
    session.setDebug(true);

    try {
        Store store = session.getStore(protocol);
        store.connect(userName, password);

        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);

        int count = inbox.getMessageCount();
        Message[] messages = inbox.getMessages(1, count);
        for (Message message : messages) {

            Address[] fromAddresses = message.getFrom();
            System.out.println("...................");
            System.out.println("\t From: " + fromAddresses[0].toString());
            System.out.println("\t To: " + parseAddresses(message.getRecipients(RecipientType.TO)));
            System.out.println("\t CC: " + parseAddresses(message.getRecipients(RecipientType.CC)));
            System.out.println("\t Subject: " + message.getSubject());
            System.out.println("\t Sent Date:" + message.getSentDate().toString());
            System.out.println(message.getContent());
        }
        inbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        System.out.println("No provider for protocol: " + protocol);
        ex.printStackTrace();
    } catch (MessagingException ex) {
        System.out.println("Could not connect to  the message store");
        ex.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

private String parseAddresses(Address[] address) {

    String listOfAddress = "";
    if ((address == null) || (address.length < 1))
        return null;
    if (!(address[0] instanceof InternetAddress))
        return null;

    for (int i = 0; i < address.length; i++) {
        InternetAddress internetAddress = (InternetAddress) address[0];
        listOfAddress += internetAddress.getAddress() + ",";
    }
    return listOfAddress;
}

When I try to run the above code it hangs on store.connect(userName, password);

Below is the link from where I tried the above code http://www.developer.com/java/data/monitoring-email-accounts-imap-in-java.html.
Here is a link which has no answer for the question
https://community.oracle.com/message/13244272#13244272

Below is the logs while running with both JDK.

JDK 7 LOGS :

    DEBUG:setDebug:

JavaMail version 1.5.0-
b01
DEBUG:

getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle]
DEBUG IMAP: mail.imap.fetchsize: 16384
DEBUG IMAP: mail.imap.ignorebodystructuresize: false
DEBUG IMAP: mail.imap.statuscachetimeout: 1000
DEBUG IMAP: mail.imap.appendbuffersize: -1
DEBUG IMAP: mail.imap.minidletime: 10
DEBUG IMAP: trying to connect to host "XXXXXXXXXXXXXXXXXXX", port 993, isSSL false
* OK server ready. Unauthorized Access Prohibited.
A0 CAPABILITY
* CAPABILITY IMAP4REV1 IDLE AUTH=PLAIN
A0 OK CAPABILITY completed
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: protocolConnect login, host=XXXXXXXXXXXXXXXXXXX, user=XXXXXXXXXXXXXXXXXXX, password=<non-null>
DEBUG IMAP: AUTHENTICATE PLAIN command trace suppressed
DEBUG IMAP: AUTHENTICATE PLAIN command result: A1 OK AUTHENTICATE completed
A2 CAPABILITY
* CAPABILITY IMAP4REV1 IDLE AUTH=PLAIN
A2 OK CAPABILITY completed
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: connection available -- size: 1
A3 SELECT INBOX

JDK 8 LOGS :

    DEBUG:setDebug:

JavaMail version 1.5.0-
b01
DEBUG:

getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle]
DEBUG IMAP: mail.imap.fetchsize: 16384
DEBUG IMAP: mail.imap.ignorebodystructuresize: false
DEBUG IMAP: mail.imap.statuscachetimeout: 1000
DEBUG IMAP: mail.imap.appendbuffersize: -1
DEBUG IMAP: mail.imap.minidletime: 10
DEBUG IMAP: trying to connect to host "XXXXXXXXXXXXXXXXXXX", port 993, isSSL false
* OK server ready. Unauthorized Access Prohibited.
A0 CAPABILITY
* CAPABILITY IMAP4REV1 IDLE AUTH=PLAIN
A0 OK CAPABILITY completed
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: protocolConnect login, host=XXXXXXXXXXXXXXXXXXX, user=XXXXXXXXXXXXXXXXXXX, password=<non-null>
DEBUG IMAP: AUTHENTICATE PLAIN command trace suppressed

After the above line it hangs and did not respond.


问:
Invalid argument supplied for foreach() laravel using whereIn (laravel 5.3)
I am getting ids using jquery in my controller its as

```<code>if(!empty($request->input('ids'))) {
    $ids = $request->input('ids');
    }else{
                $ids = null;
            }
</code>```

I try dd($ids)

Output is as in my console

```<code>array:3 [
  0 => "1"
  1 => "2"
  2 => "on"
]
</code>```

When i pass ids to my query as

Query

```<code>$student_ids = DB::table('students')
             ->orderBy('name', 'asc')
              ->where('group_id', '<>', 0)
              ->whereIn('students.id','=', $ids)
              ->pluck('id');
</code>```

Its not working

Error is : Invalid argument supplied for foreach

Please help where I am wrong. Thanks

答:
Like others have mentioned update the whereIn parameter. Also simplify your request input like so.

```<code>$ids = $request->input('ids', []);

$student_ids = DB::table('students')
    ->orderBy('name', 'asc')
    ->where('group_id', '<>', 0)
    ->whereIn('students.id', $ids)
    ->pluck('id');
</code>```

Body:
I am getting ids using jquery in my controller its as

if(!empty($request->input('ids'))) {
    $ids = $request->input('ids');
    }else{
                $ids = null;
            }

I try dd($ids)

Output is as in my console

array:3 [
  0 => "1"
  1 => "2"
  2 => "on"
]

When i pass ids to my query as

Query

$student_ids = DB::table('students')
             ->orderBy('name', 'asc')
              ->where('group_id', '<>', 0)
              ->whereIn('students.id','=', $ids)
              ->pluck('id');

Its not working

Error is : Invalid argument supplied for foreach

Please help where I am wrong. Thanks

Body:
Like others have mentioned update the whereIn parameter. Also simplify your request input like so.

$ids = $request->input('ids', []);

$student_ids = DB::table('students')
    ->orderBy('name', 'asc')
    ->where('group_id', '<>', 0)
    ->whereIn('students.id', $ids)
    ->pluck('id');


问:
Calling method from a specific childViewControllers class
Alright, hope I can explain this as clearly as possible.

I have a Parent ViewController which has a ContainerView, this will contain different viewControllers/Class. I'm changing the content of this container at runtime like this:

```<code>    let newController = (storyboard?.instantiateViewController(withIdentifier: classIdentifierFromStoryboard))! as UIViewController
    let oldController = childViewControllers.last! as UIViewController

    oldController.willMove(toParentViewController: nil)
    addChildViewController(newController)
    newController.view.frame = oldController.view.frame

    transition(from: oldController, to: newController, duration: 0, options: .transitionCrossDissolve, animations:{ () -> Void in
        }, completion: { (finished) -> Void in

    })

    oldController.removeFromParentViewController()
    newController.didMove(toParentViewController: self)
</code>```

So for example, the current controller that shows on UI is firstVC, which kinda look like

```<code>class firstVC {
    func removeAnnotations() {
        //something that removes annotation from MapVC
     }
}
</code>```

On a certain event on the parent controller, how can I access the instance of firstVC so that i'll be able to call removeAnnotations? As of the moment I am getting nil, using this on parent controller firstVC.removeAnnotations, assumably this calls another instance of the class. Any help would be great! Hope my explanation makes sense. Thanks!

答:
You could run down the child view controllers like this:

```<code>for case let vc as firstVC in self.childViewControllers {
    vc.removeAnnotations()
}
</code>```

This will run down all the child view controllers that are of type firstVC and execute the removeAnnotations method

Body:
Alright, hope I can explain this as clearly as possible.

I have a Parent ViewController which has a ContainerView, this will contain different viewControllers/Class. I'm changing the content of this container at runtime like this:

    let newController = (storyboard?.instantiateViewController(withIdentifier: classIdentifierFromStoryboard))! as UIViewController
    let oldController = childViewControllers.last! as UIViewController

    oldController.willMove(toParentViewController: nil)
    addChildViewController(newController)
    newController.view.frame = oldController.view.frame

    transition(from: oldController, to: newController, duration: 0, options: .transitionCrossDissolve, animations:{ () -> Void in
        }, completion: { (finished) -> Void in

    })

    oldController.removeFromParentViewController()
    newController.didMove(toParentViewController: self)

So for example, the current controller that shows on UI is firstVC, which kinda look like

class firstVC {
    func removeAnnotations() {
        //something that removes annotation from MapVC
     }
}

On a certain event on the parent controller, how can I access the instance of firstVC so that i'll be able to call removeAnnotations? As of the moment I am getting nil, using this on parent controller firstVC.removeAnnotations, assumably this calls another instance of the class. Any help would be great! Hope my explanation makes sense. Thanks!

Body:
You could run down the child view controllers like this:

for case let vc as firstVC in self.childViewControllers {
    vc.removeAnnotations()
}

This will run down all the child view controllers that are of type firstVC and execute the removeAnnotations method


问:
Stop Scrollbar from resizing
My VBA-Code has a little beauty mistake, that I'd like to correct.
What my code is doing is that on click some columns of a sheet are being hidden and others being shown.
The thing is that while those columns are changing so is the scrollbar. It seems resizing a few times, until the process is completed.

Is there a way to stop that?

Here is a little example of my code:

```<code>Application.ScreenUpdating = False
Sheets("MySheet").Range("B:F").Columns.Hidden = True
Sheets("MySheet").Range("H:M").Columns.Hidden = False
Application.ScreenUpdating = True
</code>```

Of course I've already searched the Internet and Stackoverflow for solutions, but nothing worked as I wanted.

Greetings,
Frame

答:
Can you try it like this:

```<code>With ActiveWindow
    .DisplayHorizontalScrollBar = False 'True
    .DisplayVerticalScrollBar = False 'True
End With
</code>```

It would simply hide it. Concerning resizing, I think that you cannot change it.

Title: Stop Scrollbar from resizing

Body:
My VBA-Code has a little beauty mistake, that I'd like to correct.
What my code is doing is that on click some columns of a sheet are being hidden and others being shown.
The thing is that while those columns are changing so is the scrollbar. It seems resizing a few times, until the process is completed.

Is there a way to stop that?

Here is a little example of my code:

Application.ScreenUpdating = False
Sheets("MySheet").Range("B:F").Columns.Hidden = True
Sheets("MySheet").Range("H:M").Columns.Hidden = False
Application.ScreenUpdating = True

Of course I've already searched the Internet and Stackoverflow for solutions, but nothing worked as I wanted.

Greetings,
Frame

Body:
Can you try it like this:

With ActiveWindow
    .DisplayHorizontalScrollBar = False 'True
    .DisplayVerticalScrollBar = False 'True
End With

It would simply hide it. Concerning resizing, I think that you cannot change it.


问:
Find out where the error happened in Clojure
For the most part I understand what Clojure is telling me with it's error messages. But I am still clueless as to find out where the error happened.

Here is an example of what I mean

```<code>(defn extract [m]
  (keys m))

(defn multiple [xs]
  (map #(* 2 %) xs))

(defn process [xs]
  (-> xs
      (multiple)     ; seq -> seq
      (extract))) ; map -> seq ... fails

(process [1 2 3])
</code>```

Statically typed languages would now tell me that I tried to pass a sequence to a function that expects a map on line X. And Clojure does this in a way:

```<code>ClassCastException java.lang.Long cannot be cast to java.util.Map$Entry
</code>```

But I still have no idea where the error happened. Obviously for this instance it's easy because there are just 3 functions involved, you can easily just read through all of them but as programs grow bigger this gets old very quickly.

Is there a way find out where the errors happened other than just proof reading the code from top to bottom? (which is my current approach)

答:
If you have a REPL session you can print a stack trace:

```<code>(clojure.stacktrace/print-stack-trace *e 30)
</code>```

See http://puredanger.github.io/tech.puredanger.com/2010/02/17/clojure-stack-trace-repl/ for various different ways of printing the stack trace. You will need to have a dependency such as this in your project.clj:

```<code>[org.clojure/tools.namespace "0.2.11"]
</code>```

I didn't get a stack trace using the above method, however just typing *e at the REPL will give you all the available information about the error, which to be honest didn't seem very helpful.

For the rare cases where the stack trace is not helpful I usually debug using a call to a function that returns the single argument it is given, yet has the side effect of printing that argument. I happen to call this function probe. In your case it can be put at multiple places in the threading macro.

Body:
For the most part I understand what Clojure is telling me with it's error messages. But I am still clueless as to find out where the error happened.

Here is an example of what I mean

(defn extract [m]
  (keys m))

(defn multiple [xs]
  (map #(* 2 %) xs))

(defn process [xs]
  (-> xs
      (multiple)     ; seq -> seq
      (extract))) ; map -> seq ... fails

(process [1 2 3])

Statically typed languages would now tell me that I tried to pass a sequence to a function that expects a map on line X. And Clojure does this in a way:

ClassCastException java.lang.Long cannot be cast to java.util.Map$Entry

But I still have no idea where the error happened. Obviously for this instance it's easy because there are just 3 functions involved, you can easily just read through all of them but as programs grow bigger this gets old very quickly.

Is there a way find out where the errors happened other than just proof reading the code from top to bottom? (which is my current approach)

Body:
If you have a REPL session you can print a stack trace:

(clojure.stacktrace/print-stack-trace *e 30)

See http://puredanger.github.io/tech.puredanger.com/2010/02/17/clojure-stack-trace-repl/ for various different ways of printing the stack trace. You will need to have a dependency such as this in your project.clj:

[org.clojure/tools.namespace "0.2.11"]

I didn't get a stack trace using the above method, however just typing *e at the REPL will give you all the available information about the error, which to be honest didn't seem very helpful.

For the rare cases where the stack trace is not helpful I usually debug using a call to a function that returns the single argument it is given, yet has the side effect of printing that argument. I happen to call this function probe. In your case it can be put at multiple places in the threading macro.