问:
how to produce a customer retention table /cohort analysis with SQL
I'm trying to write an SQL query (Presto SQL syntax) to produce a customer retention table (see sample below).
A customer who makes at least one transaction in a month is considered as retained for that month.

this is the table

```<code>user_id       transaction_date
bdcff651- .   2018-01-01
bdcff641 .     2018-03-15
</code>```

this is the result I would like to get

The first row should be understood as follows:
Out of all customers who made their first transaction in the month of Jan 2018 (defined as “Jan Activation Cohort”), 35% subsequently made a transaction during the one month period following their first transaction date, 23% in the next month, 15% in the next month and so on.

```<code>  Date         1st Month   2nd Month       3rd Month

2018-01-01      35%               23% .         15%
2018-02-0       33 %             26% .         13%
2018-03-0       36%               27%           12%
</code>```

As an example, if person XYZ makes his first transaction on 10th February 2018, his 1st month will be from 11th February 2018 to 10th March 2018, 2nd month will be from 11th March 2018 to 10th April 2018 and so on. This person’s details need to appear in the Feb 2018 cohort in the Customer Retention Table.

would appreciate any help! thanks.

答:
You can use conditional aggregation.  However, I am not sure what your real calculations are.

If I just use the built-in definitions of date_diff(), then the logic looks like:

```<code>select date_trunc(month, first_td) as yyyymm,
       count(distinct user_id) as cnt,
       (count(distinct case when date_diff(month, first_td, transaction_date) = 1
                            then user_id
                       end) /
        count(distinct user_id)
       ) as month_1_ratio,
       (count(distinct case when date_diff(month, first_td, transaction_date) = 2
                            then user_id
                       end) /
        count(distinct user_id)
       ) as month_2_ratio
from (select t.*,
             min(transaction_date) over (partition by user_id) as first_td
      from t
     ) t
group by date_trunc(month, first_td)
order by yyyymm;
</code>```

Body:
I'm trying to write an SQL query (Presto SQL syntax) to produce a customer retention table (see sample below).
A customer who makes at least one transaction in a month is considered as retained for that month.

this is the table

user_id       transaction_date
bdcff651- .   2018-01-01
bdcff641 .     2018-03-15

this is the result I would like to get

The first row should be understood as follows:
Out of all customers who made their first transaction in the month of Jan 2018 (defined as “Jan Activation Cohort”), 35% subsequently made a transaction during the one month period following their first transaction date, 23% in the next month, 15% in the next month and so on.

  Date         1st Month   2nd Month       3rd Month

2018-01-01      35%               23% .         15%
2018-02-0       33 %             26% .         13%
2018-03-0       36%               27%           12%

As an example, if person XYZ makes his first transaction on 10th February 2018, his 1st month will be from 11th February 2018 to 10th March 2018, 2nd month will be from 11th March 2018 to 10th April 2018 and so on. This person’s details need to appear in the Feb 2018 cohort in the Customer Retention Table.

would appreciate any help! thanks.

Body:
You can use conditional aggregation.  However, I am not sure what your real calculations are.

If I just use the built-in definitions of date_diff(), then the logic looks like:

select date_trunc(month, first_td) as yyyymm,
       count(distinct user_id) as cnt,
       (count(distinct case when date_diff(month, first_td, transaction_date) = 1
                            then user_id
                       end) /
        count(distinct user_id)
       ) as month_1_ratio,
       (count(distinct case when date_diff(month, first_td, transaction_date) = 2
                            then user_id
                       end) /
        count(distinct user_id)
       ) as month_2_ratio
from (select t.*,
             min(transaction_date) over (partition by user_id) as first_td
      from t
     ) t
group by date_trunc(month, first_td)
order by yyyymm;


来源: stackexchange

问:
Flattening a list of NumPy arrays?
It appears that I have data in the format of a list of NumPy arrays (type() = np.ndarray):

```<code>[array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]),
array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]),
array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]),
array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]),
array([[ 0.00353654]])]
</code>```

I am trying to put this into a polyfit function:

```<code>m1 = np.polyfit(x, y, deg=2)
</code>```

However, it returns the error: TypeError: expected 1D vector for x

I assume I need to flatten my data into something like:

```<code>[0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654 ...]
</code>```

I have tried a list comprehension which usually works on lists of lists, but this as expected has not worked:

```<code>[val for sublist in risks for val in sublist]
</code>```

What would be the best way to do this?

答:
Another way using itertools for flattening the array:

```<code>import itertools

# Recreating array from question
a = [np.array([[0.00353654]])] * 13

# Make an iterator to yield items of the flattened list and create a list from that iterator
flattened = list(itertools.chain.from_iterable(a))
</code>```

This solution should be very fast, see https://stackoverflow.com/a/408281/5993892 for more explanation.

If the resulting data structure should be a numpy array instead, use numpy.fromiter() to exhaust the iterator into an array:

```<code># Make an iterator to yield items of the flattened list and create a numpy array from that iterator
flattened_array = np.fromiter(itertools.chain.from_iterable(a), float)
</code>```

Docs for itertools.chain.from_iterable():
https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable

Docs for numpy.fromiter():
https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html

ContentLicense: CC BY-SA 3.0

Title: Flattening a list of NumPy arrays?

Body:
It appears that I have data in the format of a list of NumPy arrays (type() = np.ndarray):

[array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]),
array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]),
array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]),
array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]),
array([[ 0.00353654]])]

I am trying to put this into a polyfit function:

m1 = np.polyfit(x, y, deg=2)

However, it returns the error: TypeError: expected 1D vector for x

I assume I need to flatten my data into something like:

[0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654 ...]

I have tried a list comprehension which usually works on lists of lists, but this as expected has not worked:

[val for sublist in risks for val in sublist]

What would be the best way to do this?

Body:
Another way using itertools for flattening the array:

import itertools

# Recreating array from question
a = [np.array([[0.00353654]])] * 13

# Make an iterator to yield items of the flattened list and create a list from that iterator
flattened = list(itertools.chain.from_iterable(a))

This solution should be very fast, see https://stackoverflow.com/a/408281/5993892 for more explanation.

If the resulting data structure should be a numpy array instead, use numpy.fromiter() to exhaust the iterator into an array:

# Make an iterator to yield items of the flattened list and create a numpy array from that iterator
flattened_array = np.fromiter(itertools.chain.from_iterable(a), float)

Docs for itertools.chain.from_iterable():
https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable

Docs for numpy.fromiter():
https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html

ContentLicense: CC BY-SA 4.0


问:
How to choose HTTP status code for unavailable event
Description:

The user inquires about the availability of the event on a given day.

Question:
Which response code should I send back if new event can not be created on this day? 404? 400? 422?

My choice:
I chose the "404 Not Found" status code:

```<code>{
  "statusCode": 404,
  "error": "Not Found",
  "message": "The event can not be created on the selected date."
}
</code>```

答:
As a response to a POST request I would use the 422 Unprocessable Entity status code along with a description of why the request could not be processed. </p>

<p>If you only want to test if there is already an event at this day, perform a GET request (for example: /event/2019-06-01) to check if it exists.
If it does not exist yet, respond with a 404 not found. </p>

Body:
Description:

The user inquires about the availability of the event on a given day.

Question:
Which response code should I send back if new event can not be created on this day? 404? 400? 422?

My choice:
I chose the "404 Not Found" status code:

{
  "statusCode": 404,
  "error": "Not Found",
  "message": "The event can not be created on the selected date."
}

Body:
As a response to a POST request I would use the 422 Unprocessable Entity status code along with a description of why the request could not be processed.

If you only want to test if there is already an event at this day, perform a GET request (for example: /event/2019-06-01) to check if it exists.
If it does not exist yet, respond with a 404 not found.


