问:
How can I save only 'Show <> entries" state in datatables in HTML?
I am trying to save the state of showing entries in datatable but I cant, I tried by using stateSave: true and it works for saving the state for everything in the datable but in my case I just want to save the state for number of entries to show in a table.

Here is my entire code:

```<code> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="../style.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">

<body>

<div class="content">
    <table id="dt-filter-select" class="display compact" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Dev.no</th>
                <th>IMEI</th>
                <th>Serial no.</th>
                <th>Barcode</th>
                <th>Device</th>
                <th>Date added on stock</th>
                <th>Client</th>
                <th>Sales date</th>
            </tr>
        </thead>

        <tbody>
            <?php if (!empty($devices)) { ?>
                <?php foreach ($devices as $device) : ?>
                    <tr>
                        <td>
                            <?php echo $device["device_no"] ?>
                        </td>

                        <td>
                            <?php echo $device["serial_imei"] ?>
                        </td>

                        <td>
                            <?php echo $device["serial_no"] ?>
                        </td>

                        <td>
                            <?php echo $device["barcode"] ?>
                        </td>

                        <td>
                            <?php echo $device["dev_name"] ?>
                        </td>

                        <td>
                            <?php echo $device["created_date"] ?>
                        </td>

                        <td>
                            <?php echo $device["name"] ?>
                        </td>

                        <td>
                            <?php echo $device["sales_date"] ?>
                        </td>

                    </tr>
                <?php endforeach; ?>
            <?php } ?>

        </tbody>
        <tfoot>
            <tr>
                <th>
                </th>
                <th>
                </th>
                <th>
                </th>
                <th>
                </th>
                <th>
                </th>
                <th>
                </th>
                <th>
                </th>
                <th>
                </th>
            </tr>
        </tfoot>
    </table>
</div>
<script>
    $(document).ready(function() {
        $('#dt-filter-select').dataTable({
            initComplete: function() {
               stateSave: true,
                this.api().columns().every(function() {
                    var column = this;
                    var select = $('<select  class="browser-default custom-select form-control-sm"><option value="" selected>Filter</option></select>')
                        .appendTo($(column.footer()).empty())
                        .on('change', function() {
                            var val = $.fn.dataTable.util.escapeRegex(
                                $(this).val()
                            );
                            column
                                .search(val ? '^' + val + '$' : '', true, false)
                                .draw();
                        });
                    column.data().unique().sort().each(function(d, j) {
                        select.append('<option value="' + d + '">' + d + '</option>')
                    });
                });
            }
        });
    });

</script>
</body>
</code>```

