问:
Graphic Location Not Work Crystal Reports
i'm using crystal report version 13

Graphic Location path work fine if the location is my local directory,
but it will show blank if i give path from another computer but i can open the image if i run the path manually.

i access the path using IP address -> share folder(eg: \\192.168.0.10\sharefolder\image.Jpeg), where permission is Full Control

i show the data (including image) to my form before print it using crystal reports. and the image is show correctly

is crystal report not support path from another computer?

答:
The solution is to map the network directory, where the file resides, as a MAPPED network drive.

the Crystal Report API operates better if the path is R:\{CustomerNo}\{ProjectAlias}


来源: stackexchange

问:
How do I use Unix domain sockets from Java/Scala?
What's the best way of using Unix domain sockets from Scala?

I've found a Java library called JUDS, but it doesn't appear to allow me to send file descriptors over the socket --- the reason I want to use Unix domain sockets in the first place.

The JUDS readme refers to a competing library called J-BUDS, but I cannot find this anywhere.

I could add the feature to JUDS myself, but I'd rather I'd rather not reinvent the wheel if it's already in a jar file elsewhere.

答:
http://download.oracle.com/javase/6/docs/api/java/net/Socket.html

By "file descriptors" do you mean objects of the class java.util.File?
...or C-style "FILE *"? (IIRC)

The latter would be tied to the particular instance of the OS, so I wouldn't think you would want to move that to (possibly) another machine.

ContentLicense: CC BY-SA 3.0


问:
How do I change columns in the same order as in my order matrix, per row
I have a matrix where I stored the order of items of a questionnaire, where the first column contains the name of the item that is first shown, the second column has the second shown item, etc. Each row in this matrix represents a new questionnaire, with the same items but with the order randomized in a different order.

```<code>> order.matrix
     [,1]    [,2]    [,3]
[1,] "Anger" "Happy" "Sad"
[2,] "Happy" "Sad"   "Anger"
[3,] "Sad"   "Anger" "Happy"
</code>```

I have stored the responses on the items in a dataframe:

```<code>> df.responses
  Anger Happy Sad
1     1     2   3
2     3     2   0
3     9     2   1
</code>```

Now, I want to change the order of the responses in df.responses, such that they are analogue to the order of items in the order.matrix, for each row. (As a result, the column names of df.responses shouldn't be in the resulting df anymore.)
The result in this example should look like this:

```<code>> df.result
  V1 V2 V3
1  1  2  3
2  2  0  3
3  1  9  2
</code>```

How can/should I do this?

EDIT, due to comment: I want to replace the item names in order.matrix by its corresponding value in df.responses

答:
1.Create reproducible example

```<code>order.matrix <- matrix(c("Anger", "Happy", "Sad", "Happy", "Sad","Anger", "Sad", "Anger", "Happy"),
                       ncol=3,
                       byrow=TRUE)

df.responses <-matrix(c(1, 2, 3, 3, 2, 0, 9, 2, 1),
                        ncol=3,
                        byrow=TRUE)
colnames(df.responses) <- c("Anger", "Happy", "Sad")
</code>```

2.Solution using base R:

```<code>result <- NULL
for (i in seq_along(order.matrix[, 1])) {
  result <- rbind(result, df.responses[i, order.matrix[i, ]])
}
colnames(result) <- c("V1", "V2", "V3")

        V1    V2  V3
[1,]     1     2   3
[2,]     2     0   3
[3,]     1     9   2
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a matrix where I stored the order of items of a questionnaire, where the first column contains the name of the item that is first shown, the second column has the second shown item, etc. Each row in this matrix represents a new questionnaire, with the same items but with the order randomized in a different order.

> order.matrix
     [,1]    [,2]    [,3]
[1,] "Anger" "Happy" "Sad"
[2,] "Happy" "Sad"   "Anger"
[3,] "Sad"   "Anger" "Happy"

I have stored the responses on the items in a dataframe:

> df.responses
  Anger Happy Sad
1     1     2   3
2     3     2   0
3     9     2   1

Now, I want to change the order of the responses in df.responses, such that they are analogue to the order of items in the order.matrix, for each row. (As a result, the column names of df.responses shouldn't be in the resulting df anymore.)
The result in this example should look like this:

> df.result
  V1 V2 V3
1  1  2  3
2  2  0  3
3  1  9  2

How can/should I do this?

EDIT, due to comment: I want to replace the item names in order.matrix by its corresponding value in df.responses

Body:
1.Create reproducible example

order.matrix <- matrix(c("Anger", "Happy", "Sad", "Happy", "Sad","Anger", "Sad", "Anger", "Happy"),
                       ncol=3,
                       byrow=TRUE)

df.responses <-matrix(c(1, 2, 3, 3, 2, 0, 9, 2, 1),
                        ncol=3,
                        byrow=TRUE)
colnames(df.responses) <- c("Anger", "Happy", "Sad")

2.Solution using base R:

result <- NULL
for (i in seq_along(order.matrix[, 1])) {
  result <- rbind(result, df.responses[i, order.matrix[i, ]])
}
colnames(result) <- c("V1", "V2", "V3")

        V1    V2  V3
[1,]     1     2   3
[2,]     2     0   3
[3,]     1     9   2


问:
SQL Request with LEFT JOIN not able to find data
I'm working on my C# project and I have to get data from database thanks to .sql procedures.

Synthesis :

Table ProprietesCourantes is linked to table Entite.

Table Archive is linked to table EntiteArchive

==> I would like to make a link between ProprietesCourantes and Archive thanks to field Libellé

Table ProprietesCourantes

I have several tables in my case :

```<code>SELECT TOP (1000) [IdEntite]
      ,[Libelle]
      ,[EstActif]
      , ...
      , ...
  FROM [Database].[dbo].[ProprietesCourantes]
  WHERE [Libelle] = 'DELTA SERVICE AUTO';
</code>```

Table Entite

```<code>SELECT TOP (1000) [IdEntite]
      ,[TypeEntite]
      ,[CodeEntite]
      ,[TypeCodeEntite]
  FROM [Database].[dbo].[Entite]
  WHERE IdEntite = '165';
</code>```

Table Archive

```<code>SELECT TOP (1000) [IdArchive]
      ,[IdEntite]
      ,[NoteFinale]
      ,[EstValide]
  FROM [Database].[dbo].[Archive]
  WHERE IdEntite = '33' and EstValide = '1';
</code>```

Table EntiteArchive

```<code>SELECT TOP (1000) [IdEntite]
      ,[TypeEntite]
      ,[CodeEntite]
      ,[Libelle]
      ,...
  FROM [Database].[dbo].[EntiteArchive]
</code>```

MY SQL REQUEST :

```<code>SELECT
            ProprietesCourantes.IdEntite                                                                    as IdEntite,
            ProprietesCourantes.Libelle                                                                     as RaisonSociale,
            Entite.CodeEntite                                                                               as IdCMCIC,
            ProprietesCourantes.NomParent                                                                   as NomGN,
            Archive.NoteFinale                                                                              as Cotation,
            Archive.DateValiditeQuestionnaireDeSoutien                                                      as DateValiditeQuestionnaireDeSoutien,
            ProprietesCourantes.CodePays                                                                    as Pays,
            ProprietesCourantes.EstActif                                                                    as Statut,
            CAST(CASE WHEN Entite.CodeEntite = ProprietesCourantes.IdSocMere THEN 1 ELSE 0 END AS BIT)      as EstMaisonMere,
            ProprietesCourantes.IdCMCICParent                                                               as IdCMCICParent,
            ProprietesCourantesGN.CodeAlgo                                                                  as CodeAlgoParent

    FROM ProprietesCourantes

    LEFT JOIN Archive   ON (Archive.IdEntite  = ProprietesCourantes.IdEntite and Archive.EstValide=1)
    LEFT JOIN Entite ON Entite.IdEntite = ProprietesCourantes.IdEntite
    LEFT JOIN Entite as EntiteGN ON EntiteGN.CodeEntite = ProprietesCourantes.IdCMCICParent
    LEFT JOIN ProprietesCourantes as ProprietesCourantesGN ON ProprietesCourantesGN.IdEntite = EntiteGN.IdEntite

    WHERE Entite.TypeEntite = 1
        AND   (ProprietesCourantes.Libelle LIKE '%'+'DELTA SERVICE'+'%' )
</code>```

As you can see : Cotation and DateValiditeQuestionnaireDeSoutien are NULL because LEFT JOIN Archive   ON (Archive.IdEntite  = ProprietesCourantes.IdEntite can't work (different IDEntite).

I tried to replace by this, but it doesn't work, any idea ?

```<code>LEFT JOIN Archive   ON ((select EntiteArchive.Libelle from EntiteArchive LEFT JOIN Archive ON (EntiteArchive.IdEntite = Archive.IdEntite)) = ProprietesCourantes.Libelle and Archive.EstValide=1)
</code>```

答:
Just move the condition on the let joined table Entite to the on part of the join. Otherwise, it becomes a mandatory condition, and filters out records for which there is no match in Entite.

```<code>SELECT
            ProprietesCourantes.IdEntite                                                                    as IdEntite,
            ProprietesCourantes.Libelle                                                                     as RaisonSociale,
            Entite.CodeEntite                                                                               as IdCMCIC,
            ProprietesCourantes.NomParent                                                                   as NomGN,
            Archive.NoteFinale                                                                              as Cotation,
            Archive.DateValiditeQuestionnaireDeSoutien                                                      as DateValiditeQuestionnaireDeSoutien,
            ProprietesCourantes.CodePays                                                                    as Pays,
            ProprietesCourantes.EstActif                                                                    as Statut,
            CAST(CASE WHEN Entite.CodeEntite = ProprietesCourantes.IdSocMere THEN 1 ELSE 0 END AS BIT)      as EstMaisonMere,
            ProprietesCourantes.IdCMCICParent                                                               as IdCMCICParent,
            ProprietesCourantesGN.CodeAlgo                                                                  as CodeAlgoParent
    FROM ProprietesCourantes
    LEFT JOIN Archive
        ON  Archive.IdEntite  = ProprietesCourantes.IdEntite
        AND Archive.EstValide=1)
    LEFT JOIN Entite
        ON  Entite.IdEntite = ProprietesCourantes.IdEntite
        AND Entite.TypeEntite = 1
    LEFT JOIN Entite as EntiteGN
        ON  EntiteGN.CodeEntite = ProprietesCourantes.IdCMCICParent
    LEFT JOIN ProprietesCourantes as ProprietesCourantesGN
        ON  ProprietesCourantesGN.IdEntite = EntiteGN.IdEntite
    WHERE ProprietesCourantes.Libelle LIKE '%'+'DELTA SERVICE'+'%'
