问:
Convert 4 level nested JSON file to 1 level nested with Python
I have the 4 level nested JSON file below, that I would like to normalize to a one level nesting:

Input file is like this:

```<code>{
    "@index": "40",
    "row": [
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "text 1"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "text 2"
            }
          },
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "text 3"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "text 4"
            }
          }
        ]
      }
    ]
  }
</code>```

Desired output is like this:

```<code>{
    "@index": "40",
    "row": [
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "Text 1"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "Text 2"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "Text 3"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "Text 4"
          }
    ]
  }
</code>```

The code I have so far is this using pandas is below, but I don´t know how to continue to normalize to one level.

```<code>import json
import pandas as pd
from pandas.io.json import json_normalize #package for flattening json in pandas df

#load json object
with open('D:\Files\JSON\4Level.json') as f:
    d = json.load(f)

nycphil = json_normalize(d['row'])
print (nycphil.head(4))
</code>```

This is the current output tabulated, where shows that column is a nested element:

```<code>                                            column
0  [{'text': {'@fontName': 'Times New Roman', '@f...
1  [{'text': {'@fontName': 'Times New Roman', '@f...
2  [{'text': {'@fontName': 'Times New Roman', '@f...
</code>```

The print with one level nesting would be:

```<code>text.#text   text.@fontName text.@fontSize   ...   text.@width text.@x text.@y
0     Text 1  Times New Roman           12.0   ...        250.01   85.10  663.12
1     Text 2  Times New Roman            8.0   ...        348.98  121.10  675.36
2     Text 3  Times New Roman           12.0   ...         42.47  473.30  676.92
3     Text 4  Times New Roman           12.0   ...        433.61   85.10  690.72
</code>```

The Input/Output comparison is like this:

Maybe someone could help me with this. Thanks for any help.

UPDATE

In order to make a small sample in first sample input I showed, I removed some elements that seems to be are needed in your scripts to work. So now I show exactly the same structure as real file but with this input your scripts don't work. I think they need a little tweak but I've been trying and I don't know how to change them to get the same output with this new input. Maybe you can help me and sorry for not show the correct input from beginning.

```<code>{
   "document":{
      "page":[
         {
            "@index":"0",
            "image":{
               "@data":"ABC",
               "@format":"png",
               "@height":"620.00",
               "@type":"base64encoded",
               "@width":"450.00",
               "@x":"85.00",
               "@y":"85.00"
            }
         },
         {
            "@index":"1",
            "row":[
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text1",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"71.04",
                           "@x":"121.10",
                           "@y":"83.42"
                        }
                     }
                  ]
               },
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text2",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"101.07",
                           "@x":"121.10",
                           "@y":"124.82"
                        }
                     }
                  ]
               }
            ]
         },
         {
            "@index":"2",
            "row":[
               {
                  "column":{
                     "text":{
                        "#text":"Text3",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"363.44",
                        "@x":"85.10",
                        "@y":"69.62"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text4",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"382.36",
                        "@x":"85.10",
                        "@y":"83.42"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text5",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"435.05",
                        "@x":"85.10",
                        "@y":"97.22"
                     }
                  }
               }
            ]
         },
         {
            "@index":"3"
         }
      ]
   }
}
</code>```

Body:
I have the 4 level nested JSON file below, that I would like to normalize to a one level nesting:

Input file is like this:

{
    "@index": "40",
    "row": [
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "text 1"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "text 2"
            }
          },
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "text 3"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "text 4"
            }
          }
        ]
      }
    ]
  }

Desired output is like this:

{
    "@index": "40",
    "row": [
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "Text 1"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "Text 2"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "Text 3"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "Text 4"
          }
    ]
  }

The code I have so far is this using pandas is below, but I don´t know how to continue to normalize to one level.

import json
import pandas as pd
from pandas.io.json import json_normalize #package for flattening json in pandas df

#load json object
with open('D:\Files\JSON\4Level.json') as f:
    d = json.load(f)

nycphil = json_normalize(d['row'])
print (nycphil.head(4))

This is the current output tabulated, where shows that column is a nested element:

                                            column