答:
You need to move stateSave: true, one line up, before initComplete: function() {. both stateSave and initComplete are properties of the same object you need to pass as a parameter to dataTable.

Now you can check 'localstorage' with your browser developer tools.

Explanation: State Saving

save with a callback stateSaveCallback

load with callback stateLoadCallback

To save and load specific data, you need to adjust the data attribute you are passing to the callback functions.

Body:
I am trying to save the state of showing entries in datatable but I cant, I tried by using stateSave: true and it works for saving the state for everything in the datable but in my case I just want to save the state for number of entries to show in a table.

Here is my entire code:

 <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="../style.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" />

<meta name="viewport" content="width=device-width, initial-scale=1">

                Dev.no
                IMEI
                Serial no.
                Barcode
                Device
                Date added on stock
                Client
                Sales date

            <?php if (!empty($devices)) { ?>
                <?php foreach ($devices as $device) : ?>

                            <?php echo $device["device_no"] ?>

                            <?php echo $device["serial_imei"] ?>

                            <?php echo $device["serial_no"] ?>

                            <?php echo $device["barcode"] ?>

                            <?php echo $device["dev_name"] ?>

                            <?php echo $device["created_date"] ?>

                            <?php echo $device["name"] ?>

                            <?php echo $device["sales_date"] ?>

                <?php endforeach; ?>
            <?php } ?>


来源: stackexchange

问:
Trying to embed another intranet site in react
I am trying to build a react application where in I have created a menu of "Help". In Help, I am putting iFrame code to show intranet site, confluence pages, and show documents and videos. Problem is that confluence page also has header and my app also has its own. Is there any way to pick selected area of another web app in my react app.</p>

```<code><div>
           <Iframe url="https://community.intranet.com/community/pages/home"
            width="100%"
            height="450px"
            id="myId"
            className="myClassname"
            display="initial"
            position="relative"/>

          </div>
</code>```

答:
You can do it with css:

```<code>        <div style={{ marginTop: -50 }}> //whatever is the height of the confluence page header
          <Iframe
            url="https://community.intranet.com/community/pages/home"
            width="100%"
            height="450px"
            id="myId"
            className="myClassname"
            display="initial"
            position="relative"
          />
        </div>
</code>```

This is a workaround solution in case if you dont find any other.but it works,tested.

ContentLicense: CC BY-SA 4.0

Body:
You can do it with css:

        <div style={{ marginTop: -50 }}> //whatever is the height of the confluence page header
          <Iframe
            url="https://community.intranet.com/community/pages/home"
            width="100%"
            height="450px"
            id="myId"
            className="myClassname"
            display="initial"
            position="relative"
          />
        </div>

This is a workaround solution in case if you dont find any other.but it works,tested.


问:
StoryBook addon-docs: "No props found for this component" using TypeScript
I have an issue with a project based on TypeScript and StoryBook:

Table with component properties is not created and visible in StoryBook "Docs" tab on a project setup with TypeScript.

And a text ""No props found for this component" is shown instead (please look at screenshot attached).

I would need to show the table with listed the properties in this case "name".

What am I doing wrong in the setup?

Code snippets

Test.tsx

```<code>import * as React from 'react';

type TestProps = {
 /**
  * Description of prop "name".
  */
  name: string;
};

export function Test({ name }: TestProps) {
  return <div>{name}</div>;
}

</code>```

Test.stories.tsx

```<code>import { storiesOf } from '@storybook/react';
import * as React from 'react';
import { Test } from './Test';

storiesOf('00_Test', module)
  .addParameters({ component: Test })
  .add('Test', () => <Test name="Hello world!" />);

</code>```

System:

```<code>System:
    OS: macOS 10.15.4
    CPU: (8) x64 Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
  Binaries:
    Node: 10.16.0 - ~/.nvm/versions/node/v10.16.0/bin/node
    Yarn: 1.17.3 - /usr/local/bin/yarn
    npm: 6.14.4 - ~/.nvm/versions/node/v10.16.0/bin/npm
  Browsers:
    Chrome: 83.0.4103.61
    Firefox: 76.0.1
    Safari: 13.1
  npmPackages:
    @storybook/addon-actions: ^5.3.19 => 5.3.19
    @storybook/addon-docs: ^5.3.19 => 5.3.19
    @storybook/addon-info: ^5.3.19 => 5.3.19
    @storybook/addon-knobs: ^5.3.19 => 5.3.19
    @storybook/addon-links: ^5.3.19 => 5.3.19
    @storybook/addon-storyshots: ^5.3.19 => 5.3.19
    @storybook/addons: ^5.3.19 => 5.3.19
    @storybook/react: ^5.3.19 => 5.3.19
    @storybook/theming: ^5.3.19 => 5.3.19

</code>```

Additional context

package.json

```<code>"react": "^16.12.0",
"react-dom": "^16.12.0",
  "typescript": "^3.7.5"
</code>```

.storybook/main.js

```<code>module.exports = {
  stories: ['../src/**/*.stories.tsx'],
  addons: [
    '@storybook/addon-actions/register',
    '@storybook/addon-knobs/register',
    '@storybook/addon-docs'
  ]
};
</code>```

.storybook/webpack.config.js

```<code>module.exports = ({ config }) => {
  addons: [
    {
      name: '@storybook/addon-docs',
      options: {
        configureJSX: true,
        babelOptions: {},
        sourceLoaderOptions: null,
      },
    },
  ],
  config.module.rules.push({
    test: /\.(ts|tsx)$/,
    use: [
      {
        loader: require.resolve("awesome-typescript-loader")
      },
    ]
  });
  config.resolve.extensions.push(".ts", ".tsx");
  return config;
};
</code>```

答:
I was able to solve this issue, basically I had misconfigured the webpack.config.js for StoryBook,

```<code>      {
        loader: require.resolve('react-docgen-typescript-loader'),
      },
</code>```

I hope can help others.

Full version:

.storybook/webpack.config.js

```<code>module.exports = ({ config }) => {
  addons: [
    {
      name: '@storybook/addon-docs',
      options: {
        configureJSX: true,
        babelOptions: {},
        sourceLoaderOptions: null,
      },
    },
  ],
  config.module.rules.push({
    test: /\.(ts|tsx)$/,
    use: [
      {
        loader: require.resolve("awesome-typescript-loader")
      },
      {
        loader: require.resolve('react-docgen-typescript-loader'),
      },
    ]
  });
  config.resolve.extensions.push(".ts", ".tsx");
  return config;
};

</code>```

Body:
I have an issue with a project based on TypeScript and StoryBook:

Table with component properties is not created and visible in StoryBook "Docs" tab on a project setup with TypeScript.

And a text ""No props found for this component" is shown instead (please look at screenshot attached).

I would need to show the table with listed the properties in this case "name".

What am I doing wrong in the setup?

Code snippets

Test.tsx

import * as React from 'react';

type TestProps = {
 /**
  * Description of prop "name".
  */
  name: string;
};

export function Test({ name }: TestProps) {
  return
{name}
;
}

Test.stories.tsx

import { storiesOf } from '@storybook/react';
import * as React from 'react';
import { Test } from './Test';

storiesOf('00_Test', module)
  .addParameters({ component: Test })
  .add('Test', () => <Test name="Hello world!" />);

System:

System:
    OS: macOS 10.15.4
    CPU: (8) x64 Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
  Binaries:
    Node: 10.16.0 - ~/.nvm/versions/node/v10.16.0/bin/node
    Yarn: 1.17.3 - /usr/local/bin/yarn
    npm: 6.14.4 - ~/.nvm/versions/node/v10.16.0/bin/npm
  Browsers:
    Chrome: 83.0.4103.61
    Firefox: 76.0.1
    Safari: 13.1
  npmPackages:
    @storybook/addon-actions: ^5.3.19 => 5.3.19
    @storybook/addon-docs: ^5.3.19 => 5.3.19
    @storybook/addon-info: ^5.3.19 => 5.3.19
    @storybook/addon-knobs: ^5.3.19 => 5.3.19
    @storybook/addon-links: ^5.3.19 => 5.3.19
    @storybook/addon-storyshots: ^5.3.19 => 5.3.19
    @storybook/addons: ^5.3.19 => 5.3.19
    @storybook/react: ^5.3.19 => 5.3.19
    @storybook/theming: ^5.3.19 => 5.3.19

Additional context

package.json

"react": "^16.12.0",
"react-dom": "^16.12.0",
  "typescript": "^3.7.5"

.storybook/main.js

module.exports = {
  stories: ['../src/**/*.stories.tsx'],
  addons: [
    '@storybook/addon-actions/register',
    '@storybook/addon-knobs/register',
    '@storybook/addon-docs'
  ]
};

.storybook/webpack.config.js

module.exports = ({ config }) => {
  addons: [
    {
      name: '@storybook/addon-docs',
      options: {
        configureJSX: true,
        babelOptions: {},
        sourceLoaderOptions: null,
      },
    },
  ],
  config.module.rules.push({
    test: /\.(ts|tsx)$/,
    use: [
      {
        loader: require.resolve("awesome-typescript-loader")
      },
    ]
  });
  config.resolve.extensions.push(".ts", ".tsx");
  return config;
};

Body:
I was able to solve this issue, basically I had misconfigured the webpack.config.js for StoryBook,

      {
        loader: require.resolve('react-docgen-typescript-loader'),
      },

I hope can help others.

Full version:

.storybook/webpack.config.js

module.exports = ({ config }) => {
  addons: [
    {
      name: '@storybook/addon-docs',
      options: {
        configureJSX: true,
        babelOptions: {},
        sourceLoaderOptions: null,
      },
    },
  ],
  config.module.rules.push({
    test: /\.(ts|tsx)$/,
    use: [
      {
        loader: require.resolve("awesome-typescript-loader")
      },
      {
        loader: require.resolve('react-docgen-typescript-loader'),
      },
    ]
  });
  config.resolve.extensions.push(".ts", ".tsx");
  return config;
};


问:
jquery animate scrolltop callback
I have the following jquery that scrolls the page to the top, then performs a callback function.

The problem is that even if the page is already at the top, it still waits for the '1000' to elapse before performing the callback, which i dont want it to.

```<code>$('html').animate({scrollTop:0}, 1000, 'swing', function(){

//do something

});
</code>```

答:
```<code>var html=$('html');
if(html.scrollTop()>0){
  html.animate({scrollTop:0}, 1000, 'swing', function(){
  //do something
});
}else{
  //do something
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: jquery animate scrolltop callback

Body:
I have the following jquery that scrolls the page to the top, then performs a callback function.

The problem is that even if the page is already at the top, it still waits for the '1000' to elapse before performing the callback, which i dont want it to.

$('html').animate({scrollTop:0}, 1000, 'swing', function(){

//do something

});


问:
Christmas Tree using while in Java
I can write code for Christmas Tree using for loop. Now, I want to write that code with while loop.  I just can't figure out what I'm doing wrong.

```<code>public static void main(String[] args) {
             int i = 0;
             int j =0;
             int k =0;
             while(i<10){
                 while(j<10-i){
                     System.out.print(" ");
                     j++;

                 }
                 while(k<(2*i)+1){
                     System.out.print("*");
                     k++;

                 }
                 ++i;
                 System.out.println("");

             }
}
</code>```

I expect the output of code to be like the christmas tree. But, the actual output is:

```<code>          *
**
**
**
**
**
**
**
**
**
</code>```

答:
You just need to put the loop indices j and k into the outer loop, such that they are reset to 0 in each iteration.

public static void main(String[] args) {
             int i = 0;
             while(i<10){
                 int j = 0;
                 int k = 0;
                 while(j<10-i){
                     System.out.print(" ");
                     j++;
                 }
                 while(k<(2*i)+1){
                     System.out.print("*");
                     k++;
                 }
                 ++i;
                 System.out.println("");
             }
}
```

<p>Then it will print the following tree:</p>

```          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************
```

Title: Christmas Tree using while in Java

Body:
I can write code for Christmas Tree using for loop. Now, I want to write that code with while loop.  I just can't figure out what I'm doing wrong.

public static void main(String[] args) {
             int i = 0;
             int j =0;
             int k =0;
             while(i<10){
                 while(j<10-i){
                     System.out.print(" ");
                     j++;

                 }
                 while(k<(2*i)+1){
                     System.out.print("*");
                     k++;

                 }
                 ++i;
                 System.out.println("");

             }
}

I expect the output of code to be like the christmas tree. But, the actual output is:

          *
**
**
**
**
**
**
**
**
**

Body:
You just need to put the loop indices j and k into the outer loop, such that they are reset to 0 in each iteration.

public static void main(String[] args) {
             int i = 0;
             while(i<10){
                 int j = 0;
                 int k = 0;
                 while(j<10-i){
                     System.out.print(" ");
                     j++;
                 }
                 while(k<(2*i)+1){
                     System.out.print("*");
                     k++;
                 }
                 ++i;
                 System.out.println("");
             }
}

Then it will print the following tree:

          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************


问:
Accessing react native StyleSheet member via dynamic key string in typescript
I have this stylesheet:

```<code>const styles = StyleSheet.create({
  primary: {},
  secondary: {},
})
</code>```

And I would like to access the keys with dynamically composed strings.

```<code><View style={styles[props.type]}/>
</code>```

This is when TS complains (but the code runs just fine as one would expect):

```<code>Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ primary: { }; secondary: { }'.
  No index signature with a parameter of type 'string' was found on type '...'.ts(7053)
</code>```

How could I nudge TS in the right direction and make it happy?

答:
This is the minimal stripped-down working example:</p>

```<code>import { StyleSheet } from "react-native";

type Props = {
    type: 'primary' | 'secondary'
}

const styles = StyleSheet.create({
    primary: {},
    secondary: {}
});

const Component: React.FC<Props> = ({ type }) => {
  const style = styles[props.type];

  // ...
}
</code>```

Body:
I have this stylesheet:

const styles = StyleSheet.create({
  primary: {},
  secondary: {},
})

And I would like to access the keys with dynamically composed strings.

<View style={styles[props.type]}/>

This is when TS complains (but the code runs just fine as one would expect):

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ primary: { }; secondary: { }'.
  No index signature with a parameter of type 'string' was found on type '...'.ts(7053)

How could I nudge TS in the right direction and make it happy?

Body:
This is the minimal stripped-down working example:

import { StyleSheet } from "react-native";

type Props = {
    type: 'primary' | 'secondary'
}

const styles = StyleSheet.create({
    primary: {},
    secondary: {}
});

const Component: React.FC<Props> = ({ type }) => {
  const style = styles[props.type];

  // ...
}


问:
How to style an element created with JavaScript by using the HTML id attribute
I am trying to style an element created with JavaScript like this:

```<code>  const h1 = document.createElement("h1");
  h1.textContent = data.name;
  h1.setAttribute("id", "heading");
  window.data.appendChild(h1);
</code>```

This is my CSS code:

```<code>#heading{
  padding-right: 100px;
  colour: red;
}
</code>```

The element appears on the page since i have an async function which takes data from a JSON file, but i don't see a difference in the style of the element. I can't seem to find the issue in the code since I am new to JavaScript too.

答:
Probably something like this should work:

```<code>h1.style.color = "red";
h1.style.paddingRight = "100px";
</code>```

Check documentation for other specific cases
https://www.w3schools.com/jsref/dom_obj_style.asp

Also, a good practice in CSS is to avoid to target your element with id. Use HTML tag directly if possible or class

In your case, instead of

```<code>h1.setAttribute("id", "heading");
</code>```

you should

```<code>h1.classList.add("heading");
</code>```

Then in your CSS (If needed)

```<code>.heading{
  padding-right: 100px;
  colour: red;
}

</code>```

Body:
I am trying to style an element created with JavaScript like this:

  const h1 = document.createElement("h1");
  h1.textContent = data.name;
  h1.setAttribute("id", "heading");
  window.data.appendChild(h1);

This is my CSS code:

#heading{
  padding-right: 100px;
  colour: red;
}

The element appears on the page since i have an async function which takes data from a JSON file, but i don't see a difference in the style of the element. I can't seem to find the issue in the code since I am new to JavaScript too.

Body:
Probably something like this should work:

h1.style.color = "red";
h1.style.paddingRight = "100px";

Check documentation for other specific cases
https://www.w3schools.com/jsref/dom_obj_style.asp

Also, a good practice in CSS is to avoid to target your element with id. Use HTML tag directly if possible or class

In your case, instead of

h1.setAttribute("id", "heading");

you should

h1.classList.add("heading");

Then in your CSS (If needed)

.heading{
  padding-right: 100px;
  colour: red;
}


问:
How to git revert a commit using a SHA
How can I revert a commit with a GIVEN SHA? I just want to remove the changes with a given SHA? I want to keep all the commits made BEFORE & AFTER  the give SHA. I just want to remove changes of that specified SHA.

I have read Revert to a commit by a SHA hash in Git?, my understanding is that reset all the commits made AFTER the SHA i want to revert.
That is not way i want.

答:
One can use the

```<code>git revert <commit hash> --no-commit
</code>```

if they want to tweak the changes produced by commit revert, before they commit again. For more information have a look here

Title: How to git revert a commit using a SHA

Body:
One can use the

git revert <commit hash> --no-commit

if they want to tweak the changes produced by commit revert, before they commit again. For more information have a look here


问:
What is the "proper" tag prefix for the AjaxControlToolkit?
I've seen many examples where they just use the "asp" prefix.  Is this a good practice?

(The reason I'm asking is because the templates that create the default for a new website appear to be problematic.  There's an apparent naming collision on the BulletedList control.)