</code>```

Body:
I'm working on my C# project and I have to get data from database thanks to .sql procedures.

Synthesis :

Table ProprietesCourantes is linked to table Entite.

Table Archive is linked to table EntiteArchive

==> I would like to make a link between ProprietesCourantes and Archive thanks to field Libellé

Table ProprietesCourantes

I have several tables in my case :

SELECT TOP (1000) [IdEntite]
      ,[Libelle]
      ,[EstActif]
      , ...
      , ...
  FROM [Database].[dbo].[ProprietesCourantes]
  WHERE [Libelle] = 'DELTA SERVICE AUTO';

Table Entite

SELECT TOP (1000) [IdEntite]
      ,[TypeEntite]
      ,[CodeEntite]
      ,[TypeCodeEntite]
  FROM [Database].[dbo].[Entite]
  WHERE IdEntite = '165';

Table Archive

SELECT TOP (1000) [IdArchive]
      ,[IdEntite]
      ,[NoteFinale]
      ,[EstValide]
  FROM [Database].[dbo].[Archive]
  WHERE IdEntite = '33' and EstValide = '1';

Table EntiteArchive

SELECT TOP (1000) [IdEntite]
      ,[TypeEntite]
      ,[CodeEntite]
      ,[Libelle]
      ,...
  FROM [Database].[dbo].[EntiteArchive]

MY SQL REQUEST :

SELECT
            ProprietesCourantes.IdEntite                                                                    as IdEntite,
            ProprietesCourantes.Libelle                                                                     as RaisonSociale,
            Entite.CodeEntite                                                                               as IdCMCIC,
            ProprietesCourantes.NomParent                                                                   as NomGN,
            Archive.NoteFinale                                                                              as Cotation,
            Archive.DateValiditeQuestionnaireDeSoutien                                                      as DateValiditeQuestionnaireDeSoutien,
            ProprietesCourantes.CodePays                                                                    as Pays,
            ProprietesCourantes.EstActif                                                                    as Statut,
            CAST(CASE WHEN Entite.CodeEntite = ProprietesCourantes.IdSocMere THEN 1 ELSE 0 END AS BIT)      as EstMaisonMere,
            ProprietesCourantes.IdCMCICParent                                                               as IdCMCICParent,
            ProprietesCourantesGN.CodeAlgo                                                                  as CodeAlgoParent

    FROM ProprietesCourantes

    LEFT JOIN Archive   ON (Archive.IdEntite  = ProprietesCourantes.IdEntite and Archive.EstValide=1)
    LEFT JOIN Entite ON Entite.IdEntite = ProprietesCourantes.IdEntite
    LEFT JOIN Entite as EntiteGN ON EntiteGN.CodeEntite = ProprietesCourantes.IdCMCICParent
    LEFT JOIN ProprietesCourantes as ProprietesCourantesGN ON ProprietesCourantesGN.IdEntite = EntiteGN.IdEntite

    WHERE Entite.TypeEntite = 1
        AND   (ProprietesCourantes.Libelle LIKE '%'+'DELTA SERVICE'+'%' )

As you can see : Cotation and DateValiditeQuestionnaireDeSoutien are NULL because LEFT JOIN Archive   ON (Archive.IdEntite  = ProprietesCourantes.IdEntite can't work (different IDEntite).

I tried to replace by this, but it doesn't work, any idea ?

LEFT JOIN Archive   ON ((select EntiteArchive.Libelle from EntiteArchive LEFT JOIN Archive ON (EntiteArchive.IdEntite = Archive.IdEntite)) = ProprietesCourantes.Libelle and Archive.EstValide=1)

Body:
Just move the condition on the let joined table Entite to the on part of the join. Otherwise, it becomes a mandatory condition, and filters out records for which there is no match in Entite.

SELECT
            ProprietesCourantes.IdEntite                                                                    as IdEntite,
            ProprietesCourantes.Libelle                                                                     as RaisonSociale,
            Entite.CodeEntite                                                                               as IdCMCIC,
            ProprietesCourantes.NomParent                                                                   as NomGN,
            Archive.NoteFinale                                                                              as Cotation,
            Archive.DateValiditeQuestionnaireDeSoutien                                                      as DateValiditeQuestionnaireDeSoutien,
            ProprietesCourantes.CodePays                                                                    as Pays,
            ProprietesCourantes.EstActif                                                                    as Statut,
            CAST(CASE WHEN Entite.CodeEntite = ProprietesCourantes.IdSocMere THEN 1 ELSE 0 END AS BIT)      as EstMaisonMere,
            ProprietesCourantes.IdCMCICParent                                                               as IdCMCICParent,
            ProprietesCourantesGN.CodeAlgo                                                                  as CodeAlgoParent
    FROM ProprietesCourantes
    LEFT JOIN Archive
        ON  Archive.IdEntite  = ProprietesCourantes.IdEntite
        AND Archive.EstValide=1)
    LEFT JOIN Entite
        ON  Entite.IdEntite = ProprietesCourantes.IdEntite
        AND Entite.TypeEntite = 1
    LEFT JOIN Entite as EntiteGN
        ON  EntiteGN.CodeEntite = ProprietesCourantes.IdCMCICParent
    LEFT JOIN ProprietesCourantes as ProprietesCourantesGN
        ON  ProprietesCourantesGN.IdEntite = EntiteGN.IdEntite
    WHERE ProprietesCourantes.Libelle LIKE '%'+'DELTA SERVICE'+'%'


问:
Minimum number of swaps to convert a string to palindrome
We are given a string and we have to find out the minimum number of swaps to convert it into a palindrome.

```<code>Ex-
Given string: ntiin
Palindrome: nitin
Minimum number of swaps: 1
</code>```

If it is not possible to convert it into a palindrome, return -1.

I am unable to think of any approach except brute force. We can check on the first and last characters, if they are equal, we check for the smaller substring, and then apply brute force on it. But this will be of a very high complexity, and I feel this question can be solved in another way. Maybe dynamic programming. How to approach it?

答:
My solution revolves around the palindrome property that first element and last element should match and if their adjacent elements also do not match then its not a palindrome. Keep comparing and swapping till both reach the same element or adjacent elements.

Written solution in java as below:

```<code>public static void main(String args[]){
        String input = "natinat";
        char[] arr = input.toCharArray();
        int swap = 0;
        int i = 0;
        int j = arr.length-1;
        char temp;
        while(i<j){
            if(arr[i] != arr[j]){
                if(arr[i+1] == arr[j]){
                    //swap i and i+1 and increment i, decrement j, swap++
                    temp = arr[i];
                    arr[i] = arr[i+1];
                    arr[i+1] = temp;

                    i++;j--;
                    swap++;
                } else if(arr[i] == arr[j-1]){
                    //swap j and j-1 and increment i, decrement j, swap++
                    temp = arr[j];
                    arr[j] = arr[j-1];
                    arr[j-1] = temp;

                    i++;j--;
                    swap++;
                } else if(arr[i+1] == arr[j-1] && i+1 != j-1){
                    //swap i and i+1, swap j and j-1 and increment i, decrement j, swap+2
                    temp = arr[j];
                    arr[j] = arr[j-1];
                    arr[j-1] = temp;

                    temp = arr[i];
                    arr[i] = arr[i+1];
                    arr[i+1] = temp;

                    i++;j--;
                    swap = swap+2;
                }else{
                    swap = -1;break;
                }
            } else{
                //increment i, decrement j
                i++;j--;
            }
        }
        System.out.println("No Of Swaps: "+swap);
    }
</code>```

Body:
We are given a string and we have to find out the minimum number of swaps to convert it into a palindrome.

Ex-
Given string: ntiin
Palindrome: nitin
Minimum number of swaps: 1

If it is not possible to convert it into a palindrome, return -1.

I am unable to think of any approach except brute force. We can check on the first and last characters, if they are equal, we check for the smaller substring, and then apply brute force on it. But this will be of a very high complexity, and I feel this question can be solved in another way. Maybe dynamic programming. How to approach it?

Body:
My solution revolves around the palindrome property that first element and last element should match and if their adjacent elements also do not match then its not a palindrome. Keep comparing and swapping till both reach the same element or adjacent elements.

Written solution in java as below:

public static void main(String args[]){
        String input = "natinat";
        char[] arr = input.toCharArray();
        int swap = 0;
        int i = 0;
        int j = arr.length-1;
        char temp;
        while(i<j){
            if(arr[i] != arr[j]){
                if(arr[i+1] == arr[j]){
                    //swap i and i+1 and increment i, decrement j, swap++
                    temp = arr[i];
                    arr[i] = arr[i+1];
                    arr[i+1] = temp;

                    i++;j--;
                    swap++;
                } else if(arr[i] == arr[j-1]){
                    //swap j and j-1 and increment i, decrement j, swap++
                    temp = arr[j];
                    arr[j] = arr[j-1];
                    arr[j-1] = temp;

                    i++;j--;
                    swap++;
                } else if(arr[i+1] == arr[j-1] && i+1 != j-1){
                    //swap i and i+1, swap j and j-1 and increment i, decrement j, swap+2
                    temp = arr[j];
                    arr[j] = arr[j-1];
                    arr[j-1] = temp;

                    temp = arr[i];
                    arr[i] = arr[i+1];
                    arr[i+1] = temp;

                    i++;j--;
                    swap = swap+2;
                }else{
                    swap = -1;break;
                }
            } else{
                //increment i, decrement j
                i++;j--;
            }
        }
        System.out.println("No Of Swaps: "+swap);
    }


问:
How to transpose a base-10 number into a numbering system with characters?
In a base-10 numbering system, each digit can be from 0 to 9. I want to "increase the resolution" of each digit to be 0-9abc...custom_set_of_letters. This way, I can convert a large integer number into a shorter alphanumeric string representation.

For example, the number 102234 would be something like "A45" ("A45" is not the actual answer I'm looking for, it's just to illustrate that the string version would be shorter thanks to having more digits)

C/C++/Java/C# answer would be much preferred. Thank you!

(custom_set_of_letters could be in a non-latin language, do not assume ASCII)

答:
In C++, I will do something like that:

```<code>#include    <iostream>
#include    <string>
#include    <algorithm>

