问:
Modifying and recompiling the Android SDK
I know that some methods and some classes that are implemented in Android are not exported to the Android public SDK. I've been able to create an application that uses some of these functions by compiling my application placing it inside the Android tree.
Would it be possible to export these functions to the Android SDK by recompiling it from the sources? How can this be done? Can I include custom classes and functions in the Android SDK as well (supposing of course I create a new SDK and a new firmware)?
Thanks!</p>

答:
It is possible to download the SDK and make changes to it.

If you are releasing a public app, you should not use any non-public API's as there are no guarantees they will be available on all phones, or in future versions of OS.


来源: stackexchange

问:
Eloquent where clause in JOIN table - Laravel 5.5
I have two models which are connected each other.

```<code>class Company extends Model {
   public function addresses() {
      return $this->belongsToMany('\App\Address', 'address_mapping', 'uid_company', 'uid_address');
   }
}

class Address extends Model {
}
</code>```

In my JOIN table I have a column named active. How can I fetch all active addresses from the company? Or how can I implement a where-clause in the JOIN table?

Thank you!

答:
The table that you call a "JOIN table", usually called a pivot table.
You can fetch all active records by using wherePivot method:

```<code> $company = Company::first();
 $activeAdresses = $company->addresses()->wherePivot('active', 1);
</code>```

Or you can directly define the relationship in your model:

```<code>class Company extends Model {
   public function activeAddresses() {
      return $this->belongsToMany('\App\Address', 'address_mapping', 'uid_company', 'uid_address')
                  ->wherePivot('active', 1);
   }
}
</code>```

See section Filtering Relationships Via Intermediate Table Columns in Eloquent documentation

ContentLicense: CC BY-SA 3.0

Body:
I have two models which are connected each other.

class Company extends Model {
   public function addresses() {
      return $this->belongsToMany('\App\Address', 'address_mapping', 'uid_company', 'uid_address');
   }
}

class Address extends Model {
}

In my JOIN table I have a column named active. How can I fetch all active addresses from the company? Or how can I implement a where-clause in the JOIN table?

Thank you!

Body:
The table that you call a "JOIN table", usually called a pivot table.
You can fetch all active records by using wherePivot method:

 $company = Company::first();
 $activeAdresses = $company->addresses()->wherePivot('active', 1);

Or you can directly define the relationship in your model:

class Company extends Model {
   public function activeAddresses() {
      return $this->belongsToMany('\App\Address', 'address_mapping', 'uid_company', 'uid_address')
                  ->wherePivot('active', 1);
   }
}

See section Filtering Relationships Via Intermediate Table Columns in Eloquent documentation


问:
JavaScript: Uncaught TypeError: Cannot read property 'appendChild' of null
I am a beginner and I am currently working on a memory card game. Help me, please.

Here is my code to which the error message applies:

HTML

```<code><div id="game-board" class="board clearfix"></div>
</code>```

Javascript

```<code>var createBoard = function() {
    for (var i = 0; i < cards.length; i++) {
        var cardElement = document.createElement('img');
        cardElement.setAttribute('src', "images/back.png");
        cardElement.setAttribute('data-id', i);
        document.getElementsByTagName('img')[0].addEventListener('click', flipCard);
        document.querySelector('game-board').appendChild(cardElement);
    }
}

createBoard();
</code>```

答:
The error "cannot read property 'appendChild' of null" means that your line with appendChild evaluates to

```<code>null.appendChild(cardElement);
</code>```

In other words, document.querySelector('game-board') must be evaluating to null and null doesn't have an appendChild method.

Solution: Probably the selector inside querySelector is wrong; check the docs.

If game-board is a class it should be

```<code>document.querySelector('.game-board')
</code>```

If game-board is an id it should be

```<code>document.querySelector('#game-board')
</code>```

Body:
I am a beginner and I am currently working on a memory card game. Help me, please.

Here is my code to which the error message applies:

HTML

Javascript

var createBoard = function() {
    for (var i = 0; i < cards.length; i++) {
        var cardElement = document.createElement('img');
        cardElement.setAttribute('src', "images/back.png");
        cardElement.setAttribute('data-id', i);
        document.getElementsByTagName('img')[0].addEventListener('click', flipCard);
        document.querySelector('game-board').appendChild(cardElement);
    }
}

createBoard();

Body:
The error "cannot read property 'appendChild' of null" means that your line with appendChild evaluates to

null.appendChild(cardElement);

In other words, document.querySelector('game-board') must be evaluating to null and null doesn't have an appendChild method.

Solution: Probably the selector inside querySelector is wrong; check the docs.

If game-board is a class it should be

document.querySelector('.game-board')

If game-board is an id it should be

document.querySelector('#game-board')


问:
Google Analytics reports 10 times lesser sessions than hits in server logs
Let's say I've a page mysite.com/mypage

Landing Page Report in GA for this URL for a specified duration, gives me a number of sessions - say 50.

For the same duration, I checked Apache's access.log, and did a grep "GET /mypage, and I've got around 10x more hits -- say 500.

How can we have a 10x anomaly between GA & Server Logs? Where did the hits go?

This anomaly is present for other durations too. I've compared various durations.

Before someone tells the standard reasons for this, let me point out that:

A difference of 2x or 3x is understandable, but not 10x.

No, this is not Bot Traffic. I extracted all unique IPs from the logs, and the IPs are 99% unique. So the traffic is all coming from different IPs.

I also analyzed user agents, and they all look real (with various models of phones like iPhone, Samsung etc.)

GA also says that this report is based on 100% data (sampling ruled out).

As I pointed out, I'm only counting the GET requests to the /mypage. That is, I'm not counting asset downloads, favicon hits etc. etc.

I performed another test. I took all IPs, then made them unique, then for each IP I analyzed how many hits came from that IP. I found from 84% of the IPs, there's no second request. They made only 1 request.

I've read Anamoly between google analytics and server hits and have taken care of everything given in the accepted answer.

What could it be? Any clues on how to debug this? The traffic is coming from Paid Facebook Ads.

答:
I suspect the GA JS isn't loading for those "extra" sessions.  If it were loading correctly, there would be one tracking hit sent for each /mypage hit.

The best way to get information on what's happening is to store a local copy of the tracking data sent to Google.  When the GA JS loads correctly, there will be one tracking request sent to Google and another tracking request sent to your web server's log file.

Here's an article that explains how to configure your GA JS code to keep a copy of all tracking requests sent to Google, with syntax examples:

http://support.angelfishstats.com/entries/42575637-How-To-Process-Google-Analytics-Data-with-Angelfish

Once you have the requests, you will see a __ua.gif hit for each request sent to Google.  If you see a hit to /mypage with a FB referral WITHOUT a corresponding __ua.gif hit, you'll want to investigate the details of the /mypage hit.  For example:

What network & country is associated to the IP address that request /mypage?

If you examine multiple IP addresses, does a pattern emerge?

Does the user agent look legit?

Are the clients using a browser or an app?

Is FB charging you for the click?

If the hits look bogus, use your findings to complain to FB and get some money back.


问:
Console pause c#
In this code

```<code>Console.Write("Enter any number from 0 to 9:");
int k = Console.Read();
Console.Write("The ASCII code for it is:");
Console.WriteLine(k);
Console.Read();
</code>```

after I input a number my console close instantly.
If I write this code

```<code>Console.Write("Enter any string:");
string k = Console.ReadLine();
Console.Write("Your string is:");
Console.WriteLine(k);
Console.Read();
</code>```

my console stops so I can see what I wrote.
Why is that happening?

答:
Try using the following instead of Console.ReadLine();

```<code>Console.ReadKey();
</code>```

This will wait for your console to input any key before closing.

Title: Console pause c#

Body:
In this code

Console.Write("Enter any number from 0 to 9:");
int k = Console.Read();
Console.Write("The ASCII code for it is:");
Console.WriteLine(k);
Console.Read();

after I input a number my console close instantly.
If I write this code

Console.Write("Enter any string:");
string k = Console.ReadLine();
Console.Write("Your string is:");
Console.WriteLine(k);
Console.Read();

my console stops so I can see what I wrote.
Why is that happening?

Body:
Try using the following instead of Console.ReadLine();

Console.ReadKey();

This will wait for your console to input any key before closing.


问:
How to Run Server Client code using Socket Programming in Java Eclipse?
Client code:

```<code>import java.io.*;
import java.net.*;

public class SimpleClient {

    public static void main(String[] args) throws IOException {

 Socket clientSocket = null;

 try {
     clientSocket = new Socket(args[0], 4442);
 } catch (UnknownHostException e) {
     System.err.println("Don't know about host: " + args[0] + ".");
     System.exit(1);
 } catch (IOException e) {
     System.err.println("Couldn't get I/O for " +
          "the connection to: " + args[0] + "");
     System.exit(1);
 }

 BufferedInputStream in;
 BufferedOutputStream out;

 try {
     in = new BufferedInputStream(clientSocket.getInputStream());
     out = new BufferedOutputStream(clientSocket.getOutputStream());
 } catch (IOException e) {
     System.out.println(e.toString());
     return;
 }

 byte[] m_txt = args[1].getBytes();

 out.write(m_txt, 0, m_txt.length);

 out.flush();

 byte[] m_rcv = new byte[m_txt.length];

 int n = in.read(m_rcv, 0, m_rcv.length);

 if (n != m_rcv.length) {
     System.out.println("Some data are lost ...");
 }

 System.out.println(new String(m_rcv));

 out.close();
 in.close();
 clientSocket.close();
    }
}
</code>```

Server:

```<code>import java.io.*;
import java.net.*;

public class SimpleServer {

    public static void main(String[] args) throws IOException {

 boolean listening = true;
 ServerSocket serverSocket = null;
 try {
     serverSocket = new ServerSocket(4442);
 } catch (IOException e) {
     System.err.println("Could not listen on port: 4444.");
  System.exit(1);
 }

 while(listening) {
     Socket clientSocket = serverSocket.accept();
     (new SimpleConHandler(clientSocket)).start();
 }

 serverSocket.close();
    }
}
</code>```

Connection Handler:

```<code>import java.io.*;
import java.net.*;

public class SimpleConHandler extends Thread
{

    private Socket clientSocket;

    public SimpleConHandler(Socket clientSocket) {

 this.clientSocket = clientSocket;
    }

    public void run() {

 BufferedInputStream in;
 BufferedOutputStream out;

 try {

     in = new BufferedInputStream(clientSocket.getInputStream());
     out = new BufferedOutputStream(clientSocket.getOutputStream());

 } catch (IOException e) {
     System.out.println(e.toString());
     return;
 }

 try {
     byte[] msg = new byte[4096];
     int bytesRead = 0;
     int n;

     while((n = in.read(msg, bytesRead, 256)) != -1) {
  bytesRead += n;
  if (bytesRead == 4096) {
      break;
  }
  if (in.available() == 0) {
      break;
  }
     }

     for(int i=bytesRead; i>0; i--) {
  out.write(msg[i-1]);
     }

     out.flush();

 } catch(IOException e1) {
     System.out.println(e1.toString());
 }

 try {
     out.close();
     in.close();
     clientSocket.close();
 } catch ( IOException e2 ) {;}
    }
}
</code>```