问:
is it possible to add Google recaptcha v2(Checkbox I'm not robot) in contact form 7
I have created a contact form 7 application form. I want to add Google recaptcha v2. I don't want v3 of Google recaptcha.

    First Name [text* first-name id:speci minlength:3 maxlength:20]

    Last Name [text* last-name id:speci minlength:3 maxlength:20]

    Email [email* email maxlength:30]

    Phone [tel* tel minlength:8 maxlength:20]

    Description [textarea* Description]

  [submit id:contact-submit "Send"]

```

that's a dummy site key

答:
You can use the contact form 7 integration method. If you haven't done that already:

Go to Google’s reCAPTCHA admin page.

Register your site.

Get a site key and secret key.

Choose the reCAPTCHA v2 + Checkbox type.

Copy the key pair into the WordPress admin screen of the site you registered.

Go to the admin menu Contact > Integration.

Find reCAPTCHA panel and click Configure Keys.

Copy the site key and secret key into the fields and save them.

Finally instead of using

```

Just use:

[recaptcha size:compact]

Check source here

Body:
I have created a contact form 7 application form. I want to add Google recaptcha v2. I don't want v3 of Google recaptcha.

    First Name [text* first-name id:speci minlength:3 maxlength:20]

    Last Name [text* last-name id:speci minlength:3 maxlength:20]

    Email [email* email maxlength:30]

    Phone [tel* tel minlength:8 maxlength:20]

    Description [textarea* Description]

  [submit id:contact-submit "Send"]

that's a dummy site key

Body:
You can use the contact form 7 integration method. If you haven't done that already:

Go to Google’s reCAPTCHA admin page.

Register your site.

Get a site key and secret key.

Choose the reCAPTCHA v2 + Checkbox type.

Copy the key pair into the WordPress admin screen of the site you registered.

Go to the admin menu Contact > Integration.

Find reCAPTCHA panel and click Configure Keys.

Copy the site key and secret key into the fields and save them.

Finally instead of using

<div class="g-recaptcha" data-sitekey="cvvdfvvdsvkjgjksdncscs"></div>

Just use:

[recaptcha size:compact]

Check source here


问:
Can QTimer fire when the queue is not empty?
If there are both overdue QTimer-s and events waiting in event queue, what will QT dispatcher do?  Fire the timers and run functions connected to them, or process events?  In other words, can a timer fire when the event queue is not empty?</p>

答:
A QTimer firing is an event. See:

https://doc.qt.io/qt-5/qobject.html#timerEvent

Timer events are processed together with all the other events. QTimer is just a nice API around timer events, so that you don't have to deal with them manually. The QTimer class takes care of that for you.


问:
Android: broadcast receiver to get GPS position
i would like to be notified when the user is near a certain GPS position with a specific intent filter: do you know if it is possible in an Android app?</p>

答: If I understand you correctly you should look at LocationManager.addProximityAlert(double latitude, double longitude, float radius, long expiration, PendingIntent intent).  When you are within proximity of the GPS coords the PendingIntent will be fired off.


问:
Why computing the mse step by step don't yield the same solution as MSE function?
I tried to calculate the mse value for a test set by hand and by using the MSE function from the MLmetrics package but get different results.

Here is a reproducible example:

```<code>ActualValuesExample <- c(1,1,3,3,2,5,1)
MSE(PredictionExample,ActualValuesExample)
Bias <- mean(PredictionExample-ActualValuesExample)
Variance <- mean((PredictionExample-ActualValuesExample)^2)
# MSE = Bias^2 + Variance
(Bias)^2 + Variance
</code>```

0.4489796 is the result for the computation by hand and 0.4285714 the result of the MSE function.

Where is my mistake, why i dotn get the same results?

答:
I don't understand why you add (Bias)^2 and Variance. MSE is simply equal to:

mean((PredictionExample-ActualValuesExample)^2) by definition. This is the variance variable in your example. More explicitly MSE is the mean of squred errors. Here error refers to (actual - predicted). I tried for an artifical value set and get the same results. Below is the code:

```<code>> ActualValuesExample <- c(1,1,3,3,2,5,1)
> PredictionExample <-   c(3,1,2,4,3,2,2)
> MSE(PredictionExample,ActualValuesExample) == mean((PredictionExample-ActualValuesExample)^2)
[1] TRUE
</code>```

Body:
I tried to calculate the mse value for a test set by hand and by using the MSE function from the MLmetrics package but get different results.

Here is a reproducible example:

ActualValuesExample <- c(1,1,3,3,2,5,1)
MSE(PredictionExample,ActualValuesExample)
Bias <- mean(PredictionExample-ActualValuesExample)
Variance <- mean((PredictionExample-ActualValuesExample)^2)
# MSE = Bias^2 + Variance
(Bias)^2 + Variance

0.4489796 is the result for the computation by hand and 0.4285714 the result of the MSE function.

Where is my mistake, why i dotn get the same results?

Body:
I don't understand why you add (Bias)^2 and Variance. MSE is simply equal to:

mean((PredictionExample-ActualValuesExample)^2) by definition. This is the variance variable in your example. More explicitly MSE is the mean of squred errors. Here error refers to (actual - predicted). I tried for an artifical value set and get the same results. Below is the code:

> ActualValuesExample <- c(1,1,3,3,2,5,1)
> PredictionExample <-   c(3,1,2,4,3,2,2)
> MSE(PredictionExample,ActualValuesExample) == mean((PredictionExample-ActualValuesExample)^2)
[1] TRUE


问:
How to get auto increment work on NAVICAT
I am using NAVICAT to make tables for MYSQL and I am unable to find the auto-increment attribute option for my primary key column.

```<code>id integer(10)(auto_increment)primary key
</code>```

Anyone pls help me out!

答: click on key at the end of field, and it makes visible Auto increment option

Body:
I am using NAVICAT to make tables for MYSQL and I am unable to find the auto-increment attribute option for my primary key column.

id integer(10)(auto_increment)primary key

Anyone pls help me out!


问:
Shell Script to find the Operating System of the machine
How to find the operating system using bash script? I found this answer: Detect the OS from a Bash script. It is not clear it would work on Mac OS X.

I would like to find it on Mac OS X vs different linux OS's.

答:
use uname

```<code>$(uname -s)
</code>```

this will give you the os name (Darwin = OSX)

```<code>$(uname -v)
</code>```

will give you the os version

see uname manual here

Body:
use uname

$(uname -s)

this will give you the os name (Darwin = OSX)

$(uname -v)

will give you the os version

see uname manual here


问:
Using a int value, which is in another class file?
I want to use a int value, that is in Gui.class, in DrawPanel1.class, how can I pass over the int value easily from Class to Class file?
My int value:

/* Gui.java */
static int gamestate = 1;

I want to decrease gamestate by 1, in the DrawPanel.java, in a buttonHandler, like so:

```<code>/*DrawPanel.java */
    class StartNewGameHandler implements ActionListener{
     public void actionPerformed( ActionEvent e ){
                    gamestate--;
     }
}
</code>```

答:
You just make it public like:

```<code>public static int gamestate = 1;
</code>```

and then you call it staticly:

```<code>Gui.gamestate
</code>```

Body:
I want to use a int value, that is in Gui.class, in DrawPanel1.class, how can I pass over the int value easily from Class to Class file?
My int value:

/* Gui.java */
static int gamestate = 1;

I want to decrease gamestate by 1, in the DrawPanel.java, in a buttonHandler, like so:

/*DrawPanel.java */
    class StartNewGameHandler implements ActionListener{
     public void actionPerformed( ActionEvent e ){
                    gamestate--;
     }
}

Body:
You just make it public like:

public static int gamestate = 1;

and then you call it staticly:

Gui.gamestate


问:
Is there a way to run multiple bash scripts with one script at the same time?
I am running an Instagram bot using python and selenium. I use a bash script to run a python script with the accounts credentials(Username, password, hashtags, etc...) I run multiple Instagrams so I have made multiple copies of this file. Is there a way to put this in a single file that I can click on and run?
To open multiple terminals running their assigned account?

I've already tried just to add them to one big file but the scripts wont run until the previous one finishes.

Also since I'm using selenium, trying multi threading in python is somewhat difficult but would not mind going that route if someone could point me to where I could start with that.

#!/bin/sh
cd PycharmProjects/InstaBot
python3 W.py
```

答:
I highly recommend that everyone read about Bash Job Control.

Getting into multithreading is ridiculous overkill if your bottleneck has nothing to do with the CPU.

for script in PycharmProjects/InstaBot/*.py; do
  python3 "$script" &
done
jobs
```


问:
Telegram Bot how to set parsing mode in curl?
Im editing some script for telegram bot, and I only want to add parsing mode html, so it allows me to use bold,italic etc..

I cant seem to find way to adopt parse_mode: "HTML" to curl line

```<code> if [ -n "${TOKEN}" ];
  then
    echo "Sending telegram...";
    #Telegram notification
    curl -s -X POST https://api.telegram.org/bot${TOKEN}/sendMessage -d chat_id=${CHAT_ID} -d text="${1}" >> /dev/null
  fi
</code>```

答:
parse_mode is just another parameter like text or chat_id. You can use -d!

```<code>curl -s -X POST https://api.telegram.org/bot${TOKEN}/sendMessage -d chat_id=${CHAT_ID} -d text="${1}" -d "parse_mode='HTML'" >> /dev/null

</code>```

Documentation

Body:
Im editing some script for telegram bot, and I only want to add parsing mode html, so it allows me to use bold,italic etc..

I cant seem to find way to adopt parse_mode: "HTML" to curl line

 if [ -n "${TOKEN}" ];
  then
    echo "Sending telegram...";
    #Telegram notification
    curl -s -X POST https://api.telegram.org/bot${TOKEN}/sendMessage -d chat_id=${CHAT_ID} -d text="${1}" >> /dev/null
  fi

Body:
parse_mode is just another parameter like text or chat_id. You can use -d!

curl -s -X POST https://api.telegram.org/bot${TOKEN}/sendMessage -d chat_id=${CHAT_ID} -d text="${1}" -d "parse_mode='HTML'" >> /dev/null

Documentation


问:
How to Find Words Not Containing Specific Letters?
I'm trying to write a code using regex and my text file. My file contains these words line by line:

```<code>nana
abab
nanac
eded
</code>```

My purpose is: displaying the words which does not contain the letters which are given as substring's letters.

For example, if my substring is "bn", my output should be only eded. Because nana and nanac contains "n" and abab contains "b".

I have written a code but it only checks first letter of my substring:

```<code>import re

substring = "bn"
def xstring():
    with open("deneme.txt") as f:
        for line in f:
            for word in re.findall(r'\w+', line):
                for letter in substring:
                    if len(re.findall(letter, word)) == 0:
                        print(word)
                        #yield word
xstring()
</code>```

How do I solve this problem?

答:
It might not be the most efficient but you could try doing something with set intersections the following code segment will print the the value in the string word only if it does not contain any of the letters 'b' or 'n' </p>

```<code>if (not any(set(word) & set('bn'))):
        print(word)
</code>```

Body:
I'm trying to write a code using regex and my text file. My file contains these words line by line:

nana
abab
nanac
eded

My purpose is: displaying the words which does not contain the letters which are given as substring's letters.

For example, if my substring is "bn", my output should be only eded. Because nana and nanac contains "n" and abab contains "b".

I have written a code but it only checks first letter of my substring:

import re

substring = "bn"
def xstring():
    with open("deneme.txt") as f:
        for line in f:
            for word in re.findall(r'\w+', line):
                for letter in substring:
                    if len(re.findall(letter, word)) == 0:
                        print(word)
                        #yield word
xstring()

How do I solve this problem?

Body:
It might not be the most efficient but you could try doing something with set intersections the following code segment will print the the value in the string word only if it does not contain any of the letters 'b' or 'n'

if (not any(set(word) & set('bn'))):
        print(word)


问:
jQuery UI autocomplete doesn't work for me
I need jQuery autocomplete for a project but it doesn't work for me.
I don't know where is my mistake.
Thanks in advance !</p>

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="iso-8859-1" />
    <title>Votre titre</title>

    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/themes/smoothness/jquery-ui.css" />
</head>
<body>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js"></script>
    <script>
        var liste = [
            "Draggable",
            "Droppable",
            "Resizable",
            "Selectable",
            "Sortable"
        ];

        $('#recherche').autocomplete({
            source : liste
        });
    </script>

    <form>
        <input type="text" id="recherche" />
    </form>
</body>
</html>
</code>```

答:
You have multiple issues with html syntax here:

Move the script tags for jquery files to the head tag

move your script to after the body

Your script must be after the body tag or it can be placed instead of the head tag and use a document ready check to allow it to run after the page loads (see http://learn.jquery.com/using-jquery-core/document-ready/). Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

```<code>    <!DOCTYPE html>
<html>
<head>
    <meta charset="iso-8859-1" />
    <title>Votre titre</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/themes/smoothness/jquery-ui.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js"></script>
</head>
  <body>
      <form>
          <input type="text" id="recherche" />
      </form>
  </body>
    <script>
        var liste = [
            "Draggable",
            "Droppable",
            "Resizable",
            "Selectable",
            "Sortable"
        ];

       $('#recherche').autocomplete({
            source : liste
        });
    </script>
</html>
</code>```

see a working example here https://jsfiddle.net/q7k28bp0/1/

Body:
I need jQuery autocomplete for a project but it doesn't work for me.
I don't know where is my mistake.
Thanks in advance !

<!DOCTYPE html>

    <meta charset="iso-8859-1" />
    <title>Votre titre</title>

    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/themes/smoothness/jquery-ui.css" />

    <form>
        <input type="text" id="recherche" />
    </form>

Body:
You have multiple issues with html syntax here:

Move the script tags for jquery files to the head tag

move your script to after the body

Your script must be after the body tag or it can be placed instead of the head tag and use a document ready check to allow it to run after the page loads (see http://learn.jquery.com/using-jquery-core/document-ready/). Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

    <!DOCTYPE html>
<html>
<head>
    <meta charset="iso-8859-1" />
    <title>Votre titre</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/themes/smoothness/jquery-ui.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js"></script>
</head>
  <body>
      <form>
          <input type="text" id="recherche" />
      </form>
  </body>
    <script>
        var liste = [
            "Draggable",
            "Droppable",
            "Resizable",
            "Selectable",
            "Sortable"
        ];

       $('#recherche').autocomplete({
            source : liste
        });
    </script>
</html>

see a working example here https://jsfiddle.net/q7k28bp0/1/


问:
Can't send user data if firebaseAuth.signOut() si called
I am a bit confused about why this is happening.

I want to update my user profile in the Registration Activity, it all works fine and the database is updated, until I add firebaseAuth.signOut() to the sendUserData() function. Does anyone have this problem before?

package com.example.myapplication;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class RegisterActivity extends AppCompatActivity {

    private EditText userName, userPassword, userEmail, phoneNumber;
    private Button logButton, regButton;
    private FirebaseAuth firebaseAuth;
    String email, name, phone, password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        setupUIViews();

        firebaseAuth = FirebaseAuth.getInstance();

        regButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(validate()){
                    //upload everithing to the database
                    String user_name = userName.getText().toString().trim();
                    String user_email = userEmail.getText().toString().trim();
                    String user_password = userPassword.getText().toString().trim();
                    String user_phone = phoneNumber.getText().toString().trim();

                    firebaseAuth.createUserWithEmailAndPassword(user_email, user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if(task.isSuccessful()) {
                                sendEmailVerification();
                            }
                            else{
                                Toast.makeText(RegisterActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

                }
            }
        });
        logButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(RegisterActivity.this, MainActivity.class));
            }
        });
    }

    private void setupUIViews(){
        userName = (EditText)findViewById(R.id.etUser2);
        userPassword = (EditText)findViewById(R.id.etPas2);
        userEmail = (EditText)findViewById(R.id.etEmail2);
        phoneNumber = (EditText)findViewById(R.id.etPhone1);
        regButton = (Button)findViewById(R.id.registerButton2);
        logButton = (Button)findViewById(R.id.loginButton2);

    }

    private Boolean validate(){
        Boolean result = false;

         name = userName.getText().toString();
         email = userEmail.getText().toString();
         phone = phoneNumber.getText().toString();
         password = userPassword.getText().toString();

        if(name.isEmpty() || password.isEmpty() || email.isEmpty()){
           Toast.makeText(this, "Please enter all the details", Toast.LENGTH_SHORT).show();
        }
        else{
            result = true;
        }
        return result;
    }

    private void sendEmailVerification(){
        final FirebaseUser firebaseUser = firebaseAuth.getInstance().getCurrentUser();

        if(firebaseUser != null){
            firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if(task.isSuccessful()){
                        sendUserData();
                        Toast.makeText(RegisterActivity.this, "Sucessfully registered", Toast.LENGTH_SHORT).show();
 //---------------->>>//firebaseAuth.signOut();//<<<-----------//
                        finish();
                        startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                    }
                    else{
                        Toast.makeText(RegisterActivity.this, "Verification email was not sent", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    private void sendUserData(){
        FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
        DatabaseReference myRef = firebaseDatabase.getReference(firebaseAuth.getUid());
        UserProfile userProfile = new UserProfile(name, email, phone);

        Toast.makeText(RegisterActivity.this, "User data was sent to the database" + firebaseDatabase.toString(), Toast.LENGTH_SHORT).show();

        myRef.setValue(userProfile).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                firebaseAuth.signOut();
            }
        });
    }
}
```

So the database works (data is uploaded into the real-time database by firebase) without the logout, but then I have the problem that the user is automatically logged in in the UserProfileActivity.

答: Please provide error trace or error so that we can understand what's happening.and btw,your toast should be displayed inside onSuccessListener().You are displaying toast before it is checking whether the task is sucess or not</p>

Body:
I am a bit confused about why this is happening.

I want to update my user profile in the Registration Activity, it all works fine and the database is updated, until I add firebaseAuth.signOut() to the sendUserData() function. Does anyone have this problem before?

package com.example.myapplication;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class RegisterActivity extends AppCompatActivity {

    private EditText userName, userPassword, userEmail, phoneNumber;
    private Button logButton, regButton;
    private FirebaseAuth firebaseAuth;
    String email, name, phone, password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        setupUIViews();

        firebaseAuth = FirebaseAuth.getInstance();

        regButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(validate()){
                    //upload everithing to the database
                    String user_name = userName.getText().toString().trim();
                    String user_email = userEmail.getText().toString().trim();
                    String user_password = userPassword.getText().toString().trim();
                    String user_phone = phoneNumber.getText().toString().trim();

                    firebaseAuth.createUserWithEmailAndPassword(user_email, user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if(task.isSuccessful()) {
                                sendEmailVerification();
                            }
                            else{
                                Toast.makeText(RegisterActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

                }
            }
        });
        logButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(RegisterActivity.this, MainActivity.class));
            }
        });
    }

    private void setupUIViews(){
        userName = (EditText)findViewById(R.id.etUser2);
        userPassword = (EditText)findViewById(R.id.etPas2);
        userEmail = (EditText)findViewById(R.id.etEmail2);
        phoneNumber = (EditText)findViewById(R.id.etPhone1);
        regButton = (Button)findViewById(R.id.registerButton2);
        logButton = (Button)findViewById(R.id.loginButton2);

    }

    private Boolean validate(){
        Boolean result = false;

         name = userName.getText().toString();
         email = userEmail.getText().toString();
         phone = phoneNumber.getText().toString();
         password = userPassword.getText().toString();

        if(name.isEmpty() || password.isEmpty() || email.isEmpty()){
           Toast.makeText(this, "Please enter all the details", Toast.LENGTH_SHORT).show();
        }
        else{
            result = true;
        }
        return result;
    }

    private void sendEmailVerification(){
        final FirebaseUser firebaseUser = firebaseAuth.getInstance().getCurrentUser();

        if(firebaseUser != null){
            firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if(task.isSuccessful()){
                        sendUserData();
                        Toast.makeText(RegisterActivity.this, "Sucessfully registered", Toast.LENGTH_SHORT).show();
 //---------------->>>//firebaseAuth.signOut();//<<<-----------//
                        finish();
                        startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                    }
                    else{
                        Toast.makeText(RegisterActivity.this, "Verification email was not sent", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    private void sendUserData(){
        FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
        DatabaseReference myRef = firebaseDatabase.getReference(firebaseAuth.getUid());
        UserProfile userProfile = new UserProfile(name, email, phone);

        Toast.makeText(RegisterActivity.this, "User data was sent to the database" + firebaseDatabase.toString(), Toast.LENGTH_SHORT).show();

        myRef.setValue(userProfile).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                firebaseAuth.signOut();
            }
        });
    }
}

