问:
get minimum and maxiumum time for a particular date in pandas
I've separate columns for start( timestamp ) and end( timestamp) and i need to get the earliest starttime and last endtime for each date.

```<code>   number               start                 end  test      time
0       1 2020-02-01 06:27:38 2020-02-01 08:29:42     1  02:02:04
1       1 2020-02-01 08:41:03 2020-02-01 11:05:30     2  02:24:27
2       1 2020-02-01 11:20:22 2020-02-01 13:03:49     1  01:43:27
3       1 2020-02-01 13:38:18 2020-02-01 16:04:31     2  02:26:13
4       1 2020-02-01 16:26:46 2020-02-01 17:42:49     1  01:16:03
5       1 2020-02-02 10:11:00 2020-02-02 12:11:00     1  02:00:00
</code>```

I want the output for each date as : Date Min Max

I'm fairly new to Pandas and most of the solutions i've across is finding the min and max datetime from column. While what i want to do is min and max datetime for each date, where the timestamps are spread over two columns

expected output (ignore the date and time formats please)

```<code>date        min     max
1/2/2020    6:27    17:42
2/2/2020    10:11   12:11
</code>```

答:
I believe you need to start by creating a date column and later performing groupby with date.

```<code>df['date'] = df['start'].dt.date
df['start_hm'] = df['start'].dt.strftime('%H:%M')
df['end_hm'] = df['end'].dt.strftime('%H:%M')

output = df.groupby('date').agg(min = pd.NamedAgg(column = 'start_hm',aggfunc='min'),
                                max = pd.NamedAgg(column='end_hm',aggfunc='max'))
</code>```

Output:

```<code>              min    max
date
2020-02-01  06:27  17:42
2020-02-02  10:11  12:11
</code>```

Body:
I've separate columns for start( timestamp ) and end( timestamp) and i need to get the earliest starttime and last endtime for each date.

   number               start                 end  test      time
0       1 2020-02-01 06:27:38 2020-02-01 08:29:42     1  02:02:04
1       1 2020-02-01 08:41:03 2020-02-01 11:05:30     2  02:24:27
2       1 2020-02-01 11:20:22 2020-02-01 13:03:49     1  01:43:27
3       1 2020-02-01 13:38:18 2020-02-01 16:04:31     2  02:26:13
4       1 2020-02-01 16:26:46 2020-02-01 17:42:49     1  01:16:03
5       1 2020-02-02 10:11:00 2020-02-02 12:11:00     1  02:00:00

I want the output for each date as : Date Min Max

I'm fairly new to Pandas and most of the solutions i've across is finding the min and max datetime from column. While what i want to do is min and max datetime for each date, where the timestamps are spread over two columns

expected output (ignore the date and time formats please)

date        min     max
1/2/2020    6:27    17:42
2/2/2020    10:11   12:11

Body:
I believe you need to start by creating a date column and later performing groupby with date.

df['date'] = df['start'].dt.date
df['start_hm'] = df['start'].dt.strftime('%H:%M')
df['end_hm'] = df['end'].dt.strftime('%H:%M')

output = df.groupby('date').agg(min = pd.NamedAgg(column = 'start_hm',aggfunc='min'),
                                max = pd.NamedAgg(column='end_hm',aggfunc='max'))

Output:

              min    max
date
2020-02-01  06:27  17:42
2020-02-02  10:11  12:11


来源: stackexchange

问:
How to render element in React.js from object map
I have a question about rendering components from object map. I have a structure like this:

```<code>const tabs = [
    'tab1': {
        name: 'Tab 1',
        renderComponent: () => <Tab1Component />
    },
    'tab2': {
        name: 'Tab 2',
        renderComponent: () => <Tab2Component />
    }
];
</code>```

I want to access the renderComponent property and render sub component.
Tried with function invocation, React.createElement(), doesn't work.

```<code>const MyComponent = ({tabs}) => {
    const activeTab = 'tab1';
    return (
        <>
        // How to render it?
        // function invocation?
        // createElement??
            tabs[activeTab].renderComponent();
        </>
    );
};
</code>```

答:
Your array declaration is wrong. you should use object or array that includes objects. Try this block.

```<code>const tabs = {
  tab1: {
    name: "Tab 1",
    renderComponent: () => <Tab1Component />
  },
  tab2: {
    name: "Tab 2",
    renderComponent: () => <Tab2Component />
  }
};
</code>```

Also surround your js code with {} like;