First i RUN Server, but when i try to RUN Client, the error which i am getting is:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at SimpleClient.main(SimpleClient.java:11)

May be i have to use different consoles to run both the Server and the Client? If so, then please tell me the way. i am using Java Eclipse 1.6 SE.

答:
clientSocket = new Socket(args[0], 4442);

Your program needs a command line argument:

java your.Program <ip>

ContentLicense: CC BY-SA 2.5

Body:
Client code:

import java.io.*;
import java.net.*;

public class SimpleClient {

    public static void main(String[] args) throws IOException {

 Socket clientSocket = null;

 try {
     clientSocket = new Socket(args[0], 4442);
 } catch (UnknownHostException e) {
     System.err.println("Don't know about host: " + args[0] + ".");
     System.exit(1);
 } catch (IOException e) {
     System.err.println("Couldn't get I/O for " +
          "the connection to: " + args[0] + "");
     System.exit(1);
 }

 BufferedInputStream in;
 BufferedOutputStream out;

 try {
     in = new BufferedInputStream(clientSocket.getInputStream());
     out = new BufferedOutputStream(clientSocket.getOutputStream());
 } catch (IOException e) {
     System.out.println(e.toString());
     return;
 }

 byte[] m_txt = args[1].getBytes();

 out.write(m_txt, 0, m_txt.length);

 out.flush();

 byte[] m_rcv = new byte[m_txt.length];

 int n = in.read(m_rcv, 0, m_rcv.length);

 if (n != m_rcv.length) {
     System.out.println("Some data are lost ...");
 }

 System.out.println(new String(m_rcv));

 out.close();
 in.close();
 clientSocket.close();
    }
}

Server:

import java.io.*;
import java.net.*;

public class SimpleServer {

    public static void main(String[] args) throws IOException {

 boolean listening = true;
 ServerSocket serverSocket = null;
 try {
     serverSocket = new ServerSocket(4442);
 } catch (IOException e) {
     System.err.println("Could not listen on port: 4444.");
  System.exit(1);
 }

 while(listening) {
     Socket clientSocket = serverSocket.accept();
     (new SimpleConHandler(clientSocket)).start();
 }

 serverSocket.close();
    }
}

Connection Handler:

import java.io.*;
import java.net.*;

public class SimpleConHandler extends Thread
{

    private Socket clientSocket;

    public SimpleConHandler(Socket clientSocket) {

 this.clientSocket = clientSocket;
    }

    public void run() {

 BufferedInputStream in;
 BufferedOutputStream out;

 try {

     in = new BufferedInputStream(clientSocket.getInputStream());
     out = new BufferedOutputStream(clientSocket.getOutputStream());

 } catch (IOException e) {
     System.out.println(e.toString());
     return;
 }

 try {
     byte[] msg = new byte[4096];
     int bytesRead = 0;
     int n;

     while((n = in.read(msg, bytesRead, 256)) != -1) {
  bytesRead += n;
  if (bytesRead == 4096) {
      break;
  }
  if (in.available() == 0) {
      break;
  }
     }

     for(int i=bytesRead; i>0; i--) {
  out.write(msg[i-1]);
     }

     out.flush();

 } catch(IOException e1) {
     System.out.println(e1.toString());
 }

 try {
     out.close();
     in.close();
     clientSocket.close();
 } catch ( IOException e2 ) {;}
    }
}

First i RUN Server, but when i try to RUN Client, the error which i am getting is:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at SimpleClient.main(SimpleClient.java:11)

May be i have to use different consoles to run both the Server and the Client? If so, then please tell me the way. i am using Java Eclipse 1.6 SE.


问:
Textarea Calculations
I'm trying to have three textareas. The first two are addends and the last is the sum. What's supposed to happen is if your math equation is correct, a paragraph will say true.

Else, it'll say false. However, the paragraph doesn't say anything when I try.
Here's my code:

```<code><textarea id="x"></textarea>
<textarea id="y"></textarea>
<textarea id="z"></textarea>
<script>
    var x = document.getElementById('x').innerHTML;
  var y = document.getElementById('y').innerHTML;
  var z = x + y;
  var p = document.getElementById('p');
</script>
<button oclick="if (z = document.getElementById('z').innerHTML) {p.innerHTML = true} else {p.innerHTML = false}">Calculate</button>
<br>
<p id="p"></p>
</code>```

答:
First attaching the click event to your button from the JS code using addEventListener will be better (avoid the inline-events), then put your code inside, you have to use .value insted of innerHTML to get the value of a textarea.

Note also that you should use double equals == when you want to compare two elements, and because we need to perform a math operations we should cast our values to numbers using Number() method.

Should be something like :