So the database works (data is uploaded into the real-time database by firebase) without the logout, but then I have the problem that the user is automatically logged in in the UserProfileActivity.


问:
How to exclude rows from a SQL fetch that have a related keyword through a many to many relationship
I have a MySQL database with a media table, and a keywords table, and a many-to-many relationship between media and keywords via a media_keywords join table.

I want to fetch all records from the media table where the following set of conditions match:

```<code>'description' is like 'dog' OR
'media.keywords' includes the id for the 'dog' keyword [100]
</code>```

And exclude from the found set any records where:

```<code>'description' is like 'cat' OR
'media.keywords' includes the id for the 'cat' keyword [400]
</code>```

And also exclude any row where:

```<code>'media.keywords' includes the id for the 'monochrome' keyword [500]
</code>```

I also want to return only distinct rows, so I'm using GROUP By 'media.id'

The SQL statement I have at the moment is as follows:

```<code>    SELECT DISTINCT
    `media`.`id`,`media`.`description`,
    `keywords`.`id` AS `keywords.id`,
    `keywords->media_keywords`.`id` AS `keywords.media_keywords.id`,
    `keywords->media_keywords`.`media_id` AS `keywords.media_keywords.media_id`,
    `keywords->media_keywords`.`keyword_id` AS `keywords.media_keywords.keyword_id`

    FROM database.media

    LEFT OUTER JOIN
    (
        `media_keywords` AS `keywords->media_keywords`

        INNER JOIN `keywords` AS `keywords`
        ON `keywords`.`id` = `keywords->media_keywords`.`keyword_id`
    )

    ON `media`.`id` = `keywords->media_keywords`.`media_id`

    WHERE
    (
            (`media`.`description` LIKE '%dog%' )

            OR `keywords`.`id` IN (100)
    )

    AND NOT
    (
            (`media`.`description` LIKE '%cat%' )

            OR `keywords`.`id` IN (400,500)
    )

    GROUP BY `media`.`id` ;
</code>```

