问:
Prints integer value, Arduino HC-05 Bluetooth module
I have a problem which I have been working on for some time. I have an Arduino Uno board and an HC-05 Bluetooth transceiver with TTL outputs.

The connections are as follows:

```<code>RX (HC_05)  --> TX (Arduino UNO)

TX (HC_05)  --> RX (Arduino UNO)

GND (HC-05) --> GND (Arduino UNO)

+5V (HC-05) --> +5V (Arduino UNO)
</code>```

I have the following Arduino code:

```<code>#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  Serial.begin(9600);
  BTSerial.begin(38400);  // HC-05 default speed in AT command more
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  pinMode(10, INPUT);
  pinMode(11, OUTPUT);

  digitalWrite(9, HIGH);
  Serial.println("Enter AT commands:");
  BTSerial.println("Welcome to ARBA-Beat");
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available()) {
    Serial.println(BTSerial.read());
    BTSerial.write(BTSerial.read());
    BTSerial.flush();
  }
}
</code>```

I connect to the Bluetooth module through the Bluetooth Terminal Android app. Everything works fine (even the lights on the Bluetooth module). But when I send a character from the phone to Arduino, I get the following output:

Text sent to Bluetooth module - a

please help

thank you

答:
I had the exact same issue. Have you tried running the HC-05 at 9600? Try the code below (with your pins). I used the code to switch a relay on pin 2, but you could use an LED if you want. I used the same Bluetooth app and it worked fine:

```<code>#include <SoftwareSerial.h>
int relay = 2; // Set pin for relay control

SoftwareSerial bleserial(8,9);

// setup the relay output and the bluetooth serial, and the serial monitor (if you want to print the outputs)
void setup() {
  // set relay pin as output.
  pinMode(relay, OUTPUT);
  // start bluetooth and serial monitor
  bleserial.begin(9600);
  Serial.begin(9600);

}

void loop() {

  if(bleserial.available()){

    char char1 = bleserial.read();
    Serial.println(char1);
    // Set protocol that you want to turn on the light bulb, I chose 1 and 0 as on and off, respectively

    if(char1=='1'){
      Serial.println("ON");
      digitalWrite(relay,LOW);
    } else if (char1=='0'){
      digitalWrite(relay,HIGH);
    }
  }

}
</code>```

If you want to see wiring etc. check out the entry on my blog:

https://engineersportal.com/blog/2017/11/15/bluetooth-home-automation-light-bulb-switch-using-an-hc-05-a-relay-and-arduino

Body:
I have a problem which I have been working on for some time. I have an Arduino Uno board and an HC-05 Bluetooth transceiver with TTL outputs.

The connections are as follows:

RX (HC_05)  --> TX (Arduino UNO)

TX (HC_05)  --> RX (Arduino UNO)

GND (HC-05) --> GND (Arduino UNO)

+5V (HC-05) --> +5V (Arduino UNO)

I have the following Arduino code:

#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  Serial.begin(9600);
  BTSerial.begin(38400);  // HC-05 default speed in AT command more
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  pinMode(10, INPUT);
  pinMode(11, OUTPUT);

  digitalWrite(9, HIGH);
  Serial.println("Enter AT commands:");
  BTSerial.println("Welcome to ARBA-Beat");
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available()) {
    Serial.println(BTSerial.read());
    BTSerial.write(BTSerial.read());
    BTSerial.flush();
  }
}

I connect to the Bluetooth module through the Bluetooth Terminal Android app. Everything works fine (even the lights on the Bluetooth module). But when I send a character from the phone to Arduino, I get the following output:

Text sent to Bluetooth module - a

please help

thank you

Body:
I had the exact same issue. Have you tried running the HC-05 at 9600? Try the code below (with your pins). I used the code to switch a relay on pin 2, but you could use an LED if you want. I used the same Bluetooth app and it worked fine:

#include <SoftwareSerial.h>
int relay = 2; // Set pin for relay control

SoftwareSerial bleserial(8,9);

// setup the relay output and the bluetooth serial, and the serial monitor (if you want to print the outputs)
void setup() {
  // set relay pin as output.
  pinMode(relay, OUTPUT);
  // start bluetooth and serial monitor
  bleserial.begin(9600);
  Serial.begin(9600);

}

void loop() {

  if(bleserial.available()){

    char char1 = bleserial.read();
    Serial.println(char1);
    // Set protocol that you want to turn on the light bulb, I chose 1 and 0 as on and off, respectively

    if(char1=='1'){
      Serial.println("ON");
      digitalWrite(relay,LOW);
    } else if (char1=='0'){
      digitalWrite(relay,HIGH);
    }
  }

}

If you want to see wiring etc. check out the entry on my blog:

https://engineersportal.com/blog/2017/11/15/bluetooth-home-automation-light-bulb-switch-using-an-hc-05-a-relay-and-arduino


来源: stackexchange

问:
SQL, Select One row with min field value from subquery
I have following SQL query:

```<code> select count(t.id) from Tickets t
    where t.IsPaid = 1 and t.Price_id = (select price.Id from Prices price
            where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F' AND price.Quantity > (select count(t1.Id) from Tickets t1
                where t1.IsPaid = 1 AND t1.Price_id IN (select pr.Id from Prices pr
                    where price.Product_id = pr.Id)))
</code>```

The question is: how to get the row with min value of price.Price1 field from this part of my code?

```<code>(select price.Id from Prices price
            where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F' AND price.Quantity > (select count(t1.Id) from Tickets t1
                where t1.IsPaid = 1 AND t1.Price_id IN (select pr.Id from Prices pr
                    where price.Product_id = pr.Id)))
</code>```

I expect that as a result of second part of my code would be only Id of the ONE row. Right now this code always returning me all prices.
Here is relationships in main tables Database structure and relations

I was trying different methods like this:

```<code>(select price.Id, MIN(Price1) from Prices price
        where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F' AND price.Quantity > (select count(t1.Id) from Tickets t1
            where t1.IsPaid = 1 AND t1.Price_id IN (select pr.Id from Prices pr
                where price.Product_id = pr.Id)) Group by Id)
</code>```

But the result is: Result with MIN function

Example of data in Prices table: Prices table

Example of data in Tickets table: Tickets table

答:
What I think you are trying to achieve:
for a given product id find the lowest possible price that has available unpaid tickets and then show how many tickets are available

If that's correct:

```<code>SELECT isnull(ticket_count, 0) AS ticket_count
FROM
(
        SELECT *
        FROM (SELECT Price_Id, MIN(Price1) OVER (Partition By Product_id) min_price from Prices) x
        WHERE min_price=Price1
    ) p
    JOIN
    (
        SELECT COUNT(Id) ticket_count, Price_Id FROM Tickets WHERE IsPaid=1 GROUP BY Price_Id
    ) t ON p.Price_Id=t.Price_Id
WHERE p.Quantity > t.ticket_count
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have following SQL query:

 select count(t.id) from Tickets t
    where t.IsPaid = 1 and t.Price_id = (select price.Id from Prices price
            where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F' AND price.Quantity > (select count(t1.Id) from Tickets t1
                where t1.IsPaid = 1 AND t1.Price_id IN (select pr.Id from Prices pr
                    where price.Product_id = pr.Id)))

The question is: how to get the row with min value of price.Price1 field from this part of my code?

(select price.Id from Prices price
            where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F' AND price.Quantity > (select count(t1.Id) from Tickets t1
                where t1.IsPaid = 1 AND t1.Price_id IN (select pr.Id from Prices pr
                    where price.Product_id = pr.Id)))

I expect that as a result of second part of my code would be only Id of the ONE row. Right now this code always returning me all prices.
Here is relationships in main tables Database structure and relations

I was trying different methods like this:

(select price.Id, MIN(Price1) from Prices price
        where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F' AND price.Quantity > (select count(t1.Id) from Tickets t1
            where t1.IsPaid = 1 AND t1.Price_id IN (select pr.Id from Prices pr
                where price.Product_id = pr.Id)) Group by Id)

But the result is: Result with MIN function

Example of data in Prices table: Prices table

Example of data in Tickets table: Tickets table

Body:
What I think you are trying to achieve:
for a given product id find the lowest possible price that has available unpaid tickets and then show how many tickets are available

If that's correct:

SELECT isnull(ticket_count, 0) AS ticket_count
FROM
(
        SELECT *
        FROM (SELECT Price_Id, MIN(Price1) OVER (Partition By Product_id) min_price from Prices) x
        WHERE min_price=Price1
    ) p
    JOIN
    (
        SELECT COUNT(Id) ticket_count, Price_Id FROM Tickets WHERE IsPaid=1 GROUP BY Price_Id
    ) t ON p.Price_Id=t.Price_Id
WHERE p.Quantity > t.ticket_count


问:
space between xaxis and barplot in matlab
I want to create a small gap between begining of the bar plot and xaxis when plotting negative and poistive values.

Given:

```<code>barData = [1 2 3; 2 2 2];
bar(barData,'stacked')
hold on
bar(barData*-1, 'stacked')
</code>```

returns usual stacked bar plot which looks like this (no spaces):

and I would like to have a space between xaxis and the begining of the yaxis something as in this example (in this case its not stacked bar and only positve values).

答:
You mean like this?</p>

```<code>barData = [1 2 3; 2 2 2];

bar(barData,'stacked','BarWidth',0.65);
hold on;
bar(barData*-1,'stacked','BarWidth',0.65);
hold off;