std::string ch_base (int i) {
    const std::string figures = "0123456789abcdefghijklmnopqrstuvwxyz";
    const int base = figures.length();
    std::string res;
    if (i == 0) return "0";
    while (i) {
        res += figures[i%base];
        i /= base;
    }
    int size = res.size();
    for (int i = 0; i < size/2; i++) {
        std::swap (res[i], res[size-i-1]);
    }
    return res;
}

int main() {
    int i = 102234;
    std::cout << i << " = " << ch_base(i) << "\n";
}
</code>```

It can be easily adapted to a different set of figures.

EDIT: a simpler version here:

```<code>std::string ch_base (int i) {
    const std::string figures = "0123456789abcdefghijklmnopqrstuvwxyz";
    const int base = figures.length();
    std::string res;
    if (i == 0) return "0";
    while (i) {
        res.push_back(figures[i%base]);
        i /= base;
    }
    return res;
}
</code>```

Body:
In C++, I will do something like that:

#include    <iostream>
#include    <string>
#include    <algorithm>

std::string ch_base (int i) {
    const std::string figures = "0123456789abcdefghijklmnopqrstuvwxyz";
    const int base = figures.length();
    std::string res;
    if (i == 0) return "0";
    while (i) {
        res += figures[i%base];
        i /= base;
    }
    int size = res.size();
    for (int i = 0; i < size/2; i++) {
        std::swap (res[i], res[size-i-1]);
    }
    return res;
}

int main() {
    int i = 102234;
    std::cout << i << " = " << ch_base(i) << "\n";
}

It can be easily adapted to a different set of figures.

EDIT: a simpler version here:

std::string ch_base (int i) {
    const std::string figures = "0123456789abcdefghijklmnopqrstuvwxyz";
    const int base = figures.length();
    std::string res;
    if (i == 0) return "0";
    while (i) {
        res.push_back(figures[i%base]);
        i /= base;
    }
    return res;
}


问:
One regex to capture words separated by one space-character in combination with the opposite capture occurrences more than one space-character
I would like to have just one regex to capture words separated by one space-character in combination with the opposite capture occurrences more than one space-character

I would like to have the following example covered:

```<code>This line with     sometimes more than    1  space needs to be captured in 3 matches with 2 groups.
</code>```

I expect the following groups:

```<code>([This line with][     ])([sometimes more than][    ])([1][  ])space needs to be captured in 3 matches with 2 groups.
</code>```

To capture one of the two is no problem.
i.e.
to capture more than one space-char:

```<code>([\s]{2,})
</code>```

and to capture words separated by only one space-char(see https://stackoverflow.com/a/60288115/3710053):

```<code>\S+(?:\s\S+)*
</code>```

答:
You might use an alternation to match either a word followed by a repeating pattern of a single space and a word OR match 2 or more spaces

```<code>\S+(?: \S+)*| {2,}
</code>```

Explanation

\S+ Match 1+ non whitespace chars

(?: \S+)* Repeat 0+ times matching a space and 1+ non whitespace chars

| Or

 {2,} Repeat 2 or more times matching a space

Regex demo

If you want to match whitespace chars instead, you could replace the space with \s but note that it could also possibly match newlines.

Edit

For the updated question, you could use 2 capturing groups:

```<code>(\S+(?: \S+)*)( {2,})
</code>```

Explanation

( Capture group 1

\S+ Match 1+ non whitespace chars

(?: \S+)* Repeat 0+ times matching a space and 1+ non whitespace chars

) Close group 1

( Capture group 2

 {2,} Match 2 or more spaces

) Close group 2

Regex demo

Body:
I would like to have just one regex to capture words separated by one space-character in combination with the opposite capture occurrences more than one space-character

I would like to have the following example covered:

This line with     sometimes more than    1  space needs to be captured in 3 matches with 2 groups.

I expect the following groups:

([This line with][     ])([sometimes more than][    ])([1][  ])space needs to be captured in 3 matches with 2 groups.

To capture one of the two is no problem.
i.e.
to capture more than one space-char:

([\s]{2,})

and to capture words separated by only one space-char(see https://stackoverflow.com/a/60288115/3710053):

\S+(?:\s\S+)*

Body:
You might use an alternation to match either a word followed by a repeating pattern of a single space and a word OR match 2 or more spaces

\S+(?: \S+)*| {2,}

Explanation

\S+ Match 1+ non whitespace chars

(?: \S+)* Repeat 0+ times matching a space and 1+ non whitespace chars

| Or

 {2,} Repeat 2 or more times matching a space

Regex demo

If you want to match whitespace chars instead, you could replace the space with \s but note that it could also possibly match newlines.

Edit

For the updated question, you could use 2 capturing groups:

(\S+(?: \S+)*)( {2,})

Explanation

( Capture group 1

\S+ Match 1+ non whitespace chars

(?: \S+)* Repeat 0+ times matching a space and 1+ non whitespace chars

) Close group 1

( Capture group 2

 {2,} Match 2 or more spaces

) Close group 2

Regex demo


问:
Is there a way to override "blacklisted" words if there is a certain variable that's allowed?
```<code>            const BannedLinks = ["https://", "http://", "www.", ".com", ".net", ".org", ".tv", ".xyz", ".blog"]
            if(BannedLinks.some(word => message.content.includes(word)) ) {
            message.delete();
            message.reply("please dont post links, take that to DM's").then(m => m.delete(3000));
            }
</code>```

This is my anti-link code for my Discord bot, but I want to allow links like Twitch.tv and cdn.discordapp.com, but I'm struggling to find right functions.

答:
You can use array.prototype.some method.

Discord solution

client.on('message', message => {
    const whiteListLinks = ['Twitch', 'Youtube']
    const blackListLinks = ['https', 'http']

    let isBlacklisted = blackListLinks.some(checkInclude) && !whiteListLinks.some(checkInclude)
    if (isBlacklisted) message.delete()

    function checkInclude(element, index, array) {
      return message.content.toUpperCase().includes(element.toUpperCase());
    }
});
```
<p><strong>Online snippet</strong></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-js lang-js prettyprint-override"><code>  const message = {
       content: 'https:Twitch'
  }
    const whiteListLinks = ['Twitch', 'Youtube']
    const blackListLinks = ['https', 'http']

  let isBlacklisted = blackListLinks.some(checkInclude) && !whiteListLinks.some(checkInclude)
  console.log(isBlacklisted)

function checkInclude(element, index, array) {
  return message.content.toUpperCase().includes(element.toUpperCase());
}</code>```

Body:
            const BannedLinks = ["https://", "http://", "www.", ".com", ".net", ".org", ".tv", ".xyz", ".blog"]
            if(BannedLinks.some(word => message.content.includes(word)) ) {
            message.delete();
            message.reply("please dont post links, take that to DM's").then(m => m.delete(3000));
            }

This is my anti-link code for my Discord bot, but I want to allow links like Twitch.tv and cdn.discordapp.com, but I'm struggling to find right functions.

Body:
You can use array.prototype.some method.

Discord solution

client.on('message', message => {
    const whiteListLinks = ['Twitch', 'Youtube']
    const blackListLinks = ['https', 'http']

    let isBlacklisted = blackListLinks.some(checkInclude) && !whiteListLinks.some(checkInclude)
    if (isBlacklisted) message.delete()

    function checkInclude(element, index, array) {
      return message.content.toUpperCase().includes(element.toUpperCase());
    }
});

Online snippet

  const message = {
       content: 'https:Twitch'
  }
    const whiteListLinks = ['Twitch', 'Youtube']
    const blackListLinks = ['https', 'http']

  let isBlacklisted = blackListLinks.some(checkInclude) && !whiteListLinks.some(checkInclude)
  console.log(isBlacklisted)

function checkInclude(element, index, array) {
  return message.content.toUpperCase().includes(element.toUpperCase());
}


问:
posting an array using JQuery .post()
so I am rather new to the whole .post() experience with jquery.

I have only experience POSTing input values so far. What I want to do is POST an array.

which is a standard array of a list of numbers. The end goal being: performing a query with these values.

Could somebody explain to me very basically how using JQuery .post() I can post my array?

many thanks,

答:
Check jQuery.post(). There is an example for posting arrays.

EDITED: Example is like;

```<code>$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
</code>```

Title: posting an array using JQuery .post()

Body:
Check jQuery.post(). There is an example for posting arrays.

EDITED: Example is like;

$.post("test.php", { 'choices[]': ["Jon", "Susan"] });


问:
iText7: Creating PDF from TIFF multipage image using iText
I am trying to use iText 7.1.1 to convert a TIFF image to PDF file with multiple pages. Thanks for those to get me started with this article Create PDF from TIFF image using iText. However, it is iText 5.5.x and I have trouble to duplicate it in iText 7.

I did find TiffImageData.getNumberOfPages(raf) to replace int pages = TiffImage.getNumberOfPages(rafa).

However, I am not able to replace TiffImage.getTiffImage(rafa, i) in iText7. Do I need to use new Image(ImageDataFactory.createTiff(...)). Appreciate any suggestion(s).

iText 5.5.x code

```<code>import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.io.FileChannelRandomAccessSource;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.RandomAccessFileOrArray;
import com.itextpdf.text.pdf.codec.TiffImage;

