问:
Test two directory trees for equality
I am working on integration testing some part of my code that creates directory trees under SVN. This requires me to test if the directory structure and the files within are what I expect them to be.

On one hand I have the expected directory tree with the files I want and on the other, an export of the files from SVN (prefer svn export over svn co to avoid the .svn noise).

However, is there any library that can assert two directory trees? The last resort I have in mind is to do an iterative comparison myself.

Basically I am looking for an API that can just accept two directories and tell me if they are equal or not.

Something on the lines of

```<code>boolean areDirectoriesEqual(File dir1, File dir2)
</code>```

答:
I know this is an old question but I will try to solve it.
Here is a code that opens 2 directories and compares their contents.
It returns false if the files found in one are missing in the other or if their contents are distinct.
To do this, I browse the content of the 2 directories and I recursively compare the files and directories found (in alphabetical order).</p>

```<code>// Comparison of 2 files
private static boolean compareFiles(File f1, File f2) {
    long i1 = f1.length();
    long i2 = f2.length();
    if (i1 != i2) {
        return false;
    }
    try {
        byte b1, b2;
        DataInputStream dis = new DataInputStream(
                new BufferedInputStream(
                        new FileInputStream(f1)));
        DataInputStream dis1 = new DataInputStream(
                new BufferedInputStream(
                        new FileInputStream(f2)));
        while (true) {
            b1 = dis.readByte();
            b2 = dis1.readByte();
            if (b1 != b2) {
                return false;
            }
        }
    } catch (IOException ex) {
        return true;
    }
}

// Recursive comparison of 2 files.
// The idea is that if 2 directories are the same,
// they will have the same files and the same under directories
private static boolean areDirsEqual(File dir1, File dir2) {
    File[] list1 = dir1.listFiles(), list2 = dir2.listFiles();
    if (list1.length != list2.length) {
        return false;
    }
    for (int i = 0; i < list2.length; i++) {
        if (list1[i].isFile() && list2[i].isFile()) {
            if (!compareFiles(list1[i], list2[i])) {
                return false;
            }
        } else if (list1[i].isDirectory() && list2[i].isDirectory()) {
            if (!areDirsEqual(list1[i], list2[i])) {
                return false;
            }
        } else {
            return false;
        }
    }
    return true;
}
</code>```

Title: Test two directory trees for equality

Body:
I am working on integration testing some part of my code that creates directory trees under SVN. This requires me to test if the directory structure and the files within are what I expect them to be.

On one hand I have the expected directory tree with the files I want and on the other, an export of the files from SVN (prefer svn export over svn co to avoid the .svn noise).

However, is there any library that can assert two directory trees? The last resort I have in mind is to do an iterative comparison myself.

Basically I am looking for an API that can just accept two directories and tell me if they are equal or not.

Something on the lines of

boolean areDirectoriesEqual(File dir1, File dir2)

Body:
I know this is an old question but I will try to solve it.
Here is a code that opens 2 directories and compares their contents.
It returns false if the files found in one are missing in the other or if their contents are distinct.
To do this, I browse the content of the 2 directories and I recursively compare the files and directories found (in alphabetical order).

// Comparison of 2 files
private static boolean compareFiles(File f1, File f2) {
    long i1 = f1.length();
    long i2 = f2.length();
    if (i1 != i2) {
        return false;
    }
    try {
        byte b1, b2;
        DataInputStream dis = new DataInputStream(
                new BufferedInputStream(
                        new FileInputStream(f1)));
        DataInputStream dis1 = new DataInputStream(
                new BufferedInputStream(
                        new FileInputStream(f2)));
        while (true) {
            b1 = dis.readByte();
            b2 = dis1.readByte();
            if (b1 != b2) {
                return false;
            }
        }
    } catch (IOException ex) {
        return true;
    }
}

// Recursive comparison of 2 files.
// The idea is that if 2 directories are the same,
// they will have the same files and the same under directories
private static boolean areDirsEqual(File dir1, File dir2) {
    File[] list1 = dir1.listFiles(), list2 = dir2.listFiles();
    if (list1.length != list2.length) {
        return false;
    }
    for (int i = 0; i < list2.length; i++) {
        if (list1[i].isFile() && list2[i].isFile()) {
            if (!compareFiles(list1[i], list2[i])) {
                return false;
            }
        } else if (list1[i].isDirectory() && list2[i].isDirectory()) {
            if (!areDirsEqual(list1[i], list2[i])) {
                return false;
            }
        } else {
            return false;
        }
    }
    return true;
}


来源: stackexchange

问:
Counting the number of occurrences of an ID in a dataframe in R
I have a dataframe with roughly 6000 objects that looks like this:

V1 and V2 are IDs of people who have communicated with each other (messages from V1 to V2), and V3 can be ignored. I am trying to find out the number of persons someone has communicated with i.e. the number of times an ID appears in either column V1 or V2 (I removed the duplicates). Can I use the count function to do this? If so, how?

答:
You said "find out the number of persons someone has communicated with", suggesting you need to break it down by-person.

Similar data to @bbiasi, though I'll reduce it for readability (since the matrix is large/square):

set.seed(2)
df <- data.frame(V1 = sample(x = 10, size = 50, replace = TRUE),
                 V2 = sample(x = 10, size = 50, replace = TRUE))
(m <- do.call(table, df[1:2]))
#     V2
# V1   1 2 3 4 5 6 7 8 9 10
#   1  1 0 0 1 0 0 0 0 0  0
#   2  1 1 2 2 0 2 1 1 0  1
#   3  0 0 0 2 1 0 0 0 1  0
#   4  1 1 0 1 0 0 0 0 1  0
#   5  0 0 1 0 0 0 1 1 1  0
#   6  0 2 0 0 0 0 1 2 0  0
#   7  0 0 1 0 0 0 0 1 1  0
#   8  1 1 0 0 0 0 1 0 0  0
#   9  2 0 0 0 3 0 0 0 0  2
#   10 0 0 1 1 3 0 0 0 1  1
```

<p>From this, you can see that (for instance) id 5 (fifth row) communicates with 3 and 7-9. Since I don't infer that your data is perfectly commutative, id 5 (fifth column) is <em>communicated-to</em> by id 3 and a lot more by ids 9-10.</p>

<p>If you need it to be commutative (identical across the diagonal), you can force it with:</p>

<pre class="lang-r prettyprint-override"><code>m[upper.tri(m)] <- m[upper.tri(m)] + m[lower.tri(m)]
m[lower.tri(m)] <- m[upper.tri(m)]
m
#     V2
# V1   1 2 3 4 5 6 7 8 9 10
#   1  1 1 0 1 1 1 0 0 0  0
#   2  1 1 3 2 2 2 1 1 1  1
#   3  0 0 0 2 1 2 0 1 1  0
#   4  3 1 0 1 0 0 1 0 1  1
#   5  1 2 1 0 0 1 1 1 1  0
#   6  2 2 1 1 1 0 2 2 3  0
#   7  2 0 2 2 1 0 0 1 4  0
#   8  1 1 0 1 1 0 1 0 0  0
#   9  2 0 1 0 3 1 0 0 0  3
#   10 1 1 1 1 4 0 0 0 3  1
</code>```

(If the number of columns is fixed, do.call(...) can be replaced with xtabs(~V1+V2, data=df) or table(V1=df$V1, V2=df$V2).)

ContentLicense: CC BY-SA 4.0

Body:
You said "find out the number of persons someone has communicated with", suggesting you need to break it down by-person.

Similar data to @bbiasi, though I'll reduce it for readability (since the matrix is large/square):

set.seed(2)
df <- data.frame(V1 = sample(x = 10, size = 50, replace = TRUE),
                 V2 = sample(x = 10, size = 50, replace = TRUE))
(m <- do.call(table, df[1:2]))
#     V2
# V1   1 2 3 4 5 6 7 8 9 10
#   1  1 0 0 1 0 0 0 0 0  0
#   2  1 1 2 2 0 2 1 1 0  1
#   3  0 0 0 2 1 0 0 0 1  0
#   4  1 1 0 1 0 0 0 0 1  0
#   5  0 0 1 0 0 0 1 1 1  0
#   6  0 2 0 0 0 0 1 2 0  0
#   7  0 0 1 0 0 0 0 1 1  0
#   8  1 1 0 0 0 0 1 0 0  0
#   9  2 0 0 0 3 0 0 0 0  2
#   10 0 0 1 1 3 0 0 0 1  1

From this, you can see that (for instance) id 5 (fifth row) communicates with 3 and 7-9. Since I don't infer that your data is perfectly commutative, id 5 (fifth column) is communicated-to by id 3 and a lot more by ids 9-10.

If you need it to be commutative (identical across the diagonal), you can force it with:

m[upper.tri(m)] <- m[upper.tri(m)] + m[lower.tri(m)]
m[lower.tri(m)] <- m[upper.tri(m)]
m
#     V2
# V1   1 2 3 4 5 6 7 8 9 10
#   1  1 1 0 1 1 1 0 0 0  0
#   2  1 1 3 2 2 2 1 1 1  1
#   3  0 0 0 2 1 2 0 1 1  0
#   4  3 1 0 1 0 0 1 0 1  1
#   5  1 2 1 0 0 1 1 1 1  0
#   6  2 2 1 1 1 0 2 2 3  0
#   7  2 0 2 2 1 0 0 1 4  0
#   8  1 1 0 1 1 0 1 0 0  0
#   9  2 0 1 0 3 1 0 0 0  3
#   10 1 1 1 1 4 0 0 0 3  1

(If the number of columns is fixed, do.call(...) can be replaced with xtabs(~V1+V2, data=df) or table(V1=df$V1, V2=df$V2).)


问:
Exclude a property from unobstrusive client Validation with MVC 3
I have a class User, that have an Email property, like that :

```<code>public class User : Entity
{
...
    [Display(Name = "Email"), Required(ErrorMessage = "Required."), Remote("EmailExists", "User", ErrorMessage = "Email already in Use.")]
    public virtual string Email { get; set; }
...
}
</code>```

My View Create works fine with all the validation ...
But in my view Edit, my Email texbox is Readonly, so The user cant change the email...

The problem is my Remote validation EmailExists keeps firing...

Is there a way to exclude the Email client validation just in that case? Or maybe another solution?

Thanks

答: I think that the easier way is to disable the field in the client instead of using readonly. The validate plugin doesn't take in account disabled fields. </p>

ContentLicense: CC BY-SA 3.0

Body:
I have a class User, that have an Email property, like that :

public class User : Entity
{
...
    [Display(Name = "Email"), Required(ErrorMessage = "Required."), Remote("EmailExists", "User", ErrorMessage = "Email already in Use.")]
    public virtual string Email { get; set; }
...
}