document.getElementById("calculate").addEventListener("click", function() {
  var x = Number( document.getElementById('x').value );
  var y = Number( document.getElementById('y').value );
  var z = x + y;
  var p = document.getElementById('p');

  if (z == document.getElementById('z').value) {
    p.innerText = "true";
  } else {
    p.innerText = "false";
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="x"></textarea>
<textarea id="y"></textarea>
<textarea id="z"></textarea>
<button id="calculate">Calculate</button>
<br>
<p id="p"></p></code>```

Title: Textarea Calculations

Body:
I'm trying to have three textareas. The first two are addends and the last is the sum. What's supposed to happen is if your math equation is correct, a paragraph will say true.

Else, it'll say false. However, the paragraph doesn't say anything when I try.
Here's my code:

<textarea id="x"></textarea>
<textarea id="y"></textarea>
<textarea id="z"></textarea>

<button oclick="if (z = document.getElementById('z').innerHTML) {p.innerHTML = true} else {p.innerHTML = false}">Calculate</button>

Body:
First attaching the click event to your button from the JS code using addEventListener will be better (avoid the inline-events), then put your code inside, you have to use .value insted of innerHTML to get the value of a textarea.

Note also that you should use double equals == when you want to compare two elements, and because we need to perform a math operations we should cast our values to numbers using Number() method.

Should be something like :

document.getElementById("calculate").addEventListener("click", function() {
  var x = Number( document.getElementById('x').value );
  var y = Number( document.getElementById('y').value );
  var z = x + y;
  var p = document.getElementById('p');

  if (z == document.getElementById('z').value) {
    p.innerText = "true";
  } else {
    p.innerText = "false";
  }
});

<textarea id="x"></textarea>
<textarea id="y"></textarea>
<textarea id="z"></textarea>
<button id="calculate">Calculate</button>
<br>
<p id="p"></p>


问:
Recover Data Firestore Collection
I have a service scheduling screen.

But there is a problem:

I need to check if the date and time the user is trying to schedule is available or reserved.

```<code>Structure DB:
Companies
-Company ID (Document)
--name
--phone
---Schedules (Collection)
------Event1
--------Hour: 08:30
--------Date: 01/01/2018
------Event2
--------Hour: 09:00
--------Date: 05/01/2018
------Event3
--------Hour: 10:30
--------Date: 01/002/2018
</code>```

I access Scheduling data with this code:

```<code>String dateExample = "01/01/2018"
String hourExample = "08:30"

FirebaseFirestore mDB = FirebaseFirestore.getInstance();
CollectionReference mDBCompaniesSchedules = (CollectionReference) mDB.collection("Companies").document(mId_Company).collection("Schedules")
.get()
    .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
    @Override
    public void onSuccess(QuerySnapshot documentSnapshots) {

        for (Schedules document : documentSnapshots.toObjects(Schedules.class)) {

            String dtSchedules = document.getSchedules_date();
            String hourSchedules = document.getSchedules_hour();

            if ( dtSchedules.equals(dateExample) && hourSchedules.equals(hourExample) ){

                //Execute a "Toast" and closes the operation

            } else {

                //Call up the scheduling function.
                startScheduling();
            }

        }
    }
})
</code>```

Process:

I need to run this code and go through all the documents in that collection. I need to check and analyze whether the date and time of the schedule already exists.

If there is: Show a Toast and block.

If there is no: Executing a specific function for the schedule record ("startScheduling()").

Problem:

When the data exists (it will only be once) then it will work.

When there is no data, it falls into the ELSE loop. And it is executing several times the same function "startScheduling();".

I need some way to go through this collection and when I do not find any results, the function "startScheduling (), be executed only once.

答:
This how a for loop works. It will continue iterate till the last element to see if the condition is true or not. With other words, your if-else statement is triggered for every iteration in the loop. It means that, if the condition is true it will go with the if part, if the condition is false it will go with else part, for each and every element.

There are two ways in which you can solve this. One would be to break the loop once the condition was fulfilled. But this means that will iterate till it gets that element. Second, would be to change the logic of your code. Use first the if statement and second iterate.

Edit: The best option in this case would be to query your database using whereEqualTo() method.

```<code>Query query = db
    .collection("Companies")
    .document(mId_Company)
    .collection("Schedules")
    .whereEqualTo("dtSchedules", dateExample)
    .whereEqualTo("hourSchedules", hourExample);
</code>```

In which dateExample and hourExample are the actual values with which you want to compare.

To count the number of documents in a Collection, please use the following code:

```<code>public void onSuccess(QuerySnapshot documentSnapshots) {
    if(documentSnapshots.size() == 0) {
        startScheduling();
    }
    for (Schedules document : documentSnapshots.toObjects(Schedules.class)) {
        String dtSchedules = document.getSchedules_date();
        String hourSchedules = document.getSchedules_hour();
    }
}
</code>```

Title: Recover Data Firestore Collection

Body:
I have a service scheduling screen.

But there is a problem:

I need to check if the date and time the user is trying to schedule is available or reserved.

Structure DB:
Companies
-Company ID (Document)
--name
--phone
---Schedules (Collection)
------Event1
--------Hour: 08:30
--------Date: 01/01/2018
------Event2
--------Hour: 09:00
--------Date: 05/01/2018
------Event3
--------Hour: 10:30
--------Date: 01/002/2018

I access Scheduling data with this code:

String dateExample = "01/01/2018"
String hourExample = "08:30"

FirebaseFirestore mDB = FirebaseFirestore.getInstance();
CollectionReference mDBCompaniesSchedules = (CollectionReference) mDB.collection("Companies").document(mId_Company).collection("Schedules")
.get()
    .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
    @Override
    public void onSuccess(QuerySnapshot documentSnapshots) {

        for (Schedules document : documentSnapshots.toObjects(Schedules.class)) {

            String dtSchedules = document.getSchedules_date();
            String hourSchedules = document.getSchedules_hour();

            if ( dtSchedules.equals(dateExample) && hourSchedules.equals(hourExample) ){

                //Execute a "Toast" and closes the operation

            } else {

                //Call up the scheduling function.
                startScheduling();
            }

        }
    }
})

Process:

I need to run this code and go through all the documents in that collection. I need to check and analyze whether the date and time of the schedule already exists.

If there is: Show a Toast and block.

If there is no: Executing a specific function for the schedule record ("startScheduling()").

Problem:

When the data exists (it will only be once) then it will work.

When there is no data, it falls into the ELSE loop. And it is executing several times the same function "startScheduling();".

I need some way to go through this collection and when I do not find any results, the function "startScheduling (), be executed only once.

Body:
This how a for loop works. It will continue iterate till the last element to see if the condition is true or not. With other words, your if-else statement is triggered for every iteration in the loop. It means that, if the condition is true it will go with the if part, if the condition is false it will go with else part, for each and every element.

There are two ways in which you can solve this. One would be to break the loop once the condition was fulfilled. But this means that will iterate till it gets that element. Second, would be to change the logic of your code. Use first the if statement and second iterate.

Edit: The best option in this case would be to query your database using whereEqualTo() method.

Query query = db
    .collection("Companies")
    .document(mId_Company)
    .collection("Schedules")
    .whereEqualTo("dtSchedules", dateExample)
    .whereEqualTo("hourSchedules", hourExample);

In which dateExample and hourExample are the actual values with which you want to compare.

To count the number of documents in a Collection, please use the following code:

public void onSuccess(QuerySnapshot documentSnapshots) {
    if(documentSnapshots.size() == 0) {
        startScheduling();
    }
    for (Schedules document : documentSnapshots.toObjects(Schedules.class)) {
        String dtSchedules = document.getSchedules_date();
        String hourSchedules = document.getSchedules_hour();
    }
}


问:
Does anything like NSPredicateEditor exist for iOS?
As far as I know NSPredicateEditor isn't available for iOS. But has anyone created something similar for iOS?

I imagine it would be fairly difficult UI wise since the screen is much smaller but I don't see why it wouldn't be possible in theory.

答: There's PredicateEditor which resembles what's done in the Workflow app.</p>


问:
How to update a JSONB object with a parent in postgresql
I have a database with a table foo containing a column id and a column data with the following data:

```<code>{
   "startDate":"2017-07-04",
   "endDate":"2017-07-10",
   "notDelegated":false,
   "sold":false,
   "disableRanking":false,
   "type":"PERIOD"
}
</code>```

I would like to update this data with a parent rangeData and extract the type property like this:

```<code>{
   "rangeData": {
       "startDate":"2017-07-04",
       "endDate":"2017-07-10",
       "notDelegated":false,
       "sold":false,
       "disableRanking":false
   },
   "type":"PERIOD"
}
</code>```

I tried a lot of things with JSON operators in vain.

Thank you for your answers.

答:
You can use jsonb_set(target jsonb, path text[], new_value jsonb[, create_missing boolean]) (see the docs).

It's not very pretty, but I did this (you can run it yourself on this SQLFiddle I made):

```<code>SELECT
  jsonb_set(
    (final.range_data):: jsonb,
    '{type}',
    to_jsonb(final.type)
  )
FROM
  (
    SELECT
      jsonb_set(
        jsonb '{}', '{rangeData}', fields.range_data
      ) AS range_data,
      fields.type AS type
    FROM
      (
        SELECT
          data.jsonb - 'type' AS range_data,
          data.jsonb ->> 'type' AS type
        FROM
          (
            SELECT
              '{"startDate":"2017-07-04","endDate":"2017-07-10","notDelegated":false,"sold":false,"disableRanking":false,"type":"PERIOD"}' :: jsonb
          ) data
      ) fields
  ) final;
</code>```

This will get you your jsonb output of:

```<code>{"rangeData": {"startDate":"2017-07-04","endDate":"2017-07-10","notDelegated":false,"sold":false,"disableRanking":false},"type":"PERIOD"}
</code>```

So you'll end up doing something like:

```<code>UPDATE
  foo
SET
  data = (
    SELECT
      jsonb_set(
        (final.range_data):: jsonb,
        '{type}',
        to_jsonb(final.type)
      )
    FROM
      (
        SELECT
          jsonb_set(
            jsonb '{}', '{rangeData}', fields.range_data
          ) AS range_data,
          fields.type AS type
        FROM
          (
            SELECT
              data.jsonb - 'type' AS range_data,
              data.jsonb ->> 'type' AS type
            FROM
              (
                SELECT
                  foo.data
              ) data
          ) fields
      ) final
  );
</code>```

I haven't run the final UPDATE query, but I did run the naïve SELECT statement and it got me the output as expected.

Also, caveat, I'm new to SQL (and especially the jsonb stuff), so I'm sure there will be a more performant and/or more correct "jsonb-like" way to do this. Depends on your use-case (if it's a one-off migration, or if you need to do this during every live read, etc.)

Body:
I have a database with a table foo containing a column id and a column data with the following data:

{
   "startDate":"2017-07-04",
   "endDate":"2017-07-10",
   "notDelegated":false,
   "sold":false,
   "disableRanking":false,
   "type":"PERIOD"
}

I would like to update this data with a parent rangeData and extract the type property like this:

{
   "rangeData": {
       "startDate":"2017-07-04",
       "endDate":"2017-07-10",
       "notDelegated":false,
       "sold":false,
       "disableRanking":false
   },
   "type":"PERIOD"
}

I tried a lot of things with JSON operators in vain.

Thank you for your answers.

Body:
You can use jsonb_set(target jsonb, path text[], new_value jsonb[, create_missing boolean]) (see the docs).

It's not very pretty, but I did this (you can run it yourself on this SQLFiddle I made):

SELECT
  jsonb_set(
    (final.range_data):: jsonb,
    '{type}',
    to_jsonb(final.type)
  )
FROM
  (
    SELECT
      jsonb_set(
        jsonb '{}', '{rangeData}', fields.range_data
      ) AS range_data,
      fields.type AS type
    FROM
      (
        SELECT
          data.jsonb - 'type' AS range_data,
          data.jsonb ->> 'type' AS type
        FROM
          (
            SELECT
              '{"startDate":"2017-07-04","endDate":"2017-07-10","notDelegated":false,"sold":false,"disableRanking":false,"type":"PERIOD"}' :: jsonb
          ) data
      ) fields
  ) final;

This will get you your jsonb output of:

{"rangeData": {"startDate":"2017-07-04","endDate":"2017-07-10","notDelegated":false,"sold":false,"disableRanking":false},"type":"PERIOD"}

So you'll end up doing something like:

UPDATE
  foo
SET
  data = (
    SELECT
      jsonb_set(
        (final.range_data):: jsonb,
        '{type}',
        to_jsonb(final.type)
      )
    FROM
      (
        SELECT
          jsonb_set(
            jsonb '{}', '{rangeData}', fields.range_data
          ) AS range_data,
          fields.type AS type
        FROM
          (
            SELECT
              data.jsonb - 'type' AS range_data,
              data.jsonb ->> 'type' AS type
            FROM
              (
                SELECT
                  foo.data
              ) data
          ) fields
      ) final
  );

I haven't run the final UPDATE query, but I did run the naïve SELECT statement and it got me the output as expected.

Also, caveat, I'm new to SQL (and especially the jsonb stuff), so I'm sure there will be a more performant and/or more correct "jsonb-like" way to do this. Depends on your use-case (if it's a one-off migration, or if you need to do this during every live read, etc.)


问:
Python - GUI linking multiple Frames
Very new to working with GUI's so was wondering if someone could give me some guidance on how to link multiple frames so you can press a button to go to that frame.

If anyone has an ideas or suggestions that would be great!

```<code>from tkinter import *

class main(Frame):
   def __init__(self, master=None):
       super(main, self).__init__(master)
       self.grid()
       self.pack()
   def buttons_dash():
      # create first button
       self.bttn1_dash = Button(self, text = "Student Login",)
       self.bttn1_dash.grid()
       self.bttn1_dash.config(height=3, width=30)

       # create second button
       self.bttn2_dash = Button(self)
       self.bttn2_dash.grid()
       self.bttn2_dash.configure(text = "Staff Login")
       self.bttn2_dash.config(height=3, width=30)

       # create third button
       self.bttn3_dash = Button(self)
       self.bttn3_dash.grid()
       self.bttn3_dash["text"] = "Exit"
       self.bttn3_dash.config(height=3, width=30)
       self.bttn3_dash = Button(self, text= "Exit")

class student_dashboard(Frame):
      def __init__(self, master=None):
       super(main, self).__init__(master)
       self.grid()
       self.pack()
      def buttons_student():
       #create first button
       self.bttn1_student = Button(self, text = "View Highscores")
       self.bttn1_student.grid()
       self.bttn1_student.config(height=3, width=30)

       # create second button
       self.bttn2_student = Button(self)
       self.bttn2_student.grid()
       self.bttn2_student.configure(text = "Save Score")
       self.bttn2_student.config(height=3, width=30)

# main
root = Tk()
root.title("Dashboard")
app = main(root)
root.mainloop()
</code>```

答:
You can create a button in your main class with a command calling a function which contains a nested class and new tkinter frame then you'll have a nested top-level.</p>

```<code>import tkinter as tk
class main:
    def __init__(self, root1):
        self.root1=root1
        self.frame1=tk.Frame(root1)
        self.button_spawn_top=tk.Button(text="spawn_frame",
        command=self.new_window)
        self.button_spawn_top.grid(row=0,column=0)
        self.frame1.grid(row=0,column=0)
    def new_window(self):
        class NewWindow:
            def __init__(self, root2):
                self.root2=root2
                self.frame2=tk.Frame(root2)
                self.label2=tk.Label(text='new_window')
                self.label2.grid(row=0,column=0)
                self.frame2.grid(row=0,column=0)
        root2=tk.Toplevel()
        app2=NewWindow(root2)
root1=tk.Tk()
app1=main(root1)
root1.mainloop()
</code>```

Title: Python - GUI linking multiple Frames

Body:
Very new to working with GUI's so was wondering if someone could give me some guidance on how to link multiple frames so you can press a button to go to that frame.

If anyone has an ideas or suggestions that would be great!

from tkinter import *

class main(Frame):
   def __init__(self, master=None):
       super(main, self).__init__(master)
       self.grid()
       self.pack()
   def buttons_dash():
      # create first button
       self.bttn1_dash = Button(self, text = "Student Login",)
       self.bttn1_dash.grid()
       self.bttn1_dash.config(height=3, width=30)

       # create second button
       self.bttn2_dash = Button(self)
       self.bttn2_dash.grid()
       self.bttn2_dash.configure(text = "Staff Login")
       self.bttn2_dash.config(height=3, width=30)

       # create third button
       self.bttn3_dash = Button(self)
       self.bttn3_dash.grid()
       self.bttn3_dash["text"] = "Exit"
       self.bttn3_dash.config(height=3, width=30)
       self.bttn3_dash = Button(self, text= "Exit")

class student_dashboard(Frame):
      def __init__(self, master=None):
       super(main, self).__init__(master)
       self.grid()
       self.pack()
      def buttons_student():
       #create first button
       self.bttn1_student = Button(self, text = "View Highscores")
       self.bttn1_student.grid()
       self.bttn1_student.config(height=3, width=30)

       # create second button
       self.bttn2_student = Button(self)
       self.bttn2_student.grid()
       self.bttn2_student.configure(text = "Save Score")
       self.bttn2_student.config(height=3, width=30)

# main
root = Tk()
root.title("Dashboard")
app = main(root)
root.mainloop()

Body:
You can create a button in your main class with a command calling a function which contains a nested class and new tkinter frame then you'll have a nested top-level.

import tkinter as tk
class main:
    def __init__(self, root1):
        self.root1=root1
        self.frame1=tk.Frame(root1)
        self.button_spawn_top=tk.Button(text="spawn_frame",
        command=self.new_window)
        self.button_spawn_top.grid(row=0,column=0)
        self.frame1.grid(row=0,column=0)
    def new_window(self):
        class NewWindow:
            def __init__(self, root2):
                self.root2=root2
                self.frame2=tk.Frame(root2)
                self.label2=tk.Label(text='new_window')
                self.label2.grid(row=0,column=0)
                self.frame2.grid(row=0,column=0)
        root2=tk.Toplevel()
        app2=NewWindow(root2)
root1=tk.Tk()
app1=main(root1)
root1.mainloop()


问:
How to update a GemFire Region based on changes in some other Region
My retail application has various contexts like receive, transfer etc. The requests to these contexts are handled by RESTful microservices developed using Spring Boot. The persistence layer is Cassandra. This is shared by all services as we couldn't do a vertical scaling for microservices at DB level as the services are tightly coupled conceptually.

We want vertical scaling at GemFire end by creating different Regions for different contexts.

For example, a BOX table in Cassandra will be updated by Region Box-Receive(receive context) and Region Box-Transfer(transfer context) via CacheWriter.

Our problem is how to maintain data sync between these two Regions?
Please suggest any other approach also for separation at GemFire end.

gemfire version-

```<code><dependency>
        <groupId>com.gemstone.gemfire</groupId>
        <artifactId>gemfire</artifactId>
        <version>8.2.6</version>
</dependency>
</code>```

答:
You can use transactions. Something like this should work:

```<code>txMgr = cache.getTransactionManager();
txMgr.begin();
boxReceive.put();
...
boxtransfer.put();
txMgr.commit();
</code>```

This will work provided you co-locate the box-receive and the box-transfer region and use the same key, or use a PartitionResolver to colocate the data.

Body:
My retail application has various contexts like receive, transfer etc. The requests to these contexts are handled by RESTful microservices developed using Spring Boot. The persistence layer is Cassandra. This is shared by all services as we couldn't do a vertical scaling for microservices at DB level as the services are tightly coupled conceptually.

We want vertical scaling at GemFire end by creating different Regions for different contexts.

For example, a BOX table in Cassandra will be updated by Region Box-Receive(receive context) and Region Box-Transfer(transfer context) via CacheWriter.

Our problem is how to maintain data sync between these two Regions?
Please suggest any other approach also for separation at GemFire end.

gemfire version-

<dependency>
        <groupId>com.gemstone.gemfire</groupId>
        <artifactId>gemfire</artifactId>
        <version>8.2.6</version>
</dependency>

Body:
You can use transactions. Something like this should work:

txMgr = cache.getTransactionManager();
txMgr.begin();
boxReceive.put();
...
boxtransfer.put();
txMgr.commit();

This will work provided you co-locate the box-receive and the box-transfer region and use the same key, or use a PartitionResolver to colocate the data.


问:
Construct a Ruby object that returns the names of methods called on it
I want to construct a Ruby object that has the following property: For any method name, when that method name is passed to the object, the return value is the method name as a string.

Here is an attempt that has a few problems:

```<code>class Echo < BasicObject
  def self.method_missing(the_method)
    the_method.to_s
  end
end
</code>```

Echo responds to most method calls as desired:

```<code>> Echo.foo
 => "foo"
> Echo.send("Hello world.")
=> "Hello world."
</code>```

But Echo inherits from BasicObject and so it responds in the normal way to its superclass' methods:

```<code>> Echo.to_s
=> "Echo"
</code>```

How can I construct an object that always echoes back the messages its passed. (Bonus points if the solution doesn't require complex method lookups on every call.)

答:
How about:

```<code>class Echo
  class << self
    def method_missing(the_method)
      the_method.to_s
    end

    methods.each do |name|
      define_method(name) do |*any|
        name.to_s
      end
    end
  end
end
</code>```

Tests:

```<code>RSpec.describe Echo do
  it "returns a missing method as a string" do
    expect(described_class.some_method_that_doesnt_exist).
      to eq("some_method_that_doesnt_exist")
  end

  it "returns an existing method as a string" do
    expect(described_class.to_s).
      to eq("to_s")
  end
end
</code>```

Body:
I want to construct a Ruby object that has the following property: For any method name, when that method name is passed to the object, the return value is the method name as a string.

Here is an attempt that has a few problems:

class Echo < BasicObject
  def self.method_missing(the_method)
    the_method.to_s
  end
end

Echo responds to most method calls as desired:

> Echo.foo
 => "foo"
> Echo.send("Hello world.")
=> "Hello world."

But Echo inherits from BasicObject and so it responds in the normal way to its superclass' methods:

> Echo.to_s
=> "Echo"

How can I construct an object that always echoes back the messages its passed. (Bonus points if the solution doesn't require complex method lookups on every call.)

Body:
How about:

class Echo
  class << self
    def method_missing(the_method)
      the_method.to_s
    end

    methods.each do |name|
      define_method(name) do |*any|
        name.to_s
      end
    end
  end
end

Tests:

RSpec.describe Echo do
  it "returns a missing method as a string" do
    expect(described_class.some_method_that_doesnt_exist).
      to eq("some_method_that_doesnt_exist")
  end

  it "returns an existing method as a string" do
    expect(described_class.to_s).
      to eq("to_s")
  end
end


问:
VBA - Get cursor position as cell address
I have the following code which works fine for retrieving the cursor position as pixels:

```<code>Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
' Create custom variable that holds two integers
Type POINTAPI
    Xcoord As Long
    Ycoord As Long
End Type

Sub GetCursorPosDemo()
    Dim llCoord As POINTAPI
    ' Get the cursor positions
    GetCursorPos llCoord
    ' Display the cursor position coordinates
    MsgBox "X Position: " & llCoord.Xcoord & vbNewLine & "Y Position: " & llCoord.Ycoord
End Sub
</code>```

I'd like it to return the cell address on which my cursor currently is, or perhaps the coordinates in Points, so I can convert it to an address. Is that possible?

答:
Use ActiveWindow.RangeFromPoint to get the cell address.

```<code>Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
' Create custom variable that holds two integers
Type POINTAPI
    Xcoord As Long
    Ycoord As Long
End Type

Sub GetCursorPosDemo()
    Dim llCoord As POINTAPI
    Dim rng As Range
    ' Get the cursor positions
    GetCursorPos llCoord
    ' Display the cursor position coordinates
    'MsgBox "X Position: " & llCoord.Xcoord & vbNewLine & "Y Position: " & llCoord.Ycoord

    Set rng = GetRange(llCoord.Xcoord, llCoord.Ycoord)

    If Not rng Is Nothing Then
        MsgBox "Cell under mouse is :" & rng.Address
    Else
        MsgBox "Not a valid location."
    End If

End Sub

Function GetRange(x As Long, y As Long) As Range
    Set GetRange = ActiveWindow.RangeFromPoint(x, y)
End Function
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following code which works fine for retrieving the cursor position as pixels:

Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
' Create custom variable that holds two integers
Type POINTAPI
    Xcoord As Long
    Ycoord As Long
End Type

Sub GetCursorPosDemo()
    Dim llCoord As POINTAPI
    ' Get the cursor positions
    GetCursorPos llCoord
    ' Display the cursor position coordinates
    MsgBox "X Position: " & llCoord.Xcoord & vbNewLine & "Y Position: " & llCoord.Ycoord
End Sub

I'd like it to return the cell address on which my cursor currently is, or perhaps the coordinates in Points, so I can convert it to an address. Is that possible?

Body:
Use ActiveWindow.RangeFromPoint to get the cell address.

Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
' Create custom variable that holds two integers
Type POINTAPI
    Xcoord As Long
    Ycoord As Long
End Type

Sub GetCursorPosDemo()
    Dim llCoord As POINTAPI
    Dim rng As Range
    ' Get the cursor positions
    GetCursorPos llCoord
    ' Display the cursor position coordinates
    'MsgBox "X Position: " & llCoord.Xcoord & vbNewLine & "Y Position: " & llCoord.Ycoord

    Set rng = GetRange(llCoord.Xcoord, llCoord.Ycoord)

    If Not rng Is Nothing Then
        MsgBox "Cell under mouse is :" & rng.Address
    Else
        MsgBox "Not a valid location."
    End If

End Sub

Function GetRange(x As Long, y As Long) As Range
    Set GetRange = ActiveWindow.RangeFromPoint(x, y)
End Function


问:
trying to run repository impl with autowired candidates for testing
I was curious of there was a way for me to run a repository impl containing autowired candidates, with an application main() (for testing purposes).

i know the problem is that the repo class containing the main isn't being wired in the main() method, which is causing none of the autowired candidates to be wired but I'm having trouble finding the syntax to make this happen.

The sample code snippet is below, as well as comments in the section where I'm encountering the issue

```<code>@Repository
@Transactional
public class RepositoryImpl implements Repository {

    @Autowired
    JdbcTemplate jdbcTemplate;

    String query = "some query"

    @Override
    public boolean runQuery() {
        Object[] params = {param1, param2};
        boolean result = jdbcTemplate.queryForObject(query , params, Integer.class) == 1;
        return result;
    }

    //included just for testing purposes
    public static void main(String[] args) {
        /*this is where i would like to run runQuery() to see a sample output
        * something like this:
        * repositoryImpl = new RepositoryImpl();
        * syso(repositoryImpl.runQuery());
        */
    }
}
</code>```

I run into a null pointer which is coming from jdbc template not being wired properly. Could someone direct me as to how to autowire a class with a self contained application main()?

Is this even possible?

Thanks for your help!

答:
You can't autowire easily for static method (little hack).

The easiest way to test something is to... write a test ;)