public class Test1 {
    public static void main(String[] args) throws Exception {
    RandomAccessFile aFile = new RandomAccessFile("/myfolder/origin.tif", "r");
    FileChannel inChannel = aFile.getChannel();
    FileChannelRandomAccessSource fcra =  new FileChannelRandomAccessSource(inChannel);
    Document document = new Document();
    PdfWriter.getInstance(document,  new FileOutputStream("/myfolder/destination.pdf"));
    document.open();
    RandomAccessFileOrArray rafa = new RandomAccessFileOrArray(fcra);
    int pages = TiffImage.getNumberOfPages(rafa);
    Image image;
    for (int i = 1; i <= pages; i++) {
        image = TiffImage.getTiffImage(rafa, i);
        Rectangle pageSize = new Rectangle(image.getWidth(), image.getHeight());
        document.setPageSize(pageSize);
        document.newPage();
        document.add(image);
    }
    document.close();
    aFile.close();
}
</code>```

答:
This is the same above but in vb.net.
It converts a multipage TIFF to a PDF.</p>

```<code>Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf

Sub ConvertTIFF2PDF(ByVal inFile As String, ByVal outFile As String)

    Dim pdfDoc As PdfDocument = New PdfDocument(New PdfWriter(outFile))
    Dim doc As Document = New Document(pdfDoc)

    Dim aFile = New RandomAccessFileOrArray(New RandomAccessSourceFactory().CreateBestSource(inFile.ToString))

    Dim tiffPages = TiffImageData.GetNumberOfPages(aFile)

    Dim uri As System.Uri = New Uri(inFile)

    For i As Integer = 1 To tiffPages

        Console.WriteLine("tiffPages: " & (i) & " of " & tiffPages.ToString)

        Dim tiffImage = ImageDataFactory.CreateTiff(uri, False, i, False)
        Dim tiffPageSize = New Geom.Rectangle(tiffImage.GetWidth(), tiffImage.GetHeight())
        Dim newPage = pdfDoc.AddNewPage(New PageSize(tiffPageSize))
        Dim canvas As PdfCanvas = New PdfCanvas(newPage)
        canvas.AddImage(tiffImage, tiffPageSize, False)

    Next

    doc.Close()
    pdfDoc.Close()
    aFile.Close()

End Sub
</code>```

Body:
I am trying to use iText 7.1.1 to convert a TIFF image to PDF file with multiple pages. Thanks for those to get me started with this article Create PDF from TIFF image using iText. However, it is iText 5.5.x and I have trouble to duplicate it in iText 7.

I did find TiffImageData.getNumberOfPages(raf) to replace int pages = TiffImage.getNumberOfPages(rafa).

However, I am not able to replace TiffImage.getTiffImage(rafa, i) in iText7. Do I need to use new Image(ImageDataFactory.createTiff(...)). Appreciate any suggestion(s).

iText 5.5.x code

import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.io.FileChannelRandomAccessSource;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.RandomAccessFileOrArray;
import com.itextpdf.text.pdf.codec.TiffImage;

public class Test1 {
    public static void main(String[] args) throws Exception {
    RandomAccessFile aFile = new RandomAccessFile("/myfolder/origin.tif", "r");
    FileChannel inChannel = aFile.getChannel();
    FileChannelRandomAccessSource fcra =  new FileChannelRandomAccessSource(inChannel);
    Document document = new Document();
    PdfWriter.getInstance(document,  new FileOutputStream("/myfolder/destination.pdf"));
    document.open();
    RandomAccessFileOrArray rafa = new RandomAccessFileOrArray(fcra);
    int pages = TiffImage.getNumberOfPages(rafa);
    Image image;
    for (int i = 1; i <= pages; i++) {
        image = TiffImage.getTiffImage(rafa, i);
        Rectangle pageSize = new Rectangle(image.getWidth(), image.getHeight());
        document.setPageSize(pageSize);
        document.newPage();
        document.add(image);
    }
    document.close();
    aFile.close();
}

Body:
This is the same above but in vb.net.
It converts a multipage TIFF to a PDF.

Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf

Sub ConvertTIFF2PDF(ByVal inFile As String, ByVal outFile As String)

    Dim pdfDoc As PdfDocument = New PdfDocument(New PdfWriter(outFile))
    Dim doc As Document = New Document(pdfDoc)

    Dim aFile = New RandomAccessFileOrArray(New RandomAccessSourceFactory().CreateBestSource(inFile.ToString))

    Dim tiffPages = TiffImageData.GetNumberOfPages(aFile)

    Dim uri As System.Uri = New Uri(inFile)

    For i As Integer = 1 To tiffPages

        Console.WriteLine("tiffPages: " & (i) & " of " & tiffPages.ToString)

        Dim tiffImage = ImageDataFactory.CreateTiff(uri, False, i, False)
        Dim tiffPageSize = New Geom.Rectangle(tiffImage.GetWidth(), tiffImage.GetHeight())
        Dim newPage = pdfDoc.AddNewPage(New PageSize(tiffPageSize))
        Dim canvas As PdfCanvas = New PdfCanvas(newPage)
        canvas.AddImage(tiffImage, tiffPageSize, False)

    Next

    doc.Close()
    pdfDoc.Close()
    aFile.Close()

End Sub


问:
Is there any youtube data api for analytics if yes how to use it in my node js web application which is user for uploading videos to YouTube?
My web application is used for education purpose, and im able to upload videos to youtube but now i want to use analytics api so where can i get that api and how do i use it in my nodejs application.</p>

答:
Here you are. Maybe this should help.
https://developers.google.com/youtube/v3/quickstart/nodejs</p>


问:
Cant create CSV file with django although already copaste from the documentation
So i try to follow the documentation from django itself how to create CSV file, i copaste the code but it didnt work , it should be the browser download the somefilename.csv when it success , is there anything wrong? or do i need to set something in settings.py?
Here's the code (HTML and Views)

```<code>  <div class="col-lg-12">
            <div class="form-panel">
              <form action="#" class="form-horizontal style-form" id="form1">
                <div class="form-group">
                  <label class="control-label col-md-3">Campaign Name</label>
                   <div class="col-md-3 col-xs-11">
                    <input id = "campaign_name" type="text" class="form-control form-width">
                  </div>
                </div>
                <div class="form-group">
                 <label class="control-label col-md-3">Campaign Type</label>
                  <div class="col-md-3 col-xs-11">
                   <div class="btn-group">
                     <select id = "campaigntype"  style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
                            <option disabled selected value>-- Choose --</option>
                            <!-- <li><a href="#"></a></li> -->
                            <option value = "Informasi" >Informasi</option>
                            <option value = "Promosi" >Promosi</option>
                            <!-- <li><a href="#">Dropdown link</a></li> -->
                            </select>
                   </div>
                  </div>
                </div>
                <div class="form-group">
                 <label class="control-label col-md-3">Segment</label>
                  <div class="col-md-3 col-xs-11">
                   <div class="btn-group">
                     <select id = "segment_list_name"  style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
                            <option disabled selected value>-- Choose --</option>
                            <!-- <li><a href="#"></a></li> -->
                            {% for x in segmentname %}
                                    <option value = "{{x}}" >{{ x }}</option>
                            {% endfor %}
                            <!-- <li><a href="#">Dropdown link</a></li> -->
                            </select>
                   </div>
                  </div>
                </div>
                <div class="form-group">
                  <label class="control-label col-md-3">Channel</label>
                  <div class="col-md-4">
                    <div class="input-group bootstrap-timepicker">
                      <div class="btn-group">
                         <select id="channeltype" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
                            <option disabled selected value>-- Choose --</option>
                            <!-- <li><a href="#"></a></li> -->
                            {% for y in channel %}
                                    <option value = "{{y}}" >{{ y }}</option>
                            {% endfor %}
                            <!-- <li><a href="#">Dropdown link</a></li> -->
                            </select>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="form-group">
                  <label class="control-label col-md-3">Product</label>
                  <div class="col-md-4">
                    <div class="input-group bootstrap-timepicker">
                      <div class="btn-group">
                         <select id="producttype" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
                            <option disabled selected value>-- Choose --</option>
                            <!-- <li><a href="#"></a></li> -->
                            {% for z in product %}
                                    <option value = "{{z}}" >{{ z }}</option>
                            {% endfor %}
                            <!-- <li><a href="#">Dropdown link</a></li> -->
                            </select>
                      </div>
                    </div>
                    <br>
                    <div id="rowselect">
                    </div>
                  </div>
                  <div class="col-md-1">
                        <button type="button" id="countbutton" class="btn btn-info" onclick="return button()">Count</button>
                  </div>
                </div>
                <div class="form-group">
                  <label class="control-label col-md-3">Order By</label>
                  <div class="col-md-4">
                    <div class="input-group bootstrap-timepicker">
                      <div class="btn-group">
                        <select id="columnsegment" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
                        </select>
                      </div>
                    </div>
                    <br>
                    <div id="sortby">
                        <input type="radio" name="order" value="asc" checked> Ascending
                        <input type="radio" name="order" value="desc"> Descending
                    </div>
                  </div>
                  </div>
                <div class="form-group">
                  <label class="control-label col-md-3">Max Row</label>
                   <div class="col-md-3 col-xs-11">
                    <input id="maxrow" type="number" min="1" class="form-control form-width">
                  </div>
                </div>
                <div class="form-group">
                  <label class="control-label col-md-3">Output File</label>
                   <div id="outputfile" class="col-md-3 col-xs-11">
                        <input type="radio" name="output" value="csv" checked> csv
                        <input type="radio" name="output" value="txt"> txt
                  </div>
                </div>
                <div class="form-group">
                 <label class="control-label col-md-3">Description</label>
                  <div class="col-md-3 col-xs-11">
                   <textarea id="desc" name="desc" class="form-control form-width" maxlength="150"></textarea>
                  </div>
                </div>
              </form>
            </div>
            <!-- /form-panel -->
          </div>
          <!-- /col-lg-12 -->
        </div>
        <button id="export" class="btn btn-theme03" onclick="return button()">Export</button>
<script>
      $(document).ready(function() {
      $("#export").click(function () {
          var urls = "{% url 'polls:export' %}";
          var camp_name = $('#campaign_name').val();
          var seg_name = $('#segment_list_name').val();
          var col_seg = $('#columnsegment').val();
          var sortby = $('#sortby').val();
          var maxrow = $('#maxrow').val();
          var outfile = $('#outputfile').val();
          var path_upload = $('#flup').val();

      data = {
        'camp_name' : camp_name,
        'seg_name' : seg_name,
        'col_seg' : col_seg,
        'sortby' : sortby,
        'maxrow' : maxrow,
        'outfile' : outfile,
        'path_upload' : path_upload,
      };

        $.ajax({
          url: urls,
          data: data,
          success: function(data) {
            return(data);
          },
          error: function(data)
          {

          }
        });
      });
      });
  </script>

</code>```

Views.py

```<code>from django.template import loader
from django.http import HttpResponse, HttpResponseRedirect

def export_script(request):
    campaign_name = request.GET.get('camp_name')
    segment_name = request.GET.get('seg_name')
    column_segment = request.GET.get('col_seg')
    sort_by = request.GET.get('sortby')
    max_row = request.GET.get('maxrow')
    out_file = request.GET.get('outfile')
    path_upload = request.GET.get('path_upload')