This correctly fetches records where 'dog' is in the description or is a keyword, but ignores the exclusions completely.

Can anyone see what I'm doing wrong here?

答:
I would use a where clause:

```<code>select m.*
from media m
where (m.description like '%dog%' or
       exists (select 1
               from keywords k
               where k.media_id = m.id and
                     k.keyword_id = 100
              )
      ) and
      (m.description not like '%cat%' or
       exists (select 1
               from keywords k
               where k.media_id = m.id and
                     k.keyword_id in (400, 500)
              )
       );
</code>```

This is pretty much a direct translation of your conditions.

Body:
I have a MySQL database with a media table, and a keywords table, and a many-to-many relationship between media and keywords via a media_keywords join table.

I want to fetch all records from the media table where the following set of conditions match:

'description' is like 'dog' OR
'media.keywords' includes the id for the 'dog' keyword [100]

And exclude from the found set any records where:

'description' is like 'cat' OR
'media.keywords' includes the id for the 'cat' keyword [400]

And also exclude any row where:

'media.keywords' includes the id for the 'monochrome' keyword [500]

I also want to return only distinct rows, so I'm using GROUP By 'media.id'

The SQL statement I have at the moment is as follows:

    SELECT DISTINCT
    `media`.`id`,`media`.`description`,
    `keywords`.`id` AS `keywords.id`,
    `keywords->media_keywords`.`id` AS `keywords.media_keywords.id`,
    `keywords->media_keywords`.`media_id` AS `keywords.media_keywords.media_id`,
    `keywords->media_keywords`.`keyword_id` AS `keywords.media_keywords.keyword_id`

    FROM database.media

    LEFT OUTER JOIN
    (
        `media_keywords` AS `keywords->media_keywords`

        INNER JOIN `keywords` AS `keywords`
        ON `keywords`.`id` = `keywords->media_keywords`.`keyword_id`
    )

    ON `media`.`id` = `keywords->media_keywords`.`media_id`

    WHERE
    (
            (`media`.`description` LIKE '%dog%' )

            OR `keywords`.`id` IN (100)
    )

    AND NOT
    (
            (`media`.`description` LIKE '%cat%' )

            OR `keywords`.`id` IN (400,500)
    )

    GROUP BY `media`.`id` ;

This correctly fetches records where 'dog' is in the description or is a keyword, but ignores the exclusions completely.

Can anyone see what I'm doing wrong here?

Body:
I would use a where clause:

select m.*
from media m
where (m.description like '%dog%' or
       exists (select 1
               from keywords k
               where k.media_id = m.id and
                     k.keyword_id = 100
              )
      ) and
      (m.description not like '%cat%' or
       exists (select 1
               from keywords k
               where k.media_id = m.id and
                     k.keyword_id in (400, 500)
              )
       );

This is pretty much a direct translation of your conditions.


问:
Serial communication from JavaScript?
Is it possible to communicate over a machine's serial port through JavaScript?

I have to write a short program that sends data to a microcontroller over the serial port that has a GUI and is cross-platform compatible, and I really don't want to use Java's Swing.

答:
Yes, it's possible using an ActiveX(I did it). You can make an activeX and use JavaScript to invoke it.
If you prefer, you can make a .net dll and register it using regasm. Take a look at this link

You also can write an activeX using VB6 and register it. Both works fine.
Ps.: if you are using ActiveX, the JavaScript code will run just on IE.

Title: Serial communication from JavaScript?


问:
VirtualBox: mounting shared folder fails during start-up, but succeed from shell
Problem description:

When I boot my VirtualBox Guest OS, the mounting of the shared file-system - which is referenced in /etc/fstab - fails.

However, after login - mount -a succeeds.

Details:

The boot process gets stuck here ...

... and pressing s continues the boot process, which finishes.

In the shell, I verify that my shared directory is not mounted:

But now, from the shell, the mount of the shared file-system succeeds:

What should I do to make my mount succeed during start-up?

Environment:

VirtualBox: 4.3.12.r93733

Host OS: Windows 7

Guest OS: Linux ubuntu 3.13.0-32-generic #57~precise1-Ubuntu x86_64 GNU/Linux

/etc/fstab

Relevant lines in /var/log/boot.log

答:
You need to install VirtualBox Guest Additions properly and use VirtualBox Manager to specify share folders. The issue happens because the mount point is in place with root permissions. The default mount location is in /media/sf_.

You can change mount point with VBoxControl command. To change the mount point from /media/sf_... to /home/user/sf_... use the command:

```<code>sudo VBoxControl guestproperty set /VirtualBox/GuestAdd/SharedFolders/MountDir /home/user/
</code>```

To check if that's working:

```<code>sudo VBoxControl guestproperty get /VirtualBox/GuestAdd/SharedFolders/MountDir
</code>```

Body:
You need to install VirtualBox Guest Additions properly and use VirtualBox Manager to specify share folders. The issue happens because the mount point is in place with root permissions. The default mount location is in /media/sf_.

You can change mount point with VBoxControl command. To change the mount point from /media/sf_... to /home/user/sf_... use the command:

sudo VBoxControl guestproperty set /VirtualBox/GuestAdd/SharedFolders/MountDir /home/user/

To check if that's working:

sudo VBoxControl guestproperty get /VirtualBox/GuestAdd/SharedFolders/MountDir


问:
How to compare what the person type? If char equal char do that
Im trying to do a comparison with what the user type (his name - char) with the variable name (char). But idk how can i do that.

```<code>var nome=document.getElementById("nome").value;
var mat=document.getElementById("mat").value; //Disciplina

if (nome===name){
    alert("Sua média é: "+ resultado);
} else {
    alert("Error.");
    return;
}
</code>```

HTML Code:

```<code><p class="p">Nome do aluno: <input class ="form-control" id="nome" type="text" name="name" placeholder="Preencha seu nome"/></p>
<button type="button" class="" onclick="media()">Calcular</button>
</code>```

Javascript code:

```<code>function media() {
    var nome=document.getElementById("nome").value;
    var mat=document.getElementById("mat").value; //Disciplina

    if (nome===name){
        alert("Sua média é: "+ resultado);
    } else {
        alert("Error.");
        return;
    }
}
</code>```

答:
Do you mean you want to test if the input value is a valid name?Like this?

```<code>function testName(input) {
  return /^[a-zA-Z]+$/.test(input)
}
</code>```

The regexp /^[a-zA-Z]+$/ only match strings combined by char a-z and A-Z.

In your code:

```<code>function media() {

    var nome=document.getElementById("nome").value;
    var mat=document.getElementById("mat").value; //Disciplina

    if (/^[a-zA-Z]+$/.test(nome)){
        alert("Sua média é: "+ resultado);

    }

    else{
        alert("Error.");
        return;
    }

}
</code>```

Body:
Im trying to do a comparison with what the user type (his name - char) with the variable name (char). But idk how can i do that.

var nome=document.getElementById("nome").value;
var mat=document.getElementById("mat").value; //Disciplina

if (nome===name){
    alert("Sua média é: "+ resultado);
} else {
    alert("Error.");
    return;
}

HTML Code:

Nome do aluno: <input class ="form-control" id="nome" type="text" name="name" placeholder="Preencha seu nome"/>

<button type="button" class="" onclick="media()">Calcular</button>

Javascript code:

function media() {
    var nome=document.getElementById("nome").value;
    var mat=document.getElementById("mat").value; //Disciplina

    if (nome===name){
        alert("Sua média é: "+ resultado);
    } else {
        alert("Error.");
        return;
    }
}

Body:
Do you mean you want to test if the input value is a valid name?Like this?

function testName(input) {
  return /^[a-zA-Z]+$/.test(input)
}

The regexp /^[a-zA-Z]+$/ only match strings combined by char a-z and A-Z.

In your code:

function media() {

    var nome=document.getElementById("nome").value;
    var mat=document.getElementById("mat").value; //Disciplina

    if (/^[a-zA-Z]+$/.test(nome)){
        alert("Sua média é: "+ resultado);

    }

    else{
        alert("Error.");
        return;
    }

}


答:
@Xosrov has the right approach, with a few minor issues and typos.  The below version of the same logic works</p>

```<code>import re

def xstring(substring, words):
    regex = re.compile('[%s]' % ''.join(sorted(set(substring))))
    # Excluding words matching regex.pattern
    for word in words:
        if not re.search(regex, word):
            print(word)

words = [
    'nana',
    'abab',
    'nanac',
    'eded',
]

xstring("bn", words)
</code>```

Title: How to Find Words Not Containing Specific Letters?