0  [{'text': {'@fontName': 'Times New Roman', '@f...
1  [{'text': {'@fontName': 'Times New Roman', '@f...
2  [{'text': {'@fontName': 'Times New Roman', '@f...

The print with one level nesting would be:

text.#text   text.@fontName text.@fontSize   ...   text.@width text.@x text.@y
0     Text 1  Times New Roman           12.0   ...        250.01   85.10  663.12
1     Text 2  Times New Roman            8.0   ...        348.98  121.10  675.36
2     Text 3  Times New Roman           12.0   ...         42.47  473.30  676.92
3     Text 4  Times New Roman           12.0   ...        433.61   85.10  690.72

The Input/Output comparison is like this:

Maybe someone could help me with this. Thanks for any help.

UPDATE

In order to make a small sample in first sample input I showed, I removed some elements that seems to be are needed in your scripts to work. So now I show exactly the same structure as real file but with this input your scripts don't work. I think they need a little tweak but I've been trying and I don't know how to change them to get the same output with this new input. Maybe you can help me and sorry for not show the correct input from beginning.

{
   "document":{
      "page":[
         {
            "@index":"0",
            "image":{
               "@data":"ABC",
               "@format":"png",
               "@height":"620.00",
               "@type":"base64encoded",
               "@width":"450.00",
               "@x":"85.00",
               "@y":"85.00"
            }
         },
         {
            "@index":"1",
            "row":[
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text1",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"71.04",
                           "@x":"121.10",
                           "@y":"83.42"
                        }
                     }
                  ]
               },
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text2",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"101.07",
                           "@x":"121.10",
                           "@y":"124.82"
                        }
                     }
                  ]
               }
            ]
         },
         {
            "@index":"2",
            "row":[
               {
                  "column":{
                     "text":{
                        "#text":"Text3",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"363.44",
                        "@x":"85.10",
                        "@y":"69.62"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text4",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"382.36",
                        "@x":"85.10",
                        "@y":"83.42"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text5",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"435.05",
                        "@x":"85.10",
                        "@y":"97.22"
                     }
                  }
               }
            ]
         },
         {
            "@index":"3"
         }
      ]
   }
}

Body:
You can use a list comprehension:

d = {'@index': '40', 'row': [{'column': [{'text': {'@fontName': 'Times New Roman', '@fontSize': '12.0', '@x': '85.10', '@y': '663.12', '@width': '250.01', '@height': '12.00', '#text': 'text 1'}}]}, {'column': [{'text': {'@fontName': 'Times New Roman', '@fontSize': '8.0', '@x': '121.10', '@y': '675.36', '@width': '348.98', '@height': '8.04', '#text': 'text 2'}}, {'text': {'@fontName': 'Times New Roman', '@fontSize': '12.0', '@x': '473.30', '@y': '676.92', '@width': '42.47', '@height': '12.00', '#text': 'text 3'}}]}, {'column': [{'text': {'@fontName': 'Times New Roman', '@fontSize': '12.0', '@x': '85.10', '@y': '690.72', '@width': '433.61', '@height': '12.00', '#text': 'text 4'}}]}]}
new_d = {**d, 'row':[c['text'] for b in d['row'] for c in b['column']]}

import json
print(json.dumps(new_d, indent=4))

Output:

{
 "@index": "40",
 "row": [
     {
        "@fontName": "Times New Roman",
        "@fontSize": "12.0",
        "@x": "85.10",
        "@y": "663.12",
        "@width": "250.01",
        "@height": "12.00",
        "#text": "text 1"
     },
     {
        "@fontName": "Times New Roman",
        "@fontSize": "8.0",
        "@x": "121.10",
        "@y": "675.36",
        "@width": "348.98",
        "@height": "8.04",
        "#text": "text 2"
     },
     {
        "@fontName": "Times New Roman",
        "@fontSize": "12.0",
        "@x": "473.30",
        "@y": "676.92",
        "@width": "42.47",
        "@height": "12.00",
        "#text": "text 3"
     },
     {
        "@fontName": "Times New Roman",
        "@fontSize": "12.0",
        "@x": "85.10",
        "@y": "690.72",
        "@width": "433.61",
        "@height": "12.00",
        "#text": "text 4"
    }
  ]
}

Edit: to flatten a nested structure, you can use recursion with a generator:

def flatten(d, t = ["image", "text"]):
   for a, b in d.items():
      if a in t:
         yield b
      elif isinstance(b, dict):
         yield from flatten(b)
      elif isinstance(b, list):
         for i in b:
            yield from flatten(i)

d = {'document': {'page': [{'@index': '0', 'image': {'@data': 'ABC', '@format': 'png', '@height': '620.00', '@type': 'base64encoded', '@width': '450.00', '@x': '85.00', '@y': '85.00'}}, {'@index': '1', 'row': [{'column': [{'text': ''}, {'text': {'#text': 'Text1', '@fontName': 'Arial', '@fontSize': '12.0', '@height': '12.00', '@width': '71.04', '@x': '121.10', '@y': '83.42'}}]}, {'column': [{'text': ''}, {'text': {'#text': 'Text2', '@fontName': 'Arial', '@fontSize': '12.0', '@height': '12.00', '@width': '101.07', '@x': '121.10', '@y': '124.82'}}]}]}, {'@index': '2', 'row': [{'column': {'text': {'#text': 'Text3', '@fontName': 'Arial', '@fontSize': '12.0', '@height': '12.00', '@width': '363.44', '@x': '85.10', '@y': '69.62'}}}, {'column': {'text': {'#text': 'Text4', '@fontName': 'Arial', '@fontSize': '12.0', '@height': '12.00', '@width': '382.36', '@x': '85.10', '@y': '83.42'}}}, {'column': {'text': {'#text': 'Text5', '@fontName': 'Arial', '@fontSize': '12.0', '@height': '12.00', '@width': '435.05', '@x': '85.10', '@y': '97.22'}}}]}, {'@index': '3'}]}}
print(json.dumps(list(filter(None, flatten(d))), indent=4))

Output:

[
  {
    "@data": "ABC",
    "@format": "png",
    "@height": "620.00",
    "@type": "base64encoded",
    "@width": "450.00",
    "@x": "85.00",
    "@y": "85.00"
  },
  {
    "#text": "Text1",
    "@fontName": "Arial",
    "@fontSize": "12.0",
    "@height": "12.00",
    "@width": "71.04",
    "@x": "121.10",
    "@y": "83.42"
  },
  {
    "#text": "Text2",
    "@fontName": "Arial",
    "@fontSize": "12.0",
    "@height": "12.00",
    "@width": "101.07",
    "@x": "121.10",
    "@y": "124.82"
  },
  {
    "#text": "Text3",
    "@fontName": "Arial",
    "@fontSize": "12.0",
    "@height": "12.00",
    "@width": "363.44",
    "@x": "85.10",
    "@y": "69.62"
  },
  {
    "#text": "Text4",
    "@fontName": "Arial",
    "@fontSize": "12.0",
    "@height": "12.00",
    "@width": "382.36",
    "@x": "85.10",
    "@y": "83.42"
  },
  {
    "#text": "Text5",
    "@fontName": "Arial",
    "@fontSize": "12.0",
    "@height": "12.00",
    "@width": "435.05",
    "@x": "85.10",
    "@y": "97.22"
  }
]


来源: stackexchange

问:
Open specific URL on successful login to noVNC
I have setup vnc server and access it using noVnc, works really good.

On every successful login I want to do the following:

Open up google-chrome - This can be done by adding chrome to startup applications.

Open a different URL everytime, so this has to be passed from my browser during login. On every login open up it up on chrome.

Any pointers would be appreciated.

答:
I don't know much about VNC but you should be able to configure a script to run at startup if you can configure a program to run, say a .bat or .sh file.

Within this file you have a few ways of launching Chrome with a specific URL:

1. Shortcut files, and choosing one randomly.

You could have many in a folder, and your startup script chooses one at random.

```<code>╔══════════╦════════════════╦═════════════════════════════════╗
║ Protocol ║ Target         ║ Result                          ║
╠══════════╬════════════════╬═════════════════════════════════╣
║ HTTP     ║ www.google.com ║ googlechrome://www.google.com/  ║
║ HTTPS    ║ www.google.com ║ googlechromes://www.google.com/ ║
╚══════════╩════════════════╩═════════════════════════════════╝
</code>```

2. Launching Chrome directly with a random URL.

Make a script to pass the following, you can specify incognito by using the -incognito flag.

```<code>chrome.exe https://google.com
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I don't know much about VNC but you should be able to configure a script to run at startup if you can configure a program to run, say a .bat or .sh file.

Within this file you have a few ways of launching Chrome with a specific URL:

1. Shortcut files, and choosing one randomly.

You could have many in a folder, and your startup script chooses one at random.

╔══════════╦════════════════╦═════════════════════════════════╗
║ Protocol ║ Target         ║ Result                          ║
╠══════════╬════════════════╬═════════════════════════════════╣
║ HTTP     ║ www.google.com ║ googlechrome://www.google.com/  ║
║ HTTPS    ║ www.google.com ║ googlechromes://www.google.com/ ║
╚══════════╩════════════════╩═════════════════════════════════╝

2. Launching Chrome directly with a random URL.

Make a script to pass the following, you can specify incognito by using the -incognito flag.

chrome.exe https://google.com


问:
How to get rows of a most recent day in the ascending order of time way when reading csv file?
I want to get rows of a most recent day which is in ascending order of time way.

I get dataframe as follows:

```<code>    label      uId          adId    operTime                    siteId  slotId  contentId   netType
0   0          u147333631   3887    2019-03-30 15:01:55.617     10      30      2137        1
1   0          u146930169   1462    2019-03-31 09:51:15.275     3       32      1373        1
2   0          u139816523   2084    2019-03-27 08:10:41.769     10      30      2336        1
3   0          u106546472   1460    2019-03-31 08:51:41.085     3       32      1371        4
4   0          u106642861   2295    2019-03-27 22:58:03.679     3       32      2567        4
</code>```

Cause I get about 100 million rows in this csv file, it is impossible to load all this into my PC memory.

So I want to get rows of a most recent day in ascending order of time way when reading this csv files.

For examples, if the most recent day is on 2019-04-04, it will output as follows:

```<code>#this not a real data, just for examples.
    label      uId          adId    operTime                    siteId  slotId  contentId   netType
0   0          u147336431   3887    2019-04-04 00:08:42.315     1       54      2427        2
1   0          u146933269   1462    2019-04-04 01:06:16.417     30      36      1343        6
2   0          u139536523   2084    2019-04-04 02:08:58.079     15      23      1536        7
3   0          u106663472   1460    2019-04-04 03:21:13.050     32      45      1352        2
4   0          u121642861   2295    2019-04-04 04:36:08.653     3       33      3267        4
</code>```

Could anyone help me?

Thanks in advence.

Body:
I want to get rows of a most recent day which is in ascending order of time way.

I get dataframe as follows:

    label      uId          adId    operTime                    siteId  slotId  contentId   netType
0   0          u147333631   3887    2019-03-30 15:01:55.617     10      30      2137        1
1   0          u146930169   1462    2019-03-31 09:51:15.275     3       32      1373        1
2   0          u139816523   2084    2019-03-27 08:10:41.769     10      30      2336        1
3   0          u106546472   1460    2019-03-31 08:51:41.085     3       32      1371        4
4   0          u106642861   2295    2019-03-27 22:58:03.679     3       32      2567        4

Cause I get about 100 million rows in this csv file, it is impossible to load all this into my PC memory.

So I want to get rows of a most recent day in ascending order of time way when reading this csv files.

For examples, if the most recent day is on 2019-04-04, it will output as follows:

#this not a real data, just for examples.
    label      uId          adId    operTime                    siteId  slotId  contentId   netType
0   0          u147336431   3887    2019-04-04 00:08:42.315     1       54      2427        2
1   0          u146933269   1462    2019-04-04 01:06:16.417     30      36      1343        6
2   0          u139536523   2084    2019-04-04 02:08:58.079     15      23      1536        7
3   0          u106663472   1460    2019-04-04 03:21:13.050     32      45      1352        2
4   0          u121642861   2295    2019-04-04 04:36:08.653     3       33      3267        4

Could anyone help me?

Thanks in advence.

Body:
Seconding what anky_91 said, sort_values() will be helpful here.

import pandas as pd

df = pd.read_csv('file.csv')

# >>> df
#    label         uId  adId                 operTime  siteId  slotId  contentId  netType
# 0      0  u147333631  3887  2019-03-30 15:01:55.617      10      30       2137        1
# 1      0  u146930169  1462  2019-03-31 09:51:15.275       3      32       1373        1
# 2      0  u139816523  2084  2019-03-27 08:10:41.769      10      30       2336        1
# 3      0  u106546472  1460  2019-03-31 08:51:41.085       3      32       1371        4
# 4      0  u106642861  2295  2019-03-27 22:58:03.679       3      32       2567        4

sub_df = df[(df['operTime']>'2019-03-31') & (df['operTime']<'2019-04-01')]

# >>> sub_df
#    label         uId  adId                 operTime  siteId  slotId  contentId  netType
# 1      0  u146930169  1462  2019-03-31 09:51:15.275       3      32       1373        1
# 3      0  u106546472  1460  2019-03-31 08:51:41.085       3      32       1371        4

final_df = sub_df.sort_values(by=['operTime'])

# >>> final_df
#    label         uId  adId                 operTime  siteId  slotId  contentId  netType
# 3      0  u106546472  1460  2019-03-31 08:51:41.085       3      32       1371        4
# 1      0  u146930169  1462  2019-03-31 09:51:15.275       3      32       1373        1

I think you could also use a datetimeindex here; that might be necessary if the file is sufficiently large.


问:
create folder into maven package
I would like to include all the folders contained in "" within a folder that will be created in the package that will be called "common".

To be more explicite, I would like the tree structure to be in this form:

```<code>mypackage.jar
    | common
        | library
        | public
        | layout
        | application
        | rss
        | config
        | package.properties
        | .htaccess

</code>```

For the moment it works however the deliverable has this form:

```<code>mypackage.jar
    | library
    | public
    | layout
    | application
    | rss
    | config
    | package.properties
    | .htaccess
</code>```

I can't figure out how to do this operation, which seems rather simple. Sorry, this is the first time I've done maven scripts.

Thank you very much for your time :)

Here is my code :

```<code>    <build>
        <directory>target</directory>
        <finalName>${project.artifactId}-${project.version}</finalName>
        <outputDirectory>${project.build.directory}/pdc</outputDirectory>
        <resources>
            <resource>
            <directory>${project.basedir}</directory>
                <includes>
                    <include>library/</include>
                    <include>public/</include>
                    <include>layout/</include>
                    <include>application/</include>
                    <include>rss/</include>
                    <include>config/include.php</include>
                    <include>config/constant.php</include>
                    <include>.htaccess</include>
                    <include>package.properties</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <outputDirectory>target</outputDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
</code>```

答:
Add targetPath as below.

```<code><project>
   <build>
       ...
      <resources>
         <resource>
             <targetPath>common</targetPath>
               ...
          </resource>
      </resources>

      <testResources>
           ...
      </testResources>
      ...
  </build>
</project>
</code>```

Title: create folder into maven package

Body:
I would like to include all the folders contained in "" within a folder that will be created in the package that will be called "common".

To be more explicite, I would like the tree structure to be in this form:

mypackage.jar
    | common
        | library
        | public
        | layout
        | application
        | rss
        | config
        | package.properties
        | .htaccess

For the moment it works however the deliverable has this form:

mypackage.jar
    | library
    | public
    | layout
    | application
    | rss
    | config
    | package.properties
    | .htaccess

I can't figure out how to do this operation, which seems rather simple. Sorry, this is the first time I've done maven scripts.

Thank you very much for your time :)

Here is my code :

    <build>
        <directory>target</directory>
        <finalName>${project.artifactId}-${project.version}</finalName>
        <outputDirectory>${project.build.directory}/pdc</outputDirectory>
        <resources>
            <resource>
            <directory>${project.basedir}</directory>
                <includes>
                    <include>library/</include>
                    <include>public/</include>
                    <include>layout/</include>
                    <include>application/</include>
                    <include>rss/</include>
                    <include>config/include.php</include>
                    <include>config/constant.php</include>
                    <include>.htaccess</include>
                    <include>package.properties</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <outputDirectory>target</outputDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>

Body:
Add targetPath as below.

<project>
   <build>
       ...
      <resources>
         <resource>
             <targetPath>common</targetPath>
               ...
          </resource>
      </resources>

      <testResources>
           ...
      </testResources>
      ...
  </build>
</project>


问:
How to verify multiple method calls with different params
I have the following method that I wish to verify behaviour on.

```<code>public void methodToTest(Exception e, ActionErrors errors) {
    ...

    errors.add("exception.message",
            ActionMessageFactory.createErrorMessage(e.toString()));

    errors.add("exception.detail",
            ActionMessageFactory.createErrorMessage(e.getStackTrace()[0].toString()));

    ...
}
</code>```

In my @Test class I was hoping to do something like this to verify that errors.add() is called with "exception.message" and again with "exception.detail"

```<code>verify(errors).add(eq("exception.message"), any(ActionError.class));
verify(errors).add(eq("exception.detail"), any(ActionError.class));
</code>```

however Mockito complains as follows

```<code>Argument(s) are different! Wanted:
actionErrors.add(
    "exception.message",
    <any>
);

Actual invocation has different arguments:
actionErrors.add(
    "exception.detail",
    org.apache.struts.action.ActionError@38063806
);
</code>```

How can I tell Mockito to check for both values?

答:
In a similar way to @sendon1928 we can use:

```<code>Mockito.times(wantedInvocationCount)
</code>```

to make sure method was called exact number of times (preferable solution in my opinion). Afterwards, we can call

```<code>Mockito.verifyNoMoreInteractions(mock)
</code>```

To make sure that mock was not used further in any context. Full example:

```<code>Mockito.verify(mockObject, Mockito.times(wantedInvocationCount)).testMethod(Mockito.eq(1));

Mockito.verify(mockObject, Mockito.times(wantedInvocationCount)).testMethod(Mockito.eq(2));

Mockito.verifyNoMoreInteractions(mockObject)
</code>```

Body:
I have the following method that I wish to verify behaviour on.

public void methodToTest(Exception e, ActionErrors errors) {
    ...

    errors.add("exception.message",
            ActionMessageFactory.createErrorMessage(e.toString()));

    errors.add("exception.detail",
            ActionMessageFactory.createErrorMessage(e.getStackTrace()[0].toString()));

    ...
}

In my @Test class I was hoping to do something like this to verify that errors.add() is called with "exception.message" and again with "exception.detail"

verify(errors).add(eq("exception.message"), any(ActionError.class));
verify(errors).add(eq("exception.detail"), any(ActionError.class));

however Mockito complains as follows

Argument(s) are different! Wanted:
actionErrors.add(
    "exception.message",
    <any>
);

Actual invocation has different arguments:
actionErrors.add(
    "exception.detail",
    org.apache.struts.action.ActionError@38063806
);

How can I tell Mockito to check for both values?

Body:
In a similar way to @sendon1928 we can use:

Mockito.times(wantedInvocationCount)

to make sure method was called exact number of times (preferable solution in my opinion). Afterwards, we can call

Mockito.verifyNoMoreInteractions(mock)

To make sure that mock was not used further in any context. Full example:

Mockito.verify(mockObject, Mockito.times(wantedInvocationCount)).testMethod(Mockito.eq(1));

Mockito.verify(mockObject, Mockito.times(wantedInvocationCount)).testMethod(Mockito.eq(2));

Mockito.verifyNoMoreInteractions(mockObject)


问:
display clickable Amazon image links from JAVA to HTML
have a simple calculation that if the selected 2 radio is true it will display the correct link to the div where you can find it. the link is now clickable and opens the right website/URL thanks to User: imvain2 who helped with some of the code. Now when I put an Amazon link in it, it only displays the URL and not the Amazon affiliate clickable Image link. </p>

```<code> <div id="DisplayResults"></div>

    function create_link(url, target_obj){
        var a = document.createElement('a');
        var linkText = document.createTextNode(url);
        a.appendChild(linkText);
        a.title = url;
        a.href = url;
        target_obj.appendChild(a);
    }

function Selectport() {

var aOpticalin = document.getElementById("aOpticalin");
var aOpticalout = document.getElementById("aOpticalout");
var astereoout = document.getElementById("astereoout");
var astereoin = document.getElementById("astereoin");
var DisplayResults = document.getElementById("DisplayResults");

    if(astereoout.checked && aOpticalin.checked){

create_link(<iframe style="width:120px;height:240px;" marginwidth="0"
marginheight="0" scrolling="no" frameborder="0" src="//ws-
na.amazon-adsystem.com/widgets/q?
ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=
US&source=ac&ref=
tf_til& ad_type=product_link&tracking_id=whatsmycable-
20&marketplace=amazon&region=US&placement=B01HGHNCMW&asins=
B01HGHNCMW&linkId=
f3759832fc138a941ade9bde6128b083&show_border=
true&link_opens_in_new_window=
false&price_color=333333&title_color=000000&bg_color=d1d1d1">
</iframe>,DisplayResults);
    }
}
</code>```

答:
That function was originally created based on simply creating a link from a URL. If you would like to append actual precreated HTML, you can use innerHTML.

Make sure to wrap your code in single quotes (apostrophes) if your code has double quotes in it.

```<code>DisplayResults.innerHTML += 'Your iframe code goes here';
</code>```

Body:
have a simple calculation that if the selected 2 radio is true it will display the correct link to the div where you can find it. the link is now clickable and opens the right website/URL thanks to User: imvain2 who helped with some of the code. Now when I put an Amazon link in it, it only displays the URL and not the Amazon affiliate clickable Image link.

    function create_link(url, target_obj){
        var a = document.createElement('a');
        var linkText = document.createTextNode(url);
        a.appendChild(linkText);
        a.title = url;
        a.href = url;
        target_obj.appendChild(a);
    }

function Selectport() {

var aOpticalin = document.getElementById("aOpticalin");
var aOpticalout = document.getElementById("aOpticalout");
var astereoout = document.getElementById("astereoout");
var astereoin = document.getElementById("astereoin");
var DisplayResults = document.getElementById("DisplayResults");

    if(astereoout.checked && aOpticalin.checked){

create_link(<iframe style="width:120px;height:240px;" marginwidth="0"
marginheight="0" scrolling="no" frameborder="0" src="//ws-
na.amazon-adsystem.com/widgets/q?
ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=
US&source=ac&ref=
tf_til& ad_type=product_link&tracking_id=whatsmycable-
20&marketplace=amazon&region=US&placement=B01HGHNCMW&asins=
B01HGHNCMW&linkId=
f3759832fc138a941ade9bde6128b083&show_border=
true&link_opens_in_new_window=
false&price_color=333333&title_color=000000&bg_color=d1d1d1">
,DisplayResults);
    }
}

Body:
That function was originally created based on simply creating a link from a URL. If you would like to append actual precreated HTML, you can use innerHTML.

Make sure to wrap your code in single quotes (apostrophes) if your code has double quotes in it.

DisplayResults.innerHTML += 'Your iframe code goes here';


问:
awk: dealing with variable in if statement
I am trying to understand how awk deals with variables in if statements.

Here is a toy text file:

```<code>$ cat myscript.sh
#! /bin/bash

set -eu
set -o pipefail

IFS=$'\n\t'

for arg in $@; do
    echo "do something with file $arg"
done
</code>```

Now I want awk to print the longest line in the file.
I thought of doing that:

```<code>$  awk '{max = 0}{if (length($0) > max) {max = length($0)} else {}} END {print max}' myscript.sh
</code>```

But this print the length of the last line.
However, when I run the following:

```<code>awk '{if (length($0) > max) {max = length($0)} else {}}END{print max}' myscript.sh
</code>```

The outcome is correct and it prints the right length 35.

I cannot really understand why when I specify the max variable before the if statement, the condition is not recognized.
I am sure there is an easy explanation for the awk-gurus, but I personally cannot see it.

Thank you

答:
@Corentin already explained your problem so you should leave his/her answer as accepted but just FYI the right way to print the length of the longest line in the file is this:

```<code>awk '{cur=length()} cur>max{max=cur} END{print max+0}' myscript.sh
</code>```

That ensures max will be a number even if all lines are empty, doesn't call length() multiple times per line, and ensures you'll get numeric output even if the input is empty (just like wc does for empty files).

Body:
I am trying to understand how awk deals with variables in if statements.

Here is a toy text file:

$ cat myscript.sh
#! /bin/bash

set -eu
set -o pipefail

IFS=$'\n\t'

for arg in $@; do
    echo "do something with file $arg"
done

Now I want awk to print the longest line in the file.
I thought of doing that:

$  awk '{max = 0}{if (length($0) > max) {max = length($0)} else {}} END {print max}' myscript.sh

But this print the length of the last line.
However, when I run the following:

awk '{if (length($0) > max) {max = length($0)} else {}}END{print max}' myscript.sh

The outcome is correct and it prints the right length 35.

I cannot really understand why when I specify the max variable before the if statement, the condition is not recognized.
I am sure there is an easy explanation for the awk-gurus, but I personally cannot see it.

Thank you

Body:
@Corentin already explained your problem so you should leave his/her answer as accepted but just FYI the right way to print the length of the longest line in the file is this:

awk '{cur=length()} cur>max{max=cur} END{print max+0}' myscript.sh

That ensures max will be a number even if all lines are empty, doesn't call length() multiple times per line, and ensures you'll get numeric output even if the input is empty (just like wc does for empty files).


问:
Unable to understand this JSON parse error
JSON parse error while paring the JSON string

I have this below JS code and it is giving error. I would like to print the engineCode and value?

Thanks.

```<code>//I have update the code. Sorry about the confusion ...
let a = '{ "car": "Honda", "specs": {"engineCode": 1001} }';
let b = JSON.parse(a);
console.log(b); //prints json
//JSON.parse(b.engineCode); //please ignore this .....
JSON.parse(b.specs); //error while parsing and how to fix??

"SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at bajahisowi.js:7:6
    at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:13924
    at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:10866"
</code>```

答:
As others have already said, there is no need to re-parse it. Try console.log(b.specs.engineCode) considering your JSON looks like:

```<code>{
  "car": "Honda",
  "specs": {
    "engineCode": 1001
  }
}
</code>```

If you want really want to b.engineCode then refactor your JSON to reflect the following:

```<code>{
  "car": "Honda",
  "engineCode": 1001
}
</code>```

Body:
JSON parse error while paring the JSON string

I have this below JS code and it is giving error. I would like to print the engineCode and value?

Thanks.

//I have update the code. Sorry about the confusion ...
let a = '{ "car": "Honda", "specs": {"engineCode": 1001} }';
let b = JSON.parse(a);
console.log(b); //prints json
//JSON.parse(b.engineCode); //please ignore this .....
JSON.parse(b.specs); //error while parsing and how to fix??

"SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at bajahisowi.js:7:6
    at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:13924
    at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:10866"

Body:
As others have already said, there is no need to re-parse it. Try console.log(b.specs.engineCode) considering your JSON looks like:

{
  "car": "Honda",
  "specs": {
    "engineCode": 1001
  }
}

If you want really want to b.engineCode then refactor your JSON to reflect the following:

{
  "car": "Honda",
  "engineCode": 1001
}


问:
How can I remove text after a comma from a description field of Get-ADComputer?
I want to delete everything after the comma in the description field, so Text2 and Text3. Does anyone know how I can do this? I have heard something about regex but I don't know how to use it in this case.</p>

```<code>$time = (Get-Date).Adddays(-(1))
$Result = Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -Properties * | Select-Object Name,Description, @{N='LastLogonTimeStamp'; E={[DateTime]::FromFileTime($_.LastLogonTimeStamp)}}
$Result | Format-Table

Name          Description                        LastLogonTimeStamp
----          -----------                        ------------------
SRV-TEST      Text1, Text2, Text3                10-1-2019 09:45:00
</code>```

答:
Try this:

```<code>$time = (Get-Date).Adddays(-(1))
$Result = Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -Properties * | Select-Object Name, @{N='Description'; E={$_.Description -replace ',.*$','' }}, @{N='LastLogonTimeStamp'; E={[DateTime]::FromFileTime($_.LastLogonTimeStamp)}}
$Result | Format-Table
</code>```

For me it returns:

```<code>Name          Description                        LastLogonTimeStamp
----          -----------                        ------------------
SRV-TEST      Text1                              10-1-2019 09:45:00
</code>```

Body:
I want to delete everything after the comma in the description field, so Text2 and Text3. Does anyone know how I can do this? I have heard something about regex but I don't know how to use it in this case.

$time = (Get-Date).Adddays(-(1))
$Result = Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -Properties * | Select-Object Name,Description, @{N='LastLogonTimeStamp'; E={[DateTime]::FromFileTime($_.LastLogonTimeStamp)}}
$Result | Format-Table

Name          Description                        LastLogonTimeStamp
----          -----------                        ------------------
SRV-TEST      Text1, Text2, Text3                10-1-2019 09:45:00

Body:
Try this:

$time = (Get-Date).Adddays(-(1))
$Result = Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -Properties * | Select-Object Name, @{N='Description'; E={$_.Description -replace ',.*$','' }}, @{N='LastLogonTimeStamp'; E={[DateTime]::FromFileTime($_.LastLogonTimeStamp)}}
$Result | Format-Table

For me it returns:

Name          Description                        LastLogonTimeStamp
----          -----------                        ------------------
SRV-TEST      Text1                              10-1-2019 09:45:00


问:
How to convert stacked columns with duplicate indices into multiple unique columns with pandas?
I'm working with a cryptocurrency time-series data-set which has all of the different currencies vertically stacked. It has 3 columns for the date, currency and price. There date ranges are also different for each currency.

i.e.

```<code>>>> df
        Currency  Date    Price
0       0x        2017-08-16  0.111725
1       0x        2017-08-17  0.211486
2       0x        2017-08-18  0.283789
3       0x        2017-08-19  0.511434
4       0x        2017-08-20  0.429522
...     ...       ...         ...
657311  zurcoin   2018-02-04  0.003254
657312  zurcoin   2018-02-05  0.002774
657313  zurcoin   2018-02-06  0.001986
657314  zurcoin   2018-02-09  0.002684
657315  zurcoin   2018-02-10  0.002325
</code>```

I need to instead have a column for each currency's price and the date as the index with only unique dates. There will be plenty of null values which I intend to replace with 0's.

i.e

```<code>date          0x_price  10mtoken_price  1337coin_price  ...
2017-08-16    1         4               (NaN)->0        ...
2017-08-17    2         5               (NaN)->0        ...
2017-08-18    3         6               7               ...
...           ...       ...             ...             ...
</code>```

I've tried to iterate over the dataframe with a groupby as shown:

```<code>df2 = pd.DataFrame()
df2["date"] = df["Date"].unique()
df2.set_index("date", inplace=True)

for currency, group in df.groupby("Currency"):
df2.loc[df2.index.isin(group.Date), f"{currency}_price"] = group["Price"]
</code>```

This returned the desired column names and shape but the dataframe was filled with NaN's.

i.e.

```<code>date          0x_price  10mtoken_price  1337coin_price  ...
2017-08-16    NaN       NaN             NaN             ...
2017-08-17    NaN       NaN             NaN             ...
2017-08-18    NaN       NaN             NaN             ...
...           ...       ...             ...             ...
</code>```

I also tried to achieve the same thing with df.join() as shown:

```<code>df2 = pd.DataFrame()
df2["date"] = df["Date"].unique()
df2.set_index("date", inplace=True)

for currency, group in df.groupby("Currency"):
df2 = df2.join(group.set_index("Date")[["Price"]].rename(columns={"Price": f"{currency}_price"}))
</code>```

This didn't get to finish executing before freezing up my computer. Perhaps it's inefficient and I'm working with around 650,000 entries?

I haven't been able to find the same type of problem here and I haven't been able to figure out a solution after checking the documentation. I've probably missed something but hopefully I've described the problem sufficiently. Thanks in advance.

答:
I hope this'll work for your data size:</p>

```<code>for coin in set(df['Currency'].values):
    new_column_name = 'Price_'+coin
    df.assign(new_column_name = lambda x: x['Price']*(x['Currency']==coin))
df.fillna(0).drop('Currency',axis=1).set_index('Date')
</code>```

Body:
I'm working with a cryptocurrency time-series data-set which has all of the different currencies vertically stacked. It has 3 columns for the date, currency and price. There date ranges are also different for each currency.

i.e.

>>> df
        Currency  Date    Price
0       0x        2017-08-16  0.111725
1       0x        2017-08-17  0.211486
2       0x        2017-08-18  0.283789
3       0x        2017-08-19  0.511434
4       0x        2017-08-20  0.429522
...     ...       ...         ...
657311  zurcoin   2018-02-04  0.003254
657312  zurcoin   2018-02-05  0.002774
657313  zurcoin   2018-02-06  0.001986
657314  zurcoin   2018-02-09  0.002684
657315  zurcoin   2018-02-10  0.002325

I need to instead have a column for each currency's price and the date as the index with only unique dates. There will be plenty of null values which I intend to replace with 0's.

i.e

date          0x_price  10mtoken_price  1337coin_price  ...
2017-08-16    1         4               (NaN)->0        ...
2017-08-17    2         5               (NaN)->0        ...
2017-08-18    3         6               7               ...
...           ...       ...             ...             ...

I've tried to iterate over the dataframe with a groupby as shown:

df2 = pd.DataFrame()
df2["date"] = df["Date"].unique()
df2.set_index("date", inplace=True)

for currency, group in df.groupby("Currency"):
df2.loc[df2.index.isin(group.Date), f"{currency}_price"] = group["Price"]

This returned the desired column names and shape but the dataframe was filled with NaN's.

i.e.

date          0x_price  10mtoken_price  1337coin_price  ...
2017-08-16    NaN       NaN             NaN             ...
2017-08-17    NaN       NaN             NaN             ...
2017-08-18    NaN       NaN             NaN             ...
...           ...       ...             ...             ...

I also tried to achieve the same thing with df.join() as shown:

df2 = pd.DataFrame()
df2["date"] = df["Date"].unique()
df2.set_index("date", inplace=True)

for currency, group in df.groupby("Currency"):
df2 = df2.join(group.set_index("Date")[["Price"]].rename(columns={"Price": f"{currency}_price"}))

This didn't get to finish executing before freezing up my computer. Perhaps it's inefficient and I'm working with around 650,000 entries?

I haven't been able to find the same type of problem here and I haven't been able to figure out a solution after checking the documentation. I've probably missed something but hopefully I've described the problem sufficiently. Thanks in advance.

Body:
I hope this'll work for your data size:

for coin in set(df['Currency'].values):
    new_column_name = 'Price_'+coin
    df.assign(new_column_name = lambda x: x['Price']*(x['Currency']==coin))
df.fillna(0).drop('Currency',axis=1).set_index('Date')


问:
Decrypting in Python an string encrypted using .NET
I am trying to encrypt a string using C# and decrypt it using Python. The encryption/decryption part works as expected (i.e. I am able to decrypt the string I originally encrypted). However the string returned by Python has 2 extra bytes at the beginning and each character is separated by a space.

```<code>**Original string** (before encryption -- encrypted using C#) = "Something you want to keep private with AES"

**Decrypted string** (using Python) = "��S o m e t h i n g  y o u   w a n t   t o   k e e p   p r i v a t e   w i t h  A E S"
</code>```

Why am I getting these two extra bytes at the beginning of the string? Why all those spaces in the decrypted string? Any idea why?

Thanks!

Encryption with C#

```<code>public static string Encrypt<T>(string value, string password, string salt)
         where T : SymmetricAlgorithm, new()
{
    DeriveBytes rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));

    SymmetricAlgorithm algorithm = new T();

    byte[] rgbKey = rgb.GetBytes(algorithm.KeySize >> 3);
    byte[] rgbIV = rgb.GetBytes(algorithm.BlockSize >> 3);

    ICryptoTransform transform = algorithm.CreateEncryptor(rgbKey, rgbIV);

    using (MemoryStream buffer = new MemoryStream())
    {
        using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Write))
        {
            using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
            {
                writer.Write(value);
            }
        }

        return Convert.ToBase64String(buffer.ToArray());
    }
}