    import cx_Oracle
    dsn_tns = cx_Oracle.makedsn('', '', sid='')
    conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns)
    c = conn.cursor()
    curr = conn.cursor()
    c.execute("select script from arman_segment_dimension where segment_name = '"+segment_name+"'")
    c.rowfactory = makeDictFactory(c)
    columnalldata = []

    for rowDict in c:
        columnalldata.append(rowDict['SCRIPT'])

    import re

    queryscript = columnalldata[0]
    query_con = queryscript + " order by " + column_segment + sort_by + " fetch next " + max_row + " rows only"

    upr = queryscript.upper()
    splitter = upr.split()
    comparison = splitter[-2]
    filtering = re.search('SELECT (.*) FROM', upr)

    if comparison == "FROM":
        filtering2 = re.search('FROM (.*)', upr)
    else:
        filtering2 = re.search('FROM (.*) WHERE', upr)

    table_name = filtering2.group(1)
    result = filtering.group(1)
    data_names = result.split(',')

    import cx_Oracle
    dsn_tns = cx_Oracle.makedsn('', '', sid='')
    conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns)
    c = conn.cursor()
    c.execute(query_con)

    c.rowfactory = makeDictFactory(c)
    columnalldata = []

    response = HttpResponse(content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename="somefile.txt"'
    writer = csv.writer(response)
    if result == "*":
        connection = conn.cursor()
        connection.execute("select column_name from all_tab_cols where table_name = '"+table_name+"'")
        connection.rowfactory = makeDictFactory(connection)
        columnallname = []

        for rowDict in connection:
            columnallname.append(rowDict['COLUMN_NAME'])
            writer.writerow(rowDict[name] for name in columnallname)

        for row in c:
            columnalldata.append([row[data_name] for data_name in columnallname])
            writer.writerow([row[data_name] for data_name in columnallname])
    else:
        writer.writerow(data_names)

        for row in c:
            columnalldata.append([row[data_name] for data_name in data_names])
            writer.writerow([row[data_name] for data_name in data_names])

    return  response

</code>```

i just want to do it automatically, dont want to press F12 then double click so the browser can download it

答:
You are not setting correctly the content_type.

response = HttpResponse(content_type='text/plain')

And also setting the filename as TXT instead of CSV

response['Content-Disposition'] = 'attachment;
  filename="somefile.txt"'

The following code works just fine for me.

```<code>import csv
from django.http import HttpResponse

def CsvOutputView(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    writer = csv.writer(response)
    data = your_model.objects.all().values_list()
    for this_data in data:
        writer.writerow(this_data)

    return response
</code>```

Hope it helps.

Body:
So i try to follow the documentation from django itself how to create CSV file, i copaste the code but it didnt work , it should be the browser download the somefilename.csv when it success , is there anything wrong? or do i need to set something in settings.py?
Here's the code (HTML and Views)

              <form action="#" class="form-horizontal style-form" id="form1">

                  Campaign Name

                    <input id = "campaign_name" type="text" class="form-control form-width">

                 Campaign Type

                     <select id = "campaigntype"  style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
                            <option disabled selected value>-- Choose --</option>

                            <option value = "Informasi" >Informasi</option>
                            <option value = "Promosi" >Promosi</option>

                            </select>

                 Segment

                     <select id = "segment_list_name"  style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
                            <option disabled selected value>-- Choose --</option>

                            {% for x in segmentname %}
                                    <option value = "{{x}}" >{{ x }}</option>
                            {% endfor %}

                            </select>

                  Channel

                         <select id="channeltype" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
                            <option disabled selected value>-- Choose --</option>

                            {% for y in channel %}
                                    <option value = "{{y}}" >{{ y }}</option>
                            {% endfor %}

                            </select>

                  Product

                         <select id="producttype" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
                            <option disabled selected value>-- Choose --</option>

                            {% for z in product %}
                                    <option value = "{{z}}" >{{ z }}</option>
                            {% endfor %}

                            </select>

                        <button type="button" id="countbutton" class="btn btn-info" onclick="return button()">Count</button>

                  Order By

                        <select id="columnsegment" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
                        </select>

                        <input type="radio" name="order" value="asc" checked> Ascending
                        <input type="radio" name="order" value="desc"> Descending

                  Max Row

                    <input id="maxrow" type="number" min="1" class="form-control form-width">

                  Output File

                        <input type="radio" name="output" value="csv" checked> csv
                        <input type="radio" name="output" value="txt"> txt

                 Description

                   <textarea id="desc" name="desc" class="form-control form-width" maxlength="150"></textarea>

              </form>

        <button id="export" class="btn btn-theme03" onclick="return button()">Export</button>

Views.py

from django.template import loader
from django.http import HttpResponse, HttpResponseRedirect

def export_script(request):
    campaign_name = request.GET.get('camp_name')
    segment_name = request.GET.get('seg_name')
    column_segment = request.GET.get('col_seg')
    sort_by = request.GET.get('sortby')
    max_row = request.GET.get('maxrow')
    out_file = request.GET.get('outfile')
    path_upload = request.GET.get('path_upload')

    import cx_Oracle
    dsn_tns = cx_Oracle.makedsn('', '', sid='')
    conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns)
    c = conn.cursor()
    curr = conn.cursor()
    c.execute("select script from arman_segment_dimension where segment_name = '"+segment_name+"'")
    c.rowfactory = makeDictFactory(c)
    columnalldata = []

    for rowDict in c:
        columnalldata.append(rowDict['SCRIPT'])

    import re

    queryscript = columnalldata[0]
    query_con = queryscript + " order by " + column_segment + sort_by + " fetch next " + max_row + " rows only"

    upr = queryscript.upper()
    splitter = upr.split()
    comparison = splitter[-2]
    filtering = re.search('SELECT (.*) FROM', upr)

    if comparison == "FROM":
        filtering2 = re.search('FROM (.*)', upr)
    else:
        filtering2 = re.search('FROM (.*) WHERE', upr)

    table_name = filtering2.group(1)
    result = filtering.group(1)
    data_names = result.split(',')

    import cx_Oracle
    dsn_tns = cx_Oracle.makedsn('', '', sid='')
    conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns)
    c = conn.cursor()
    c.execute(query_con)

    c.rowfactory = makeDictFactory(c)
    columnalldata = []

    response = HttpResponse(content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename="somefile.txt"'
    writer = csv.writer(response)
    if result == "*":
        connection = conn.cursor()
        connection.execute("select column_name from all_tab_cols where table_name = '"+table_name+"'")
        connection.rowfactory = makeDictFactory(connection)
        columnallname = []

        for rowDict in connection:
            columnallname.append(rowDict['COLUMN_NAME'])
            writer.writerow(rowDict[name] for name in columnallname)

        for row in c:
            columnalldata.append([row[data_name] for data_name in columnallname])
            writer.writerow([row[data_name] for data_name in columnallname])
    else:
        writer.writerow(data_names)

        for row in c:
            columnalldata.append([row[data_name] for data_name in data_names])
            writer.writerow([row[data_name] for data_name in data_names])

    return  response

i just want to do it automatically, dont want to press F12 then double click so the browser can download it

Body:
You are not setting correctly the content_type.

response = HttpResponse(content_type='text/plain')

And also setting the filename as TXT instead of CSV

response['Content-Disposition'] = 'attachment;
  filename="somefile.txt"'

The following code works just fine for me.

import csv
from django.http import HttpResponse

def CsvOutputView(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    writer = csv.writer(response)
    data = your_model.objects.all().values_list()
    for this_data in data:
        writer.writerow(this_data)

    return response

Hope it helps.


问:
Warning: mCrypt extension needs to be loaded for OpenCart to work
I'm trying to install OpenCart but get the following warning:
"Warning: mCrypt extension needs to be loaded for OpenCart to work!"

Since I'm a noob on this, could someone point me in the right direction on how to solve this? Google don't really help me out here :(

Thanks!

答:
I solved this issue by put in COMMENT the error message validation for mCrypt inside the file

```<code>/install/controller/install/step_2.php change inside private function validate()
//if (!function_exists('mcrypt_encrypt')) {
//  $this->error['warning'] = $this->language->get('error_mcrypt');
//}
</code>```

and voila

and after install this extension
Then, you may want to try this extension:

(https://www.opencart.com/index.php?rout ... n_id=35487)

Body:
I solved this issue by put in COMMENT the error message validation for mCrypt inside the file

/install/controller/install/step_2.php change inside private function validate()
//if (!function_exists('mcrypt_encrypt')) {
//  $this->error['warning'] = $this->language->get('error_mcrypt');
//}

and voila

and after install this extension
Then, you may want to try this extension:

(https://www.opencart.com/index.php?rout ... n_id=35487)


问:
Django aggregated field error on returning
I'm stubbling on a problem where I'm no longer shure if I'm doing something wrong or there is something wrong with the package.

I have a custom ordering filter of django-filter:

```<code>class CustomOrderingFilter(OrderingFilter):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.extra['choices'] += [
            ('trainingDates', 'Training Dates'),
            ('-trainingDates', 'Training Dates (descending)'),
        ]

    def filter(self, qs, value):
        if any(v in ['trainingDates', '-trainingDates'] for v in value):
            data = qs.annotate(first_date=Min('training_dates__date')).order_by('first_date')
            return data
        return super().filter(qs, value)
</code>```

When I add a debug point add the return statement I can see the field 'first_date' but when I continue I get the following error:

```<code>ERROR 2020-02-20 14:00:45,047 utils 24233 Traceback (most recent call last):
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/promise/promise.py", line 487, in _resolve_from_executor
    executor(resolve, reject)
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/promise/promise.py", line 754, in executor
    return resolve(f(*args, **kwargs))
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/graphql/execution/middleware.py", line 75, in make_it_promise
    return next(*args, **kwargs)
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/graphene_django/filter/fields.py", line 107, in connection_resolver
    **args
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/graphene_django/fields.py", line 164, in connection_resolver
    return on_resolve(iterable)
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/graphene_django/fields.py", line 118, in resolve_connection
    pageinfo_type=PageInfo,
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/graphql_relay/connection/arrayconnection.py", line 88, in connection_from_list_slice
    for i, node in enumerate(_slice)
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/query.py", line 274, in __iter__
    self._fetch_all()
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/query.py", line 55, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1087, in execute_sql
    sql, params = self.as_sql()
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 474, in as_sql
    extra_select, order_by, group_by = self.pre_sql_setup()
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 55, in pre_sql_setup
    order_by = self.get_order_by()
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 330, in get_order_by
    field, self.query.get_meta(), default_order=asc))
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 704, in find_ordering_name
    field, targets, alias, joins, path, opts, transform_function = self._setup_joins(pieces, opts, alias)
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 734, in _setup_joins
    field, targets, opts, joins, path, transform_function = self.query.setup_joins(pieces, opts, alias)
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1504, in setup_joins
    names[:pivot], opts, allow_many, fail_on_missing=True,
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1420, in names_to_path
    "Choices are: %s" % (name, ", ".join(available)))
