问:
Can't launch activity from ADB shell
Using the command adb shell am start -a com.myfit.sugatmanshakya.my_fit.LoginActivity throws out the following error:

> Activity not started, unable to resolve intent, flg=0x10000000

Part of my AndroidManifest.xml code:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest android:versionCode="1" android:versionName="1.0" package="com.myfit.sugatmanshakya.my_fit"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="28" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <permission android:name="com.myfit.sugatmanshakya.my_fit.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="com.myfit.sugatmanshakya.my_fit.permission.C2D_MESSAGE" />
    <application android:theme="@style/AppTheme" android:label="@string/app_name" android:icon="@drawable/transparent_logo" android:debuggable="true" android:allowBackup="true" android:supportsRtl="true" android:roundIcon="@mipmap/ic_launcher_round" android:appComponentFactory="android.support.v4.app.CoreComponentFactory">
        <activity android:name="com.myfit.sugatmanshakya.my_fit.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.myfit.sugatmanshakya.my_fit.LoginActivity" />
        <activity android:name="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Healthy Facts" android:name="com.myfit.sugatmanshakya.my_fit.HealthyFactsActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Help" android:name="com.myfit.sugatmanshakya.my_fit.HelpActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Note Exercise" android:name="com.myfit.sugatmanshakya.my_fit.CatalogActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:name="com.myfit.sugatmanshakya.my_fit.ExerciseEditorActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.CatalogActivity" />
        <provider android:name="com.myfit.sugatmanshakya.my_fit.Database.ExerciseProvider" android:exported="false" android:authorities="com.myfit.sugatmanshakya.my_fit" />
        <activity android:label="Send Feedback" android:name="com.myfit.sugatmanshakya.my_fit.FeedbackActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Workouts" android:name="com.myfit.sugatmanshakya.my_fit.DetailedWorkOutActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Healthy Facts" android:name="com.myfit.sugatmanshakya.my_fit.FatBurnActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Legs" android:name="com.myfit.sugatmanshakya.my_fit.LegActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Abs" android:name="com.myfit.sugatmanshakya.my_fit.AbsActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Butt" android:name="com.myfit.sugatmanshakya.my_fit.ButtActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Core" android:name="com.myfit.sugatmanshakya.my_fit.CoreActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Arms" android:name="com.myfit.sugatmanshakya.my_fit.ArmsActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Strength" android:name="com.myfit.sugatmanshakya.my_fit.StrengthActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />

</code>```

So what should I do?

答:
```<code>adb shell am start -a com.myfit.sugatmanshakya.my_fit.LoginActivity
</code>```

-a is for an action string. You do not have an action string on this activity:

```<code><activity android:name="com.myfit.sugatmanshakya.my_fit.LoginActivity" />
</code>```

Instead, use:

```<code>adb shell am start -n com.myfit.sugatmanshakya.my_fit/com.myfit.sugatmanshakya.my_fit.LoginActivity
</code>```

(replace the first com.myfit.sugatmanshakya.my_fit with your application ID, if that is not already your application ID)

Title: Can't launch activity from ADB shell

Body:
Using the command adb shell am start -a com.myfit.sugatmanshakya.my_fit.LoginActivity throws out the following error:

> Activity not started, unable to resolve intent, flg=0x10000000

Part of my AndroidManifest.xml code:

<?xml version="1.0" encoding="utf-8"?>
<manifest android:versionCode="1" android:versionName="1.0" package="com.myfit.sugatmanshakya.my_fit"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="28" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <permission android:name="com.myfit.sugatmanshakya.my_fit.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="com.myfit.sugatmanshakya.my_fit.permission.C2D_MESSAGE" />
    <application android:theme="@style/AppTheme" android:label="@string/app_name" android:icon="@drawable/transparent_logo" android:debuggable="true" android:allowBackup="true" android:supportsRtl="true" android:roundIcon="@mipmap/ic_launcher_round" android:appComponentFactory="android.support.v4.app.CoreComponentFactory">
        <activity android:name="com.myfit.sugatmanshakya.my_fit.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.myfit.sugatmanshakya.my_fit.LoginActivity" />
        <activity android:name="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Healthy Facts" android:name="com.myfit.sugatmanshakya.my_fit.HealthyFactsActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Help" android:name="com.myfit.sugatmanshakya.my_fit.HelpActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Note Exercise" android:name="com.myfit.sugatmanshakya.my_fit.CatalogActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:name="com.myfit.sugatmanshakya.my_fit.ExerciseEditorActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.CatalogActivity" />
        <provider android:name="com.myfit.sugatmanshakya.my_fit.Database.ExerciseProvider" android:exported="false" android:authorities="com.myfit.sugatmanshakya.my_fit" />
        <activity android:label="Send Feedback" android:name="com.myfit.sugatmanshakya.my_fit.FeedbackActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Workouts" android:name="com.myfit.sugatmanshakya.my_fit.DetailedWorkOutActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Healthy Facts" android:name="com.myfit.sugatmanshakya.my_fit.FatBurnActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Legs" android:name="com.myfit.sugatmanshakya.my_fit.LegActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Abs" android:name="com.myfit.sugatmanshakya.my_fit.AbsActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Butt" android:name="com.myfit.sugatmanshakya.my_fit.ButtActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Core" android:name="com.myfit.sugatmanshakya.my_fit.CoreActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Arms" android:name="com.myfit.sugatmanshakya.my_fit.ArmsActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />
        <activity android:label="Strength" android:name="com.myfit.sugatmanshakya.my_fit.StrengthActivity" android:parentActivityName="com.myfit.sugatmanshakya.my_fit.WorkoutsActivity" />

So what should I do?

Body:
adb shell am start -a com.myfit.sugatmanshakya.my_fit.LoginActivity

-a is for an action string. You do not have an action string on this activity:

<activity android:name="com.myfit.sugatmanshakya.my_fit.LoginActivity" />

Instead, use:

adb shell am start -n com.myfit.sugatmanshakya.my_fit/com.myfit.sugatmanshakya.my_fit.LoginActivity

(replace the first com.myfit.sugatmanshakya.my_fit with your application ID, if that is not already your application ID)


来源: stackexchange

问:
How to remove numeric keys when converting a json object to xml in java
I am new to JSON and XML and I got a weird issue which am trying to work on since few days now. No luck yet.

There is a json object which is being sent to my program as String. Now I need to convert the given string to json and then to XML. My output should be a String of my converted XML.

I was able to convert the string to JSON and then to XML without any issues. Sample code below

```<code>org.json.JSONObject jsonFileObject = new org.json.JSONObject(json);
String xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-15\"?>\n<"+root+">"
                 + org.json.XML.toString(jsonFileObject) + "</"+root+">";
</code>```

But the problem is there are few keys in the json object which are numeric and we need to remove such keys.

Sample JSON

```<code>{
"product": {
    "p1": true,
     "test": {
        "1000": [
        {
        "name": "name1",
        "id": "id1"
        }
                ],
        "2100": [
        {
        "name": "name2",
        "id": "id2"
        }
        ],
        "3200": [
        {
        "name": "name3",
        "id": "id3"
        }
        ],
        "8340": [
        {
        "name": "name4",
        "id": "id4"
        }
        ],
        "6200": [
        {
        "name": "name5",
        "id": "id5"
        }
        ]
    },
    "p2": "p2 test"
  }
}
</code>```

In the above case my output should be

```<code><test/>
</code>```

Here the name and id are not always available. sometimes they might be empty as well.

Can someone please help me with this.

答:
This JSON can be converted to this XML.</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<product>
  <p1 boolean="true">true</p1>
  <test>
    <__GE__000 array="true">
      <name>name1</name>
      <id>id1</id>
    </__GE__000>
    <__GI__100 array="true">
      <name>name2</name>
      <id>id2</id>
    </__GI__100>
    <__GM__200 array="true">
      <name>name3</name>
      <id>id3</id>
    </__GM__200>
    <__HA__340 array="true">
      <name>name4</name>
      <id>id4</id>
    </__HA__340>
    <__GY__200 array="true">
      <name>name5</name>
      <id>id5</id>
    </__GY__200>
   </test>
  <p2>p2 test</p2>
</product>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to JSON and XML and I got a weird issue which am trying to work on since few days now. No luck yet.

There is a json object which is being sent to my program as String. Now I need to convert the given string to json and then to XML. My output should be a String of my converted XML.

I was able to convert the string to JSON and then to XML without any issues. Sample code below

org.json.JSONObject jsonFileObject = new org.json.JSONObject(json);
String xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-15\"?>\n<"+root+">"
                 + org.json.XML.toString(jsonFileObject) + "</"+root+">";

But the problem is there are few keys in the json object which are numeric and we need to remove such keys.

Sample JSON

{
"product": {
    "p1": true,
     "test": {
        "1000": [
        {
        "name": "name1",
        "id": "id1"
        }
                ],
        "2100": [
        {
        "name": "name2",
        "id": "id2"
        }
        ],
        "3200": [
        {
        "name": "name3",
        "id": "id3"
        }
        ],
        "8340": [
        {
        "name": "name4",
        "id": "id4"
        }
        ],
        "6200": [
        {
        "name": "name5",
        "id": "id5"
        }
        ]
    },
    "p2": "p2 test"
  }
}

In the above case my output should be

<test/>

Here the name and id are not always available. sometimes they might be empty as well.

Can someone please help me with this.

Body:
This JSON can be converted to this XML.

<?xml version="1.0" encoding="UTF-8"?>
<product>
  <p1 boolean="true">true</p1>
  <test>
    <__GE__000 array="true">
      <name>name1</name>
      <id>id1</id>
    </__GE__000>
    <__GI__100 array="true">
      <name>name2</name>
      <id>id2</id>
    </__GI__100>
    <__GM__200 array="true">
      <name>name3</name>
      <id>id3</id>
    </__GM__200>
    <__HA__340 array="true">
      <name>name4</name>
      <id>id4</id>
    </__HA__340>
    <__GY__200 array="true">
      <name>name5</name>
      <id>id5</id>
    </__GY__200>
   </test>
  <p2>p2 test</p2>
</product>

ContentLicense: CC BY-SA 4.0


问:
Youtube API getCurrentTime() in milliseconds?
I am using the Youtube API to show subtitles below a video. Whenever the video is stopped/started or the position moved I will take the time using getCurrentTime(), however it only provides the value in full seconds. When I want to have fast changes in the subtitles, I need a more precise way to get the time, is there any way to get it in milliseconds?</p>

答:
The getTime() function is supposed to return the current time of the video in second followed by milliseconds, such as 2.1313131 when the video is paused early. The modified code snippit of the api's demo shows this in the console.
I'm unsure if you're setting any time interval, or accidentally converting the time into integers.

      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        var videotime = 0;
        event.target.playVideo();
        function updateTime() {
          console.log(player.getCurrentTime());
        }
        timeupdater = setInterval(updateTime, 0);
      }```