string plain = "Something you want to keep private with AES";
string encrypted = CipherUtility.Encrypt<AesManaged>(plain, "password", "salt");
</code>```

Decryption with Python + pycrypto

```<code>import base64, sys
import Crypto.Cipher.AES

password = base64.b64decode('PSCIQGfoZidjEuWtJAdn1JGYzKDonk9YblI0uv96O8s=') # See rgbKey
salt = base64.b64decode('ehjtnMiGhNhoxRuUzfBOXw==') # See rgbIV
aes = Crypto.Cipher.AES.new(password, Crypto.Cipher.AES.MODE_CBC, salt)
text = base64.b64decode('QpHn/fnraLswwI2Znt1xTaBzRtDqO4V5QI78jLOlVsbvaIs0yXMUlqJhQtK+su2hYn28G2vNyLkj0zLOs+RIjElCSqJv1aK/Yu8uY07oAeStqRt4u/DVUzoWlxdrlF0u')

print aes.decrypt(text)
</code>```

答:
```<code> def decrypted(self) -> str:
    _pwd = base64.b64decode(self._key)
    _salt = base64.b64decode(self._salt)
    _aes = Crypto.Cipher.AES.new(_pwd, Crypto.Cipher.AES.MODE_CBC, _salt)
    _text = base64.b64decode(self._encrypted_str)
    _decode = _aes.decrypt(_text).decode('utf-16')
    _regex = '[a-zA-Z0-9 +-,\/ ]+'
    return re.findall(_regex, _decode)