My View Create works fine with all the validation ...
But in my view Edit, my Email texbox is Readonly, so The user cant change the email...

The problem is my Remote validation EmailExists keeps firing...

Is there a way to exclude the Email client validation just in that case? Or maybe another solution?

Thanks


问:
How to use Python's RotatingFileHandler
I'm trying to do a test run of the logging module's RotatingFileHandler as follows:

```<code>import logging
from logging.handlers import RotatingFileHandler

# logging.basicConfig(filename="example.log", level=logging.DEBUG)

logger = logging.getLogger('my_logger')
handler = RotatingFileHandler("my_log.log", maxBytes=2000, backupCount=10)
logger.addHandler(handler)

for _ in range(10000):
    logger.debug("Hello, world!")
</code>```

However, with logging.basicConfig line commented out, the resulting my_log.log file contains no data:

If I comment in the line with logging.basicConfig(filename="example.log", level=logging.DEBUG), I get the expected my_log.log files with numbered suffixes. However, there is also the example.log which is a (relatively) large file:

How can I set up the logging so that it only generates the my_log.log files, and not the large example.log file?

答:
Going off of Kurt Peek's answer you can also put the rotating file handler in the logging.basicConfig directly</p>

```<code>import logging
from logging.handlers import RotatingFileHandler
logging.basicConfig(
        handlers=[RotatingFileHandler('./my_log.log', maxBytes=100000, backupCount=10)],
        level=logging.DEBUG,
        format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
        datefmt='%Y-%m-%dT%H:%M:%S')
</code>```

Title: How to use Python's RotatingFileHandler

Body:
I'm trying to do a test run of the logging module's RotatingFileHandler as follows:

import logging
from logging.handlers import RotatingFileHandler

# logging.basicConfig(filename="example.log", level=logging.DEBUG)

logger = logging.getLogger('my_logger')
handler = RotatingFileHandler("my_log.log", maxBytes=2000, backupCount=10)
logger.addHandler(handler)

for _ in range(10000):
    logger.debug("Hello, world!")

However, with logging.basicConfig line commented out, the resulting my_log.log file contains no data:

If I comment in the line with logging.basicConfig(filename="example.log", level=logging.DEBUG), I get the expected my_log.log files with numbered suffixes. However, there is also the example.log which is a (relatively) large file:

How can I set up the logging so that it only generates the my_log.log files, and not the large example.log file?

Body:
Going off of Kurt Peek's answer you can also put the rotating file handler in the logging.basicConfig directly

import logging
from logging.handlers import RotatingFileHandler
logging.basicConfig(
        handlers=[RotatingFileHandler('./my_log.log', maxBytes=100000, backupCount=10)],
        level=logging.DEBUG,
        format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
        datefmt='%Y-%m-%dT%H:%M:%S')


问:
Laravel Command outputs different version of node than command line
I upgraded my node to v10.16.0 on a server containing a running Laravel instance.

This is the output after upgrade:

$ node -v
v10.16.0
```

<p>This is the ouptut from running the Laravel scheduled command manually and echo-ing the response:</p>

<pre class="lang-sh prettyprint-override"><code>$ php artisan custom:command
v10.16.0
</code>```

This is the output when that command is run by Laravel on it's 5 minute schedule:

v6.14.3
```

<p>Laravel command is as follows:</p>

<pre class="lang-php prettyprint-override"><code>$process = new Process("node -v");
$process->run();
</code>```

How is this possible? Surely Laravel just runs a command on the command line in the same way you'd use exec() and thus should be on the same version. Even php artisan seems to get the right version.

答:
Restart the server

Make sure that you've removed the older version of node and you only have v10

Body:
I upgraded my node to v10.16.0 on a server containing a running Laravel instance.

This is the output after upgrade:

$ node -v
v10.16.0

This is the ouptut from running the Laravel scheduled command manually and echo-ing the response:

$ php artisan custom:command
v10.16.0

This is the output when that command is run by Laravel on it's 5 minute schedule:

v6.14.3

Laravel command is as follows:

$process = new Process("node -v");
$process->run();

How is this possible? Surely Laravel just runs a command on the command line in the same way you'd use exec() and thus should be on the same version. Even php artisan seems to get the right version.


问:
Extract groups of consecutive values having greater than specified size
I am trying to find within a dataframe if there are at least X consecutive operations (I already included a column "Filter_OK" that calculates if the row meets the criteria), and extract that group of rows.

```<code>      TRN     TRN_DATE          FILTER_OK
0   5153    04/04/2017 11:40:00      True
1   7542    04/04/2017 17:18:00      True
2   875     04/04/2017 20:08:00      True
3   74      05/04/2017 20:30:00     False
4   9652    06/04/2017 20:32:00      True
5   965     07/04/2017 12:52:00      True
6   752     10/04/2017 17:40:00      True
7   9541    10/04/2017 19:29:00      True
8   7452    11/04/2017 12:20:00      True
9   9651    12/04/2017 13:57:00     False
</code>```

For this example, if I am looking for 4 operations.

OUTPUT DESIRED:

```<code>    TRN     TRN_DATE    FILTER_OK
4   9652    06/04/2017  20:32:00    True
5   965     07/04/2017  12:52:00    True
6   752     10/04/2017  17:40:00    True
7   9541    10/04/2017  19:29:00    True
8   7452    11/04/2017  12:20:00    True
</code>```

How can i subset the operations I need?

Body:
I am trying to find within a dataframe if there are at least X consecutive operations (I already included a column "Filter_OK" that calculates if the row meets the criteria), and extract that group of rows.

      TRN     TRN_DATE          FILTER_OK
0   5153    04/04/2017 11:40:00      True
1   7542    04/04/2017 17:18:00      True
2   875     04/04/2017 20:08:00      True
3   74      05/04/2017 20:30:00     False
4   9652    06/04/2017 20:32:00      True
5   965     07/04/2017 12:52:00      True
6   752     10/04/2017 17:40:00      True
7   9541    10/04/2017 19:29:00      True
8   7452    11/04/2017 12:20:00      True
9   9651    12/04/2017 13:57:00     False

For this example, if I am looking for 4 operations.

OUTPUT DESIRED:

    TRN     TRN_DATE    FILTER_OK
4   9652    06/04/2017  20:32:00    True
5   965     07/04/2017  12:52:00    True
6   752     10/04/2017  17:40:00    True
7   9541    10/04/2017  19:29:00    True
8   7452    11/04/2017  12:20:00    True

How can i subset the operations I need?

Body:
This is actually part of a "group by" operation (by CRD Column).
If there are two consecutive groups of rows (Crd 111 and 333), and the second group of rows does not meet the condition (not 4 consecutive True), the first row of the group is included (the bold line), when it shouldn't

CRD     TRN     TRN_DATE            FILTER_OK

0    111    5153    04/04/2017 11:40:00     True

1       111     7542    04/04/2017 17:18:00     True

2       256     875     04/04/2017 20:08:00     True

3       365     74      05/04/2017 20:30:00     False

4       111     9652    06/04/2017 20:32:00     True

5       111     965     07/04/2017 12:52:00     True

6       111     752     10/04/2017 17:40:00     True

7       111     9541    10/04/2017 19:29:00     True

**8     333     7452    11/04/2017 12:20:00     True**

9       333     9651    12/04/2017 13:57:00     False

10      333     961     12/04/2017 13:57:00     False

11      333     871     12/04/2017 13:57:00     False

Actual output:

    CRD  TRN     TRN_DATE          FILTER_OK
4   111  9652    06/04/2017 20:32:00      True

5   111  965     07/04/2017 12:52:00      True

6   111  752     10/04/2017 17:40:00      True

7   111  9541    10/04/2017 19:29:00      True

**8   333  7452    11/04/2017 12:20:00      True**

Desired output:

    CRD  TRN     TRN_DATE          FILTER_OK
4   111  9652    06/04/2017 20:32:00      True

5   111  965     07/04/2017 12:52:00      True

6   111  752     10/04/2017 17:40:00      True

7   111  9541    10/04/2017 19:29:00      True


问:
Can a Silverlight MediaElement open a video from the client?
Can a Silverlight MediaElement open and play a video from the client, after it is selected from an open file dialog?</p>

答: The answer is no. You can only source a Uri, but not a file:// one because you cannot read local folder information.</p>

OwnerDisplayName: BC

ContentLicense: CC BY-SA 2.5


问:
Delete square brackets in the CSV fie
I plot the results from python to CSV file. Unfortunately, the data plotted on the CSV file is difficult to edit. In fact each cell of Excel contains a data wrapped by square brackets. How would it be possible to delete the square brackets in the CSV file?

Here below you can find the code.

```<code>a=[[1.5458, 1.2585, 3.5687]]
S=(["S"], np.round(a,3), {' [MPa]'})
with open('Output.csv', 'w', newline='') as dest:
    thewriter = csv.writer(dest, delimiter=',')
    thewriter.writerows(a)
</code>```

The output the I would like to get in the CSV file is the following one:

```<code>1.5458 1.2585 3.5687
</code>```

Each number appears in a single cell of Excel.

答:
Excel can be a bit picky when opening flat text files such as CSV.  Sometimes it will automatically place items into separate columns other times it won't.  It seems the last setting used on "Text to columns" feature "sticks" until you close Excel.

Close all your open Excel windows then reopen the file.