```<code>@RunWith(SpringJUnit4ClassRunner.class)
public class RepositoryImplTest {

    @Autowired
    private Repository repository;

    @Test
    public void testJob() throws Exception {
        //when
        boolean val = repository.runQuery();

        Assert.assertTrue(val);
    }
}
</code>```

Check out Unit Testing section.

Body:
I was curious of there was a way for me to run a repository impl containing autowired candidates, with an application main() (for testing purposes).

i know the problem is that the repo class containing the main isn't being wired in the main() method, which is causing none of the autowired candidates to be wired but I'm having trouble finding the syntax to make this happen.

The sample code snippet is below, as well as comments in the section where I'm encountering the issue

@Repository
@Transactional
public class RepositoryImpl implements Repository {

    @Autowired
    JdbcTemplate jdbcTemplate;

    String query = "some query"

    @Override
    public boolean runQuery() {
        Object[] params = {param1, param2};
        boolean result = jdbcTemplate.queryForObject(query , params, Integer.class) == 1;
        return result;
    }

    //included just for testing purposes
    public static void main(String[] args) {
        /*this is where i would like to run runQuery() to see a sample output
        * something like this:
        * repositoryImpl = new RepositoryImpl();
        * syso(repositoryImpl.runQuery());
        */
    }
}

I run into a null pointer which is coming from jdbc template not being wired properly. Could someone direct me as to how to autowire a class with a self contained application main()?