问:
CSS decrease space between text and border
When hovering a link I want it to get an underline.
The underline should be 2px strong and 4px below the text.

With

```<code>text-decoration: underline
</code>```

I get a 1px strong line which is 4px below. (Distances vary by font)

If I write

```<code>border-bottom: 2px solid #000;
</code>```

I get a 2px line which is about 10px below the text.

How can I decrease the distance between the text and the border?

```<code>padding-bottom: -6px
</code>```

does not work. Any negative value with padding-bottom does not work.

Or how can i get the underline to be 2px strong?

http://jsfiddle.net/qJE2w/1/

Update 2022: For everyone coming here years after this question was asked:

It's now possible to change the underline via CSS. There are "new" properties like text-underline-offset and text-decoration-thickness.

答:
Multi line solution

Explanation. I'm creating a sibling which has the same text and text style and is shifted to top a bit. If you want to keep your code clean you can insert the sibling using JS on a page load event.

Restrictions. This solution doesn't work inside paragraph of text.

.underlined_link {
  text-decoration: none;
  display: inline;
}
.underlined_link h2,
.underlined_link div {
  display: inline;
  font-size: 20px;
  margin: 0;
  line-height: 35px;
  font-weight: normal;
  padding: 0;
}
.underlined_link h2 {
  color: transparent;
  border-bottom: 1px solid red;
}
.underlined_link div {
  position: absolute;
  top: 10px;
  left: 8px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  <h2>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu nulla vel massa efficitur lacinia. In at dolor ac nulla interdum convallis. Nullam vitae eros orci. Curabitur vitae maximus erat, vel pulvinar ex.</h2>
  <div><span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu nulla vel massa efficitur lacinia. In at dolor ac nulla interdum convallis. Nullam vitae eros orci. Curabitur vitae maximus erat, vel pulvinar ex.</span></div>
</code>```

Body:
When hovering a link I want it to get an underline.
The underline should be 2px strong and 4px below the text.

With

text-decoration: underline

I get a 1px strong line which is 4px below. (Distances vary by font)

If I write

border-bottom: 2px solid #000;

I get a 2px line which is about 10px below the text.

How can I decrease the distance between the text and the border?

padding-bottom: -6px

does not work. Any negative value with padding-bottom does not work.

Or how can i get the underline to be 2px strong?

http://jsfiddle.net/qJE2w/1/

Update 2022: For everyone coming here years after this question was asked:

It's now possible to change the underline via CSS. There are "new" properties like text-underline-offset and text-decoration-thickness.

Body:
Multi line solution

Explanation. I'm creating a sibling which has the same text and text style and is shifted to top a bit. If you want to keep your code clean you can insert the sibling using JS on a page load event.

Restrictions. This solution doesn't work inside paragraph of text.

.underlined_link {
  text-decoration: none;
  display: inline;
}
.underlined_link h2,
.underlined_link div {
  display: inline;
  font-size: 20px;
  margin: 0;
  line-height: 35px;
  font-weight: normal;
  padding: 0;
}
.underlined_link h2 {
  color: transparent;
  border-bottom: 1px solid red;
}
.underlined_link div {
  position: absolute;
  top: 10px;
  left: 8px;
}

<a class="underlined_link" href="#">
  <h2>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu nulla vel massa efficitur lacinia. In at dolor ac nulla interdum convallis. Nullam vitae eros orci. Curabitur vitae maximus erat, vel pulvinar ex.</h2>
  <div><span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu nulla vel massa efficitur lacinia. In at dolor ac nulla interdum convallis. Nullam vitae eros orci. Curabitur vitae maximus erat, vel pulvinar ex.</span></div>
</a>


问:
SyntaxError: Unexpected token '<' when dockerizing react app
I have a react project with Webpack which I'm trying to dockerize it following this article.

Dockerfile:

```<code>FROM node:12.14.1

RUN npm install webpack -g

WORKDIR /tmp
COPY package.json /tmp/
RUN npm config set registry http://registry.npmjs.org/ && npm install

WORKDIR /usr/app
COPY . /usr/app/
RUN cp -a /tmp/node_modules /usr/app/

RUN webpack

ENV NODE_ENV=production
ENV PORT=4000

CMD [ "/usr/local/bin/node", "--experimental-modules", "./src/index.js" ]

EXPOSE 4000
</code>```

docker-compose.yml:

```<code>ex_dashboard:
  build: .
  ports:
  - "80:4000"
  volumes:
  - .:/usr/app/:rw
  environment:
  - NODE_ENV=dev
  command: >
    sh -c '
      if test -d node_modules;
      then
        echo node_modules_exists ;
      else
        cp -a /tmp/node_modules /usr/app/dashboard;
      fi &&
      npm install &&
      /usr/local/bin/node --experimental-modules ./src/index.js
    '
</code>```

When I run docker-compose up, everything goes well until I encounter this error:

```<code>ex_dashboard_1  | (node:18) ExperimentalWarning: The ESM module loader is experimental.
ex_dashboard_1  | file:///usr/app/src/index.js:9
ex_dashboard_1  |   <Provider store={store}>
ex_dashboard_1  |   ^
ex_dashboard_1  |
ex_dashboard_1  | SyntaxError: Unexpected token '<'
ex_dashboard_1  |     at Loader.moduleStrategy (internal/modules/esm/translators.js:66:18)
ex_dashboard_1  |     at async link (internal/modules/esm/module_job.js:37:21)
</code>```

The whole project works well if I just run it by npm start or build it by npm run build. But I don't know why this happens in docker container.

Here is package.json:

```<code>{
  "name": "explore_dashboard",
  "version": "1.0.0",
  "description": "A dashboard for the Explore project",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "cross-env NODE_ENV=development webpack-dev-server --hot",
    "build": "cross-env NODE_ENV=production webpack",
    "lint": "eslint ./src",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://gitlab.basalam.dev/data/explore_dashboard.git"
  },
  "author": "Gh.Sherafati",
  "license": "ISC",
  "resolve": {
    "alias": {
      "react-dom": "@hot-loader/react-dom"
    }
  },
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/plugin-transform-runtime": "^7.8.3",
    "@babel/preset-env": "^7.8.4",
    "@babel/preset-react": "^7.8.3",
    "babel-eslint": "^10.0.3",
    "babel-loader": "^8.0.6",
    "cross-env": "^7.0.0",
    "css-loader": "^3.4.2",
    "eslint": "^6.1.0",
    "eslint-config-airbnb": "^18.0.1",
    "eslint-loader": "^3.0.3",
    "eslint-plugin-import": "^2.20.0",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-react": "^7.18.0",
    "eslint-plugin-react-hooks": "^1.7.0",
    "html-webpack-plugin": "^3.2.0",
    "node-sass": "^4.13.1",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.1.3",
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.10.2"
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.27",
    "@fortawesome/free-solid-svg-icons": "^5.12.1",
    "@fortawesome/react-fontawesome": "^0.1.8",
    "@hot-loader/react-dom": "^16.11.0",
    "@types/react": "^16.9.19",
    "axios": "^0.19.2",
    "react": "^16.12.0",
    "react-beautiful-dnd": "^12.2.0",
    "react-dom": "^16.12.0",
    "react-hot-loader": "^4.12.19",
    "react-redux": "^7.1.3",
    "redux": "^4.0.5",
    "redux-saga": "^1.1.3"
  }
}
</code>```

And webpack.config.js:

```<code>const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const { env } = process;

module.exports = {
  entry: './src/index.js',
  mode: env.NODE_ENV,
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader', 'eslint-loader'],
      },
      {
        test: /\.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          'style-loader',
          // Translates CSS into CommonJS
          'css-loader',
          // Compiles Sass to CSS
          'sass-loader',
        ],
      },
    ],
  },
  resolve: {
    extensions: ['*', '.js', '.jsx'],
  },
  output: {
    path: path.join(__dirname, '/build'),
    publicPath: '/',
    filename: 'bundle.js',
  },
  plugins: [
    new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(env.NODE_ENV) }),
    new HtmlWebpackPlugin({
      template: path.resolve('./src/index.html'),
    }),
  ],
  devServer: {
    contentBase: './build',
    hot: true,
  },
  devtool: env.NODE_ENV === 'development' ? 'cheap-module-eval-source-map' : undefined,
};
</code>```

Also index.js:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './redux/store';
import App from './components/App';
import './scss/main.scss';

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('app'),
);

module.hot.accept();
</code>```

答:
The --experimental-modules flag can be used to enable support for ECMAScript modules (ES modules).

option 1

```<code>CMD ["sh", "-c", "exec node --experimental-modules index.js"]
</code>```

option 2

```<code>CMD exec node --experimental-modules index.js
</code>```

Full Docs:

Body:
I have a react project with Webpack which I'm trying to dockerize it following this article.

Dockerfile:

FROM node:12.14.1

RUN npm install webpack -g

WORKDIR /tmp
COPY package.json /tmp/
RUN npm config set registry http://registry.npmjs.org/ && npm install

WORKDIR /usr/app
COPY . /usr/app/
RUN cp -a /tmp/node_modules /usr/app/

RUN webpack

ENV NODE_ENV=production
ENV PORT=4000

CMD [ "/usr/local/bin/node", "--experimental-modules", "./src/index.js" ]

EXPOSE 4000

docker-compose.yml:

ex_dashboard:
  build: .
  ports:
  - "80:4000"
  volumes:
  - .:/usr/app/:rw
  environment:
  - NODE_ENV=dev
  command: >
    sh -c '
      if test -d node_modules;
      then
        echo node_modules_exists ;
      else
        cp -a /tmp/node_modules /usr/app/dashboard;
      fi &&
      npm install &&
      /usr/local/bin/node --experimental-modules ./src/index.js
    '

When I run docker-compose up, everything goes well until I encounter this error:

ex_dashboard_1  | (node:18) ExperimentalWarning: The ESM module loader is experimental.
ex_dashboard_1  | file:///usr/app/src/index.js:9
ex_dashboard_1  |   <Provider store={store}>
ex_dashboard_1  |   ^
ex_dashboard_1  |
ex_dashboard_1  | SyntaxError: Unexpected token '<'
ex_dashboard_1  |     at Loader.moduleStrategy (internal/modules/esm/translators.js:66:18)
ex_dashboard_1  |     at async link (internal/modules/esm/module_job.js:37:21)

The whole project works well if I just run it by npm start or build it by npm run build. But I don't know why this happens in docker container.

Here is package.json:

{
  "name": "explore_dashboard",
  "version": "1.0.0",
  "description": "A dashboard for the Explore project",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "cross-env NODE_ENV=development webpack-dev-server --hot",
    "build": "cross-env NODE_ENV=production webpack",
    "lint": "eslint ./src",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://gitlab.basalam.dev/data/explore_dashboard.git"
  },
  "author": "Gh.Sherafati",
  "license": "ISC",
  "resolve": {
    "alias": {
      "react-dom": "@hot-loader/react-dom"
    }
  },
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/plugin-transform-runtime": "^7.8.3",
    "@babel/preset-env": "^7.8.4",
    "@babel/preset-react": "^7.8.3",
    "babel-eslint": "^10.0.3",
    "babel-loader": "^8.0.6",
    "cross-env": "^7.0.0",
    "css-loader": "^3.4.2",
    "eslint": "^6.1.0",
    "eslint-config-airbnb": "^18.0.1",
    "eslint-loader": "^3.0.3",
    "eslint-plugin-import": "^2.20.0",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-react": "^7.18.0",
    "eslint-plugin-react-hooks": "^1.7.0",
    "html-webpack-plugin": "^3.2.0",
    "node-sass": "^4.13.1",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.1.3",
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.10.2"
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.27",
    "@fortawesome/free-solid-svg-icons": "^5.12.1",
    "@fortawesome/react-fontawesome": "^0.1.8",
    "@hot-loader/react-dom": "^16.11.0",
    "@types/react": "^16.9.19",
    "axios": "^0.19.2",
    "react": "^16.12.0",
    "react-beautiful-dnd": "^12.2.0",
    "react-dom": "^16.12.0",
    "react-hot-loader": "^4.12.19",
    "react-redux": "^7.1.3",
    "redux": "^4.0.5",
    "redux-saga": "^1.1.3"
  }
}

And webpack.config.js:

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const { env } = process;

module.exports = {
  entry: './src/index.js',
  mode: env.NODE_ENV,
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader', 'eslint-loader'],
      },
      {
        test: /\.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          'style-loader',
          // Translates CSS into CommonJS
          'css-loader',
          // Compiles Sass to CSS
          'sass-loader',
        ],
      },
    ],
  },
  resolve: {
    extensions: ['*', '.js', '.jsx'],
  },
  output: {
    path: path.join(__dirname, '/build'),
    publicPath: '/',
    filename: 'bundle.js',
  },
  plugins: [
    new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(env.NODE_ENV) }),
    new HtmlWebpackPlugin({
      template: path.resolve('./src/index.html'),
    }),
  ],
  devServer: {
    contentBase: './build',
    hot: true,
  },
  devtool: env.NODE_ENV === 'development' ? 'cheap-module-eval-source-map' : undefined,
};

Also index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './redux/store';
import App from './components/App';
import './scss/main.scss';

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('app'),
);

module.hot.accept();

Body:
The --experimental-modules flag can be used to enable support for ECMAScript modules (ES modules).

option 1

CMD ["sh", "-c", "exec node --experimental-modules index.js"]

option 2

CMD exec node --experimental-modules index.js

Full Docs:


问:
Remove Value in Sharedprefenreces
I noticed that in sharedprefrences you can remove a key but not a value.

```<code>SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove(key);
</code>```

How can i remove a  value?

答:
Welcome to Stackoverflow,
from the documentation of the package on pub.dev I can see that you might have understood the method's intention:

1 - Using the remove method removes both the key and the value, and you can set the key later with another value, that works perfectly.

2- Alternatively as 'MyNameIs' pointed out, you can set the key's value with null.

please also note that you can clear all of SharedPreferences' data using the clear method.

You can refer to the documentation of the SharedPreferences class from here:
https://pub.dev/documentation/shared_preferences/latest/shared_preferences/SharedPreferences-class.html

Title: Remove Value in Sharedprefenreces

Body:
I noticed that in sharedprefrences you can remove a key but not a value.

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove(key);

How can i remove a  value?


问:
update row after Period of time using laravel
I am developing a site that works for reservation and  i have rows for payment and status .son i need to update row for payment and status automatic after 24 hours How can  I do this

答:
If you use cpanel you have somthing called Cron Jobs

From Cron Jobs you can select php script path you want to execute and you can select slot duration


问:
How many minimum and maximum records FULL JOIN can return
This question is interested me in SQL query. How many min. and max. records FULL JOIN can return when joining two tables without any other conditions? Say, if there are 5 rows in table '1' and 10 rows in table '2'.

It seems to me that the minimum and maximum will be equal. 10/10. Is it so?

Exm:

```<code>SELECT customers.customer_id,

orders.order_id,

orders.order_date

FROM customers

FULL OUTER JOIN orders

ON customers.customer_id = orders.customer_id
</code>```

答:
Minimum rows returned: A FULL JOIN would return at minimum the number of rows that is contained in the largest table. This would happen for instance if all the rows from the smallest table are matched by only one row from the other joined table the JOIN condition.

Maximum rows returned: At maximum the product of number of rows in both table if the FULL JOIN condition always matches (for instance FULL JOIN ON TRUE).

Body:
This question is interested me in SQL query. How many min. and max. records FULL JOIN can return when joining two tables without any other conditions? Say, if there are 5 rows in table '1' and 10 rows in table '2'.

It seems to me that the minimum and maximum will be equal. 10/10. Is it so?

Exm:

SELECT customers.customer_id,

orders.order_id,

orders.order_date

FROM customers

FULL OUTER JOIN orders

ON customers.customer_id = orders.customer_id


问:
get CPU usage for process by PID (top source code)
How can I get CPU usage for process if i know only PID?
MAXOS X

I looked through top utility source codes for MACOSX and
I have found several important functions in libtop.c

```<code>/* Iterate through all processes and update their statistics. */
libtop_p_proc_table_read(boolean_t reg)

libtop_p_task_update()

/* Get CPU usage statistics.    */
libtop_pinfo_update_cpu_usage()
</code>```

The problem is that I don't understand how they get %CPU usage from this huge amout of
MACOS specific "mach kernel" system calls.
Does anybody have solution for this?

I the source they get system_time, user_time , total_time.

I total_time is time from process start or what?
Or may be total_time is equal 1 sec.

For example my results: for Opera Browser:

pid:1214 user:653.517582sec system:193.597306sec total:847.114888sec

Correct info from top utility:

PID   COMMAND      %CPU TIME

1214- Opera        8.0  14:04.52

I dont understand how to convert my results to 8.0%.
Total time here is a sum of user time and system time.
Total time is correct: 847sec is approx 14min 04 sec
To get cpu usage percent i need something like idle time for all process.

I have already spend the whole day but without any advance.

答: Look at GetCPUUsage() in https://chromium.googlesource.com/chromium/src/+/master/base/process/process_metrics_mac.cc for how this is implemented in chrome's task manager.</p>

ContentLicense: CC BY-SA 2.5

Body:
How can I get CPU usage for process if i know only PID?
MAXOS X

I looked through top utility source codes for MACOSX and
I have found several important functions in libtop.c

/* Iterate through all processes and update their statistics. */
libtop_p_proc_table_read(boolean_t reg)

libtop_p_task_update()

/* Get CPU usage statistics.    */
libtop_pinfo_update_cpu_usage()

The problem is that I don't understand how they get %CPU usage from this huge amout of
MACOS specific "mach kernel" system calls.
Does anybody have solution for this?

I the source they get system_time, user_time , total_time.

I total_time is time from process start or what?
Or may be total_time is equal 1 sec.

For example my results: for Opera Browser:

pid:1214 user:653.517582sec system:193.597306sec total:847.114888sec

Correct info from top utility:

PID   COMMAND      %CPU TIME

1214- Opera        8.0  14:04.52

I dont understand how to convert my results to 8.0%.
Total time here is a sum of user time and system time.
Total time is correct: 847sec is approx 14min 04 sec
To get cpu usage percent i need something like idle time for all process.

I have already spend the whole day but without any advance.


问:
Cast is invalid on object
I have this problem, when I try to cast the "batch" object, I am raised exception "Invalid cast".
Can you help me out with why?
The vault5 object exists and is correct.

```<code>public void batch(IEdmVault5 vault5)
{
    edmVault11 = (IEdmVault11)vault5;
    IEdmBatchRefVars batch = default(IEdmBatchRefVars);
    batch = (IEdmBatchRefVars)edmVault11.CreateUtility(EdmUtility.EdmUtil_BatchRefVars);

    //some code
}
</code>```

Edit 1:
Error message:

System.InvalidCastException
        HResult=0x80004002
        Messaggio=Cast specificato non valido

答:
I would suggest you try out this change , also

```<code> public void batch(IEdmVault5 vault5)
{
    IEdmVault7 edmValult11 = null;
    if (vault5 == null)
    {
           vault5 = new EdmVault5();
    }
    edmVault11 = (IEdmVault11)vault5;
    IEdmBatchRefVars batch = default(IEdmBatchRefVars);
    batch = (IEdmBatchRefVars)edmVault11.CreateUtility(EdmUtility.EdmUtil_BatchRefVars);

    //some code
}
</code>```

Besides given the nature of Solidworks API make sure that the installation and license are valid .

Title: Cast is invalid on object

Body:
I have this problem, when I try to cast the "batch" object, I am raised exception "Invalid cast".
Can you help me out with why?
The vault5 object exists and is correct.

public void batch(IEdmVault5 vault5)
{
    edmVault11 = (IEdmVault11)vault5;
    IEdmBatchRefVars batch = default(IEdmBatchRefVars);
    batch = (IEdmBatchRefVars)edmVault11.CreateUtility(EdmUtility.EdmUtil_BatchRefVars);

    //some code
}

Edit 1:
Error message:

System.InvalidCastException
        HResult=0x80004002
        Messaggio=Cast specificato non valido

Body:
I would suggest you try out this change , also

 public void batch(IEdmVault5 vault5)
{
    IEdmVault7 edmValult11 = null;
    if (vault5 == null)
    {
           vault5 = new EdmVault5();
    }
    edmVault11 = (IEdmVault11)vault5;
    IEdmBatchRefVars batch = default(IEdmBatchRefVars);
    batch = (IEdmBatchRefVars)edmVault11.CreateUtility(EdmUtility.EdmUtil_BatchRefVars);

    //some code
}

Besides given the nature of Solidworks API make sure that the installation and license are valid .


问:
AngularJs -- Access to XMLHttpRequest has been blocked by CORS policy
error :

Access to XMLHttpRequest at 'http://localhost:8080/api/v1/locations' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I test the get method in a request.http file of WebStorm and in Postman and that work , but that doesn't work in my Angularjs project .
(I get from a Spring boot java project).

```<code>var app = angular.module('myApp', []);
  app.controller('myCtrl', function($scope, $http) {
    $http.get("http://localhost:8080/api/v1/locations")
            .then(function(response) {
              $scope.result = response.data;
              console.log("OK:", response.data);
            }).catch(function(response) {
              console.log("ERROR:", response);
    });
  });
</code>```

my get function return something like this in postman