Also just open the file in notepad to check that it looks ok.  Don't allow the complexity of everything Excel does to complicate things.  Sorry this is an answer and not a comment, I am new to this site and don't have enough points to comment yet :-(

Title: Delete square brackets in the CSV fie

Body:
I plot the results from python to CSV file. Unfortunately, the data plotted on the CSV file is difficult to edit. In fact each cell of Excel contains a data wrapped by square brackets. How would it be possible to delete the square brackets in the CSV file?

Here below you can find the code.

a=[[1.5458, 1.2585, 3.5687]]
S=(["S"], np.round(a,3), {' [MPa]'})
with open('Output.csv', 'w', newline='') as dest:
    thewriter = csv.writer(dest, delimiter=',')
    thewriter.writerows(a)

The output the I would like to get in the CSV file is the following one:

1.5458 1.2585 3.5687

Each number appears in a single cell of Excel.


问:
The variables i'm seeing in MySQL workbench does not match up with what i see in my docker-compose
Im using docker-compose to setup a mysql instance with a customized configuration file.

Here's what I have in the file:

```<code>version: '3.7'

services:
  db:
    build: ./db
    command: mysqld --default-authentication-plugin=mysql_native_password
    restart: always
    ports:
      - 3306:3306
    environment:
      MYSQL_RANDOM_ROOT_PASSWORD: 'yes'
    volumes:
      - mysql_data:/var/lib/mysql
      - $HOME/infrastructure/config/:/etc/mysql/conf.d
volumes:
  mysql_data:
</code>```

When i build the container and connect to my database through mysql workbench, i'm not seeing the correct variables that matching up with what i see in docker. I connected to Bash in my mysql container and executed: 'mysqld --verbose --help' and I see that the variables match up with my configuration file, but not with my mysql workbench.

I'm using MySQL 8.0.

Edit: After running 'mysqladmin variables' in the bash, i realized the variables do not match with my my.cnf file.

Any help would be much appreciated. Thank you!

答:
Everything is fine and I guess this will answer your question:

The file must have the ".cnf" extension, otherwise it will be
ignored.

In mysql 8.0 the sql mode syntax changed:

```<code>[mysqld]
sql-mode="modes"
</code>```

You can also use the --sql-mode="" directly in the docker command.

Body:
Im using docker-compose to setup a mysql instance with a customized configuration file.

Here's what I have in the file:

version: '3.7'

services:
  db:
    build: ./db
    command: mysqld --default-authentication-plugin=mysql_native_password
    restart: always
    ports:
      - 3306:3306
    environment:
      MYSQL_RANDOM_ROOT_PASSWORD: 'yes'
    volumes:
      - mysql_data:/var/lib/mysql
      - $HOME/infrastructure/config/:/etc/mysql/conf.d
volumes:
  mysql_data:

When i build the container and connect to my database through mysql workbench, i'm not seeing the correct variables that matching up with what i see in docker. I connected to Bash in my mysql container and executed: 'mysqld --verbose --help' and I see that the variables match up with my configuration file, but not with my mysql workbench.

I'm using MySQL 8.0.

Edit: After running 'mysqladmin variables' in the bash, i realized the variables do not match with my my.cnf file.

Any help would be much appreciated. Thank you!

Body:
Everything is fine and I guess this will answer your question:

The file must have the ".cnf" extension, otherwise it will be
ignored.

In mysql 8.0 the sql mode syntax changed:

[mysqld]
sql-mode="modes"

You can also use the --sql-mode="" directly in the docker command.


问:
Conversion from a formatted date to a variable
```<code>$now =  date("Y-m-d H:i:s");
$date1=date_create($StartDate);
$date2=date_create($now);
$diff=date_diff($date1,$date2);
echo $diff->format("%a");  //Difference in days, Es: 5
</code>```

echo shows 5 as expected, but how can I now cast $diff into a variable like an int that I can use to make other numerical comparisons?

答:
Most of the time PHP will automatically convert to an int when you use the variable in a numeric context. But if you want to do it yourself, use the intval() function.

```<code>$days_diff = intval($diff->format("%a"));
</code>```

Body:
$now =  date("Y-m-d H:i:s");
$date1=date_create($StartDate);
$date2=date_create($now);
$diff=date_diff($date1,$date2);
echo $diff->format("%a");  //Difference in days, Es: 5

echo shows 5 as expected, but how can I now cast $diff into a variable like an int that I can use to make other numerical comparisons?

Body:
Most of the time PHP will automatically convert to an int when you use the variable in a numeric context. But if you want to do it yourself, use the intval() function.

$days_diff = intval($diff->format("%a"));


问:
ImportError: cannot import name pubsub_v1
I need to import Pubsub_v1 and bigquery from google.cloud module. I have installed it and pip freeze shows below :

```<code>gapic-google-cloud-pubsub-v1==0.15.4
google-cloud-bigquery==0.26.0
google-cloud-pubsub==0.27.0
proto-google-cloud-pubsub-v1==0.15.4
</code>```

In my python script, i am importing the modules as below:

```<code>import os
from google.cloud import pubsub_v1
import time
import json
from google.cloud import bigquery
</code>```

The script is throwing error as :

```<code>ImportError: cannot import name pubsub_v1
</code>```

If i run $sudo pip install --upgrade google-cloud-pubsub then It is able to import pubsub but failing to import Bigquery. I need both modules. Can anybody please help ?

答:
$sudo pip install googleapis-common-protos

It resolves the issue for me!

Body:
I need to import Pubsub_v1 and bigquery from google.cloud module. I have installed it and pip freeze shows below :

gapic-google-cloud-pubsub-v1==0.15.4
google-cloud-bigquery==0.26.0
google-cloud-pubsub==0.27.0
proto-google-cloud-pubsub-v1==0.15.4

In my python script, i am importing the modules as below:

import os
from google.cloud import pubsub_v1
import time
import json
from google.cloud import bigquery

The script is throwing error as :

ImportError: cannot import name pubsub_v1

If i run $sudo pip install --upgrade google-cloud-pubsub then It is able to import pubsub but failing to import Bigquery. I need both modules. Can anybody please help ?


问:
In AWS CloudFormation are booleans and strings of booleans interchangeable?
I am confused by how AWS CloudFormation treats booleans and strings of booleans.

For instance, are 'true' and true (or 'false' and false) logically equivalent as far as CloudFormation is concerned? I see examples of both cases in their Quick Start templates that lead me to think they are (even though I haven't found documentation of this one way or another).

For instance, in their template, quickstart-compliance-common/templates/vpc-production.template, they define a variable, pSupportsNatGateway, of type "String" (even though its default is the literal value, true):

```<code>Parameters:
  ...
  pSupportsNatGateway:
    Description: Specifies whether this region supports NAT Gateway (this value is
      determined by the main stack if it is invoked from there)
    Type: String
    Default: true
</code>```

Then, in a condition later in the template, that parameter (presumably a String) is compared to the literal value, true.

```<code>Conditions:
  ...
  cSupportsNatGateway:
    !Equals
    - true
    - !Ref pSupportsNatGateway
</code>```

My question is, how does CloudFormation compare literal values and strings of those values? Where is this defined in the AWS documentation?

答:
I don't know where this is documented, but yes! It does appear that literal booleans (or numbers) and their string values are equivalent as far as CloudFormation is concerned.

I created a minimal CloudFormation template to test this:

```<code>---
AWSTemplateFormatVersion: 2010-09-09
Description: Test CloudFormation template

Parameters:

  pCreateCluster:
    Description: To create or not create?
    Type: String
    Default: 'true'
    AllowedValues:
    - 'true'
    - 'false'

Conditions:
  CreateClusterConditionTrue1:
    !Equals
    - !Ref pCreateCluster
    - 'true'

  CreateClusterConditionTrue2:
    !Equals
    - !Ref pCreateCluster
    - true

  CreateClusterConditionFalse1:
    !Equals
    - !Ref pCreateCluster
    - 'false'

  CreateClusterConditionFalse2:
    !Equals
    - !Ref pCreateCluster
    - false

Resources:

  rFargateCluster:
    Type: AWS::ECS::Cluster
    Condition: CreateClusterConditionTrue1
    Properties:
      ClusterName: "my-test-cluster"

Outputs:
  CreateClusterConditionTrue1:
    Value:
      !If
      - CreateClusterConditionTrue1
      - "The answer is True"
      - "The answer is False"
  CreateClusterConditionTrue2:
    Value:
      !If
      - CreateClusterConditionTrue2
      - "The answer is True"
      - "The answer is False"
  CreateClusterConditionFalse1:
    Value:
      !If
      - CreateClusterConditionFalse1
      - "The answer is True"
      - "The answer is False"
  CreateClusterConditionFalse2:
    Value:
      !If
      - CreateClusterConditionFalse2
      - "The answer is True"
      - "The answer is False"
...
</code>```

And the results demonstrate that they are in fact equivalent:

```<code>Key                             Value
CreateClusterConditionTrue1     The answer is True
CreateClusterConditionTrue2     The answer is True
CreateClusterConditionFalse2    The answer is False
CreateClusterConditionFalse1    The answer is False
</code>```

Body:
I am confused by how AWS CloudFormation treats booleans and strings of booleans.

For instance, are 'true' and true (or 'false' and false) logically equivalent as far as CloudFormation is concerned? I see examples of both cases in their Quick Start templates that lead me to think they are (even though I haven't found documentation of this one way or another).

For instance, in their template, quickstart-compliance-common/templates/vpc-production.template, they define a variable, pSupportsNatGateway, of type "String" (even though its default is the literal value, true):

Parameters:
  ...
  pSupportsNatGateway:
    Description: Specifies whether this region supports NAT Gateway (this value is
      determined by the main stack if it is invoked from there)
    Type: String
    Default: true

Then, in a condition later in the template, that parameter (presumably a String) is compared to the literal value, true.

Conditions:
  ...
  cSupportsNatGateway:
    !Equals
    - true
    - !Ref pSupportsNatGateway

My question is, how does CloudFormation compare literal values and strings of those values? Where is this defined in the AWS documentation?

Body:
I don't know where this is documented, but yes! It does appear that literal booleans (or numbers) and their string values are equivalent as far as CloudFormation is concerned.

I created a minimal CloudFormation template to test this:

---
AWSTemplateFormatVersion: 2010-09-09
Description: Test CloudFormation template

Parameters:

  pCreateCluster:
    Description: To create or not create?
    Type: String
    Default: 'true'
    AllowedValues:
    - 'true'
    - 'false'

Conditions:
  CreateClusterConditionTrue1:
    !Equals
    - !Ref pCreateCluster
    - 'true'

  CreateClusterConditionTrue2:
    !Equals
    - !Ref pCreateCluster
    - true

  CreateClusterConditionFalse1:
    !Equals
    - !Ref pCreateCluster
    - 'false'

  CreateClusterConditionFalse2:
    !Equals
    - !Ref pCreateCluster
    - false

Resources:

  rFargateCluster:
    Type: AWS::ECS::Cluster
    Condition: CreateClusterConditionTrue1
    Properties:
      ClusterName: "my-test-cluster"

Outputs:
  CreateClusterConditionTrue1:
    Value:
      !If
      - CreateClusterConditionTrue1
      - "The answer is True"
      - "The answer is False"
  CreateClusterConditionTrue2:
    Value:
      !If
      - CreateClusterConditionTrue2
      - "The answer is True"
      - "The answer is False"
  CreateClusterConditionFalse1:
    Value:
      !If
      - CreateClusterConditionFalse1
      - "The answer is True"
      - "The answer is False"
  CreateClusterConditionFalse2:
    Value:
      !If
      - CreateClusterConditionFalse2
      - "The answer is True"
      - "The answer is False"
...

And the results demonstrate that they are in fact equivalent:

Key                             Value
CreateClusterConditionTrue1     The answer is True
CreateClusterConditionTrue2     The answer is True
CreateClusterConditionFalse2    The answer is False
CreateClusterConditionFalse1    The answer is False


问:
nodejs push of undefined
```<code>function seedDB(){
   //Remove all campgrounds
   Campground.remove({}, function(err){
        if(err){
            console.log(err);
        }
        console.log("removed campgrounds!");
         //add a few campgrounds
        data.forEach(function(seed){
            Campground.create(seed, function(err, campground){
                if(err){
                    console.log(err)
                } else {
                    console.log("added a campground");
                    //create a comment
                    Comment.create(
                        {
                            text: "This place is great, but I wish there was internet",
                            author: "Homer"
                        }, function(err, comment){
                            if(err){
                                console.log(err);
                            } else {
                                **campground.comment.push(comment);**
                                campground.save();
                                console.log("Created new comment");
                            }
                        });
                }
            });
        });
    });
    //add a few comments
}

module.exports = seedDB;
</code>```

TypeError: Cannot read property 'push' of undefined
 can someone help me plz
i don't know what wrong in this function?
why he can't read the property push

答:
Try this

```<code> Comment.create(
                         {
                             text: "This place is great, but I wish there was internet",
                             author: "Homer"
                         }, function(err, commenttext){
                             if(err){
                                 console.log(err);
                             } else {
                                 campground.comment.push(commenttext);
                                 campground.save();
                                 console.log("Created new comment");
                             }
                        });
</code>```

if not work ... show me campground model

Title: nodejs push of undefined

Body:
function seedDB(){
   //Remove all campgrounds
   Campground.remove({}, function(err){
        if(err){
            console.log(err);
        }
        console.log("removed campgrounds!");
         //add a few campgrounds
        data.forEach(function(seed){
            Campground.create(seed, function(err, campground){
                if(err){
                    console.log(err)
                } else {
                    console.log("added a campground");
                    //create a comment
                    Comment.create(
                        {
                            text: "This place is great, but I wish there was internet",
                            author: "Homer"
                        }, function(err, comment){
                            if(err){
                                console.log(err);
                            } else {
                                **campground.comment.push(comment);**
                                campground.save();
                                console.log("Created new comment");
                            }
                        });
                }
            });
        });
    });
    //add a few comments
}

module.exports = seedDB;

TypeError: Cannot read property 'push' of undefined
 can someone help me plz
i don't know what wrong in this function?
why he can't read the property push

Body:
Try this

 Comment.create(
                         {
                             text: "This place is great, but I wish there was internet",
                             author: "Homer"
                         }, function(err, commenttext){
                             if(err){
                                 console.log(err);
                             } else {
                                 campground.comment.push(commenttext);
                                 campground.save();
                                 console.log("Created new comment");
                             }
                        });

if not work ... show me campground model


问:
How to print a Scala import
I am working with an imported library, which I have no direct access to. I would like to convert the imported library class to a string and print it to investigate its functions further. How can I convert a class to String?

I already tried .toString, print(libraryName)

import Library._

object something {
    def something = {
        print(Library)
    }
}
```

The outcome is an object, e.g. Library$@d126bba. However, I would like to see the actual class in String format instead.

答:
Not sure if you can get what you are looking for as a string. Another approach is to inspect it in the scala REPL.

Run scala -cp library.jar or whatever the jar name is.

Now, in the REPL run import Library._.

Typing Library. followed by tab should print out the classes and methods available.

For example I can explore the java.date package which consists of other packages.

```<code>scala> java.Date.
applet   awt   beans   io   lang   math   net   nio   rmi   security   sql ...
</code>```

Title: How to print a Scala import

Body:
I am working with an imported library, which I have no direct access to. I would like to convert the imported library class to a string and print it to investigate its functions further. How can I convert a class to String?

I already tried .toString, print(libraryName)

import Library._

object something {
    def something = {
        print(Library)
    }
}

The outcome is an object, e.g. Library$@d126bba. However, I would like to see the actual class in String format instead.

Body:
Not sure if you can get what you are looking for as a string. Another approach is to inspect it in the scala REPL.

Run scala -cp library.jar or whatever the jar name is.

Now, in the REPL run import Library._.

Typing Library. followed by tab should print out the classes and methods available.

For example I can explore the java.date package which consists of other packages.

scala> java.Date.
applet   awt   beans   io   lang   math   net   nio   rmi   security   sql ...


问:
How to correctly design a regular expression in pymongo?
I use python 3.7.1 (default, Dec 14 2018, 19:28:38), and pymongo 3.7.2.

In mongodb this works:

```<code>db.collection.find(
    {$and:[
    {"field":{$regex:"bon?"}},
    {"field":{$not:{$regex:"bon souple"}}},
    {"field":{$not:{$regex:"bon léger"}}}
    ]}
    )
</code>```

So in pymongo I did the same as:

```<code>db.collection.find(
    {"$and":[
    {"field":{"$regex":"bon?"}},
    {"field":{"$not":{"$regex":"bon souple"}}},
    {"field":{"$not":{"$regex":"bon léger"}}}
    ]}
    )
</code>```

but it indicatespymongo.errors.OperationFailure: $regex has to be a string.

So I tried this as proposed here:

```<code>liste_reg=[
{'field': {'$regex': {'$not': re.compile('bon souple')}}},
{'field': {'$regex': {'$not': re.compile('bon léger')}}},
{'field': {'$regex': re.compile('bon?')}}
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
</code>```

I noticed that even when there is no special character it indicates the same error:

```<code>liste_reg=[
{'field': {'$regex': {'$not': re.compile('bon souple')}}} #where no special char is present
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
</code>```

So I tried to use "/" as:

```<code>liste_reg=[
{'field': {'$regex': {'$not':'/bon souple/'}}} #where no special char is present
#even tried re.compile('/bon souple/')
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
</code>```

the same error pymongo.errors.OperationFailure: $regex has to be a string still occurs.

What can I do?

SOME UPDATE OF MY RESEARCH OF SOLUTION

the core of the issue seems to be with $not because when I do:

```<code>liste_reg=[{'field': {'$regex': 'bon?'}}]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
len(rslt)#gives 23 013, what is ok.
</code>```

There is no error.

SOME SAMPLES

As asked by Emma I can give a sample, and it will explicit my request in mongo.
Normally I must have these modalities in the field:

sec

très léger

léger

bon léger

bon

bon souple

souple

très souple

collant

lourd

très Lourd

profond

The main problem for me is my spider did not parse correctly because I did not write a strong enough script for that.
Instead of obtaining just "bon", I obtain this kind of result:

```<code>{"_id":"ID1",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tnon",
...}
</code>```

and that's an example between many others wrong parsing.
So that's why I want result that begins with "bon?" but not "bon souple" or "bon léger" because they have correct values, no \n or \t.

So as samples:

```<code>[{"_id":"ID1",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tnon"},
{"_id":"ID2",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tpremière"},
{"_id":"ID3",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t2ème"},
{"_id":"ID4",
"field":"bon souple"},
{"_id":"ID5",
"field":"bon léger"}]
</code>```

答:
Try using a string literal with a negative look ahead. The example below should work as long as you have a carriage return (\r) after 'bon'.</p>

```<code>import re
bon = re.compile(r'bon(?=\r)')
db.collection.find({'field': bon})
</code>```

Body:
I use python 3.7.1 (default, Dec 14 2018, 19:28:38), and pymongo 3.7.2.

In mongodb this works:

db.collection.find(
    {$and:[
    {"field":{$regex:"bon?"}},
    {"field":{$not:{$regex:"bon souple"}}},
    {"field":{$not:{$regex:"bon léger"}}}
    ]}
    )

So in pymongo I did the same as:

db.collection.find(
    {"$and":[
    {"field":{"$regex":"bon?"}},
    {"field":{"$not":{"$regex":"bon souple"}}},
    {"field":{"$not":{"$regex":"bon léger"}}}
    ]}
    )

but it indicatespymongo.errors.OperationFailure: $regex has to be a string.

So I tried this as proposed here:

liste_reg=[
{'field': {'$regex': {'$not': re.compile('bon souple')}}},
{'field': {'$regex': {'$not': re.compile('bon léger')}}},
{'field': {'$regex': re.compile('bon?')}}
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)

I noticed that even when there is no special character it indicates the same error:

liste_reg=[
{'field': {'$regex': {'$not': re.compile('bon souple')}}} #where no special char is present
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)

So I tried to use "/" as:

liste_reg=[
{'field': {'$regex': {'$not':'/bon souple/'}}} #where no special char is present
#even tried re.compile('/bon souple/')
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)

the same error pymongo.errors.OperationFailure: $regex has to be a string still occurs.

What can I do?

SOME UPDATE OF MY RESEARCH OF SOLUTION

the core of the issue seems to be with $not because when I do:

liste_reg=[{'field': {'$regex': 'bon?'}}]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
len(rslt)#gives 23 013, what is ok.

There is no error.

SOME SAMPLES

As asked by Emma I can give a sample, and it will explicit my request in mongo.
Normally I must have these modalities in the field:

sec

très léger

léger

bon léger

bon

bon souple

souple

très souple

collant

lourd

très Lourd

profond

The main problem for me is my spider did not parse correctly because I did not write a strong enough script for that.
Instead of obtaining just "bon", I obtain this kind of result:

{"_id":"ID1",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tnon",
...}

and that's an example between many others wrong parsing.
So that's why I want result that begins with "bon?" but not "bon souple" or "bon léger" because they have correct values, no \n or \t.

So as samples:

[{"_id":"ID1",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tnon"},
{"_id":"ID2",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tpremière"},
{"_id":"ID3",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t2ème"},
{"_id":"ID4",
"field":"bon souple"},
{"_id":"ID5",
"field":"bon léger"}]

Body:
Try using a string literal with a negative look ahead. The example below should work as long as you have a carriage return (\r) after 'bon'.

import re
bon = re.compile(r'bon(?=\r)')
db.collection.find({'field': bon})


问:
macOS: Keep XPC Service (bundled) running after user quits main app
The bundled XPC Service in my macOS application need to do some post processing work with files dumped by the parent app, which most probably can't be completed within the usage time of the application. So, Is there a way to make the XPC service keep running even after the user quits the main app?</p>

答:
It sounds like you should be using the WatchPaths or QueueDirectories feature of launchd.

WatchPaths starts the job whenever any of the paths being watched have changed

or

QueueDirectories  starts your job whenever the given directories are non-empty, and it keeps your job running as long as those directories are not empty

Both of these are covered by Apple's launchd documentation.


问:
Command failed due to signal: Abort trap: 6
Since Xcode 7 and Swift 2.0, I get the error above, like in the screenshot shown here:

I have no idea where this is coming from, cleaning and deleting derived data didn't work.

Anyone else experiencing this problem?

Project settings:

Target settings:

答: This issue is still present in Xcode 10.2.1. After cleaning the build folder, the error went away.


问:
Moving randomly svg objects using vanilla javascript
I want to move my svg objects randomly using vanilla javascript,
i make it to move element by adding value to cx by 10px but it likes it is jumping, is there any other way to move it smoothly, keyframes does not work. and javascript is used inside svg file, i need to achive effect like bouncing balls just with these elements
Effect like this one:
https://codepen.io/pintergabor/pen/DywHc

This should be used as background picture.

```<code><svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 500 500">
<defs>
    <style>
        .cls-1 {
            fill: url(#linear-gradient);
        }

        .cls-2 {
            fill: url(#linear-gradient-2);
        }

        .cls-3 {
            fill: url(#linear-gradient-3);
        }
        #circle{
            animate: circle 4s infinite linear;
        }
        @keyframes circle{
            to{
                transform: translate(55rem, 15px);
            }
        }
    </style>

    <linearGradient id="linear-gradient" x1="61.83" y1="217.56" x2="61.83" y2="256.64" gradientUnits="userSpaceOnUse">
        <stop offset="0" stop-color="#9dcb3b" />
        <stop offset="1" stop-color="#aa2d23" />
    </linearGradient>
    <linearGradient id="linear-gradient-2" x1="316.43" y1="64.69" x2="316.43" y2="98.31" xlink:href="#linear-gradient" />
    <linearGradient id="linear-gradient-3" x1="321.31" y1="319.11" x2="321.31" y2="396.98" xlink:href="#linear-gradient" />
</defs>
<title>elements</title>
<circle id="circle" class="cls-1" cx="61.83" cy="237.1" r="19.54" />
<polygon id="triangle" class="cls-2" points="316.43 64.69 297.01 98.31 335.84 98.31 316.43 64.69" />
<path id="plus" class="cls-3" d="M323.9,397h-5.18V319.11h5.18Zm36.35-36.35v-5.17H282.37v5.17Z" />
</code>```

答:
You can animate elements or classes like this:</p>

```<code>circle, my-class {
  animation: move 2s infinite alternate;
}

@keyframes move {
  0% {
    transform: translateX(50px);
  }
  100% {
    transform: translateX(0px);
  }
}
</code>```

Body:
I want to move my svg objects randomly using vanilla javascript,
i make it to move element by adding value to cx by 10px but it likes it is jumping, is there any other way to move it smoothly, keyframes does not work. and javascript is used inside svg file, i need to achive effect like bouncing balls just with these elements
Effect like this one:
https://codepen.io/pintergabor/pen/DywHc

This should be used as background picture.

<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 500 500">
<defs>

    <linearGradient id="linear-gradient" x1="61.83" y1="217.56" x2="61.83" y2="256.64" gradientUnits="userSpaceOnUse">
        <stop offset="0" stop-color="#9dcb3b" />
        <stop offset="1" stop-color="#aa2d23" />
    </linearGradient>
    <linearGradient id="linear-gradient-2" x1="316.43" y1="64.69" x2="316.43" y2="98.31" xlink:href="#linear-gradient" />
    <linearGradient id="linear-gradient-3" x1="321.31" y1="319.11" x2="321.31" y2="396.98" xlink:href="#linear-gradient" />
</defs>
<title>elements</title>
<circle id="circle" class="cls-1" cx="61.83" cy="237.1" r="19.54" />
<polygon id="triangle" class="cls-2" points="316.43 64.69 297.01 98.31 335.84 98.31 316.43 64.69" />
<path id="plus" class="cls-3" d="M323.9,397h-5.18V319.11h5.18Zm36.35-36.35v-5.17H282.37v5.17Z" />

Body:
You can animate elements or classes like this:

circle, my-class {
  animation: move 2s infinite alternate;
}

@keyframes move {
  0% {
    transform: translateX(50px);
  }
  100% {
    transform: translateX(0px);
  }
}


问:
Error when searching for string containing &
I am using a linq query to get a list of objects that contain a variable string:

```<code>   string str = FilterAllSource;
                if (!string.IsNullOrEmpty(str))
                {
                    ss = ss.Where(it => (it.SourceCode.ToUpper()
                                               .Contains(str.ToUpper())
                                         || it.SourceName.ToUpper()
                                               .Contains(str.ToUpper())));
                }

                if (top > 0)
                    ss = ss.Take(top);

                return ss.ToList();
</code>```

when FilterAllsource contains a & (e.g m & m) it throws an exception

Unterminated string literal at position 38 in '(ResourceId eq 3) and (substringof('M '.

my guess is that the & interferes with some internal concatenation process. Is there a way to avoid this without removing the & from the query string?

EDIT1: ss is a list of objects List where SourceCode and Sourcename are both strings

答:
This works for me...</p>

```<code>class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        List<Test> list = p.GetList();
    }

    public List<Test> GetList()
    {
        List<Test> ss = new List<Test>();
        ss.Add(new Test("m & mm & mm & mm & mm & mm & mm & m", "m & mm & mm & mm & mm & mm & mm & m"));
        string str = "m & m";

        if (!string.IsNullOrEmpty(str))
        {
            ss = ss.Where(it => (it.SourceCode.ToUpper().Contains(str.ToUpper()) || it.SourceName.ToUpper().Contains(str.ToUpper()))).ToList();
        }

        //if (top > 0)
        //{
        //    ss = ss.Take(top);
        //}

        return ss.ToList();
    }
}

public class Test
{
    public Test(string sourceCode, string sourceName)
    {
        this.SourceCode = sourceCode;
    }

    public string SourceCode
    {
        get;
        set;
    }

    public string SourceName
    {
        get;
        set;
    }
}
</code>```

Body:
I am using a linq query to get a list of objects that contain a variable string:

   string str = FilterAllSource;
                if (!string.IsNullOrEmpty(str))
                {
                    ss = ss.Where(it => (it.SourceCode.ToUpper()
                                               .Contains(str.ToUpper())
                                         || it.SourceName.ToUpper()
                                               .Contains(str.ToUpper())));
                }

                if (top > 0)
                    ss = ss.Take(top);

                return ss.ToList();

when FilterAllsource contains a & (e.g m & m) it throws an exception

Unterminated string literal at position 38 in '(ResourceId eq 3) and (substringof('M '.

my guess is that the & interferes with some internal concatenation process. Is there a way to avoid this without removing the & from the query string?

EDIT1: ss is a list of objects List where SourceCode and Sourcename are both strings

Body:
This works for me...

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        List<Test> list = p.GetList();
    }

    public List<Test> GetList()
    {
        List<Test> ss = new List<Test>();
        ss.Add(new Test("m & mm & mm & mm & mm & mm & mm & m", "m & mm & mm & mm & mm & mm & mm & m"));
        string str = "m & m";

        if (!string.IsNullOrEmpty(str))
        {
            ss = ss.Where(it => (it.SourceCode.ToUpper().Contains(str.ToUpper()) || it.SourceName.ToUpper().Contains(str.ToUpper()))).ToList();
        }

        //if (top > 0)
        //{
        //    ss = ss.Take(top);
        //}

        return ss.ToList();
    }
}

public class Test
{
    public Test(string sourceCode, string sourceName)
    {
        this.SourceCode = sourceCode;
    }

    public string SourceCode
    {
        get;
        set;
    }

    public string SourceName
    {
        get;
        set;
    }
}


问:
Why am I unable to access props from vue root inside components template?
I am trying to access job_execs from the stage-execs component in the template...

job_execs is created in the vue root and I am trying to access it by calling it in the props of the stage-execs component.

```<code><div id="vue-job">
<div class="column">
    <div class="row">
        <h3>test</h3>
        <stage-execs></stage-execs>
    <br><br>
</div>
</div>

<script>
    Vue.component('stage-execs', {
        delimiters: [ '[[', ']]' ],
        props: ['job_execs'],
        data: function() {
                return {
                    job_execs: job_execs
                }
            },
        template: `
        <ul id="example-1">
          <li v-for="item in job_execs">
            [[ item.build_id ]]
          </li>
        </ul>
        `,
    });

    var v_root = new Vue({
        delimiters: [ '[[', ']]' ],
        el: '#vue-job',
        data: {
            job_execs: []
        },
        created() {
            url="http://{{ api_endpoint }}"
            fetch(url)
                .then(response => response.json())
                .then(body => {
                    for(i=0; i<body.length; i++){
                        this.job_execs.push({
                            'build_id': JSON.stringify(body[i].build_id),
                            'status': JSON.stringify(body[i].status.name),
                        })
                    }
            })
            .catch( err => {
                console.log('Error Fetching:', url, err);
                return { 'failure': url, 'reason': err };
            });

        },
    });
</code>```

What is the correct way here to access job_execs in the stage-execs component?

答:
remove this part:

```<code>data: function() {
     return {
         job_execs: job_execs
     }
}
</code>```

and update the template with:

```<code><ul id="example-1">
    <li v-for="item in this.job_execs">
        {{ item.build_id }}
    </li>
</ul>
</code>```

Body:
I am trying to access job_execs from the stage-execs component in the template...

job_execs is created in the vue root and I am trying to access it by calling it in the props of the stage-execs component.

test

        <stage-execs></stage-execs>

Body:
remove this part:

data: function() {
     return {
         job_execs: job_execs
     }
}

and update the template with:

<ul id="example-1">
    <li v-for="item in this.job_execs">
        {{ item.build_id }}
    </li>
</ul>


问:
How would I return all null values from a left join?
I am trying to left join two tables (A and B) together and would like to return all values that have a column in table B marked as null in mySQL.

The two tables I am joining are both very large and I am running into an issue where my connection will timeout after 6000 seconds due to the DBMS settings; is there a way to make this query run more efficiently?

Another bit of information: Even if I limit the query to 10 rows, it will still timeout and give me the error code listed below.

```<code>select *
from Table_A a
left join Table_B b
on a.field_X = b.field_X
where b.Field_X is null;
</code>```

I am experiencing the following error code: "Error Code 2013. Lost Connection to MySQL server during query."

Side note: I am a new SQL user and may need to ask for clarification on some answers. Thank you in advance!

答:
Maybe something like this will work for you:</p>

```<code>    select * from table_A a where a.field_X not in (select field_x from table_B);
</code>```

Body:
I am trying to left join two tables (A and B) together and would like to return all values that have a column in table B marked as null in mySQL.

The two tables I am joining are both very large and I am running into an issue where my connection will timeout after 6000 seconds due to the DBMS settings; is there a way to make this query run more efficiently?

Another bit of information: Even if I limit the query to 10 rows, it will still timeout and give me the error code listed below.

select *
from Table_A a
left join Table_B b
on a.field_X = b.field_X
where b.Field_X is null;

I am experiencing the following error code: "Error Code 2013. Lost Connection to MySQL server during query."

Side note: I am a new SQL user and may need to ask for clarification on some answers. Thank you in advance!

Body:
Maybe something like this will work for you:

    select * from table_A a where a.field_X not in (select field_x from table_B);


问:
Generate a list with a head based on object property in array
In Vue, i'm trying to generate a list based on a property in an object.
I have an array coming from the vuex store that looks like this:

```<code>const array = [
 {
   name: "British title string"
   nationality: "British"
 },
 {
   name: "Another title"
   nationality: "American"
 },
 {
   name: "Name"
   nationality: "Dutch"
 },
{
   name: "Another american item"
   nationality: "American"
 },
];

</code>```

What i want to have is the output like this using v-for:

```<code><h2>British</h2>
<ul>
   <li>British title string</li>
</ul>

<h2>American</h2>
<ul>
   <li>Another title</li>
   <li>Another american item</li>
</ul>

<h2>Dutch</h2>
<ul>
   <li>Name</li>
</ul>
</code>```

I have already sorted the array by the nationality property using lodash _.sortBy and it's given me an array sorted by nationality but i want to add a H2 element with the value of nationality.

答:
If you have multiple items with same nationality and you want to group them up, use _.groupBy() before _.sortBy():

Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
  el: '#app',
  template: '#appTemplate',
  data: () => ({
    rawData: [{
        name: "British title string",
        nationality: "British"
      },
      {
        name: "Another title",
        nationality: "American"
      },
      {
        name: "Name",
        nationality: "Dutch"
      },
      {
        name: "Another american item",
        nationality: "American"
      }
    ]
  }),
  computed: {
    groupedItems() {
      return _.sortBy(
        _.map(
          _.groupBy(this.rawData, 'nationality'),
          items => ({
            items,
            nationality: items[0].nationality
          })
        ),
        ['nationality']
      );
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<script type="text/template" id="appTemplate">
  <div>
    <template v-for="group in groupedItems">
      <h2 v-text="group.nationality" />
      <ul>
        <li v-for="(item, index) in group.items" :key="index" v-text="item.name" />
      </ul>
    </template>
  </div>
</script>
<div id="app"></div></code>```

For convenience and data readability, I mapped first item's nationality as the group's nationality (and named the grouped items items), but you could have used item 0's nationality in the template directly, instead.

To demonstrate, here's how that would have looked like:

Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
  el: '#app',
  template: '#appTemplate',
  data: () => ({
    rawData: [{
        name: "British title string",
        nationality: "British"
      },
      {
        name: "Another title",
        nationality: "American"
      },
      {
        name: "Name",
        nationality: "Dutch"
      },
      {
        name: "Another american item",
        nationality: "American"
      }
    ]
  }),
  computed: {
    groupedItems() {
      return _.sortBy(
        _.groupBy(this.rawData, 'nationality'),
        ['0.nationality']
      );
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<script type="text/template" id="appTemplate">
  <div>
    <template v-for="grouped in groupedItems">
      <h2 v-text="grouped[0].nationality" />
      <ul>
        <li v-for="(item, index) in grouped" :key="index" v-text="item.name" />
      </ul>
    </template>
  </div>
</script>
<div id="app"></div></code>```

Note both of the above examples output the required markup. If you want each item to have its own wrapper, replace <template> with an html tag and add keys. i.e:

```<code><article v-for="(grouped, key) in groupedItems" :key="key">
</code>```

Body:
In Vue, i'm trying to generate a list based on a property in an object.
I have an array coming from the vuex store that looks like this:

const array = [
 {
   name: "British title string"
   nationality: "British"
 },
 {
   name: "Another title"
   nationality: "American"
 },
 {
   name: "Name"
   nationality: "Dutch"
 },
{
   name: "Another american item"
   nationality: "American"
 },
];

What i want to have is the output like this using v-for:

British

British title string

American

Another title

Another american item

Dutch

Name

I have already sorted the array by the nationality property using lodash _.sortBy and it's given me an array sorted by nationality but i want to add a H2 element with the value of nationality.

Body:
If you have multiple items with same nationality and you want to group them up, use _.groupBy() before _.sortBy():

Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
  el: '#app',
  template: '#appTemplate',
  data: () => ({
    rawData: [{
        name: "British title string",
        nationality: "British"
      },
      {
        name: "Another title",
        nationality: "American"
      },
      {
        name: "Name",
        nationality: "Dutch"
      },
      {
        name: "Another american item",
        nationality: "American"
      }
    ]
  }),
  computed: {
    groupedItems() {
      return _.sortBy(
        _.map(
          _.groupBy(this.rawData, 'nationality'),
          items => ({
            items,
            nationality: items[0].nationality
          })
        ),
        ['nationality']
      );
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<script type="text/template" id="appTemplate">
  <div>
    <template v-for="group in groupedItems">
      <h2 v-text="group.nationality" />
      <ul>
        <li v-for="(item, index) in group.items" :key="index" v-text="item.name" />
      </ul>
    </template>
  </div>
</script>
<div id="app"></div>

For convenience and data readability, I mapped first item's nationality as the group's nationality (and named the grouped items items), but you could have used item 0's nationality in the template directly, instead.

To demonstrate, here's how that would have looked like:

Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
  el: '#app',
  template: '#appTemplate',
  data: () => ({
    rawData: [{
        name: "British title string",
        nationality: "British"
      },
      {
        name: "Another title",
        nationality: "American"
      },
      {
        name: "Name",
        nationality: "Dutch"
      },
      {
        name: "Another american item",
        nationality: "American"
      }
    ]
  }),
  computed: {
    groupedItems() {
      return _.sortBy(
        _.groupBy(this.rawData, 'nationality'),
        ['0.nationality']
      );
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<script type="text/template" id="appTemplate">
  <div>
    <template v-for="grouped in groupedItems">
      <h2 v-text="grouped[0].nationality" />
      <ul>
        <li v-for="(item, index) in grouped" :key="index" v-text="item.name" />
      </ul>
    </template>
  </div>
</script>
<div id="app"></div>

Note both of the above examples output the required markup. If you want each item to have its own wrapper, replace <template> with an html tag and add keys. i.e:

<article v-for="(grouped, key) in groupedItems" :key="key">


问:
PHP 7.3 (CPanel) update results in 500 server error
When I upgrade my server from PHP 7.2 to PHP 7.3 I get a server error 500.

I'm using the same packages as I did with 7.2 (and none have been deprecated). My error logs aren't very helpful as they don't provide any inclination of the problem (or anything else, a problem for another day).

I've never had any issues updating my PHP version so I'm not sure why I'm having issues now.

I use htaccess but I can't think why my htaccess file will work with 7.2 and not 7.3. All I get is a 500 Server Error, no additional information.

Does anyone have any ideas? I would be very grateful!

答:
Does index.php ONLY containing the following and still has a 500?

```<code><?php
 phpinfo();
?>
</code>```

If so make sure you've disabled the old php 7.2 and enable 7.3

```<code> sudo a2dismod php7.2
 sudo a2enmod php7.3
</code>```

this assumes you use apache

Body:
Does index.php ONLY containing the following and still has a 500?

<?php
 phpinfo();
?>

If so make sure you've disabled the old php 7.2 and enable 7.3

 sudo a2dismod php7.2
 sudo a2enmod php7.3

this assumes you use apache


问:
How to provide a python argparse.parser with arguments from inside the code, without command-line arguments?
I have a code that takes the command-line arguments into a parser and modifies some configuration settings. Something like this:

command:

```<code>python mycode.py --config-file "some_file.yaml" SOMETHING.subsetting_a 2 SOMETHING.subsetting_b 3
</code>```

and then it does:

```<code>import argparse
parser = argparse.ArgumentParser(description="Some description here")
parser.add_argument(
    "--config-file",
    default="",
    metavar="FILE",
    help="path to config file",
    type=str,
)
//some more 'add_argument' lines here
args = parser.parse_args()
</code>```

But as I am using jupyter notebook, it would be easier to provide the arguments directly to the parser, as if they come from the command-line. How can I create a string containing the command (as mentioned above) and pass it to parser?

答:
Note: As @ShadowRanger mentioned, there is no need to use sys.argv. See his response.

One way is to use sys.argv to mimic the command-line arguments:

```<code>import sys

sys.argv = [
    "--config-file" , "some_file.yaml",
    "SOMETHING.subsetting_a" , "2",
    "SOMETHING.subsetting_b" , "3"]

args = parser.parse_args(sys.argv)
</code>```

The content of args is something liek this:

```<code>> Namespace(config_file='some_file.yaml', opts=['SOMETHING.subsetting_a', '2', 'SOMETHING.subsetting_b', '3')
</code>```

which is similar to the output of print(parser.parse_args()).

Body:
I have a code that takes the command-line arguments into a parser and modifies some configuration settings. Something like this:

command:

python mycode.py --config-file "some_file.yaml" SOMETHING.subsetting_a 2 SOMETHING.subsetting_b 3

and then it does:

import argparse
parser = argparse.ArgumentParser(description="Some description here")
parser.add_argument(
    "--config-file",
    default="",
    metavar="FILE",
    help="path to config file",
    type=str,
)
//some more 'add_argument' lines here
args = parser.parse_args()

But as I am using jupyter notebook, it would be easier to provide the arguments directly to the parser, as if they come from the command-line. How can I create a string containing the command (as mentioned above) and pass it to parser?

Body:
Note: As @ShadowRanger mentioned, there is no need to use sys.argv. See his response.

One way is to use sys.argv to mimic the command-line arguments:

import sys

sys.argv = [
    "--config-file" , "some_file.yaml",
    "SOMETHING.subsetting_a" , "2",
    "SOMETHING.subsetting_b" , "3"]

args = parser.parse_args(sys.argv)

The content of args is something liek this:

> Namespace(config_file='some_file.yaml', opts=['SOMETHING.subsetting_a', '2', 'SOMETHING.subsetting_b', '3')

which is similar to the output of print(parser.parse_args()).


问:
laravel prevent go back after order placed in ecommerce
How to prevent Laravel page from going back after order placed to not make a double payment. I've got many related answers but none of them work with me.

I've tried makeing a middleware class and call header code

and called it from route file

return $response->header('Cache-Control','no-store, nocache, no-store, max-age=0, must-revalidate')
->header('Pragma','no-cache')
->header('Expires','Sun, 02 Jan 1990 00:00:00 GMT')
->header('Cache-Control',' post-check=0, pre-check=0, false');
```

<p>and then I've called the class in route like this:</p>

<pre class="lang-php prettyprint-override"><code>Route::group(['middleware' => 'prevent-order-back'],function(){
        Auth::routes();
        //Route::get('/home', 'HomeController@index');
        Route::post('/place_order', 'OrdersController@place_order');
    });
</code>```

I'm using Laravel 5.5

答:
I did some more searching (stripe api) and found that you could use something callend an idempotent request to fix the double payment issue. I've found a laravel library which handles this through middleware.

It's basically sending an (user)unique key and stores the response in cache, the browser wil send the cached reponse if the same (user)unique key is used in the following 24 hours.

Body:
How to prevent Laravel page from going back after order placed to not make a double payment. I've got many related answers but none of them work with me.

I've tried makeing a middleware class and call header code

and called it from route file

return $response->header('Cache-Control','no-store, nocache, no-store, max-age=0, must-revalidate')
->header('Pragma','no-cache')
->header('Expires','Sun, 02 Jan 1990 00:00:00 GMT')
->header('Cache-Control',' post-check=0, pre-check=0, false');

and then I've called the class in route like this:

Route::group(['middleware' => 'prevent-order-back'],function(){
        Auth::routes();
        //Route::get('/home', 'HomeController@index');
        Route::post('/place_order', 'OrdersController@place_order');
    });

I'm using Laravel 5.5


问:
Websocket send image file by Javascript client
I'm writing a simple application in which a javascript web socket client has to send image to a webscoket implemented by tomcat and Java language.
when I send a string message every thing is going well but @Onmessage event don't be fired if I send an image data. I've spent 2 days but haven't the solution yet.

Java WebSocket Code:

```<code>@ServerEndpoint("/sendfile")
public class BinaryWebSocketServer {
    private
    static final Set<Session> sessions =
    Collections.synchronizedSet(new HashSet<Session>());

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        System.out.println("onOpen_File::" + session.getId());
    }
    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
        System.out.println("onClose_File::" +  session.getId());
    }

    @OnMessage
    public void onMessage(byte[] data, Session session) {
        System.out.println("onByteArrayMessage::From=" + session.getId() + " with len:" + data.length );
        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        BufferedImage bImage2;
        try {
            bImage2 = ImageIO.read(bis);
             ImageIO.write(bImage2, "jpg", new File("output.jpg") );
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        System.out.println("image created");

    }

    @OnError
    public void onError(Throwable t) {
        System.out.println("onError::" + t.getMessage());
    }

}
</code>```

Javascript Client:

```<code><body>
    <h2>File Upload</h2>   Select file

    <input type="file" id="filename" />

    <br>

    <input type="button" value="Connect" onclick="connectChatServer()" />

    <br>

    <input type="button" value="Upload" onclick="sendFile()" />
     <input onclick="wsCloseConnection();" value="Disconnect" type="button">
    <br />
    <textarea id="echoText" rows="5" cols="30"></textarea>
    <script>

    var webSocket = new WebSocket("ws://192.168.1.55:8081/Hello-Capture/sendfile");
    webSocket.binaryType = 'arraybuffer';
    webSocket.onopen = function(message){ wsOpen(message);};
    //webSocket.onmessage = function(message){ wsGetMessage(message);};
    webSocket.onclose = function(message){ wsClose(message);};
    webSocket.onerror = function(message){ wsError(message);};
    function wsOpen(message){
        echoText.value += "Connected ... \n";
    }
    function wsSendMessage(){
        webSocket.send(message.value);
        echoText.value += "Message sended to the server : " + message.value + "\n";
        message.value = "";
    }
    function wsCloseConnection(){
        webSocket.close();
    }
    function wsGetMessage(message){
        echoText.value += "Message received from to the server : " + message.data + "\n";
    }
    function wsClose(message){
        echoText.value += "Disconnect ... \n";
    }

    function wsError(message){
        echoText.value += "Error ..." + message.code +" \n";
    }

        function sendFile() {

            var file = document.getElementById('filename').files[0];

            var reader = new FileReader();

            var rawData = new ArrayBuffer();

            reader.loadend = function(e) {

            };

            reader.onload = function(e) {

                var rawData = e.target.result;
                var byteArray = new Uint8Array(rawData);
                var fileByteArray = [];

                webSocket.send(byteArray.buffer);

                echoText.value =("the File has been transferred.\n");

            };

            reader.readAsArrayBuffer(file);

        }

    </script>

</body>
</code>```

答:
Finally I find the solution so I comment it maybe some one else gets stuck into.
I've forgotten to pass a boolean parameter to onMessage function.
the correct form is :</p>

```<code> @OnMessage
public void onMessage(byte[] data,boolean last, Session session) {
    .
    .
    .
 }
</code>```

Body:
I'm writing a simple application in which a javascript web socket client has to send image to a webscoket implemented by tomcat and Java language.
when I send a string message every thing is going well but @Onmessage event don't be fired if I send an image data. I've spent 2 days but haven't the solution yet.

Java WebSocket Code:

@ServerEndpoint("/sendfile")
public class BinaryWebSocketServer {
    private
    static final Set<Session> sessions =
    Collections.synchronizedSet(new HashSet<Session>());

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        System.out.println("onOpen_File::" + session.getId());
    }
    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
        System.out.println("onClose_File::" +  session.getId());
    }

    @OnMessage
    public void onMessage(byte[] data, Session session) {
        System.out.println("onByteArrayMessage::From=" + session.getId() + " with len:" + data.length );
        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        BufferedImage bImage2;
        try {
            bImage2 = ImageIO.read(bis);
             ImageIO.write(bImage2, "jpg", new File("output.jpg") );
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        System.out.println("image created");

    }

    @OnError
    public void onError(Throwable t) {
        System.out.println("onError::" + t.getMessage());
    }

}

Javascript Client:

File Upload
   Select file

    <input type="file" id="filename" />

    <input type="button" value="Connect" onclick="connectChatServer()" />

    <input type="button" value="Upload" onclick="sendFile()" />
     <input onclick="wsCloseConnection();" value="Disconnect" type="button">

    <textarea id="echoText" rows="5" cols="30"></textarea>

Body:
Finally I find the solution so I comment it maybe some one else gets stuck into.
I've forgotten to pass a boolean parameter to onMessage function.
the correct form is :

 @OnMessage
public void onMessage(byte[] data,boolean last, Session session) {
    .
    .
    .
 }


问:
Value of type 'AnimationView?' has no member 'setAnimation'
I am trying to add an animation to my application using Lottie but I get this error and I still do not know how to solve it.

```<code>import UIKit
import Lottie

class ViewController: UIViewController {
    @IBOutlet var animationView: AnimationView!

    override func viewDidLoad() {
        super.viewDidLoad()
        startAnimation()
    }

    func startAnimation(){
        animationView.setAnimation(named: "data")//error1
        animationView.loopAnimation = true//error2
        animationView.play()
    }
}
</code>```

The error that comes out:

Value of type 'AnimationView?' has no member 'setAnimation'

Value of type 'AnimationView?' has no member 'loopAnimation'

答:
it seems you are new in swift.

this happen because the class AnimationView does not have function named setAnimation(named:) or variable named loopAnimation, you need to declare them inside  AnimationView class

Body:
I am trying to add an animation to my application using Lottie but I get this error and I still do not know how to solve it.

import UIKit
import Lottie

class ViewController: UIViewController {
    @IBOutlet var animationView: AnimationView!

    override func viewDidLoad() {
        super.viewDidLoad()
        startAnimation()
    }

    func startAnimation(){
        animationView.setAnimation(named: "data")//error1
        animationView.loopAnimation = true//error2
        animationView.play()
    }
}

The error that comes out:

Value of type 'AnimationView?' has no member 'setAnimation'

Value of type 'AnimationView?' has no member 'loopAnimation'


问:
What are the directory locations that are writable on iOS?
I was not able to find on Apple iOS SDK information regarding which directories are writable and which are not for your application.

I only assume that NSCachesDirectory and NSDocumentDirectory are writable but how about others, like NSApplicationSupportDirectory or NSTemporaryDirectory.

Where can I find a complete list of common directories with their purpose and if they are writable or not by my application?

I was able to locate possible values for NSSearchPathDirectory enum but they do not contain any information regarding their purpose and more important if you are able to write to them.

答:
Have a look in the "iOS Application Programming Guide" > The Application Runtime Environment > The File System > A Few Important Application Directories.

There are several useful links on the same page to methods that will help or to further FS related documentation.


问:
Azure Resource Manager - Cannot deploy Keyvault with Microsoft App Service in access policy
So I'm trying to codify all my Azure infrastructure using Azure Devops Pipelines and ARM templates. It's pretty tough going but I can see the benefit when a deployment delivers me 20 resources in 5 minutes which are all good-to-go!

However, I have hit a problem. I want to deploy a new Keyvault. Tick, easy! I want to store a x509 certificate which is a wildcard cert used by my Web Apps.  Tick easily done. Now I want to create a "Microsoft.Web/Certificates" certificates resources which I can then use to create an SSL custom binding for my Web Apps. This fails:

```<code>"The service does not have access to '...microsoft.keyvault/vaults/gs-prd1-kv-apps' Key Vault.
</code>```

This is reasonably well documented in the sample template here: https://github.com/Azure/azure-quickstart-templates/tree/master/201-web-app-certificate-from-key-vault.  It turns out that the **Microsoft.Azure.Websites" resource provider does not have access to the Keyvault. To get around this the guidance is to run a powershell or az cli command to add the RP to my new Keyvault

```<code>Set-AzureRmKeyVaultAccessPolicy -VaultName KEY_VAULT_NAME -ServicePrincipalName abfa0a7c-a6b6-4736-8310-5855508787cd -PermissionsToSecrets get
</code>```

Problem is, I need to do this in the Devops pipeline or ARM template and I have absolutely no idea how.

I have tried to add the az command into a new build task, but the service principle which is running the pipeline ALSO does not have the correct permissions to add it in.

Can anyone help? There MUST be a way of deploying a Keyvault with x509 cert and assigning this resource to a Web App?

答:
I thought I would share my now working solution to this issue.  So lets clarify what we want to deploy within the ARM template:

A new KeyVault (Microsoft.KeyVault/vaults) which has an x509 certificate stored as a secret in pkcs12 format

A new App Service Plan (Microsoft.Web/serverfarms)

A new web certificate (Microsoft.Web/certificates )in the App Service Plan which can be used to define a custom domain name with HTTPS. This is the x509 certificate which has been placed in the new KeyVault

This would all work fine except that the resource provider used to create the App Service Plan does not have an access policy for the new Keyvault and cannot, therefore, extract the x509 cert. This is documented in the sample template referenced in the question. The guidance is to run a command to add an access policy for the resource provider. However, as I state in the question, we are trying to do this entirely within the ARM template.

The solution is to define the access policy for the resource provider within the ARM template. However, there are two problems:

I'm not sure which resource provider to use

I have no idea how to get the ObjectId of the service principal used by this resource provider

I took a hint from this SO question and did the following.

1. Create new Keyvault and add the x509 certificate to it as a secret

2. Run an az CLI command to get service principal for the "Microsoft Azure App Service"

```<code>az ad sp list --display-name "Microsoft Azure App Service"
</code>```

This displays a lot of properties for the service, including the [objectId] which I can copy for use in the ARM template

3. Create a Keyvault Access Policy resource in the ARM template for the "Microsoft Azure App Service" service principal - using the [objectId] above. Grant this principal "Get" permissions for secrets only.

4. Create App Service Plan and a new Web certificate resource for it

Now when I run the template which the Microsoft Azure App Service principal has permission to retrieve the x509 cert from the new Keyvault and create a web certificate resource in the service plan.

Body:
So I'm trying to codify all my Azure infrastructure using Azure Devops Pipelines and ARM templates. It's pretty tough going but I can see the benefit when a deployment delivers me 20 resources in 5 minutes which are all good-to-go!

However, I have hit a problem. I want to deploy a new Keyvault. Tick, easy! I want to store a x509 certificate which is a wildcard cert used by my Web Apps.  Tick easily done. Now I want to create a "Microsoft.Web/Certificates" certificates resources which I can then use to create an SSL custom binding for my Web Apps. This fails:

"The service does not have access to '...microsoft.keyvault/vaults/gs-prd1-kv-apps' Key Vault.

This is reasonably well documented in the sample template here: https://github.com/Azure/azure-quickstart-templates/tree/master/201-web-app-certificate-from-key-vault.  It turns out that the **Microsoft.Azure.Websites" resource provider does not have access to the Keyvault. To get around this the guidance is to run a powershell or az cli command to add the RP to my new Keyvault

Set-AzureRmKeyVaultAccessPolicy -VaultName KEY_VAULT_NAME -ServicePrincipalName abfa0a7c-a6b6-4736-8310-5855508787cd -PermissionsToSecrets get

Problem is, I need to do this in the Devops pipeline or ARM template and I have absolutely no idea how.

I have tried to add the az command into a new build task, but the service principle which is running the pipeline ALSO does not have the correct permissions to add it in.

Can anyone help? There MUST be a way of deploying a Keyvault with x509 cert and assigning this resource to a Web App?

Body:
I thought I would share my now working solution to this issue.  So lets clarify what we want to deploy within the ARM template:

A new KeyVault (Microsoft.KeyVault/vaults) which has an x509 certificate stored as a secret in pkcs12 format

A new App Service Plan (Microsoft.Web/serverfarms)

A new web certificate (Microsoft.Web/certificates )in the App Service Plan which can be used to define a custom domain name with HTTPS. This is the x509 certificate which has been placed in the new KeyVault

This would all work fine except that the resource provider used to create the App Service Plan does not have an access policy for the new Keyvault and cannot, therefore, extract the x509 cert. This is documented in the sample template referenced in the question. The guidance is to run a command to add an access policy for the resource provider. However, as I state in the question, we are trying to do this entirely within the ARM template.

The solution is to define the access policy for the resource provider within the ARM template. However, there are two problems:

I'm not sure which resource provider to use

I have no idea how to get the ObjectId of the service principal used by this resource provider

I took a hint from this SO question and did the following.

1. Create new Keyvault and add the x509 certificate to it as a secret

2. Run an az CLI command to get service principal for the "Microsoft Azure App Service"

az ad sp list --display-name "Microsoft Azure App Service"

This displays a lot of properties for the service, including the [objectId] which I can copy for use in the ARM template

3. Create a Keyvault Access Policy resource in the ARM template for the "Microsoft Azure App Service" service principal - using the [objectId] above. Grant this principal "Get" permissions for secrets only.

4. Create App Service Plan and a new Web certificate resource for it

Now when I run the template which the Microsoft Azure App Service principal has permission to retrieve the x509 cert from the new Keyvault and create a web certificate resource in the service plan.


问:
Non-existent foreign key doesn't cause error in SQLite
The following code should IMO produce an error because the user_id=1 doesn't exist. Why does it work?

```<code>CREATE TABLE users (
user_id int PRIMARY KEY,
email text UNIQUE
);

CREATE TABLE claimed (
account_id int PRIMARY KEY,
user_id int,
domain text,
FOREIGN KEY (user_id) REFERENCES users (user_id)
);

INSERT INTO claimed
(user_id, domain)
VALUES (1, "abcd");
</code>```

答:
From the relevant documentation:

In order to use foreign key constraints in SQLite, the library must be compiled with neither SQLITE_OMIT_FOREIGN_KEY or SQLITE_OMIT_TRIGGER defined. If SQLITE_OMIT_TRIGGER is defined but SQLITE_OMIT_FOREIGN_KEY is not, then SQLite behaves as it did prior to version 3.6.19 (2009-10-14) - foreign key definitions are parsed and may be queried using PRAGMA foreign_key_list, but foreign key constraints are not enforced.

and:

Foreign key constraints are disabled by default (for backwards compatibility), so must be enabled separately for each database connection.

and:

Assuming the library is compiled with foreign key constraints enabled, it must still be enabled by the application at runtime, using the PRAGMA foreign_keys command. For example:

sqlite> PRAGMA foreign_keys = ON;

Apparently you should use PRAGMA foreign_keys = ON at the top of your connection, and potentially rebuild with the appropriate options (though if you installed from package then I would personally assume that this has been done).

Source: Google sqlite foreign key, first result

Body:
The following code should IMO produce an error because the user_id=1 doesn't exist. Why does it work?

CREATE TABLE users (
user_id int PRIMARY KEY,
email text UNIQUE
);

CREATE TABLE claimed (
account_id int PRIMARY KEY,
user_id int,
domain text,
FOREIGN KEY (user_id) REFERENCES users (user_id)
);

INSERT INTO claimed
(user_id, domain)
VALUES (1, "abcd");


问:
Centering featured image in Wordpress
I would like to center Wordpress featured image on my site: https://link.do/ibXD8

I cannot find suitable option in theme properties.

答:
https://wordpress.org/support/topic/center-featured-imagine/
Add below css code it may fix your problem .

.attachment-post-thumbnail {
  margin: 0 auto;
}

 ```
</div>
</div>
</p>

<p>or  </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>. image {
    text-align: center;
}</code>```

Title: Centering featured image in Wordpress

Body:
https://wordpress.org/support/topic/center-featured-imagine/
Add below css code it may fix your problem .

.attachment-post-thumbnail {
  margin: 0 auto;
}

or

. image {
    text-align: center;
}


问:
Is it possible to Decompile and read an SSIS package code?
I am working on a project which was owned by a different person. He created a job to update bunch of fields in handful of tables in SQL server. That job was based on an SSIS package. Now I have the DTSX file and the disabled job. When I tried to enable the job after changing the old credentials in the DTSX file, I am getting weird errors. I want to see the code behind the SSIS package and want to see how the update process is coded.
Is there a way to do this?</p>

答:
I want to see the code behind the SSIS package and want to see how the update process is coded

As other answers mentioned, dtsx files are XML files, you can simply open these files using a text editor to check the code behind, or you can simply create a new Integration Services project using visual studio and add the package to check it's control flow.

Integration Services (SSIS) Projects and Solutions

I added my own answer to list some of what i posted related to this issue, since it may give you some insights:

Automate Version number Retrieval from .Dtsx files

Reverse engineering SSIS package using C#

Is there a way to save all queries present in a ssis package/dtsx file?

Parse SSIS package

Loading SSIS Package Programmatically in C#


问:
Passing Arraylist between activities? Using Parcelable
EDIT: I've updated my question considerably and am now going with Parcelable as my method.

I'm attempting to a pass an ArrayList from one activity to another. I've been reading around and can't seem to find any answers to my problem.

I've got an ArrayList<SearchList> which implements Parcelable SearchList has the following code...

```<code>  public class SearchList implements Parcelable {
private String title;
  private String description;
  private String link;
  public SearchList(String name, String phone, String mail) {
          super();
          this.title = name;
          this.description = phone;
          this.link = mail;
  }
  public SearchList(Parcel source){
      /*
       * Reconstruct from the Parcel
       */
      title = source.readString();
      description = source.readString();
      link = source.readString();
}
  public String gettitle() {
          return title;
  }
  public void setTitle(String title) {
          this.title = title;
  }
  public String getDescription() {
          return description;
  }
  public void setDescription(String description) {
          this.description = description;
  }
  public String getLink() {
          return link;
  }
  public void setLink(String link) {
          this.link = link;
  }

public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

public void writeToParcel(Parcel dest, int flags) {
      dest.writeString(title);
      dest.writeString(description);
      dest.writeString(link);

}

 public static final Creator<SearchList> CREATOR = new Creator<SearchList>() {
        public SearchList createFromParcel(Parcel source) {
            return new SearchList(source);
        }
        public SearchList[] newArray(int size) {
            return new SearchList[size];
        }
    };
  }
</code>```

However, when I try and do...

```<code> List<SearchList> listOfResults = new ArrayList<SearchList>();
 intent.putParcelableArrayListExtra("results", listOfResults);
</code>```

I get not applicable for type (String, List<SearchList> why?

答: You can use SQLite as alternative. To pass data from one Activity to another. Here the link.</p>

Body:
EDIT: I've updated my question considerably and am now going with Parcelable as my method.

I'm attempting to a pass an ArrayList from one activity to another. I've been reading around and can't seem to find any answers to my problem.

I've got an ArrayList<SearchList> which implements Parcelable SearchList has the following code...

  public class SearchList implements Parcelable {
private String title;
  private String description;
  private String link;
  public SearchList(String name, String phone, String mail) {
          super();
          this.title = name;
          this.description = phone;
          this.link = mail;
  }
  public SearchList(Parcel source){
      /*
       * Reconstruct from the Parcel
       */
      title = source.readString();
      description = source.readString();
      link = source.readString();
}
  public String gettitle() {
          return title;
  }
  public void setTitle(String title) {
          this.title = title;
  }
  public String getDescription() {
          return description;
  }
  public void setDescription(String description) {
          this.description = description;
  }
  public String getLink() {
          return link;
  }
  public void setLink(String link) {
          this.link = link;
  }

public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

public void writeToParcel(Parcel dest, int flags) {
      dest.writeString(title);
      dest.writeString(description);
      dest.writeString(link);

}

 public static final Creator<SearchList> CREATOR = new Creator<SearchList>() {
        public SearchList createFromParcel(Parcel source) {
            return new SearchList(source);
        }
        public SearchList[] newArray(int size) {
            return new SearchList[size];
        }
    };
  }

However, when I try and do...

 List<SearchList> listOfResults = new ArrayList<SearchList>();
 intent.putParcelableArrayListExtra("results", listOfResults);

I get not applicable for type (String, List<SearchList> why?