</code>```

is using regex

ContentLicense: CC BY-SA 3.0

Body:
I am trying to encrypt a string using C# and decrypt it using Python. The encryption/decryption part works as expected (i.e. I am able to decrypt the string I originally encrypted). However the string returned by Python has 2 extra bytes at the beginning and each character is separated by a space.

**Original string** (before encryption -- encrypted using C#) = "Something you want to keep private with AES"

**Decrypted string** (using Python) = "��S o m e t h i n g  y o u   w a n t   t o   k e e p   p r i v a t e   w i t h  A E S"

Why am I getting these two extra bytes at the beginning of the string? Why all those spaces in the decrypted string? Any idea why?

Thanks!

Encryption with C#

public static string Encrypt<T>(string value, string password, string salt)
         where T : SymmetricAlgorithm, new()
{
    DeriveBytes rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));

    SymmetricAlgorithm algorithm = new T();

    byte[] rgbKey = rgb.GetBytes(algorithm.KeySize >> 3);
    byte[] rgbIV = rgb.GetBytes(algorithm.BlockSize >> 3);

    ICryptoTransform transform = algorithm.CreateEncryptor(rgbKey, rgbIV);

    using (MemoryStream buffer = new MemoryStream())
    {
        using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Write))
        {
            using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
            {
                writer.Write(value);
            }
        }

        return Convert.ToBase64String(buffer.ToArray());
    }
}

string plain = "Something you want to keep private with AES";
string encrypted = CipherUtility.Encrypt<AesManaged>(plain, "password", "salt");

Decryption with Python + pycrypto

import base64, sys
import Crypto.Cipher.AES

password = base64.b64decode('PSCIQGfoZidjEuWtJAdn1JGYzKDonk9YblI0uv96O8s=') # See rgbKey
salt = base64.b64decode('ehjtnMiGhNhoxRuUzfBOXw==') # See rgbIV
aes = Crypto.Cipher.AES.new(password, Crypto.Cipher.AES.MODE_CBC, salt)
text = base64.b64decode('QpHn/fnraLswwI2Znt1xTaBzRtDqO4V5QI78jLOlVsbvaIs0yXMUlqJhQtK+su2hYn28G2vNyLkj0zLOs+RIjElCSqJv1aK/Yu8uY07oAeStqRt4u/DVUzoWlxdrlF0u')

print aes.decrypt(text)

Body:
 def decrypted(self) -> str:
    _pwd = base64.b64decode(self._key)
    _salt = base64.b64decode(self._salt)
    _aes = Crypto.Cipher.AES.new(_pwd, Crypto.Cipher.AES.MODE_CBC, _salt)
    _text = base64.b64decode(self._encrypted_str)
    _decode = _aes.decrypt(_text).decode('utf-16')
    _regex = '[a-zA-Z0-9 +-,\/ ]+'
    return re.findall(_regex, _decode)

is using regex


问:
Area under curve cyclic voltammetry within specific bound
I want to calculate the integral area under the curve for I>0 and V<0.4, I could not do it with trapz function, please help!

I have tried both integral and trapz functions but of no use! I could not attach the text file so if you need it for debugging, please let me know how to do that.

```<code>close all
clear all
clc
c=Constants;
F = dir('*.txt');
nF = length(F) ;
count = 0 ;
for ii = 1:nF
fname = F(ii).name ;
end
filename = fullfile(fname);
fileID = fopen(filename);
formatSpec = '%s';
N = 1;
c_text = textscan(fileID,formatSpec,N,'Delimiter',' ');
c_data = textscan(fileID,'%f %f');
v=c_data{1};
i=c_data{2};