```<code>[
 {
   "datetime": "2019-01-10T19:00:00.000+0000",
"user": {
  "firstName": "thr",
  "lastName": "an",
  "id": 1
},
"speed": 0.0,
"latitude": 37.421998333333335,
"longitude": -122.08400000000002,
"id": 1
},

{
   "datetime": "2019-01-10T19:01:00.000+0000",
"user": {
  "firstName": "thr",
  "lastName": "an",
  "id": 1
},
"speed": 1.575,
"latitude": 37.42198333333335,
"longitude": -122.080000000002,
"id": 2
}
]
</code>```

the console : https://i.top4top.io/p_1507d02621.jpg

答:
Postman usually doesn't use or consider the CORS header. The browser on the other hand needs it and if its missing, you get this error.
In your backend code, you should whitelist the domain which you use to request the data. In your case this would be http://localhost:8080.
I hope this makes sense.

Body:
error :

Access to XMLHttpRequest at 'http://localhost:8080/api/v1/locations' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I test the get method in a request.http file of WebStorm and in Postman and that work , but that doesn't work in my Angularjs project .
(I get from a Spring boot java project).

var app = angular.module('myApp', []);
  app.controller('myCtrl', function($scope, $http) {
    $http.get("http://localhost:8080/api/v1/locations")
            .then(function(response) {
              $scope.result = response.data;
              console.log("OK:", response.data);
            }).catch(function(response) {
              console.log("ERROR:", response);
    });
  });

my get function return something like this in postman

[
 {
   "datetime": "2019-01-10T19:00:00.000+0000",
"user": {
  "firstName": "thr",
  "lastName": "an",
  "id": 1
},
"speed": 0.0,
"latitude": 37.421998333333335,
"longitude": -122.08400000000002,
"id": 1
},

{
   "datetime": "2019-01-10T19:01:00.000+0000",
"user": {
  "firstName": "thr",
  "lastName": "an",
  "id": 1
},
"speed": 1.575,
"latitude": 37.42198333333335,
"longitude": -122.080000000002,
"id": 2
}
]

the console : https://i.top4top.io/p_1507d02621.jpg


问:
Python object persistence over re-execs
Is where a way to persist objects over re-execs of a running script?  If I want a running script to re execute itself to pick up any code changes, (os.exec*) is there a way to persist the objects for access after the re-execution?  I could set environment variables with pickled ascii data, or write that data to a pipe and re-read it after the re-execution, but that seems inelegant or like a hack.  Even if doing that, not all items pickle well. </p>

答:
Check out shelve.

```<code>import shelve

db = shelve.open("database", "c")
db["one"] = 1
db["two"] = 2
db["three"] = 3
db.close()
</code>```

Title: Python object persistence over re-execs

Body:
Check out shelve.

import shelve

db = shelve.open("database", "c")
db["one"] = 1
db["two"] = 2
db["three"] = 3
db.close()


问:
Is it possible to conditionally set the artifact name in my Azure DevOps build pipeline "publish artifact" task?
I was wondering if it is possible to conditionally set the name of my build artifact in my Azure DevOps build pipeline "publish artifact" task?  I want to produce different artifacts based on the input to my build pipeline.  Say, based on  the input pipeline variables, I want to produce one of three artifacts ("red", "blue", "green").  Is it possible to specify the artifact being produced in my "publish artifact" task based on the input variable, or is it easier/better just to produce three build pipelines?</p>

答:
This is the bash version in case you run the task on Linux. The NAME is a custom variable which uses the pre-defined variable as value.</p>

```<code>trigger_model_version=RELEASE_ARTIFACTS_${NAME^^}_BUILDNUMBER
export version=${!trigger_model_version}
echo Deploying ${NAME}:${version}
</code>```

Body:
This is the bash version in case you run the task on Linux. The NAME is a custom variable which uses the pre-defined variable as value.

trigger_model_version=RELEASE_ARTIFACTS_${NAME^^}_BUILDNUMBER
export version=${!trigger_model_version}
echo Deploying ${NAME}:${version}


问:
Reading varbinary column from database and displaying it in a pop window
I am writing a file uploader using html tags.

my Data column stores data in binary format in a column of datatype varbinary(max).

I am able to successfully upload my file.

I am also making a grid which display the list of all my files with an icon next to it which when clicked will open a pop window and view me the file.

I have an onclick function

```<code>onclick = showDocument('" + dr["Id"] + "');
</code>```

which I am accessing in the code behind through page method. This is my JS function in the aspx:

```<code>function showDocument(_id) {
     PageMethods.ShowDocument();
}
</code>```

This function is pointing to my code behind function which is as follows.

```<code>[System.Web.Services.WebMethod]
public static void ShowDocument()
{
    byte[] bytes;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

    using (SqlConnection con = new SqlConnection(constr))
    {
        con.Open();

        using (SqlCommand com = new SqlCommand("SELECT Data FROM FileUploader2", con))
        {
             using (SqlDataReader reader = com.ExecuteReader())
             {
                 if (reader.Read())
                 {
                     bytes = (byte[])reader["Data"];
                 }
             }
         }
     }
}
</code>```

The above ShowDocument function is not really working. It just returns the bytes of my file and then nothing. Can someone edit the code above? Such that it reads varbinary(max) from my database and also display it in a popup window?

UPDATE:
Error:

答:
You cannot download from an Ajax call directly, you could try by removing the static keyword from ShowDocument and the WebMethod attribute and use a simple link from your HTML.

Regarding the downloading, you have the contents of the file in your byte array and the content type and original filename stored in your database so it seems you have all the ingredients you need to send the response back to the browser, something like this:

```<code>public void ShowDocument()
{
    string filename = string.Empty;
    string contentType = string.Empty;
    byte[] bytes = null;

    using (SqlConnection con = new SqlConnection(constr))
    {
        con.Open();

        using (SqlCommand com = new SqlCommand("SELECT * FROM FileUploader2", con))
        {
             using (SqlDataReader reader = com.ExecuteReader())
             {
                 if (reader.Read())
                 {
                     filename = (string)reader["Name"];
                     contentType = (string)reader["ContentType"];
                     bytes = (byte[])reader["Data"];
                 }
             }
         }
     }
    Response.ContentType = contentType;
    Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
    Response.OutputStream.Write(bytes, 0, bytes.Length);
    Response.Flush();
}
</code>```

Body:
I am writing a file uploader using html tags.

my Data column stores data in binary format in a column of datatype varbinary(max).

I am able to successfully upload my file.

I am also making a grid which display the list of all my files with an icon next to it which when clicked will open a pop window and view me the file.

I have an onclick function

onclick = showDocument('" + dr["Id"] + "');

which I am accessing in the code behind through page method. This is my JS function in the aspx:

function showDocument(_id) {
     PageMethods.ShowDocument();
}

This function is pointing to my code behind function which is as follows.

[System.Web.Services.WebMethod]
public static void ShowDocument()
{
    byte[] bytes;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

    using (SqlConnection con = new SqlConnection(constr))
    {
        con.Open();

        using (SqlCommand com = new SqlCommand("SELECT Data FROM FileUploader2", con))
        {
             using (SqlDataReader reader = com.ExecuteReader())
             {
                 if (reader.Read())
                 {
                     bytes = (byte[])reader["Data"];
                 }
             }
         }
     }
}

The above ShowDocument function is not really working. It just returns the bytes of my file and then nothing. Can someone edit the code above? Such that it reads varbinary(max) from my database and also display it in a popup window?

UPDATE:
Error:

Body:
You cannot download from an Ajax call directly, you could try by removing the static keyword from ShowDocument and the WebMethod attribute and use a simple link from your HTML.

Regarding the downloading, you have the contents of the file in your byte array and the content type and original filename stored in your database so it seems you have all the ingredients you need to send the response back to the browser, something like this:

public void ShowDocument()
{
    string filename = string.Empty;
    string contentType = string.Empty;
    byte[] bytes = null;

    using (SqlConnection con = new SqlConnection(constr))
    {
        con.Open();

        using (SqlCommand com = new SqlCommand("SELECT * FROM FileUploader2", con))
        {
             using (SqlDataReader reader = com.ExecuteReader())
             {
                 if (reader.Read())
                 {
                     filename = (string)reader["Name"];
                     contentType = (string)reader["ContentType"];
                     bytes = (byte[])reader["Data"];
                 }
             }
         }
     }
    Response.ContentType = contentType;
    Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
    Response.OutputStream.Write(bytes, 0, bytes.Length);
    Response.Flush();
}


问:
nextjs console.log doesn't work inside function return function
I'm playing around with nextjs
and I've trouble to debug a function like
this:

```<code>export const authInitialProps = isProtectedRoute => {
  console.log("mylog");// this works
  return ({ req, res }) => {
    console.log("inner my log", req); // this doesn't work
  };
};
</code>```

Using in a page

```<code>ProfilePage.getInitialProps = async () => {
  const auth = authInitialProps(true);
  if (!typeof auth === "function") {
    const user = await getUserProfile();
    return { user };
  }
  return { user: null };
};
</code>```

I never see "inner my log" both in chrome console
and in my console terminal.
What's the problem please?

答:
Try this It may work:

```<code>ProfilePage.getInitialProps = async () => {
  const auth = await authInitialProps(true); // await added
  if (!typeof auth === "function") {
    const user = await getUserProfile();
    return { user };
  }
  return { user: null };
};
</code>```

I think it should be async to not pass over it!

Body:
I'm playing around with nextjs
and I've trouble to debug a function like
this:

export const authInitialProps = isProtectedRoute => {
  console.log("mylog");// this works
  return ({ req, res }) => {
    console.log("inner my log", req); // this doesn't work
  };
};

Using in a page

ProfilePage.getInitialProps = async () => {
  const auth = authInitialProps(true);
  if (!typeof auth === "function") {
    const user = await getUserProfile();
    return { user };
  }
  return { user: null };
};

I never see "inner my log" both in chrome console
and in my console terminal.
What's the problem please?

Body:
Try this It may work:

ProfilePage.getInitialProps = async () => {
  const auth = await authInitialProps(true); // await added
  if (!typeof auth === "function") {
    const user = await getUserProfile();
    return { user };
  }
  return { user: null };
};

I think it should be async to not pass over it!


问:
How to invoke default template functional argument in C++?
I want my template function

```<code>template<class function>
int probe(function call = [] (int a, int b) { return a+b; })
{
    return call(10, 10);
}
</code>```

to be able to receive pointers to functions and invoke this function later. This excerpt is correct and the compiler does not complain on errors. Let's consider the such program

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

template<class function>
int probe(function call = [] (int a, int b) { return a+b; })
{
    return call(10, 10);
}