```<code>const MyComponent= () => {
  const activeTab = "tab1";
  return <>{tabs[activeTab].renderComponent()}</>;
};
export default MyComponent;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a question about rendering components from object map. I have a structure like this:

const tabs = [
    'tab1': {
        name: 'Tab 1',
        renderComponent: () => <Tab1Component />
    },
    'tab2': {
        name: 'Tab 2',
        renderComponent: () => <Tab2Component />
    }
];

I want to access the renderComponent property and render sub component.
Tried with function invocation, React.createElement(), doesn't work.

const MyComponent = ({tabs}) => {
    const activeTab = 'tab1';
    return (
        <>
        // How to render it?
        // function invocation?
        // createElement??
            tabs[activeTab].renderComponent();
        </>
    );
};

Body:
Your array declaration is wrong. you should use object or array that includes objects. Try this block.

const tabs = {
  tab1: {
    name: "Tab 1",
    renderComponent: () => <Tab1Component />
  },
  tab2: {
    name: "Tab 2",
    renderComponent: () => <Tab2Component />
  }
};

Also surround your js code with {} like;

const MyComponent= () => {
  const activeTab = "tab1";
  return <>{tabs[activeTab].renderComponent()}</>;
};
export default MyComponent;


问:
Active Choices Reactive Reference Parameter in jenkins pipeline
I'm using the Active Choices Reactive Reference Parameter plugin in a dsl job here the code

```<code> parameters {
                  activeChoiceParam('choice1') {
                      description('select your choice')
                      choiceType('RADIO')
                      groovyScript {
                          script("return['aaa','bbb']")
                          fallbackScript('return ["error"]')
                      }
                  }
                  activeChoiceReactiveParam('choice2') {
                      description('select your choice')
                      choiceType('RADIO')
                      groovyScript {
                          script("if(choice1.equals("aaa")){return ['a', 'b']} else {return ['aaaaaa','fffffff']}")
                          fallbackScript('return ["error"]')
                      }
                      referencedParameter('choice1')
                  }
</code>```

and it work's fine what i want now is how to use the activeChoiceReactiveParam  in a jenkinsFile for pipeline job i did that :

```<code>properties(
    [
            [
                    $class              : 'ParametersDefinitionProperty',
                    parameterDefinitions: [
                            [
                                    $class     : 'ChoiceParameterDefinition',
                                    choices    : 'aaa\nbbb',
                                    description: 'select your choice : ',
                                    name       : 'choice1'
                            ]
</code>```

but how can i add the choice2 parameter !!!

答:
Thanks a ton @Yogeesh. It helped a lot.
In my case, the requirement was to select multiple instead of one. So, used choiceType: 'PT_CHECKBOX',  and it served the purpose.</p>

```<code>properties([
parameters([
    [$class: 'ChoiceParameter',
        choiceType: 'PT_SINGLE_SELECT',
        description: 'Select the Env Name from the Dropdown List',
        filterLength: 1,
        filterable: true,
        name: 'Env',
        randomName: 'choice-parameter-5631314439613978',
        script: [
            $class: 'GroovyScript',
            fallbackScript: [
                classpath: [],
                sandbox: false,
                script:
                    'return[\'Could not get Env\']'
            ],
            script: [
                classpath: [],
                sandbox: false,
                script:
                    'return["Dev","QA","Stage","Prod"]'
            ]
        ]
    ],
    [$class: 'CascadeChoiceParameter',
        choiceType: 'PT_CHECKBOX',
        description: 'Select Servers',
        filterLength: 1,
        filterable: true,
        name: 'Server',
        randomName: 'choice-parameter-5631314456178619',
        referencedParameters: 'Env',
        script: [
            $class: 'GroovyScript',
            fallbackScript: [
                classpath: [],
                sandbox: false,
                script:
                    'return[\'Could not get Environment from Env Param\']'
            ],
            script: [
                classpath: [],
                sandbox: false,
                script:
                    ''' if (Env.equals("Dev")){
                            return["devaaa001","devaaa002","devbbb001","devbbb002","devccc001","devccc002"]
                        }
                        else if(Env.equals("QA")){
                            return["qaaaa001","qabbb002","qaccc003"]
                        }
                        else if(Env.equals("Stage")){
                            return["staaa001","stbbb002","stccc003"]
                        }
                        else if(Env.equals("Prod")){
                            return["praaa001","prbbb002","prccc003"]
                        }
                    '''
            ]
        ]
    ]
])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using the Active Choices Reactive Reference Parameter plugin in a dsl job here the code

 parameters {
                  activeChoiceParam('choice1') {
                      description('select your choice')
                      choiceType('RADIO')
                      groovyScript {
                          script("return['aaa','bbb']")
                          fallbackScript('return ["error"]')
                      }
                  }
                  activeChoiceReactiveParam('choice2') {
                      description('select your choice')
                      choiceType('RADIO')
                      groovyScript {
                          script("if(choice1.equals("aaa")){return ['a', 'b']} else {return ['aaaaaa','fffffff']}")
                          fallbackScript('return ["error"]')
                      }
                      referencedParameter('choice1')
                  }

and it work's fine what i want now is how to use the activeChoiceReactiveParam  in a jenkinsFile for pipeline job i did that :

properties(
    [
            [
                    $class              : 'ParametersDefinitionProperty',
                    parameterDefinitions: [
                            [
                                    $class     : 'ChoiceParameterDefinition',
                                    choices    : 'aaa\nbbb',
                                    description: 'select your choice : ',
                                    name       : 'choice1'
                            ]

but how can i add the choice2 parameter !!!

Body:
Thanks a ton @Yogeesh. It helped a lot.
In my case, the requirement was to select multiple instead of one. So, used choiceType: 'PT_CHECKBOX',  and it served the purpose.

properties([
parameters([
    [$class: 'ChoiceParameter',
        choiceType: 'PT_SINGLE_SELECT',
        description: 'Select the Env Name from the Dropdown List',
        filterLength: 1,
        filterable: true,
        name: 'Env',
        randomName: 'choice-parameter-5631314439613978',
        script: [
            $class: 'GroovyScript',
            fallbackScript: [
                classpath: [],
                sandbox: false,
                script:
                    'return[\'Could not get Env\']'
            ],
            script: [
                classpath: [],
                sandbox: false,
                script:
                    'return["Dev","QA","Stage","Prod"]'
            ]
        ]
    ],
    [$class: 'CascadeChoiceParameter',
        choiceType: 'PT_CHECKBOX',
        description: 'Select Servers',
        filterLength: 1,
        filterable: true,
        name: 'Server',
        randomName: 'choice-parameter-5631314456178619',
        referencedParameters: 'Env',
        script: [
            $class: 'GroovyScript',
            fallbackScript: [
                classpath: [],
                sandbox: false,
                script:
                    'return[\'Could not get Environment from Env Param\']'
            ],
            script: [
                classpath: [],
                sandbox: false,
                script:
                    ''' if (Env.equals("Dev")){
                            return["devaaa001","devaaa002","devbbb001","devbbb002","devccc001","devccc002"]
                        }
                        else if(Env.equals("QA")){
                            return["qaaaa001","qabbb002","qaccc003"]
                        }
                        else if(Env.equals("Stage")){
                            return["staaa001","stbbb002","stccc003"]
                        }
                        else if(Env.equals("Prod")){
                            return["praaa001","prbbb002","prccc003"]
                        }
                    '''
            ]
        ]
    ]
])


问:
Accounts Receivable Query: with CASE, PARTITION BY and WHERE
I have used a previous Stack example to get started but I am having trouble SUMing the totals of the data. Sorry it is long but it is all relevant.

```<code>SELECT DISTINCT         TRIM(RMCUST.REP_CODE) AS 'Rep',
                        RMCUST.CUST_NAME AS 'Customer',
                        FORMAT(CASE WHEN DATEDIFF(DD, RMDET.TRAN_DATE, GETDATE()) <= 30
                        THEN SUM(RMDET.TRAN_AMT)
                        OVER (PARTITION BY RMCUST.CUST_NAME)
                        ELSE 0
                        END, 'c') AS '0 - 30',
                        FORMAT(CASE WHEN DATEDIFF(DD, RMDET.TRAN_DATE, GETDATE()) > 30 AND DATEDIFF(DD, RMDET.TRAN_DATE, GETDATE()) <= 60
                        THEN SUM(RMDET.TRAN_AMT)
                        OVER (PARTITION BY RMCUST.CUST_NAME)
                        ELSE 0
                        END, 'c') AS '31 - 60',
                        FORMAT(CASE WHEN DATEDIFF(DD, RMDET.TRAN_DATE, GETDATE()) > 60 AND DATEDIFF(DD, RMDET.TRAN_DATE, GETDATE()) <= 90
                        THEN SUM(RMDET.TRAN_AMT)
                        OVER (PARTITION BY RMCUST.CUST_NAME)
                        ELSE 0
                        END, 'c') AS '61 - 90',
                        FORMAT(CASE WHEN DATEDIFF(DD, RMDET.TRAN_DATE, GETDATE()) > 90
                        THEN SUM(RMDET.TRAN_AMT)
                        OVER (PARTITION BY RMCUST.CUST_NAME)
                        ELSE 0
                        END, 'c') AS '>90'
FROM                    RMDET (NOLOCK)
INNER JOIN              RMCUST (NOLOCK) ON RMCUST.CUST_CODE = RMDET.CUST_CODE
WHERE                   RMDET.TRAN_AMT_APPLIED = 0
GROUP BY                RMCUST.REP_CODE, RMCUST.CUST_NAME, RMDET.TRAN_DATE, RMDET.TRAN_AMT
ORDER BY                RMCUST.CUST_NAME
</code>```

Output:

```<code>Rep Customer                        0 - 30     31 - 60  61 - 90    >90
------------------------------------------------------------------------
KG  135 PRIME                       $0.00       $0.00   $462.66    $0.00
AS  71 ABOVE                        $2,469.60   $0.00   $0.00      $0.00
KH  ABERNETHYS MUSIC CENTER         $0.00       $0.00   $1,014.60  $0.00
KH  ABERNETHYS MUSIC CENTER         $1,014.60   $0.00   $0.00      $0.00
BH  AC HOTEL                        $132.28     $0.00   $0.00      $0.00
AS  ACE HOTEL                       $0.00       $0.00   $0.00      ($0.91)
AS  AKASHA                          $0.00       $0.00   $12,052.06 $0.00
AS  AKASHA                          $0.00       $12,052.06  $0.00  $0.00
AS  AKASHA                          $12,052.06  $0.00   $0.00      $0.00
</code>```

Here is the raw data from the table. The query is putting the total owed in all columns when it should show only one row with the different totals for each column depending on the date. Where am I going wrong? Thank you.

```<code>Rep Customer                        Date     Invoice #  0 - 30 31 - 60  61 - 90 >90
------------------------------------------------------------------------------------
KG  135 PRIME                       12/20/2019  870     $0.00   $0.00   $462.66 $0.00
AS  71 ABOVE                        02/14/2020  5240    $397.60 $0.00   $0.00   $0.00
AS  71 ABOVE                        02/15/2020  5341    $978.60 $0.00   $0.00   $0.00
AS  71 ABOVE                        02/17/2020  5423    $427.00 $0.00   $0.00   $0.00
AS  71 ABOVE                        02/18/2020  5529    $509.60 $0.00   $0.00   $0.00
AS  71 ABOVE                        02/19/2020  5608    $156.80 $0.00   $0.00   $0.00
KH  ABERNETHYS MUSIC CENTER         12/19/2019  721     $0.00   $0.00   $450.50 $0.00
KH  ABERNETHYS MUSIC CENTER         02/19/2020  5657    $180.20 $0.00   $0.00   $0.00
KH  ABERNETHYS MUSIC CENTER         12/05/2019  235884  $0.00   $0.00   $383.90 $0.00
BH  AC HOTEL                        02/13/2020  5181    $30.21  $0.00   $0.00   $0.00
BH  AC HOTEL                        02/18/2020  5593    $102.07 $0.00   $0.00   $0.00
AS  ACE HOTEL                       03/14/2018  193386  $0.00   $0.00   $0.00   ($0.72)
AS  ACE HOTEL                       04/30/2018  CREDITS-09  $0.00   $0.00   $0.00   ($0.19)
AS  AKASHA                          01/02/2020  1789    $0.00   $128.70 $0.00   $0.00
AS  AKASHA                          01/04/2020  1959    $0.00   $223.37 $0.00   $0.00
AS  AKASHA                          01/07/2020  2141    $0.00   $161.95 $0.00   $0.00
AS  AKASHA                          01/08/2020  2218    $0.00   $102.00 $0.00   $0.00
AS  AKASHA                          01/09/2020  2326    $0.00   $444.00 $0.00   $0.00
AS  AKASHA                          01/10/2020  2416    $0.00   $596.82 $0.00   $0.00
AS  AKASHA                          01/11/2020  2531    $0.00   $462.11 $0.00   $0.00
AS  AKASHA                          01/14/2020  2701    $0.00   $303.10 $0.00   $0.00
AS  AKASHA                          01/16/2020  2879    $0.00   $804.24 $0.00   $0.00
AS  AKASHA                          01/17/2020  2989    $0.00   $442.11 $0.00   $0.00
AS  AKASHA                          01/18/2020  3080    $0.00   $95.47  $0.00   $0.00
AS  AKASHA                          01/20/2020  3181    $225.86 $0.00   $0.00   $0.00
AS  AKASHA                          01/22/2020  3366    $145.02 $0.00   $0.00   $0.00
AS  AKASHA                          01/23/2020  3451    $126.42 $0.00   $0.00   $0.00
AS  AKASHA                          01/24/2020  3544    $510.90 $0.00   $0.00   $0.00
AS  AKASHA                          01/25/2020  3656    $227.76 $0.00   $0.00   $0.00
AS  AKASHA                          01/27/2020  3733    $156.88 $0.00   $0.00   $0.00
AS  AKASHA                          01/29/2020  3914    $264.37 $0.00   $0.00   $0.00
AS  AKASHA                          01/30/2020  4006    $705.27 $0.00   $0.00   $0.00
AS  AKASHA                          01/31/2020  4106    $184.20 $0.00   $0.00   $0.00
AS  AKASHA                          02/01/2020  4222    $180.30 $0.00   $0.00   $0.00
AS  AKASHA                          02/04/2020  4387    $209.59 $0.00   $0.00   $0.00
AS  AKASHA                          02/05/2020  4462    $259.76 $0.00   $0.00   $0.00
AS  AKASHA                          02/06/2020  4572    $276.91 $0.00   $0.00   $0.00
AS  AKASHA                          02/07/2020  4666    $558.18 $0.00   $0.00   $0.00
AS  AKASHA                          02/08/2020  4782    $249.31 $0.00   $0.00   $0.00
AS  AKASHA                          02/11/2020  4866    $395.93 $0.00   $0.00   $0.00
AS  AKASHA                          02/13/2020  5108    $467.89 $0.00   $0.00   $0.00
AS  AKASHA                          02/14/2020  5220    $125.63 $0.00   $0.00   $0.00
AS  AKASHA                          02/15/2020  5367    $173.64 $0.00   $0.00   $0.00
AS  AKASHA                          02/17/2020  5449    $355.40 $0.00   $0.00   $0.00
AS  AKASHA                          02/18/2020  5548    $220.65 $0.00   $0.00   $0.00
AS  AKASHA                          02/19/2020  5636    $608.92 $0.00   $0.00   $0.00
AS  AKASHA                          12/04/2019  235786  $0.00   $0.00   $299.46 $0.00
AS  AKASHA                          12/04/2019  235806  $0.00   $0.00   $150.18 $0.00
AS  AKASHA                          12/06/2019  236042  $0.00   $0.00   $954.18 $0.00
AS  AKASHA                          12/07/2019  236108  $0.00   $0.00   $310.82 $0.00
AS  AKASHA                          12/10/2019  236300  $0.00   $0.00   $70.50  $0.00
AS  AKASHA                          12/31/2019  CREDITS-08  $0.00   ($125.74)   $0.00   $0.00
</code>```

Body:
I have used a previous Stack example to get started but I am having trouble SUMing the totals of the data. Sorry it is long but it is all relevant.

SELECT DISTINCT         TRIM(RMCUST.REP_CODE) AS 'Rep',
                        RMCUST.CUST_NAME AS 'Customer',
                        FORMAT(CASE WHEN DATEDIFF(DD, RMDET.TRAN_DATE, GETDATE()) <= 30
                        THEN SUM(RMDET.TRAN_AMT)
                        OVER (PARTITION BY RMCUST.CUST_NAME)
                        ELSE 0
                        END, 'c') AS '0 - 30',
                        FORMAT(CASE WHEN DATEDIFF(DD, RMDET.TRAN_DATE, GETDATE()) > 30 AND DATEDIFF(DD, RMDET.TRAN_DATE, GETDATE()) <= 60
                        THEN SUM(RMDET.TRAN_AMT)
                        OVER (PARTITION BY RMCUST.CUST_NAME)
                        ELSE 0
                        END, 'c') AS '31 - 60',
                        FORMAT(CASE WHEN DATEDIFF(DD, RMDET.TRAN_DATE, GETDATE()) > 60 AND DATEDIFF(DD, RMDET.TRAN_DATE, GETDATE()) <= 90
                        THEN SUM(RMDET.TRAN_AMT)
                        OVER (PARTITION BY RMCUST.CUST_NAME)
                        ELSE 0
                        END, 'c') AS '61 - 90',
                        FORMAT(CASE WHEN DATEDIFF(DD, RMDET.TRAN_DATE, GETDATE()) > 90
                        THEN SUM(RMDET.TRAN_AMT)
                        OVER (PARTITION BY RMCUST.CUST_NAME)
                        ELSE 0
                        END, 'c') AS '>90'
FROM                    RMDET (NOLOCK)
INNER JOIN              RMCUST (NOLOCK) ON RMCUST.CUST_CODE = RMDET.CUST_CODE
WHERE                   RMDET.TRAN_AMT_APPLIED = 0
GROUP BY                RMCUST.REP_CODE, RMCUST.CUST_NAME, RMDET.TRAN_DATE, RMDET.TRAN_AMT
ORDER BY                RMCUST.CUST_NAME

Output:

Rep Customer                        0 - 30     31 - 60  61 - 90    >90
------------------------------------------------------------------------
KG  135 PRIME                       $0.00       $0.00   $462.66    $0.00
AS  71 ABOVE                        $2,469.60   $0.00   $0.00      $0.00
KH  ABERNETHYS MUSIC CENTER         $0.00       $0.00   $1,014.60  $0.00
KH  ABERNETHYS MUSIC CENTER         $1,014.60   $0.00   $0.00      $0.00
BH  AC HOTEL                        $132.28     $0.00   $0.00      $0.00
AS  ACE HOTEL                       $0.00       $0.00   $0.00      ($0.91)
AS  AKASHA                          $0.00       $0.00   $12,052.06 $0.00
AS  AKASHA                          $0.00       $12,052.06  $0.00  $0.00
AS  AKASHA                          $12,052.06  $0.00   $0.00      $0.00

Here is the raw data from the table. The query is putting the total owed in all columns when it should show only one row with the different totals for each column depending on the date. Where am I going wrong? Thank you.

Rep Customer                        Date     Invoice #  0 - 30 31 - 60  61 - 90 >90
------------------------------------------------------------------------------------
KG  135 PRIME                       12/20/2019  870     $0.00   $0.00   $462.66 $0.00
AS  71 ABOVE                        02/14/2020  5240    $397.60 $0.00   $0.00   $0.00
AS  71 ABOVE                        02/15/2020  5341    $978.60 $0.00   $0.00   $0.00
AS  71 ABOVE                        02/17/2020  5423    $427.00 $0.00   $0.00   $0.00
AS  71 ABOVE                        02/18/2020  5529    $509.60 $0.00   $0.00   $0.00
AS  71 ABOVE                        02/19/2020  5608    $156.80 $0.00   $0.00   $0.00
KH  ABERNETHYS MUSIC CENTER         12/19/2019  721     $0.00   $0.00   $450.50 $0.00
KH  ABERNETHYS MUSIC CENTER         02/19/2020  5657    $180.20 $0.00   $0.00   $0.00
KH  ABERNETHYS MUSIC CENTER         12/05/2019  235884  $0.00   $0.00   $383.90 $0.00
BH  AC HOTEL                        02/13/2020  5181    $30.21  $0.00   $0.00   $0.00
BH  AC HOTEL                        02/18/2020  5593    $102.07 $0.00   $0.00   $0.00
AS  ACE HOTEL                       03/14/2018  193386  $0.00   $0.00   $0.00   ($0.72)
AS  ACE HOTEL                       04/30/2018  CREDITS-09  $0.00   $0.00   $0.00   ($0.19)
AS  AKASHA                          01/02/2020  1789    $0.00   $128.70 $0.00   $0.00
AS  AKASHA                          01/04/2020  1959    $0.00   $223.37 $0.00   $0.00
AS  AKASHA                          01/07/2020  2141    $0.00   $161.95 $0.00   $0.00
AS  AKASHA                          01/08/2020  2218    $0.00   $102.00 $0.00   $0.00
AS  AKASHA                          01/09/2020  2326    $0.00   $444.00 $0.00   $0.00
AS  AKASHA                          01/10/2020  2416    $0.00   $596.82 $0.00   $0.00
AS  AKASHA                          01/11/2020  2531    $0.00   $462.11 $0.00   $0.00
AS  AKASHA                          01/14/2020  2701    $0.00   $303.10 $0.00   $0.00
AS  AKASHA                          01/16/2020  2879    $0.00   $804.24 $0.00   $0.00
AS  AKASHA                          01/17/2020  2989    $0.00   $442.11 $0.00   $0.00
AS  AKASHA                          01/18/2020  3080    $0.00   $95.47  $0.00   $0.00
AS  AKASHA                          01/20/2020  3181    $225.86 $0.00   $0.00   $0.00
AS  AKASHA                          01/22/2020  3366    $145.02 $0.00   $0.00   $0.00
AS  AKASHA                          01/23/2020  3451    $126.42 $0.00   $0.00   $0.00
AS  AKASHA                          01/24/2020  3544    $510.90 $0.00   $0.00   $0.00
AS  AKASHA                          01/25/2020  3656    $227.76 $0.00   $0.00   $0.00
AS  AKASHA                          01/27/2020  3733    $156.88 $0.00   $0.00   $0.00
AS  AKASHA                          01/29/2020  3914    $264.37 $0.00   $0.00   $0.00
AS  AKASHA                          01/30/2020  4006    $705.27 $0.00   $0.00   $0.00
AS  AKASHA                          01/31/2020  4106    $184.20 $0.00   $0.00   $0.00
AS  AKASHA                          02/01/2020  4222    $180.30 $0.00   $0.00   $0.00
AS  AKASHA                          02/04/2020  4387    $209.59 $0.00   $0.00   $0.00
AS  AKASHA                          02/05/2020  4462    $259.76 $0.00   $0.00   $0.00
AS  AKASHA                          02/06/2020  4572    $276.91 $0.00   $0.00   $0.00
AS  AKASHA                          02/07/2020  4666    $558.18 $0.00   $0.00   $0.00
AS  AKASHA                          02/08/2020  4782    $249.31 $0.00   $0.00   $0.00
AS  AKASHA                          02/11/2020  4866    $395.93 $0.00   $0.00   $0.00
AS  AKASHA                          02/13/2020  5108    $467.89 $0.00   $0.00   $0.00
AS  AKASHA                          02/14/2020  5220    $125.63 $0.00   $0.00   $0.00
AS  AKASHA                          02/15/2020  5367    $173.64 $0.00   $0.00   $0.00
AS  AKASHA                          02/17/2020  5449    $355.40 $0.00   $0.00   $0.00
AS  AKASHA                          02/18/2020  5548    $220.65 $0.00   $0.00   $0.00
AS  AKASHA                          02/19/2020  5636    $608.92 $0.00   $0.00   $0.00
AS  AKASHA                          12/04/2019  235786  $0.00   $0.00   $299.46 $0.00
AS  AKASHA                          12/04/2019  235806  $0.00   $0.00   $150.18 $0.00
AS  AKASHA                          12/06/2019  236042  $0.00   $0.00   $954.18 $0.00
AS  AKASHA                          12/07/2019  236108  $0.00   $0.00   $310.82 $0.00
AS  AKASHA                          12/10/2019  236300  $0.00   $0.00   $70.50  $0.00
AS  AKASHA                          12/31/2019  CREDITS-08  $0.00   ($125.74)   $0.00   $0.00

Body:
You can do this just using GROUP BY and CASE without needing to use window functions:

select
    c.rep_code,
    c.cust_name,
    sum(case when datediff(day,d.tran_date,getdate()) <= 30             then d.tran_amt else 0 end) as [0 - 30],
    sum(case when datediff(day,d.tran_date,getdate()) between 31 and 60 then d.tran_amt else 0 end) as [31 - 60],
    sum(case when datediff(day,d.tran_date,getdate()) between 61 and 90 then d.tran_amt else 0 end) as [61 - 90],
    sum(case when datediff(day,d.tran_date,getdate()) > 90              then d.tran_amt else 0 end) as [>90]
from rmdet d
join rmcust c on d.cust_code = c.cust_code
group by
    c.rep_code,
    c.cust_name
order by c.cust_name

Results:

/--------------------------------------------------------------------------\
| rep_code |        cust_name        | 0 - 30  | 31 - 60 | 61 - 90 |  >90  |
|----------|-------------------------|---------|---------|---------|-------|
|    KG    |        135 PRIME        |    0.00 |    0.00 |  462.66 |  0.00 |
|    AS    |        71 ABOVE         | 2469.60 |    0.00 |    0.00 |  0.00 |
|    KH    | ABERNETHYS MUSIC CENTER |  180.20 |    0.00 |  834.40 |  0.00 |
|    BH    |        AC HOTEL         |  132.28 |    0.00 |    0.00 |  0.00 |
|    AS    |        ACE HOTEL        |    0.00 |    0.00 |    0.00 | -0.91 |
|    AS    |         AKASHA          | 6402.93 | 3863.99 | 1785.14 |  0.00 |
\--------------------------------------------------------------------------/


问:
How can I "Fold" a UIView in 3D along a line?
If you have a UIView

Imagine the view being full of text, animations, a cat photo, a gradient, or indeed any of the stuff a UIView can be full of.

It's easy to tilt it back to the left in 3D

or back to the right ..

(BTW I highly recommend the perfect OHCubeView ohcubeview when you have to do that sort of thing.)

But I want to crease a view along a seam, and have one side going backwards to the left and the other side going backwards to the right ..

!

My first solution was simply: whatever the view is (the user is typing in text, a photo of a cat, whatever), just perfectly duplicate it, and then solve the problem in the obvious way.

That's inelegant, but does work.

But...

the thing I want to fold like this, is ... an SKView with an emitter in it.

Particle emitters are of course random, and while two of the same one will look similar, it's not a real solution.

Essentially, if someone knows how to "copy" a UIView to another, well, view, or something ...

the problem would be solved.

For a problem like this in a game engine, say, you just throw a "virtual camera" (whatever the concept is in your favorite game engine) on the thing in question, and put the other half, or whatever, anywhere you want, but, I don't know the analogy of that in iOS!

Does anyone have an angle on this:

答:
There's 2 approaches I could think of.

1) Bend Approach

You could bend your scene using an SKWarpGeometry. Semantically, you'd envision a 2 x 2 quadrant grid on your game scene, described by a 3 x 3 point data structure. You'd move the left and right edges in a little, and make them a little smaller. And you'd make the centre vertical edge a little longer.

Apple's documentation also mentions that essentially any type of node (including an SKEmitterNode), can be warped by putting it into an SKEffectNode, and applying the warp to that. See: https://developer.apple.com/documentation/spritekit/skwarpgeometrygrid/animate_the_warping_of_a_sprite?language=objc.

All we have to do is make an effect node be the root node of everything, and apply the warp to it. Now, this works, but as soon as there's an emitter in it, the warp starts spazzing in seizure-like convulsions. I regard this as a bug. I'll include the code anyway incase its fixed later on, because it's supposed to work according to the documentation.

```<code>let sourcePoints = [
    // bottom row: left, center, right
    vector_float2(0.0, 0.0),
    vector_float2(0.5, 0.0),
    vector_float2(1.0, 0.0),

    // middle row: left, center, right
    vector_float2(0.0, 0.5),
    vector_float2(0.5, 0.5),
    vector_float2(1.0, 0.5),

    // top row: left, center, right
    vector_float2(0.0, 1.0),
    vector_float2(0.5, 1.0),
    vector_float2(1.0, 1.0)
]

var destinationPoints = sourcePoints

// Bring lefts in, and make the edge shorter
destinationPoints[0] = vector_float2(0.1, 0.1)
destinationPoints[3] = vector_float2(0.1, 0.4)
destinationPoints[6] = vector_float2(0.1, 0.9)

// Bring rights in, and make the edge shorter
destinationPoints[2] = vector_float2(0.9, 0.1)
destinationPoints[5] = vector_float2(0.9, 0.4)
destinationPoints[8] = vector_float2(0.9, 0.9)

// Make the center edge longer
destinationPoints[1] = vector_float2(0.5, -0.2)
destinationPoints[4] = vector_float2(0.5, 0.7)
destinationPoints[7] = vector_float2(0.5, 1.2)

// Need to set the no warp geometry first
effectNode.warpGeometry = SKWarpGeometryGrid(columns: 2, rows: 2)

let newGeometry = SKWarpGeometryGrid(columns: 2, rows: 2,
                                         sourcePositions: sourcePoints,
                                         destinationPositions: destinationPoints)

effectNode.run(SKAction.warp(to: newGeometry, duration: 1.0)!)
</code>```

Sources used:

https://www.hackingwithswift.com/example-code/games/how-to-warp-a-sprite-using-skwarpgeometrygrid

http://sound-of-silence.com/?page=blog&sort=recent&count=0

2) Live Copy Approach

This is simpler, there's far less code, and it's a lot more versatile; you can do things like in this Rayman Legends level https://youtu.be/7m5YQrucis8?t=1226. Also, it works.

Basically, we have our master SKView showing the master scene. We'll add a copy SKView showing a copy scene. The copy scene will have only one sprite node in it.
In the master scene's update loop, we'll grab a flattened texture of the scene and assign it to the sprite node in the copy scene. An object that is the scene's delegate can tap into this update loop, so we'll make the view controller conform to SKSceneDelegate.

```<code>class Playground_VC: UIViewController, SKSceneDelegate {

    var sprite: SKSpriteNode?

    override func loadView() {
        self.view = SKView()
    }

    var skView: SKView {
        return self.view as! SKView
    }

    override func viewWillAppear(_ animated: Bool) {
        let scene = SKScene(size: self.skView.bounds.size)
        scene.backgroundColor = UIColor.clear
        scene.delegate = self
        self.skView.presentScene(scene)

        let e = newEmitter()
        scene.addChild(e)
        e.position = self.skView.midPoint

        self.createCopy()

    }

    func update(_ currentTime: TimeInterval, for scene: SKScene) {
        // Grab the root texture and assign to the sprite that's in the copy scene
        let t = self.skView.texture(from: self.skView.scene!)
        self.sprite?.texture = t
    }

    func createCopy() {

        // Make a new SKView that's 4 times smaller

        var f = self.skView.bounds
        f.size.height *= 0.4
        f.size.width *= 0.4

        let copy = SKView(frame: f)
        copy.presentScene(SKScene(size: f.size))
        self.view.addSubview(copy)

        let sprite = SKSpriteNode(texture: nil, size: f.size)
        copy.scene?.addChild(sprite)
        self.sprite = sprite
        sprite.position = CGPoint(x: f.size.width / 2, y: f.size.height / 2)

    }

    func newEmitter() -> SKEmitterNode {
        return SKEmitterNode(fileNamed: "Particle.sks")!
    }
}
</code>```

Any manipulations you perform on the master SKView, like tilting it in 3D space, shouldn't affect the appearance of the copy, because the game scene is unaffected by those manipulations.

Body:
There's 2 approaches I could think of.

1) Bend Approach

You could bend your scene using an SKWarpGeometry. Semantically, you'd envision a 2 x 2 quadrant grid on your game scene, described by a 3 x 3 point data structure. You'd move the left and right edges in a little, and make them a little smaller. And you'd make the centre vertical edge a little longer.

Apple's documentation also mentions that essentially any type of node (including an SKEmitterNode), can be warped by putting it into an SKEffectNode, and applying the warp to that. See: https://developer.apple.com/documentation/spritekit/skwarpgeometrygrid/animate_the_warping_of_a_sprite?language=objc.

All we have to do is make an effect node be the root node of everything, and apply the warp to it. Now, this works, but as soon as there's an emitter in it, the warp starts spazzing in seizure-like convulsions. I regard this as a bug. I'll include the code anyway incase its fixed later on, because it's supposed to work according to the documentation.

let sourcePoints = [
    // bottom row: left, center, right
    vector_float2(0.0, 0.0),
    vector_float2(0.5, 0.0),
    vector_float2(1.0, 0.0),

    // middle row: left, center, right
    vector_float2(0.0, 0.5),
    vector_float2(0.5, 0.5),
    vector_float2(1.0, 0.5),

    // top row: left, center, right
    vector_float2(0.0, 1.0),
    vector_float2(0.5, 1.0),
    vector_float2(1.0, 1.0)
]

var destinationPoints = sourcePoints

// Bring lefts in, and make the edge shorter
destinationPoints[0] = vector_float2(0.1, 0.1)
destinationPoints[3] = vector_float2(0.1, 0.4)
destinationPoints[6] = vector_float2(0.1, 0.9)

// Bring rights in, and make the edge shorter
destinationPoints[2] = vector_float2(0.9, 0.1)
destinationPoints[5] = vector_float2(0.9, 0.4)
destinationPoints[8] = vector_float2(0.9, 0.9)

// Make the center edge longer
destinationPoints[1] = vector_float2(0.5, -0.2)
destinationPoints[4] = vector_float2(0.5, 0.7)
destinationPoints[7] = vector_float2(0.5, 1.2)

// Need to set the no warp geometry first
effectNode.warpGeometry = SKWarpGeometryGrid(columns: 2, rows: 2)

let newGeometry = SKWarpGeometryGrid(columns: 2, rows: 2,
                                         sourcePositions: sourcePoints,
                                         destinationPositions: destinationPoints)

effectNode.run(SKAction.warp(to: newGeometry, duration: 1.0)!)

Sources used:

https://www.hackingwithswift.com/example-code/games/how-to-warp-a-sprite-using-skwarpgeometrygrid

http://sound-of-silence.com/?page=blog&sort=recent&count=0

2) Live Copy Approach

This is simpler, there's far less code, and it's a lot more versatile; you can do things like in this Rayman Legends level https://youtu.be/7m5YQrucis8?t=1226. Also, it works.

Basically, we have our master SKView showing the master scene. We'll add a copy SKView showing a copy scene. The copy scene will have only one sprite node in it.
In the master scene's update loop, we'll grab a flattened texture of the scene and assign it to the sprite node in the copy scene. An object that is the scene's delegate can tap into this update loop, so we'll make the view controller conform to SKSceneDelegate.

class Playground_VC: UIViewController, SKSceneDelegate {

    var sprite: SKSpriteNode?

    override func loadView() {
        self.view = SKView()
    }

    var skView: SKView {
        return self.view as! SKView
    }

    override func viewWillAppear(_ animated: Bool) {
        let scene = SKScene(size: self.skView.bounds.size)
        scene.backgroundColor = UIColor.clear
        scene.delegate = self
        self.skView.presentScene(scene)

        let e = newEmitter()
        scene.addChild(e)
        e.position = self.skView.midPoint

        self.createCopy()

    }

    func update(_ currentTime: TimeInterval, for scene: SKScene) {
        // Grab the root texture and assign to the sprite that's in the copy scene
        let t = self.skView.texture(from: self.skView.scene!)
        self.sprite?.texture = t
    }

    func createCopy() {

        // Make a new SKView that's 4 times smaller

        var f = self.skView.bounds
        f.size.height *= 0.4
        f.size.width *= 0.4

        let copy = SKView(frame: f)
        copy.presentScene(SKScene(size: f.size))
        self.view.addSubview(copy)

        let sprite = SKSpriteNode(texture: nil, size: f.size)
        copy.scene?.addChild(sprite)
        self.sprite = sprite
        sprite.position = CGPoint(x: f.size.width / 2, y: f.size.height / 2)

    }

    func newEmitter() -> SKEmitterNode {
        return SKEmitterNode(fileNamed: "Particle.sks")!
    }
}

Any manipulations you perform on the master SKView, like tilting it in 3D space, shouldn't affect the appearance of the copy, because the game scene is unaffected by those manipulations.


问:
c#: Ignore argument exception / An approach or trick to make my code work
I'm doing a console app web scraper, basically using Net Core 3.0 and from the part when I want to use proxy or use my own connection I'm having an error with my approach IF statement. Please see below.

Basically if:

```<code>bool useProxy = false;
proxyFunction(proxy ? null : File.ReadAllLines(//HERE IS PATH TO FILE))
</code>```

So if the bool "useProxy" is false, it returns null which is how I wanted but it still continues on the "File.ReadAllLines" and since the bool "useProxy" is false it pretty much returns an argument exception telling it cannot be null (the File.ReadAllLines) which shouldn't be happening at the very first it shouldn't continue from there anymore as my operator "?" on the "proxyFunction" returns the null already because the bool "useProxy" is false.

Please ignore the "proxyFunction" as it's just a function from a my proxy class on HttpClient to return if bool "useProxy" is null, if not, runs the "File.ReadAllLines" and return its value.

Thank you for the time! :)

答: Did a function with try-catch statement, not a good approach when it comes to being fast/great in performance but solves the problem anyway.</p>

Body:
I'm doing a console app web scraper, basically using Net Core 3.0 and from the part when I want to use proxy or use my own connection I'm having an error with my approach IF statement. Please see below.

Basically if:

bool useProxy = false;
proxyFunction(proxy ? null : File.ReadAllLines(//HERE IS PATH TO FILE))

So if the bool "useProxy" is false, it returns null which is how I wanted but it still continues on the "File.ReadAllLines" and since the bool "useProxy" is false it pretty much returns an argument exception telling it cannot be null (the File.ReadAllLines) which shouldn't be happening at the very first it shouldn't continue from there anymore as my operator "?" on the "proxyFunction" returns the null already because the bool "useProxy" is false.

Please ignore the "proxyFunction" as it's just a function from a my proxy class on HttpClient to return if bool "useProxy" is null, if not, runs the "File.ReadAllLines" and return its value.

Thank you for the time! :)


问:
How can I import from the standard library, when my project has a module with the same name? (How can I control where Python looks for modules?)
There is a module in my project folder called calendar. Elsewhere in the code, I would like to use the standard library Calendar class. But when I try to import this class, using from calendar import Calendar, this imports from my own module instead, causing errors later.

How can I avoid this? Do I have to rename the module?

答:
Actually, solving this is rather easy, but the implementation will always be a bit fragile, because it depends python import mechanism's internals and they are subject to change in future versions.

(the following code shows how to load both local and non-local modules and how they may coexist)

```<code>def import_non_local(name, custom_name=None):
    import imp, sys

    custom_name = custom_name or name

    f, pathname, desc = imp.find_module(name, sys.path[1:])
    module = imp.load_module(custom_name, f, pathname, desc)
    f.close()

    return module

# Import non-local module, use a custom name to differentiate it from local
# This name is only used internally for identifying the module. We decide
# the name in the local scope by assigning it to the variable calendar.
calendar = import_non_local('calendar','std_calendar')

# import local module normally, as calendar_local
import calendar as calendar_local

print calendar.Calendar
print calendar_local
</code>```

The best solution, if possible, is to avoid naming your modules with the same name as standard-library or built-in module names.

Body:
Actually, solving this is rather easy, but the implementation will always be a bit fragile, because it depends python import mechanism's internals and they are subject to change in future versions.

(the following code shows how to load both local and non-local modules and how they may coexist)

def import_non_local(name, custom_name=None):
    import imp, sys

    custom_name = custom_name or name

    f, pathname, desc = imp.find_module(name, sys.path[1:])
    module = imp.load_module(custom_name, f, pathname, desc)
    f.close()

    return module

# Import non-local module, use a custom name to differentiate it from local
# This name is only used internally for identifying the module. We decide
# the name in the local scope by assigning it to the variable calendar.
calendar = import_non_local('calendar','std_calendar')

# import local module normally, as calendar_local
import calendar as calendar_local

print calendar.Calendar
print calendar_local

The best solution, if possible, is to avoid naming your modules with the same name as standard-library or built-in module names.


问:
How to set a fake GeoLocation in Chrome for Selenium
How to set a Fake GeoLocation in Chrome for Selenium? (Tried using locationcontext and also Javascript below but it doesnt seem to work)

I have tried the solution here - fake Geolocation in chrome automation but it doesn't seem to work

答:
You can use the Chrome Devtools Protocol (cdp):</p>

```<code>params = {
    "latitude": 50.1109,
    "longitude": 8.6821,
    "accuracy": 100
}

self.driver = webdriver.Chrome()
self.driver.execute_cdp_cmd("Page.setGeolocationOverride", params)
self.driver.get('https://www.google.com/maps')
</code>```

Body:
You can use the Chrome Devtools Protocol (cdp):

params = {
    "latitude": 50.1109,
    "longitude": 8.6821,
    "accuracy": 100
}

self.driver = webdriver.Chrome()
self.driver.execute_cdp_cmd("Page.setGeolocationOverride", params)
self.driver.get('https://www.google.com/maps')


问:
Applying angular material theme to a specific component only
Is it possible to apply the angular material built-in theme to a specific component only?

I did:

```<code>@import "~@angular/material/prebuilt-themes/indigo-pink.css";
</code>```

In one of my component.scss file and referenced this as the styleUrl inside of component.ts file. But the styles did not apply to my angular material paginator.

Here is what the paginator looks like

As shown, the styles do not apply.

Is it something to do with the fact that I'm importing them in a component specific scss file instead of importing it in angular.json?

答:
The best way to make each component independent of default theme in angular is to having the import statement different for each component

As usual to have a default theme for overall application we can use that import
(ex @import '@angular/material/prebuilt-themes/purple-green.css';)
in the main css file which is style.css

After that for each component we can use the other themes based on requirement.

ex: for a component named homepage we can add a different theme to the file
homepage.component.css

```<code>@import '@angular/material/prebuilt-themes/indigo-pink.css';
</code>```

and for other component like login we add a different theme for the page login.component.css

```<code>@import '@angular/material/prebuilt-themes/pink-bluegrey.css';
</code>```

This solved my issue.

Body:
Is it possible to apply the angular material built-in theme to a specific component only?

I did:

@import "~@angular/material/prebuilt-themes/indigo-pink.css";

In one of my component.scss file and referenced this as the styleUrl inside of component.ts file. But the styles did not apply to my angular material paginator.

Here is what the paginator looks like

As shown, the styles do not apply.

Is it something to do with the fact that I'm importing them in a component specific scss file instead of importing it in angular.json?

Body:
The best way to make each component independent of default theme in angular is to having the import statement different for each component

As usual to have a default theme for overall application we can use that import
(ex @import '@angular/material/prebuilt-themes/purple-green.css';)
in the main css file which is style.css

After that for each component we can use the other themes based on requirement.

ex: for a component named homepage we can add a different theme to the file
homepage.component.css

@import '@angular/material/prebuilt-themes/indigo-pink.css';

and for other component like login we add a different theme for the page login.component.css

@import '@angular/material/prebuilt-themes/pink-bluegrey.css';

This solved my issue.


问:
How to jump to a particular column in SQL Developer table view?
Suppose I have a table with 300 columns. I open a table in SQL developer and apply a filter(through UI widget) on one of the first columns. Now, I need to check the value of a particular column for the filtered row(I know the name of the column). At the moment I have to search for the column by scrolling right, but it's tedious. Is there a better approach? I know about CTRL+F but it's only for values in columns, not columns itself as far as I know.

答:
No way today.

You can hide the 290 columns you rarely look at however.

Right click on the column header, select Columns, and then remove the ones getting in your way.

I don't need to see these columns 99% of the time...


问:
Use java.time.Instant to represent DateTime instead of OffsetDateTime
I'm using the openApi maven plugin to generate java request/responses for a REST api.

The request has a DateTime property, when I run the generator I get the DateTime property of the attribute represented as java.time.OffsetDateTime. The problem is I have a requirement to represent the property as java.time.Instant.

This is the openApi specification for the request:

```<code>"DocumentDto" : {
      "type" : "object",
      "properties" : {
        "uuid" : {
          "type" : "string",
          "format" : "uuid"
        },
        "creationDate" : {
          "type" : "string",
          "format" : "date-time"
        }
      }
    }
</code>```

The generated java request:

```<code>@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-21T13:07:21.639+02:00[Europe/Zurich]")
public class DocumentDto {
  public static final String SERIALIZED_NAME_UUID = "uuid";
  @SerializedName(SERIALIZED_NAME_UUID)
  private UUID uuid;

  public static final String SERIALIZED_NAME_TEST = "creationDate";
  @SerializedName(SERIALIZED_NAME_TEST)
  private OffsetDateTime creationDate;
}
</code>```

The maven plugin setup:

```<code><plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>3.3.4</version>
    <executions>
        <execution>
            <id>test-service</id>
            <phase>validate</phase>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>
                    ${project.build.directory}/open-api/swagger.json
                </inputSpec>
                <generatorName>java</generatorName>
                <validateSpec>false</validateSpec>
                <generateApis>false</generateApis>
                <groupId>com.test</groupId>
                <artifactId>test-service</artifactId>
                <modelPackage>test.model</modelPackage>
                <apiPackage>test.api</apiPackage>
                <configOptions>
                    <sourceFolder>src/gen/java/main</sourceFolder>
                    <dateLibrary>java8</dateLibrary>
                    <java8>true</java8>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

I've already tried the typeMappings and importMappings as follow but it had no affect on the generated code:

```<code><typeMappings>DateTime=Instant</typeMappings>
<importMappings>Instant=java.time.Instant</importMappings>
</code>```

答:
Had the same problem but wanted to use LocalDateTime instead of Instant. Adding the following works, at least for entities:

```<code><configuration>
  <typeMappings>
    <typeMapping>OffsetDateTime=LocalDateTime</typeMapping>
  </typeMappings>
  <importMappings>
    <importMapping>java.time.OffsetDateTime=java.time.LocalDateTime</importMapping>
  </importMappings>
</configuration>
</code>```

i.e. an import for LocalDateTime is added, and any entity fields in the yaml with type format: date-time are mapped to LocalDateTime.

However, for api parameters, no import was added with those settings.
After a while I gave up and instead used fully qualified types so that no import is required. Just change the above typeMapping to:

```<code><typeMapping>OffsetDateTime=java.time.LocalDateTime</typeMapping>
</code>```

Your generated methods afterwards looked like:

```<code>    default ResponseEntity<List<SomeDto>> someMethodGet(
        @ApiParam(value = "") @Valid @RequestParam(value = "changeDateFrom",
            required = false) @org.springframework.format.annotation.DateTimeFormat(
                iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME) java.time.LocalDateTime changeDateFrom,
    {
        return getDelegate().someMethodGet(..., changeDateFrom, ...);
    }
</code>```

PS1 Make sure you use the most recent version of the plugin.

PS2 I used the delegate pattern.

PS2 I used the spring model.

Body:
I'm using the openApi maven plugin to generate java request/responses for a REST api.

The request has a DateTime property, when I run the generator I get the DateTime property of the attribute represented as java.time.OffsetDateTime. The problem is I have a requirement to represent the property as java.time.Instant.

This is the openApi specification for the request:

"DocumentDto" : {
      "type" : "object",
      "properties" : {
        "uuid" : {
          "type" : "string",
          "format" : "uuid"
        },
        "creationDate" : {
          "type" : "string",
          "format" : "date-time"
        }
      }
    }

The generated java request:

@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-21T13:07:21.639+02:00[Europe/Zurich]")
public class DocumentDto {
  public static final String SERIALIZED_NAME_UUID = "uuid";
  @SerializedName(SERIALIZED_NAME_UUID)
  private UUID uuid;

  public static final String SERIALIZED_NAME_TEST = "creationDate";
  @SerializedName(SERIALIZED_NAME_TEST)
  private OffsetDateTime creationDate;
}

The maven plugin setup:

<plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>3.3.4</version>
    <executions>
        <execution>
            <id>test-service</id>
            <phase>validate</phase>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>
                    ${project.build.directory}/open-api/swagger.json
                </inputSpec>
                <generatorName>java</generatorName>
                <validateSpec>false</validateSpec>
                <generateApis>false</generateApis>
                <groupId>com.test</groupId>
                <artifactId>test-service</artifactId>
                <modelPackage>test.model</modelPackage>
                <apiPackage>test.api</apiPackage>
                <configOptions>
                    <sourceFolder>src/gen/java/main</sourceFolder>
                    <dateLibrary>java8</dateLibrary>
                    <java8>true</java8>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>

I've already tried the typeMappings and importMappings as follow but it had no affect on the generated code:

<typeMappings>DateTime=Instant</typeMappings>
<importMappings>Instant=java.time.Instant</importMappings>

Body:
Had the same problem but wanted to use LocalDateTime instead of Instant. Adding the following works, at least for entities:

<configuration>
  <typeMappings>
    <typeMapping>OffsetDateTime=LocalDateTime</typeMapping>
  </typeMappings>
  <importMappings>
    <importMapping>java.time.OffsetDateTime=java.time.LocalDateTime</importMapping>
  </importMappings>
</configuration>

i.e. an import for LocalDateTime is added, and any entity fields in the yaml with type format: date-time are mapped to LocalDateTime.

However, for api parameters, no import was added with those settings.
After a while I gave up and instead used fully qualified types so that no import is required. Just change the above typeMapping to:

<typeMapping>OffsetDateTime=java.time.LocalDateTime</typeMapping>

Your generated methods afterwards looked like:

    default ResponseEntity<List<SomeDto>> someMethodGet(
        @ApiParam(value = "") @Valid @RequestParam(value = "changeDateFrom",
            required = false) @org.springframework.format.annotation.DateTimeFormat(
                iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME) java.time.LocalDateTime changeDateFrom,
    {
        return getDelegate().someMethodGet(..., changeDateFrom, ...);
    }

PS1 Make sure you use the most recent version of the plugin.

PS2 I used the delegate pattern.

PS2 I used the spring model.


问:
How to make code wait for okay/cancel button selection?
I am using JQuery's $.dialog(), where I open a dialog with OK and Cancel buttons.

I would have expected that when the dialog opens, the code stops, and would first continue, when the user had selected OK or Cancel.

Here is my complete source code
http://pastebin.com/uw7bvtn7

The section where I have the problem is at line 127-151.

```<code>$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 600,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("<h3><b>Users</b></h3>" + makeDialogTable(users) + "<h3><b>Owners</b></h3>" + makeDialogTable(owners));
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },

    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    } // buttons

}); // dialog

alert(is_okay);
</code>```

What the code does right now is to first show the dialog and then the alert(is_okay) on top.

What I would like is that the code first continues when the user have pressed OK or Cancel.

How could that be done?

答:
That can't be done in a "good" manner plus I strongly recommend not to go that way.

What you describe is a complete blocking, modal window/dialog which is just aweful for web applications. You're already creating the dialog with the modal flag, so a user can't really do anything on your site while the dialog is open, BUT the UI keeps responsive.

Again, there is actually no way to "hold" code execution. Any approach in that direction would freeze the UI thread since Javascript and UI updates share the same thread.

Since quite a few years, developers pushed Javascript to be more and more non-blocking (Javascript in browsers actually always followed that route, which is very good thing). The idea was reborn with nodeJS on the backend. So, you're swimming upstream here, don't do it.

Whatever the problem is you try to solve there, try to think in different way. Think functional, use callbacks and events, think... ECMAscript! :p

Body:
I am using JQuery's $.dialog(), where I open a dialog with OK and Cancel buttons.

I would have expected that when the dialog opens, the code stops, and would first continue, when the user had selected OK or Cancel.

Here is my complete source code
http://pastebin.com/uw7bvtn7

The section where I have the problem is at line 127-151.

$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 600,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("
Users
" + makeDialogTable(users) + "
Owners
" + makeDialogTable(owners));
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },

    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    } // buttons

}); // dialog

alert(is_okay);

What the code does right now is to first show the dialog and then the alert(is_okay) on top.

What I would like is that the code first continues when the user have pressed OK or Cancel.

How could that be done?


问:
Window.close() is not working after restart

In laravel controller I am using  tag in which on button click window.close() is working well, but when i restart my server or my PC then after it is not working.

Please give me a solution for how to close the current tab in  tag in the Laravel controller without using Javascript.
Window.close() is not working in also firefox.

答:
I tried your code and got the below error that means If your script did not initiate opening the window (with something like window.open), then the script in that window is not allowed to close it. Its a security to prevent a website taking control of your browser and closing windows.

"Scripts may close only the windows that were opened by it."


问:
Bash script to get specific user(s) id and processes count
I need bash script to count processes of SPECIFIC users or all users. We can enter 0, 1 or more arguments. For example

```<code>./myScript.sh root deamon
</code>```

should execute like this:

```<code>root      92
deamon     8
2 users has total processes: 100
</code>```

If nothing is entered as parameter, then all users should be listed:

```<code>uuidd      1
awkd       2
daemon     1
root     210
kklmn      6
  5 users has total processes: 220
</code>```

What I have till now is script for all users, and it works fine (with some warnings). I just need part where arguments are entered (some kind of filter results). Here is script for all users:

```<code>cntp = 0  #process counter
cntu = 0  #user counter

ps aux |
awk 'NR>1{tot[$1]++; cntp++}
     END{for(id in tot){printf "%s\t%4d\n",id,tot[id]; cntu++}
     printf "%4d users has total processes:%4d\n", cntu, cntp}'
</code>```

答:
The following seems to work:

```<code>ps axo user |
awk -v args="$(IFS=,; echo "$*")" '
    BEGIN {
        # split args on comma
        split(args, users, ",");
        # associative array with user as indexes
        for (i in users) {
            enabled[users[i]] = 1
        }
    }
    NR > 1 {
        tot[$1]++;
        cntp++;
    }
    END {
        for(id in tot) {

            # if we passed some arguments
            # and its disabled
            if (length(args) && enabled[id] == 0) {
                continue
            }

            printf "%s\t%4d\n", id, tot[id];
            cntu++;
        }
        printf "%4d users has total processes:%4d\n", cntu, cntp
    }
'
</code>```

Tested in repl.

Body:
I need bash script to count processes of SPECIFIC users or all users. We can enter 0, 1 or more arguments. For example

./myScript.sh root deamon

should execute like this:

root      92
deamon     8
2 users has total processes: 100

If nothing is entered as parameter, then all users should be listed:

uuidd      1
awkd       2
daemon     1
root     210
kklmn      6
  5 users has total processes: 220

What I have till now is script for all users, and it works fine (with some warnings). I just need part where arguments are entered (some kind of filter results). Here is script for all users:

cntp = 0  #process counter
cntu = 0  #user counter

ps aux |
awk 'NR>1{tot[$1]++; cntp++}
     END{for(id in tot){printf "%s\t%4d\n",id,tot[id]; cntu++}
     printf "%4d users has total processes:%4d\n", cntu, cntp}'

Body:
The following seems to work:

ps axo user |
awk -v args="$(IFS=,; echo "$*")" '
    BEGIN {
        # split args on comma
        split(args, users, ",");
        # associative array with user as indexes
        for (i in users) {
            enabled[users[i]] = 1
        }
    }
    NR > 1 {
        tot[$1]++;
        cntp++;
    }
    END {
        for(id in tot) {

            # if we passed some arguments
            # and its disabled
            if (length(args) && enabled[id] == 0) {
                continue
            }

            printf "%s\t%4d\n", id, tot[id];
            cntu++;
        }
        printf "%4d users has total processes:%4d\n", cntu, cntp
    }
'

Tested in repl.


问:
CSS how can I get an inline display with a working ::first-line pseudo-element
This looks very simple, but I couldn't get it working, either with combinations of float, inline-block and so on. I am trying to get more space on the first line so that the second one doesn't "collide" with the header. I know that ::first-line doesn't work on inline elements. I want to keep this layout (the layout is what's important, not the inline display, so whatever works is OK). The solution should have a wide browser support.

My design must stay responsive, so the text shouldn't be cut in different parts. I could do it in javascript and keep it responsive by running a script on resize, but I really would like to avoid this solution.

EDIT: @TemaniAfif's comment about setting inline-block to the header does the trick for my special case, but for curiosity and future readers, it doesn't directly answer for the pseudo-element. For example if someone wanter to capitalize or change color, I feel the question is still valid, so I'm editing the snippet.

.heading {
  padding: 5px;
  background-color: blue;
  color: white;
}
.content {
  margin-left: 5px;
}
.content::first-line {
  line-height: 2;
  text-transform: uppercase;
  color: red;
}
.block {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>Display is fine, first-line doesn't work because of inline + margin left works fine:</b>
<br><br>

<span class="heading">header: </span>
<span class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>

<br><br>
<b>Display is out now that first-line works because of block (or inline-block) + margin left out too:</b>
<br><br>

<span class="heading">header: </span>
<span class="content block">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span></code>```

答:
.box-text { position:relative;}
.box-text p::first-line { display:inline-block; position:relative; color:#ccc;}
.box-text p { display:inline-block; position:relative;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-text">

<p>header:</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

</div>

<div class="box-text">

<p>header:</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

</div>

<div class="box-text">

<p>header:</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

</div></code>```

Body:
This looks very simple, but I couldn't get it working, either with combinations of float, inline-block and so on. I am trying to get more space on the first line so that the second one doesn't "collide" with the header. I know that ::first-line doesn't work on inline elements. I want to keep this layout (the layout is what's important, not the inline display, so whatever works is OK). The solution should have a wide browser support.

My design must stay responsive, so the text shouldn't be cut in different parts. I could do it in javascript and keep it responsive by running a script on resize, but I really would like to avoid this solution.

EDIT: @TemaniAfif's comment about setting inline-block to the header does the trick for my special case, but for curiosity and future readers, it doesn't directly answer for the pseudo-element. For example if someone wanter to capitalize or change color, I feel the question is still valid, so I'm editing the snippet.

.heading {
  padding: 5px;
  background-color: blue;
  color: white;
}
.content {
  margin-left: 5px;
}
.content::first-line {
  line-height: 2;
  text-transform: uppercase;
  color: red;
}
.block {
  display: block;
}

Display is fine, first-line doesn't work because of inline + margin left works fine:

header:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Display is out now that first-line works because of block (or inline-block) + margin left out too:

header:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Body:
.box-text { position:relative;}
.box-text p::first-line { display:inline-block; position:relative; color:#ccc;}
.box-text p { display:inline-block; position:relative;}

<div class="box-text">

<p>header:</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

</div>

<div class="box-text">

<p>header:</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

</div>

<div class="box-text">

<p>header:</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

</div>


问:
How to migrate svn repository to git with svn2git?
I want to migrate a repository from svn to git. I'm using svn2git from this repository: https://github.com/svn-all-fast-export/svn2git

When I do :  svn2git/svn-all-fast-export --rules ruleset/module svn/module

I get this error:

```<code>svn: E000002: : Can't open file 'svn/module/format': No such file or directory
</code>```

This Format file does not exist.

Where the svn/module folder is my repository that contains a trunk folder and tags folder, both with files inside.

The ruleset/module file has:

```<code>create repository module
end repository

match /trunk/module/
  repository module/
  branch master
end match

match /tags/module_(\d+)
  repository module
  branch master
end match
</code>```

Does anyone know how to solve this problem?

答:
You are probably trying to convert svn working copy not a repository.
If your repository is hosted at remote location then first create a dump using svnadmin.

```<code>svnadmin dump
</code>```

Then create a local repo:

```<code>svnadmin create /path/to/repo
</code>```

Check svnadmin help create for compatibility options. You might need to use

```<code>--pre-1.6-compatible
</code>```

Then load the dump svnadmin load /path/to/repo < dump

Then you can migrate the newly created local repo.

Body:
I want to migrate a repository from svn to git. I'm using svn2git from this repository: https://github.com/svn-all-fast-export/svn2git

When I do :  svn2git/svn-all-fast-export --rules ruleset/module svn/module

I get this error:

svn: E000002: : Can't open file 'svn/module/format': No such file or directory

This Format file does not exist.

Where the svn/module folder is my repository that contains a trunk folder and tags folder, both with files inside.

The ruleset/module file has:

create repository module
end repository

match /trunk/module/
  repository module/
  branch master
end match

match /tags/module_(\d+)
  repository module
  branch master
end match

Does anyone know how to solve this problem?

Body:
You are probably trying to convert svn working copy not a repository.
If your repository is hosted at remote location then first create a dump using svnadmin.

svnadmin dump

Then create a local repo:

svnadmin create /path/to/repo

Check svnadmin help create for compatibility options. You might need to use

--pre-1.6-compatible

Then load the dump svnadmin load /path/to/repo < dump

Then you can migrate the newly created local repo.


问:
I want modify dialog height and maintain the background
I would like to adjust the height of an existing dialog, but keep scrollabble and background color, currently if I give it height then the background color will only expand at the specified height if scrolling down then the height will be lost.

Here is the code of dialogs height:

```<code>  @media (min-width: 768px) {
    .dialog-layout-modal-body {
    max-height: 662px;
  }
}
</code>```

If I give it a background color then it fills in at full screen width, I wouldn't want that.

What is the solution to keep the background color down, but I can adjust the height of the dialog?

答:
```<code>@media (min-width: 768px) {
    .dialog-layout-modal-body { overflow-y: auto;}
}
</code>```

Hope this will help.

Body:
I would like to adjust the height of an existing dialog, but keep scrollabble and background color, currently if I give it height then the background color will only expand at the specified height if scrolling down then the height will be lost.

Here is the code of dialogs height:

  @media (min-width: 768px) {
    .dialog-layout-modal-body {
    max-height: 662px;
  }
}

If I give it a background color then it fills in at full screen width, I wouldn't want that.

What is the solution to keep the background color down, but I can adjust the height of the dialog?

Body:
@media (min-width: 768px) {
    .dialog-layout-modal-body { overflow-y: auto;}
}

Hope this will help.


问:
Postgis: How do I select every second point from LINESTRING?
In DBeaver I have a table containing some GPS coordinates stored as Postgis LINESTRING format.
My questions is: If I have, say, this info:

```<code>LINESTRING(20 20, 30 30, 40 40, 50 50, 60 60, 70 70)
</code>```

which built-in ST function can I use to get every N-th element in that LINESTRING? For example, if I choose 2, I would get:

```<code>LINESTRING(20 20, 40 40, 60 60)
</code>```

, if 3:

```<code>LINESTRING(20 20, 50 50)
</code>```

and so on.

I've tried with ST_SIMPLIFY and ST_POINTN, but that's now exactly what I need because I still want it to stay a LINESTRING but just with less points (lower resolution).

Any ideas?

Thanks :-)

答:
Welcome to SO. Have you tried using ST_DumpPoints and applying a module % over the vertices path? e.g. every second record:

```<code>WITH j AS (
SELECT
  ST_DumpPoints('LINESTRING(20 20, 30 30, 40 40, 50 50, 60 60, 70 70)') AS point
)
SELECT ST_AsText(ST_MakeLine((point).geom)) FROM j
WHERE (point).path[1] % 2 = 0;

           st_astext
-------------------------------
 LINESTRING(30 30,50 50,70 70)
(1 Zeile)
</code>```

Further reading:

ST_MakeLine

CTE

Body:
In DBeaver I have a table containing some GPS coordinates stored as Postgis LINESTRING format.
My questions is: If I have, say, this info:

LINESTRING(20 20, 30 30, 40 40, 50 50, 60 60, 70 70)

which built-in ST function can I use to get every N-th element in that LINESTRING? For example, if I choose 2, I would get:

LINESTRING(20 20, 40 40, 60 60)

, if 3:

LINESTRING(20 20, 50 50)

and so on.

I've tried with ST_SIMPLIFY and ST_POINTN, but that's now exactly what I need because I still want it to stay a LINESTRING but just with less points (lower resolution).

Any ideas?

Thanks :-)

Body:
Welcome to SO. Have you tried using ST_DumpPoints and applying a module % over the vertices path? e.g. every second record:

WITH j AS (
SELECT
  ST_DumpPoints('LINESTRING(20 20, 30 30, 40 40, 50 50, 60 60, 70 70)') AS point
)
SELECT ST_AsText(ST_MakeLine((point).geom)) FROM j
WHERE (point).path[1] % 2 = 0;

           st_astext
-------------------------------
 LINESTRING(30 30,50 50,70 70)
(1 Zeile)

Further reading:

ST_MakeLine

CTE


问:
TextField with Label over the border at Top-Left position
I need to implement outline textfield with placeholder in my swift project one like the Material UI. I tried googling for the same but could not found anything. Anyone know how to achieve it in swift?
Reference Images:

答:
You can use Material Components:-

It will be looking like this below.

https://material.io/components/text-fields/

Github repo - https://github.com/material-components/material-components-ios


问:
Do I need Nginx with Gunicorn if I am not serving any static content?
In a typical python server setup it is recommended to have Nginx web server serve the static content and proxy the dynamic requests to  Gunicorn app server.
Now if I am not serving any static content through my python application do I still need Nginx in front of Gunicorn ? What would be the advantages ?
Detailed explanation would be really appreciated.

All the static content is served through CDN and the backend server will only need to serve the APIs(REST). So when I will only server dynamic content, will I need to have Nginx ? Does it have any advantage in case of high load etc.

答:
It is recommended in Gunicorn docs to run it behind a proxy server.

Technically, you don't really need Nginx.

BUT it's the Internet: your server will receive plenty of malformed HTTP requests which are made by bots and vulnerability scanner scripts. Now, your Gunicorn process will be busy parsing and dealing with these requests instead of serving genuine clients.

With Nginx in front, it will terminate these requests without forwarding to your Gunicorn backend.

Most of these bots make requests to your IP address, instead of your domain name. So it's really easy to configure Nginx to ignore requests made to IP address and only serve requests made to your domain. This is far more secure and faster than relying on Django's ALLOWED_HOSTS settings.

Also, it's much easier to find resources for Nginx about protecting your server, like blacklisting rogue IP addresses or user agents, etc. Compare these two google searches: nginx ban ip vs gunicorn ban ip. You can see Nginx search has more resources.

If you're worried about performance, then rest assured Nginx will not be the bottleneck. If you really want to optimise performance, database querying will be the first place to start.


问:
Django-Secretballot does not work?
I am using Django-secretballot app which allows anonymous voting. First we register a model for secret voting and then there is a function add_vote() which takes 2 arguments. 'Token' and vote value(+1 or -1).

from docs:

add_vote:

function that takes a token and a vote (+1 or -1) and adds or updates the vote for said     token (can be renamed by passing add_vote_name parameter to enable_voting_on)

What am I supposed to pass in as 'Token'?
I used this in my views.py

```<code>t=request.META['REMOTE_ADDR']
feed.add_vote(t,+1)
</code>```

Yet it does not work. I mean if I try voting from different machines, only first vote gets counted. But it does not get incremented when other vote for that same feed.

Anyone who has used this app or figured out what I am doing wrong by checking the doc. Please help.

答:
I'm the author and although I haven't actively developed it recently I hope you find it useful.

token can be any unique string you require, generally speaking what you have should work but there's a chance you're behind a proxy or there's another issue with REMOTE_ADDR in your server config (which is beyond what I'd be able to assist with)

Check that the value of REMOTE_ADDR is actually changing, also consider using a combination of  REMOTE_ADDR and something else like a User Agent or unique value stored in a cookie.

Title: Django-Secretballot does not work?

Body:
I am using Django-secretballot app which allows anonymous voting. First we register a model for secret voting and then there is a function add_vote() which takes 2 arguments. 'Token' and vote value(+1 or -1).

from docs:

add_vote:

function that takes a token and a vote (+1 or -1) and adds or updates the vote for said     token (can be renamed by passing add_vote_name parameter to enable_voting_on)

What am I supposed to pass in as 'Token'?
I used this in my views.py

t=request.META['REMOTE_ADDR']
feed.add_vote(t,+1)

Yet it does not work. I mean if I try voting from different machines, only first vote gets counted. But it does not get incremented when other vote for that same feed.

Anyone who has used this app or figured out what I am doing wrong by checking the doc. Please help.


问:
How to render element in React.js from object map
I have a question about rendering components from object map. I have a structure like this:

```<code>const tabs = [
    'tab1': {
        name: 'Tab 1',
        renderComponent: () => <Tab1Component />
    },
    'tab2': {
        name: 'Tab 2',
        renderComponent: () => <Tab2Component />
    }
];
</code>```

I want to access the renderComponent property and render sub component.
Tried with function invocation, React.createElement(), doesn't work.

```<code>const MyComponent = ({tabs}) => {
    const activeTab = 'tab1';
    return (
        <>
        // How to render it?
        // function invocation?
        // createElement??
            tabs[activeTab].renderComponent();
        </>
    );
};
</code>```

答:
Here things i guess you did wrong is

1) adding the single quotes around the object-key

2) writing key-value pairs in array without enclosing it in {}

I think you should do something like this

```<code>const tabs = [
        {
            tab1: {
                name: 'Tab 1',
                renderComponent: () => <Tab1Component />
            },
            tab: {
                name: 'Tab 2',
                renderComponent: () => <Tab1Component />
            }
        }
    ];

    const activeTab = 'tab1';
</code>```

and

```<code>const MyComponent = ({tabs}) => {
    const activeTab = 'tab1';
    return (
        <>
        // How to render it?
        // function invocation?
        // createElement??
            tabs[0][activeTab].renderComponent();
        </>
    );
};
</code>```

Body:
I have a question about rendering components from object map. I have a structure like this:

const tabs = [
    'tab1': {
        name: 'Tab 1',
        renderComponent: () => <Tab1Component />
    },
    'tab2': {
        name: 'Tab 2',
        renderComponent: () => <Tab2Component />
    }
];

I want to access the renderComponent property and render sub component.
Tried with function invocation, React.createElement(), doesn't work.

const MyComponent = ({tabs}) => {
    const activeTab = 'tab1';
    return (
        <>
        // How to render it?
        // function invocation?
        // createElement??
            tabs[activeTab].renderComponent();
        </>
    );
};

Body:
Here things i guess you did wrong is

1) adding the single quotes around the object-key

2) writing key-value pairs in array without enclosing it in {}

I think you should do something like this

const tabs = [
        {
            tab1: {
                name: 'Tab 1',
                renderComponent: () => <Tab1Component />
            },
            tab: {
                name: 'Tab 2',
                renderComponent: () => <Tab1Component />
            }
        }
    ];

    const activeTab = 'tab1';

and

const MyComponent = ({tabs}) => {
    const activeTab = 'tab1';
    return (
        <>
        // How to render it?
        // function invocation?
        // createElement??
            tabs[0][activeTab].renderComponent();
        </>
    );
};


问:
Vue props become null on $router.go(-1)
I am trying to route back on the 2nd page like this.
This is the 3rd page

```<code> <v-btn text small @click="$router.go(-1)">
   <v-icon>fas fa-arrow-left</v-icon>
 </v-btn>
</code>```

This is my App.vue

```<code><keep-alive :max="40">
  <router-view :key="$route.fullPath"></router-view>
</keep-alive>
</code>```

This are my 2nd page props.

```<code>props: {
    abc: {
      type: String,
      default() {
        return null;
      }
    },
    xyz: {
      type: Array,
      default() {
        return null;
      }
    }
  },
</code>```

Now the 2nd page has props in it. Now when i route back from 3rd page the props in the previous
component is set to null.
Is there a way to handle this props from being setting it to null on routing back.

答:
You should use keep-alive to fix this problem, or instead use vuex
to pass the data to the route, because when you are going back your route doesn't have any passed props, because it received it from another component our route,

vuex well make global state management that will contain your data and you can access it from anywhere

Title: Vue props become null on $router.go(-1)

Body:
I am trying to route back on the 2nd page like this.
This is the 3rd page

 <v-btn text small @click="$router.go(-1)">
   <v-icon>fas fa-arrow-left</v-icon>
 </v-btn>

This is my App.vue

<keep-alive :max="40">
  <router-view :key="$route.fullPath"></router-view>
</keep-alive>

This are my 2nd page props.

props: {
    abc: {
      type: String,
      default() {
        return null;
      }
    },
    xyz: {
      type: Array,
      default() {
        return null;
      }
    }
  },

Now the 2nd page has props in it. Now when i route back from 3rd page the props in the previous
component is set to null.
Is there a way to handle this props from being setting it to null on routing back.


问:
Apply with Linkedin Button does not work with Chrome 80?
We have a problem with Linkedin button that we have implemented on our job portal that users can apply directly with their Linkedin account. With the last Chrome Update (80) , users can not login linkedin with script generated button therefore It is not possible to apply with linkedin button. I guess it happens because the script from Linkedin has no samesite attribute. Info: https://blog.heroku.com/chrome-changes-samesite-cookie Are you familiar with this Problem? Can you please help me with the problem?

https://s5.gifyu.com/images/Chrome80ApplyWithLinkedin.gif

答:
The error message there states that your instance of Chrome is not yet blocking the cookies, so it's unlikely that the SameSite attribute is the cause of the issue here. However, you can verify this by taking the following steps.

Check your browser at https://samesite-sandbox.glitch.me - if all the rows are green with ✅ then your browser is using the new behaviour.

You can toggle this behaviour on and off via chrome://flags. Enter the following in your location bar:

chrome://flags/#same-site-by-default-cookies

chrome://flags/#cookies-without-same-site-must-be-secure

Set both to "Disabled".

Try your site in an incognito window so that you can be sure there are no old cookies set. If you still receive the error, then this is highly unlikely to be related to the SameSite attribute.

I don't know how long ago your initial implementation was, but it does look as if there were some updates to the API at the end of 2018: https://learn.microsoft.com/en-us/linkedin/talent/apply-with-linkedin


问:
Kill process that raises Device or resource busy: '/dev/ttyUSB0'?
I connect to my Arduino board with the following Python code.

```<code>device=glob.glob("/dev/ttyUSB*")[0]
time.sleep(1)
arduino = serial.Serial(device, 115200, timeout=5)
</code>```

It generally works, but somehow some other process must be accessing the board after reboot giving me the error

serial.serialutil.SerialException: could not open port /dev/ttyUSB0: [Errno 16] Device or resource busy: '/dev/ttyUSB0'

When unplugging and replugging the USB-plug I can execute the Python code normally, without the error occuring. How can I avoid any other process blocking the port? And how do I find out the reason for this error?

答:
In my case

```<code>$ fuser /dev/ttyUSB0
</code>```

was not working (it showed nothing).

What was working, however, was the following:

```<code>$ sudo lsof /dev/ttyUSB0
</code>```

This gave me a list of the processes that were using my serial port and I could simply kill them using the PID (corresponding to the second column in the list).

Body:
I connect to my Arduino board with the following Python code.

device=glob.glob("/dev/ttyUSB*")[0]
time.sleep(1)
arduino = serial.Serial(device, 115200, timeout=5)

It generally works, but somehow some other process must be accessing the board after reboot giving me the error

serial.serialutil.SerialException: could not open port /dev/ttyUSB0: [Errno 16] Device or resource busy: '/dev/ttyUSB0'

When unplugging and replugging the USB-plug I can execute the Python code normally, without the error occuring. How can I avoid any other process blocking the port? And how do I find out the reason for this error?

Body:
In my case

$ fuser /dev/ttyUSB0

was not working (it showed nothing).

What was working, however, was the following:

$ sudo lsof /dev/ttyUSB0

This gave me a list of the processes that were using my serial port and I could simply kill them using the PID (corresponding to the second column in the list).


问:
Schedule sending http requests to particular site
I want some way to be notified whenever a new result appears for search query in particular site. The site does not provide any feature(via RSS, alerts ..etc) for this. One way I think to accomplish this would be to send http request (for search) and process http response to send mail for any new result which comes up.The search parameters can be static or better taken from a source (like a csv file). Does anyone know of an existing solution/s preferably online which can accomplish this.

Thanks,
Jeet

答: That would depend on the particular site you want to query.</p>


问:
Remove an item from a list of objects - Typescript
I want to remove a specific object from a list. The object model looks like this:

```<code>export class Task {
  taskId: number;
  projectId: Project;
  userId: User;
  state: string;
  description: string;
}
</code>```

I created a list of Task objects and I want to delete a Task that has a specific taskId.

```<code> moveTaskInProgress(task: Task) {
    console.log('The task is in progress...');
    task.state = 'IN_PROGRESS';
    this.taskService.updateTask(task).subscribe((nbOfUpdates) => {
      console.log('Number of updates: ' + JSON.stringify(nbOfUpdates));
      this.removeItemFromAListOfTasks(task, this.openTasks);
      console.log('List of task task: ' + JSON.stringify(this.openTasks));
    });
 }

  removeItemFromAListOfTasks(task: Task, listOfTasks: Task[]) {
    let filteredList: Task[];
    filteredList = listOfTasks.filter(item => item.taskId !== task.taskId);
  }
</code>```

I have a method that receive a task, call a method that updates some properties, and after that i want to delete the task from the list.

But it seems that nothing happen. Could you, please, help me with this?

答:
You could send only the ID instead of sending the complete object.

```<code>removeItemFromAListOfTasks(id: any, listOfTasks: Task[]) {
  return listOfTasks.filter(tast => task.taskId !== id);
}
</code>```

Now it can be called like

```<code>this.openTasks = this.removeItemFromAListOfTasks(task.taskId, this.openTasks);
</code>```

Body:
I want to remove a specific object from a list. The object model looks like this:

export class Task {
  taskId: number;
  projectId: Project;
  userId: User;
  state: string;
  description: string;
}

I created a list of Task objects and I want to delete a Task that has a specific taskId.

 moveTaskInProgress(task: Task) {
    console.log('The task is in progress...');
    task.state = 'IN_PROGRESS';
    this.taskService.updateTask(task).subscribe((nbOfUpdates) => {
      console.log('Number of updates: ' + JSON.stringify(nbOfUpdates));
      this.removeItemFromAListOfTasks(task, this.openTasks);
      console.log('List of task task: ' + JSON.stringify(this.openTasks));
    });
 }

  removeItemFromAListOfTasks(task: Task, listOfTasks: Task[]) {
    let filteredList: Task[];
    filteredList = listOfTasks.filter(item => item.taskId !== task.taskId);
  }

I have a method that receive a task, call a method that updates some properties, and after that i want to delete the task from the list.

But it seems that nothing happen. Could you, please, help me with this?

Body:
You could send only the ID instead of sending the complete object.

removeItemFromAListOfTasks(id: any, listOfTasks: Task[]) {
  return listOfTasks.filter(tast => task.taskId !== id);
}

Now it can be called like

this.openTasks = this.removeItemFromAListOfTasks(task.taskId, this.openTasks);


问:
I'm using Visual studio 2019 and my project's name ends with .Sln insted of .cpp
I'm new to programming I use visual studio 2019 and when I'm creating a new project the project's name always end with .Sln instead of .cpp</p>

答: .sln is a diminutive for solution, it's a Visual Studio executable that has some basic configurations like the VS version you are using, the project id, name, and things like that, as you execute this, it will open your .vcxproj that has all the global configurations of the project, .cpp file names, etc. and will open your project. If you look in your project folder you should have at least a .cpp file.