Is this even possible?

Thanks for your help!

Body:
You can't autowire easily for static method (little hack).

The easiest way to test something is to... write a test ;)

@RunWith(SpringJUnit4ClassRunner.class)
public class RepositoryImplTest {

    @Autowired
    private Repository repository;

    @Test
    public void testJob() throws Exception {
        //when
        boolean val = repository.runQuery();

        Assert.assertTrue(val);
    }
}

Check out Unit Testing section.


问:
isMinifyEnabled() is deprecated. What is the alternative?
I use the below code to automatically generate pro guard mapping file apparently according to product flavors.

```<code>buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

            applicationVariants.all { variant ->
                if (variant.getBuildType().isMinifyEnabled()) {
                    variant.assemble.doLast {
                        copy {
                            from variant.mappingFile
                            into "${rootDir}/proguardTools"
                            rename { String fileName ->
                                "mapping-${variant.name}.txt"
                            }
                        }
                    }
                }
            }

        }
    }
</code>```

After upgrading android studio to 3.0 it shows a warning saying isMinifyEnabled() is Deprecated and I could not find any solution or an alternative for this isMinifyEnabled(). Any help thanks in advance?

答:
From the sources of Android Gradle Plugin 3.0:

```
<code>
    /**
     * Returns whether minification is enabled for this build type.
     *
     * @return true if minification is enabled.
     * @deprecated remember that this flag means that some "ProGuard-like" tool has run, it does not
     *     say if the tool was used to obfuscate and/or minify. In build system code this
     *     information is available elsewhere and should be used instead of this method.
     */
    @Deprecated
    boolean isMinifyEnabled();
</code>
```

This documentation is vague and does not directly tell what to use instead.
In the blame we can see, that it's Michał Bendowski that has performed those changes, from whom I have asked to help out with that question in twitter. Here's the reply:

Also I cannot see @Deprecated annotation in the latest commit (at the time of writing this it's android-8.0.0_r34), which means, that the API is not deprecated there.

As a fix, you can suppress that warning putting this line before if statement:

```
<code>
    //noinspection GrDeprecatedAPIUsage
    if (variant.getBuildType().isMinifyEnabled()) {
        ...
    }
</code>
```

Body:
I use the below code to automatically generate pro guard mapping file apparently according to product flavors.

buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

            applicationVariants.all { variant ->
                if (variant.getBuildType().isMinifyEnabled()) {
                    variant.assemble.doLast {
                        copy {
                            from variant.mappingFile
                            into "${rootDir}/proguardTools"
                            rename { String fileName ->
                                "mapping-${variant.name}.txt"
                            }
                        }
                    }
                }
            }

        }
    }

After upgrading android studio to 3.0 it shows a warning saying isMinifyEnabled() is Deprecated and I could not find any solution or an alternative for this isMinifyEnabled(). Any help thanks in advance?

Body:
From the sources of Android Gradle Plugin 3.0:

    /**
     * Returns whether minification is enabled for this build type.
     *
     * @return true if minification is enabled.
     * @deprecated remember that this flag means that some "ProGuard-like" tool has run, it does not
     *     say if the tool was used to obfuscate and/or minify. In build system code this
     *     information is available elsewhere and should be used instead of this method.
     */
    @Deprecated
    boolean isMinifyEnabled();

This documentation is vague and does not directly tell what to use instead.
In the blame we can see, that it's Michał Bendowski that has performed those changes, from whom I have asked to help out with that question in twitter. Here's the reply:

Also I cannot see @Deprecated annotation in the latest commit (at the time of writing this it's android-8.0.0_r34), which means, that the API is not deprecated there.

As a fix, you can suppress that warning putting this line before if statement:

    //noinspection GrDeprecatedAPIUsage
    if (variant.getBuildType().isMinifyEnabled()) {
        ...
    }


问:
RecyclerView onClick for multiple buttons and handling from Activity
I'm using RecyclerView with CardView and inside the CardView have 2 buttons. Now, have implemented the onClick events by implementing View.OnClickListener by the ViewHolder static class and overriding the event (its working )like

```<code>    @Override
    public void onClick(View v) {

        if (v.getId() == mClassBtn.getId()){

        }
        else if (v.getId() == mDaysBtn.getId()){

        }
     }
</code>```

Looking for a solution/pattern to handle the Click in the Activity class like

```<code>adapter = new ItemsListAdapter(getActivity(), data, new CustomItemClickListener() {

    @override
    public void onItemClick(View v, int position) {

       Log.d(TAG, "clicked position:" + position);
       // which button clicked and separate action for each button
    }
});
// CustomItemClickListener -- interface in the adapter class which holds the click event .
</code>```

The above code working fine and able to log the Clicks but not able to differentiate which button has clicked.

Appreciate any help

答:
I do it this way.

Set an OnClickListener on your Button in the ViewHolder

Create a method in your activity with the button position as a parameter

Pass the position of the clicked entry and do stuff

ViewHolder

```<code>yourButton.setOnClickListener(new View.OnClickListener()
{
     @Override
     public void onClick(View v)
     {

        int position = getAdapterPosition(); //Clicked entry in your List

        //Method from your activity
        yourActivity.methodOnBtnClick(position);
     }
</code>```

Activity

```<code>public void methodOnBtnClick(int position)
{
    yourList.remove(position);
    recycler.getAdapter().notifyDataSetChanged();
}
</code>```

Body:
I'm using RecyclerView with CardView and inside the CardView have 2 buttons. Now, have implemented the onClick events by implementing View.OnClickListener by the ViewHolder static class and overriding the event (its working )like

    @Override
    public void onClick(View v) {

        if (v.getId() == mClassBtn.getId()){

        }
        else if (v.getId() == mDaysBtn.getId()){

        }
     }

Looking for a solution/pattern to handle the Click in the Activity class like

adapter = new ItemsListAdapter(getActivity(), data, new CustomItemClickListener() {

    @override
    public void onItemClick(View v, int position) {

       Log.d(TAG, "clicked position:" + position);
       // which button clicked and separate action for each button
    }
});
// CustomItemClickListener -- interface in the adapter class which holds the click event .

The above code working fine and able to log the Clicks but not able to differentiate which button has clicked.

Appreciate any help

Body:
I do it this way.

Set an OnClickListener on your Button in the ViewHolder

Create a method in your activity with the button position as a parameter

Pass the position of the clicked entry and do stuff

ViewHolder

yourButton.setOnClickListener(new View.OnClickListener()
{
     @Override
     public void onClick(View v)
     {

        int position = getAdapterPosition(); //Clicked entry in your List

        //Method from your activity
        yourActivity.methodOnBtnClick(position);
     }

Activity

public void methodOnBtnClick(int position)
{
    yourList.remove(position);
    recycler.getAdapter().notifyDataSetChanged();
}


问:
how do I get access to the object that I'm intercepting?
I'm using Castle Core to create a custom attribute and interceptor to inject security checks into our code using attributes.
e.g. [Security("Role1")]

In the implementation of the interceptor:

```<code>public class SecurityInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        object o;

        MethodInfo mi = invocation.Method;
        SecurityAttribute[] atts = (SecurityAttribute[])mi.GetCustomAttributes(typeof(SecurityAttribute), true);

        // if method not marked with Security attribute, then pass on call
        if (atts.Length == 0)
        {
            invocation.Proceed();
        }
        else
        {
            //for now assume that there is only one security attribute on the method
            //do some security test
            {
                invocation.Proceed();
            }
        }

    }
</code>```

In the "do some security test" section above, I need access to the HttpContext.Session object in order to retrieve some saved objects to do the security test.

Assume the method that this attribute is on, is a code-behind asp.net page, i.e an instance of the Page class)
I can't just use this.Context in the attribute like this [Security("Role1", this.Context)]
as attributes don't allow that.

So how do I get access to the httpContext inside the Intercept method?

Or is there a better way of doing this in an aspect-like way?

答: You can use HttpContext.Current.Session from anywhere so long as the code is being called from an ASP.net process.

Body:
I'm using Castle Core to create a custom attribute and interceptor to inject security checks into our code using attributes.
e.g. [Security("Role1")]

In the implementation of the interceptor:

public class SecurityInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        object o;

        MethodInfo mi = invocation.Method;
        SecurityAttribute[] atts = (SecurityAttribute[])mi.GetCustomAttributes(typeof(SecurityAttribute), true);

        // if method not marked with Security attribute, then pass on call
        if (atts.Length == 0)
        {
            invocation.Proceed();
        }
        else
        {
            //for now assume that there is only one security attribute on the method
            //do some security test
            {
                invocation.Proceed();
            }
        }

    }

In the "do some security test" section above, I need access to the HttpContext.Session object in order to retrieve some saved objects to do the security test.

Assume the method that this attribute is on, is a code-behind asp.net page, i.e an instance of the Page class)
I can't just use this.Context in the attribute like this [Security("Role1", this.Context)]
as attributes don't allow that.

So how do I get access to the httpContext inside the Intercept method?

Or is there a better way of doing this in an aspect-like way?


问:
MySQL: Counting number of staff
I'm very new to programming in sql and I'm having an issue with a question.

I have to find the department with the largest number of staff, and I'm not at all sure how to do it.

The tables i can use are