int main()
{
    std::cout << probe([](int a,int b){ return a-b;});
}
</code>```

The program outputs what I've expected: zero. However, I explicitly denoted for this call what a function I am passing - I mean about this lambda-expression in the parentheses [](int a,int b){ return a-b;}. That's fine until I pass nothing - the call std::cout << probe(); is incorrect, however I've expected that the function will use default function function call = [] (int a, int b) { return a+b; }. So, how do I call the function that instance of this function will use default lambda-expression in the declaration?

答:
Another way could be add a default for the template parameter.

Obviously must be a type compatible with the default value for call (decltype([] (int a, int b) { return a+b; }) doesn't works because every time you define a lambda is a different object).

```<code>template <typename function = std::function<int(int,int)>>
int probe (function call = [] (int a, int b) { return a+b; })
{
    return call(10, 10);
}
</code>```

Now

```<code>probe();
</code>```

works, if you remember to #include <functional>.

Otherwise you can define the default value for call before, save it in a constant so you can use decltype() (and no need to #include <functional>)

```<code>static const auto lam = [] (int a, int b) { return a+b; };

template <typename function = decltype(lam)>
int probe (function call = lam)
{
    return call(10, 10);
}
</code>```

Body:
I want my template function

template<class function>
int probe(function call = [] (int a, int b) { return a+b; })
{
    return call(10, 10);
}

to be able to receive pointers to functions and invoke this function later. This excerpt is correct and the compiler does not complain on errors. Let's consider the such program

#include <iostream>
#include <string>

template<class function>
int probe(function call = [] (int a, int b) { return a+b; })
{
    return call(10, 10);
}

int main()
{
    std::cout << probe([](int a,int b){ return a-b;});
}

The program outputs what I've expected: zero. However, I explicitly denoted for this call what a function I am passing - I mean about this lambda-expression in the parentheses [](int a,int b){ return a-b;}. That's fine until I pass nothing - the call std::cout << probe(); is incorrect, however I've expected that the function will use default function function call = [] (int a, int b) { return a+b; }. So, how do I call the function that instance of this function will use default lambda-expression in the declaration?

Body:
Another way could be add a default for the template parameter.

Obviously must be a type compatible with the default value for call (decltype([] (int a, int b) { return a+b; }) doesn't works because every time you define a lambda is a different object).

template <typename function = std::function<int(int,int)>>
int probe (function call = [] (int a, int b) { return a+b; })
{
    return call(10, 10);
}

Now

probe();

works, if you remember to #include <functional>.

Otherwise you can define the default value for call before, save it in a constant so you can use decltype() (and no need to #include <functional>)

static const auto lam = [] (int a, int b) { return a+b; };

template <typename function = decltype(lam)>
int probe (function call = lam)
{
    return call(10, 10);
}


问:
The behavior of unary & operator when met []
I've been reading C11 6.5.3.2 p3

The unary & operator yields the address of its operand. If the operand has type “type”, the result has
  type “pointer to type”. If the operand is the result of a unary * operator, neither that operator nor
  the & operator is evaluated and the result is as if both were omitted, except that the constraints on
  the operators still apply and the result is not an lvalue. Similarly, if the operand is the result of a []
  operator, neither the & operator nor the unary * that is implied by the [] is evaluated and the result
  is as if the & operator were removed and the [] operator were changed to a+ operator. Otherwise,
  the result is a pointer to the object or function designated by its operand.

I can't understand most of this paragraph although reading it repeatedly.

My problem parts are * that is implied by the [], []operator were changed to a + operator, function designated by this operand. This paragraph is talking about & but why does * appear and term "function designated" appear after saying []. And [] operator were changed to a + operator seems trying to say the definition of array : E1[E2] = *((E1) + (E2)) What does these lines mean? I need some help.

答:
If the operand is the result of a unary * operator, neither that
  operator nor the & operator is evaluated and the result is as if both
  were omitted, except that the constraints on the operators still apply
  and the result is not an lvalue.

Unary & applied to the result of unary *, cancels the * and converts the operand of the original * to an r-value:

```<code>#include <assert.h>
int main()
{
    int *p=&(int){42};
    assert(&*p == p); //the value (42) is not fetched from the target
    #if 0
        &*p = &(int){1000}; //not OK; & cancels the * but converts p to an r-value (can't be on the left-hand side of an assignment)
    #endif
    p = &(int){1000}; //ok; p is an l-value (can be on the left hand side of an assignment)
    //(more accurately: can have its address taken)
}
</code>```

Now since a pointerOrArray[index] expression is defined (6.5.2.1p2) as *(pointerOrArray+index) (the result of a unary *, except the * is hidden), you can apply the same rule to it: &pointerOrArray[index] <=> (pointerOrArry+Index). That's what your first quoted sentence says.

The last sentence you quoted can be (within the context of 6.5.3.2p3) interpreted as:

Otherwise (if unary & isn't combined with * or []), the result (of unary &) is a pointer to the object (&object) or function (&function) designated by its operand (an object or a function).

Body:
If the operand is the result of a unary * operator, neither that
  operator nor the & operator is evaluated and the result is as if both
  were omitted, except that the constraints on the operators still apply
  and the result is not an lvalue.

Unary & applied to the result of unary *, cancels the * and converts the operand of the original * to an r-value:

#include <assert.h>
int main()
{
    int *p=&(int){42};
    assert(&*p == p); //the value (42) is not fetched from the target
    #if 0
        &*p = &(int){1000}; //not OK; & cancels the * but converts p to an r-value (can't be on the left-hand side of an assignment)
    #endif
    p = &(int){1000}; //ok; p is an l-value (can be on the left hand side of an assignment)
    //(more accurately: can have its address taken)
}

Now since a pointerOrArray[index] expression is defined (6.5.2.1p2) as *(pointerOrArray+index) (the result of a unary *, except the * is hidden), you can apply the same rule to it: &pointerOrArray[index] <=> (pointerOrArry+Index). That's what your first quoted sentence says.

The last sentence you quoted can be (within the context of 6.5.3.2p3) interpreted as:

Otherwise (if unary & isn't combined with * or []), the result (of unary &) is a pointer to the object (&object) or function (&function) designated by its operand (an object or a function).


问:
How to fix Error: EEXIST: file already exists, mkdir 'C:\Users\Phantom' when create react app[CLOSE]
I'm installing react and want to create my first project on react but I'm got something problem while install it. how to fix it ?

```<code>Error: EEXIST: file already exists, mkdir 'C:\Users\Phantom'
TypeError: Cannot read property 'loaded' of undefined
    at exit (F:\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27)
    at errorHandler (F:\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3)
    at F:\nodejs\node_modules\npm\bin\npm-cli.js:78:20
    at cb (F:\nodejs\node_modules\npm\lib\npm.js:225:22)
    at F:\nodejs\node_modules\npm\lib\npm.js:263:24
    at F:\nodejs\node_modules\npm\lib\config\core.js:83:7
    at Array.forEach (<anonymous>)
    at F:\nodejs\node_modules\npm\lib\config\core.js:82:13
    at f (F:\nodejs\node_modules\npm\node_modules\once\once.js:25:25)
    at afterExtras (F:\nodejs\node_modules\npm\lib\config\core.js:173:20)
F:\nodejs\node_modules\npm\lib\utils\error-handler.js:98
  var doExit = npm.config.loaded ? npm.config.get('_exit') : true
                          ^

TypeError: Cannot read property 'loaded' of undefined
    at exit (F:\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27)
    at process.errorHandler (F:\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3)
    at process.emit (events.js:197:13)
    at process._fatalException (internal/process/execution.js:123:25)
Install for create-react-app@latest failed with code 7
</code>```

that's the error said

答:
I executed the following steps:

npm uninstall -g create-react-app

npm install -g create-react-app

npx create-react-app the-name-of-your-app

Body:
I'm installing react and want to create my first project on react but I'm got something problem while install it. how to fix it ?

Error: EEXIST: file already exists, mkdir 'C:\Users\Phantom'
TypeError: Cannot read property 'loaded' of undefined
    at exit (F:\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27)
    at errorHandler (F:\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3)
    at F:\nodejs\node_modules\npm\bin\npm-cli.js:78:20
    at cb (F:\nodejs\node_modules\npm\lib\npm.js:225:22)
    at F:\nodejs\node_modules\npm\lib\npm.js:263:24
    at F:\nodejs\node_modules\npm\lib\config\core.js:83:7
    at Array.forEach (<anonymous>)
    at F:\nodejs\node_modules\npm\lib\config\core.js:82:13
    at f (F:\nodejs\node_modules\npm\node_modules\once\once.js:25:25)
    at afterExtras (F:\nodejs\node_modules\npm\lib\config\core.js:173:20)
F:\nodejs\node_modules\npm\lib\utils\error-handler.js:98
  var doExit = npm.config.loaded ? npm.config.get('_exit') : true
                          ^

TypeError: Cannot read property 'loaded' of undefined
    at exit (F:\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27)
    at process.errorHandler (F:\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3)
    at process.emit (events.js:197:13)
    at process._fatalException (internal/process/execution.js:123:25)
Install for create-react-app@latest failed with code 7

that's the error said


问:
Remove elements from array with another array containing duplicates javascript
I have 2 arrays, I want to delete the elements from first array with the second ones just once conserving the other duplicates that might be:

```<code>array1 = [1,1,1,1,2,2,2,2];
array2 = [1,1,2];

//resultingArray = [1,1,2,2,2];
</code>```

It seems that all the answers I got are about removing duplicates while searching for this..

I'm wondering if there's a way to do this with filter, but it only seems to filter all the entries

```<code>resultingArray = array1.filter(function(el){
   return array2.indexOf(el) === -1;
});