答:
I think there's no "best practice" for that. I usually use the company name for the control sets. For the MS Ajax and AjaxToolKit I use "ajax" as prefix, because it's short and different that "asp".

For the controls I develop where I work, I use "esi" because that is the abbreviation. That's the only one reason.

OwnerDisplayName: Larsenal

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Larsenal

OwnerDisplayName: diegojancic


问:
react-native init AwesomeProject gives an error EPERM: operation not permitted, chmod '/node_modules/@react-native-com...'
After installing brew, watchman and node. I tried to initiate my first react-native application from the terminal on a Mac machine.

When I run the command like it says on React Native Development site - React Native CLI Quickstart for macOS and iOS target.

```<code>npx react-native init AwesomeProject
</code>```

I get the following error

```<code>EPERM: operation not permitted, chmod '/usr/local/lib/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/server/external/xsel'
</code>```

I am logged in as an admin, so that is not an issue, and I have even tried "sudo", but with no success.

Has anybody faced a similar issue?

Thanks in advance.

答:
It seems that you are having a permission problem try to change the permissions to react-native's folder with your username.

```<code>sudo chown userName -R [PATH]
</code>```

to know your username run this command in the terminal

```<code>whoami
</code>```

or just do the following

close all VS Code instances.

clean cache with

```<code>npm cache clean --force
</code>```

install the latest version of npm globally as admin:

```<code>npm install -g npm@latest --force
</code>```

clean cache with

```<code>npm cache clean --force
</code>```

Try to install your component once again.

you may want temporarily disable your antivirus program and try again.

Body:
After installing brew, watchman and node. I tried to initiate my first react-native application from the terminal on a Mac machine.

When I run the command like it says on React Native Development site - React Native CLI Quickstart for macOS and iOS target.

npx react-native init AwesomeProject

I get the following error

EPERM: operation not permitted, chmod '/usr/local/lib/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/server/external/xsel'

I am logged in as an admin, so that is not an issue, and I have even tried "sudo", but with no success.

Has anybody faced a similar issue?

Thanks in advance.

Body:
It seems that you are having a permission problem try to change the permissions to react-native's folder with your username.

sudo chown userName -R [PATH]

to know your username run this command in the terminal

whoami

or just do the following

close all VS Code instances.

clean cache with

npm cache clean --force

install the latest version of npm globally as admin:

npm install -g npm@latest --force

clean cache with

npm cache clean --force

Try to install your component once again.

you may want temporarily disable your antivirus program and try again.


问:
Springboot standalone application deploy in production
I am trying to deploy my springboot standalone application in production in linux server.I am trying to use the out of the box tomcat server.

'java -jar jarname.jar'

This works fine , but if I close my putty session the application is unistalled.

Now I used

'nohup java -jar jarname.jar &'

this works good and my application is not shutdown even if my putty session is closed.But the logs will not roll correctly(I have configured log4j to create a new log file for each day) in this case. So was wondering if this is the right way to do this.

I have searched several documentation but was not able to find a correct solution for this problem.
Please help.

Thanks

答:
Well I think it's better to use Linux services for running application, you can read here for example

And if you want to collect logs - better write them to the file.
Spring provides build-in me mechanics to do that

logging:
    level:
        root: INFO
    file:
        clean-history-on-start: false
        max-history: 7
        max-size: 10MB
        name: some-name
        path: /path/log/dir
        total-size-cap: 0B

```


问:
Registering generic type with type constraint in .NET Core (MS.DI)
I have a generic interface IPipelineBehavior<TRequest, TResponse> (from MediatR). I'm trying to register a specific behavior for this interface as follows:

services.AddTransient(typeof(IPipelineBehavior<,>),
    typeof(ValidationMiddleware<,>));
```

<p><code>ValidationMiddleware</code> implements <code>IPipelineBehavior</code> like so:</p>

<pre class="lang-cs prettyprint-override"><code>public class ValidationMiddleware<TRequest, TResponse>
    : IPipelineBehavior<TRequest, Result<TResponse>>
</code>```

Result is a custom class I want all of my MediatR IRequestHandlers to return.

When the app runs, the service container gives me the following error:

System.ArgumentException: Implementation type 'StudentManagement.App.Middleware.ValidationMiddleware2[StudentManagement.App.Students.DisenrollStudentCommand,StudentManagement.App.Result1[System.Object]]' can't be converted to service type 'MediatR.IPipelineBehavior2[StudentManagement.App.Students.DisenrollStudentCommand,StudentManagement.App.Result1[System.Object]]'

I can't see why because they clearly both have the same type arguments at runtime. My guess is that the Result<TResponse> bit is causing the error for some reason, because other behaviors work fine when they just implement IPipelineBehavior<TRequest, TResponse>.

Does anyone understand why I'm getting this error, and what I need to do to solve it?

答:
As Steven suggested, it turns out the built-in .NET DI container is pretty limited when it comes to generics. I ended up switching to Autofac and everything worked fine. For anyone wondering, with Autofac the registration looks like this:

builder.RegisterGeneric(typeof(ValidationMiddleware<,>))
    .As(typeof(IPipelineBehavior<,>))
    .InstancePerDependency();
```

No further changes were required, except integrating Autofac with ASP.NET Core, of course.

Body:
I have a generic interface IPipelineBehavior<TRequest, TResponse> (from MediatR). I'm trying to register a specific behavior for this interface as follows:

services.AddTransient(typeof(IPipelineBehavior<,>),
    typeof(ValidationMiddleware<,>));

ValidationMiddleware implements IPipelineBehavior like so:

public class ValidationMiddleware<TRequest, TResponse>
    : IPipelineBehavior<TRequest, Result<TResponse>>

Result is a custom class I want all of my MediatR IRequestHandlers to return.

When the app runs, the service container gives me the following error:

System.ArgumentException: Implementation type 'StudentManagement.App.Middleware.ValidationMiddleware2[StudentManagement.App.Students.DisenrollStudentCommand,StudentManagement.App.Result1[System.Object]]' can't be converted to service type 'MediatR.IPipelineBehavior2[StudentManagement.App.Students.DisenrollStudentCommand,StudentManagement.App.Result1[System.Object]]'

I can't see why because they clearly both have the same type arguments at runtime. My guess is that the Result<TResponse> bit is causing the error for some reason, because other behaviors work fine when they just implement IPipelineBehavior<TRequest, TResponse>.

Does anyone understand why I'm getting this error, and what I need to do to solve it?

Body:
As Steven suggested, it turns out the built-in .NET DI container is pretty limited when it comes to generics. I ended up switching to Autofac and everything worked fine. For anyone wondering, with Autofac the registration looks like this:

builder.RegisterGeneric(typeof(ValidationMiddleware<,>))
    .As(typeof(IPipelineBehavior<,>))
    .InstancePerDependency();

No further changes were required, except integrating Autofac with ASP.NET Core, of course.


问:
Why does iterating through the loop is not working
I have a question, I am trying to complete an exercise where I enter 1,2,3 and the output would say: One, Two Three. The following code is not working.  My logic is to enter the numbers, 1,2,3 and then run a for loop through the input.  Thank you so much!

```<code>phone = input("Phone")
digitmap = {
    1: "One",
    2: "Two",
    3: "Three",
    4: "Four"
}
for i in phone:
  output = digitmap[i]
  print(output)
</code>```

答:
First, you need to ensure that your input is a list of int to look up in your dictionary. So we first declare phone as a list, and then fill it using the method below:

[int(x) for x in input("Phone\n").split(',')]

Then, might end up with a dictionary that is out of order. Perhaps your digitmap looks like:

```<code>digitmap = {
    3: "Three",
    4: "Four",
    1: "One",
    2: "Two"
}
</code>```

At that point, your index based reference would fail. Instead, we should use the dict.get() method which returns the value for the key in the hashmap

```<code>phone = []
# https://www.geeksforgeeks.org/python-program-to-input-a-comma-separated-string/
phone = [int(x) for x in input("Phone\n").split(',')]
digitmap = {
    1: "One",
    2: "Two",
    3: "Three",
    4: "Four"
}
for i in phone:
  output = digitmap.get(i)
  print(output)
</code>```

Looks like:

```<code>C:\Users\wundermahn\Desktop>python stack_example.py
Phone
1,2,3
One
Two
Three
</code>```

Body:
I have a question, I am trying to complete an exercise where I enter 1,2,3 and the output would say: One, Two Three. The following code is not working.  My logic is to enter the numbers, 1,2,3 and then run a for loop through the input.  Thank you so much!

phone = input("Phone")
digitmap = {
    1: "One",
    2: "Two",
    3: "Three",
    4: "Four"
}
for i in phone:
  output = digitmap[i]
  print(output)

Body:
First, you need to ensure that your input is a list of int to look up in your dictionary. So we first declare phone as a list, and then fill it using the method below:

[int(x) for x in input("Phone\n").split(',')]

Then, might end up with a dictionary that is out of order. Perhaps your digitmap looks like:

digitmap = {
    3: "Three",
    4: "Four",
    1: "One",
    2: "Two"
}

At that point, your index based reference would fail. Instead, we should use the dict.get() method which returns the value for the key in the hashmap

phone = []
# https://www.geeksforgeeks.org/python-program-to-input-a-comma-separated-string/
phone = [int(x) for x in input("Phone\n").split(',')]
digitmap = {
    1: "One",
    2: "Two",
    3: "Three",
    4: "Four"
}
for i in phone:
  output = digitmap.get(i)
  print(output)

Looks like:

C:\Users\wundermahn\Desktop>python stack_example.py
Phone
1,2,3
One
Two
Three


问:
Templated struct inside function
I want to define a helper templated struct inside a function. (Has to be inside the current function due to our own convention)

Why doesn't the following work? How do I fix it?

```<code>void foo() {
  template<typename T>
  struct MyHelper {
     // ....
     void func(int x, int y, ...) {
        some_other<T>(...);
     }
  };

  // Use MyHelper with different types.
  if (some_logic) {
      MyHelper<TypeA> helper;
      helper.func(x, y, z);
  } else if (some_other) {
     MyHelper<TypeB> helper;
     // ....
  }
  // ... more
  // TypeA, TypeB, TypeC, ... don't share common parents.
}
</code>```