y_lim = get(gca,'YLim') + [-1 1];
set(gca,'YLim',y_lim);
</code>```

Body:
I want to create a small gap between begining of the bar plot and xaxis when plotting negative and poistive values.

Given:

barData = [1 2 3; 2 2 2];
bar(barData,'stacked')
hold on
bar(barData*-1, 'stacked')

returns usual stacked bar plot which looks like this (no spaces):

and I would like to have a space between xaxis and the begining of the yaxis something as in this example (in this case its not stacked bar and only positve values).

Body:
You mean like this?

barData = [1 2 3; 2 2 2];

bar(barData,'stacked','BarWidth',0.65);
hold on;
bar(barData*-1,'stacked','BarWidth',0.65);
hold off;

y_lim = get(gca,'YLim') + [-1 1];
set(gca,'YLim',y_lim);


问:
iOS 11 Logo and title in NavigationBar
I have been searching and trying for days but since it's a new thing there's not much information available (or I can't find them).

Anyway, I am trying to get use of new NavBar features in iOS 11 but I want to put both a logo and a large title (of each ViewController) in my NavBar. Something like the screenshot below:

How is it possible to implement this?

Side Hint:

For same app in iOS 10 I set the logo to show instead of titleView in NavBar but now in newer version we want to add the Title too.

Thanks in advance

答:
Did you try setting a background image for your navbar? Like this:</p>

```<code>// Set Navigation bar background Image
let navBgImage:UIImage = UIImage(named: "[image.jpg]")!
self.navigationController!.navigationBar.setBackgroundImage(navBgImage, for: .default)
</code>```

Title: iOS 11 Logo and title in NavigationBar

Body:
Did you try setting a background image for your navbar? Like this:

// Set Navigation bar background Image
let navBgImage:UIImage = UIImage(named: "[image.jpg]")!
self.navigationController!.navigationBar.setBackgroundImage(navBgImage, for: .default)


问:
I Can't re-write Java's solution to C# in Selenium
I have some problems with modified FireFox browser on C#.
When the Browser opens and I get an error:

TypeError: Given browserName [object String] "firefox", but my name is [object String] "anotherbrowser"

I think, it's because of browser's name "anotherbrowser" instead of "firefox" in it's binary code.

So I found the solution on Java:

```<code>FirefoxOptions options = new FirefoxOptions();
options.setBinary("Path to browser binary");
options.setCapability("browserName", "anotherbrowser");
options.setCapability("marionette", false);
driver = new FirefoxDriver(options);
</code>```

I tested it, and its work fine. But I need on C#, so I tried to rewrite it:

```<code>DesiredCapabilities cap = DesiredCapabilities.Firefox();
cap.SetCapability("browserName", "anotherbrowser");
cap.SetCapability("firefox_binary", @"Path to browser binary");
IWebDriver driver = new FirefoxDriver(cap); //here's error
</code>```

But I got an error:

There is already an option for the browserName capability. Please use
  the  instead.

Please, help me to re-write Java solution to C#. I got troubles, because there isn't same method in C#, like in Java: "options.setCapability(" "," ");"

P.s. I can't use original Firefox browser, because it doesn't have same advantages as my modified Firefox.

答:
Have you tried using the options class like you are in Java?

In c# you can use something like this:

```<code>FirefoxOptions options = new FirefoxOptions();
options.BrowserExecutableLocation = @"C:\Path\to\firefox";

IWebDriver driver = new FirefoxDriver(options)
</code>```

According to: https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities

The name of the browser being used; should be one of {android, chrome, firefox, htmlunit, internet explorer, iPhone, iPad, opera, safari}

Based on what the documentation says, I would assume that you do not need to set the "browserName" capability to use your custom binaries.

Body:
I have some problems with modified FireFox browser on C#.
When the Browser opens and I get an error:

TypeError: Given browserName [object String] "firefox", but my name is [object String] "anotherbrowser"

I think, it's because of browser's name "anotherbrowser" instead of "firefox" in it's binary code.

So I found the solution on Java:

FirefoxOptions options = new FirefoxOptions();
options.setBinary("Path to browser binary");
options.setCapability("browserName", "anotherbrowser");
options.setCapability("marionette", false);
driver = new FirefoxDriver(options);

I tested it, and its work fine. But I need on C#, so I tried to rewrite it:

DesiredCapabilities cap = DesiredCapabilities.Firefox();
cap.SetCapability("browserName", "anotherbrowser");
cap.SetCapability("firefox_binary", @"Path to browser binary");
IWebDriver driver = new FirefoxDriver(cap); //here's error

But I got an error:

There is already an option for the browserName capability. Please use
  the  instead.

Please, help me to re-write Java solution to C#. I got troubles, because there isn't same method in C#, like in Java: "options.setCapability(" "," ");"

P.s. I can't use original Firefox browser, because it doesn't have same advantages as my modified Firefox.

Body:
Have you tried using the options class like you are in Java?

In c# you can use something like this:

FirefoxOptions options = new FirefoxOptions();
options.BrowserExecutableLocation = @"C:\Path\to\firefox";

IWebDriver driver = new FirefoxDriver(options)

According to: https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities

The name of the browser being used; should be one of {android, chrome, firefox, htmlunit, internet explorer, iPhone, iPad, opera, safari}

Based on what the documentation says, I would assume that you do not need to set the "browserName" capability to use your custom binaries.


问:
Merge multiple variables in R
I have a dataset such that the same variable is contained in difference columns for each subject. I want to merge them to the same columns.

E.g.:, I have this dataframe, and there are three DVs, but they are in different columns (A,B,C) for different subjects.

```<code>data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"))
</code>```

How can I merge them to just two columns? so the result is:

```<code>data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"), DV_1 = c(1,4,5), DV_2 = c(3,3,5))
</code>```

答:
For the sake of completeness, here is also a data.table  solution using melt() to reshape two measure variables simultaneously:

```<code>library(data.table)
cols <- c("DV1", "DV2")
melt(setDT(DF), measure.vars = patterns(cols), value.name = cols, na.rm = TRUE)[
  , -"variable"]
</code>```

```<code>   ID FACT DV1 DV2
1:  1    A   1   3
2:  2    B   4   3
3:  3    C   5   5
</code>```

Now, the six columns have been merged to just two columns as requested by the OP.

However, the OP has given a data.frame with the expected result where the new columns are appended to the existing  columns. This can be achieved by joining above result with the original data frame:

```<code> setDT(DF)[melt(DF, measure.vars = patterns(cols), value.name = cols, na.rm = TRUE)[
  , -"variable"], on = .(ID, FACT)]