//resultingArray = [];
</code>```

Another way that I could think of is removing each one of the array elements one by one like this

```<code>for( var i = 0; i < arr.length; i++){
   if ( arr[i] === Number) {
     arr.splice(i, 1);
     i = arr.length;
};
</code>```

But it doesn't seem to be a great way to do this?

And again the difference between those arrays will remove all the duplicated elements

Would appreciate to know the best method for this or directions to a duplicated posts that i couldn't find!!

答:
To achieve this you can loop through array2 removing the first matching item matching the current value in array1. Something like this:

let array1 = [1,1,1,1,2,2,2,2];
let array2 = [1,1,2];

array2.forEach(i => array1.splice(array1.indexOf(i), 1));

console.log(array1);```

Body:
I have 2 arrays, I want to delete the elements from first array with the second ones just once conserving the other duplicates that might be:

array1 = [1,1,1,1,2,2,2,2];
array2 = [1,1,2];

//resultingArray = [1,1,2,2,2];

It seems that all the answers I got are about removing duplicates while searching for this..

I'm wondering if there's a way to do this with filter, but it only seems to filter all the entries

resultingArray = array1.filter(function(el){
   return array2.indexOf(el) === -1;
});

//resultingArray = [];

Another way that I could think of is removing each one of the array elements one by one like this

for( var i = 0; i < arr.length; i++){
   if ( arr[i] === Number) {
     arr.splice(i, 1);
     i = arr.length;
};

But it doesn't seem to be a great way to do this?

And again the difference between those arrays will remove all the duplicated elements

Would appreciate to know the best method for this or directions to a duplicated posts that i couldn't find!!


问:
Syntax to use parameters in Body section of HTTP Request Sampler in JMeter, using Rest API POST request with body and input from CSV file
I'm using JMeter to test a microservice and I need to use a parameter dynamically with a different value in each request. Also, the parameter is a part of a query that contains other constant values as well.

I defined user variables in the JMeter user.properties file (in JMeter bin folder):

JMeter -- bin/user.properties

```<code># Parameters to use in JMeter
ES_HOST=127.0.0.1
ES_PORT=9200
ES_INDEX=segments
ES_TYPE=_doc
THREAD=5
CSVDATA_ROOT=C:/devtools/apache-jmeter-5.2.1/csv_data
</code>```

Of course, I have User-Defined Variables:

And how my Test Plan is defined in JMeter

As you can see in the following screenshot of View Result Tree the parameter agentName I defined and shown in the HTTP Request (above) is working.

I want to define it in the body of the HTTP Request, to replace the hardcoded "John Doe" with a parameters that have a different value in each request.

```<code>"query":"SearchStartTime=2020-01-01 00:00:00.000TO2020-01-31 23:59:59.999&AgentName=John Doe"}
</code>```

How can I do that?
I need a way to add a parameter to an existing string

I've already tried Using Apache JMeter to Test Elasticsearch (or any REST API) and In Jmeter, What would be syntax of parameters in Body Data section of HTTP Request Sampler, for Rest APIs and input should be generated dynamically also doesn't solve my problem.

答:
Use same syntax as HTTP request - ${agentname} for getting variable value:

```<code>"query":"SearchStartTime=2020-01-01 00:00:00.000TO2020-01-31 23:59:59.999&AgentName=${agentname}"
</code>```

Body:
I'm using JMeter to test a microservice and I need to use a parameter dynamically with a different value in each request. Also, the parameter is a part of a query that contains other constant values as well.

I defined user variables in the JMeter user.properties file (in JMeter bin folder):

JMeter -- bin/user.properties

# Parameters to use in JMeter
ES_HOST=127.0.0.1
ES_PORT=9200
ES_INDEX=segments
ES_TYPE=_doc
THREAD=5
CSVDATA_ROOT=C:/devtools/apache-jmeter-5.2.1/csv_data

Of course, I have User-Defined Variables:

And how my Test Plan is defined in JMeter

As you can see in the following screenshot of View Result Tree the parameter agentName I defined and shown in the HTTP Request (above) is working.

I want to define it in the body of the HTTP Request, to replace the hardcoded "John Doe" with a parameters that have a different value in each request.

"query":"SearchStartTime=2020-01-01 00:00:00.000TO2020-01-31 23:59:59.999&AgentName=John Doe"}

How can I do that?
I need a way to add a parameter to an existing string

I've already tried Using Apache JMeter to Test Elasticsearch (or any REST API) and In Jmeter, What would be syntax of parameters in Body Data section of HTTP Request Sampler, for Rest APIs and input should be generated dynamically also doesn't solve my problem.

Body:
Use same syntax as HTTP request - ${agentname} for getting variable value:

"query":"SearchStartTime=2020-01-01 00:00:00.000TO2020-01-31 23:59:59.999&AgentName=${agentname}"


问:
How i can convert json into xml without the elements index numbers?
I am trying to implement the following code that is allowing me to convert json to xml. But i don't want to get output in the form of element index such as starting from <0> and closing tag as  similary second node starting from <1> and ending as . I have big xml big json code that is why it is creating index tags such as <0>  and so on. I want to display my xml without these index tags. The code is as below:-

```<code>function convertJSon2XML()
{
$("#xmlArea").val(x2js.json2xml_str($.parseJSON($("#jsonArea").val())));
}

$("#xmlArea").val("<root><child><textNode>First & Child</textNode></child><child><textNode>Second
Child</textNode></child><testAttrs attr1='attr1Value'/></root>");

convertJSon2XML();

$("#convertToXmlBtn").click(convertJSon2XML);
</code>```

For reference i am also attaching output that what is meant by index tag. At the very start there is tag <0> and this is going so on. such as <1> then <2> and so on. So due to these index tags such as <0> , i am unable to read my xml in browser. I want to convert json to xml without these index tags such as <0> and so on. Please help.

Output:- <img src="https://i.stack.imgur.com/hzhqI.png" alt="This is how the output is displaying. Starting from <0> tag.">

答:
It may be converted to this JSON.</p>

```<code>{
  "root": {
    "child": [
      {
        "textNode": "First & Child"
      },
      {
       "textNode": "Second \nChild"
      }
    ],
    "testAttrs": {
      "-attr1": "attr1Value",
      "-self-closing": "true"
    }
  },
  "#omit-xml-declaration": "yes"
}
</code>```

Body:
I am trying to implement the following code that is allowing me to convert json to xml. But i don't want to get output in the form of element index such as starting from <0> and closing tag as  similary second node starting from <1> and ending as . I have big xml big json code that is why it is creating index tags such as <0>  and so on. I want to display my xml without these index tags. The code is as below:-

function convertJSon2XML()
{
$("#xmlArea").val(x2js.json2xml_str($.parseJSON($("#jsonArea").val())));
}

$("#xmlArea").val("<root><child><textNode>First & Child</textNode></child><child><textNode>Second
Child</textNode></child><testAttrs attr1='attr1Value'/></root>");

convertJSon2XML();

$("#convertToXmlBtn").click(convertJSon2XML);

For reference i am also attaching output that what is meant by index tag. At the very start there is tag <0> and this is going so on. such as <1> then <2> and so on. So due to these index tags such as <0> , i am unable to read my xml in browser. I want to convert json to xml without these index tags such as <0> and so on. Please help.

Output:- <img src="https://i.stack.imgur.com/hzhqI.png" alt="This is how the output is displaying. Starting from <0> tag.">

Body:
It may be converted to this JSON.

{
  "root": {
    "child": [
      {
        "textNode": "First & Child"
      },
      {
       "textNode": "Second \nChild"
      }
    ],
    "testAttrs": {
      "-attr1": "attr1Value",
      "-self-closing": "true"
    }
  },
  "#omit-xml-declaration": "yes"
}


问:
How View Custom Type Set By ACF In My WordPress Controller
I Am Programmer in Windows Application
I Use This Library In My Project :
https://github.com/wp-net/WordPressPCL/wiki/Create-post-with-custom-type
In Above Link Description : This Library Supported Of AFC .
But Programmer Need Know AFC : Where And What set in Rest Api
Main Problem is : I Used above Library And Need what post data until make new post in post category define by me in WordPress .
Please See ScreenShot Of ACF Fields in WordPress :
https://www.mediafire.com/convkey/955f/zvqv16i4u852qntzg.jpg
https://www.mediafire.com/convkey/4b0d/vn4bo4ezm8kgnoazg.jpg

My Question Is : Repeater Field which i Mark in second screenshot how determine and which set for two or three or five and etc values repeat
Thx My Friends

答:
Hope I noticed your problem

In this image you can see 2 Rectangle:

blue Rectangle is : when you have a repeater field, every subfield repeat

and

in red Rectangle you can set howmany times user can repeat it

open image by this link : a link


问:
Anaconda Installed but Cannot Launch Navigator
Anaconda (listed as "Python 3.6.0 (Anaconda 4.3.1 64 bit)" ) is in my programs and features list, but there is seeming no Anaconda Navigator desktop app, as their seems to be no icon on my desktop and I am unable to search for it through "Start". Could this be because I have the 32-bit version of Anaconda downloaded and I have a 64-bit OS (I thought I should do this because Python on my computer was 64-bit) or because I downloaded Anaconda under "users" instead of Desktop. I also downloaded Anaconda twice, if that could be causing some of the problem. I have a Windows 10 laptop, if that is any help.

答:
activate the virtual env with command:

```<code> conda activate base
</code>```

run anacond anavigator

```<code> anaconda-navigator
</code>```

Body:
activate the virtual env with command:

 conda activate base

run anacond anavigator

 anaconda-navigator


问:
/bin/sh: pushd: not found
I am doing the following inside a make file

```<code>pushd %dir_name%
</code>```

and i get the following error

```<code>/bin/sh : pushd : not found
</code>```

Can someone please tell me why this error is showing up ?
I checked my $PATH variable and it contains /bin so I don't think that is causing a problem.

答:
add

SHELL := /bin/bash

at the top of your makefile
I have found it on another question How can I use Bash syntax in Makefile targets?

Title: /bin/sh: pushd: not found

Body:
I am doing the following inside a make file

pushd %dir_name%

and i get the following error

/bin/sh : pushd : not found

Can someone please tell me why this error is showing up ?
I checked my $PATH variable and it contains /bin so I don't think that is causing a problem.


问:
Avoid nested subscription in RXJS
I have the following code:

```<code>someService.subscribeToChanges().subscribe(value => {
    const newValue = someArray.find(val => val.id === value.id)
    if (newValue) {
       if (value.status === 'someStatus') {
          someArray.findIndex((a) => a.id === value.id)
          someArray.splice(index, 1);
       } else {
          newValue.status = value.status;
       }
    } else {
        if (value.someProp === 'abc') {
          someService.doSomeAsyncStuff().subscribe(data => {
            someService.handleData(data);
          });
        }
    }
 });
</code>```

I would like to keep the same logic while avoiding the second subscribe.

This is the code that I tried

```<code>sub$ = someService.subscribeToChanges().pipe(switchMap(value => {
  const newValue = someArray.find(val => val.id === value.id)
  if (newValue) {
       if (value.status === 'someStatus') {
          someArray.findIndex((a) => a.id === value.id)
          someArray.splice(index, 1);
       } else {
          newValue.status = value.status;
       }
  } else {
    return iif(() => value.someProp === 'ABC', someService.doSomeAsyncStuff);
  }
}));

sub$.subscribe(data => someService.handleData(data))
</code>```

This works if the iif condition is true, but if it is false, it just stops the whole stream, while I want it to keep streaming.

答:
You can split them into three conditions </p>

```<code>sub$ = someService.subscribeToChanges().pipe(switchMap(value => {
 const newValue = someArray.find(val => val.id === value.id)
 if (newValue) {
   if (value.status === 'someStatus') {
      someArray.findIndex((a) => a.id === value.id)
      someArray.splice(index, 1);
   } else {
      newValue.status = value.status;
   }
 return of(value);
 }

    if(value.someProp === 'ABC')
      return someService.doSomeStuff()

    return of(value)
  })
)
</code>```

Title: Avoid nested subscription in RXJS

Body:
I have the following code:

someService.subscribeToChanges().subscribe(value => {
    const newValue = someArray.find(val => val.id === value.id)
    if (newValue) {
       if (value.status === 'someStatus') {
          someArray.findIndex((a) => a.id === value.id)
          someArray.splice(index, 1);
       } else {
          newValue.status = value.status;
       }
    } else {
        if (value.someProp === 'abc') {
          someService.doSomeAsyncStuff().subscribe(data => {
            someService.handleData(data);
          });
        }
    }
 });

I would like to keep the same logic while avoiding the second subscribe.

This is the code that I tried

sub$ = someService.subscribeToChanges().pipe(switchMap(value => {
  const newValue = someArray.find(val => val.id === value.id)
  if (newValue) {
       if (value.status === 'someStatus') {
          someArray.findIndex((a) => a.id === value.id)
          someArray.splice(index, 1);
       } else {
          newValue.status = value.status;
       }
  } else {
    return iif(() => value.someProp === 'ABC', someService.doSomeAsyncStuff);
  }
}));

sub$.subscribe(data => someService.handleData(data))

This works if the iif condition is true, but if it is false, it just stops the whole stream, while I want it to keep streaming.

Body:
You can split them into three conditions

sub$ = someService.subscribeToChanges().pipe(switchMap(value => {
 const newValue = someArray.find(val => val.id === value.id)
 if (newValue) {
   if (value.status === 'someStatus') {
      someArray.findIndex((a) => a.id === value.id)
      someArray.splice(index, 1);
   } else {
      newValue.status = value.status;
   }
 return of(value);
 }

    if(value.someProp === 'ABC')
      return someService.doSomeStuff()

    return of(value)
  })
)


问:
How to resolve Ripple test server connection error?
I am persistently getting following error on connecting to test server using RippleAPI for Javascript:

```<code>[ConnectionError(Error: connect() timed out after 2000 ms. If your internet connection is working, the rippled server may be blocked or inaccessible.)]
</code>```

However, if I try to get balance from curl, it works:

```<code>curl 'https://testnet.data.api.ripple.com/v2/accounts/rwAVpkGNU9Shn63EpFq7ju1tr89SsSBwHz/balances?currency=XRP'
</code>```

Code snippet below:

```<code>'use strict';
const RippleAPI = require('ripple-lib').RippleAPI;

const api = new RippleAPI({
  server: 'wss://s.altnet.rippletest.net:51233' // Public rippled server
});
api.connect().then(() => {
  /* begin custom code ------------------------------------ */
  const myAddress = 'rwAVpkGNU9Shn63EpFq7ju1tr89SsSBwHz';

  console.log('getting account info for', myAddress);
  return api.getAccountInfo(myAddress);

}).then(info => {
  console.log(info);
  console.log('getAccountInfo done');

  /* end custom code -------------------------------------- */
}).then(() => {
  return api.disconnect();
}).then(() => {
  console.log('done and disconnected.');
}).catch(console.error);
</code>```

答:
timeout param doesn't seem to work even if I suggest;

use:
api.connection._config.connectionTimeout = 3e4;

Body:
I am persistently getting following error on connecting to test server using RippleAPI for Javascript:

[ConnectionError(Error: connect() timed out after 2000 ms. If your internet connection is working, the rippled server may be blocked or inaccessible.)]

However, if I try to get balance from curl, it works:

curl 'https://testnet.data.api.ripple.com/v2/accounts/rwAVpkGNU9Shn63EpFq7ju1tr89SsSBwHz/balances?currency=XRP'

Code snippet below:

'use strict';
const RippleAPI = require('ripple-lib').RippleAPI;

const api = new RippleAPI({
  server: 'wss://s.altnet.rippletest.net:51233' // Public rippled server
});
api.connect().then(() => {
  /* begin custom code ------------------------------------ */
  const myAddress = 'rwAVpkGNU9Shn63EpFq7ju1tr89SsSBwHz';

  console.log('getting account info for', myAddress);
  return api.getAccountInfo(myAddress);

}).then(info => {
  console.log(info);
  console.log('getAccountInfo done');

  /* end custom code -------------------------------------- */
}).then(() => {
  return api.disconnect();
}).then(() => {
  console.log('done and disconnected.');
}).catch(console.error);


问:
Undefined function with extern "c" and assembly
Hey so I'm getting an undefined function error when I'm trying to compile my code and I don't know why.

Here are my files:
Api.h

```<code>extern "C" NTSTATUS NtWriteVirtualMem(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, ULONG NumberOfBytesToWrite, PULONG NumberOfBytesWritten);
</code>```

API_ASM.asm

```<code>.code
_NtWriteVirtualMem:
    mov r10, rcx
    mov eax, 3Ah
    syscall
    ret

end
</code>```

Both of them compile correctly but I get an error because NtWriteVirtualMem is defined but I defined it in my asm?

EDIT 1.

So I changed my code to:

```<code>PUBLIC NtWriteVirtualMem

_TEXT SEGMENT
NtWriteVirtualMem PROC
    mov r10, rcx
    mov eax, 3Ah
    syscall
    ret
    NtWriteVirtualMem ENDP
_TEXT ENDS
END
</code>```

The program now compiles but the write doesn't work. I've tested it to see if writeprocessmemory works and it does.   Also, my IDE shows that NtWriteVirtualMem is still undefined when I hover over the name in the C source.

EDIT 2.

Also, the NTSTATUS return code for the operation is a negative max integer.

答:
Windows x64 doesn't use a leading underscore _ in asm symbol names.  Your asm label name should just be NtWriteVirtualMem, matching the extern "C" function name.

See Agner Fog's calling convention guide, for example. http://www.agner.org/optimize/calling_conventions.pdf

(Also make sure you tell the assembler to export it, if necessary.  Like with NASM you'd use global to modify that label declaration.  IDK if MASM needs proc / endp or if a label can work.)

Your fixed version links properly, and you confirmed that execution goes through the syscall instruction.  Probably you're passing the wrong args, or passing them the wrong way, or using the wrong call number.

The syscall ABI is undocumented and unsupported on Windows, and can change between kernel versions.  https://j00ru.vexillium.org/syscalls/nt/64/ says that the call number for NtWriteVirtualMem is 3Ah on all Windows 10 versions, but I don't know if you're passing other args correctly.  On earlier verisons of Windows, 0x3a is a different system call.

I'll leave this part of the question for someone who uses Windows and knows what that system call does.

Body:
Hey so I'm getting an undefined function error when I'm trying to compile my code and I don't know why.

Here are my files:
Api.h

extern "C" NTSTATUS NtWriteVirtualMem(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, ULONG NumberOfBytesToWrite, PULONG NumberOfBytesWritten);

API_ASM.asm

.code
_NtWriteVirtualMem:
    mov r10, rcx
    mov eax, 3Ah
    syscall
    ret

end

Both of them compile correctly but I get an error because NtWriteVirtualMem is defined but I defined it in my asm?

EDIT 1.

So I changed my code to:

PUBLIC NtWriteVirtualMem

_TEXT SEGMENT
NtWriteVirtualMem PROC
    mov r10, rcx
    mov eax, 3Ah
    syscall
    ret
    NtWriteVirtualMem ENDP
_TEXT ENDS
END

The program now compiles but the write doesn't work. I've tested it to see if writeprocessmemory works and it does.   Also, my IDE shows that NtWriteVirtualMem is still undefined when I hover over the name in the C source.

EDIT 2.

Also, the NTSTATUS return code for the operation is a negative max integer.


问:
Huge performance spike with EventSystem.Update() just on the first screen touch on Android
On my 2D platformer for android I have a huge performance spike when I touch the screen for the first time. After that a small lag occures once and than the game is running smoothly. No error messages.

I already tried to asign graphic raycaster just to certain buttons which helped a bit. But the small lag is still present. In the profiler the performance spike is under the scripts and is marked as the EventSystem.Update(). here is the screenshot from the

On button click I use the following code as the UI Manager:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine.UI;
using UnityEngine;

public class UIManager : MonoBehaviour
{
    public GameObject menu;
    public GameObject options;
    public GameObject pause;
    public Animator animatorMain;
    public Animator animatorOptions;
    public Animator animatorPause;
    public bool hide;
    public bool show;

    public void UIDefaults()
    {
        menu = GameObject.Find("MainMenu");
        options = GameObject.Find("optionsMenu");
        pause = GameObject.Find("pauseMenu");

        animatorMain = menu.GetComponent<Animator>();
        animatorOptions = options.GetComponent<Animator>();
        animatorPause = pause.GetComponent<Animator>();

        hide = true;
        show = false;
    }

    /* --- EXIT APPLICATION --- */
    public void Exit()
    {
        Application.Quit();
    }
    /* --- EXIT APPLICATION --- */

    /* --- MAIN MENU --- */
    public void OpenMainMenu()
    {
        UIDefaults();
        animatorOptions.SetBool("OptionsBool", hide);
        StartCoroutine("WaitMainMenu");
    }

    // line 28. Coroutine
    IEnumerator WaitMainMenu()
    {
        // wait for Options menu animation to end.
        yield return new WaitForSeconds(1.15f);

        SetMainMenuActive();
    }

    // line 35. function to Start the Main menu animation.
    void SetMainMenuActive()
    {
        menu.GetComponent<Canvas>().enabled = true;
        options.GetComponent<Canvas>().enabled = false;
        pause.GetComponent<Canvas>().enabled = false;

        animatorMain.SetBool("MainBool", show);
        animatorOptions.SetBool("StartOptions", show);
        animatorOptions.SetBool("OptionsBool", show);
    }
    /* --- MAIN MENU --- */

    /* --- OPTIONS MENU --- */
    public void OpenSettings()
    {
        UIDefaults();
        animatorMain.SetBool("MainBool", hide);
        StartCoroutine("WaitOptions");
    }

    // line 66. Coroutine
    IEnumerator WaitOptions()
    {
        // wait for Main menu animation to end.
        yield return new WaitForSeconds(1.15f);

        SetOptionsActive();
    }

    // line 73. function to Start the Options menu animation.
    void SetOptionsActive()
    {
        menu.GetComponent<Canvas>().enabled = false;
        options.GetComponent<Canvas>().enabled = true;
        pause.GetComponent<Canvas>().enabled = false;

        animatorOptions.SetBool("StartOptions", hide);
    }
    /* --- OPTIONS MENU --- */
}
</code>```

I wish to get rid of the initial one time lag when I touch the screen for the first time.

答:
I had a similar issue and for me, it was a call to DateTime.Now somewhere deep in the methods that was slow!
take a look at this:
https://issuetracker.unity3d.com/issues/ios-il2cpp-system-dot-datetime-dot-now-is-slow-on-the-first-run
I replaced the code with Time.time and it's fixed now. </p>

Body:
On my 2D platformer for android I have a huge performance spike when I touch the screen for the first time. After that a small lag occures once and than the game is running smoothly. No error messages.

I already tried to asign graphic raycaster just to certain buttons which helped a bit. But the small lag is still present. In the profiler the performance spike is under the scripts and is marked as the EventSystem.Update(). here is the screenshot from the

On button click I use the following code as the UI Manager:

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine.UI;
using UnityEngine;

public class UIManager : MonoBehaviour
{
    public GameObject menu;
    public GameObject options;
    public GameObject pause;
    public Animator animatorMain;
    public Animator animatorOptions;
    public Animator animatorPause;
    public bool hide;
    public bool show;

    public void UIDefaults()
    {
        menu = GameObject.Find("MainMenu");
        options = GameObject.Find("optionsMenu");
        pause = GameObject.Find("pauseMenu");

        animatorMain = menu.GetComponent<Animator>();
        animatorOptions = options.GetComponent<Animator>();
        animatorPause = pause.GetComponent<Animator>();

        hide = true;
        show = false;
    }

    /* --- EXIT APPLICATION --- */
    public void Exit()
    {
        Application.Quit();
    }
    /* --- EXIT APPLICATION --- */

    /* --- MAIN MENU --- */
    public void OpenMainMenu()
    {
        UIDefaults();
        animatorOptions.SetBool("OptionsBool", hide);
        StartCoroutine("WaitMainMenu");
    }

    // line 28. Coroutine
    IEnumerator WaitMainMenu()
    {
        // wait for Options menu animation to end.
        yield return new WaitForSeconds(1.15f);

        SetMainMenuActive();
    }

    // line 35. function to Start the Main menu animation.
    void SetMainMenuActive()
    {
        menu.GetComponent<Canvas>().enabled = true;
        options.GetComponent<Canvas>().enabled = false;
        pause.GetComponent<Canvas>().enabled = false;

        animatorMain.SetBool("MainBool", show);
        animatorOptions.SetBool("StartOptions", show);
        animatorOptions.SetBool("OptionsBool", show);
    }
    /* --- MAIN MENU --- */

    /* --- OPTIONS MENU --- */
    public void OpenSettings()
    {
        UIDefaults();
        animatorMain.SetBool("MainBool", hide);
        StartCoroutine("WaitOptions");
    }

    // line 66. Coroutine
    IEnumerator WaitOptions()
    {
        // wait for Main menu animation to end.
        yield return new WaitForSeconds(1.15f);

        SetOptionsActive();
    }

    // line 73. function to Start the Options menu animation.
    void SetOptionsActive()
    {
        menu.GetComponent<Canvas>().enabled = false;
        options.GetComponent<Canvas>().enabled = true;
        pause.GetComponent<Canvas>().enabled = false;

        animatorOptions.SetBool("StartOptions", hide);
    }
    /* --- OPTIONS MENU --- */
}

I wish to get rid of the initial one time lag when I touch the screen for the first time.


问:
Forge Viewer as Extension for another viewer
We have a two forge viewers in one div. We has initialize those viewers same time and showing different models.
Is it possible to initialize Autodesk Forge viewer as extension for another viewer and show in that viewers different models? </p>

答:
There is no official extension for showing one Forge Viewer inside another, but implementing this is possible. You could reuse one of the UI components of the viewer (for example, DockingPanel, also explained in this tutorial), and host the second viewer in it.

Here's how such an extension might look like:

```<code>class MyExtension extends Autodesk.Viewing.Extension {
    constructor(viewer, options) {
        super(viewer, options);
        this._group = null;
        this._button = null;
        this._panel = null;
    }

    load() {
        return true;
    }

    unload() {
        return true;
    }

    onToolbarCreated() {
        this._group = new Autodesk.Viewing.UI.ControlGroup('allMyAwesomeExtensionsToolbar');
        this._button = new Autodesk.Viewing.UI.Button('MyExtensionButton');
        this._button.setToolTip('My Extension Button');
        this._group.addControl(this._button);
        this._panel = new MyPanel(this.viewer, this.viewer.container, 'MyPanel', 'My Panel Title');
        this._button.onClick = (ev) => {
            this._panel.setVisible(true);
        };
        this.viewer.toolbar.addControl(this._group);
    }
}

class MyPanel extends Autodesk.Viewing.UI.DockingPanel {
    constructor(viewer, container, id, title, options) {
        super(container, id, title, options);
        this.viewer = viewer;
        this.secondViewer = null;
        this.container.style.width = '640px';
        this.container.style.height = '480px';
        this.container.style.left = '1em';
        this.container.style.top = '1em';
    }

    setVisible(show) {
        super.setVisible(show);
        if (show && !this.secondViewer) {
            this.secondViewer = new Autodesk.Viewing.GuiViewer3D(this.container);
            this.secondViewer.start();
            Autodesk.Viewing.Document.load(
                'urn:<your model urn>',
                this.onDocumentLoadSuccess.bind(this),
                this.onDocumentLoadFailure.bind(this)
            );
        }
    }

    onDocumentLoadSuccess(doc) {
        const viewables = doc.getRoot().getDefaultGeometry();
        this.secondViewer.loadDocumentNode(doc, viewables);
    }

    onDocumentLoadFailure(viewerErrorCode) {
        console.error('onDocumentLoadFailure() - errorCode:' + viewerErrorCode);
    }
}

Autodesk.Viewing.theExtensionManager.registerExtension('MyExtension', MyExtension);
</code>```

Body:
There is no official extension for showing one Forge Viewer inside another, but implementing this is possible. You could reuse one of the UI components of the viewer (for example, DockingPanel, also explained in this tutorial), and host the second viewer in it.

Here's how such an extension might look like:

class MyExtension extends Autodesk.Viewing.Extension {
    constructor(viewer, options) {
        super(viewer, options);
        this._group = null;
        this._button = null;
        this._panel = null;
    }

    load() {
        return true;
    }

    unload() {
        return true;
    }

    onToolbarCreated() {
        this._group = new Autodesk.Viewing.UI.ControlGroup('allMyAwesomeExtensionsToolbar');
        this._button = new Autodesk.Viewing.UI.Button('MyExtensionButton');
        this._button.setToolTip('My Extension Button');
        this._group.addControl(this._button);
        this._panel = new MyPanel(this.viewer, this.viewer.container, 'MyPanel', 'My Panel Title');
        this._button.onClick = (ev) => {
            this._panel.setVisible(true);
        };
        this.viewer.toolbar.addControl(this._group);
    }
}

class MyPanel extends Autodesk.Viewing.UI.DockingPanel {
    constructor(viewer, container, id, title, options) {
        super(container, id, title, options);
        this.viewer = viewer;
        this.secondViewer = null;
        this.container.style.width = '640px';
        this.container.style.height = '480px';
        this.container.style.left = '1em';
        this.container.style.top = '1em';
    }

    setVisible(show) {
        super.setVisible(show);
        if (show && !this.secondViewer) {
            this.secondViewer = new Autodesk.Viewing.GuiViewer3D(this.container);
            this.secondViewer.start();
            Autodesk.Viewing.Document.load(
                'urn:<your model urn>',
                this.onDocumentLoadSuccess.bind(this),
                this.onDocumentLoadFailure.bind(this)
            );
        }
    }

    onDocumentLoadSuccess(doc) {
        const viewables = doc.getRoot().getDefaultGeometry();
        this.secondViewer.loadDocumentNode(doc, viewables);
    }

    onDocumentLoadFailure(viewerErrorCode) {
        console.error('onDocumentLoadFailure() - errorCode:' + viewerErrorCode);
    }
}

Autodesk.Viewing.theExtensionManager.registerExtension('MyExtension', MyExtension);


问:
How would I bulk load the data into a SQL Server table which is referenced by the foreign keys but the data is plain in Excel format?
I have a table BasicDetails with these columns:

```<code>ID   Name   Father    Country_ID   City_ID   ContactDetails_ID
</code>```

But client has shared Excel sheets with me and I should be loading that into the table. The sheet has the following columns

```<code>ID   Name   Father   CountryName   CountryCode   CityName   CityCode   ContactNo   CellNo   Address
</code>```

Now, in my database CountryName, CountryCode, CityName these are stored in a separate table named Countries.

CityName  CityCode are saved in a separate table Cities.

ContactNo   CellNo   Address are stored in a separate table ContactDetails

Their respective primary keys are used as foreign key in the main table.

Now the problem is that I the sheets has thousands of records and I cannot figure out how do i import the data into the BasicDetails table which is referenced by foreign keys.

答:
You need to do this in multiple parts.

Load the Excel tables into a staging table, say staging.

Then, be sure that the foreign key references work, for instance:

```<code>select s.countrycode, count(*)
from staging s left join
     countries c
     on s.countrycode = c.countrycode
where c.countrycode is null
group by s.countrycode;
</code>```

You need to repeat this for cities and contacts.  The latter may be more complicated.  This question does not ask what to do about conflicting information -- if you need help with that, ask a NEW question.

When you are satisfied that all the reference tables are correct, you can load the table using joins:

```<code>insert into basicdata (Name, Father, Country_ID, City_ID ContactDetails_ID)
    select s.name, s.father, co.country_id, ci.city_id,
           con.contact_id
    from staging s join
         counties co
         on s.countrycode = co.countrycode join
         cities ci
         on s.citycode = ci.citycode join
         contacts con
         on s.contacctno = con.contactno;
</code>```

Body:
I have a table BasicDetails with these columns:

ID   Name   Father    Country_ID   City_ID   ContactDetails_ID

But client has shared Excel sheets with me and I should be loading that into the table. The sheet has the following columns

ID   Name   Father   CountryName   CountryCode   CityName   CityCode   ContactNo   CellNo   Address

Now, in my database CountryName, CountryCode, CityName these are stored in a separate table named Countries.

CityName  CityCode are saved in a separate table Cities.

ContactNo   CellNo   Address are stored in a separate table ContactDetails

Their respective primary keys are used as foreign key in the main table.

Now the problem is that I the sheets has thousands of records and I cannot figure out how do i import the data into the BasicDetails table which is referenced by foreign keys.

Body:
You need to do this in multiple parts.

Load the Excel tables into a staging table, say staging.

Then, be sure that the foreign key references work, for instance:

select s.countrycode, count(*)
from staging s left join
     countries c
     on s.countrycode = c.countrycode
where c.countrycode is null
group by s.countrycode;

You need to repeat this for cities and contacts.  The latter may be more complicated.  This question does not ask what to do about conflicting information -- if you need help with that, ask a NEW question.

When you are satisfied that all the reference tables are correct, you can load the table using joins:

insert into basicdata (Name, Father, Country_ID, City_ID ContactDetails_ID)
    select s.name, s.father, co.country_id, ci.city_id,
           con.contact_id
    from staging s join
         counties co
         on s.countrycode = co.countrycode join
         cities ci
         on s.citycode = ci.citycode join
         contacts con
         on s.contacctno = con.contactno;