答:
If the convention is not applicable then screw the convention. Seriously, conventions are not to be followed blindly. In this case the best the convention can do for you is to remind you that you are doing something which is uncommon in your work environment and that you should add a comment explaining why you decided to not follow the convention. Declare the helper outside of the function if you think this is the right thing to do.

However, as foo is not templated, I do assume that the types the Helper has to handle is from a limited set of types and that overloads would do as well:

```<code>void foo() {
  struct MyHelper {
     void func(TypeA, int x, int y) {
        some_other<TypeA>(...);
     }
     void func(TypeB, int x, int y) {}
     void func(TypeC, int x, int y) {}
  };

  MyHelper helper;
  if (some_logic) {
      helper.func(TypeA{},x, y);
  } else if (some_other) {
      helper.func(TypeB{},x, y);
 // ....
}
</code>```

If TypeA is nothing you want to create instances of on the fly, you could use tags instead to pick the right overload. However, from your usage it looks like you neither need templates nor overloads, but simple named functions would be fine:

```<code>void foo() {
  struct MyHelper {
     void funcA(int x, int y) {
        some_other<TypeA>(...);
     }
     void funcB(int x, int y) {
        some_other<TypeB>(...);
     }
     void funcC(int x, int y) {}
  };

  MyHelper helper;
  if (some_logic) {
      helper.funcA(x, y);
  } else if (some_other) {
      helper.funcB(x, y);
 // ....
}
</code>```

Templates and overloads enable great flexibility, but sometimes you just don't need that flexibility and simply using differently named functions is the much simpler alternative.

Title: Templated struct inside function

Body:
I want to define a helper templated struct inside a function. (Has to be inside the current function due to our own convention)

Why doesn't the following work? How do I fix it?

void foo() {
  template<typename T>
  struct MyHelper {
     // ....
     void func(int x, int y, ...) {
        some_other<T>(...);
     }
  };

  // Use MyHelper with different types.
  if (some_logic) {
      MyHelper<TypeA> helper;
      helper.func(x, y, z);
  } else if (some_other) {
     MyHelper<TypeB> helper;
     // ....
  }
  // ... more
  // TypeA, TypeB, TypeC, ... don't share common parents.
}

Body:
If the convention is not applicable then screw the convention. Seriously, conventions are not to be followed blindly. In this case the best the convention can do for you is to remind you that you are doing something which is uncommon in your work environment and that you should add a comment explaining why you decided to not follow the convention. Declare the helper outside of the function if you think this is the right thing to do.

However, as foo is not templated, I do assume that the types the Helper has to handle is from a limited set of types and that overloads would do as well:

void foo() {
  struct MyHelper {
     void func(TypeA, int x, int y) {
        some_other<TypeA>(...);
     }
     void func(TypeB, int x, int y) {}
     void func(TypeC, int x, int y) {}
  };

  MyHelper helper;
  if (some_logic) {
      helper.func(TypeA{},x, y);
  } else if (some_other) {
      helper.func(TypeB{},x, y);
 // ....
}

If TypeA is nothing you want to create instances of on the fly, you could use tags instead to pick the right overload. However, from your usage it looks like you neither need templates nor overloads, but simple named functions would be fine:

void foo() {
  struct MyHelper {
     void funcA(int x, int y) {
        some_other<TypeA>(...);
     }
     void funcB(int x, int y) {
        some_other<TypeB>(...);
     }
     void funcC(int x, int y) {}
  };

  MyHelper helper;
  if (some_logic) {
      helper.funcA(x, y);
  } else if (some_other) {
      helper.funcB(x, y);
 // ....
}

Templates and overloads enable great flexibility, but sometimes you just don't need that flexibility and simply using differently named functions is the much simpler alternative.


问:
Updating UI when working with OperationQueue
I have an operation queue setup as follows:

```<code>let queue = OperationQueue()
queue.name = "com.company.myQueue"
queue.qualityOfService = .userInitiated
queue.maxConcurrentOperationCount = 64
...
var current = 0
var totalCount = someArray.count
for i in someArray {
...
   let op = BlockOperation {
   ... // do some database queries
   current += 1
   }

   op.completionBlock = {
     DispatchQueue.main.async {
     let nData: [String: CGFloat] = ["value": CGFloat(current/totalCount)]
     NotificationCenter.default.post(name:Notification.Name(rawValue: "update"), object: nil, userInfo: nData)
   }

   queue.addOperation(op)
}
</code>```

In my ViewController I listen for the notification and update a UILabel with the percentage. Problem is though I don't get any intermediate values... it jumps from being 0 directly to 100 once all the operations are done.

What am I doing wrong?

Thanks

答:
You can move your notification send function directly in op.completionBlock (without dispatching it in main thread).

Edit (comments) :

let queue = OperationQueue()
    queue.name = "com.company.myQueue"
    queue.qualityOfService = .userInitiated
    queue.maxConcurrentOperationCount = 64

let array = ["", "", "", "", "", ]

var current = 0
var totalCount = array.count

for _ in array {
    let op = BlockOperation { current += 1 ; print(current) }
        op.completionBlock = {
            DispatchQueue.main.async {
                NotificationCenter.default.post(name: Notification.Name(rawValue: "update"), object: nil, userInfo: ["value": CGFloat(current / totalCount)])
            }
        }

   queue.addOperation(op)
}

NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: "update"), object: nil, queue: nil) { (notification) in
    print(notification.userInfo)
}
```

<p>Edit 2 (comments) :
You should make your percentage by float casting current and totalCount before dividing them.</p>

<pre class="lang-swift prettyprint-override"><code>CGFloat(current) / CGFloat(totalCount)
'''
</code>```

Body:
I have an operation queue setup as follows:

let queue = OperationQueue()
queue.name = "com.company.myQueue"
queue.qualityOfService = .userInitiated
queue.maxConcurrentOperationCount = 64
...
var current = 0
var totalCount = someArray.count
for i in someArray {
...
   let op = BlockOperation {
   ... // do some database queries
   current += 1
   }

   op.completionBlock = {
     DispatchQueue.main.async {
     let nData: [String: CGFloat] = ["value": CGFloat(current/totalCount)]
     NotificationCenter.default.post(name:Notification.Name(rawValue: "update"), object: nil, userInfo: nData)
   }

   queue.addOperation(op)
}

In my ViewController I listen for the notification and update a UILabel with the percentage. Problem is though I don't get any intermediate values... it jumps from being 0 directly to 100 once all the operations are done.

What am I doing wrong?

Thanks

Body:
You can move your notification send function directly in op.completionBlock (without dispatching it in main thread).

Edit (comments) :

let queue = OperationQueue()
    queue.name = "com.company.myQueue"
    queue.qualityOfService = .userInitiated
    queue.maxConcurrentOperationCount = 64

let array = ["", "", "", "", "", ]

var current = 0
var totalCount = array.count

for _ in array {
    let op = BlockOperation { current += 1 ; print(current) }
        op.completionBlock = {
            DispatchQueue.main.async {
                NotificationCenter.default.post(name: Notification.Name(rawValue: "update"), object: nil, userInfo: ["value": CGFloat(current / totalCount)])
            }
        }

   queue.addOperation(op)
}

NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: "update"), object: nil, queue: nil) { (notification) in
    print(notification.userInfo)
}

Edit 2 (comments) :
You should make your percentage by float casting current and totalCount before dividing them.