I think the end result would have the columns, Department_no and Max(Count(Department_no)) but I'm not sure how I'd get this? Or is there a simpler way that I'm just not seeing?

EDIT So far I have

SELECT Department_no, Count(Department_no)
 FROM ManagerOrBoss
 GROUP BY Department_no;

But I ideally want to find the maximum of the count, but SQL keeps giving a 'Invalid use of group function error'.

答:
Some more database-inclined folks may be able to tell us why this is a very bad idea, but to get the deparment(s) with the highest number of members I would do something like:

```<code>SELECT Department_no, COUNT(Staff_id) TheCount
FROM ManagerOrBoss
GROUP BY Department_no
HAVING TheCount = (
    SELECT MAX(Num)
    FROM (
        SELECT Department_no, COUNT(Staff_id) Num
        FROM ManagerOrBoss
        GROUP BY Department_no
    ) as A
)
</code>```

Apologies if my syntax is a bit off. I usually work in MSSQL, but tried to adapt this to MySQL.

Title: MySQL: Counting number of staff

Body:
Some more database-inclined folks may be able to tell us why this is a very bad idea, but to get the deparment(s) with the highest number of members I would do something like:

SELECT Department_no, COUNT(Staff_id) TheCount
FROM ManagerOrBoss
GROUP BY Department_no
HAVING TheCount = (
    SELECT MAX(Num)
    FROM (
        SELECT Department_no, COUNT(Staff_id) Num
        FROM ManagerOrBoss
        GROUP BY Department_no
    ) as A
)

Apologies if my syntax is a bit off. I usually work in MSSQL, but tried to adapt this to MySQL.


问:
Is it more efficient to limit a union query before limiting the total results?

Setup

I am joining several tables to filter e-mail addresses in an autocomplete from several sources. I only include 2 in this example for simplicity but I'm actually using 6 at the moment.

Using SQL Server 2008.

Current Query

```<code>SELECT TOP 20 * FROM (
  SELECT
    ID AS id,
    LastName + ', ' + FirstName AS label,
    Email AS identifier,
    'person' AS source_type
  FROM Persons
  WHERE (LastName + ', ' + FirstName LIKE 'a%' OR FirstName + ' ' + LastName LIKE 'a%')
    AND DATALENGTH(Email) > 0 AND Email IS NOT NULL
UNION
  SELECT
    Company AS id,
    Name AS label,
    Email AS identifier,
    'company' AS source_type
  FROM Companies
  WHERE (Name LIKE 'a%')
    AND DATALENGTH(Email) > 0 AND Email IS NOT NULL
) temp ORDER BY label ASC
</code>```

Question

Would it be more efficient or more performant to pre-order & limit the union queries? Something like:

```<code>SELECT TOP 20 * FROM (
  SELECT TOP 20
    ID AS id,
    LastName + ', ' + FirstName AS label,
    Email AS identifier,
    'person' AS source_type
  FROM Persons
  WHERE (LastName + ', ' + FirstName LIKE 'a%' OR FirstName + ' ' + LastName LIKE 'a%')
    AND DATALENGTH(Email) > 0 AND Email IS NOT NULL
  ORDER BY LastName ASC, FirstName ASC
UNION
  SELECT TOP 20
    ID AS id,
    Name AS label,
    Email AS identifier,
    'company' AS source_type
  FROM Companies
  WHERE (Name LIKE 'a%')
    AND DATALENGTH(Email) > 0 AND Email IS NOT NULL
  ORDER BY Name ASC
) temp ORDER BY label ASC
</code>```

答:
Absolutely with UNION.

UNION incurs overhead for removing duplicates -- this is either a hash-based or sort-based duplicate removal algorithm.  Either way, fewer records going in is faster.

The situation is a bit different with UNION ALL.  SQL Server is pretty good about pushing predicates down from the outer query into the inner subqueries.  However, sometimes the subqueries can take advantage of indexes (or even partitioning) and including logic in the subqueries makes it simpler for the optimizer to find such improvements.

Body:
Setup

I am joining several tables to filter e-mail addresses in an autocomplete from several sources. I only include 2 in this example for simplicity but I'm actually using 6 at the moment.

Using SQL Server 2008.

Current Query

SELECT TOP 20 * FROM (
  SELECT
    ID AS id,
    LastName + ', ' + FirstName AS label,
    Email AS identifier,
    'person' AS source_type
  FROM Persons
  WHERE (LastName + ', ' + FirstName LIKE 'a%' OR FirstName + ' ' + LastName LIKE 'a%')
    AND DATALENGTH(Email) > 0 AND Email IS NOT NULL
UNION
  SELECT
    Company AS id,
    Name AS label,
    Email AS identifier,
    'company' AS source_type
  FROM Companies
  WHERE (Name LIKE 'a%')
    AND DATALENGTH(Email) > 0 AND Email IS NOT NULL
) temp ORDER BY label ASC

Question

Would it be more efficient or more performant to pre-order & limit the union queries? Something like:

SELECT TOP 20 * FROM (
  SELECT TOP 20
    ID AS id,
    LastName + ', ' + FirstName AS label,
    Email AS identifier,
    'person' AS source_type
  FROM Persons
  WHERE (LastName + ', ' + FirstName LIKE 'a%' OR FirstName + ' ' + LastName LIKE 'a%')
    AND DATALENGTH(Email) > 0 AND Email IS NOT NULL
  ORDER BY LastName ASC, FirstName ASC
UNION
  SELECT TOP 20
    ID AS id,
    Name AS label,
    Email AS identifier,
    'company' AS source_type
  FROM Companies
  WHERE (Name LIKE 'a%')
    AND DATALENGTH(Email) > 0 AND Email IS NOT NULL
  ORDER BY Name ASC
) temp ORDER BY label ASC


问:
assembly max and min procedure not producing expected result
I am trying to write an assembly program that finds the min and max of an array using a procedure (max_min). The array ends with a zero telling the program the end of the array has been reached.

The results should be as follows:
for Numbers DW 3,4,5,2,6,0
max:6
min:2

However the result I receive is
max 6:
min 0:

Lp2 - loop 2 is supposed to find the minimum and it should give 2 as a result. However, it doesn't, it gives 0 as the result. How do I correct this so that I get 2 as the minimum?

```<code>%include "io.mac"
.STACK 100H

.DATA
   Numbers DW 3,4,5,2,6,0
   msg1  db "Max",0
   msg2  db "Min",0

.CODE
.STARTUP
    call max_min

    nwln
    PutStr msg1
    nwln
    PutInt ax
    nwln
    PutStr msg2
    nwln
    PutInt bx
    done:
.EXIT

max_min:
    mov si, Numbers ;point to array
    mov ax, si
lp1:
    cmp word [si],0
    je next
    add si,2
    cmp ax, [si]
    jl max

continue:
    jmp lp1

next:
    mov si, Numbers ;point to array
    mov bx, si
lp2:
    cmp word [si],0
    je complete
    add si,2
    cmp bx, [si]
    jg min
go:
    jmp lp2

max:
    mov ax, [si]  ;keep track of max
    jmp continue

min:
    mov bx, [si]  ;keep track of min
    PutInt[si]
    jmp go

complete:
    ret
</code>```

答:
I am committing a grave sin here - blind coding one of my weaker assembler languages without compiling/assembling or testing.  Please use this as a reference to my above comment on how to organize your code in a simpler to understand and maintain format.  Even if there are bugs here, it demonstrates the idea of breaking up the code into manageable chunks and use of comments to explain what is going on. (Editorial note: x86 assembler is ugly! I want my ARM code back :)  )</p>

```<code>
max_min:
    mov si, Numbers ;point to array

    ; Set Min/Max to first array entry and exit if value is 0
    mov ax, [si]
    mov bx, [si]
    cmp word [si],0
    je  done

    ; Increment to next value
    add si,2

main_loop:
    ; if number is 0, we are done
    cmp word [si],0
    je done

    ; if number is greater than or equal to max, don't assign to ax
    cmp ax, [si]
    jge not_max

    mov ax, [si]

not_max:
    ; if number is less than or equal to min, don't assign to bx
    cmp bx, [si]
    jle not_min

    mov bx, [si]

not_min:
    ; Next array entry and loop
    add si,2
    jmp main_loop

done:
    ret
</code>```

Body:
I am trying to write an assembly program that finds the min and max of an array using a procedure (max_min). The array ends with a zero telling the program the end of the array has been reached.

The results should be as follows:
for Numbers DW 3,4,5,2,6,0
max:6
min:2

However the result I receive is
max 6:
min 0:

Lp2 - loop 2 is supposed to find the minimum and it should give 2 as a result. However, it doesn't, it gives 0 as the result. How do I correct this so that I get 2 as the minimum?

%include "io.mac"
.STACK 100H

.DATA
   Numbers DW 3,4,5,2,6,0
   msg1  db "Max",0
   msg2  db "Min",0

.CODE
.STARTUP
    call max_min

    nwln
    PutStr msg1
    nwln
    PutInt ax
    nwln
    PutStr msg2
    nwln
    PutInt bx
    done:
.EXIT

max_min:
    mov si, Numbers ;point to array
    mov ax, si
lp1:
    cmp word [si],0
    je next
    add si,2
    cmp ax, [si]
    jl max

continue:
    jmp lp1

next:
    mov si, Numbers ;point to array
    mov bx, si
lp2:
    cmp word [si],0
    je complete
    add si,2
    cmp bx, [si]
    jg min
go:
    jmp lp2

max:
    mov ax, [si]  ;keep track of max
    jmp continue

min:
    mov bx, [si]  ;keep track of min
    PutInt[si]
    jmp go

complete:
    ret

Body:
I am committing a grave sin here - blind coding one of my weaker assembler languages without compiling/assembling or testing.  Please use this as a reference to my above comment on how to organize your code in a simpler to understand and maintain format.  Even if there are bugs here, it demonstrates the idea of breaking up the code into manageable chunks and use of comments to explain what is going on. (Editorial note: x86 assembler is ugly! I want my ARM code back :)  )

max_min:
    mov si, Numbers ;point to array

    ; Set Min/Max to first array entry and exit if value is 0
    mov ax, [si]
    mov bx, [si]
    cmp word [si],0
    je  done

    ; Increment to next value
    add si,2

main_loop:
    ; if number is 0, we are done
    cmp word [si],0
    je done

    ; if number is greater than or equal to max, don't assign to ax
    cmp ax, [si]
    jge not_max

    mov ax, [si]

not_max:
    ; if number is less than or equal to min, don't assign to bx
    cmp bx, [si]
    jle not_min

    mov bx, [si]

not_min:
    ; Next array entry and loop
    add si,2
    jmp main_loop

done:
    ret


问:
I need checkboxes to save their state whn i go out of app or the activity
So i need checkboxes to save state when i exit or switch activity. I need many checkboxes, so I need a function that works for all the checkboxes.
please help.</p>