idi = i>0;
idv=v<0.4;
v_pos = v(idv);
i_pos= i(idi);
% v_limit=v_pos(idv)

inty = trapz(v_pos, i_pos)

setvalue = 0.06;
[~,closestIndex] = min(abs(setvalue-v_pos));
vm= v_pos(closestIndex)

setvalue = 0.4;
[~,closestIndex] = min(abs(setvalue-v_pos));
vf= v_pos(closestIndex)
ifinal=i_pos(closestIndex)

figure(1)
plot(v,i)
hold on
hold off
grid
area=inty-[(vf-vm)*ifinal]
yline(0);

cvarea=area/1000;
qh=cvarea/c.cvscanrate;
active_area=qh/(c.qpt*c.A);
fprintf('Active surface area of catalyst %g cm^2 Pt/ cm^2 electrode \n', active_area);
</code>```

Error using trapz (line 66)
Point spacing must be a scalar specifying uniform spacing or a vector of x-coordinates for each data point.

答:
There is several method to compute a discret integral.

Here is the Riemann sum approximation

And here is the trapezoidal rule used by trapz

The Riemann sum is the easiest to compute.

You simply need the width and the height of each rectangle (so we can calculate the area).

```<code>%Dummy data:
x = 0:0.1:10;
y = x.^2;
%Width
X = diff(x)
%Height
Y = conv(y,ones(2,1),'valid')/2
%Integral:
I = sum(X.*Y)
</code>```

This method would work even if the point spacing are not uniform.

Body:
I want to calculate the integral area under the curve for I>0 and V<0.4, I could not do it with trapz function, please help!

I have tried both integral and trapz functions but of no use! I could not attach the text file so if you need it for debugging, please let me know how to do that.

close all
clear all
clc
c=Constants;
F = dir('*.txt');
nF = length(F) ;
count = 0 ;
for ii = 1:nF
fname = F(ii).name ;
end
filename = fullfile(fname);
fileID = fopen(filename);
formatSpec = '%s';
N = 1;
c_text = textscan(fileID,formatSpec,N,'Delimiter',' ');
c_data = textscan(fileID,'%f %f');
v=c_data{1};
i=c_data{2};

idi = i>0;
idv=v<0.4;
v_pos = v(idv);
i_pos= i(idi);
% v_limit=v_pos(idv)

inty = trapz(v_pos, i_pos)

setvalue = 0.06;
[~,closestIndex] = min(abs(setvalue-v_pos));
vm= v_pos(closestIndex)

setvalue = 0.4;
[~,closestIndex] = min(abs(setvalue-v_pos));
vf= v_pos(closestIndex)
ifinal=i_pos(closestIndex)

figure(1)
plot(v,i)
hold on
hold off
grid
area=inty-[(vf-vm)*ifinal]
yline(0);

cvarea=area/1000;
qh=cvarea/c.cvscanrate;
active_area=qh/(c.qpt*c.A);
fprintf('Active surface area of catalyst %g cm^2 Pt/ cm^2 electrode \n', active_area);

Error using trapz (line 66)
Point spacing must be a scalar specifying uniform spacing or a vector of x-coordinates for each data point.

Body:
There is several method to compute a discret integral.

Here is the Riemann sum approximation

And here is the trapezoidal rule used by trapz

The Riemann sum is the easiest to compute.

You simply need the width and the height of each rectangle (so we can calculate the area).

%Dummy data:
x = 0:0.1:10;
y = x.^2;
%Width
X = diff(x)
%Height
Y = conv(y,ones(2,1),'valid')/2
%Integral:
I = sum(X.*Y)

This method would work even if the point spacing are not uniform.


问:
multiple INApp purchase request for different product in tableView
multiple in app purchaseI am working a music player application, the user need to purchase the albums before they start hearing it, I have attached a sample purchase screen. when the user tap it it should move to inApp purchase . The purchase type is non- consumable they need to pay only once.

I am having a table view with list of albums in it, if I purchase the first index album, it is working fine when I move to second index it was stating like already purchased.

I have used SwiftyStoreKit pod for the inappropriate purchase and everything is working as I expected. but I don't know how to handle tableview with n number of cell.

```<code>   //INAPP purchase swift guy

func getinfo (purchase: RegisterPurchase) {
    NetworkActivityIndicatioManager.NetworkoperationStarted()
    SwiftyStoreKit.retrieveProductsInfo([bundleId + "." + purchase.rawValue]) { (result) in
        NetworkActivityIndicatioManager.NetworkOperationFinished()
        self.showAlert(self.alertForProductRetrievalInfo(result))
    }
}