</code>```

```<code>   ID DV1_A DV1_B DV1_C DV2_A DV2_B DV2_C FACT DV1 DV2
1:  1     1    NA    NA     3    NA    NA    A   1   3
2:  2    NA     4    NA    NA     3    NA    B   4   3
3:  3    NA    NA     5    NA    NA     5    C   5   5
</code>```

Title: Merge multiple variables in R

Body:
I have a dataset such that the same variable is contained in difference columns for each subject. I want to merge them to the same columns.

E.g.:, I have this dataframe, and there are three DVs, but they are in different columns (A,B,C) for different subjects.

data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"))

How can I merge them to just two columns? so the result is:

data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"), DV_1 = c(1,4,5), DV_2 = c(3,3,5))

Body:
For the sake of completeness, here is also a data.table  solution using melt() to reshape two measure variables simultaneously:

library(data.table)
cols <- c("DV1", "DV2")
melt(setDT(DF), measure.vars = patterns(cols), value.name = cols, na.rm = TRUE)[
  , -"variable"]

   ID FACT DV1 DV2
1:  1    A   1   3
2:  2    B   4   3
3:  3    C   5   5

Now, the six columns have been merged to just two columns as requested by the OP.

However, the OP has given a data.frame with the expected result where the new columns are appended to the existing  columns. This can be achieved by joining above result with the original data frame:

 setDT(DF)[melt(DF, measure.vars = patterns(cols), value.name = cols, na.rm = TRUE)[
  , -"variable"], on = .(ID, FACT)]

   ID DV1_A DV1_B DV1_C DV2_A DV2_B DV2_C FACT DV1 DV2
1:  1     1    NA    NA     3    NA    NA    A   1   3
2:  2    NA     4    NA    NA     3    NA    B   4   3
3:  3    NA    NA     5    NA    NA     5    C   5   5


问:
Querying and Converting Documents using Named Keys
I'm an old SQL hand, now working with an existing Mongo database.

Rather than using arrays of embedded documents, with key information being one of the fields in the array element, each embedded document is its own field, with the key as the field name.

Suppose a collection called bank_branches.  Rather than this:

```<code>{
  branch : "St. Louis",
  branch_employees : [
    {
       name : "Mary",
       id : "M12345"
       hire_date : Date("2010-05-20")
    },
    {
       name :  "John",
       id : "J29876",
       hire_date : Date("2015-03-23")
    }
  ]
},
{
  branch : "Jefferson City",
  branch_employees : [
    {
       name : "Lisa",
       id : "L87653"
       hire_date : Date("2016-01-07")
    }
  ]
}
</code>```

... we have documents like this:

```<code>{
  branch : "St. Louis",
  branch_employees : {
     M12345 : {
        name : "Mary",
        hire_date : Date("2010-05-20")
     },
     J29876 :  {
       name :  "John",
       hire_date : Date("2015-03-23")
     }
 }
 {
   branch : "Jefferson City",
   branch_employees : {
      L87653 : {
        name : "Lisa",
        hire_date : Date("2016-01-07")
      }
   }
}
</code>```

(This is an invented structure to show the problem.)

Is there any way, within the MongoDB Aggregate Pipeline or otherwise, to do either of the following?

Query the component fields of the employee embedded documents, so that I could, for example, get all branches with employees hired in 2016, without knowing all the field names for all the embedded documents in advance?

"Unwind" these objects, so that I could have an array of branch employee documents, again without knowing all the field names for all the embedded documents in advance?  (The MongoDB $unwind pipeline operation only works on arrays.)

I suspect the first might be solvable with $where and javascript,  and/or a custom javascript stored function.  (I've never worked with stored functions before.) But I suspect the second could only be addressed programmatically.

I can satisfy my use case by writing Python and doing iteration. But I'd rather write queries to find records than filter them programmatically.  (The only guaranteed bug-free code is the code you don't have to write.)

Suggestions, anyone?  Many thanks, in advance.

答:
I could ramble on about this but you already appear at least aware of the best answer. Convert your data to arrays. The only way you "query" the documents involves essentially manipulating the document ( per document processing ) on the server to coerce these "named keys" into arrays.

There are more "modern" methods in recent releases of MongoDB that mean you don't "have to" use $where, but there is still the main caveat where this is still in the wrong form, you simply "cannot use an index" to speed the query results.

In the basic addressing of your questions:

Query

If you want o "find documents" by your condition on the branch employees hire date, then you can use an expression with $where as follows:

```<code>db.bank_branches.find(
  function() {
    return Object.keys(this.branch_employees).some(e =>
      e.hire_date => new Date("2016-01-01") && e.hire_date < new Date("2017-01-01")
    )
  }
)
</code>```

The main reason we're using JavaScript evaluation is because you need to "traverse the keys" of the document in a way that the query DSL cannot express, and therefore needs a condition to be evaluated against each document instead of using an index.

With more recent releases since MongoDB 3.4.4 you can use $objectToArray for much the same purpose as Object.keys(), and use it as part of an expression inside a $redact aggregation pipeline stage:

```<code>db.bank_branches.aggregate([
  { "$redact": {
    "$cond": {
      "if": {
        "$anyElementTrue": {
          "$map": {
            "input": { "$objectToArray": "$branch_employees" },
            "in": {
              "$and": [
                { "$gte": [ "$$this.hire_date", new Date("2016-01-01") ] },
                { "$lt": [ "$$this.hire_date", new Date("2017-01-01") ] }
              ]
            }
          }
        }
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])
</code>```

The $redact essentially evaluates a condition and either returns via $$KEEP or "removes" via $$PRUNE the documents based on what the boolean result of the condition was. This is similar to $where except it is a native operator rather than using interpreted JavaScript and is essentially the "whole" query condition as opposed to $where which is technically just another query parameter and can be used with other conditions.

From MongoDB 3.6 we get $expr which allows this to shorten, and even be used as the same "additional parameter" syntax as what $where does, except with native coded operators:

```<code>db.bank_branches.find({
  "$expr": {
    "$anyElementTrue": {
      "$map": {
        "input": { "$objectToArray": "$branch_employees" },
        "in": {
          "$and": [
            { "$gte": [ "$$this.hire_date", new Date("2016-01-01") ] },
            { "$lt": [ "$$this.hire_date", new Date("2017-01-01") ] }
          ]
        }
      }
    }
  }
})
</code>```

But they are all still basically horrible since all you can do is "scan the entire collection" in order to obtain a result. So the better "array" syntax is:

```<code>db.bank_branches.find({
  "branch_employees": {
    "$elemMatch": {
      "hire_date": { "$gte": new Date("2016-01-01"), "$lte": new Date("2017-01-01") }
    }
  }
})
</code>```

Which can of course use an index since the path to "branch_employees.hire_date" is consistent, and does not use a "named key" as part of the intermediate path to the desired property. This is the prime reason you want this structure

Reshaping

In order to actually get the documents in that "array shape", then we should have been given some indication by how the queries were constructed.

So in the first option, if writing to a "new collection" is an option for you, then in modern releases you should be able to simply do the whole conversion on the server itself:

```<code>db.bank_branches.aggregate([
  { "$project": {
    "branch": 1,
    "branch_employees": {
      "$map": {
        "input": { "$objectToArray": "$branch_employees" },
        "in": {
          "$arrayToObject": {
            "$concatArrays": [
              [{ "k": "id", "v": "$$this.k" }],
              { "$objectToArray": "$$this.v" }
            ]
          }
        }
      }
    }
  }},
  { "$out": "new_branches" }
])
</code>```

Or in the case where you don't have the modern operators available or simply cannot write to a new collection, then basically looping the collection and writing back the new data for the property:

```<code>var ops = [];

db.bank_branches.find({ "branch_employees.0": { "$exists": false } }).forEach( doc => {

  ops.push({
    "updateOne": {
      "filter": { "_id": doc._id },
      "update": {
        "$set": {
          "branch_employees": Object.keys(doc.branch_employees).map(id =>
            Object.assign({ id },doc.branch_employees[id])
          )
        }
      }
    }
  });

  if ( ops.length > 1000 ) {
    db.bank_branches.bulkWrite(ops);
    ops = [];
  }

})

if ( ops.length > 0 ) {
  db.bank_branches.bulkWrite(ops);
  ops = [];
}
</code>```

Both essentially use the same technique of taking the value of the object's sub-keys and merging that with the underlying object as the elements of what gets returned as an "array".

N.B Code that runs in a $where expression is in JavaScript and runs on the server, so it's still a "language agnostic solution" where the "JavaScript" to be evaluated there is actually submitted as a "string" in other languages.

Other expressions essentially break down to BSON representation in the language of choice. Python and Ruby are near identical to JavaScript in regards to this syntax, and the same BSON conventions apply everywhere.

The other routines here are given for "conversion" of data, which as a "one off" operation should always be sufficient to run in the JavaScript execution environment of the shell.

So there's no "need" to use JavaScript ( with the exception of $where expressions ) but the examples are given here in the common format which everyone can run in the shell provided with your MongoDB installation.

Body:
I'm an old SQL hand, now working with an existing Mongo database.

Rather than using arrays of embedded documents, with key information being one of the fields in the array element, each embedded document is its own field, with the key as the field name.

Suppose a collection called bank_branches.  Rather than this:

{
  branch : "St. Louis",
  branch_employees : [
    {
       name : "Mary",
       id : "M12345"
       hire_date : Date("2010-05-20")
    },
    {
       name :  "John",
       id : "J29876",
       hire_date : Date("2015-03-23")
    }
  ]
},
{
  branch : "Jefferson City",
  branch_employees : [
    {
       name : "Lisa",
       id : "L87653"
       hire_date : Date("2016-01-07")
    }
  ]
}

... we have documents like this:

{
  branch : "St. Louis",
  branch_employees : {
     M12345 : {
        name : "Mary",
        hire_date : Date("2010-05-20")
     },
     J29876 :  {
       name :  "John",
       hire_date : Date("2015-03-23")
     }
 }
 {
   branch : "Jefferson City",
   branch_employees : {
      L87653 : {
        name : "Lisa",
        hire_date : Date("2016-01-07")
      }
   }
}

(This is an invented structure to show the problem.)

Is there any way, within the MongoDB Aggregate Pipeline or otherwise, to do either of the following?

Query the component fields of the employee embedded documents, so that I could, for example, get all branches with employees hired in 2016, without knowing all the field names for all the embedded documents in advance?

"Unwind" these objects, so that I could have an array of branch employee documents, again without knowing all the field names for all the embedded documents in advance?  (The MongoDB $unwind pipeline operation only works on arrays.)

I suspect the first might be solvable with $where and javascript,  and/or a custom javascript stored function.  (I've never worked with stored functions before.) But I suspect the second could only be addressed programmatically.

I can satisfy my use case by writing Python and doing iteration. But I'd rather write queries to find records than filter them programmatically.  (The only guaranteed bug-free code is the code you don't have to write.)

Suggestions, anyone?  Many thanks, in advance.

Body:
I could ramble on about this but you already appear at least aware of the best answer. Convert your data to arrays. The only way you "query" the documents involves essentially manipulating the document ( per document processing ) on the server to coerce these "named keys" into arrays.

There are more "modern" methods in recent releases of MongoDB that mean you don't "have to" use $where, but there is still the main caveat where this is still in the wrong form, you simply "cannot use an index" to speed the query results.

In the basic addressing of your questions:

Query

If you want o "find documents" by your condition on the branch employees hire date, then you can use an expression with $where as follows:

db.bank_branches.find(
  function() {
    return Object.keys(this.branch_employees).some(e =>
      e.hire_date => new Date("2016-01-01") && e.hire_date < new Date("2017-01-01")
    )
  }
)

The main reason we're using JavaScript evaluation is because you need to "traverse the keys" of the document in a way that the query DSL cannot express, and therefore needs a condition to be evaluated against each document instead of using an index.

With more recent releases since MongoDB 3.4.4 you can use $objectToArray for much the same purpose as Object.keys(), and use it as part of an expression inside a $redact aggregation pipeline stage:

db.bank_branches.aggregate([
  { "$redact": {
    "$cond": {
      "if": {
        "$anyElementTrue": {
          "$map": {
            "input": { "$objectToArray": "$branch_employees" },
            "in": {
              "$and": [
                { "$gte": [ "$$this.hire_date", new Date("2016-01-01") ] },
                { "$lt": [ "$$this.hire_date", new Date("2017-01-01") ] }
              ]
            }
          }
        }
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])

The $redact essentially evaluates a condition and either returns via $$KEEP or "removes" via $$PRUNE the documents based on what the boolean result of the condition was. This is similar to $where except it is a native operator rather than using interpreted JavaScript and is essentially the "whole" query condition as opposed to $where which is technically just another query parameter and can be used with other conditions.

From MongoDB 3.6 we get $expr which allows this to shorten, and even be used as the same "additional parameter" syntax as what $where does, except with native coded operators:

db.bank_branches.find({
  "$expr": {
    "$anyElementTrue": {
      "$map": {
        "input": { "$objectToArray": "$branch_employees" },
        "in": {
          "$and": [
            { "$gte": [ "$$this.hire_date", new Date("2016-01-01") ] },
            { "$lt": [ "$$this.hire_date", new Date("2017-01-01") ] }
          ]
        }
      }
    }
  }
})

But they are all still basically horrible since all you can do is "scan the entire collection" in order to obtain a result. So the better "array" syntax is:

db.bank_branches.find({
  "branch_employees": {
    "$elemMatch": {
      "hire_date": { "$gte": new Date("2016-01-01"), "$lte": new Date("2017-01-01") }
    }
  }
})

Which can of course use an index since the path to "branch_employees.hire_date" is consistent, and does not use a "named key" as part of the intermediate path to the desired property. This is the prime reason you want this structure

Reshaping

In order to actually get the documents in that "array shape", then we should have been given some indication by how the queries were constructed.

So in the first option, if writing to a "new collection" is an option for you, then in modern releases you should be able to simply do the whole conversion on the server itself:

db.bank_branches.aggregate([
  { "$project": {
    "branch": 1,
    "branch_employees": {
      "$map": {
        "input": { "$objectToArray": "$branch_employees" },
        "in": {
          "$arrayToObject": {
            "$concatArrays": [
              [{ "k": "id", "v": "$$this.k" }],
              { "$objectToArray": "$$this.v" }
            ]
          }
        }
      }
    }
  }},
  { "$out": "new_branches" }
])

Or in the case where you don't have the modern operators available or simply cannot write to a new collection, then basically looping the collection and writing back the new data for the property:

var ops = [];

db.bank_branches.find({ "branch_employees.0": { "$exists": false } }).forEach( doc => {

  ops.push({
    "updateOne": {
      "filter": { "_id": doc._id },
      "update": {
        "$set": {
          "branch_employees": Object.keys(doc.branch_employees).map(id =>
            Object.assign({ id },doc.branch_employees[id])
          )
        }
      }
    }
  });

  if ( ops.length > 1000 ) {
    db.bank_branches.bulkWrite(ops);
    ops = [];
  }

})

if ( ops.length > 0 ) {
  db.bank_branches.bulkWrite(ops);
  ops = [];
}

Both essentially use the same technique of taking the value of the object's sub-keys and merging that with the underlying object as the elements of what gets returned as an "array".

N.B Code that runs in a $where expression is in JavaScript and runs on the server, so it's still a "language agnostic solution" where the "JavaScript" to be evaluated there is actually submitted as a "string" in other languages.

Other expressions essentially break down to BSON representation in the language of choice. Python and Ruby are near identical to JavaScript in regards to this syntax, and the same BSON conventions apply everywhere.

The other routines here are given for "conversion" of data, which as a "one off" operation should always be sufficient to run in the JavaScript execution environment of the shell.

So there's no "need" to use JavaScript ( with the exception of $where expressions ) but the examples are given here in the common format which everyone can run in the shell provided with your MongoDB installation.


问:
Seclecting photos from picker and posting on to server issue
I am facing an issue related to application's memory consumption getting increased drastically. I need to select photos using uiimage picker controller, post those multiple images on to the server and dismiss the controller. But each time I chose the photos, the memory of the application increases and doesn't reduce and at some point the application crashes. I have already checked for memory leaks but didn't find any.
Thanks in advance.</p>

答:
We have noticed that each time the UIImagePickerController is presented, the application internally consumes some memory which it doesn't relinquish even when the picker controller is dismissed.In our application, we have need to invoke the picker controller frequently and so after sometime the overall memory of the application increases and the application's crashes. We created a sample application and found that this leak in the picker is existing. After searching various forums , we tried the below snippet code in the picker delegate method but it was in vain:

picker.delegate = nil;
[picker release];
picker = nil;

We also tried to create a static picker controller, but still the issue persisted.

Could anyone provide some inputs on it.

ContentLicense: CC BY-SA 2.5


问:
Converting Binary to Decimal in python (without built in binary function)
Alrighty, first post here, so please forgive and ignore if the question is not workable;

Background:
I'm in computer science 160.  I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced.  We have been working in Python and each week we are prompted to write a program.

I have been working with this problem for over a week and am having a hard time even starting.

The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent.  Now, I have gotten some tips from a classmate and it sent me at least in a direction.

Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.

I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.

```<code>setbitval = 0
counter = 0

user = int(input("enter a binary value. "))

if user % 2 == 1:
        user = (user/10) - .1
        setbitval += 1
</code>```

This is all I've got so far.. My thinking is getting in the way.  I've searched and searched, even through these forums.

Any information or thoughts are extremely appreciated,

T

Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.

```<code>for i in reversed(bits):
decimal += 2**counter * int(i)

counter += 1
</code>```

This is the formula someone here gave me and I've been trying different iterations of "for i in bits:  if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".

Any thoughts?

答:
I'll agree this is close to the "code this for me" territory, but I'll try to answer in a way that gets you on the right track, instead of just posting a working code snippet.

A simple way of doing this is just to use int()'s base argument, but I'm guessing that is disallowed.

You already have a way of testing the current bit in your question, namely checking whether n % 2 == 1. If this is the case, we need to add a power of two.

Then, we need some way of going to the next bit. In binary, we would use bit shifts, but sadly, we don't have those. a >> b is equivalent to a // (2**b) - can you write a decimal equivalent to that?

You also need to keep a counter of which power of two the current bit represents, a loop, and some way of detecting an end condition. Those are left as exercises to the reader.

Body:
Alrighty, first post here, so please forgive and ignore if the question is not workable;

Background:
I'm in computer science 160.  I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced.  We have been working in Python and each week we are prompted to write a program.

I have been working with this problem for over a week and am having a hard time even starting.

The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent.  Now, I have gotten some tips from a classmate and it sent me at least in a direction.

Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.

I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.

setbitval = 0
counter = 0

user = int(input("enter a binary value. "))

if user % 2 == 1:
        user = (user/10) - .1
        setbitval += 1

This is all I've got so far.. My thinking is getting in the way.  I've searched and searched, even through these forums.

Any information or thoughts are extremely appreciated,

T

Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.

for i in reversed(bits):
decimal += 2**counter * int(i)

counter += 1

This is the formula someone here gave me and I've been trying different iterations of "for i in bits:  if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".

Any thoughts?


问:
Adding new datasources to an existing .rrd
I have a .rrd db which is collecting data from a temperature gauge. Now I have a second gauge so I'd like to add this new gauge to the existing .rrd database. I tried many times with the "rrdtool tune" command, but after that I run a "rrdtool info" on my database, and I see that there's not the last data source (another gauge) that I tried to insert.

How can I do this?

答:
I finally did it, but I wasn't able to use the rrdtool tune function.

I finally found here how to perform a dump of the database, how to modify it, and finally restore it to its original location (so I could also correct some data).

This is not what I was searching for, but it solved my problem so I want to share it.


问:
SVN Relocate - Change all externals to "relative url to repository root"
We recently changed the server name of our svn projects (http to https)
Unfortunately all my externals which were using absolute urls are now not working.
I want to change all of them with relative url to repository root "^/...".

Folder 1

Folder 1.1

External 1

Folder 1.1.1

External 2

External 3

Folder 2

Folder 2.1

External 4

Folder 2.1.1

External 5

External 6

Is there a simple way to change them all at the same time ?

I am using SVN 1.8.11

Thank you in advance for your help

答:
I would've made this a comment, but unfortunately I don't have access to comments yet. But are you using a Subversion Client?

TortoiseSVN is a good svn client to use with an easy-to-use shell menu where all you would have to do would be to go to your checked out directory:
- Right Click > TortoiseSVN > Properties > New... > Externals

Otherwise, yeah you would have to use the propset with the file. Something like this:

```<code>$ svn propset svn:externals BaseDirectory
Folder 1                       https://url/to/folder1
Folder 1/external 1            https://url/to/external1
</code>```

Or you might have to use propedit, if they're already there. See more information:

Manipulating Properties

Externals Definitions

Having externals shouldn't be an issue though, just make sure the directories aren't already there if you're doing an update. Sometimes subversion messes up if you're trying to add externals and point them to directories that already exist. You might see an error like

```<code>Cannot obtain lock on non directory
</code>```

Or something like that. Hope this helps somewhat!

Body:
I would've made this a comment, but unfortunately I don't have access to comments yet. But are you using a Subversion Client?

TortoiseSVN is a good svn client to use with an easy-to-use shell menu where all you would have to do would be to go to your checked out directory:
- Right Click > TortoiseSVN > Properties > New... > Externals

Otherwise, yeah you would have to use the propset with the file. Something like this:

$ svn propset svn:externals BaseDirectory
Folder 1                       https://url/to/folder1
Folder 1/external 1            https://url/to/external1

Or you might have to use propedit, if they're already there. See more information:

Manipulating Properties

Externals Definitions

Having externals shouldn't be an issue though, just make sure the directories aren't already there if you're doing an update. Sometimes subversion messes up if you're trying to add externals and point them to directories that already exist. You might see an error like

Cannot obtain lock on non directory

Or something like that. Hope this helps somewhat!


问:
toggling css classes using knockout
I am trying to do some like this. is it a valid syntax? I am checking for some flag value and toggling b/w two css classes?

```<code><div data-bind="visible:'anchorJobContractor'===JobDetail_SelctedTab(), css:IsTabsCollapsed ? TabCollapsed : TabExpanded"></div>
</code>```

First part visible dataBinding  works for me.

答:
Disclaimer: Quick and dirty version

I needed a quick and dirty way to apply a class to a debugging panel, and came up with the following.

I recommend this version only for debugging, and it only works if you are also using jQuery.

```<code><div class="debug-only knockout-debug-panel"
            data-bind="click: function(data, event) { $(event.currentTarget).toggleClass('transparent'); }">

</div>

.transparent { opacity: .5; }
</code>```

Knockout has a function toggleDomNodeCssClass, but unfortuntely it requires a boolean whether to add or remove the class.

Title: toggling css classes using knockout

Body:
I am trying to do some like this. is it a valid syntax? I am checking for some flag value and toggling b/w two css classes?

First part visible dataBinding  works for me.

Body:
Disclaimer: Quick and dirty version

I needed a quick and dirty way to apply a class to a debugging panel, and came up with the following.

I recommend this version only for debugging, and it only works if you are also using jQuery.

<div class="debug-only knockout-debug-panel"
            data-bind="click: function(data, event) { $(event.currentTarget).toggleClass('transparent'); }">

</div>

.transparent { opacity: .5; }

Knockout has a function toggleDomNodeCssClass, but unfortuntely it requires a boolean whether to add or remove the class.


问:
Vue instance inside another Vue instance
I’m integrating Vue with a CMS called AEM thats works basically as component base system like Vue works too. But instead of having a webpack and imports of .vue files, every component on this CMS is a new Vue instance (new Vue({…})). So on my page I have a lot of Veu instances that communicate with each other using the same store (vuex).

This is actually working fine, but I have a scenario when I need a CMS component inside another. Since both this components are a unique vue instance and the “el” property from the parent includes the “el” from the child, the child component doesn’t work.

I know that this is not the expected use of this lib, but is there any way that I can tell or share the same “context” on both vue instances or even another approach for this scenario.

Thx,
Alexandre.

答:
There should be only one instance of Vue.

I suggest you to create single empty Vue instance inside the body tag

All your existent Vue instances transform into components

Register all components in the root Vue instance

With this approach it will be fine to nest one component into another


问:
Program terminates after another class is called
I am trying to design a Java Program which offers multiple things like Calculator and tetris game and many more. Both Calculator and Tetris game are written in Swing having GUI, but the main program is CLI. it presents options like press 1 for calculator , press 2 for tetris, etc. but as soon as I press 1 calculator launches in another window and my main program terminates. I want a method that my main program still gives options like press 1 for calculator , press 2 for tetris, etc. even when I close the GUI Calculator or Tetris Window. here's what I'm trying to do:</p>

```<code>if (input == 1)
    {
        new Calc();
        mainScreen();
    }
else if (input == 2)
    {
        new Tetris();
        mainScreen();
    }
    .
    .
    .
    And So On
</code>```

答:
You can also pre-make the tetris game and calculator and do something like

```<code>        Calc calculator;
Tetris tetrisGame;
    if(input == 1) {

calculator = new Calc();
calculator.mainScreen();

    }
else if(input == 2) {

tetrisGame = new Tetris();
tetrisGame.mainScreen();

}
</code>```

You could also make a constructor where you initialize these variables and then just use them.

Body:
I am trying to design a Java Program which offers multiple things like Calculator and tetris game and many more. Both Calculator and Tetris game are written in Swing having GUI, but the main program is CLI. it presents options like press 1 for calculator , press 2 for tetris, etc. but as soon as I press 1 calculator launches in another window and my main program terminates. I want a method that my main program still gives options like press 1 for calculator , press 2 for tetris, etc. even when I close the GUI Calculator or Tetris Window. here's what I'm trying to do:

if (input == 1)
    {
        new Calc();
        mainScreen();
    }
else if (input == 2)
    {
        new Tetris();
        mainScreen();
    }
    .
    .
    .
    And So On

Body:
You can also pre-make the tetris game and calculator and do something like

        Calc calculator;
Tetris tetrisGame;
    if(input == 1) {

calculator = new Calc();
calculator.mainScreen();

    }
else if(input == 2) {

tetrisGame = new Tetris();
tetrisGame.mainScreen();

}

You could also make a constructor where you initialize these variables and then just use them.


问:
how to restrict HTTP requests for an application in Mulesoft?
How to restrict only 10 requests for an application in MuleSoft and should send an alert message if the 11th request is sent to application so that we can prevent server crash?</p>

答:
Here is the details

https://docs.mulesoft.com/api-manager/rate-limiting-and-throttling

If you are using API Manager using Anypoint platform then it will be very easy to use the out of box policies to enforce on the APIs.


问:
How can I call a parent function which would use the subclass's overriden final variables?
Relevant code from my first class:

```<code>protected static final float MAX_HEALTH = 100.0f;
protected static final float MIN_HEALTH = 0.0f;

public void modifyHealth(float enteredAmount)
{
    if (health + enteredAmount > MAX_HEALTH )
    {
        health = MAX_HEALTH;
    }
    else if (health + enteredAmount < MIN_HEALTH)
    {
        health = MIN_HEALTH;
    }
    else
    {
        health += enteredAmount;
    }
}
</code>```

Second class which extends the first class:

```<code>private final float MAX_HEALTH = 500.0f;
</code>```

When I call the modifyHealth method on the second class, I want the health to be able to increase beyond 100, however currently it still uses the parent classs' final variable value. How can I make it so that the health can increase up to 500, while keeping both the variables final?

答:
As mentioned in the comments by others, think about changing the design (if you are in control of it). Otherwise you could use Reflection to access the field and change its value like: </p>

```<code>Field field = myParentclass.getDeclaredField("MAX_HEALTH");
field.setAccessible(true);
field.setFloat(yourInstance, 500.0f);
</code>```

Body:
Relevant code from my first class:

protected static final float MAX_HEALTH = 100.0f;
protected static final float MIN_HEALTH = 0.0f;

public void modifyHealth(float enteredAmount)
{
    if (health + enteredAmount > MAX_HEALTH )
    {
        health = MAX_HEALTH;
    }
    else if (health + enteredAmount < MIN_HEALTH)
    {
        health = MIN_HEALTH;
    }
    else
    {
        health += enteredAmount;
    }
}

Second class which extends the first class:

private final float MAX_HEALTH = 500.0f;

When I call the modifyHealth method on the second class, I want the health to be able to increase beyond 100, however currently it still uses the parent classs' final variable value. How can I make it so that the health can increase up to 500, while keeping both the variables final?

Body:
As mentioned in the comments by others, think about changing the design (if you are in control of it). Otherwise you could use Reflection to access the field and change its value like:

Field field = myParentclass.getDeclaredField("MAX_HEALTH");
field.setAccessible(true);
field.setFloat(yourInstance, 500.0f);


问:
SQL: One column with different types, how to query
I'll do my best to explain my issue, however most of my experience in SQL is self taught, so please bear with me.

I have a table [limit_table] which has a column called [amount], however this limit_table.amount column holds an amount but is for different limit types, the limit type is determined by the a column called LimitTypeid, which has a foreign-key link to another table [LimitType]

The limit_table also has a foreign key link to a [client] table.

What i am trying to do is to get the limit for each client in the [client] table where the LimitType = x out of those results i also want to know if the client as LimitType of y even if it doesn't exist.

For the life of me i can't get this to work? Any pointers would be great I have tried joining/left outer joining back into the client table using the client.id from the client table, but this didn't seem to work.

So LimitType X must be present (can be zero but not NULL) but LimitType y is optional.

Hoping to end with results that look basically like

```<code>Client   LimitTypeXAmount   LimitTypeYAmount
ClientA  15000.00           1000.00
ClientB  10000.00           NULL
ClientC  0                  1000.00
</code>```

Here is a previous query i tried:

```<code>SELECT CL.CLIENT, LIM.AMOUNT AS LIMITTYPEXAMOUNT, LIM2.AMOUNT AS LIMITTYPEYAMOUNT, FROM CLIENT CL1
INNER JOIN LIMIT LIM1 ON LIM1.CLIENTID = CL1.ID
INNER JOIN LIMITTYPE LT1 ON LIM1.LIMITTYPEID = LT1.ID AND LT1.TYPE = 'X'
LEFT OUTER JOIN CLIENT CL2 ON CL1.ID = CL2.ID
LEFT OUTER JOIN LIMIT LIM2 ON LIM2.CLIENTID = CL2.ID
LEFT OUTER JOIN LIMITTYPE LT2 ON LIM2.LIMITTYPEID = LT2.ID AND LT2.TYPE = 'Y'
</code>```

Presumed schema below (added by moderator):

```<code>create table Client (Id int not null, Client varchar(10) not null);
create table Limit (Id int not null, ClientId int not null, Amount decimal (8, 2) not null, LimitTypeId int not null);
create table LimitType (Id int not null, Type char(1) not null);

insert into LimitType (Id, Type) values (1, 'X'), (2, 'Y');
insert into Client (Id, Client) values (1, 'ClientA'), (2, 'ClientB'), (3, 'ClientC');
insert into Limit (Id, ClientId, Amount, LimitTypeId) values
    (1, 1, 15000.00, 1), (2, 1, 1000.00, 2), -- ClientA  15000.00    1000.00
    (3, 2, 10000.00, 1),                     -- ClientB  10000.00       NULL
    (4, 3,     0.00, 1), (5, 3, 1000.00, 2)  -- ClientC      0.00    1000.00
;
</code>```

答:
I'm not entirely sure why you have the LIMITTYPE table. I'm assuming there's only one row in that table with TYPE = 'Y'. So connecting to that as an inner join first should pull in just that one row and then you can link to the appropriate LIMITTYPEID. What I'm unclear about is why TYPE isn't just an attribute of LIMIT. You were referencing two different instances of the CLIENT table but that appears to be unnecessary and I removed it.

```<code>select
c.Client, l1.Amount as LimitTypeXAmount, l2.Amount as LimitTypeYAmount
from
    Client c
    inner join Limit as l1 on l1.ClientId = c.Id
    inner join LimitType as lt1 on lt1.Id = l1.LimitTypeId and lt1.Type = 'X'
    inner join LimitType as lt2 on lt2.Type = 'Y'
    left outer join Limit as l2 on l2.ClientId = c.Id and l2.LimitTypeId = lt2.Id;
</code>```

Assuming that works you could mirror that same logic in the earlier three joins. I'll leave those alone.

Another approaches uses a derived table:

```<code>-- derived table
SELECT
    C.CLIENT,
    L1.AMOUNT AS LIMITTYPEXAMOUNT,
    L2.LIMITTYPEYAMOUNT
FROM
    CLIENT C
    INNER JOIN LIMIT L1 ON L1.CLIENTID = C.ID
    INNER JOIN LIMITTYPE LT1 ON LT1.ID = L1.LIMITTYPEID
    LEFT OUTER JOIN (
        SELECT
            L.CLIENTID, L.AMOUNT AS LIMITTYPEYAMOUNT
        FROM
            LIMIT L
            INNER JOIN LIMITTYPE LT ON LT.ID = L.LIMITTYPEID
        WHERE
            LT.TYPE = 'Y'
    ) AS L2 ON L2.CLIENTID = C.ID
WHERE
    LT1.TYPE = 'X';
</code>```

And just for fun, with outer apply:

```<code>-- outer apply
SELECT
    C.CLIENT,
    L1.AMOUNT AS LIMITTYPEXAMOUNT,
    L2.LIMITTYPEYAMOUNT
FROM
    CLIENT C
    INNER JOIN LIMIT L1 ON L1.CLIENTID = C.ID
    INNER JOIN LIMITTYPE LT1 ON LT1.ID = L1.LIMITTYPEID
    OUTER APPLY (
        SELECT
            L.AMOUNT AS LIMITTYPEYAMOUNT
        FROM
            LIMIT L
            INNER JOIN LIMITTYPE LT ON LT.ID = L.LIMITTYPEID
        WHERE
            LT.TYPE = 'Y' AND L.CLIENTID = C.ID
    ) AS L2
WHERE
    LT1.TYPE = 'X';
</code>```

Edit: I guess I'm a little rusty since I didn't also immediately recognize this as a join order problem. Here's another approach you can study. It has the advantage of working on some older systems where other options aren't available.

```<code>select
    c.Client, l1.Amount as LimitTypeXAmount, l2.Amount as LimitTypeYAmount
from
    Client c
    inner join Limit as l1
        inner join LimitType as lt1
            on lt1.Id = l1.LimitTypeId and lt1.Type = 'X'
        on l1.ClientId = c.Id

    left outer join Limit as l2
        inner join LimitType as lt2
            on l2.LimitTypeId = lt2.Id and lt2.Type = 'Y'
        on l2.ClientId = c.Id;
</code>```

Play with it here: http://rextester.com/WJZ23471

Body:
I'll do my best to explain my issue, however most of my experience in SQL is self taught, so please bear with me.

I have a table [limit_table] which has a column called [amount], however this limit_table.amount column holds an amount but is for different limit types, the limit type is determined by the a column called LimitTypeid, which has a foreign-key link to another table [LimitType]

The limit_table also has a foreign key link to a [client] table.

What i am trying to do is to get the limit for each client in the [client] table where the LimitType = x out of those results i also want to know if the client as LimitType of y even if it doesn't exist.

For the life of me i can't get this to work? Any pointers would be great I have tried joining/left outer joining back into the client table using the client.id from the client table, but this didn't seem to work.

So LimitType X must be present (can be zero but not NULL) but LimitType y is optional.

Hoping to end with results that look basically like

Client   LimitTypeXAmount   LimitTypeYAmount
ClientA  15000.00           1000.00
ClientB  10000.00           NULL
ClientC  0                  1000.00

Here is a previous query i tried:

SELECT CL.CLIENT, LIM.AMOUNT AS LIMITTYPEXAMOUNT, LIM2.AMOUNT AS LIMITTYPEYAMOUNT, FROM CLIENT CL1
INNER JOIN LIMIT LIM1 ON LIM1.CLIENTID = CL1.ID
INNER JOIN LIMITTYPE LT1 ON LIM1.LIMITTYPEID = LT1.ID AND LT1.TYPE = 'X'
LEFT OUTER JOIN CLIENT CL2 ON CL1.ID = CL2.ID
LEFT OUTER JOIN LIMIT LIM2 ON LIM2.CLIENTID = CL2.ID
LEFT OUTER JOIN LIMITTYPE LT2 ON LIM2.LIMITTYPEID = LT2.ID AND LT2.TYPE = 'Y'

Presumed schema below (added by moderator):

create table Client (Id int not null, Client varchar(10) not null);
create table Limit (Id int not null, ClientId int not null, Amount decimal (8, 2) not null, LimitTypeId int not null);
create table LimitType (Id int not null, Type char(1) not null);

insert into LimitType (Id, Type) values (1, 'X'), (2, 'Y');
insert into Client (Id, Client) values (1, 'ClientA'), (2, 'ClientB'), (3, 'ClientC');
insert into Limit (Id, ClientId, Amount, LimitTypeId) values
    (1, 1, 15000.00, 1), (2, 1, 1000.00, 2), -- ClientA  15000.00    1000.00
    (3, 2, 10000.00, 1),                     -- ClientB  10000.00       NULL
    (4, 3,     0.00, 1), (5, 3, 1000.00, 2)  -- ClientC      0.00    1000.00
;

Body:
I'm not entirely sure why you have the LIMITTYPE table. I'm assuming there's only one row in that table with TYPE = 'Y'. So connecting to that as an inner join first should pull in just that one row and then you can link to the appropriate LIMITTYPEID. What I'm unclear about is why TYPE isn't just an attribute of LIMIT. You were referencing two different instances of the CLIENT table but that appears to be unnecessary and I removed it.

select
c.Client, l1.Amount as LimitTypeXAmount, l2.Amount as LimitTypeYAmount
from
    Client c
    inner join Limit as l1 on l1.ClientId = c.Id
    inner join LimitType as lt1 on lt1.Id = l1.LimitTypeId and lt1.Type = 'X'
    inner join LimitType as lt2 on lt2.Type = 'Y'
    left outer join Limit as l2 on l2.ClientId = c.Id and l2.LimitTypeId = lt2.Id;

Assuming that works you could mirror that same logic in the earlier three joins. I'll leave those alone.

Another approaches uses a derived table:

-- derived table
SELECT
    C.CLIENT,
    L1.AMOUNT AS LIMITTYPEXAMOUNT,
    L2.LIMITTYPEYAMOUNT
FROM
    CLIENT C
    INNER JOIN LIMIT L1 ON L1.CLIENTID = C.ID
    INNER JOIN LIMITTYPE LT1 ON LT1.ID = L1.LIMITTYPEID
    LEFT OUTER JOIN (
        SELECT
            L.CLIENTID, L.AMOUNT AS LIMITTYPEYAMOUNT
        FROM
            LIMIT L
            INNER JOIN LIMITTYPE LT ON LT.ID = L.LIMITTYPEID
        WHERE
            LT.TYPE = 'Y'
    ) AS L2 ON L2.CLIENTID = C.ID
WHERE
    LT1.TYPE = 'X';

And just for fun, with outer apply:

-- outer apply
SELECT
    C.CLIENT,
    L1.AMOUNT AS LIMITTYPEXAMOUNT,
    L2.LIMITTYPEYAMOUNT
FROM
    CLIENT C
    INNER JOIN LIMIT L1 ON L1.CLIENTID = C.ID
    INNER JOIN LIMITTYPE LT1 ON LT1.ID = L1.LIMITTYPEID
    OUTER APPLY (
        SELECT
            L.AMOUNT AS LIMITTYPEYAMOUNT
        FROM
            LIMIT L
            INNER JOIN LIMITTYPE LT ON LT.ID = L.LIMITTYPEID
        WHERE
            LT.TYPE = 'Y' AND L.CLIENTID = C.ID
    ) AS L2
WHERE
    LT1.TYPE = 'X';

Edit: I guess I'm a little rusty since I didn't also immediately recognize this as a join order problem. Here's another approach you can study. It has the advantage of working on some older systems where other options aren't available.

select
    c.Client, l1.Amount as LimitTypeXAmount, l2.Amount as LimitTypeYAmount
from
    Client c
    inner join Limit as l1
        inner join LimitType as lt1
            on lt1.Id = l1.LimitTypeId and lt1.Type = 'X'
        on l1.ClientId = c.Id

    left outer join Limit as l2
        inner join LimitType as lt2
            on l2.LimitTypeId = lt2.Id and lt2.Type = 'Y'
        on l2.ClientId = c.Id;

Play with it here: http://rextester.com/WJZ23471


问:
Can you reuse a fragment in multiple activities but with different functionalities?
Say I have a fragment that has three buttons and I want to reuse it for at least three activities, but I want those buttons to do different things for each activity. For example, in ActivityA, I want button1 to open Google Maps while in ActivityB, button1 goes to the music player. Is this possible or even the right way?</p>

答:
Is this possible?

It definetely is. You could just check which Activity is hosting your Fragment instance:

```<code>private void button1OnClick(){
 /* could also use instanceof, BUT: if you have something like ActivityC extends ActivityA
         then instanceof would evaluate to true for both */
   if(getActivity().getClass().equals(ActivityA.class)) {
     // do stuff
   } else if(getActivity().getClass().equals(ActivityB.class)) {
     // do another stuff
   }
}
</code>```

Is this the right way?

(attention opinionated answer)
It depends. If you have a complex and unique layout/functionality, I'd use different Fragments. If you have a simple layout with some buttons that just need to act differently in different Activities it is a good idea to reuse an existing Fragment class.

Body:
Is this possible?

It definetely is. You could just check which Activity is hosting your Fragment instance:

private void button1OnClick(){
 /* could also use instanceof, BUT: if you have something like ActivityC extends ActivityA
         then instanceof would evaluate to true for both */
   if(getActivity().getClass().equals(ActivityA.class)) {
     // do stuff
   } else if(getActivity().getClass().equals(ActivityB.class)) {
     // do another stuff
   }
}

Is this the right way?

(attention opinionated answer)
It depends. If you have a complex and unique layout/functionality, I'd use different Fragments. If you have a simple layout with some buttons that just need to act differently in different Activities it is a good idea to reuse an existing Fragment class.


问:
using mod_rewrite to create SEO friendly URLS
I've been searching google for this but can't find the solution to my exact needs. Basically I've already got my URL's named how I like them i.e. "http://mysite.com/blog/page1.php"

What I'm trying to achieve (if it's possible!) is to use rewrite to alter the existing URLS to: "http://mysite.com/blog/page1"

The problem I've come across is I've found examples that will do this if the user enters "http://mysite.com/blog/page1" into the broweser which is great, however I need it to work for the existing links in google as not to loose traffic, so incoming URLS "http://mysite.com/blog/page1.php" are directed to "http://mysite.com/blog/page1".

答:
This should do the trick, rewriting requests without .php to have it, invisible to the user.</p>

```<code>RewriteEngine On
RewriteRule ^/blog/([^.]+)$  /blog/$1.php
</code>```

Body:
This should do the trick, rewriting requests without .php to have it, invisible to the user.

RewriteEngine On
RewriteRule ^/blog/([^.]+)$  /blog/$1.php


问:
Angular 2 Material - Router animations broke sidenav content and scroll
I'm trying to add some router animations in my Angular 2 Material (angular/material2) application.
Without animations all works fine but when I add them to my components the content overflows the viewport and the scrolling behaviour does not work anymore.

To add animations I've defined a ts file router.animations.ts:

```<code>import { AnimationEntryMetadata, trigger, state, animate, style, transition } from "@angular/core";

export function slideToLeft(): AnimationEntryMetadata {
    "use strict";
    return trigger("slideToLeft", [
        state("void", style({ position: "fixed", width: "100%" })),
        state("*", style({ position: "fixed", width: "100%" })),
        transition(":enter", [
            style({ transform: "translateX(100%)" }),
            animate("0.5s ease-in-out", style({ transform: "translateX(0%)" }))
        ]),
        transition(":leave", [
            style({ transform: "translateX(0%)" }),
            animate("0.5s ease-in-out", style({ transform: "translateX(-100%)" }))
        ])
    ]);
}
</code>```

Then inside my components:

```<code>import { Component } from "@angular/core";
import { slideToLeft } from "./router.animations";

@Component({
    selector: "home",
    templateUrl: "src/home.component.html",
    animations: [slideToLeft()],
    host: { "[@slideToLeft]": "" }
})
export class HomeComponent  {

    constructor() {
    }
}
</code>```

Here is a plunker which shows the issue:

https://plnkr.co/edit/Vz1iqSmcWwu3QG65Qxgw?p=preview

Ho can I solve this?

答:
Scrolling is disabled because the component is set to "position: fixed" due to the animation. Changing the second state to "position: relative" and resetting the position in the leave transition will fix this:</p>

```<code>export function slideToLeft(): AnimationEntryMetadata {
    "use strict";
    return trigger("slideToLeft", [
        state("void", style({ position: "fixed", width: "100%" })),
        state('*', style({position:'relative', width:'100%'}) ),
        transition(":enter", [
            style({ transform: "translateX(100%)" }),
            animate("0.5s ease-in-out", style({ transform: "translateX(0%)" }))
        ]),
        transition(":leave", [
            style({transform: 'translateX(0%)', position:'fixed', width:'100%'}),
            animate("0.5s ease-in-out", style({ transform: "translateX(-100%)" }))
        ])
    ]);
}
</code>```

Body:
I'm trying to add some router animations in my Angular 2 Material (angular/material2) application.
Without animations all works fine but when I add them to my components the content overflows the viewport and the scrolling behaviour does not work anymore.

To add animations I've defined a ts file router.animations.ts:

import { AnimationEntryMetadata, trigger, state, animate, style, transition } from "@angular/core";

export function slideToLeft(): AnimationEntryMetadata {
    "use strict";
    return trigger("slideToLeft", [
        state("void", style({ position: "fixed", width: "100%" })),
        state("*", style({ position: "fixed", width: "100%" })),
        transition(":enter", [
            style({ transform: "translateX(100%)" }),
            animate("0.5s ease-in-out", style({ transform: "translateX(0%)" }))
        ]),
        transition(":leave", [
            style({ transform: "translateX(0%)" }),
            animate("0.5s ease-in-out", style({ transform: "translateX(-100%)" }))
        ])
    ]);
}

Then inside my components:

import { Component } from "@angular/core";
import { slideToLeft } from "./router.animations";

@Component({
    selector: "home",
    templateUrl: "src/home.component.html",
    animations: [slideToLeft()],
    host: { "[@slideToLeft]": "" }
})
export class HomeComponent  {

    constructor() {
    }
}

Here is a plunker which shows the issue:

https://plnkr.co/edit/Vz1iqSmcWwu3QG65Qxgw?p=preview

Ho can I solve this?

Body:
Scrolling is disabled because the component is set to "position: fixed" due to the animation. Changing the second state to "position: relative" and resetting the position in the leave transition will fix this:

export function slideToLeft(): AnimationEntryMetadata {
    "use strict";
    return trigger("slideToLeft", [
        state("void", style({ position: "fixed", width: "100%" })),
        state('*', style({position:'relative', width:'100%'}) ),
        transition(":enter", [
            style({ transform: "translateX(100%)" }),
            animate("0.5s ease-in-out", style({ transform: "translateX(0%)" }))
        ]),
        transition(":leave", [
            style({transform: 'translateX(0%)', position:'fixed', width:'100%'}),
            animate("0.5s ease-in-out", style({ transform: "translateX(-100%)" }))
        ])
    ]);
}


问:
Angular Url without slash with optional parameters
Both ui-router optional param without trailing slash
and How to define optional parameter using UI-Router without trailing slash as well? have insufficient arguments and invalid (at least for my scenario i.e. working links (href) for angular routes without trailing slashes) answers .

Live Demo Link

Here are the example html links

```<code> <div>
    <a ui-sref="home">Home</a>
    | <a href="#/posting/">Post 1</a>
    | <a href="#/posting">Post 2</a>
    | <a href="#/posting/sami">Post 3</a>
    | <a ui-sref="post">Post 4</a>
    | <a ui-sref="post({nam:'sami'})">Post 5</a>
</div>
</code>```

All of the above links are working fine except Post 2 because I have an optional parameter and so the link needs at least a slash at the end

I am using stateprovider and a state looks like

```<code>name: 'post',
val: {
    url : '/posting/:nam',
    views: {
        v1: {
         template: '<h4>Posting <label ng-if="stateParams.nam">{{stateParams.nam}}</label> </h4>',
         controller: 'post',
            resolve: {
              deps: function ($ocLazyLoad) {
                  return $ocLazyLoad.load([{ name: appName, files: ['post.js'] }]);
              }
            }
        },
        params: {
            nam: { squash: true, value: null }
        }
    }
 }
</code>```

How can i have a valid link without trailing slash if I have only option to use links href and not the ui-sref

答:
In case you like me tried @egor.xyz solution, and it didn't work. check the  ui-router Frequent Questions, and you will find the following:

For older version of ui-router, add this snippet to your module's config function. It creates a rule on $urlRouterProvider that maps all urls that are missing a trailing slash to the same url but with the trailing slash appended.

```<code>$urlRouterProvider.rule(function ($injector, $location) {
    var path = $location.url();

    // check to see if the path already has a slash where it should be
    if (path[path.length - 1] === '/' || path.indexOf('/?') > -1) {
        return;
    }

    if (path.indexOf('?') > -1) {
        return path.replace('?', '/?');
    }

    return path + '/';
});
</code>```

Worked for me.

Body:
Both ui-router optional param without trailing slash
and How to define optional parameter using UI-Router without trailing slash as well? have insufficient arguments and invalid (at least for my scenario i.e. working links (href) for angular routes without trailing slashes) answers .

Live Demo Link

Here are the example html links

    Home
    | Post 1
    | Post 2
    | Post 3
    | Post 4
    | Post 5

All of the above links are working fine except Post 2 because I have an optional parameter and so the link needs at least a slash at the end

I am using stateprovider and a state looks like

name: 'post',
val: {
    url : '/posting/:nam',
    views: {
        v1: {
         template: '
Posting {{stateParams.nam}}
',
         controller: 'post',
            resolve: {
              deps: function ($ocLazyLoad) {
                  return $ocLazyLoad.load([{ name: appName, files: ['post.js'] }]);
              }
            }
        },
        params: {
            nam: { squash: true, value: null }
        }
    }
 }

How can i have a valid link without trailing slash if I have only option to use links href and not the ui-sref

Body:
In case you like me tried @egor.xyz solution, and it didn't work. check the  ui-router Frequent Questions, and you will find the following:

For older version of ui-router, add this snippet to your module's config function. It creates a rule on $urlRouterProvider that maps all urls that are missing a trailing slash to the same url but with the trailing slash appended.

$urlRouterProvider.rule(function ($injector, $location) {
    var path = $location.url();

    // check to see if the path already has a slash where it should be
    if (path[path.length - 1] === '/' || path.indexOf('/?') > -1) {
        return;
    }

    if (path.indexOf('?') > -1) {
        return path.replace('?', '/?');
    }

    return path + '/';
});

Worked for me.


问:
How to use .format() string in a MySQL statement?
I'm trying to format a MySQL statement with today's data, as well as 7 days back. I'm pretty sure the date is in the correct format, so I don't think that's the issue.

The error report is:

```<code> Warning: (1292, "Incorrect datetime value: '{} 16:00:00' for column 'run_start_date' at row 1")
      result = self._query(query)
    Traceback (most recent call last):
         AttributeError: 'int' object has no attribute 'format'
</code>```

e.g.

```<code>today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
print(today.strftime('%Y-%m-%d'))
print(week_ago.strftime('%Y-%m-%d'))

cursor.execute(SELECT * FROM db WHERE run_start_date BETWEEN '{} 16:00:00' AND '{} 16:00:00'format(week_ago, today)
</code>```

答:
Using prepared statements (safe way):

```<code>qry = """
    SELECT *
    FROM db
    WHERE run_start_date BETWEEN '%s 16:00:00' AND '%s 16:00:00'
""" #

today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
today = str(today.strftime('%Y-%m-%d'))  # Convert to string
week_ago = str(week_ago.strftime('%Y-%m-%d'))  # Convert to string

cursor.execute(qry, [today, week_ago])
</code>```

Using .format() which leaves you at risk for sql injections (if you pass user input to .format() e.g.)

```<code>qry = """
    SELECT *
    FROM db
    WHERE run_start_date BETWEEN '{today} 16:00:00' AND '{week_ago} 16:00:00'
""" # Use named placeholders, nicer to read, prevents you having to repeat variables multiple time when calling .format()

today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
today = str(today.strftime('%Y-%m-%d'))  # Convert to string
week_ago = str(week_ago.strftime('%Y-%m-%d'))  # Convert to string

qry = qry.format(today=today, week_ago=week_ago)
cursor.execute(qry)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to format a MySQL statement with today's data, as well as 7 days back. I'm pretty sure the date is in the correct format, so I don't think that's the issue.

The error report is:

 Warning: (1292, "Incorrect datetime value: '{} 16:00:00' for column 'run_start_date' at row 1")
      result = self._query(query)
    Traceback (most recent call last):
         AttributeError: 'int' object has no attribute 'format'

e.g.

today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
print(today.strftime('%Y-%m-%d'))
print(week_ago.strftime('%Y-%m-%d'))

cursor.execute(SELECT * FROM db WHERE run_start_date BETWEEN '{} 16:00:00' AND '{} 16:00:00'format(week_ago, today)

Body:
Using prepared statements (safe way):

qry = """
    SELECT *
    FROM db
    WHERE run_start_date BETWEEN '%s 16:00:00' AND '%s 16:00:00'
""" #

today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
today = str(today.strftime('%Y-%m-%d'))  # Convert to string
week_ago = str(week_ago.strftime('%Y-%m-%d'))  # Convert to string

cursor.execute(qry, [today, week_ago])

Using .format() which leaves you at risk for sql injections (if you pass user input to .format() e.g.)

qry = """
    SELECT *
    FROM db
    WHERE run_start_date BETWEEN '{today} 16:00:00' AND '{week_ago} 16:00:00'
""" # Use named placeholders, nicer to read, prevents you having to repeat variables multiple time when calling .format()

today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
today = str(today.strftime('%Y-%m-%d'))  # Convert to string
week_ago = str(week_ago.strftime('%Y-%m-%d'))  # Convert to string

qry = qry.format(today=today, week_ago=week_ago)
cursor.execute(qry)


问:
Return even if more associations than scope asks
I have Users and Languages tables, joined by LanguagesUsers. LanguagesUsers stores the language_id, user_id, and level.
Users can have unlimited LanguagesUsers.

I want to get all users who have any two languages. I have two scopes in my user model:

```<code>scope :seeking_proficiency_in, ->(language) {
  joins(:languages_users).where("level < 5 and language_id = ?", language)
}
scope :proficient_in, ->(language) {
  joins(:languages_users).where("level > 4 and language_id = ?", language)
}
</code>```

I want to pass two languages, and find users who have both these scopes. The query is like this:

```<code>@users =
  (User.seeking_proficiency_in(1) && User.proficient_in(2)) ||
  (User.seeking_proficiency_in(2) && User.proficient_in(1))
</code>```

This returns all users who have both languages and the appropriate level of the languages. The issue is that user that have more than two languages are not included; only users with exactly the two languages are included.

How can I get all users even if they have more languages than the two given?

UPDATE
To give more context, this would work, but I feel there is a simple, one-two step version I am not comprehending:

```<code>learning = User.seeking_proficiency_in(1)
fluent = User.proficient_in(2)
matches = learning & fluent

learning = User.seeking_proficiency_in(2)
fluent = User.proficient_in(1)
second_matches = learning & fluent

all_matches = matches + second_matches
</code>```

答:
I thought I wasn't just aware of the additional usage of && and || recently added to ActiveRecord.  I think that's your issue there.

@users is effectively just User.proficient_in(2) because of how && and || operators work.  See examples below

```<code>  >> nil && true                            # nil
  >> true && 1                              # 1
  >> [] && 1                                # 1
  >> User.where(id: 1) && User.where(id: 2) # result will be the result of User.where(id: 2)
</code>```

Since User.where(...) queries return an ActiveRecord::Relation object, the returned value is not falsy therefore the second part of your code (the one that comes after ||) is never executed.

In short, you cannot use && and || to merge ActiveRecord queries.  Try the following instead

```<code> inverse = User.seeking_proficiency_in(2).proficient_in(1)
 @users = User.seeking_proficiency_in(1).proficient_in(2).or(inverse)
</code>```

Body:
I have Users and Languages tables, joined by LanguagesUsers. LanguagesUsers stores the language_id, user_id, and level.
Users can have unlimited LanguagesUsers.

I want to get all users who have any two languages. I have two scopes in my user model:

scope :seeking_proficiency_in, ->(language) {
  joins(:languages_users).where("level < 5 and language_id = ?", language)
}
scope :proficient_in, ->(language) {
  joins(:languages_users).where("level > 4 and language_id = ?", language)
}

I want to pass two languages, and find users who have both these scopes. The query is like this:

@users =
  (User.seeking_proficiency_in(1) && User.proficient_in(2)) ||
  (User.seeking_proficiency_in(2) && User.proficient_in(1))

This returns all users who have both languages and the appropriate level of the languages. The issue is that user that have more than two languages are not included; only users with exactly the two languages are included.

How can I get all users even if they have more languages than the two given?

UPDATE
To give more context, this would work, but I feel there is a simple, one-two step version I am not comprehending:

learning = User.seeking_proficiency_in(1)
fluent = User.proficient_in(2)
matches = learning & fluent

learning = User.seeking_proficiency_in(2)
fluent = User.proficient_in(1)
second_matches = learning & fluent

all_matches = matches + second_matches

Body:
I thought I wasn't just aware of the additional usage of && and || recently added to ActiveRecord.  I think that's your issue there.

@users is effectively just User.proficient_in(2) because of how && and || operators work.  See examples below

  >> nil && true                            # nil
  >> true && 1                              # 1
  >> [] && 1                                # 1
  >> User.where(id: 1) && User.where(id: 2) # result will be the result of User.where(id: 2)

Since User.where(...) queries return an ActiveRecord::Relation object, the returned value is not falsy therefore the second part of your code (the one that comes after ||) is never executed.

In short, you cannot use && and || to merge ActiveRecord queries.  Try the following instead

 inverse = User.seeking_proficiency_in(2).proficient_in(1)
 @users = User.seeking_proficiency_in(1).proficient_in(2).or(inverse)


答:
Yes you can, but you have to add more logic to your fragments and add some interfaces for each activity.
I don't recommend to do that, maybe you could reuse your layouts. </p>

Title: Can you reuse a fragment in multiple activities but with different functionalities?

Body: Say I have a fragment that has three buttons and I want to reuse it for at least three activities, but I want those buttons to do different things for each activity. For example, in ActivityA, I want button1 to open Google Maps while in ActivityB, button1 goes to the music player. Is this possible or even the right way?


问:
How to deal with library of images in android?
I'm rewriting existing Windows application to android.

My application is a kind of customizeable picture communicator for people with disabilities. It uses about 300 categorized images and this number is growing. They take 100-300kB each.

In Windows version I just have a folder with subfolders and I'm copying it to Program files\My application in installer. During runtime I just read images and folder tree from filesystem.

Now I want to re-use this folder structure with images in Android application, but my knowledge about Android development is poor.

My question:

How can I "include" whole folder of images in apk file and make it "expand" to somewhere in filesystem during installation?

My minSdkVersion is 21.

答:
My question(s):

How can I add a folder with 300 images to my Android app?

You would get Environment.getExternalStorageDirectory() which is where directories like Pictures are, or for app internal storage context.getFilesDir() - which is private to your app - this is the location where databases and preferences are.

download from internet during first application run and store them in filesystem?
      copy my folder to resources in Android project?

You could hook into the onCreate() of either your Application class, or launcher Activity hooks.

Few things to note:

If you want to store directly in internal app folder you only require Internet permissions in your Manifest, however if using external sotrage you will need READ/WRITE permissions, and targeting Marshmallow+ will require handling runtime permissions.  Also downloading 300 images without user consent could be bad practice, consider letting user decide first.

As you have mentioned you are happy with handling I/O I won't go into any detail regarding this.


问:
wp_schedule_event() in plugin not scheduling a cron event
I'm creating a WordPress plugin, when the plugin is activated I need a cron job to be scheduled to run every 5 minutes.

Here's my code;

```<code>// Register plugin activation hook
function my_plugin_activate() {
    if( !wp_next_scheduled( 'my_function_hook' ) ) {
       wp_schedule_event( time(), '5', 'my_function_hook' );
    }
}
register_activation_hook( __FILE__, 'my_plugin_activate' );

// Register plugin deactivation hook
function my_plugin_deactivate(){
    wp_clear_scheduled_hook('my_function_hook');
}
register_deactivation_hook(__FILE__,'my_plugin_deactivate');

// Function I want to run when cron event runs
function my_function(){
    //Function code
}
add_action( 'my_function_hook', 'my_function');
</code>```

When I use this plugin https://wordpress.org/plugins/wp-crontrol/ to check the cron events, nothing has been added, I'm expecting a cron event to be added that runs 'my_function' at 5 minute intervals, I have no errors

答:
See: wp_schedule_event()

Valid values for the recurrence are hourly, daily, and twicedaily.
  These can be extended using the ‘cron_schedules’ filter in
  wp_get_schedules().

So you just need to add a custom schedule that runs every 5 minutes.

```<code><?php // Requires PHP 5.4+.

add_filter( 'cron_schedules', function ( $schedules ) {
    $schedules['every-5-minutes'] = array(
        'interval' => 5 * MINUTE_IN_SECONDS,
        'display'  => __( 'Every 5 minutes' )
    );
    return $schedules;
} );

if( ! wp_next_scheduled( 'my_function_hook' ) ) {
    wp_schedule_event( time(), 'every-5-minutes', 'my_function_hook' );
}
</code>```

Body:
I'm creating a WordPress plugin, when the plugin is activated I need a cron job to be scheduled to run every 5 minutes.

Here's my code;

// Register plugin activation hook
function my_plugin_activate() {
    if( !wp_next_scheduled( 'my_function_hook' ) ) {
       wp_schedule_event( time(), '5', 'my_function_hook' );
    }
}
register_activation_hook( __FILE__, 'my_plugin_activate' );

// Register plugin deactivation hook
function my_plugin_deactivate(){
    wp_clear_scheduled_hook('my_function_hook');
}
register_deactivation_hook(__FILE__,'my_plugin_deactivate');

// Function I want to run when cron event runs
function my_function(){
    //Function code
}
add_action( 'my_function_hook', 'my_function');

When I use this plugin https://wordpress.org/plugins/wp-crontrol/ to check the cron events, nothing has been added, I'm expecting a cron event to be added that runs 'my_function' at 5 minute intervals, I have no errors

Body:
See: wp_schedule_event()

Valid values for the recurrence are hourly, daily, and twicedaily.
  These can be extended using the ‘cron_schedules’ filter in
  wp_get_schedules().

So you just need to add a custom schedule that runs every 5 minutes.

<?php // Requires PHP 5.4+.

add_filter( 'cron_schedules', function ( $schedules ) {
    $schedules['every-5-minutes'] = array(
        'interval' => 5 * MINUTE_IN_SECONDS,
        'display'  => __( 'Every 5 minutes' )
    );
    return $schedules;
} );

if( ! wp_next_scheduled( 'my_function_hook' ) ) {
    wp_schedule_event( time(), 'every-5-minutes', 'my_function_hook' );
}


问:
Sizing problem with WPF's grid layout
Here's my problem. I have three controls in a row (they capture people's names). The controls themselves size themselves to an appropriate size. I want to space these three controls horizontally to be evenly spaced along the line. This bit is easy:

```<code><Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*"/>
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>
  <Grid.RowDefinitions>
    <RowDefinition />
  </Grid.RowDefinitions>
  <Border Grid.Row="0" Grid.Column="0" BorderThickness="2" Height="50" Width="50" />
  <Border Grid.Row="0" Grid.Column="1" BorderThickness="2" Height="50" Width="50" />
  <Border Grid.Row="0" Grid.Column="2" BorderThickness="2" Height="50" Width="50" />
</Grid>
</code>```

The problem comes when I want to hide the second entry. If I set its visibility to collapsed, I would want the two remaining items to be equally spaced. This does not happen, the middle column remains at 1/3 of the grid's width.

I have tried various combinations of grids and stackpanels but cannot find a way around this. I am trying to find a fairly generic solution as this situation may arise again.

Visually, it should look like:

```<code>   +----------------------------------------------+
   | +------------+ +------------+ +------------+ |
   | |aardvark    | |beatle      | |cat         | |
   | +------------+ +------------+ +------------+ |
   +----------------------------------------------+
</code>```

Note that the inner boxes use the width=* to size them to 1/3 but the controls inside the boxes are not stretched.

答:
Instead of setting Visibility, set the Width of the ColumnDefinition to 0

suppose the name of the grid is grid1 then

```<code>grid1.ColumnDefinitions[1].Width = new GridLength(0);
</code>```

Title: Sizing problem with WPF's grid layout

Body:
Here's my problem. I have three controls in a row (they capture people's names). The controls themselves size themselves to an appropriate size. I want to space these three controls horizontally to be evenly spaced along the line. This bit is easy:

<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*"/>
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>
  <Grid.RowDefinitions>
    <RowDefinition />
  </Grid.RowDefinitions>
  <Border Grid.Row="0" Grid.Column="0" BorderThickness="2" Height="50" Width="50" />
  <Border Grid.Row="0" Grid.Column="1" BorderThickness="2" Height="50" Width="50" />
  <Border Grid.Row="0" Grid.Column="2" BorderThickness="2" Height="50" Width="50" />
</Grid>

The problem comes when I want to hide the second entry. If I set its visibility to collapsed, I would want the two remaining items to be equally spaced. This does not happen, the middle column remains at 1/3 of the grid's width.

I have tried various combinations of grids and stackpanels but cannot find a way around this. I am trying to find a fairly generic solution as this situation may arise again.

Visually, it should look like:

   +----------------------------------------------+
   | +------------+ +------------+ +------------+ |
   | |aardvark    | |beatle      | |cat         | |
   | +------------+ +------------+ +------------+ |
   +----------------------------------------------+

Note that the inner boxes use the width=* to size them to 1/3 but the controls inside the boxes are not stretched.

Body:
Instead of setting Visibility, set the Width of the ColumnDefinition to 0

suppose the name of the grid is grid1 then

grid1.ColumnDefinitions[1].Width = new GridLength(0);


问:
Is there a way to create an Azure Data Science VM using Terraform?
I am using Terraform to create Azure VMs, but since those don't have much functionality installed, I was investigating on other Azure resources. I found the Azure Data Science VM is the one that covers most of my requirements, so I was wondering if there is a way to create those with Terraform. I can't see it in the documentation, but maybe there is a workaround.

Any orientation on this would be great!

答:
Here is the list of SKUs and Offers for the Azure Data Science VM.

Windows Server 2016 edition: offer=windows-data-science-vm sku=windows2016

Ubuntu edition: offer=linux-data-science-vm-ubuntu sku=linuxdsvmubuntu

Windows Server 2012 edition: offer=standard-data-science-vm sku=standard-data-science-vm

CentOS edition: offer=linux-data-science-vm sku=linuxdsvm

Publisher for all these is microsoft-ads