Body:
@Xosrov has the right approach, with a few minor issues and typos.  The below version of the same logic works

import re

def xstring(substring, words):
    regex = re.compile('[%s]' % ''.join(sorted(set(substring))))
    # Excluding words matching regex.pattern
    for word in words:
        if not re.search(regex, word):
            print(word)

words = [
    'nana',
    'abab',
    'nanac',
    'eded',
]

xstring("bn", words)


问:
mongoDB aggregation: $addToSet then $sort
I'm trying to sort unique values in arrays in multiple fields from a mongoDB collection (with the nodeJS driver).

a small dataset :

```<code>[{
    "_id" : "5c93db3dd0184516406013f7",
    "filters" : {
        "genres" : [
            {
                "_id" : "9CXBYc4qP8sqcNMZ5",
                "fr" : "Art Abstrait",
                "en" : "Abstract Art",
                "de" : "Abstrakte Kunst",
                "it" : "Arte astratta",
                "es" : "Arte Abstracto"
            }
        ],
        "subjects" : [
            {
                "_id" : "3QjL6YSfmuY6NFHGG",
                "fr" : "Abstrait",
                "en" : "Abstract",
                "de" : "Abstrakt",
                "it" : "Astratto",
                "es" : "Abstracto"
            }
        ],
        "type" : {
            "_id" : "CYK2WcepkJsy5xXMo",
            "fr" : "Gravure au carborundum",
            "en" : "Carborundum etching",
            "de" : "Carborundum Radierung",
            "it" : "Incisione carborandum",
            "es" : "Grabado al Carborundum"
        }
    }
},
{
    "_id" : "5c93db3ed0184516406013f8",
    "filters" : {
        "genres" : [
            {
                "_id" : "9CXBYc4qP8sqcNMZ5",
                "fr" : "Art Abstrait",
                "en" : "Abstract Art",
                "de" : "Abstrakte Kunst",
                "it" : "Arte astratta",
                "es" : "Arte Abstracto"
            }
        ],
        "subjects" : [
            {
                "_id" : "3QjL6YSfmuY6NFHGG",
                "fr" : "Abstrait",
                "en" : "Abstract",
                "de" : "Abstrakt",
                "it" : "Astratto",
                "es" : "Abstracto"
            }
        ],
        "type" : {
            "_id" : "CYK2WcepkJsy5xXMo",
            "fr" : "Gravure au carborundum",
            "en" : "Carborundum etching",
            "de" : "Carborundum Radierung",
            "it" : "Incisione carborandum",
            "es" : "Grabado al Carborundum"
        }
    }
},
{
    "_id" : "5c93e19ed018451640601da6",
    "filters" : {
        "genres" : [
            {
                "_id" : "9CXBYc4qP8sqcNMZ5",
                "fr" : "Art Abstrait",
                "en" : "Abstract Art",
                "de" : "Abstrakte Kunst",
                "it" : "Arte astratta",
                "es" : "Arte Abstracto"
            }
        ],
        "subjects" : [
            {
                "_id" : "3QjL6YSfmuY6NFHGG",
                "fr" : "Abstrait",
                "en" : "Abstract",
                "de" : "Abstrakt",
                "it" : "Astratto",
                "es" : "Abstracto"
            }
        ],
        "type" : {
            "_id" : "KfGWEHL2pAto8nfze",
            "fr" : "Gravure",
            "en" : "Etching",
            "de" : "Radierung",
            "it" : "Incisione",
            "es" : "Grabado"
        }
    }
}]
</code>```

the result of my query (with lang = 'en'):

```<code>{
  "subjects": [
    {
      "_id": "3QjL6YSfmuY6NFHGG",
      "fr": "Abstrait",
      "en": "Abstract",
      "de": "Abstrakt",
      "it": "Astratto",
      "es": "Abstracto"
    },
    {
      "_id": "3QjL6YSfmuY6NFHGG",
      "fr": "Abstrait",
      "en": "Abstract",
      "de": "Abstrakt",
      "it": "Astratto",
      "es": "Abstracto"
    }
  ],
  "genres": [
    {
      "_id": "9CXBYc4qP8sqcNMZ5",
      "fr": "Art Abstrait",
      "en": "Abstract Art",
      "de": "Abstrakte Kunst",
      "it": "Arte astratta",
      "es": "Arte Abstracto"
    },
    {
      "_id": "9CXBYc4qP8sqcNMZ5",
      "fr": "Art Abstrait",
      "en": "Abstract Art",
      "de": "Abstrakte Kunst",
      "it": "Arte astratta",
      "es": "Arte Abstracto"
    }
  ],
  "types": [
    {
      "_id": "CYK2WcepkJsy5xXMo",
      "fr": "Gravure au carborundum",
      "en": "Carborundum etching",
      "de": "Carborundum Radierung",
      "it": "Incisione carborandum",
      "es": "Grabado al Carborundum"
    },
    {
      "_id": "KfGWEHL2pAto8nfze",
      "fr": "Gravure",
      "en": "Etching",
      "de": "Radierung",
      "it": "Incisione",
      "es": "Grabado"
    }
  ]
}
</code>```

The pipeline for the aggregation :

```<code>[
    { $unwind: '$filters.subjects' },
    { $unwind: '$filters.genres' },
    { $group: {
      _id: null,
      subjects: { $addToSet: '$filters.subjects' },
      types: { $addToSet: '$filters.type' },
      genres: { $addToSet: '$filters.genres' },
    }},
    { $unwind: '$subjects' },
    { $unwind: '$genres' },
    { $unwind: '$types' },
    { $sort: {
      [`subjects.${lang}`]: 1,
      [`types.${lang}`]: 1,
      [`genres.${lang}`]: 1,
    }},
    { $group: {
      _id: null,
      subjects: { $push: '$subjects' },
      types: { $push: '$types' },
      genres: { $push: '$genres' },
    }},
    { $project: {
      _id: false,
      subjects: '$subjects',
      types: '$types',
      genres: '$genres'
    }}
]
</code>```

Instead of getting sorted arrays of unique values as so :
[A, B, C, D, ...]

I get sorted arrays with non unique values as so :
[A, A, A, B, B, B, C, C, C, D, D, D, ...]

Making the $addToSet grouping useless.

Any idea on what I got wrong ?

答:
The problem you're encountering is that each $unwind is going to create a copy of the document with a single array element from the array you're unwinding. You have the following:

```<code>...
{ $unwind: '$subjects' },
{ $unwind: '$genres' },
{ $unwind: '$types' },
...
</code>```

So, first you're unwinding subjects which produces a documents for each element in subjects, which we will call subject. Thus we have a document for each subject which themselves contain the arrays genres and types. On unwinding genres next, each subject document gets unwinded to contain an element genre from genres. This gives use genres.length copies of each subject--that is, each subject is duplicated based on how many genres there are in the array. A similar situation occurs when unwinding types.

In short, you're duplicating your data on every $unwind call.

To illustrate with a simpler example:

```<code>// Doc:
{
    ints: [1, 2],
    alpha: ['a', 'b', 'c']

}

// Pipeline:
[
    { $unwind: "$ints" },
    { $unwind: "$alpha" }

]

// After unwinding "ints":
[
    { ints: 1, alpha: ['a', 'b', 'c'] },
    { ints: 2, alpha: ['a', 'b', 'c'] }

]

// After unwinding "alpha":
[
    { ints: 1, alpha: 'a' },
    { ints: 1, alpha: 'b' },
    { ints: 1, alpha: 'c' },
    { ints: 2, alpha: 'a' },
    { ints: 2, alpha: 'b' },
    { ints: 2, alpha: 'c' }
]

// Result: 3 duplicates of each value in "ints", 2 duplicates of each value in "alpha".
</code>```

To resolve this, a couple of options immediately come to mind:

 1. You can $unwind an array, $sort it, and $group the results to $push the elements back into an array, repeating for each array individually, one at a time. Note that you would need to use the $first operator to grab only one copy of each duplicated array when grouping.

 2. You can change your last $group pipeline stage to use $addToSet instead of $push operations.

There are likely other options available to you, but either of the above should suffice for something quick.

Body:
I'm trying to sort unique values in arrays in multiple fields from a mongoDB collection (with the nodeJS driver).

a small dataset :

[{
    "_id" : "5c93db3dd0184516406013f7",
    "filters" : {
        "genres" : [
            {
                "_id" : "9CXBYc4qP8sqcNMZ5",
                "fr" : "Art Abstrait",
                "en" : "Abstract Art",
                "de" : "Abstrakte Kunst",
                "it" : "Arte astratta",
                "es" : "Arte Abstracto"
            }
        ],
        "subjects" : [
            {
                "_id" : "3QjL6YSfmuY6NFHGG",
                "fr" : "Abstrait",
                "en" : "Abstract",
                "de" : "Abstrakt",
                "it" : "Astratto",
                "es" : "Abstracto"
            }
        ],
        "type" : {
            "_id" : "CYK2WcepkJsy5xXMo",
            "fr" : "Gravure au carborundum",
            "en" : "Carborundum etching",
            "de" : "Carborundum Radierung",
            "it" : "Incisione carborandum",
            "es" : "Grabado al Carborundum"
        }
    }
},
{
    "_id" : "5c93db3ed0184516406013f8",
    "filters" : {
        "genres" : [
            {
                "_id" : "9CXBYc4qP8sqcNMZ5",
                "fr" : "Art Abstrait",
                "en" : "Abstract Art",
                "de" : "Abstrakte Kunst",
                "it" : "Arte astratta",
                "es" : "Arte Abstracto"
            }
        ],
        "subjects" : [
            {
                "_id" : "3QjL6YSfmuY6NFHGG",
                "fr" : "Abstrait",
                "en" : "Abstract",
                "de" : "Abstrakt",
                "it" : "Astratto",
                "es" : "Abstracto"
            }
        ],
        "type" : {
            "_id" : "CYK2WcepkJsy5xXMo",
            "fr" : "Gravure au carborundum",
            "en" : "Carborundum etching",
            "de" : "Carborundum Radierung",
            "it" : "Incisione carborandum",
            "es" : "Grabado al Carborundum"
        }
    }
},
{
    "_id" : "5c93e19ed018451640601da6",
    "filters" : {
        "genres" : [
            {
                "_id" : "9CXBYc4qP8sqcNMZ5",
                "fr" : "Art Abstrait",
                "en" : "Abstract Art",
                "de" : "Abstrakte Kunst",
                "it" : "Arte astratta",
                "es" : "Arte Abstracto"
            }
        ],
        "subjects" : [
            {
                "_id" : "3QjL6YSfmuY6NFHGG",
                "fr" : "Abstrait",
                "en" : "Abstract",
                "de" : "Abstrakt",
                "it" : "Astratto",
                "es" : "Abstracto"
            }
        ],
        "type" : {
            "_id" : "KfGWEHL2pAto8nfze",
            "fr" : "Gravure",
            "en" : "Etching",
            "de" : "Radierung",
            "it" : "Incisione",
            "es" : "Grabado"
        }
    }
}]