func purchase(purchase: RegisterPurchase) {
    NetworkActivityIndicatioManager.NetworkoperationStarted()
    SwiftyStoreKit.purchaseProduct(bundleId + "." + purchase.rawValue, atomically: true) { result in
        NetworkActivityIndicatioManager.NetworkOperationFinished()

        if case .success(let purchase) = result {
            let downloads = purchase.transaction.downloads
            if !downloads.isEmpty {
                SwiftyStoreKit.start(downloads)
            }
            // Deliver content from server, then:
            if purchase.needsFinishTransaction {
                SwiftyStoreKit.finishTransaction(purchase.transaction)
            }
        }

        if let alert = self.alertForPurchaseResult(result) {
            self.showAlert(alert)
        }
    }
}
</code>```

答:
Issue is with your product type. If you want to make the product purchasable again, you should use consumable purchase, NOT non-consumable.

Non-consumable product can be purchased only once for an iTunes
  account.

For your case, you can change the product type to consumable, then save this purchase in server and link with the user. This way, you can unlock the album if user purchased before.

Body:
multiple in app purchaseI am working a music player application, the user need to purchase the albums before they start hearing it, I have attached a sample purchase screen. when the user tap it it should move to inApp purchase . The purchase type is non- consumable they need to pay only once.

I am having a table view with list of albums in it, if I purchase the first index album, it is working fine when I move to second index it was stating like already purchased.

I have used SwiftyStoreKit pod for the inappropriate purchase and everything is working as I expected. but I don't know how to handle tableview with n number of cell.

   //INAPP purchase swift guy

func getinfo (purchase: RegisterPurchase) {
    NetworkActivityIndicatioManager.NetworkoperationStarted()
    SwiftyStoreKit.retrieveProductsInfo([bundleId + "." + purchase.rawValue]) { (result) in
        NetworkActivityIndicatioManager.NetworkOperationFinished()
        self.showAlert(self.alertForProductRetrievalInfo(result))
    }
}

func purchase(purchase: RegisterPurchase) {
    NetworkActivityIndicatioManager.NetworkoperationStarted()
    SwiftyStoreKit.purchaseProduct(bundleId + "." + purchase.rawValue, atomically: true) { result in
        NetworkActivityIndicatioManager.NetworkOperationFinished()

        if case .success(let purchase) = result {
            let downloads = purchase.transaction.downloads
            if !downloads.isEmpty {
                SwiftyStoreKit.start(downloads)
            }
            // Deliver content from server, then:
            if purchase.needsFinishTransaction {
                SwiftyStoreKit.finishTransaction(purchase.transaction)
            }
        }

        if let alert = self.alertForPurchaseResult(result) {
            self.showAlert(alert)
        }
    }
}


问:
iOS Menu title to navbar title animation
I am trying to achieve a menu translation effect similar to the gif below (from the excellent iOS Sky Guide app), where the large title of the previous menu animates up to become the navigation bar 'back' button.

I am wondering what is the cleanest way to implement such an effect in swift. I've looked through various libraries for anything similar but have drawn a blank.

Can someone put me on the right track? Thanks!

答:
Have you tried the UINavigationBar.prefersLargeTitles property?

Reference: https://developer.apple.com/documentation/uikit/uinavigationbar/2908999-preferslargetitles


问:
Flutter Reduce padding between DataRows in DataTable
How i want it to look like (before -> after) :

Is it possible to do it like in this image?

edit: Solved it like Hugo said, by copying the code of data_table.dart into a new file, changing the _dataRowHeight, and using that instead.

答:
After quickly glancing at the DataTable code it looks like padding is a private constant used for some private build methods within that class. </p>

```<code>static const double _tablePadding = 24.0;
</code>```

<p>If you really need to use the DataTable widget then you could create your own class that extends DataTable and then override its build function to create your own _buildDataCell function where you could supply your own dimensions. </p>

Body:
After quickly glancing at the DataTable code it looks like padding is a private constant used for some private build methods within that class.

static const double _tablePadding = 24.0;

If you really need to use the DataTable widget then you could create your own class that extends DataTable and then override its build function to create your own _buildDataCell function where you could supply your own dimensions.


问:
How to write response filter?
Is there a way to handle only response in a filter .

Is the code written below correct ?

```<code>  public void doFilter(request , response , chain) {
        //code to handle request
          chain.doFilter(request, response);
        //code to handle response .
  }
</code>```

答:
Your code seems to be fine.

If you only want to handle the response, you can just put your code in the //Code to handle response . section and do whatever you like.

If you want to do something with the output, you will have to provide a special response wrapper that handles the outputstream in the response where the servlet (and other filters) might write to.

Title: How to write response filter?

Body:
Is there a way to handle only response in a filter .

Is the code written below correct ?

  public void doFilter(request , response , chain) {
        //code to handle request
          chain.doFilter(request, response);
        //code to handle response .
  }


问:
How to Update if a Row Exists on Another Table (SQL)
I am trying to update a column on a itemTable if a row with a matching iid exists on a correlated table.

itemMeta is a NoSQL style table, with duplicate iids per item on the table, and itemTable is a relational table.

```<code>update itemTable it
set hasAttributes = (select
  case when select count(1) from itemMeta where (im.iid = it.iid)
  then 'Y'
  else 'N' end)
from itemMeta im
where (im.iid = it.iid)
</code>```

How do I set the column to Y on itemTable if a row with a matching iid exists on itemMeta?

答:
This would work in most databases, including SQL Server:

```<code>update itemTable
    set hasAttributes = (case when exists (select 1
                                           from itemMeta im
                                           where im.iid = itemTable.iid
                                          )
                              then 'Y' else 'N'
                         end);
</code>```

If you just want to update the value to 'Y' if the value exists (and leave the existing value if present), then I would recommend:

```<code>update itemTable
    set hasAttributes = 'Y'
    where exists (select 1
                  from itemMeta im
                  where im.iid = itemTable.iid
                 );
</code>```

This limits the rows being updated, so it should have better performance.

And, if you care about performance, you want an index on itemMeta(iid).

Body:
I am trying to update a column on a itemTable if a row with a matching iid exists on a correlated table.

itemMeta is a NoSQL style table, with duplicate iids per item on the table, and itemTable is a relational table.

update itemTable it
set hasAttributes = (select
  case when select count(1) from itemMeta where (im.iid = it.iid)
  then 'Y'
  else 'N' end)
from itemMeta im
where (im.iid = it.iid)

How do I set the column to Y on itemTable if a row with a matching iid exists on itemMeta?

Body:
This would work in most databases, including SQL Server:

update itemTable
    set hasAttributes = (case when exists (select 1
                                           from itemMeta im
                                           where im.iid = itemTable.iid
                                          )
                              then 'Y' else 'N'
                         end);

If you just want to update the value to 'Y' if the value exists (and leave the existing value if present), then I would recommend:

update itemTable
    set hasAttributes = 'Y'
    where exists (select 1
                  from itemMeta im
                  where im.iid = itemTable.iid
                 );

This limits the rows being updated, so it should have better performance.

And, if you care about performance, you want an index on itemMeta(iid).


问:
Coding a subtraction loop that takes in a list
I am making a calculator and need a subtraction loop for the code to work. Right now it is scanning the list but only doing the first and last numbers not the entire list.

```<code>if(a.equals("Subtract")) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        System.out.println("Enter integers one at a time in order");
        System.out.println("When completed type done");
        while (scan.hasNextInt()) {
            list.add(scan.nextInt());
        }
        Integer[] nums = list.toArray(new Integer[0]);
        for (int i = 0; i < nums.length-1; i++) {
            sum = nums[0];
            sum = sum - nums[i+1];
        }
        System.out.println("Your total is " + sum);
        System.out.println("-----------------------------");
        main(args);
        }