graphql.error.located_error.GraphQLLocatedError: Cannot resolve keyword 'first_date' into field. Choices are: amount, comment, company, confirmed, course_name, deleted, email, first_name, function, id, invoice, last_name, phone_number, present, reminder, training_dates, unregistered_dates
</code>```

Does anyone know how to fix this? What I want is to order by the first date in a many-to-many relation. If you want to see more of the code let me know.

Edit #1: Model registration

```<code>class RegistrationManager(models.QuerySet):
    def active(self):
        return self.filter(deleted__isnull=True)

class Registration(models.Model):
    first_name = models.CharField(max_length=64)
    last_name = models.CharField(max_length=64)

    email = models.EmailField()
    phone_number = models.CharField(max_length=64, blank=True, null=True)

    amount = models.PositiveIntegerField(blank=True, null=True)
    invoice = models.BooleanField()

    company = models.CharField(max_length=64)
    function = models.CharField(max_length=64, blank=True, null=True)

    confirmed = models.BooleanField()
    reminder = models.BooleanField()
    present = models.BooleanField()

    training_dates = models.ManyToManyField('training.TrainingDate', related_name='registrations')
    unregistered_dates = models.ManyToManyField('training.TrainingDate', related_name='unregistered_registrations',
                                                blank=True)
    course_name = models.CharField(max_length=64, null=True, blank=True)

    comment = models.CharField(max_length=512, blank=True, null=True)
    deleted = models.DateTimeField(null=True, blank=True)

    objects = RegistrationManager.as_manager()

    def delete(self):
        self.deleted = datetime.now()
        self.save()

    def __str__(self):
        return "{} {} ({})".format(self.first_name, self.last_name, self.company)