答:
the simple solution is to use SharedPreferences,
you can read about it here

Code

create these 2 methods in your activity :

```<code>private void saveCheckboxesStates(){
SharedPreferences sharedPref =getActivity().getSharedPreferences("fileName",Context.MODE_PRIVATE);//replace fileName with any name you like
SharedPreferences.Editor editor = sharedPref.edit();
//suppose we have 3 checkboxes that we want to save their states
editor.putBoolean("checkbox1_state", checkBox1.isChecked()));
editor.putBoolean("checkbox2_state", checkBox2.isChecked()));
editor.putBoolean("checkbox3_state", checkBox3.isChecked()));
editor.apply();
</code>```

}

```<code>private void loadCheckboxesStates(){
SharedPreferences sharedPref = getActivity().getSharedPreferences("fileName",Context.MODE_PRIVATE);
boolean checkbox1State= sharedPref.getBoolean("checkbox1_state", false);
boolean checkbox2State= sharedPref.getBoolean("checkbox2_state", false);
boolean checkbox3State= sharedPref.getBoolean("checkbox3_state", false);
checkBox1.setChecked(checkbox1State);
checkBox2.setChecked(checkbox2State);
checkBox3.setChecked(checkbox3State);
</code>```

}

now override onBackPressed and onDestroy methods and call saveCheckboxesStates like that:

```<code>@Override
public void onBackPressed() {
    super.onBackPressed();
    saveCheckboxesStates();
}//this handle the case when the user clicks back the activity

@Override
public void onDestroy () {
    super.onDestroy();
    saveCheckboxesStates();
}//this handle the case when your app gets killed
</code>```

then call the method loadCheckboxesStates in your onCreate method and you are done.

Body:
the simple solution is to use SharedPreferences,
you can read about it here

Code

create these 2 methods in your activity :

private void saveCheckboxesStates(){
SharedPreferences sharedPref =getActivity().getSharedPreferences("fileName",Context.MODE_PRIVATE);//replace fileName with any name you like
SharedPreferences.Editor editor = sharedPref.edit();
//suppose we have 3 checkboxes that we want to save their states
editor.putBoolean("checkbox1_state", checkBox1.isChecked()));
editor.putBoolean("checkbox2_state", checkBox2.isChecked()));
editor.putBoolean("checkbox3_state", checkBox3.isChecked()));
editor.apply();

}

private void loadCheckboxesStates(){
SharedPreferences sharedPref = getActivity().getSharedPreferences("fileName",Context.MODE_PRIVATE);
boolean checkbox1State= sharedPref.getBoolean("checkbox1_state", false);
boolean checkbox2State= sharedPref.getBoolean("checkbox2_state", false);
boolean checkbox3State= sharedPref.getBoolean("checkbox3_state", false);
checkBox1.setChecked(checkbox1State);
checkBox2.setChecked(checkbox2State);
checkBox3.setChecked(checkbox3State);

}

now override onBackPressed and onDestroy methods and call saveCheckboxesStates like that:

@Override
public void onBackPressed() {
    super.onBackPressed();
    saveCheckboxesStates();
}//this handle the case when the user clicks back the activity

@Override
public void onDestroy () {
    super.onDestroy();
    saveCheckboxesStates();
}//this handle the case when your app gets killed

then call the method loadCheckboxesStates in your onCreate method and you are done.


问:
struts-2.5.13 - conversion.impl.XWorkConverter.convertValue conversion error for locale fr_FR
I am getting an error:

Unparseable number: "10.00" at position 2

Here the value 10 entered in text field(UI). The same working fine with locale en_US.

Log trace :

com.opensymphony.xwork2.XWorkException: Unparseable number: "10.00" at position 2
    at com.opensymphony.xwork2.conversion.impl.NumberConverter.convertToDouble(NumberConverter.java:108) ~[struts2-core-2.5.13.jar:2.5.13]
    at com.opensymphony.xwork2.conversion.impl.NumberConverter.convertValue(NumberConverter.java:29) ~[struts2-core-2.5.13.jar:2.5.13]
    at com.opensymphony.xwork2.conversion.impl.NumberConverter.convertValue(NumberConverter.java:65) ~[struts2-core-2.5.13.jar:2.5.13]
    at com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.doConvertToNumber(XWorkBasicConverter.java:205) ~[struts2-core-2.5.13.jar:2.5.13]
    at com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.convertValue(XWorkBasicConverter.java:108) ~[struts2-core-2.5.13.jar:2.5.13]
    at com.opensymphony.xwork2.conversion.impl.XWorkConverter.convertValue(XWorkConverter.java:311) [struts2-core-2.5.13.jar:2.5.13]
    at com.opensymphony.xwork2.ognl.OgnlTypeConverterWrapper.convertValue(OgnlTypeConverterWrapper.java:39) [struts2-core-2.5.13.jar:2.5.13]
    at ognl.OgnlRuntime.getConvertedType(OgnlRuntime.java:1218) [ognl-3.1.15.jar:?]
    at ognl.OgnlRuntime.getConvertedTypes(OgnlRuntime.java:1235) [ognl-3.1.15.jar:?]

答:
The error is obvious since France belongs to the countries using Arabic numerals with decimal comma

```<code>String number = "20,981";
try {
    double dNumber = Double.parseDouble(number.replace('.', ','));
    System.out.println("My double is " + dNumber);
} catch (NumberFormatException nfe) {
    System.out.println("I got exception for invalid string " + number);
}
</code>```

You may also like to enforce a specific number format:

```<code>NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();
</code>```

Body:
The error is obvious since France belongs to the countries using Arabic numerals with decimal comma

String number = "20,981";
try {
    double dNumber = Double.parseDouble(number.replace('.', ','));
    System.out.println("My double is " + dNumber);
} catch (NumberFormatException nfe) {
    System.out.println("I got exception for invalid string " + number);
}

You may also like to enforce a specific number format:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();


问:
Passing imageView to new activity imageView
Currently, my app allows the user to click on a "default avatar pic" and then select from a group of images. This image is then returned to the first activity via "startActivityForResult". My next task is to take the image that is now set in the first activity and send it to a third activity when the user presses the "submit button". Right now, I'm trying the below code, but it's not working as I don't know which image is going to be selected by the user until it's selected. Can anyone help me out here?</p>

```<code>    findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.select_avatar);
            intent.putExtra("IMAGE", bitmap);
            startActivity(intent);
        }
    });

             //second activity
             Bitmap bitmap = intent.getParcelableExtra("Bitmap");
             imageViewAvatar.findViewById(R.id.imageViewFinalAvatar);
             imageViewAvatar.setImageBitmap(bitmap);
</code>```

答:
You can just simply use the ImageView Id as a integer or string value, then pass it. No need to use any bitmap. Bitmap takes too much memory.
Image should be work as a resource id if the image is selected from your resource folder. If your image comes from cloud, then definitely have a url as a string. So handle it as a string as resource id/file path/url.

```<code>int imageID = R.drawable.select_avatar;

findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
            intent.putInt("image_id", imageID); // Integer Value
            startActivity(intent);
        }
    });

//second activity
Intent intent = getIntent();
int imageIdValue = intent.getIntExtra("image_id", 0);

imageViewAvatar.setImageResource(0);
imageViewAvatar.setImageResource(imageIdValue);
</code>```

Body:
Currently, my app allows the user to click on a "default avatar pic" and then select from a group of images. This image is then returned to the first activity via "startActivityForResult". My next task is to take the image that is now set in the first activity and send it to a third activity when the user presses the "submit button". Right now, I'm trying the below code, but it's not working as I don't know which image is going to be selected by the user until it's selected. Can anyone help me out here?

    findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.select_avatar);
            intent.putExtra("IMAGE", bitmap);
            startActivity(intent);
        }
    });

             //second activity
             Bitmap bitmap = intent.getParcelableExtra("Bitmap");
             imageViewAvatar.findViewById(R.id.imageViewFinalAvatar);
             imageViewAvatar.setImageBitmap(bitmap);

Body:
You can just simply use the ImageView Id as a integer or string value, then pass it. No need to use any bitmap. Bitmap takes too much memory.
Image should be work as a resource id if the image is selected from your resource folder. If your image comes from cloud, then definitely have a url as a string. So handle it as a string as resource id/file path/url.

int imageID = R.drawable.select_avatar;

findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
            intent.putInt("image_id", imageID); // Integer Value
            startActivity(intent);
        }
    });

//second activity
Intent intent = getIntent();
int imageIdValue = intent.getIntExtra("image_id", 0);

imageViewAvatar.setImageResource(0);
imageViewAvatar.setImageResource(imageIdValue);


问:
Python elegant assignment based on True/False values
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

```<code>if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'
</code>```

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

```<code>name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]
</code>```

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

```<code>name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')
</code>```

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

答:
Since your getting all the combinations, you could create an index based on the values like this:

```<code>def value(a,b,c ):
   values = ['8th','7th','6th','5th','4th','3rd','2nd','1st']
   index = ( 4 if a else 0 ) + ( 2 if b else 0 ) + ( 1 if c else 0 )
   return values[index]

if __name__ == "__main__":
   print value(True,  True,  True )
   print value(True,  True,  False )
   print value(True,  False, True )
   print value(True,  False, False )
   print value(False, True,  True )
   print value(False, True,  False)
   print value(False, False, True )
   print value(False, False, False)
</code>```

output:

```<code>1st
2nd
3rd
4th
5th
6th
7th
8th
</code>```

Body:
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

Body:
Since your getting all the combinations, you could create an index based on the values like this:

def value(a,b,c ):
   values = ['8th','7th','6th','5th','4th','3rd','2nd','1st']
   index = ( 4 if a else 0 ) + ( 2 if b else 0 ) + ( 1 if c else 0 )
   return values[index]

if __name__ == "__main__":
   print value(True,  True,  True )
   print value(True,  True,  False )
   print value(True,  False, True )
   print value(True,  False, False )
   print value(False, True,  True )
   print value(False, True,  False)
   print value(False, False, True )
   print value(False, False, False)

output:

1st
2nd
3rd
4th
5th
6th
7th
8th


问:
angular 4 material finding tab index from tab header
i have a standard mat-tab with a difference that they are rendered dynamically based on a list of array. something like below:

```<code> <mat-tab-group>
                  <mat-tab *ngFor="let tb of dynTabs">
                        <ng-template mat-tab-label>
                              {{tb.label}}  <mat-icon (click)="removeTab($event)">close</mat-icon>
                        </ng-template>
                        <!-- tab content area -->
                        <div>
                              my blaw blaw contents
                        </div>
                  </mat-tab>
            </mat-tab-group>
</code>```

the .ts has following