</code>```

Only subtracts the first and last numbers of loop not entire loop in order

答:
You're re-initializing sum on each iteration of the loop, to the value of the first element:

```<code>sum = nums[0];
</code>```

You should do this before the loop.

Body:
I am making a calculator and need a subtraction loop for the code to work. Right now it is scanning the list but only doing the first and last numbers not the entire list.

if(a.equals("Subtract")) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        System.out.println("Enter integers one at a time in order");
        System.out.println("When completed type done");
        while (scan.hasNextInt()) {
            list.add(scan.nextInt());
        }
        Integer[] nums = list.toArray(new Integer[0]);
        for (int i = 0; i < nums.length-1; i++) {
            sum = nums[0];
            sum = sum - nums[i+1];
        }
        System.out.println("Your total is " + sum);
        System.out.println("-----------------------------");
        main(args);
        }

Only subtracts the first and last numbers of loop not entire loop in order

Body:
You're re-initializing sum on each iteration of the loop, to the value of the first element:

sum = nums[0];

You should do this before the loop.


问:
Order a Map that contains String, but strings might represent a number
I have this kind of values inside a Map:

```<code>Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1,"mark");
map.put(2,"1.1");
map.put(3,"google");
map.put(4,"12");
map.put(5,"2.2);
</code>```

I need to order this Map, ordering both numbers and strings.

What I get now is this (as you can see numbers are not "ordered" since are String)

```<code>1.1
12
2.2
google
mark
</code>```

What I should  get is:

```<code>1.1
2.2
12
google
mark
</code>```

How can I do it? I'm a little confused.

答:
You can't order a Map by entry value. SortedMap e.g. TreeMap allows to order the entries by key. It seems you might be using a wrong data structure.

In your example you can define a function that will leniently parse a double and return Double.NaN instead of an exception:

```<code>private double lenientParseDouble(String s) {
    try {
        return Double.parseDouble(s);
    } catch (NumberFormatException ex) {
        return Double.NaN;
    }
}
</code>```

As per Double.compare() docs:

Double.NaN is considered by this method to be equal to itself and greater than all other double values (including Double.POSITIVE_INFINITY).

and then use it as part of the Comparator chain

```<code>map.values().stream()
        .sorted(Comparator.comparingDouble(this::lenientParseDouble).thenComparing(Function.identity()))
        .forEach(System.out::println);
</code>```

Body:
I have this kind of values inside a Map:

Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1,"mark");
map.put(2,"1.1");
map.put(3,"google");
map.put(4,"12");
map.put(5,"2.2);

I need to order this Map, ordering both numbers and strings.

What I get now is this (as you can see numbers are not "ordered" since are String)

1.1
12
2.2
google
mark

What I should  get is:

1.1
2.2
12
google
mark

How can I do it? I'm a little confused.

Body:
You can't order a Map by entry value. SortedMap e.g. TreeMap allows to order the entries by key. It seems you might be using a wrong data structure.

In your example you can define a function that will leniently parse a double and return Double.NaN instead of an exception:

private double lenientParseDouble(String s) {
    try {
        return Double.parseDouble(s);
    } catch (NumberFormatException ex) {
        return Double.NaN;
    }
}

As per Double.compare() docs:

Double.NaN is considered by this method to be equal to itself and greater than all other double values (including Double.POSITIVE_INFINITY).

and then use it as part of the Comparator chain

map.values().stream()
        .sorted(Comparator.comparingDouble(this::lenientParseDouble).thenComparing(Function.identity()))
        .forEach(System.out::println);


问:
Why does ckeditor plugin tab doesn't work?
Hy,

I need the tab function to work in Ckeditor and I put the "tab" plugin in the plugin folder and I told the editor but when I press tab on the keyboard the focus leaves the editor. What am I doing wrong? My script:

```<code>        <script>
            CKEDITOR.replace( 'editor', {
                width: 795, height: 642,
                enterMode: CKEDITOR.ENTER_DIV,
                shiftEnterMode: CKEDITOR.ENTER_BR
            }
            );
            CKEDITOR.editorConfig = function( config ) {
                config.toolbarGroups = [
                    { name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
                    { name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
                    { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },
                    { name: 'forms', groups: [ 'forms' ] },
                    '/',
                    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
                    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },
                    { name: 'links', groups: [ 'links' ] },
                    { name: 'insert', groups: [ 'insert' ] },
                    '/',
                    { name: 'styles', groups: [ 'styles' ] },
                    { name: 'colors', groups: [ 'colors' ] },
                    { name: 'tools', groups: [ 'tools' ] },
                    { name: 'others', groups: [ 'others' ] },
                    { name: 'about', groups: [ 'about' ] }
                ];

                config.removeButtons = 'Source,Save,Templates,NewPage,Preview,Print,Flash,HorizontalRule,Smiley,PageBreak,Iframe,ShowBlocks,Maximize,About,Link,Unlink,Anchor,Language,CreateDiv';
                config.extraPlugins = 'tab';    };

        </script>
</code>```

答:
If you wish to move the text when pressing tab, you need to set the tabSpaces configuration setting to value greater than 0 e.g.

```<code>var editor = CKEDITOR.replace( 'editor1', {
    tabSpaces : 4
});
</code>```

Please also see:https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-tabSpaces

Body:
If you wish to move the text when pressing tab, you need to set the tabSpaces configuration setting to value greater than 0 e.g.

var editor = CKEDITOR.replace( 'editor1', {
    tabSpaces : 4
});

Please also see:https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-tabSpaces


问:
variable current value doesn't change when i call the "showPrevious" function
This program was meant to change the src property of an image element
     via an array

```<code> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">

 <head>
 <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
 <title>Url next, previous</title>

 <script type="text/javascript">

 var imagesarr = ["Eikona1.jpg","Eikona2.jpg","Eikona3.jpg"];
 var current = 0;

 function showNext() {
     current ++;

     if(current==imagesarr.length) {
        current = 0;
     }
     document.getElementById("img").src = imagesarr[current];
   }
</code>```

here is the problem! It gets value: 1
instead of -1. Current price doesnt work...by calling showPrevious() function the current value should change to -1 insted of 1.

```<code>  function showPrevious() {

    current = current - 1 ;

     if(current < 0) {
        current = imagesarr.length - 1;
     }
     document.getElementById("img").scr = imagesarr[current];
  }

 </script>

 </head>

 <body>

 <img src="Eikona1.jpg" id="img" alt="Einstein" style="width:600px;
 height:500px"/>
 <br/>
</code>```

On click events will trigger each function

```<code> <input id="previous" type="button" value="Previous" style="width:220px;
 margin-top:40px" onclick="showPrevious()"/>

 <input id="next" type="button" value="Next" style="width:220px; margin-
 top:40px" onclick="showNext()"/>

 </body>

 </html>
</code>```

答:
You had one typo, src was scr but moreover there was the issue with logic. Perhaps this revised one will clear it up a bit.</p>

```<code><script type="text/javascript">

var imagesarr = ["1","2","3"];
var current = 0;

function showNext() {
    current ++;

    if(current==imagesarr.length) {
       current = 0;
    }
    document.getElementById("img").src = imagesarr[current];
  }

 function showPrevious() {
   current --;

   if(current < 0) {
      current = imagesarr.length-1;
   }
   document.getElementById("img").src = imagesarr[current];
 }

</script>
</code>```

Body:
This program was meant to change the src property of an image element
     via an array

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
 <title>Url next, previous</title>

On click events will trigger each function

 <input id="previous" type="button" value="Previous" style="width:220px;
 margin-top:40px" onclick="showPrevious()"/>

 <input id="next" type="button" value="Next" style="width:220px; margin-
 top:40px" onclick="showNext()"/>

Body:
You had one typo, src was scr but moreover there was the issue with logic. Perhaps this revised one will clear it up a bit.

<script type="text/javascript">

var imagesarr = ["1","2","3"];
var current = 0;

function showNext() {
    current ++;

    if(current==imagesarr.length) {
       current = 0;
    }
    document.getElementById("img").src = imagesarr[current];
  }

 function showPrevious() {
   current --;

   if(current < 0) {
      current = imagesarr.length-1;
   }
   document.getElementById("img").src = imagesarr[current];
 }

</script>


问:
How do stop Python running Py4J ClientServer
I have a Java main() that is starting one or more Py4J ClientServer and python instance to connect back to the ClientServer (all use different port sets).  This is working, but when the main completes, both Java and the python instance are not exiting

I'm starting the ClientServer as follows:

```<code>clientServer = new ClientServer(javaPort, GatewayServer.defaultAddress(), pythonPort,
    GatewayServer.defaultAddress(), GatewayServer.DEFAULT_CONNECT_TIMEOUT,
    GatewayServer.DEFAULT_READ_TIMEOUT, ServerSocketFactory.getDefault(),
    SocketFactory.getDefault(), jep);
</code>```

and python is started by passing in the two ports and doing as follows:

```<code>python_classifier.gateway = ClientServer(
    java_parameters=JavaParameters(port=javaPort, auto_convert=True, auto_close=True),
    python_parameters=PythonParameters(port=pythonPort, daemonize=False,
         daemonize_connections=True),
    python_server_entry_point=python_classifier)
</code>```

I've tried setting deamonize=True, but then the connections start failing.  I've also added a Java shutdown hook to try and kill the python Processes I've started, but it is not always being called.

So, any ideas on how to get python to quietly exit when the Java side has exited?

答:
I have lots of code around managing the python processes started from Java including shutdownHooks, finalizers() and timeout usage listeners.  The main problem turned out to be that for a given ClientServer/Process pair, I was calling ClientServer.shutdown() before calling Process.destroyForcibly()  After swapping the order and killing the process first , shutdown() no longer hangs in close() (see below).

There is a comment in the Py4J java code about the reader hanging in readLine() if the socket is not closed first.  It still seems to be hanging despite this socket being closed first.  The stack trace below is from Finalizer thread, but I got this in my own threads as well.

Body:
I have a Java main() that is starting one or more Py4J ClientServer and python instance to connect back to the ClientServer (all use different port sets).  This is working, but when the main completes, both Java and the python instance are not exiting

I'm starting the ClientServer as follows:

clientServer = new ClientServer(javaPort, GatewayServer.defaultAddress(), pythonPort,
    GatewayServer.defaultAddress(), GatewayServer.DEFAULT_CONNECT_TIMEOUT,
    GatewayServer.DEFAULT_READ_TIMEOUT, ServerSocketFactory.getDefault(),
    SocketFactory.getDefault(), jep);

and python is started by passing in the two ports and doing as follows:

python_classifier.gateway = ClientServer(
    java_parameters=JavaParameters(port=javaPort, auto_convert=True, auto_close=True),
    python_parameters=PythonParameters(port=pythonPort, daemonize=False,
         daemonize_connections=True),
    python_server_entry_point=python_classifier)

I've tried setting deamonize=True, but then the connections start failing.  I've also added a Java shutdown hook to try and kill the python Processes I've started, but it is not always being called.

So, any ideas on how to get python to quietly exit when the Java side has exited?


问:
Which Lisp should I learn?

Which Lisp (dialect) should I learn, and why?

The fragmentation between CL and Scheme slows uptake (at least for me!).

So, give me the "true answer", please!

I have tried to read feature comparisons, and they seem to get bogged down in esoterica (that I don't fully understand) like whether the dialect is fully tail-recursive, and the like.  I'm hoping you all (collectively) can make the opaque differences clear.

Things I like

Good library support, good environments, and Unicode support.

Things I dislike

Flamewars. Features that are useful at the beginning, but interfere with long-term learning.

Updates

I've been mostly using MzScheme, which I'm enjoying just fine, once I got readline support going.  I don't run a GUI on Unix, so it seemed to be a fine environment option for me.

I'm also very happy that Clojure has an easy to install .deb package on debian, so it's much easier to play with.  This is a big win.  Despite the hostility of some rather easy-to-anger below, low barrier to entry is a win.  I like being spoonfed.

After reading a lot more of SICP, I do understand the issues around tail recursion much better.

答:
For me, the foundational theory of Scheme is far more convincing. PLTScheme (now called Racket) is, by far, the most actively developed LISP I've found. Unfortunately, it has a proliferation of typing that obscures the beauty of Lisp.

I'd love to see something like arc succeed, but it seems unlikely.

OwnerDisplayName: Gregg Lind

Title: Which Lisp should I learn?

LastEditorDisplayName: Gregg Lind

OwnerDisplayName: Javier


问:
why can't Xcode find this header file?
Hi I'm getting an xcode "no such file or directory" for:

```<code>#import "Three20Core.h"
</code>```

I also note when I'm typing in the #import statement it recognises, and helps autocomplete, the "Three20Core.h" file, however when I compile I get the error?

This is the main library file header for the Three20 library (from Facebook).  So I've got the three20 directory at the same level as my app directory.  In the Xcode application target build settings:

Header Search Paths - "$(BUILT_PRODUCTS_DIR)/../../../three20" and recursive, and

User Header Search Paths - same as above.

Any fault finding advice?

答:
See an expanded version of this answer here: Xcode 4 Archive Version Unspecified

I've found many issues with Xcode 4 when it comes to complex project structures.

Create a group in your project called "Indexing"

Drag the header files to this group

When asked to select a target uncheck ALL targets

This has solved most of my Xcode 4 issues.

Related questions:

Xcode 4 can't locate public header files from static library
  dependancy

“lexical or preprocessor issue file not found ” in Xcode 4

Title: why can't Xcode find this header file?

Body:
Hi I'm getting an xcode "no such file or directory" for:

#import "Three20Core.h"

I also note when I'm typing in the #import statement it recognises, and helps autocomplete, the "Three20Core.h" file, however when I compile I get the error?

This is the main library file header for the Three20 library (from Facebook).  So I've got the three20 directory at the same level as my app directory.  In the Xcode application target build settings:

Header Search Paths - "$(BUILT_PRODUCTS_DIR)/../../../three20" and recursive, and

User Header Search Paths - same as above.

Any fault finding advice?


问:
How will I know the Controler’s Table in Database (Laravel)
I’m beginner in Laravel Framework. I want to know how the Controller Identifies what table it belongs to? </p>

答:
Views contain the HTML served by your application and separate your controller/application logic from your presentation logic. Views are stored in the resources/views directory. A simple view might look something like this:

```<code><!-- View stored in resources/views/greeting.blade.php -->

<html>
    <body>
        <h1>Hello, {{ $name }}</h1>
    </body>
</html>
</code>```

Models in Laravel 5.5 are created inside the App or App\Models  folder. Models are mostly used to interact with the database using Eloquent ORM. Eloquent provides simple ActiveRecord implementations for database interaction. Example:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}
</code>```

Controllers acts as a directing traffic between Views and Models.  Controllers are stored in the App/Http/Controllers directory. Example:

```<code><?php

namespace App\Http\Controllers;

use App\User;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function show($id)
    {
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}
</code>```

You can learn it from Laravel official Document. It is very helpful.

Body:
Views contain the HTML served by your application and separate your controller/application logic from your presentation logic. Views are stored in the resources/views directory. A simple view might look something like this:

<!-- View stored in resources/views/greeting.blade.php -->

<html>
    <body>
        <h1>Hello, {{ $name }}</h1>
    </body>
</html>

Models in Laravel 5.5 are created inside the App or App\Models  folder. Models are mostly used to interact with the database using Eloquent ORM. Eloquent provides simple ActiveRecord implementations for database interaction. Example:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}

Controllers acts as a directing traffic between Views and Models.  Controllers are stored in the App/Http/Controllers directory. Example:

<?php

namespace App\Http\Controllers;

use App\User;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function show($id)
    {
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}

You can learn it from Laravel official Document. It is very helpful.


问:
Does Spring Integration ServiceActivator work with Project Reactor Types?
I'm using Spring Integration 5.1.5 (with RabbitMQ using spring-integration-amqp) and I reading in the docs that Spring Integration has support for project reactor types (by this I mean Mono, Flux etc). But I cannot get this to work for ServiceActivator's. I'm trying something like this:

@ServiceActivator
public Mono<Void> myMethod(List<Message> messages) {
   Mono<Void> result = myService.doServiceStuff(messages);
   return result;
}
```

<p>(note that I'm also trying to get <code>myMethod</code> working with <code>Flux<Message></code> but that's a separate issue). </p>

<p>When <code>myMethod</code> returns <code>Mono<Void></code> I get this error:</p>

<pre class="lang-java prettyprint-override"><code>Caused by: org.springframework.messaging.core.DestinationResolutionException: no output-channel or replyChannel header available
    at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:426)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.doProduceOutput(AbstractMessageProducingHandler.java:284)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:265)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:223)
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:129)
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:162)
    ... 42 common frames omitted
</code>```

Changing the method to:

@ServiceActivator
public void myMethod(List<Message> messages) {
   Mono<Void> result = myService.doServiceStuff(messages);
   result.subscribe(); // This is not what I want to do
}
```

and subscribing to the reactive stream manually will make it work, however this is obviously not what I want to do. I would rather expect the spring-integration framework to handle the subscription.

Is this supported in Spring Integration? If so, what am I doing wrong?

答:
Exactly what are you trying to achieve by returning Mono<Void> ?

When a service activator method returns any value, that value is sent to the output channel. When it's a Mono<?>, the send is performed when the mono completes.

Simply set the return type to void.

Body:
I'm using Spring Integration 5.1.5 (with RabbitMQ using spring-integration-amqp) and I reading in the docs that Spring Integration has support for project reactor types (by this I mean Mono, Flux etc). But I cannot get this to work for ServiceActivator's. I'm trying something like this:

@ServiceActivator
public Mono<Void> myMethod(List<Message> messages) {
   Mono<Void> result = myService.doServiceStuff(messages);
   return result;
}

(note that I'm also trying to get myMethod working with Flux<Message> but that's a separate issue).

When myMethod returns Mono<Void> I get this error:

Caused by: org.springframework.messaging.core.DestinationResolutionException: no output-channel or replyChannel header available
    at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:426)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.doProduceOutput(AbstractMessageProducingHandler.java:284)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:265)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:223)
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:129)
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:162)
    ... 42 common frames omitted

Changing the method to:

@ServiceActivator
public void myMethod(List<Message> messages) {
   Mono<Void> result = myService.doServiceStuff(messages);
   result.subscribe(); // This is not what I want to do
}

and subscribing to the reactive stream manually will make it work, however this is obviously not what I want to do. I would rather expect the spring-integration framework to handle the subscription.

Is this supported in Spring Integration? If so, what am I doing wrong?


问:
How to combine two df with two different timestamps?
I have two different dfs each with a timestamp. One is collecting data every minute, the other just in case of a change, so sometimes every second, sometimes a couple hours in between two rows. How can I append the columns of df2 to df1 so the timestamp would be the same? df2 would show the same value in each row (so each minute) until something changes (so ffill the NaN's). It's okay to loose some information through that, it's more important to put the dfs together. I'm still a beginner so help would be appreciated. Thanks in advance!

At the moment it looks like this:

```<code>In[10]: df1
Out[10]:
timestamp, X, Y, Z
2018-12-15 08:00:00, 134, 7, 276
2018-12-15 08:01:00, 130, 7, 278
2018-12-15 08:02:00, 136, 8, 291

In[11]: df2
Out[11]:
timestamp, A, B, C
2018-12-15 07:34:36, 1, 44, 21
2018-12-15 08:00:46, NaN, 50, 20
2018-12-15 08:00:52, 0, NaN, 30
</code>```

It's supposed to look like this:

```<code>In[12]: df
Out[12]:
timestamp, X, Y, Z, A, B, C
2018-12-15 08:00:00, 134, 7, 276, 1, 44, 21
2018-12-15 08:01:00, 130, 7, 278, 0, 50, 30
2018-12-15 08:02:00, 136, 8, 291, 0, 50, 30
</code>```

答:
Use merge_asof which will merge on closest match:

```<code>pd.merge_asof(df1, df2, on='timestamp')

            timestamp    X   Y    Z   A     B   C
0 2018-12-15 08:00:00  134   7  276   1    44  21
1 2018-12-15 08:01:00  130   7  278   0   NaN  30
2 2018-12-15 08:02:00  136   8  291   0   NaN  30
</code>```

Note if your timestamp columns are not in datetime format, first convert them to the correct format using to_datetime:

```<code>df1['timestamp'] = pd.to_datetime(df1['timestamp'])
df2['timestamp'] = pd.to_datetime(df2['timestamp'])
</code>```

If you want to fill the NaN use:

```<code>df3 = df3.ffill()
</code>```

Body:
I have two different dfs each with a timestamp. One is collecting data every minute, the other just in case of a change, so sometimes every second, sometimes a couple hours in between two rows. How can I append the columns of df2 to df1 so the timestamp would be the same? df2 would show the same value in each row (so each minute) until something changes (so ffill the NaN's). It's okay to loose some information through that, it's more important to put the dfs together. I'm still a beginner so help would be appreciated. Thanks in advance!

At the moment it looks like this:

In[10]: df1
Out[10]:
timestamp, X, Y, Z
2018-12-15 08:00:00, 134, 7, 276
2018-12-15 08:01:00, 130, 7, 278
2018-12-15 08:02:00, 136, 8, 291

In[11]: df2
Out[11]:
timestamp, A, B, C
2018-12-15 07:34:36, 1, 44, 21
2018-12-15 08:00:46, NaN, 50, 20
2018-12-15 08:00:52, 0, NaN, 30

It's supposed to look like this:

In[12]: df
Out[12]:
timestamp, X, Y, Z, A, B, C
2018-12-15 08:00:00, 134, 7, 276, 1, 44, 21
2018-12-15 08:01:00, 130, 7, 278, 0, 50, 30
2018-12-15 08:02:00, 136, 8, 291, 0, 50, 30

Body:
Use merge_asof which will merge on closest match:

pd.merge_asof(df1, df2, on='timestamp')

            timestamp    X   Y    Z   A     B   C
0 2018-12-15 08:00:00  134   7  276   1    44  21
1 2018-12-15 08:01:00  130   7  278   0   NaN  30
2 2018-12-15 08:02:00  136   8  291   0   NaN  30

Note if your timestamp columns are not in datetime format, first convert them to the correct format using to_datetime:

df1['timestamp'] = pd.to_datetime(df1['timestamp'])
df2['timestamp'] = pd.to_datetime(df2['timestamp'])

If you want to fill the NaN use:

df3 = df3.ffill()


问:
IIS: Where can I find the IIS logs?
I'm trying to set up an application from a third party, which requires a supporting website hosted in my local IIS. I've created a website exactly as explained in their install guide, but am having some problems, and would like to see what the IIS log has to say. Embarrassingly enough, the problem is I can't find the log files!

So my question is: Where does IIS7 store logs by default?

答:
C:\inetpub\logs\LogFiles

Check the identity of the site going to sites and advanced settings

Title: IIS: Where can I find the IIS logs?