the result of my query (with lang = 'en'):

{
  "subjects": [
    {
      "_id": "3QjL6YSfmuY6NFHGG",
      "fr": "Abstrait",
      "en": "Abstract",
      "de": "Abstrakt",
      "it": "Astratto",
      "es": "Abstracto"
    },
    {
      "_id": "3QjL6YSfmuY6NFHGG",
      "fr": "Abstrait",
      "en": "Abstract",
      "de": "Abstrakt",
      "it": "Astratto",
      "es": "Abstracto"
    }
  ],
  "genres": [
    {
      "_id": "9CXBYc4qP8sqcNMZ5",
      "fr": "Art Abstrait",
      "en": "Abstract Art",
      "de": "Abstrakte Kunst",
      "it": "Arte astratta",
      "es": "Arte Abstracto"
    },
    {
      "_id": "9CXBYc4qP8sqcNMZ5",
      "fr": "Art Abstrait",
      "en": "Abstract Art",
      "de": "Abstrakte Kunst",
      "it": "Arte astratta",
      "es": "Arte Abstracto"
    }
  ],
  "types": [
    {
      "_id": "CYK2WcepkJsy5xXMo",
      "fr": "Gravure au carborundum",
      "en": "Carborundum etching",
      "de": "Carborundum Radierung",
      "it": "Incisione carborandum",
      "es": "Grabado al Carborundum"
    },
    {
      "_id": "KfGWEHL2pAto8nfze",
      "fr": "Gravure",
      "en": "Etching",
      "de": "Radierung",
      "it": "Incisione",
      "es": "Grabado"
    }
  ]
}

The pipeline for the aggregation :

[
    { $unwind: '$filters.subjects' },
    { $unwind: '$filters.genres' },
    { $group: {
      _id: null,
      subjects: { $addToSet: '$filters.subjects' },
      types: { $addToSet: '$filters.type' },
      genres: { $addToSet: '$filters.genres' },
    }},
    { $unwind: '$subjects' },
    { $unwind: '$genres' },
    { $unwind: '$types' },
    { $sort: {
      [`subjects.${lang}`]: 1,
      [`types.${lang}`]: 1,
      [`genres.${lang}`]: 1,
    }},
    { $group: {
      _id: null,
      subjects: { $push: '$subjects' },
      types: { $push: '$types' },
      genres: { $push: '$genres' },
    }},
    { $project: {
      _id: false,
      subjects: '$subjects',
      types: '$types',
      genres: '$genres'
    }}
]

Instead of getting sorted arrays of unique values as so :
[A, B, C, D, ...]

I get sorted arrays with non unique values as so :
[A, A, A, B, B, B, C, C, C, D, D, D, ...]

Making the $addToSet grouping useless.

Any idea on what I got wrong ?

Body:
The problem you're encountering is that each $unwind is going to create a copy of the document with a single array element from the array you're unwinding. You have the following:

...
{ $unwind: '$subjects' },
{ $unwind: '$genres' },
{ $unwind: '$types' },
...

So, first you're unwinding subjects which produces a documents for each element in subjects, which we will call subject. Thus we have a document for each subject which themselves contain the arrays genres and types. On unwinding genres next, each subject document gets unwinded to contain an element genre from genres. This gives use genres.length copies of each subject--that is, each subject is duplicated based on how many genres there are in the array. A similar situation occurs when unwinding types.

In short, you're duplicating your data on every $unwind call.

To illustrate with a simpler example:

// Doc:
{
    ints: [1, 2],
    alpha: ['a', 'b', 'c']

}

// Pipeline:
[
    { $unwind: "$ints" },
    { $unwind: "$alpha" }

]

// After unwinding "ints":
[
    { ints: 1, alpha: ['a', 'b', 'c'] },
    { ints: 2, alpha: ['a', 'b', 'c'] }

]

// After unwinding "alpha":
[
    { ints: 1, alpha: 'a' },
    { ints: 1, alpha: 'b' },
    { ints: 1, alpha: 'c' },
    { ints: 2, alpha: 'a' },
    { ints: 2, alpha: 'b' },
    { ints: 2, alpha: 'c' }
]

// Result: 3 duplicates of each value in "ints", 2 duplicates of each value in "alpha".

To resolve this, a couple of options immediately come to mind:

 1. You can $unwind an array, $sort it, and $group the results to $push the elements back into an array, repeating for each array individually, one at a time. Note that you would need to use the $first operator to grab only one copy of each duplicated array when grouping.

 2. You can change your last $group pipeline stage to use $addToSet instead of $push operations.

There are likely other options available to you, but either of the above should suffice for something quick.


问:
React hooks warn me for missing dependencies
Suppose I am using useEffect to prefetch data on initial rendering:

```<code>function myComponent(props) {
    const { fetchSomething } = props;
    ...
    ...
    useEffect(() => {
        fetchSomething();
    }, []);
    ...
    ...
}
</code>```

My linter warn me for "React Hook useCallback has missing dependencies". It wants me to put fetchSomething inside the dependencies array.

The issue is that even it fetchSomething is going to be changed, I don't want the component to refetch the data. And as I see it, most of the situations where useEffect uses a function, it doesn't really care whether the function is changed.

I don't want to turn off that warning and doesn't like to spread // eslint-disable-next-line react-hooks/exhaustive-deps all over my code.

What is the rational behind such behavior?

It makes me feel insecure while using hooks, as if I am doing something incorrect.

答:
You can use useRef hook to remember the value of props.fetchSomething on first rendering. This will resolve your issue with eslint

```<code>function myComponent(props) {
    const fetchSomethingRef = useRef(props.fetchSomething);

    useEffect(() => {
        fetchSomethingRef.current();
    }, []);
}

</code>```

The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class. more

Body:
Suppose I am using useEffect to prefetch data on initial rendering:

function myComponent(props) {
    const { fetchSomething } = props;
    ...
    ...
    useEffect(() => {
        fetchSomething();
    }, []);
    ...
    ...
}

My linter warn me for "React Hook useCallback has missing dependencies". It wants me to put fetchSomething inside the dependencies array.

The issue is that even it fetchSomething is going to be changed, I don't want the component to refetch the data. And as I see it, most of the situations where useEffect uses a function, it doesn't really care whether the function is changed.

I don't want to turn off that warning and doesn't like to spread // eslint-disable-next-line react-hooks/exhaustive-deps all over my code.

What is the rational behind such behavior?

It makes me feel insecure while using hooks, as if I am doing something incorrect.

Body:
You can use useRef hook to remember the value of props.fetchSomething on first rendering. This will resolve your issue with eslint

function myComponent(props) {
    const fetchSomethingRef = useRef(props.fetchSomething);

    useEffect(() => {
        fetchSomethingRef.current();
    }, []);
}

The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class. more


问:
Being penalized on Page Speed by Google Fonts
I'm using a font that is in Google Fonts on my site and I'm importing through css:

```<code>@import url('https://fonts.googleapis.com/css?family=Montserrat:100,300,300i,400,400i,600,600i,700,800,900');
</code>```

The problem is that the Google PageSpeed Insights notifies the following information:

Make sure the text is still visible when you load webfont

Use the CSS font view feature to ensure that text can be viewed by the user while webfonts are loaded.

Below the notification, all font specifications I'm importing are listed:

Has anyone had this problem?

Do you know how this can be adjusted?

I'm having this notification on multiple sites that use Google Fonts.

答:
Use font-display: swap; or font-display: fallback; under @font-face

Google Front URL for with font-display: swap;:

```<code>https://fonts.googleapis.com/css?family=Montserrat:100,300,300i,400,400i,600,600i,700,800,900&display=swap
</code>```

Google Front URL for with font-display: fallback;:

```<code>https://fonts.googleapis.com/css?family=Montserrat:100,300,300i,400,400i,600,600i,700,800,900&display=fallback
</code>```

Body:
I'm using a font that is in Google Fonts on my site and I'm importing through css:

@import url('https://fonts.googleapis.com/css?family=Montserrat:100,300,300i,400,400i,600,600i,700,800,900');

The problem is that the Google PageSpeed Insights notifies the following information:

Make sure the text is still visible when you load webfont

Use the CSS font view feature to ensure that text can be viewed by the user while webfonts are loaded.

Below the notification, all font specifications I'm importing are listed:

Has anyone had this problem?

Do you know how this can be adjusted?

I'm having this notification on multiple sites that use Google Fonts.

Body:
Use font-display: swap; or font-display: fallback; under @font-face

Google Front URL for with font-display: swap;:

https://fonts.googleapis.com/css?family=Montserrat:100,300,300i,400,400i,600,600i,700,800,900&display=swap

Google Front URL for with font-display: fallback;:

https://fonts.googleapis.com/css?family=Montserrat:100,300,300i,400,400i,600,600i,700,800,900&display=fallback


问:
Calculating time 90 minutes prior to due date/time in Objective C (iPhone app)
This is a completely noobish question, but I spent 2 hours yesterday trying to make it work, and I'm obviously missing something very basic.

What I need to do is take input from user of date/time and count back 90 minutes for an alert.

Could someone please post an example calculation, where you have a var that holds user input and a new var that receives the result of this computation? (all done in Objective C for use in an iPhone app) Thank you!

答:
I suspect you could do something like:</p>

```<code>NSDate *alertDate = [userDate dateByAddingTimeInterval:-5400.0];
</code>```

Body:
I suspect you could do something like:

NSDate *alertDate = [userDate dateByAddingTimeInterval:-5400.0];


答:
Here, we would just want to have a simple expression such as:

```<code>^[^bn]+$
</code>```

We are adding b and n in a not-char class [^bn] and collecting all other chars, then by adding ^ and $ anchors we will be failing all strings that might have b and n.

Demo

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"^[^bn]+$"

test_str = ("nana\n"
    "abab\n"
    "nanac\n"
    "eded")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

Body:
I'm trying to write a code using regex and my text file. My file contains these words line by line:

nana
abab
nanac
eded

My purpose is: displaying the words which does not contain the letters which are given as substring's letters.

For example, if my substring is "bn", my output should be only eded. Because nana and nanac contains "n" and abab contains "b".

I have written a code but it only checks first letter of my substring:

import re

substring = "bn"
def xstring():
    with open("deneme.txt") as f:
        for line in f:
            for word in re.findall(r'\w+', line):
                for letter in substring:
                    if len(re.findall(letter, word)) == 0:
                        print(word)
                        #yield word
xstring()

How do I solve this problem?

Body:
Here, we would just want to have a simple expression such as:

^[^bn]+$

We are adding b and n in a not-char class [^bn] and collecting all other chars, then by adding ^ and $ anchors we will be failing all strings that might have b and n.

Demo

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"^[^bn]+$"

test_str = ("nana\n"
    "abab\n"
    "nanac\n"
    "eded")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:


问:
How to create class diagram and write pseudocode that defines the class?
I want to design a class named houses that holds the street address, asking price, number of bedrooms and number of bathrooms in the house. I would also like methods included to get and set values for each data field.

First time working with classes.
I got the class setup and I'm able to print the classes but I'm not sure how or which methods to use.

```<code>class houses:

    def __init__(self, Adress, Askingprice, NumOfBedrooms, NumofBathroom):
        self.Adress = Adress
        self.Askingprice = Askingprice
        self.NumOfBedrooms = NumOfBedrooms
        self.NumofBathroom = NumofBathroom

    def HouseDetails(self):
        return "The house is at {} with a price of {} and has {} Bedroom/s and {} bathroom/s" \
        .format(self.Adress, self.Askingprice, self.NumOfBedrooms, self.NumofBathroom)

house1 = houses("Almonaster_Avenue87", "R 500k", 1, 1)
house2 = houses("Audubon_Place33", "R 900k", 3, 3)
house3 = houses("Baronne_Street78", "R800k", 3, 2)
house4 = houses("Basin_Street55", "R700k", 2, 1)
house5 = houses("Bayou_Road11", "R 900", 4, 2)
house6 = houses("Bienville_Street78", "R700k", 2, 2)
house7 = houses("Bourbon_Street45", "R 800k", 4, 1)
house8 = houses("Broad_Street56", "R 900k", 5, 3)

print("\n",house1.HouseDetails())
</code>```

Please Note

The "R" at asking price is my currency.

答:
If you must have getter and setter methods, here's a succinct way to do it using Python's built-in property class. The create_property() utility function shown is a simplified version of recipe 9.21 in the 3rd edition of the Python Cookbook by Beazley & Jones (2013).

```<code>def create_property(name):
    """ Utility to define repetitive property methods. """
    storage_name = '_' + name

    @property
    def prop(self):  # getter
        return getattr(self, storage_name)

    @prop.setter
    def prop(self, value):  # setter
        return setattr(self, storage_name, value)

    return prop

class House:
    address = create_property('address')
    asking_price = create_property('asking_price')
    num_bedrooms = create_property('num_bedrooms')
    num_bathrooms = create_property('num_bathrooms')

    def __init__(self, address, asking_price, num_bedrooms, num_bathrooms):
        self.address = address
        self.asking_price = asking_price
        self.num_bedrooms = num_bedrooms
        self.num_bathrooms = num_bathrooms

    def __str__(self):
        return("The house is at {} with a price of {} and has "
               "{} Bedroom/s and {} bathroom/s".format(self.address,
                    self.asking_price, self.num_bedrooms,
                    self.num_bathrooms))

house1 = House("Almonaster Avenue 87", "R 500k", 1, 1)
house2 = House("Audubon Place 33", "R 900k", 3, 3)
house3 = House("Baronne Street 78", "R 800k", 3, 2)
house4 = House("Basin Street 55", "R 700k", 2, 1)
house5 = House("Bayou Road1 1", "R 900", 4, 2)
house6 = House("Bienville Street 78", "R 700k", 2, 2)
house7 = House("Bourbon Street 45", "R 800k", 4, 1)
house8 = House("Broad Street 56", "R 900k", 5, 3)

print(house1)

</code>```

Output:

The house is at Almonaster Avenue 87 with a price of R 500k and has 1 Bedroom/s and 1 bathroom/s
```

Body:
I want to design a class named houses that holds the street address, asking price, number of bedrooms and number of bathrooms in the house. I would also like methods included to get and set values for each data field.

First time working with classes.
I got the class setup and I'm able to print the classes but I'm not sure how or which methods to use.

class houses:

    def __init__(self, Adress, Askingprice, NumOfBedrooms, NumofBathroom):
        self.Adress = Adress
        self.Askingprice = Askingprice
        self.NumOfBedrooms = NumOfBedrooms
        self.NumofBathroom = NumofBathroom

    def HouseDetails(self):
        return "The house is at {} with a price of {} and has {} Bedroom/s and {} bathroom/s" \
        .format(self.Adress, self.Askingprice, self.NumOfBedrooms, self.NumofBathroom)

house1 = houses("Almonaster_Avenue87", "R 500k", 1, 1)
house2 = houses("Audubon_Place33", "R 900k", 3, 3)
house3 = houses("Baronne_Street78", "R800k", 3, 2)
house4 = houses("Basin_Street55", "R700k", 2, 1)
house5 = houses("Bayou_Road11", "R 900", 4, 2)
house6 = houses("Bienville_Street78", "R700k", 2, 2)
house7 = houses("Bourbon_Street45", "R 800k", 4, 1)
house8 = houses("Broad_Street56", "R 900k", 5, 3)

print("\n",house1.HouseDetails())

Please Note

The "R" at asking price is my currency.

Body:
If you must have getter and setter methods, here's a succinct way to do it using Python's built-in property class. The create_property() utility function shown is a simplified version of recipe 9.21 in the 3rd edition of the Python Cookbook by Beazley & Jones (2013).

def create_property(name):
    """ Utility to define repetitive property methods. """
    storage_name = '_' + name

    @property
    def prop(self):  # getter
        return getattr(self, storage_name)

    @prop.setter
    def prop(self, value):  # setter
        return setattr(self, storage_name, value)

    return prop

class House:
    address = create_property('address')
    asking_price = create_property('asking_price')
    num_bedrooms = create_property('num_bedrooms')
    num_bathrooms = create_property('num_bathrooms')

    def __init__(self, address, asking_price, num_bedrooms, num_bathrooms):
        self.address = address
        self.asking_price = asking_price
        self.num_bedrooms = num_bedrooms
        self.num_bathrooms = num_bathrooms

    def __str__(self):
        return("The house is at {} with a price of {} and has "
               "{} Bedroom/s and {} bathroom/s".format(self.address,
                    self.asking_price, self.num_bedrooms,
                    self.num_bathrooms))

house1 = House("Almonaster Avenue 87", "R 500k", 1, 1)
house2 = House("Audubon Place 33", "R 900k", 3, 3)
house3 = House("Baronne Street 78", "R 800k", 3, 2)
house4 = House("Basin Street 55", "R 700k", 2, 1)
house5 = House("Bayou Road1 1", "R 900", 4, 2)
house6 = House("Bienville Street 78", "R 700k", 2, 2)
house7 = House("Bourbon Street 45", "R 800k", 4, 1)
house8 = House("Broad Street 56", "R 900k", 5, 3)

print(house1)

Output:

The house is at Almonaster Avenue 87 with a price of R 500k and has 1 Bedroom/s and 1 bathroom/s


问:
Test jsonb array to see if it contains one or more elements?
I have a user table with a data jsonb column. In that, I have a cars array that can have 0-N cars in it.

I'm trying to do a query like this to find if the user's cars array contains either Toyota or Mitsubishi, but it's throwing an error

```<code>await knex('users.record')
    .where('created_at', '>', '2019-05-21')
    .select('data')
    .whereRaw('cars', ['Toyota', 'Mitsubishi']) // this seems wrong
    .returning('*');
</code>```

One example user's cars array is ['Toyota', 'Mitsubishi', 'Honda', 'Ford']

答:
I think it's going to look something like this in Knex (with a little helper function to reduce repetition):

const hasCar = brand => knex.raw(
  `?? @> ?::jsonb`,
  [
    'data',
    JSON.stringify({ cars: [ brand ]})
  ]
)

knex('users.record')
  .where(hasCar('Mitsubishi'))
  .orWhere(hasCar('Toyota'))

```