</code>```

答:
I see you used graphene and found this issue in graphene. Seems like it has been fixed in this PR.
So probably updating graphene to version 2 would fix the issue.</p>

Body:
I'm stubbling on a problem where I'm no longer shure if I'm doing something wrong or there is something wrong with the package.

I have a custom ordering filter of django-filter:

class CustomOrderingFilter(OrderingFilter):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.extra['choices'] += [
            ('trainingDates', 'Training Dates'),
            ('-trainingDates', 'Training Dates (descending)'),
        ]

    def filter(self, qs, value):
        if any(v in ['trainingDates', '-trainingDates'] for v in value):
            data = qs.annotate(first_date=Min('training_dates__date')).order_by('first_date')
            return data
        return super().filter(qs, value)

When I add a debug point add the return statement I can see the field 'first_date' but when I continue I get the following error:

ERROR 2020-02-20 14:00:45,047 utils 24233 Traceback (most recent call last):
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/promise/promise.py", line 487, in _resolve_from_executor
    executor(resolve, reject)
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/promise/promise.py", line 754, in executor
    return resolve(f(*args, **kwargs))
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/graphql/execution/middleware.py", line 75, in make_it_promise
    return next(*args, **kwargs)
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/graphene_django/filter/fields.py", line 107, in connection_resolver
    **args
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/graphene_django/fields.py", line 164, in connection_resolver
    return on_resolve(iterable)
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/graphene_django/fields.py", line 118, in resolve_connection
    pageinfo_type=PageInfo,
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/graphql_relay/connection/arrayconnection.py", line 88, in connection_from_list_slice
    for i, node in enumerate(_slice)
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/query.py", line 274, in __iter__
    self._fetch_all()
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/query.py", line 55, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1087, in execute_sql
    sql, params = self.as_sql()
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 474, in as_sql
    extra_select, order_by, group_by = self.pre_sql_setup()
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 55, in pre_sql_setup
    order_by = self.get_order_by()
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 330, in get_order_by
    field, self.query.get_meta(), default_order=asc))
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 704, in find_ordering_name
    field, targets, alias, joins, path, opts, transform_function = self._setup_joins(pieces, opts, alias)
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 734, in _setup_joins
    field, targets, opts, joins, path, transform_function = self.query.setup_joins(pieces, opts, alias)
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1504, in setup_joins
    names[:pivot], opts, allow_many, fail_on_missing=True,
  File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1420, in names_to_path
    "Choices are: %s" % (name, ", ".join(available)))
graphql.error.located_error.GraphQLLocatedError: Cannot resolve keyword 'first_date' into field. Choices are: amount, comment, company, confirmed, course_name, deleted, email, first_name, function, id, invoice, last_name, phone_number, present, reminder, training_dates, unregistered_dates

Does anyone know how to fix this? What I want is to order by the first date in a many-to-many relation. If you want to see more of the code let me know.

Edit #1: Model registration

class RegistrationManager(models.QuerySet):
    def active(self):
        return self.filter(deleted__isnull=True)

class Registration(models.Model):
    first_name = models.CharField(max_length=64)
    last_name = models.CharField(max_length=64)

    email = models.EmailField()
    phone_number = models.CharField(max_length=64, blank=True, null=True)

    amount = models.PositiveIntegerField(blank=True, null=True)
    invoice = models.BooleanField()

    company = models.CharField(max_length=64)
    function = models.CharField(max_length=64, blank=True, null=True)

    confirmed = models.BooleanField()
    reminder = models.BooleanField()
    present = models.BooleanField()

    training_dates = models.ManyToManyField('training.TrainingDate', related_name='registrations')
    unregistered_dates = models.ManyToManyField('training.TrainingDate', related_name='unregistered_registrations',
                                                blank=True)
    course_name = models.CharField(max_length=64, null=True, blank=True)

    comment = models.CharField(max_length=512, blank=True, null=True)
    deleted = models.DateTimeField(null=True, blank=True)

    objects = RegistrationManager.as_manager()

    def delete(self):
        self.deleted = datetime.now()
        self.save()

    def __str__(self):
        return "{} {} ({})".format(self.first_name, self.last_name, self.company)


问:
Finding anchor text when there are tags there
I want to find the text between a pair of  tags that link to a given site

Here's the re string that I'm using to find the content:

```<code>r'''(<a([^<>]*)href=("|')(http://)?(www\.)?%s([^'"]*)("|')([^<>]*)>([^<]*))</a>''' % our_url
</code>```

The result will be something like this:

```<code>r'''(<a([^<>]*)href=("|')(http://)?(www\.)?stackoverflow.com([^'"]*)("|')([^<>]*)>([^<]*))</a>'''
</code>```

This is great for most links but it errors with a link with tags within it. I tried changing the final part of the regex from:

```<code>([^<]*))</a>'''
</code>```

to:

```<code>(.*))</a>'''
</code>```

But that just got everything on the page after the link, which I don't want. Are there any suggestions on what I can do to solve this?

答:
Do a non greedy search i.e. </p>

```<code>(.*?)
</code>```

OwnerDisplayName: Teifion

ContentLicense: CC BY-SA 2.5

Body:
I want to find the text between a pair of  tags that link to a given site

Here's the re string that I'm using to find the content:

r'''(<a([^<>]*)href=("|')(http://)?(www\.)?%s([^'"]*)("|')([^<>]*)>([^<]*))''' % our_url

The result will be something like this:

r'''(<a([^<>]*)href=("|')(http://)?(www\.)?stackoverflow.com([^'"]*)("|')([^<>]*)>([^<]*))'''

This is great for most links but it errors with a link with tags within it. I tried changing the final part of the regex from:

([^<]*))'''

to:

(.*))'''

But that just got everything on the page after the link, which I don't want. Are there any suggestions on what I can do to solve this?

Body:
Do a non greedy search i.e.

(.*?)

OwnerDisplayName: Andrew Cox


问:
Recursive regex for div tags(not trying to parse html with regex)
I have a bunch of wiki markup, sometimes people just throw random html down in the middle of wiki markup and somehow wikipedia just rolls with it, as it does for all kinds of other badly formed wiki markup.  I want to match everything inside the divs.

I need to recursively find all the
blah
 tags including div tags with other div tags inside them.  I am trying to match the div tags and everything inside of them.  I have this which I believe almost works:

```<code>new Regex(@"\<div.*?\> (?<DEPTH>)                   # opening
            (?>                # now match...
               [^(\<div.*?\>)(\<\/div\>)]+          # any characters except divs
            |                  # or
               \<div.*?\>  (?<DEPTH>)  # a opening div, increasing the depth counter
            |                  # or
               \<\/div\>  (?<-DEPTH>) # a closing div, decreasing the depth counter
            )*                 # any number of times
            (?(DEPTH)(?!))     # until the depth counter is zero again
          \<\/div\>                   # then match the closing fix",
            RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
</code>```

Maybe I should be using another methodology to parse this but at this point this is the final regex statement that I need.

Here is an example:

```<code><div class="infobox sisterproject" style="font-size: 90%; padding: .5em 1em 1em 1em;">
<div style="text-align:center;">
Find more about '''{{{display|{{{1|{{PAGENAME}}}}}}}}''' on Wikipedia's [[Wikipedia:Wikimedia sister projects|sister projects]]:
</div><!--
-->{{#ifeq:{{{wikt}}}|no||<!--
-->[[File:Wiktionary-logo-en.svg|25px|link=wikt:Special:Search/{{{wikt|{{{1|{{PAGENAME}}}}}}}}|Search Wiktionary]] [[wikt:Special:Search/{{{wikt|{{{1|{{PAGENAME}}}}}}}}|Definitions]] from Wiktionary<br />}}<!--
-->{{#ifeq:{{{b}}}|no||<!--
-->[[File:Wikibooks-logo.svg|25px|link=b:Special:Search/{{{b|{{{1|{{PAGENAME}}}}}}}}|Search Wikibooks]] [[b:Special:Search/{{{b|{{{1|{{PAGENAME}}}}}}}}|Textbooks]] from Wikibooks<br />}}<!--
-->{{#ifeq:{{{q}}}|no||<!--
-->[[File:Wikiquote-logo.svg|25px|link=q:Special:Search/{{{q|{{{1|{{PAGENAME}}}}}}}}|Search Wikiquote]] [[q:Special:Search/{{{q|{{{1|{{PAGENAME}}}}}}}}|Quotations]] from Wikiquote<br />}}<!--
-->{{#ifeq:{{{s}}}|no||{{#ifeq:{{{author|no}}}|yes|<!--
-->[[File:Wikisource-logo.svg|25px|link=s:Special:Search/Author:{{{s|{{{1|{{PAGENAME}}}}}}}}|Search Wikisource]] [[s:Special:Search/Author:{{{s|{{{1|{{PAGENAME}}}}}}}}|Source texts]] from Wikisource<br />|<!--
-->[[File:Wikisource-logo.svg|25px|link=s:Special:Search/{{{s|{{{1|{{PAGENAME}}}}}}}}|Search Wikisource]] [[s:Special:Search/{{{s|{{{1|{{PAGENAME}}}}}}}}|Source texts]] from Wikisource<br />}}}}<!--
-->{{#ifeq:{{{commons}}}|no||<!--
-->[[File:Commons-logo.svg|25px|link=commons:Special:Search/{{{commons|{{{1|{{PAGENAME}}}}}}}}|Search Commons]] [[commons:Special:Search/{{{commons|{{{1|{{PAGENAME}}}}}}}}|Images and media]] from Commons<br />}}<!--
-->{{#ifeq:{{{n}}}|no||<!--
-->[[File:Wikinews-logo.svg|25px|link=n:Special:Search/{{{n|{{{1|{{PAGENAME}}}}}}}}|Search Wikinews]] [[n:Special:Search/{{{n|{{{1|{{PAGENAME}}}}}}}}|News stories]] from Wikinews<br />}}<!--
-->{{#ifeq:{{{v}}}|no||<!--
-->[[File:Wikiversity-logo-Snorky.svg|25px|link=v:Special:Search/{{{v|{{{1|{{PAGENAME}}}}}}}}|Search Wikiversity]] [[v:Special:Search/{{{v|{{{1|{{PAGENAME}}}}}}}}|Learning resources]] from Wikiversity<br />}}<!--
-->{{#ifeq:{{{species<includeonly>|no</includeonly>}}}|no||<!--
-->[[File:Wikispecies-logo.svg|25px|link=species:Special:Search/{{{species<noinclude>|{{{1|{{PAGENAME}}}}}</noinclude>}}}|Search Wikispecies]] [[species:Special:Search/{{{species<noinclude>|{{{1|{{PAGENAME}}}}}</noinclude>}}}|{{{species<noinclude>|{{{1|{{PAGENAME}}}}}</noinclude>}}}]] from Wikispecies}}
</div><noinclude>
</code>```

Thanks

答:
```<code> new Regex(@"<div\b[^>]*>(?><div\b[^>]*>(?<DEPTH>)|</div>(?<-DEPTH>)|.?)*(?(DEPTH)(?!))</div>", RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
</code>```

In the time it took me to fix my expression I would not even be half way done with getting html agility pack up and working.

Body:
I have a bunch of wiki markup, sometimes people just throw random html down in the middle of wiki markup and somehow wikipedia just rolls with it, as it does for all kinds of other badly formed wiki markup.  I want to match everything inside the divs.

I need to recursively find all the
blah
 tags including div tags with other div tags inside them.  I am trying to match the div tags and everything inside of them.  I have this which I believe almost works:

new Regex(@"\
 (?<DEPTH>)                   # opening
            (?>                # now match...
               [^(\
)(\<\/div\>)]+          # any characters except divs
            |                  # or
               \
  (?<DEPTH>)  # a opening div, increasing the depth counter
            |                  # or
               \<\/div\>  (?<-DEPTH>) # a closing div, decreasing the depth counter
            )*                 # any number of times
            (?(DEPTH)(?!))     # until the depth counter is zero again
          \<\/div\>                   # then match the closing fix",
            RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);

Maybe I should be using another methodology to parse this but at this point this is the final regex statement that I need.

Here is an example:

Find more about '''{{{display|{{{1|{{PAGENAME}}}}}}}}''' on Wikipedia's [[Wikipedia:Wikimedia sister projects|sister projects]]:

{{#ifeq:{{{wikt}}}|no||[[File:Wiktionary-logo-en.svg|25px|link=wikt:Special:Search/{{{wikt|{{{1|{{PAGENAME}}}}}}}}|Search Wiktionary]] [[wikt:Special:Search/{{{wikt|{{{1|{{PAGENAME}}}}}}}}|Definitions]] from Wiktionary
}}{{#ifeq:{{{b}}}|no||[[File:Wikibooks-logo.svg|25px|link=b:Special:Search/{{{b|{{{1|{{PAGENAME}}}}}}}}|Search Wikibooks]] [[b:Special:Search/{{{b|{{{1|{{PAGENAME}}}}}}}}|Textbooks]] from Wikibooks
}}{{#ifeq:{{{q}}}|no||[[File:Wikiquote-logo.svg|25px|link=q:Special:Search/{{{q|{{{1|{{PAGENAME}}}}}}}}|Search Wikiquote]] [[q:Special:Search/{{{q|{{{1|{{PAGENAME}}}}}}}}|Quotations]] from Wikiquote
}}{{#ifeq:{{{s}}}|no||{{#ifeq:{{{author|no}}}|yes|[[File:Wikisource-logo.svg|25px|link=s:Special:Search/Author:{{{s|{{{1|{{PAGENAME}}}}}}}}|Search Wikisource]] [[s:Special:Search/Author:{{{s|{{{1|{{PAGENAME}}}}}}}}|Source texts]] from Wikisource
|[[File:Wikisource-logo.svg|25px|link=s:Special:Search/{{{s|{{{1|{{PAGENAME}}}}}}}}|Search Wikisource]] [[s:Special:Search/{{{s|{{{1|{{PAGENAME}}}}}}}}|Source texts]] from Wikisource
}}}}{{#ifeq:{{{commons}}}|no||[[File:Commons-logo.svg|25px|link=commons:Special:Search/{{{commons|{{{1|{{PAGENAME}}}}}}}}|Search Commons]] [[commons:Special:Search/{{{commons|{{{1|{{PAGENAME}}}}}}}}|Images and media]] from Commons
}}{{#ifeq:{{{n}}}|no||[[File:Wikinews-logo.svg|25px|link=n:Special:Search/{{{n|{{{1|{{PAGENAME}}}}}}}}|Search Wikinews]] [[n:Special:Search/{{{n|{{{1|{{PAGENAME}}}}}}}}|News stories]] from Wikinews
}}{{#ifeq:{{{v}}}|no||[[File:Wikiversity-logo-Snorky.svg|25px|link=v:Special:Search/{{{v|{{{1|{{PAGENAME}}}}}}}}|Search Wikiversity]] [[v:Special:Search/{{{v|{{{1|{{PAGENAME}}}}}}}}|Learning resources]] from Wikiversity
}}{{#ifeq:{{{species<includeonly>|no</includeonly>}}}|no||[[File:Wikispecies-logo.svg|25px|link=species:Special:Search/{{{species<noinclude>|{{{1|{{PAGENAME}}}}}</noinclude>}}}|Search Wikispecies]] [[species:Special:Search/{{{species<noinclude>|{{{1|{{PAGENAME}}}}}</noinclude>}}}|{{{species<noinclude>|{{{1|{{PAGENAME}}}}}</noinclude>}}}]] from Wikispecies}}

<noinclude>

Thanks

Body:
 new Regex(@"<div\b[^>]*>(?><div\b[^>]*>(?<DEPTH>)|</div>(?<-DEPTH>)|.?)*(?(DEPTH)(?!))</div>", RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);

In the time it took me to fix my expression I would not even be half way done with getting html agility pack up and working.


问:
Odoo 8: How can I send context to python method?

I want to send context to python method.

In xml, I have this code :

```<code><?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<record id="view_mim_wizardfor" model="ir.ui.view">
        <field name="name">mim.wizard.inherit</field>
        <field name="model">sale.order</field>
        <field name="inherit_id" ref="sale.view_order_form"/>
        <field name="arch" type="xml">

        <notebook position="before">
        <field name="entete"/>
        <field name="purchase_order_id" context="{'show_state': True}"/>
    </notebook>
            <group name="sale_total" position="after">
                <button name="action_mim_wizard"
                    attrs="{'invisible': [('state','not in',('draft','sent'))]}"
                    type="object" string="Ajout avancé"
                    class="oe_link oe_edit_only"/>
            </group>
        </field>
    </record>
</data>
</code>```

and I python I have this :

```<code>def name_get(self, cr, uid, ids, context=None):
    if context is None:
        context = {}
    res = []
    for record in self.browse(cr, uid, ids, context=context):
        _logger.info('==============context============================%s', context)
        name = record.name
        if context.get('show_state', False):
            name = '%s %s' % (name, record.state)
        res.append((record.id, name))
        _logger.info('==============name_get============================name_get==============')
    return res
</code>```

I don't get the 'show_state' in context, I don't know why.

Can you help me?

答:
I don't that context is going to be passed when you search for record, it's only passed when you try to create a record in fly (using create and edit option for example).

Instead pass the context in the action of the menu that opens sale.order records. for example the menu of Sales Orders you should change the context of its action like this, same thing for any menu you want to have this behavior in it:

```<code>   <record id="sale.action_orders" model="ir.actions.act_window">
        <field name="context">{'show_state': True}</field>
   </record>
</code>```

In this case when you search for any record in any many2one this key will be passed in the context and you should found in your method.

Body:
I want to send context to python method.

In xml, I have this code :

<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<record id="view_mim_wizardfor" model="ir.ui.view">
        <field name="name">mim.wizard.inherit</field>
        <field name="model">sale.order</field>
        <field name="inherit_id" ref="sale.view_order_form"/>
        <field name="arch" type="xml">

        <notebook position="before">
        <field name="entete"/>
        <field name="purchase_order_id" context="{'show_state': True}"/>
    </notebook>
            <group name="sale_total" position="after">
                <button name="action_mim_wizard"
                    attrs="{'invisible': [('state','not in',('draft','sent'))]}"
                    type="object" string="Ajout avancé"
                    class="oe_link oe_edit_only"/>
            </group>
        </field>
    </record>
</data>

and I python I have this :

def name_get(self, cr, uid, ids, context=None):
    if context is None:
        context = {}
    res = []
    for record in self.browse(cr, uid, ids, context=context):
        _logger.info('==============context============================%s', context)
        name = record.name
        if context.get('show_state', False):
            name = '%s %s' % (name, record.state)
        res.append((record.id, name))
        _logger.info('==============name_get============================name_get==============')
    return res

I don't get the 'show_state' in context, I don't know why.

Can you help me?

Body:
I don't that context is going to be passed when you search for record, it's only passed when you try to create a record in fly (using create and edit option for example).

Instead pass the context in the action of the menu that opens sale.order records. for example the menu of Sales Orders you should change the context of its action like this, same thing for any menu you want to have this behavior in it:

   <record id="sale.action_orders" model="ir.actions.act_window">
        <field name="context">{'show_state': True}</field>
   </record>

In this case when you search for any record in any many2one this key will be passed in the context and you should found in your method.


问:
Babel 7 and babel-polyfill
After updating to babel 7 beta, looks like babel polyfill does not transpile before bundle. I updated all scoped packages like this one "@babel/polyfill": "7.0.0-beta.36". And changed imports for two files from import 'babel-polyfill' to import '@babel/polyfill'. How to use babel/pollyfill with babel env and babel 7. Should I use babel/polyfill when use useBuiltIns: 'usage', with targets?

.babelrc.js

```<code>const nodeEnv = process.env.NODE_ENV || 'development'
let presetEnvConfig, plugins

if (nodeEnv === 'test'){
    presetEnvConfig = {targets: {node: 'current'}}
    plugins = ['istanbul']
} else {
    presetEnvConfig = {
        targets: {
            browsers: ['last 2 versions', 'ie >= 11']
        },
        modules: false
    }
    plugins = ['react-hot-loader/babel']
}

const config = {
    presets: [
        ['@babel/preset-env', presetEnvConfig],
        '@babel/react',
        '@babel/stage-2'
    ],
    plugins,
}
</code>```

types.js

```<code>import keyMirror from '../../../utils/keyMirror'

export default keyMirror({
    Unassign: null,
    Reassign: null,
    QuickAssignment: null,
}, 'TagAssignmentTypes')
</code>```

index.js

```<code> <Assignment
     assignee={assignee}
     tagId={tagId && tagId.toString(16)}
     assignmentType={assignmentTypes.Reassign}
     onRequestClose={() => this.setState({isAssignmentInProgress: false})}
     onChange={onChange}
    />
</code>```

答:
```<code>The following worked for me, add
**.babelrc**
{
"presets": [
  ["@babel/env"]
]
}

**app.js**
import "core-js/stable";
import "regenerator-runtime/runtime";

*Install as pointed by gianmarco*
npm i --save core-js regenerator-runtime
</code>```

Title: Babel 7 and babel-polyfill

Body:
After updating to babel 7 beta, looks like babel polyfill does not transpile before bundle. I updated all scoped packages like this one "@babel/polyfill": "7.0.0-beta.36". And changed imports for two files from import 'babel-polyfill' to import '@babel/polyfill'. How to use babel/pollyfill with babel env and babel 7. Should I use babel/polyfill when use useBuiltIns: 'usage', with targets?

.babelrc.js

const nodeEnv = process.env.NODE_ENV || 'development'
let presetEnvConfig, plugins

if (nodeEnv === 'test'){
    presetEnvConfig = {targets: {node: 'current'}}
    plugins = ['istanbul']
} else {
    presetEnvConfig = {
        targets: {
            browsers: ['last 2 versions', 'ie >= 11']
        },
        modules: false
    }
    plugins = ['react-hot-loader/babel']
}

const config = {
    presets: [
        ['@babel/preset-env', presetEnvConfig],
        '@babel/react',
        '@babel/stage-2'
    ],
    plugins,
}

types.js

import keyMirror from '../../../utils/keyMirror'

export default keyMirror({
    Unassign: null,
    Reassign: null,
    QuickAssignment: null,
}, 'TagAssignmentTypes')

index.js

 <Assignment
     assignee={assignee}
     tagId={tagId && tagId.toString(16)}
     assignmentType={assignmentTypes.Reassign}
     onRequestClose={() => this.setState({isAssignmentInProgress: false})}
     onChange={onChange}
    />


问:
DRF: Customising Exception Messages from the API
I'm starting to dive into DRF a little deeper of late, and I was wondering I would like to start customising the error messaging that gets return via the API for incorrect permissions, I'd like to wrap a little extra detail.

For example, if authentication credentials were not provided for an endpoint that is permission restricted, the API returns:

```<code>{
    "detail": "Authentication credentials were not provided."
}
</code>```

Which comes from line 171 from the rest_framework.exceptions: https://github.com/encode/django-rest-framework/blob/master/rest_framework/exceptions.py. Really, I'd like this to be consistent with the

```<code>{
    "success": false,
    "message": "Authentication credentials were not provided.",
    "data": null
}
</code>```

So, I assume I now need to begin customising my own exceptions.

How best should I go about doing this?

Perhaps it has some tie in with default_error_messages = {} inside the serializer ...

答:
You can override DRF's default exception handler and JSON parser on your settings.py:

```<code>REST_FRAMEWORK = {
    ...
    'EXCEPTION_HANDLER': 'helpers.exceptions.custom_exception_handler',
    'DEFAULT_RENDERER_CLASSES': [
        'helpers.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ]
}
</code>```

And then it's just a matter of customizing how to handle your exceptions and how to render the responses:

```<code>def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)
    # Customize your exception handling here
    return response
</code>```

And you can use the custom JSON renderer in case you need to do any extra formatting on the response, in my case I had to add a "status_code" to the payload:

```<code>class JSONRenderer(BaseJsonRenderer):
    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Render `data` into JSON, returning a bytestring.
        """
        <Base code from the original class...>

        response = renderer_context.get('response')
        if response and 200 <= response.status_code <= 299 and 'status_code' not in response.data:
            response.data = Errors.success(response.data)

        <Base code from the original class...>
</code>```

My Errors.success(response.data) was just a simpler way to merge the success status code to the data.

Body:
I'm starting to dive into DRF a little deeper of late, and I was wondering I would like to start customising the error messaging that gets return via the API for incorrect permissions, I'd like to wrap a little extra detail.

For example, if authentication credentials were not provided for an endpoint that is permission restricted, the API returns:

{
    "detail": "Authentication credentials were not provided."
}

Which comes from line 171 from the rest_framework.exceptions: https://github.com/encode/django-rest-framework/blob/master/rest_framework/exceptions.py. Really, I'd like this to be consistent with the

{
    "success": false,
    "message": "Authentication credentials were not provided.",
    "data": null
}

So, I assume I now need to begin customising my own exceptions.

How best should I go about doing this?

Perhaps it has some tie in with default_error_messages = {} inside the serializer ...

Body:
You can override DRF's default exception handler and JSON parser on your settings.py:

REST_FRAMEWORK = {
    ...
    'EXCEPTION_HANDLER': 'helpers.exceptions.custom_exception_handler',
    'DEFAULT_RENDERER_CLASSES': [
        'helpers.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ]
}

And then it's just a matter of customizing how to handle your exceptions and how to render the responses:

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)
    # Customize your exception handling here
    return response

And you can use the custom JSON renderer in case you need to do any extra formatting on the response, in my case I had to add a "status_code" to the payload:

class JSONRenderer(BaseJsonRenderer):
    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Render `data` into JSON, returning a bytestring.
        """
        <Base code from the original class...>

        response = renderer_context.get('response')
        if response and 200 <= response.status_code <= 299 and 'status_code' not in response.data:
            response.data = Errors.success(response.data)

        <Base code from the original class...>

My Errors.success(response.data) was just a simpler way to merge the success status code to the data.