CGFloat(current) / CGFloat(totalCount)
'''


问:
Moving dataframes between notebooks
I'm trying to move two dataframes from notebook1 to notebook2

I've tried using nbimporter:

```<code>import nbimporter
import notebook1 as nb1
nb1.df()
</code>```

Which returns:

AttributeError: module 'notebook1' has no attribute 'df' (it does)

I also tried using ipynb but that didn't work either

I would just write it to a excel file and read it but the index gets messed up when reading it in the other notebook.

答:
I propose to use pickle to save then load your dataframe

From the first notebook

```<code>df.to_pickle("./df.pkl")
</code>```

then from the second notebook

```<code>df = pd.read_pickle("./df.pkl")
</code>```

Title: Moving dataframes between notebooks

Body:
I'm trying to move two dataframes from notebook1 to notebook2

I've tried using nbimporter:

import nbimporter
import notebook1 as nb1
nb1.df()

Which returns:

AttributeError: module 'notebook1' has no attribute 'df' (it does)

I also tried using ipynb but that didn't work either

I would just write it to a excel file and read it but the index gets messed up when reading it in the other notebook.

Body:
I propose to use pickle to save then load your dataframe

From the first notebook

df.to_pickle("./df.pkl")

then from the second notebook

df = pd.read_pickle("./df.pkl")


问:
How do I calculate the rest/modulo of two numbers without the "%" operator?
For example with the following input:

```<code>int num = -100
int divisor = 10
=>  -100 mod 10 = 0   (Edge-case: negative numbers as input)
</code>```

```<code>int num = 300
int divisor = -7
=>300 mod 7 = 6
</code>```

I used this method before but with negative numbers, it´s not working:

```<code>int method(int i, int div){
    return (num - divisor * (num / divisor));
}
</code>```

Expected result :

```<code>-1234, 512 ==> <302>
</code>```

Actual result :

```<code>-1234, 512 ==> <210>
</code>```

答:
Your code runs fine with modulo and without module.

They both give same results for negative and positive numbers as well.

```<code>import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("Enter the Dividend : ");
        int i = scan.nextInt();
        System.out.println("\nEnter the Divisor : ");
        int div = scan.nextInt();

        System.out.println("Without modulo :Dividend: " + i + " , Divisor: " + div + ", Remainder: "  +(i - div * (i / div)));
        System.out.println("With modulo    :Dividend: " + i + " , Divisor: " + div + ", Remainder: "  +(i % div));
        System.out.println("Using abstract :Dividend: " + i + " , Divisor: " + div + ", Remainder: "  +Math.abs(i - div * (i / div)));

    }
}
</code>```

Output :

```<code>Enter the Dividend :
300
Enter the Divisor :
-7
Without modulo :Dividend: 300 , Divisor: -7, Remainder: 6
With module    :Dividend: 300 , Divisor: -7, Remainder: 6
Using abstract :Dividend: 300,  Divisor: -7, Remainder: 6

Enter the Dividend :
-1234

Enter the Divisor :
512
Without modulo :Dividend: -1234 , Divisor: 512, Remainder: -210
With module    :Dividend: -1234 , Divisor: 512, Remainder: -210
Using abstract :Dividend: -1234 , Divisor: 512, Remainder: 210
</code>```

Body:
For example with the following input:

int num = -100
int divisor = 10
=>  -100 mod 10 = 0   (Edge-case: negative numbers as input)

int num = 300
int divisor = -7
=>300 mod 7 = 6

I used this method before but with negative numbers, it´s not working:

int method(int i, int div){
    return (num - divisor * (num / divisor));
}

Expected result :

-1234, 512 ==> <302>

Actual result :

-1234, 512 ==> <210>

Body:
Your code runs fine with modulo and without module.

They both give same results for negative and positive numbers as well.

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("Enter the Dividend : ");
        int i = scan.nextInt();
        System.out.println("\nEnter the Divisor : ");
        int div = scan.nextInt();

        System.out.println("Without modulo :Dividend: " + i + " , Divisor: " + div + ", Remainder: "  +(i - div * (i / div)));
        System.out.println("With modulo    :Dividend: " + i + " , Divisor: " + div + ", Remainder: "  +(i % div));
        System.out.println("Using abstract :Dividend: " + i + " , Divisor: " + div + ", Remainder: "  +Math.abs(i - div * (i / div)));

    }
}

Output :

Enter the Dividend :
300
Enter the Divisor :
-7
Without modulo :Dividend: 300 , Divisor: -7, Remainder: 6
With module    :Dividend: 300 , Divisor: -7, Remainder: 6
Using abstract :Dividend: 300,  Divisor: -7, Remainder: 6

Enter the Dividend :
-1234

Enter the Divisor :
512
Without modulo :Dividend: -1234 , Divisor: 512, Remainder: -210
With module    :Dividend: -1234 , Divisor: 512, Remainder: -210
Using abstract :Dividend: -1234 , Divisor: 512, Remainder: 210


问:
How to I get rid of extra / in http://localhost:8080/test/ in Jetty?
I want any user trying to access http://localhost:8080/test/ to be redirected to http://localhost:8080/test. I want to remove the extra '/' after test.

I tried writing this in rewrite rules but it doesn't work for me.

答:
If your contextPath is /test then the extra slash is required to satisfy the context path rules of both the servlet spec and the URI / http resource declarations of the various RFCs.

If you set your web application, handler, context, etc with the "context path" of /test then you'll want to switch to using / (the root context) and having a servlet url-pattern of /test (exactly named /test).


问:
Angular 4 convert json to xml
I have a need to convert json to xml in angular 4. the client has written has written a WCF that will accept an xml parameter to the method.
We, in angular, rather use json for obvious reasons.

We decided to write a json object and convert it to xml.
I already know how to do to opposite way, xml to json:

```<code> xml2json(xml, tab) {
    var X = {
      toObj: function (xml) {
        var o = {};
        if (xml.nodeType == 1) {   // element node ..
          if (xml.attributes.length)   // element with attributes  ..
            for (var i = 0; i < xml.attributes.length; i++)
              o["@" + xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue || "").toString();
          if (xml.firstChild) { // element has child nodes ..
            var textChild = 0, cdataChild = 0, hasElementChild = false;
            for (var n = xml.firstChild; n; n = n.nextSibling) {
              if (n.nodeType == 1) hasElementChild = true;
              else if (n.nodeType == 3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) textChild++; // non-whitespace text
              else if (n.nodeType == 4) cdataChild++; // cdata section node
            }
            if (hasElementChild) {
              if (textChild < 2 && cdataChild < 2) { // structured element with evtl. a single text or/and cdata node ..
                X.removeWhite(xml);
                for (var n = xml.firstChild; n; n = n.nextSibling) {
                  if (n.nodeType == 3)  // text node
                    o["#text"] = X.escape(n.nodeValue);
                  else if (n.nodeType == 4)  // cdata node
                    o["#cdata"] = X.escape(n.nodeValue);
                  else if (o[n.nodeName]) {  // multiple occurence of element ..
                    if (o[n.nodeName] instanceof Array)
                      o[n.nodeName][o[n.nodeName].length] = X.toObj(n);
                    else
                      o[n.nodeName] = [o[n.nodeName], X.toObj(n)];
                  }
                  else  // first occurence of element..
                    o[n.nodeName] = X.toObj(n);
                }
              }
              else { // mixed content
                if (!xml.attributes.length)
                  o = X.escape(X.innerXml(xml));
                else
                  o["#text"] = X.escape(X.innerXml(xml));
              }
            }
            else if (textChild) { // pure text
              if (!xml.attributes.length)
                o = X.escape(X.innerXml(xml));
              else
                o["#text"] = X.escape(X.innerXml(xml));
            }
            else if (cdataChild) { // cdata
              if (cdataChild > 1)
                o = X.escape(X.innerXml(xml));
              else
                for (var n = xml.firstChild; n; n = n.nextSibling)
                  o["#cdata"] = X.escape(n.nodeValue);
            }
          }
          if (!xml.attributes.length && !xml.firstChild) o = null;
        }
        else if (xml.nodeType == 9) { // document.node
          o = X.toObj(xml.documentElement);
        }
        else
          alert("unhandled node type: " + xml.nodeType);
        return o;
      },
      toJson: function (o, name, ind) {
        var json = name ? ("\"" + name + "\"") : "";
        if (o instanceof Array) {
          for (var i = 0, n = o.length; i < n; i++)
            o[i] = X.toJson(o[i], "", ind + "\t");
          json += (name ? ":[" : "[") + (o.length > 1 ? ("\n" + ind + "\t" + o.join(",\n" + ind + "\t") + "\n" + ind) : o.join("")) + "]";
        }
        else if (o == null)
          json += (name && ":") + "null";
        else if (typeof (o) == "object") {
          var arr = [];
          for (var m in o)
            arr[arr.length] = X.toJson(o[m], m, ind + "\t");
          json += (name ? ":{" : "{") + (arr.length > 1 ? ("\n" + ind + "\t" + arr.join(",\n" + ind + "\t") + "\n" + ind) : arr.join("")) + "}";
        }
        else if (typeof (o) == "string")
          json += (name && ":") + "\"" + o.toString() + "\"";
        else
          json += (name && ":") + o.toString();
        return json;
      },
      innerXml: function (node) {
        var s = ""
        if ("innerHTML" in node)
          s = node.innerHTML;
        else {
          var asXml = function (n) {
            var s = "";
            if (n.nodeType == 1) {
              s += "<" + n.nodeName;
              for (var i = 0; i < n.attributes.length; i++)
                s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue || "").toString() + "\"";
              if (n.firstChild) {
                s += ">";
                for (var c = n.firstChild; c; c = c.nextSibling)
                  s += asXml(c);
                s += "</" + n.nodeName + ">";
              }
              else
                s += "/>";
            }
            else if (n.nodeType == 3)
              s += n.nodeValue;
            else if (n.nodeType == 4)
              s += "<![CDATA[" + n.nodeValue + "]]>";
            return s;
          };
          for (var c = node.firstChild; c; c = c.nextSibling)
            s += asXml(c);
        }
        return s;
      },
      escape: function (txt) {
        return txt.replace(/[\\]/g, "\\\\")
          .replace(/[\"]/g, '\\"')
          .replace(/[\n]/g, '\\n')
          .replace(/[\r]/g, '\\r');
      },
      removeWhite: function (e) {
        e.normalize();
        for (var n = e.firstChild; n;) {
          if (n.nodeType == 3) {  // text node
            if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) { // pure whitespace text node
              var nxt = n.nextSibling;
              e.removeChild(n);
              n = nxt;
            }
            else
              n = n.nextSibling;
          }
          else if (n.nodeType == 1) {  // element node
            X.removeWhite(n);
            n = n.nextSibling;
          }
          else                      // any other node
            n = n.nextSibling;
        }
        return e;
      }
    };
    if (xml.nodeType == 9) // document node
      xml = xml.documentElement;
    var json = X.toJson(X.toObj(X.removeWhite(xml)), xml.nodeName, "\t");
    return "{\n" + tab + (tab ? json.replace(/\t/g, tab) : json.replace(/\t|\n/g, "")) + "\n}";
  }
</code>```

Now I need to know, how to convert the json object to xml string or object.

thanks in advance!

答:
```<code>jsonToXML(json) {
    let xml = '';
    // tslint:disable: forin
    for (const prop in json) {
      xml += json[prop] instanceof Array ? '' : '<' + prop + '>';
      if (json[prop] instanceof Array) {
        for (const array in json[prop]) {
          xml += '<' + prop + '>';
          xml += this.jsonToXML(new Object(json[prop][array]));
          xml += '</' + prop + '>';
        }
      } else if (typeof json[prop] === 'object') {
        xml += this.jsonToXML(new Object(json[prop]));
      } else {
        xml += json[prop];
      }
      xml += json[prop] instanceof Array ? '' : '</' + prop + '>';
    }
    xml = xml.replace(/<\/?[0-9]{1,}>/g, '');
    return xml;
  }
</code>```

Title: Angular 4 convert json to xml

Body:
I have a need to convert json to xml in angular 4. the client has written has written a WCF that will accept an xml parameter to the method.
We, in angular, rather use json for obvious reasons.

We decided to write a json object and convert it to xml.
I already know how to do to opposite way, xml to json:

 xml2json(xml, tab) {
    var X = {
      toObj: function (xml) {
        var o = {};
        if (xml.nodeType == 1) {   // element node ..
          if (xml.attributes.length)   // element with attributes  ..
            for (var i = 0; i < xml.attributes.length; i++)
              o["@" + xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue || "").toString();
          if (xml.firstChild) { // element has child nodes ..
            var textChild = 0, cdataChild = 0, hasElementChild = false;
            for (var n = xml.firstChild; n; n = n.nextSibling) {
              if (n.nodeType == 1) hasElementChild = true;
              else if (n.nodeType == 3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) textChild++; // non-whitespace text
              else if (n.nodeType == 4) cdataChild++; // cdata section node
            }
            if (hasElementChild) {
              if (textChild < 2 && cdataChild < 2) { // structured element with evtl. a single text or/and cdata node ..
                X.removeWhite(xml);
                for (var n = xml.firstChild; n; n = n.nextSibling) {
                  if (n.nodeType == 3)  // text node
                    o["#text"] = X.escape(n.nodeValue);
                  else if (n.nodeType == 4)  // cdata node
                    o["#cdata"] = X.escape(n.nodeValue);
                  else if (o[n.nodeName]) {  // multiple occurence of element ..
                    if (o[n.nodeName] instanceof Array)
                      o[n.nodeName][o[n.nodeName].length] = X.toObj(n);
                    else
                      o[n.nodeName] = [o[n.nodeName], X.toObj(n)];
                  }
                  else  // first occurence of element..
                    o[n.nodeName] = X.toObj(n);
                }
              }
              else { // mixed content
                if (!xml.attributes.length)
                  o = X.escape(X.innerXml(xml));
                else
                  o["#text"] = X.escape(X.innerXml(xml));
              }
            }
            else if (textChild) { // pure text
              if (!xml.attributes.length)
                o = X.escape(X.innerXml(xml));
              else
                o["#text"] = X.escape(X.innerXml(xml));
            }
            else if (cdataChild) { // cdata
              if (cdataChild > 1)
                o = X.escape(X.innerXml(xml));
              else
                for (var n = xml.firstChild; n; n = n.nextSibling)
                  o["#cdata"] = X.escape(n.nodeValue);
            }
          }
          if (!xml.attributes.length && !xml.firstChild) o = null;
        }
        else if (xml.nodeType == 9) { // document.node
          o = X.toObj(xml.documentElement);
        }
        else
          alert("unhandled node type: " + xml.nodeType);
        return o;
      },
      toJson: function (o, name, ind) {
        var json = name ? ("\"" + name + "\"") : "";
        if (o instanceof Array) {
          for (var i = 0, n = o.length; i < n; i++)
            o[i] = X.toJson(o[i], "", ind + "\t");
          json += (name ? ":[" : "[") + (o.length > 1 ? ("\n" + ind + "\t" + o.join(",\n" + ind + "\t") + "\n" + ind) : o.join("")) + "]";
        }
        else if (o == null)
          json += (name && ":") + "null";
        else if (typeof (o) == "object") {
          var arr = [];
          for (var m in o)
            arr[arr.length] = X.toJson(o[m], m, ind + "\t");
          json += (name ? ":{" : "{") + (arr.length > 1 ? ("\n" + ind + "\t" + arr.join(",\n" + ind + "\t") + "\n" + ind) : arr.join("")) + "}";
        }
        else if (typeof (o) == "string")
          json += (name && ":") + "\"" + o.toString() + "\"";
        else
          json += (name && ":") + o.toString();
        return json;
      },
      innerXml: function (node) {
        var s = ""
        if ("innerHTML" in node)
          s = node.innerHTML;
        else {
          var asXml = function (n) {
            var s = "";
            if (n.nodeType == 1) {
              s += "<" + n.nodeName;
              for (var i = 0; i < n.attributes.length; i++)
                s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue || "").toString() + "\"";
              if (n.firstChild) {
                s += ">";
                for (var c = n.firstChild; c; c = c.nextSibling)
                  s += asXml(c);
                s += "</" + n.nodeName + ">";
              }
              else
                s += "/>";
            }
            else if (n.nodeType == 3)
              s += n.nodeValue;
            else if (n.nodeType == 4)
              s += "<![CDATA[" + n.nodeValue + "]]>";
            return s;
          };
          for (var c = node.firstChild; c; c = c.nextSibling)
            s += asXml(c);
        }
        return s;
      },
      escape: function (txt) {
        return txt.replace(/[\\]/g, "\\\\")
          .replace(/[\"]/g, '\\"')
          .replace(/[\n]/g, '\\n')
          .replace(/[\r]/g, '\\r');
      },
      removeWhite: function (e) {
        e.normalize();
        for (var n = e.firstChild; n;) {
          if (n.nodeType == 3) {  // text node
            if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) { // pure whitespace text node
              var nxt = n.nextSibling;
              e.removeChild(n);
              n = nxt;
            }
            else
              n = n.nextSibling;
          }
          else if (n.nodeType == 1) {  // element node
            X.removeWhite(n);
            n = n.nextSibling;
          }
          else                      // any other node
            n = n.nextSibling;
        }
        return e;
      }
    };
    if (xml.nodeType == 9) // document node
      xml = xml.documentElement;
    var json = X.toJson(X.toObj(X.removeWhite(xml)), xml.nodeName, "\t");
    return "{\n" + tab + (tab ? json.replace(/\t/g, tab) : json.replace(/\t|\n/g, "")) + "\n}";
  }

Now I need to know, how to convert the json object to xml string or object.

thanks in advance!


问:
How to retrieve added doc data in Firestore?
I have such code where I can get new inserted doc id:

```<code>db.collection("cities").add({
   name: "Tokyo",
   country: "Japan"
})
.then(function(docRef) {
   console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
   console.error("Error adding document: ", error);
});
</code>```

Is it possible to get data from ref?

答:
Yes you can do it like this:

```<code>.then(function(docRef) {
   db.collection("cities").doc(docRef.id).get()
     .then(snap => {
        console.log('Here is the document you wrote to', snap.data()
      })
})
</code>```

Granted it requires another read which you probably didn't want

Body:
I have such code where I can get new inserted doc id:

db.collection("cities").add({
   name: "Tokyo",
   country: "Japan"
})
.then(function(docRef) {
   console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
   console.error("Error adding document: ", error);
});

Is it possible to get data from ref?

Body:
Yes you can do it like this:

.then(function(docRef) {
   db.collection("cities").doc(docRef.id).get()
     .then(snap => {
        console.log('Here is the document you wrote to', snap.data()
      })
})

Granted it requires another read which you probably didn't want


问:
Can someone explain this regular expression?
```<code>(.*)([0-9]{6})|(.*)([0-9]{4})
</code>```

<p>Does it mean pick up a number that is either 6 digits or 4 digits ? Is there a concise way to write it ? </p>

答:
I believe this means match either

an arbitrary number of any characters (.*) followed by a 6-digit number ([0-9]{6})

or (|)

an arbitrary number of any characters (.*) followed by a 4-digit number ([0-9]{4})

. = any character

* means 0, 1 or many - in this case...lookup "kleene closure"

[0-9] indicates a digit 0-9

{6} means the last pattern is repeated 6 times

now...

Wouldn't a string followed by a 6 digit number also match the pattern of a string followed by a 4 digit number?  You could add a whitespace character or end of line to the end of each pattern if this causes problems.

I may have made the assumption that what you wrote is equal to

```<code>((.*)([0-9]{6}))|((.*)([0-9]{4}))
</code>```

Body:
(.*)([0-9]{6})|(.*)([0-9]{4})

Does it mean pick up a number that is either 6 digits or 4 digits ? Is there a concise way to write it ?

Body:
I believe this means match either

an arbitrary number of any characters (.*) followed by a 6-digit number ([0-9]{6})

or (|)

an arbitrary number of any characters (.*) followed by a 4-digit number ([0-9]{4})

. = any character

* means 0, 1 or many - in this case...lookup "kleene closure"

[0-9] indicates a digit 0-9

{6} means the last pattern is repeated 6 times

now...

Wouldn't a string followed by a 6 digit number also match the pattern of a string followed by a 4 digit number?  You could add a whitespace character or end of line to the end of each pattern if this causes problems.

I may have made the assumption that what you wrote is equal to

((.*)([0-9]{6}))|((.*)([0-9]{4}))


问:
Why mongodb arbiter needs dbpath?
An mongodb arbiter roles are as follows:

An arbiter does not have a copy of data set and cannot become a primary. However, an arbiter participates in elections for primary. An arbiter has exactly 1 election vote.

Arbiters are mongod instances that are part of a replica set but do not hold data. Then, why arbiter needs dbpath?

答:
The arbiter stores various housekeeping data, which you can inspect by looking at the local database:

```<code>MongoDB Enterprise ruby-driver-rs:ARBITER> db.getMongo().setSlaveOk()
MongoDB Enterprise ruby-driver-rs:ARBITER> use local
switched to db local
MongoDB Enterprise ruby-driver-rs:ARBITER> db.runCommand({listCollections:1})
{
        "cursor" : {
                "id" : NumberLong(0),
                "ns" : "local.$cmd.listCollections",
                "firstBatch" : [
                        {
                                "name" : "system.replset",
                                "type" : "collection",
                                "options" : {

                                },
                                "info" : {
                                        "readOnly" : false,
                                        "uuid" : UUID("108fbabe-4139-4d3d-8326-fc8e169b811d")
                                },
                                "idIndex" : {
                                        "v" : 2,
                                        "key" : {
                                                "_id" : 1
                                        },
                                        "name" : "_id_"
                                }
                        },
                        {
                                "name" : "startup_log",
                                "type" : "collection",
                                "options" : {
                                        "capped" : true,
                                        "size" : 10485760
                                },
                                "info" : {
                                        "readOnly" : false,
                                        "uuid" : UUID("1c3ed741-a7f8-4fad-89f9-36f979cbfa22")
                                },
                                "idIndex" : {
                                        "v" : 2,
                                        "key" : {
                                                "_id" : 1
                                        },
                                        "name" : "_id_"
                                }
                        },
                        {
                                "name" : "replset.oplogTruncateAfterPoint",
                                "type" : "collection",
                                "options" : {

                                },
                                "info" : {
                                        "readOnly" : false,
                                        "uuid" : UUID("37c4d64b-8fcc-4aa5-b1e0-2ac6b71e893a")
                                },
                                "idIndex" : {
                                        "v" : 2,
                                        "key" : {
                                                "_id" : 1
                                        },
                                        "name" : "_id_"
                                }
                        },
                        {
                                "name" : "replset.election",
                                "type" : "collection",
                                "options" : {

                                },
                                "info" : {
                                        "readOnly" : false,
                                        "uuid" : UUID("53fc68a9-19c9-4262-b152-fafa99ea55f5")
                                },
                                "idIndex" : {
                                        "v" : 2,
                                        "key" : {
                                                "_id" : 1
                                        },
                                        "name" : "_id_"
                                }
                        },
                        {
                                "name" : "replset.minvalid",
                                "type" : "collection",
                                "options" : {

                                },
                                "info" : {
                                        "readOnly" : false,
                                        "uuid" : UUID("5564332b-3c3f-4103-acbd-c53c7a71581c")
                                },
                                "idIndex" : {
                                        "v" : 2,
                                        "key" : {
                                                "_id" : 1
                                        },
                                        "name" : "_id_"
                                }
                        },
                        {
                                "name" : "system.rollback.id",
                                "type" : "collection",
                                "options" : {

                                },
                                "info" : {
                                        "readOnly" : false,
                                        "uuid" : UUID("fa26f83a-8843-4b6d-8d4d-4cde192976bd")
                                },
                                "idIndex" : {
                                        "v" : 2,
                                        "key" : {
                                                "_id" : 1
                                        },
                                        "name" : "_id_"
                                }
                        }
                ]
        },
        "ok" : 1
}
</code>```

Title: Why mongodb arbiter needs dbpath?

Body:
The arbiter stores various housekeeping data, which you can inspect by looking at the local database:

MongoDB Enterprise ruby-driver-rs:ARBITER> db.getMongo().setSlaveOk()
MongoDB Enterprise ruby-driver-rs:ARBITER> use local
switched to db local
MongoDB Enterprise ruby-driver-rs:ARBITER> db.runCommand({listCollections:1})
{
        "cursor" : {
                "id" : NumberLong(0),
                "ns" : "local.$cmd.listCollections",
                "firstBatch" : [
                        {
                                "name" : "system.replset",
                                "type" : "collection",
                                "options" : {

                                },
                                "info" : {
                                        "readOnly" : false,
                                        "uuid" : UUID("108fbabe-4139-4d3d-8326-fc8e169b811d")
                                },
                                "idIndex" : {
                                        "v" : 2,
                                        "key" : {
                                                "_id" : 1
                                        },
                                        "name" : "_id_"
                                }
                        },
                        {
                                "name" : "startup_log",
                                "type" : "collection",
                                "options" : {
                                        "capped" : true,
                                        "size" : 10485760
                                },
                                "info" : {
                                        "readOnly" : false,
                                        "uuid" : UUID("1c3ed741-a7f8-4fad-89f9-36f979cbfa22")
                                },
                                "idIndex" : {
                                        "v" : 2,
                                        "key" : {
                                                "_id" : 1
                                        },
                                        "name" : "_id_"
                                }
                        },
                        {
                                "name" : "replset.oplogTruncateAfterPoint",
                                "type" : "collection",
                                "options" : {

                                },
                                "info" : {
                                        "readOnly" : false,
                                        "uuid" : UUID("37c4d64b-8fcc-4aa5-b1e0-2ac6b71e893a")
                                },
                                "idIndex" : {
                                        "v" : 2,
                                        "key" : {
                                                "_id" : 1
                                        },
                                        "name" : "_id_"
                                }
                        },
                        {
                                "name" : "replset.election",
                                "type" : "collection",
                                "options" : {

                                },
                                "info" : {
                                        "readOnly" : false,
                                        "uuid" : UUID("53fc68a9-19c9-4262-b152-fafa99ea55f5")
                                },
                                "idIndex" : {
                                        "v" : 2,
                                        "key" : {
                                                "_id" : 1
                                        },
                                        "name" : "_id_"
                                }
                        },
                        {
                                "name" : "replset.minvalid",
                                "type" : "collection",
                                "options" : {

                                },
                                "info" : {
                                        "readOnly" : false,
                                        "uuid" : UUID("5564332b-3c3f-4103-acbd-c53c7a71581c")
                                },
                                "idIndex" : {
                                        "v" : 2,
                                        "key" : {
                                                "_id" : 1
                                        },
                                        "name" : "_id_"
                                }
                        },
                        {
                                "name" : "system.rollback.id",
                                "type" : "collection",
                                "options" : {

                                },
                                "info" : {
                                        "readOnly" : false,
                                        "uuid" : UUID("fa26f83a-8843-4b6d-8d4d-4cde192976bd")
                                },
                                "idIndex" : {
                                        "v" : 2,
                                        "key" : {
                                                "_id" : 1
                                        },
                                        "name" : "_id_"
                                }
                        }
                ]
        },
        "ok" : 1
}


问:
unable to use custom buildType - Active build variant "debug" does not have a test artifact
I took a look around and see some questions very similar to mine but it does appear to have the same solution I have in place which does not resolve the problem.

When I try to run a method test I receive an error in the footer of android studio that states "Active build variant "debug" does not have a test artifact"

I would like to use a different buildType for instrumented testing so that I can change an API path. It seemingly will not build and run unless I set the testBuildType "debug"

Here is what my gradle looks like

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    ...
    testBuildType "staging"

    defaultConfig {
        ...
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        debug {
            manifestPlaceholders.enableCrashReporting = "false"
            manifestPlaceholders.disableAnalytics = "true"

            buildConfigField "String", "API_DOMAIN", '"https://domain/dev/"'
        }

        staging {
            initWith debug
            buildConfigField "String", "API_DOMAIN", '"/"'
        }

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

            manifestPlaceholders.enableCrashReporting = "true"
            manifestPlaceholders.disableAnalytics = "false"

            buildConfigField "String", "API_DOMAIN", '"https://domain/prod/"'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    viewBinding {
        enabled = true
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }

    testOptions {
        unitTests.includeAndroidResources = true
        unitTests.returnDefaultValues = true
    }
}

dependencies {
    ...
}
</code>```

答:
Found the answer on this post. Appears that the Active Build Variant wont change on its own as one would expect.

android testBuildType not working

Body:
I took a look around and see some questions very similar to mine but it does appear to have the same solution I have in place which does not resolve the problem.

When I try to run a method test I receive an error in the footer of android studio that states "Active build variant "debug" does not have a test artifact"

I would like to use a different buildType for instrumented testing so that I can change an API path. It seemingly will not build and run unless I set the testBuildType "debug"

Here is what my gradle looks like

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    ...
    testBuildType "staging"

    defaultConfig {
        ...
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        debug {
            manifestPlaceholders.enableCrashReporting = "false"
            manifestPlaceholders.disableAnalytics = "true"

            buildConfigField "String", "API_DOMAIN", '"https://domain/dev/"'
        }

        staging {
            initWith debug
            buildConfigField "String", "API_DOMAIN", '"/"'
        }

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

            manifestPlaceholders.enableCrashReporting = "true"
            manifestPlaceholders.disableAnalytics = "false"

            buildConfigField "String", "API_DOMAIN", '"https://domain/prod/"'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    viewBinding {
        enabled = true
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }

    testOptions {
        unitTests.includeAndroidResources = true
        unitTests.returnDefaultValues = true
    }
}

dependencies {
    ...
}


问:
Scrambling HTML / CSS issue seems unexplainable
I've recently switched over a rails app to a new server. For some reason, search results are sometimes scrambled. They look like this:

But they should look like this:

When I check in firebug, it seems that the wrapper div is not being parsed correctly, and so instead of a bunch of nodes wrapped in an  tag, the nodes are flat in the collection.

This happens on chrome and firefox, windows and linux, and on different computers. There don't seem to be any CSS or HTML validation errors. I get no problem on my local development server, only in production.

What's odd is that when I view an offending page in Firefox, click View > Source, copy the HTML into a blank document and then open it, it comes out looking fine. I also don't seem to have this problem if I just fetch the page with curl.

The site is accessible at http://50.57.76.99. You might need to make a couple of searches to get the problematic result. Any ideas? I'm totally baffled!

答:
I've managed to avoid the issue.

If I don't wrap the whole item an  tag, the problem disappears. Obviously I'd rather have the whole item be a link, but just the image is okay for now. I think another solution would be to swap the
 tags for  tags as suggested, but this quick-fix seemed to do fine.

Still seems quite bizarre though, as it was seemingly arbitrary when it breaks. Thanks for the help!

Body:
I've managed to avoid the issue.

If I don't wrap the whole item an <a> tag, the problem disappears. Obviously I'd rather have the whole item be a link, but just the image is okay for now. I think another solution would be to swap the <div> tags for <span> tags as suggested, but this quick-fix seemed to do fine.

Still seems quite bizarre though, as it was seemingly arbitrary when it breaks. Thanks for the help!


问:
Spring Cloud Vault picking up properties from wrong profile
In my Spring Boot project I defined 4 profiles ide,dev,test and prod. When I ran the project using IntelliJ with profile ide, everything works fine and properties are retrieved from ide profile in the Vault. But during deployment in dev server when I select the dev profile using the argument -Dspring.profiles.active=dev dev profile is being selected and but ide profile properties are being retrieved

CustomVaultConfigurer.java

```<code>@Configuration
public class CustomVaultConfigurer  implements VaultConfigurer
{
    @Override
    public void addSecretBackends(SecretBackendConfigurer configurer)
    {
                configurer.add("secret/app/pres/ide");
        configurer.add("secret/app/pres/dev");
        configurer.add("secret/app/pres/test");
        configurer.add("secret/app/pres/prod");

        configurer.registerDefaultGenericSecretBackends(false);
        configurer.registerDefaultDiscoveredSecretBackends(true);
    }
}
</code>```

Error Log:

```<code>2020-05-27 19:28:25.663  INFO 1 --- [           main] gov.cancer.ccr.oit.pres.PresApplication  : The following profiles are active: dev
2020-05-27 19:28:28.495  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-05-27 19:28:29.710  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 1203ms. Found 55 JPA repository interfaces.
2020-05-27 19:28:30.142  INFO 1 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=87545ee5-101d-3ebb-a79a-d12f99f15e9c
2020-05-27 19:28:31.002  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler@70c53dbe' of type [org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-05-27 19:28:31.011  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'methodSecurityConfig' of type [gov.cancer.ccr.oit.pres.security.MethodSecurityConfig$$EnhancerBySpringCGLIB$$8721baa3] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-05-27 19:28:31.033  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'methodSecurityMetadataSource' of type [org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-05-27 19:28:31.608  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-05-27 19:28:31.635  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-05-27 19:28:31.636  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.35]
2020-05-27 19:28:31.778  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-05-27 19:28:31.778  INFO 1 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 6069 ms
2020-05-27 19:28:32.616  INFO 1 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-05-27 19:28:32.909  INFO 1 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-05-27 19:29:03.630 ERROR 1 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception during pool initialization.

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused (Connection refused). Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
</code>```

but when I place ide profile at the end(shown below) of the list, it works

```<code>configurer.add("secret/app/pres/dev");
configurer.add("secret/app/pres/test");
configurer.add("secret/app/pres/prod");
configurer.add("secret/app/pres/ide");

</code>```

答:
Okay. Dumb part on my end. As per Marks comment When you're using configurer.add(…) in combination with configurer.registerDefaultGenericSecretBackends(false) then Spring Cloud Vault does not look at spring.profiles.active at all but rather uses what your VaultConfigurer specifies.

The updated VaultConfigurer looks like below, and active profile is retrieved from

VaultConfigurer.java

```<code>@Configuration
public class CustomVaultConfigurer  implements VaultConfigurer
{
    @Autowired
    private Environment environment;

    @Override
    public void addSecretBackends(SecretBackendConfigurer configurer)
    {
        //Get active profile from environment, if none exist select DEV profile
        if(environment.getActiveProfiles().length > 0)
            configurer.add("secret/app/pres/"+environment.getActiveProfiles()[0]);
        else
            configurer.add("secret/app/pres/dev");

        configurer.registerDefaultGenericSecretBackends(false);
        configurer.registerDefaultDiscoveredSecretBackends(true);
    }
}
</code>```

Body:
In my Spring Boot project I defined 4 profiles ide,dev,test and prod. When I ran the project using IntelliJ with profile ide, everything works fine and properties are retrieved from ide profile in the Vault. But during deployment in dev server when I select the dev profile using the argument -Dspring.profiles.active=dev dev profile is being selected and but ide profile properties are being retrieved

CustomVaultConfigurer.java

@Configuration
public class CustomVaultConfigurer  implements VaultConfigurer
{
    @Override
    public void addSecretBackends(SecretBackendConfigurer configurer)
    {
                configurer.add("secret/app/pres/ide");
        configurer.add("secret/app/pres/dev");
        configurer.add("secret/app/pres/test");
        configurer.add("secret/app/pres/prod");

        configurer.registerDefaultGenericSecretBackends(false);
        configurer.registerDefaultDiscoveredSecretBackends(true);
    }
}

Error Log:

2020-05-27 19:28:25.663  INFO 1 --- [           main] gov.cancer.ccr.oit.pres.PresApplication  : The following profiles are active: dev
2020-05-27 19:28:28.495  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-05-27 19:28:29.710  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 1203ms. Found 55 JPA repository interfaces.
2020-05-27 19:28:30.142  INFO 1 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=87545ee5-101d-3ebb-a79a-d12f99f15e9c
2020-05-27 19:28:31.002  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler@70c53dbe' of type [org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-05-27 19:28:31.011  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'methodSecurityConfig' of type [gov.cancer.ccr.oit.pres.security.MethodSecurityConfig$$EnhancerBySpringCGLIB$$8721baa3] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-05-27 19:28:31.033  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'methodSecurityMetadataSource' of type [org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-05-27 19:28:31.608  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-05-27 19:28:31.635  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-05-27 19:28:31.636  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.35]
2020-05-27 19:28:31.778  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-05-27 19:28:31.778  INFO 1 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 6069 ms
2020-05-27 19:28:32.616  INFO 1 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-05-27 19:28:32.909  INFO 1 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-05-27 19:29:03.630 ERROR 1 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception during pool initialization.

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused (Connection refused). Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".

but when I place ide profile at the end(shown below) of the list, it works

configurer.add("secret/app/pres/dev");
configurer.add("secret/app/pres/test");
configurer.add("secret/app/pres/prod");
configurer.add("secret/app/pres/ide");

Body:
Okay. Dumb part on my end. As per Marks comment When you're using configurer.add(…) in combination with configurer.registerDefaultGenericSecretBackends(false) then Spring Cloud Vault does not look at spring.profiles.active at all but rather uses what your VaultConfigurer specifies.

The updated VaultConfigurer looks like below, and active profile is retrieved from

VaultConfigurer.java

@Configuration
public class CustomVaultConfigurer  implements VaultConfigurer
{
    @Autowired
    private Environment environment;

    @Override
    public void addSecretBackends(SecretBackendConfigurer configurer)
    {
        //Get active profile from environment, if none exist select DEV profile
        if(environment.getActiveProfiles().length > 0)
            configurer.add("secret/app/pres/"+environment.getActiveProfiles()[0]);
        else
            configurer.add("secret/app/pres/dev");

        configurer.registerDefaultGenericSecretBackends(false);
        configurer.registerDefaultDiscoveredSecretBackends(true);
    }
}


问:
How can I map items together in a json structure with jq?
I have a json structure that looks like this:

```<code>{
        "lorry1": {
                "box1": [
                        {"item": "shoes", "state": "new"},
                        {"item": "snacks", "state": "new"}
                ],
                "box2": [
                        {"item": "beer", "state": "cold"},
                        {"item": "potatoes"}
                ]
        },
        "lorry2": {
                "box1": [
                        {"item": "shoes", "state": "new"},
                        {"item": "snacks", "state": "new"}
                ],
                "box2": [
                        {"item": "beer", "state": "lukewarm"}
                ]
        }
}
</code>```

Now I want to know where I can find shoes:
I could come up with this jq query:

```<code>to_entries | select(.[].value | .[][].item=="shoes") | map({"lorry": "\(.key)"  })
</code>```

But that only gives me the lorries. Useful, but not quite there yet. I'd like to know the box they're in as well.

I came up with this, but it obviously is not correct:

```<code>to_entries | select(.[].value | .[][].item=="shoes") | keys as $box |map({"lorry": "\(.key)", "box": $box })
</code>```

The answer I'd like to get is lorry1, box1 and lorry2, box1.

Even better yet: I'd like to find all items and provide the information, like this:

```<code>"shoes": [ {"lorry1", "box1"}, {"lorry2", "box1" } ],
"snacks": [ {"lorry1", "box1"}, {"lorry2", "box1"} ],
"beer": [ {"lorry1", "box2"}, {"lorry2", "box2"} ],
"potatoes": [ {"lorry1", "box2"} ]
</code>```

but that may be asking a bit too much :)

答:
This looks like a overkill to me but it does the job.

```<code>[path(.[][][].item) as $p | [$p, getpath($p)]] |
group_by( .[1] ) |
map({(.[0][1]): (. | map([.[0][0,1]]))})|
add
</code>```

Save the above jq filter in file item_in.jq and run it as jq --from-file item_in.jq. Passing your input to this gives the following output:

```<code>{
  "beer": [
    [
      "lorry1",
      "box2"
    ],
    [
      "lorry2",
      "box2"
    ]
  ],
  "potatoes": [
    [
      "lorry1",
      "box2"
    ]
  ],
  "shoes": [
    [
      "lorry1",
      "box1"
    ],
    [
      "lorry2",
      "box1"
    ]
  ],
  "snacks": [
    [
      "lorry1",
      "box1"
    ],
    [
      "lorry2",
      "box1"
    ]
  ]
}
</code>```

The initial transformation was to dump leaves and their paths from the input JSON tree.
See
https://github.com/stedolan/jq/issues/78#issuecomment-17819519

Body:
I have a json structure that looks like this:

{
        "lorry1": {
                "box1": [
                        {"item": "shoes", "state": "new"},
                        {"item": "snacks", "state": "new"}
                ],
                "box2": [
                        {"item": "beer", "state": "cold"},
                        {"item": "potatoes"}
                ]
        },
        "lorry2": {
                "box1": [
                        {"item": "shoes", "state": "new"},
                        {"item": "snacks", "state": "new"}
                ],
                "box2": [
                        {"item": "beer", "state": "lukewarm"}
                ]
        }
}

Now I want to know where I can find shoes:
I could come up with this jq query:

to_entries | select(.[].value | .[][].item=="shoes") | map({"lorry": "\(.key)"  })

But that only gives me the lorries. Useful, but not quite there yet. I'd like to know the box they're in as well.

I came up with this, but it obviously is not correct:

to_entries | select(.[].value | .[][].item=="shoes") | keys as $box |map({"lorry": "\(.key)", "box": $box })

The answer I'd like to get is lorry1, box1 and lorry2, box1.

Even better yet: I'd like to find all items and provide the information, like this:

"shoes": [ {"lorry1", "box1"}, {"lorry2", "box1" } ],
"snacks": [ {"lorry1", "box1"}, {"lorry2", "box1"} ],
"beer": [ {"lorry1", "box2"}, {"lorry2", "box2"} ],
"potatoes": [ {"lorry1", "box2"} ]

but that may be asking a bit too much :)

Body:
This looks like a overkill to me but it does the job.

[path(.[][][].item) as $p | [$p, getpath($p)]] |
group_by( .[1] ) |
map({(.[0][1]): (. | map([.[0][0,1]]))})|
add

Save the above jq filter in file item_in.jq and run it as jq --from-file item_in.jq. Passing your input to this gives the following output:

{
  "beer": [
    [
      "lorry1",
      "box2"
    ],
    [
      "lorry2",
      "box2"
    ]
  ],
  "potatoes": [
    [
      "lorry1",
      "box2"
    ]
  ],
  "shoes": [
    [
      "lorry1",
      "box1"
    ],
    [
      "lorry2",
      "box1"
    ]
  ],
  "snacks": [
    [
      "lorry1",
      "box1"
    ],
    [
      "lorry2",
      "box1"
    ]
  ]
}

The initial transformation was to dump leaves and their paths from the input JSON tree.
See
https://github.com/stedolan/jq/issues/78#issuecomment-17819519