Body:
I have a user table with a data jsonb column. In that, I have a cars array that can have 0-N cars in it.

I'm trying to do a query like this to find if the user's cars array contains either Toyota or Mitsubishi, but it's throwing an error

await knex('users.record')
    .where('created_at', '>', '2019-05-21')
    .select('data')
    .whereRaw('cars', ['Toyota', 'Mitsubishi']) // this seems wrong
    .returning('*');

One example user's cars array is ['Toyota', 'Mitsubishi', 'Honda', 'Ford']


问:
Metrics/AbcSize: Assignment Branch Condition size for create is too high. [15.17/15]
I would prefer to call my JS method directly from controller, but I am getting the following Rubocop error.

Error:

Metrics/AbcSize: Assignment Branch Condition size for create is too
  high. [15.17/15]

controller:

```<code> def create ...

      def create
        @profile = current_user.profiles.new(modified_profile_params)
        respond_to do |format|
          if @profile.save
            format.html { redirect_to profiles_path }
            format.js { render js: "Helpers.SearchForm.AfterSearchSubmit();" }
          else
            format.html { render action: "new" }
            format.js {
              render js:
                         "Helpers.Bootstrap.Modal.init(
                         'Title',
                         'message','ok',
                         '',
                         '#oldmodal',
                         Helpers.SearchForm.AfterSearchSubmit
                         );"
            }
          end
        end
      end
</code>```

to fix this, I tried the below:

```<code>def limit_modal_javascript
           {
                  render js:
                             "Helpers.Bootstrap.Modal.init(
                             'Title',
                             'message','ok',
                             '',
                             '#oldmodal',
                             Helpers.SearchForm.AfterSearchSubmit
                             );"
                }
  end
</code>```

however, I then got following error at runtime:

syntax error, unexpected tLABEL, expecting do or '{' or '(' {render
  js:

答:
You can fix the syntax error by moving render to before the opening { in the limit_modal_javascript method.

However, there are better ways to structure this. Rather having the JavaScript in the controller, you could move it to a template, e.g. app/views/products/create_succeeded.js. You can then render that from the controller with:

```<code>format.js { render "products/create_succeeded" }
</code>```

Body:
I would prefer to call my JS method directly from controller, but I am getting the following Rubocop error.

Error:

Metrics/AbcSize: Assignment Branch Condition size for create is too
  high. [15.17/15]

controller:

 def create ...

      def create
        @profile = current_user.profiles.new(modified_profile_params)
        respond_to do |format|
          if @profile.save
            format.html { redirect_to profiles_path }
            format.js { render js: "Helpers.SearchForm.AfterSearchSubmit();" }
          else
            format.html { render action: "new" }
            format.js {
              render js:
                         "Helpers.Bootstrap.Modal.init(
                         'Title',
                         'message','ok',
                         '',
                         '#oldmodal',
                         Helpers.SearchForm.AfterSearchSubmit
                         );"
            }
          end
        end
      end

to fix this, I tried the below:

def limit_modal_javascript
           {
                  render js:
                             "Helpers.Bootstrap.Modal.init(
                             'Title',
                             'message','ok',
                             '',
                             '#oldmodal',
                             Helpers.SearchForm.AfterSearchSubmit
                             );"
                }
  end

however, I then got following error at runtime:

syntax error, unexpected tLABEL, expecting do or '{' or '(' {render
  js:

Body:
You can fix the syntax error by moving render to before the opening { in the limit_modal_javascript method.

However, there are better ways to structure this. Rather having the JavaScript in the controller, you could move it to a template, e.g. app/views/products/create_succeeded.js. You can then render that from the controller with:

format.js { render "products/create_succeeded" }


问:
Decrypt data in typescript that have been encrypted in python
I am trying to decrypt data that has been previously encrypted in python, but I can not.

I encrypt the data using the following in python:

```<code>iv = Random.new().read( AES.block_size )
cipher = AES.new(secret_key,AES.MODE_CBC, iv)
encrypdata = base64.b64encode(iv + cipher.encrypt(data))
</code>```

I decrypt it with the following in python:

```<code>enc = base64.b64decode(encrypdata)
iv = enc[:16]
cipher = AES.new(secret_key, AES.MODE_CBC, iv )
decryptdata = cipher.decrypt( enc[16:] ).strip()
</code>```

But when I try it with typescript it fails:

```<code>enc = Buffer.from(encrypdata, 'base64').toString();
iv = enc.toString().slice(0,16);
cipher = crypto.createDecipheriv("aes-256-cbc",secret_key,  iv );
decryptdata = cipher.update( enc.slice(16) ).strip();
</code>```

The current error that I am receiving is "Invalid IV length", but the length of iv is 16.

Can someone tell me how to accomplish this?
Thanks.

答:
With the following configuration I was able to decrypt the data:</p>

```<code>     enc = Buffer.from(datos, 'base64');
     iv = enc.slice(0, 16);
     crypt = enc.toString('base64', 16);
     decipher = crypto.createDecipheriv('aes-128-cbc', secret_key, iv);
     decipher.setAutoPadding(false);
     dec = decipher.update(crypt,'base64','utf-8');
     dec += decipher.final('utf-8');
</code>```

Body:
I am trying to decrypt data that has been previously encrypted in python, but I can not.

I encrypt the data using the following in python:

iv = Random.new().read( AES.block_size )
cipher = AES.new(secret_key,AES.MODE_CBC, iv)
encrypdata = base64.b64encode(iv + cipher.encrypt(data))

I decrypt it with the following in python:

enc = base64.b64decode(encrypdata)
iv = enc[:16]
cipher = AES.new(secret_key, AES.MODE_CBC, iv )
decryptdata = cipher.decrypt( enc[16:] ).strip()

But when I try it with typescript it fails:

enc = Buffer.from(encrypdata, 'base64').toString();
iv = enc.toString().slice(0,16);
cipher = crypto.createDecipheriv("aes-256-cbc",secret_key,  iv );
decryptdata = cipher.update( enc.slice(16) ).strip();

The current error that I am receiving is "Invalid IV length", but the length of iv is 16.

Can someone tell me how to accomplish this?
Thanks.

Body:
With the following configuration I was able to decrypt the data:

     enc = Buffer.from(datos, 'base64');
     iv = enc.slice(0, 16);
     crypt = enc.toString('base64', 16);
     decipher = crypto.createDecipheriv('aes-128-cbc', secret_key, iv);
     decipher.setAutoPadding(false);
     dec = decipher.update(crypt,'base64','utf-8');
     dec += decipher.final('utf-8');


问:
Does @angular-devkit/build-ng-packagr:build have any configurable options?
I'm using the Angular CLI to build/package my component library, and I wanted to include the README.md from the root of the project instead of the file from the projects folder.

So I wanted to see if the builder had any configuration options, but there aren't any published on the wiki.

This is what I found: https://github.com/angular/angular-cli/blob/master/packages/angular_devkit/build_ng_packagr/README.md

I want to add options to my angular.json for building the library.

```<code>        "build": {
          "builder": "@angular-devkit/build-ng-packagr:build",
          "options": {
            "tsConfig": "library/tsconfig.lib.json",
            "project": "library/ng-package.json",
            // add options here!
          }
        },
</code>```

There is no wiki on documentation on the packagr repo.

https://github.com/ng-packagr/ng-packagr

My other option was to look at the JSON schema for this builder, but I do not know how to read it.

Does the ngPackagr have configurable options for the builder?

答:
It only appears to support a watch parameter for the configuration. The schema is located here:

https://github.com/angular/angular-cli/blob/master/packages/angular_devkit/build_ng_packagr/src/build/schema.json

Looking at the source code there aren't any other options either (watch isn't use in the code).

```<code>async function initialize(
  options: NgPackagrBuilderOptions,
  root: string,
): Promise<import ('ng-packagr').NgPackagr> {
  const packager = (await import('ng-packagr')).ngPackagr();

  packager.forProject(resolve(root, options.project));

  if (options.tsConfig) {
    packager.withTsConfig(resolve(root, options.tsConfig));
  }

  return packager;
}
</code>```

https://github.com/angular/angular-cli/blob/master/packages/angular_devkit/build_ng_packagr/src/build/index.ts

Body:
I'm using the Angular CLI to build/package my component library, and I wanted to include the README.md from the root of the project instead of the file from the projects folder.

So I wanted to see if the builder had any configuration options, but there aren't any published on the wiki.

This is what I found: https://github.com/angular/angular-cli/blob/master/packages/angular_devkit/build_ng_packagr/README.md

I want to add options to my angular.json for building the library.

        "build": {
          "builder": "@angular-devkit/build-ng-packagr:build",
          "options": {
            "tsConfig": "library/tsconfig.lib.json",
            "project": "library/ng-package.json",
            // add options here!
          }
        },

There is no wiki on documentation on the packagr repo.

https://github.com/ng-packagr/ng-packagr

My other option was to look at the JSON schema for this builder, but I do not know how to read it.

Does the ngPackagr have configurable options for the builder?

Body:
It only appears to support a watch parameter for the configuration. The schema is located here:

https://github.com/angular/angular-cli/blob/master/packages/angular_devkit/build_ng_packagr/src/build/schema.json

Looking at the source code there aren't any other options either (watch isn't use in the code).

async function initialize(
  options: NgPackagrBuilderOptions,
  root: string,
): Promise<import ('ng-packagr').NgPackagr> {
  const packager = (await import('ng-packagr')).ngPackagr();

  packager.forProject(resolve(root, options.project));

  if (options.tsConfig) {
    packager.withTsConfig(resolve(root, options.tsConfig));
  }

  return packager;
}

https://github.com/angular/angular-cli/blob/master/packages/angular_devkit/build_ng_packagr/src/build/index.ts