```<code>     this.dynTabs.push(
          {"label": "Opportunities"},
     {"label": "Opportunities1"},
     {"label": "Opportunities2"}
        );

removeTab(ev){
    console.log(ev)
  }
</code>```

my questions is as i might hit the close icon even if the tab is not selected so how do i find the index of the tab whose close icon is clicked?

答:
You can pass the tb into the (click) handler in the following way:

```<code><mat-tab *ngFor="let tb of dynTabs">
    <ng-template mat-tab-label>
         {{tb.label}}  <mat-icon (click)="removeTab(tb)">close</mat-icon>
    </ng-template>
    <!-- tab content area -->
    <div>
        my blaw blaw contents
    </div>
</mat-tab>
</code>```

You can also pass index in the following way:

```<code><mat-tab *ngFor="let tb of dynTabs; let i=index">
    <ng-template mat-tab-label>
         {{tb.label}}  <mat-icon (click)="removeTab(i)">close</mat-icon>
    </ng-template>
    <!-- tab content area -->
    <div>
        my blaw blaw contents
    </div>
</mat-tab>
</code>```

You can still pass $event in both cases in the following way:

```<code><mat-tab *ngFor="let tb of dynTabs">
    <ng-template mat-tab-label>
         {{tb.label}}  <mat-icon (click)="removeTab(tb, $event)">close</mat-icon>
    </ng-template>
    <!-- tab content area -->
    <div>
        my blaw blaw contents
    </div>
</mat-tab>
</code>```

Body:
i have a standard mat-tab with a difference that they are rendered dynamically based on a list of array. something like below:

 <mat-tab-group>
                  <mat-tab *ngFor="let tb of dynTabs">
                        <ng-template mat-tab-label>
                              {{tb.label}}  <mat-icon (click)="removeTab($event)">close</mat-icon>
                        </ng-template>

                              my blaw blaw contents

                  </mat-tab>
            </mat-tab-group>

the .ts has following

     this.dynTabs.push(
          {"label": "Opportunities"},
     {"label": "Opportunities1"},
     {"label": "Opportunities2"}
        );

removeTab(ev){
    console.log(ev)
  }

my questions is as i might hit the close icon even if the tab is not selected so how do i find the index of the tab whose close icon is clicked?

Body:
You can pass the tb into the (click) handler in the following way:

<mat-tab *ngFor="let tb of dynTabs">
    <ng-template mat-tab-label>
         {{tb.label}}&nbsp;&nbsp;<mat-icon (click)="removeTab(tb)">close</mat-icon>
    </ng-template>
    <!-- tab content area -->
    <div>
        my blaw blaw contents
    </div>
</mat-tab>

You can also pass index in the following way:

<mat-tab *ngFor="let tb of dynTabs; let i=index">
    <ng-template mat-tab-label>
         {{tb.label}}&nbsp;&nbsp;<mat-icon (click)="removeTab(i)">close</mat-icon>
    </ng-template>
    <!-- tab content area -->
    <div>
        my blaw blaw contents
    </div>
</mat-tab>

You can still pass $event in both cases in the following way:

<mat-tab *ngFor="let tb of dynTabs">
    <ng-template mat-tab-label>
         {{tb.label}}&nbsp;&nbsp;<mat-icon (click)="removeTab(tb, $event)">close</mat-icon>
    </ng-template>
    <!-- tab content area -->
    <div>
        my blaw blaw contents
    </div>
</mat-tab>


问:
matplotlib.backends.backend_qt5 vs from matplotlib.backends.backend_qt5agg
What is the difference between

matplotlib.backends.backend_qt5

and

matplotlib.backends.backend_qt5agg?

It seems like they have somethings in common.

For example,

```<code>from matplotlib.backends.backend_qt5 import NavigationToolbar2QT as Navi_qt5
</code>```

and

```<code>from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as Navi_qt5agg
</code>```

import the same method as shown by using

```<code>id(Navi_qt5)
</code>```

and

```<code>id(Navi_qt5agg)
</code>```

答:
While there is a difference between backend_qt5 and backend_qt5agg, the Navigation toolbar is the same in both cases. I.e. backend_qt5agg simply imports the NavigationToolbar2QT from backend_qt5.

The difference between the two backends backend_qt5 and backend_qt5agg lies in the figure canvas. matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg subclasses matplotlib.backends.backend_qt5.FigureCanvasQT and adds the Agg feature to it, which is the antigrain (agg) rendering. So essentially you cannot draw a figure with the FigureCanvasQT alone.

Hence, always use

```<code>matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg
</code>```

Body:
What is the difference between

matplotlib.backends.backend_qt5

and

matplotlib.backends.backend_qt5agg?

It seems like they have somethings in common.

For example,

from matplotlib.backends.backend_qt5 import NavigationToolbar2QT as Navi_qt5

and

from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as Navi_qt5agg

import the same method as shown by using

id(Navi_qt5)

and

id(Navi_qt5agg)

Body:
While there is a difference between backend_qt5 and backend_qt5agg, the Navigation toolbar is the same in both cases. I.e. backend_qt5agg simply imports the NavigationToolbar2QT from backend_qt5.

The difference between the two backends backend_qt5 and backend_qt5agg lies in the figure canvas. matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg subclasses matplotlib.backends.backend_qt5.FigureCanvasQT and adds the Agg feature to it, which is the antigrain (agg) rendering. So essentially you cannot draw a figure with the FigureCanvasQT alone.

Hence, always use

matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg


问:
jQuery Ajax setTimeout being random
I have the following code that lets me get data from ajax.php and display it in a div. It is supposed to display information for 3 seconds and then hide the #ajax-content and display #welcome-content

However, although most of the time it works and seems to be 3 seconds, occasionally it would randomly be much shorter. A few times it did not even feel like 1 second.

Have I done something wrong? or is there a way to fix this?

```<code>$('#user_id').on('change', function() {
$('#user_id').focus();
id = $("#user_id").val();
$.post("ajax.php", { username:id } ,function(data){
    $("#welcome-content").hide();
    $("#ajax-content").show();
    $("#ajax-content").html(data);
        setTimeout(
           function(){
            $("#ajax-content").hide();
            $("#welcome-content").show();
           },
           3000
        );
});
</code>```

答:
As you can see in following snippet, it executes in perfect time + ~2-5 ms.

You can fit in few timing logs to check what is executing at what time; that might help you understand it better.

$(document).ready(function() {
  const logs = $('#logs');
  const log = data => `<li>${data}</li>`;

  $('#send').on('click', function() {
    logs.html('');
    logs.append(log('Starting: ' + (+new Date)));
    $.post("//jsonplaceholder.typicode.com/users", {
      username: 5
    }, function(data) {
      const x = +new Date;
      logs.append(log('Received: ' + x));
      setTimeout(
        function() {
          const y = +new Date
          logs.append(log('Hiding: ' + y));
          logs.append(log('Diff: ' + (y - x)));
        },
        3000
      );
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="send">Send AJAX</button>
<ul id="logs"></ul></code>```

Title: jQuery Ajax setTimeout being random

Body:
I have the following code that lets me get data from ajax.php and display it in a div. It is supposed to display information for 3 seconds and then hide the #ajax-content and display #welcome-content

However, although most of the time it works and seems to be 3 seconds, occasionally it would randomly be much shorter. A few times it did not even feel like 1 second.

Have I done something wrong? or is there a way to fix this?

$('#user_id').on('change', function() {
$('#user_id').focus();
id = $("#user_id").val();
$.post("ajax.php", { username:id } ,function(data){
    $("#welcome-content").hide();
    $("#ajax-content").show();
    $("#ajax-content").html(data);
        setTimeout(
           function(){
            $("#ajax-content").hide();
            $("#welcome-content").show();
           },
           3000
        );
});

Body:
As you can see in following snippet, it executes in perfect time + ~2-5 ms.

You can fit in few timing logs to check what is executing at what time; that might help you understand it better.

$(document).ready(function() {
  const logs = $('#logs');
  const log = data => `<li>${data}</li>`;

  $('#send').on('click', function() {
    logs.html('');
    logs.append(log('Starting: ' + (+new Date)));
    $.post("//jsonplaceholder.typicode.com/users", {
      username: 5
    }, function(data) {
      const x = +new Date;
      logs.append(log('Received: ' + x));
      setTimeout(
        function() {
          const y = +new Date
          logs.append(log('Hiding: ' + y));
          logs.append(log('Diff: ' + (y - x)));
        },
        3000
      );
    });
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="send">Send AJAX</button>
<ul id="logs"></ul>


问:
Assign a color gradient to markers in matplotlib based on data
I'm plotting some scatter plots with matplotlib and need to have the marker colors change based on another series of data that I'm not plotting. So it will be a normal XY plot, but the marker colors change based on an unplotted z-axis, essentially. Anyone know how to do this?

Edit: here's the code I'm using

```<code>import matplotlib.pyplot as plt
import pandas as pd

fig = plt.figure(figsize=(7, 7), dpi=150)
ax = plt.subplot()

csv = pd.read_csv('FvmTest.csv', index_col='Id')
data = csv[['CO2max', 'd13c']]

bdata = data.loc['b']

bx = bdata['CO2max']
by = bdata['d13c']

plt.plot(bx, by, 'b.', label='bdata')

plt.suptitle('CO2max vs d13c', fontsize=16)
plt.xlabel('CO2max', fontsize=14)
plt.ylabel('d13c', fontsize=14)

plt.show()
</code>```

答:
You're going to want to set c = z and z is whatever you're basing the color on

```<code>ax.scatter(x, y, c = z, s = 200, cmap='rainbow')
</code>```

s is the size of the points, you're going to want to choose a size that is large enough that you can see the colors, and you need to select a colormap.

Body:
I'm plotting some scatter plots with matplotlib and need to have the marker colors change based on another series of data that I'm not plotting. So it will be a normal XY plot, but the marker colors change based on an unplotted z-axis, essentially. Anyone know how to do this?

Edit: here's the code I'm using

import matplotlib.pyplot as plt
import pandas as pd

fig = plt.figure(figsize=(7, 7), dpi=150)
ax = plt.subplot()

csv = pd.read_csv('FvmTest.csv', index_col='Id')
data = csv[['CO2max', 'd13c']]

bdata = data.loc['b']

bx = bdata['CO2max']
by = bdata['d13c']

plt.plot(bx, by, 'b.', label='bdata')

plt.suptitle('CO2max vs d13c', fontsize=16)
plt.xlabel('CO2max', fontsize=14)
plt.ylabel('d13c', fontsize=14)

plt.show()

Body:
You're going to want to set c = z and z is whatever you're basing the color on

ax.scatter(x, y, c = z, s = 200, cmap='rainbow')

s is the size of the points, you're going to want to choose a size that is large enough that you can see the colors, and you need to select a colormap.