问:
Vue emit data to router view component. Not emitting data and Form submission is cancelled error
I have an array called components at the LiveEdit.vue file data. I want to add an array item which has an object inside to the components array. Everything works fine except the emitting data part. LiveEdit component is on /live url path. The child i'm emitting is NavBarEdit.vue which is on /edit/nav url path. I want to emit data form NavBarEdit to LiveEdit. I also want to change url path to go back to LiveEdit component. I somehow found a way to change routes which is this

```<code>this.$emit('addComponent', data)
this.$router.push('/live')
</code>```

This is my code at LiveEdit vue file

```<code>data() {
    return {
      components: []
    }
},
methods: {
    addComponent(data) {
        this.components = [...this.components, data]
    }
},
</code>```

This is my routes

```<code>routes: [
{
    path: '/',
    component: LandingPage,
},
{
  path: '/live',
  component: LiveEdit,
},
{
  path: '/edit/nav',
  component: NavBarEidt,
},
{
  path: '/edit/slider',
  component: SliderEdit,
}
</code>```

]

How can I solve this problem? I am really in a trouble with this one. I've been dealing with this like two days. And still no luck. So, please help me out

Body:
I have an array called components at the LiveEdit.vue file data. I want to add an array item which has an object inside to the components array. Everything works fine except the emitting data part. LiveEdit component is on /live url path. The child i'm emitting is NavBarEdit.vue which is on /edit/nav url path. I want to emit data form NavBarEdit to LiveEdit. I also want to change url path to go back to LiveEdit component. I somehow found a way to change routes which is this

this.$emit('addComponent', data)
this.$router.push('/live')

This is my code at LiveEdit vue file

data() {
    return {
      components: []
    }
},
methods: {
    addComponent(data) {
        this.components = [...this.components, data]
    }
},

This is my routes

routes: [
{
    path: '/',
    component: LandingPage,
},
{
  path: '/live',
  component: LiveEdit,
},
{
  path: '/edit/nav',
  component: NavBarEidt,
},
{
  path: '/edit/slider',
  component: SliderEdit,
}

]

How can I solve this problem? I am really in a trouble with this one. I've been dealing with this like two days. And still no luck. So, please help me out


来源: stackexchange

问:
always get undefined in nx monorepo build
I learning monorepo with nx, and I submodule my existing repo and put it in my apps folder, and i setting up with javascript style using nx generate with --js, because my existing file use javascript and HapiJS. then I create a dockerfile to run my application and success to build it, but when I see the container logs in my app, I got an error, like

```<code>TypeError: Cannot read properties of undefined (reading 'register')
    at module.exports.internals.Server.internals.Plugin.register (/Users/macbook/Documents/coding/apps/express-repo/node_modules/hapi/lib/plugin.js:212:29)
</code>```

It's always and always, some function always got undefined, it is because the typescript compiles? Does anyone know how to resolve it? please help me guys.. thank you... That's a simple way to run nx without compiling to ts?

The answer with example in code POV

ContentLicense: CC BY-SA 4.0

Body:
I learning monorepo with nx, and I submodule my existing repo and put it in my apps folder, and i setting up with javascript style using nx generate with --js, because my existing file use javascript and HapiJS. then I create a dockerfile to run my application and success to build it, but when I see the container logs in my app, I got an error, like

TypeError: Cannot read properties of undefined (reading 'register')
    at module.exports.internals.Server.internals.Plugin.register (/Users/macbook/Documents/coding/apps/express-repo/node_modules/hapi/lib/plugin.js:212:29)

It's always and always, some function always got undefined, it is because the typescript compiles? Does anyone know how to resolve it? please help me guys.. thank you... That's a simple way to run nx without compiling to ts?

The answer with example in code POV


问:
checkbox is not working on JS. What can i do?
Checkbox is not working when i use state.
When clicked for the first time, checked becomes true, but the checkbox is not checked.
The next time I click it, checked doesn't change and the checkbox doesn't get checked.
No matter how many clicks, the checked is still true

```<code>export default function TodoUsers({
  $target,
  initialState,
  onClickUserName,
  addFavorite,
  removeFavorite,
  onChangeFilterByFavorite,
}) {
  this.$element = document.createElement('div');
  $target.appendChild(this.$element);

  this.state = initialState;

  this.render = () => {
    this.$element.innerHTML =
      `<input type="checkbox" id="favoriteCheckBox" />
      <label for="favoriteCheckBox">즐겨찾기&#128062한 사용자만 보기</label>` +
      this.state.userNameList
        .map((user) =>
          this.state.favoriteUsers[user]
            ? `<li><span class="userName" style="cursor: pointer;">${user}</span><button data-isfavorite="true" style="border-radius: 10px; background-color: #3E6D9C; margin: 5px; cursor: pointer;">🐾</button></li>`
            : `<li style="${
                this.state.isFavorited ? 'display: none;' : ''
              }"><span class="userName" style="cursor: pointer;">${user}</span><button data-isfavorite="false" style="border-radius: 10px; background-color: white; margin: 5px; cursor: pointer; ">🐾</button></li>`
        )
        .join('');
    this.$favoriteCheck = this.$element.querySelector('input');
  };

  this.setState = (nextState) => {
    this.state = nextState;
    this.render();
  };

  this.render();

  this.$element.addEventListener('click', (e) => {
    if (e.target.tagName === 'SPAN') {
      onClickUserName(e.target.innerText);
    }

    if (e.target.tagName === 'BUTTON') {
      let isfavorite = e.target.dataset.isfavorite;
      let targetText =
        e.target.parentNode.querySelector('.userName').textContent;

      switch (isfavorite) {
        case 'false':
          isfavorite = true;
          addFavorite(targetText);
          break;
        case 'true':
          isfavorite = false;
          removeFavorite(targetText);
          break;
      }
    }
  });

 this.$element.addEventListener('change', (e) => {
    this.setState({ ...this.state, isFavorited: e.target.checked });
  });
}

</code>```

How can I enable the checkbox?

i tried change onClick attribute but is not working.

I think the state is the problem.

Body:
Checkbox is not working when i use state.
When clicked for the first time, checked becomes true, but the checkbox is not checked.
The next time I click it, checked doesn't change and the checkbox doesn't get checked.
No matter how many clicks, the checked is still true

export default function TodoUsers({
  $target,
  initialState,
  onClickUserName,
  addFavorite,
  removeFavorite,
  onChangeFilterByFavorite,
}) {
  this.$element = document.createElement('div');
  $target.appendChild(this.$element);

  this.state = initialState;

  this.render = () => {
    this.$element.innerHTML =
      `<input type="checkbox" id="favoriteCheckBox" />
      즐겨찾기&#128062한 사용자만 보기` +
      this.state.userNameList
        .map((user) =>
          this.state.favoriteUsers[user]
            ? `
${user}<button data-isfavorite="true" style="border-radius: 10px; background-color: #3E6D9C; margin: 5px; cursor: pointer;">🐾</button>
`
            : `
${user}<button data-isfavorite="false" style="border-radius: 10px; background-color: white; margin: 5px; cursor: pointer; ">🐾</button>
`
        )
        .join('');
    this.$favoriteCheck = this.$element.querySelector('input');
  };

  this.setState = (nextState) => {
    this.state = nextState;
    this.render();
  };

  this.render();

  this.$element.addEventListener('click', (e) => {
    if (e.target.tagName === 'SPAN') {
      onClickUserName(e.target.innerText);
    }

    if (e.target.tagName === 'BUTTON') {
      let isfavorite = e.target.dataset.isfavorite;
      let targetText =
        e.target.parentNode.querySelector('.userName').textContent;

      switch (isfavorite) {
        case 'false':
          isfavorite = true;
          addFavorite(targetText);
          break;
        case 'true':
          isfavorite = false;
          removeFavorite(targetText);
          break;
      }
    }
  });

 this.$element.addEventListener('change', (e) => {
    this.setState({ ...this.state, isFavorited: e.target.checked });
  });
}

How can I enable the checkbox?

i tried change onClick attribute but is not working.

I think the state is the problem.


问:
name of the downloaded file is undefined
Downloaded file is always downloading as undefined.pdf. How to download the file with the specified name output.pdf</p>
```<code>  doc.pipe(fs.createWriteStream(`output.pdf`));
    const stream = res.writeHead(200, {
        'Content-Type': 'application/pdf',
        'Content-Disposition': 'attachment;filename=file.pdf',
       });
    doc.on('data', (chunk) => stream.write(chunk));
    doc.on('end', () => stream.end());
    doc.end()
</code>```

Body:
Downloaded file is always downloading as undefined.pdf. How to download the file with the specified name output.pdf

  doc.pipe(fs.createWriteStream(`output.pdf`));
    const stream = res.writeHead(200, {
        'Content-Type': 'application/pdf',
        'Content-Disposition': 'attachment;filename=file.pdf',
       });
    doc.on('data', (chunk) => stream.write(chunk));
    doc.on('end', () => stream.end());
    doc.end()


问:
Present Labels and Live Plot dynamically using a ML Model in Tkinter
I've been working on a project that updates the label and wave-plot that's coming from the live classification using an trained machine learning . It outputs is sound class "emergency vehicle" or "non emergency".

i have tried following code but it did not work as expected.

```<code>##importing all the required library

from tkinter import *
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox

import joblib

# for audio pre-processing and analysis:
import librosa as lib

# for audio features creation
import scipy

# for array processing:
import numpy as np

# for visualizing the data
from matplotlib import pyplot as plt
%matplotlib inline

# for playing audio
import IPython.display as ipd

# for splitting data into train-test:
from sklearn.model_selection import train_test_split
from keras.layers import *
from keras.models import *
from keras.optimizers import *
from keras.callbacks import *

#!usr/local/bin/python
import glob
import sys
import os
from pydub import AudioSegment
from tqdm import tqdm

#function for extracting features from sound
def features_extractor(file_name):
    audio, sample_rate = librosa.load(file_name, res_type='kaiser_fast')
    mfccs_features = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=80)
    mfccs_scaled_features = np.mean(mfccs_features.T, axis=0)

    return mfccs_scaled_features

#load the ml model

clf = joblib.load('lstm_model(copy).pkl')

#recording live audio as in out.wav in every 5 seconds and classify its class and re-record and re-classify

import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import scipy.io.wavfile
from tkinter import *
def test():
    a=0
    while True:
        #test.winfo_children.destroy()
        ### recording wav file from earphone
        fs= 44100
        second = 5
        #second =  int(input("Enter time duration in seconds: "))
        print("Recording.....n")
        record_voice = sounddevice.rec( int ( second * fs ) , samplerate = fs , channels = 2 )
        sounddevice.wait()
        write("out.wav",fs,record_voice)
        print("Finished.....nPlease check your output file")
        clear_output(wait=True)
        test_file_name = 'out.wav'
        data_list = []
        dataf = features_extractor(test_file_name)
        data_list.append([dataf])
        df_t = pd.DataFrame(data_list,columns=['feature'])
        test_x = np.array(df_t['feature'].tolist())
        test_file_features  = test_x.reshape(len(test_x),-1,80)
        test_pred = clf.predict(test_file_features)
        if (test_pred[0][0] < 0.5):
            label = Label(win,text='emergency_vehicle',fg="black",bg="white",font = ("Calibri 12 bold"))
            label.place(x=530,y=430+a)
        else:
            label = Label(win,text='no-emergency_vehicle',fg="black",bg="white",font = ("Calibri 12 bold"))
            label.place(x=530,y=430+a)

        # Visualization:
        figure = plt.figure(figsize=(8,2))
        bar1 = FigureCanvasTkAgg(figure, win)
        bar1.get_tk_widget().place(x=80,y=120)
        data,sample_rate=librosa.load(test_file_name)
        fig = plt.plot(librosa.display.waveshow(data,sr=sample_rate))
        #ipd.Audio(test_file_name)
        #fig.show()

        a=a+10
        label.destroy()
        bar1.destroy()
        from os import system, name
        import os
        from time import sleep
        sleep(2)

#tkinter window

win =  Tk()

width= win.winfo_screenwidth()
height= win.winfo_screenheight()
win.geometry("%dx%d" % (width/2.5, height))

#win.geometry("720x620")
win.configure(background="cyan")
win.title("Sound Classification")

title = Label(win,text="Sound Classification",bg="gray",width="300",height="1",fg="White",font = ("Calibri 20 bold italic underline")).pack()

#path = Label(win,bg="cyan",font = ("Verdana 8"))
# path.place(x=80, y=100)

submit = Button(win, text="Test", width="12",height="1",activebackground="violet", bg="Pink",font= ("Calibri 12 "),command = test).place(x=500, y=60)
win.mainloop()
</code>```

Body:
I've been working on a project that updates the label and wave-plot that's coming from the live classification using an trained machine learning . It outputs is sound class "emergency vehicle" or "non emergency".

i have tried following code but it did not work as expected.

##importing all the required library

from tkinter import *
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox

import joblib

# for audio pre-processing and analysis:
import librosa as lib

# for audio features creation
import scipy

# for array processing:
import numpy as np

# for visualizing the data
from matplotlib import pyplot as plt
%matplotlib inline

# for playing audio
import IPython.display as ipd

# for splitting data into train-test:
from sklearn.model_selection import train_test_split
from keras.layers import *
from keras.models import *
from keras.optimizers import *
from keras.callbacks import *

#!usr/local/bin/python
import glob
import sys
import os
from pydub import AudioSegment
from tqdm import tqdm

#function for extracting features from sound
def features_extractor(file_name):
    audio, sample_rate = librosa.load(file_name, res_type='kaiser_fast')
    mfccs_features = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=80)
    mfccs_scaled_features = np.mean(mfccs_features.T, axis=0)

    return mfccs_scaled_features

#load the ml model

clf = joblib.load('lstm_model(copy).pkl')

#recording live audio as in out.wav in every 5 seconds and classify its class and re-record and re-classify

import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import scipy.io.wavfile
from tkinter import *
def test():
    a=0
    while True:
        #test.winfo_children.destroy()
        ### recording wav file from earphone
        fs= 44100
        second = 5
        #second =  int(input("Enter time duration in seconds: "))
        print("Recording.....n")
        record_voice = sounddevice.rec( int ( second * fs ) , samplerate = fs , channels = 2 )
        sounddevice.wait()
        write("out.wav",fs,record_voice)
        print("Finished.....nPlease check your output file")
        clear_output(wait=True)
        test_file_name = 'out.wav'
        data_list = []
        dataf = features_extractor(test_file_name)
        data_list.append([dataf])
        df_t = pd.DataFrame(data_list,columns=['feature'])
        test_x = np.array(df_t['feature'].tolist())
        test_file_features  = test_x.reshape(len(test_x),-1,80)
        test_pred = clf.predict(test_file_features)
        if (test_pred[0][0] < 0.5):
            label = Label(win,text='emergency_vehicle',fg="black",bg="white",font = ("Calibri 12 bold"))
            label.place(x=530,y=430+a)
        else:
            label = Label(win,text='no-emergency_vehicle',fg="black",bg="white",font = ("Calibri 12 bold"))
            label.place(x=530,y=430+a)

        # Visualization:
        figure = plt.figure(figsize=(8,2))
        bar1 = FigureCanvasTkAgg(figure, win)
        bar1.get_tk_widget().place(x=80,y=120)
        data,sample_rate=librosa.load(test_file_name)
        fig = plt.plot(librosa.display.waveshow(data,sr=sample_rate))
        #ipd.Audio(test_file_name)
        #fig.show()

        a=a+10
        label.destroy()
        bar1.destroy()
        from os import system, name
        import os
        from time import sleep
        sleep(2)

#tkinter window

win =  Tk()

width= win.winfo_screenwidth()
height= win.winfo_screenheight()
win.geometry("%dx%d" % (width/2.5, height))

#win.geometry("720x620")
win.configure(background="cyan")
win.title("Sound Classification")

title = Label(win,text="Sound Classification",bg="gray",width="300",height="1",fg="White",font = ("Calibri 20 bold italic underline")).pack()

#path = Label(win,bg="cyan",font = ("Verdana 8"))
# path.place(x=80, y=100)

submit = Button(win, text="Test", width="12",height="1",activebackground="violet", bg="Pink",font= ("Calibri 12 "),command = test).place(x=500, y=60)
win.mainloop()


问:
How customize EditCustomfieldDefaults screen in my customfield plugin
I'm trying to override the default customfield value setting screen, but I'm unable to add the template.
The standard edit.vm template allows you to change the value of the field in the issue, but I need a separate page for this

enter image description here

My code from atlassian-plugin.xml
`

```<code><customfield-type
        name="Metro Cascading Custom Field"
        i18n-name-key="metro-cascading-custom-field.name"
        key="metro-cascading-custom-field"
        class="MetroCascadingCustomField.MetroCascadingCustomField">
  <description
          key="metro-cascading-custom-field.description">The Metro Cascading Custom Field Plugin</description>
  <resource name="view" type="velocity" location="/templates/customfields/metro-cascading-custom-field/view.vm"/>
  <resource name="edit" type="velocity" location="/templates/customfields/metro-cascading-custom-field/edit.vm"/>
</customfield-type>

<webwork1
        key="metro-cascading-cuastomfield-webwork"
        name="Metro Cascading Cuastomfield Webwork"
        i18n-name-key="metro-cascading-cuastomfield-webwork.name">
  <description key="metro-cascading-cuastomfield-webwork.description">The Metro Cascading Cuastomfield Webwork Plugin</description>
  <actions>
    <action name="ru.jira.metro.plugin.jira.webwork.MetroCascadingCuastomfieldWebworkAction" alias="CustomMultiSelectOptionsConfiguration">>
      <view name="success">/templates/metro-cascading-cuastomfield-webwork/success.vm</view>
      <view name="input">/templates/metro-cascading-cuastomfield-webwork/input.vm</view>
      <view name="error">/templates/metro-cascading-cuastomfield-webwork/error.vm</view>
    </action>
  </actions>
  <context>atl.admin.custom-fields</context>
</webwork1>
</code>```

`

Body:
I'm trying to override the default customfield value setting screen, but I'm unable to add the template.
The standard edit.vm template allows you to change the value of the field in the issue, but I need a separate page for this

enter image description here

My code from atlassian-plugin.xml
`

<customfield-type
        name="Metro Cascading Custom Field"
        i18n-name-key="metro-cascading-custom-field.name"
        key="metro-cascading-custom-field"
        class="MetroCascadingCustomField.MetroCascadingCustomField">
  <description
          key="metro-cascading-custom-field.description">The Metro Cascading Custom Field Plugin</description>
  <resource name="view" type="velocity" location="/templates/customfields/metro-cascading-custom-field/view.vm"/>
  <resource name="edit" type="velocity" location="/templates/customfields/metro-cascading-custom-field/edit.vm"/>
</customfield-type>

<webwork1
        key="metro-cascading-cuastomfield-webwork"
        name="Metro Cascading Cuastomfield Webwork"
        i18n-name-key="metro-cascading-cuastomfield-webwork.name">
  <description key="metro-cascading-cuastomfield-webwork.description">The Metro Cascading Cuastomfield Webwork Plugin</description>
  <actions>
    <action name="ru.jira.metro.plugin.jira.webwork.MetroCascadingCuastomfieldWebworkAction" alias="CustomMultiSelectOptionsConfiguration">>
      <view name="success">/templates/metro-cascading-cuastomfield-webwork/success.vm</view>
      <view name="input">/templates/metro-cascading-cuastomfield-webwork/input.vm</view>
      <view name="error">/templates/metro-cascading-cuastomfield-webwork/error.vm</view>
    </action>
  </actions>
  <context>atl.admin.custom-fields</context>
</webwork1>

`


问:
Can't resolve 'fs' in Vue.js@3, Winston@3 and webpack@5
would like to use Winston@3 package in our project. But I can't resolve problem with requered 'fs' package.

I always get this error:

```<code>Compiled with problems:

ERROR in ./node_modules/winston/dist/winston/tail-file.js 12:9-22
Module not found: Error: Can't resolve 'fs' in '/app/node_modules/winston/dist/winston'

ERROR in ./node_modules/winston/dist/winston/transports/file.js 136:9-22
Module not found: Error: Can't resolve 'fs' in '/app/node_modules/winston/dist/winston/transports'

</code>```

(Error screenshot)

I tried everything I found. Just like define browser restriction in package.json:

{
  ...
  "browser": {
    "fs": false,
    "path": false,
    "os": false
  },
  "devDependencies": {
    "@testing-library/vue": "^6.5.1",
    "@types/applepayjs": "^3.0.4",
    "@types/googlepay": "^0.6.4",
    "@types/jest": "^27.5.2",
    "@types/vue-i18n": "^7.0.0",
    "@typescript-eslint/eslint-plugin": "^5.45.0",
    "@typescript-eslint/parser": "^5.45.0",
    "@vue/cli": "^5.0.4",
    "@vue/cli-plugin-babel": "^5.0.4",
    "@vue/cli-plugin-e2e-cypress": "^5.0.4",
    "@vue/cli-plugin-eslint": "^5.0.8",
    "@vue/cli-plugin-router": "^5.0.4",
    "@vue/cli-plugin-typescript": "^5.0.4",
    "@vue/cli-plugin-unit-jest": "^5.0.8",
    "@vue/cli-plugin-vuex": "^5.0.4",
    "@vue/cli-service": "^5.0.4",
    "@vue/compiler-sfc": "^3.2.31",
    "@vue/eslint-config-typescript": "^11.0.2",
    "@vue/test-utils": "^2.2.4",
    "@vue/vue3-jest": "^27.0.0",
    "babel-eslint": "^10.1.0",
    "babel-jest": "^27.5.1",
    "cypress": "^11.2.0",
    "eclint": "^2.8.1",
    "eslint": "^8.28.0",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-vue": "^9.8.0",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^27.5.1",
    "jest-runner-groups": "^2.2.0",
    "less": "^4.1.3",
    "less-loader": "^11.0.0",
    "lint-staged": "^13.0.4",
    "ts-jest": "^27.1.5",
    "tsconfig-paths": "^4.1.1",
    "tslib": "^2.3.1",
    "typescript": "^4.9.3"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/vue3-essential",
      "eslint:recommended",
      "@vue/typescript",
      "plugin:cypress/recommended"
    ],
    "parserOptions": {
      "parser": "@typescript-eslint/parser",
      "ecmaVersion": 2021
    },
    "rules": {
      "no-unused-vars": "off"
    },
    "overrides": [
      {
        "files": [
          "**/__tests__/*.{j,t}s?(x)",
          "**/tests/unit/**/*.test.{j,t}s?(x)"
        ],
        "env": {
          "jest": true
        }
      }
    ]
  },
  "browserslist": [
    "> 0.1%",
    "last 10 years",
    "not dead",
    "not ie 11"
  ],
  ...
}
```
<p>Configure <code>fs: 'empty'</code> in <code>webpack.config.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>module.exports = {
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx'],
    fallback: {
      util: require.resolve("util/"),
      "fs": false
    },
    alias: {
      fs: 'empty'
    }
  },
  module: {
    node: {
      fs: 'empty'
    }
  },
};
</code>```

and also configure fs: 'empty' in vue.config.js where i also configure the webpack:

module.exports = {
  ...
  configureWebpack: {
    plugins: [new NodePolyfillPlugin()],
    resolve: {
      alias: {
        fs: 'empty'
      }
    }
  },
  chainWebpack: (config) => {
    // config.node = {
    //   'fs': 'empty'
    // };

    // config.node = {
    //   fs: 'empty'
    // }
  },
  ...
}
```
<p>I also use TypeScript but I think that one is not causing this problem...</p>
<pre class="lang-json prettyprint-override"><code>{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "useDefineForClassFields": true,
    "allowJs": true,
    "sourceMap": false,
    "baseUrl": ".",
    "types": [
      "webpack-env",
      "jest"
    ],
    "paths": {
      "@/tests/*": [
        "./tests/*",
      ],
      "@/*": [
        "./src/*",
        "./*"
      ],
      "tslib" : ["bower_components/tslib/tslib.d.ts"]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "./src/*.ts",
    "./src/**/*.ts",
  ],
  "exclude": [
    "node_modules",
    "dist",
    "**/*.spec.ts",
    "./tests/e2e.api.ts"
  ]
}
</code>```

I have no idea how to fix this. I found a lot of instructions in the internet how to solve it but no one works for me. :(

Is here anyone who knows and can helps me?
Thank you!

Body:
would like to use Winston@3 package in our project. But I can't resolve problem with requered 'fs' package.

I always get this error:

Compiled with problems:

ERROR in ./node_modules/winston/dist/winston/tail-file.js 12:9-22
Module not found: Error: Can't resolve 'fs' in '/app/node_modules/winston/dist/winston'

ERROR in ./node_modules/winston/dist/winston/transports/file.js 136:9-22
Module not found: Error: Can't resolve 'fs' in '/app/node_modules/winston/dist/winston/transports'

(Error screenshot)

I tried everything I found. Just like define browser restriction in package.json:

{
  ...
  "browser": {
    "fs": false,
    "path": false,
    "os": false
  },
  "devDependencies": {
    "@testing-library/vue": "^6.5.1",
    "@types/applepayjs": "^3.0.4",
    "@types/googlepay": "^0.6.4",
    "@types/jest": "^27.5.2",
    "@types/vue-i18n": "^7.0.0",
    "@typescript-eslint/eslint-plugin": "^5.45.0",
    "@typescript-eslint/parser": "^5.45.0",
    "@vue/cli": "^5.0.4",
    "@vue/cli-plugin-babel": "^5.0.4",
    "@vue/cli-plugin-e2e-cypress": "^5.0.4",
    "@vue/cli-plugin-eslint": "^5.0.8",
    "@vue/cli-plugin-router": "^5.0.4",
    "@vue/cli-plugin-typescript": "^5.0.4",
    "@vue/cli-plugin-unit-jest": "^5.0.8",
    "@vue/cli-plugin-vuex": "^5.0.4",
    "@vue/cli-service": "^5.0.4",
    "@vue/compiler-sfc": "^3.2.31",
    "@vue/eslint-config-typescript": "^11.0.2",
    "@vue/test-utils": "^2.2.4",
    "@vue/vue3-jest": "^27.0.0",
    "babel-eslint": "^10.1.0",
    "babel-jest": "^27.5.1",
    "cypress": "^11.2.0",
    "eclint": "^2.8.1",
    "eslint": "^8.28.0",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-vue": "^9.8.0",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^27.5.1",
    "jest-runner-groups": "^2.2.0",
    "less": "^4.1.3",
    "less-loader": "^11.0.0",
    "lint-staged": "^13.0.4",
    "ts-jest": "^27.1.5",
    "tsconfig-paths": "^4.1.1",
    "tslib": "^2.3.1",
    "typescript": "^4.9.3"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/vue3-essential",
      "eslint:recommended",
      "@vue/typescript",
      "plugin:cypress/recommended"
    ],
    "parserOptions": {
      "parser": "@typescript-eslint/parser",
      "ecmaVersion": 2021
    },
    "rules": {
      "no-unused-vars": "off"
    },
    "overrides": [
      {
        "files": [
          "**/__tests__/*.{j,t}s?(x)",
          "**/tests/unit/**/*.test.{j,t}s?(x)"
        ],
        "env": {
          "jest": true
        }
      }
    ]
  },
  "browserslist": [
    "> 0.1%",
    "last 10 years",
    "not dead",
    "not ie 11"
  ],
  ...
}

Configure fs: 'empty' in webpack.config.js:

module.exports = {
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx'],
    fallback: {
      util: require.resolve("util/"),
      "fs": false
    },
    alias: {
      fs: 'empty'
    }
  },
  module: {
    node: {
      fs: 'empty'
    }
  },
};

and also configure fs: 'empty' in vue.config.js where i also configure the webpack:

module.exports = {
  ...
  configureWebpack: {
    plugins: [new NodePolyfillPlugin()],
    resolve: {
      alias: {
        fs: 'empty'
      }
    }
  },
  chainWebpack: (config) => {
    // config.node = {
    //   'fs': 'empty'
    // };

    // config.node = {
    //   fs: 'empty'
    // }
  },
  ...
}

I also use TypeScript but I think that one is not causing this problem...

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "useDefineForClassFields": true,
    "allowJs": true,
    "sourceMap": false,
    "baseUrl": ".",
    "types": [
      "webpack-env",
      "jest"
    ],
    "paths": {
      "@/tests/*": [
        "./tests/*",
      ],
      "@/*": [
        "./src/*",
        "./*"
      ],
      "tslib" : ["bower_components/tslib/tslib.d.ts"]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "./src/*.ts",
    "./src/**/*.ts",
  ],
  "exclude": [
    "node_modules",
    "dist",
    "**/*.spec.ts",
    "./tests/e2e.api.ts"
  ]
}

I have no idea how to fix this. I found a lot of instructions in the internet how to solve it but no one works for me. :(

Is here anyone who knows and can helps me?
Thank you!


问:
why does vscode catching exception nested in try except?
why does my vscode debugger caught exception when it is nested under "try-except"?

raised exception img

import inside try except

call stack

breakpoint conditions

can anyone please make some reasoning here?

the code is under try-except. so why would this happen?

thx in advance


问:
How can i dynamically import a node module (and its dependencies) given the module name?
I would like to build a function in NodeJS that accepts a module name as input parameter and import the module with its dependencies. Ideally, the could would be something like:

```<code>async function loadModule (moduleName) {
   await import(moduleName)
}

const test = await loadModule('./test.js')
</code>```

where test.js would be something like

```<code>import a from 'a'
import b from 'b'

// do something
</code>```

Is it possible to dynamically import the file and its dependencies a and b at runtime?

Body:
I would like to build a function in NodeJS that accepts a module name as input parameter and import the module with its dependencies. Ideally, the could would be something like:

async function loadModule (moduleName) {
   await import(moduleName)
}

const test = await loadModule('./test.js')

where test.js would be something like

import a from 'a'
import b from 'b'

// do something

Is it possible to dynamically import the file and its dependencies a and b at runtime?


问:
Node / Vite one build for multi environments
I'm using Vite framework to build my frontend application.

I would like to be able to build a version once, let's say 1.0 and then run it in dev env (with dev variables), then in production (with prod variables). As I do with Java apps for example.

This is quite important because I don't want to "build for prod" once my tests in dev are ok, taking the risk of building something slightly different from dev (dependencies, or even commits).

I know that node frontend projects are simply plain JS files once the application is built, so I don't think reading an env variable would be possible.

Any idea ?


问:
input error when fitting model Neural network in R
I get an error when i try to run this code. i followed a guide on youtube for building a neural network. Everything works except when i try to run this code to fit the model.</p>
```<code>history <- modnn %>% fit(
  train_X_matrix, train_Y, epochs = 50, batch_size = 600,
  validation_data = list(validation_X_matrix,validation_Y))
```
the error i get when i try to run the code above, all the names you see are the names of the columns. So the features of the model:
[error in visual studio](https://i.stack.imgur.com/ZaPXw.png)

some extra info about the variables i use. Here i created a matrix of the input variables. They did this in the guide. I tried train_x_data as input then it gave the same error but immediately so not after 1 epoch

```
# dependent and independent variables in 1 dataframe
train_X_data <- data.frame(train_X,train_y)
validation_X_data <- data.frame(validation_X,validation_y)

train_X_matrix <- model.matrix(average_daily_rate ~. -1 , data = train_X_data)
train_Y <- train_X_data$average_daily_rate
validation_X_matrix <- model.matrix(average_daily_rate ~. -1, data = validation_X_data)
validation_Y <- validation_X_data$average_daily_rate
```

The model i use, it is just a simple single layer model for testing.

# 1) single layer model structure
# step 1 make architecture powerful enough
modnn <- keras_model_sequential() %>%
  layer_dense(units = 500, activation = "relu",
              input_shape = ncol(train_X)) %>%
  layer_dense(units = 1)
summary(modnn)
modnn %>% compile(loss = "mse",
                   optimizer = optimizer_rmsprop(),
                   metrics = list("mean_absolute_error"))

The error occurs after running the first epoch. I tought it was because the model could not read the names of the columns, but i tried a lot of things and nothing seemed to work.

Does anyone have an idea on how to fix this?
</code>```

Body:
I get an error when i try to run this code. i followed a guide on youtube for building a neural network. Everything works except when i try to run this code to fit the model.

history <- modnn %>% fit(
  train_X_matrix, train_Y, epochs = 50, batch_size = 600,
  validation_data = list(validation_X_matrix,validation_Y))
```
the error i get when i try to run the code above, all the names you see are the names of the columns. So the features of the model:
[error in visual studio](https://i.stack.imgur.com/ZaPXw.png)

some extra info about the variables i use. Here i created a matrix of the input variables. They did this in the guide. I tried train_x_data as input then it gave the same error but immediately so not after 1 epoch

```
# dependent and independent variables in 1 dataframe
train_X_data <- data.frame(train_X,train_y)
validation_X_data <- data.frame(validation_X,validation_y)

train_X_matrix <- model.matrix(average_daily_rate ~. -1 , data = train_X_data)
train_Y <- train_X_data$average_daily_rate
validation_X_matrix <- model.matrix(average_daily_rate ~. -1, data = validation_X_data)
validation_Y <- validation_X_data$average_daily_rate
```

The model i use, it is just a simple single layer model for testing.

# 1) single layer model structure
# step 1 make architecture powerful enough
modnn <- keras_model_sequential() %>%
  layer_dense(units = 500, activation = "relu",
              input_shape = ncol(train_X)) %>%
  layer_dense(units = 1)
summary(modnn)
modnn %>% compile(loss = "mse",
                   optimizer = optimizer_rmsprop(),
                   metrics = list("mean_absolute_error"))

The error occurs after running the first epoch. I tought it was because the model could not read the names of the columns, but i tried a lot of things and nothing seemed to work.

Does anyone have an idea on how to fix this?


问:
Connect ECONNREFUSED 127.0.0.1:8000 with Docker devcontainers and WSL2
I'm working with Docker and WSL2 containers in my enterprise. I have an application which is separated in two: the front (ReactJS) and a mock, temporary before having the real API.
And when I try to connect them together I'm getting this error:

Backend is running on port 8000
AxiosError: connect ECONNREFUSED 127.0.0.1:3030
    at Function.AxiosError.from (/workspaces/backoffice/app/node_modules/axios/dist/node/axios.cjs:785:14)
    at RedirectableRequest.handleRequestError (/workspaces/backoffice/app/node_modules/axios/dist/node/axios.cjs:2725:25)
    at RedirectableRequest.emit (node:events:513:28)
    at ClientRequest.eventHandlers.<computed> (/workspaces/backoffice/app/node_modules/follow-redirects/index.js:14:24)
    at ClientRequest.emit (node:events:513:28)
    at Socket.socketErrorListener (node:_http_client:494:9)
    at Socket.emit (node:events:513:28)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  port: 3030,
  address: '127.0.0.1',
  syscall: 'connect',
  code: 'ECONNREFUSED',
  errno: -111,
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [ 'xhr', 'http' ],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: { FormData: [Function], Blob: null },
    validateStatus: [Function: validateStatus],
    headers: AxiosHeaders {
      Accept: 'application/json, text/plain, */*',
      'User-Agent': 'axios/1.2.0',
      'Accept-Encoding': 'gzip, deflate, br'
    },
    method: 'get',
    url: 'http://localhost:3030/catalogs/items',
    data: undefined
  },
  request: <ref *1> Writable {
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: true,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      allBuffers: true,
      allNoop: true,
      pendingcb: 0,
      constructed: true,
      prefinished: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: true,
      errored: null,
      closed: false,
      closeEmitted: false,
      [Symbol(kOnFinished)]: []
    },
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError],
      socket: [Function: handleRequestSocket]
    },
    _eventsCount: 3,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: Infinity,
      protocol: 'http:',
      path: '/catalogs/items',
      method: 'GET',
      headers: [Object: null prototype],
      agents: [Object],
      auth: undefined,
      beforeRedirect: [Function: dispatchBeforeRedirect],
      beforeRedirects: [Object],
      hostname: 'localhost',
      port: '3030',
      agent: undefined,
      nativeProtocols: [Object],
      pathname: '/catalogs/items'
    },
    _ended: true,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 0,
    _requestBodyBuffers: [],
    _onNativeResponse: [Function (anonymous)],
    _currentRequest: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      strictContentLength: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      _closed: false,
      socket: [Socket],
      _header: 'GET /catalogs/items HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'User-Agent: axios/1.2.0\r\n' +
        'Accept-Encoding: gzip, deflate, br\r\n' +
        'Host: localhost:3030\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/catalogs/items',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'localhost',
      protocol: 'http:',
      _redirectable: [Circular *1],
      [Symbol(kCapture)]: false,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(kEndCalled)]: true,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype],
      [Symbol(kUniqueHeaders)]: null
    },
    _currentUrl: 'http://localhost:3030/catalogs/items',
    [Symbol(kCapture)]: false
  },
  cause: Error: connect ECONNREFUSED 127.0.0.1:3030
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1278:16) {
    errno: -111,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 3030
  }
}
```
<p>My files are like that:</p>
<h3>Server.js</h3>
<pre class="lang-js prettyprint-override"><code>const express = require('express')
const cors = require('cors')
const axios = require('axios')
require('dotenv').config()
const bodyParser = require("body-parser");
const PORT = process.env.REACT_APP_EXPRESS_PORT

const app = express()

app.use(bodyParser.json());

app.use(cors())

app.get('/items',(req, res) => {
    axios.get(`${process.env.REACT_APP_EXPRESS_HOST}:3030/catalogs/items`)
    .then((response) => {
        res.json(response.data);
    })
    .catch((error) => {
        console.log(error);
    })
})

app.post('/items',(req, res) => {
    axios.post(`${process.env.REACT_APP_EXPRESS_HOST}:3030/catalogs/items`, req.body)
    .then((response) => {
        res.json(response.data);
    })
    .catch((error) => {
        console.log(error);
    })
})

app.delete('/items/:id',(req, res,) => {
    axios.delete(`${process.env.REACT_APP_EXPRESS_HOST}:3030/catalogs/items/:id`)
    .then((response) => {
        res.json(response.data);
    })
    .catch((error) => {
        console.log(error);
    })
})

app.put('/commandes/:id', (req, res) => {
    axios.put(`${process.env.REACT_APP_EXPRESS_HOST}:3030/commandes/:id`, req.body)
    .then(
        (response) => {
            res.json(response.data);
        }
    )
    .catch(
        (error) => {
            console.log(error);
        }
    )
})

app.listen(PORT, () => console.log(`Backend is running on port ${PORT}`))
</code>```

.env

```<code>REACT_APP_EXPRESS_HOST="http://localhost"
REACT_APP_EXPRESS_PORT="8000"
</code>```

With Docker

My two applications are running with a devcontainer.json, and that's it, no docker-compose or Dockerfile.

I create a network bridge to make them run on the same network, and add in each devcontainer.json:

    "runArgs": [
        "--network=mercure-bridge"
    ],
```
<p>Here is one of my devcontainer.json, they are the same, just the names are different:</p>
<h3>devcontainer.json</h3>
<pre class="lang-json prettyprint-override"><code>{
    "name": "MercureFront",
    "image": "mcr.microsoft.com/devcontainers/javascript-node:16-bullseye",

    "customizations": {
        "vscode": {
            "settings": {},
            "extensions": [
                "esbenp.prettier-vscode",
                "bierner.color-info",
                "jpoissonnier.vscode-styled-components",
                "visualstudioexptteam.vscodeintellicode",
                "dsznajder.es7-react-js-snippets",
                "eg2.vscode-npm-script",
                "christian-kohler.npm-intellisense",
                "cssho.vscode-svgviewer",
                "ms-azuretools.vscode-docker",
                "davidanson.vscode-markdownlint",
                "IBM.output-colorizer",
                "Gruntfuggly.todo-tree",
                "bierner.emojisense",
                "stkb.rewrap",
                "vscode-icons-team.vscode-icons",
                "JakeWilson.vscode-cdnjs",
                "quicktype.quicktype"
            ]
        }
    },
    "portsAttributes": {
        "3000": {
            "label": "Hello Mercure",
            "onAutoForward": "notify"
        }
    },
    "runArgs": [
        "--network=mercure-bridge"
    ],
    "remoteUser": "node"
}
</code>```

I checked if they runs on the same network with a Docker inspect:

$ docker network inspect mercure-bridge
[
    {
        "Name": "mercure-bridge",
        "Id": "f98f63b6d9c2d79135ecb9ca564418c52e9936e3413f9dd25fcc0c09b69c7d3b",
        "Created": "2022-12-06T15:26:09.919998982Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "172.20.0.0/16",
                    "Gateway": "172.20.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "40584f384551892d974061f621f2106ceaaced6983aafff184dc58a4573d7934": {
                "Name": "frosty_taussig",
                "EndpointID": "7e8a0454355cf75e6af62da70ac7f75889350dd3a9e8e028112a9aff8991baea",
                "MacAddress": "02:42:ac:14:00:03",
                "IPv4Address": "172.20.0.3/16",
                "IPv6Address": ""
            },
            "8d78c0afadb2c8086f6747ef726141bdb6d7bae43436a78a6c9a942b0d0279e9": {
                "Name": "charming_sanderson",
                "EndpointID": "e11d13680f0b2d715ed430160412c7b9d078d61813212c4338bb7a597fe146a3",
                "MacAddress": "02:42:ac:14:00:02",
                "IPv4Address": "172.20.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]
```

So I tried to change the base URL with :

http://localhost

http://127.0.0.1

the ip of the network

the ip of the mock container

the name of the network

the name of the mock container

the endpoint ID of the mock

the WSL gateway and the WSL2 IP address

I don't have service name, because I don't have docker-compose... but I really tried a lot of things. And have no more ideas, I'm going mad

Body:
I'm working with Docker and WSL2 containers in my enterprise. I have an application which is separated in two: the front (ReactJS) and a mock, temporary before having the real API.
And when I try to connect them together I'm getting this error:

Backend is running on port 8000
AxiosError: connect ECONNREFUSED 127.0.0.1:3030
    at Function.AxiosError.from (/workspaces/backoffice/app/node_modules/axios/dist/node/axios.cjs:785:14)
    at RedirectableRequest.handleRequestError (/workspaces/backoffice/app/node_modules/axios/dist/node/axios.cjs:2725:25)
    at RedirectableRequest.emit (node:events:513:28)
    at ClientRequest.eventHandlers.<computed> (/workspaces/backoffice/app/node_modules/follow-redirects/index.js:14:24)
    at ClientRequest.emit (node:events:513:28)
    at Socket.socketErrorListener (node:_http_client:494:9)
    at Socket.emit (node:events:513:28)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  port: 3030,
  address: '127.0.0.1',
  syscall: 'connect',
  code: 'ECONNREFUSED',
  errno: -111,
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [ 'xhr', 'http' ],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: { FormData: [Function], Blob: null },
    validateStatus: [Function: validateStatus],
    headers: AxiosHeaders {
      Accept: 'application/json, text/plain, */*',
      'User-Agent': 'axios/1.2.0',
      'Accept-Encoding': 'gzip, deflate, br'
    },
    method: 'get',
    url: 'http://localhost:3030/catalogs/items',
    data: undefined
  },
  request: <ref *1> Writable {
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: true,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      allBuffers: true,
      allNoop: true,
      pendingcb: 0,
      constructed: true,
      prefinished: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: true,
      errored: null,
      closed: false,
      closeEmitted: false,
      [Symbol(kOnFinished)]: []
    },
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError],
      socket: [Function: handleRequestSocket]
    },
    _eventsCount: 3,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: Infinity,
      protocol: 'http:',
      path: '/catalogs/items',
      method: 'GET',
      headers: [Object: null prototype],
      agents: [Object],
      auth: undefined,
      beforeRedirect: [Function: dispatchBeforeRedirect],
      beforeRedirects: [Object],
      hostname: 'localhost',
      port: '3030',
      agent: undefined,
      nativeProtocols: [Object],
      pathname: '/catalogs/items'
    },
    _ended: true,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 0,
    _requestBodyBuffers: [],
    _onNativeResponse: [Function (anonymous)],
    _currentRequest: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      strictContentLength: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      _closed: false,
      socket: [Socket],
      _header: 'GET /catalogs/items HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'User-Agent: axios/1.2.0\r\n' +
        'Accept-Encoding: gzip, deflate, br\r\n' +
        'Host: localhost:3030\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/catalogs/items',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'localhost',
      protocol: 'http:',
      _redirectable: [Circular *1],
      [Symbol(kCapture)]: false,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(kEndCalled)]: true,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype],
      [Symbol(kUniqueHeaders)]: null
    },
    _currentUrl: 'http://localhost:3030/catalogs/items',
    [Symbol(kCapture)]: false
  },
  cause: Error: connect ECONNREFUSED 127.0.0.1:3030
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1278:16) {
    errno: -111,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 3030
  }
}

My files are like that:

Server.js

const express = require('express')
const cors = require('cors')
const axios = require('axios')
require('dotenv').config()
const bodyParser = require("body-parser");
const PORT = process.env.REACT_APP_EXPRESS_PORT

const app = express()

app.use(bodyParser.json());

app.use(cors())

app.get('/items',(req, res) => {
    axios.get(`${process.env.REACT_APP_EXPRESS_HOST}:3030/catalogs/items`)
    .then((response) => {
        res.json(response.data);
    })
    .catch((error) => {
        console.log(error);
    })
})

app.post('/items',(req, res) => {
    axios.post(`${process.env.REACT_APP_EXPRESS_HOST}:3030/catalogs/items`, req.body)
    .then((response) => {
        res.json(response.data);
    })
    .catch((error) => {
        console.log(error);
    })
})

app.delete('/items/:id',(req, res,) => {
    axios.delete(`${process.env.REACT_APP_EXPRESS_HOST}:3030/catalogs/items/:id`)
    .then((response) => {
        res.json(response.data);
    })
    .catch((error) => {
        console.log(error);
    })
})

app.put('/commandes/:id', (req, res) => {
    axios.put(`${process.env.REACT_APP_EXPRESS_HOST}:3030/commandes/:id`, req.body)
    .then(
        (response) => {
            res.json(response.data);
        }
    )
    .catch(
        (error) => {
            console.log(error);
        }
    )
})

app.listen(PORT, () => console.log(`Backend is running on port ${PORT}`))

.env

REACT_APP_EXPRESS_HOST="http://localhost"
REACT_APP_EXPRESS_PORT="8000"

With Docker

My two applications are running with a devcontainer.json, and that's it, no docker-compose or Dockerfile.

I create a network bridge to make them run on the same network, and add in each devcontainer.json:

    "runArgs": [
        "--network=mercure-bridge"
    ],

Here is one of my devcontainer.json, they are the same, just the names are different:

devcontainer.json

{
    "name": "MercureFront",
    "image": "mcr.microsoft.com/devcontainers/javascript-node:16-bullseye",

    "customizations": {
        "vscode": {
            "settings": {},
            "extensions": [
                "esbenp.prettier-vscode",
                "bierner.color-info",
                "jpoissonnier.vscode-styled-components",
                "visualstudioexptteam.vscodeintellicode",
                "dsznajder.es7-react-js-snippets",
                "eg2.vscode-npm-script",
                "christian-kohler.npm-intellisense",
                "cssho.vscode-svgviewer",
                "ms-azuretools.vscode-docker",
                "davidanson.vscode-markdownlint",
                "IBM.output-colorizer",
                "Gruntfuggly.todo-tree",
                "bierner.emojisense",
                "stkb.rewrap",
                "vscode-icons-team.vscode-icons",
                "JakeWilson.vscode-cdnjs",
                "quicktype.quicktype"
            ]
        }
    },
    "portsAttributes": {
        "3000": {
            "label": "Hello Mercure",
            "onAutoForward": "notify"
        }
    },
    "runArgs": [
        "--network=mercure-bridge"
    ],
    "remoteUser": "node"
}

I checked if they runs on the same network with a Docker inspect:

$ docker network inspect mercure-bridge
[
    {
        "Name": "mercure-bridge",
        "Id": "f98f63b6d9c2d79135ecb9ca564418c52e9936e3413f9dd25fcc0c09b69c7d3b",
        "Created": "2022-12-06T15:26:09.919998982Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "172.20.0.0/16",
                    "Gateway": "172.20.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "40584f384551892d974061f621f2106ceaaced6983aafff184dc58a4573d7934": {
                "Name": "frosty_taussig",
                "EndpointID": "7e8a0454355cf75e6af62da70ac7f75889350dd3a9e8e028112a9aff8991baea",
                "MacAddress": "02:42:ac:14:00:03",
                "IPv4Address": "172.20.0.3/16",
                "IPv6Address": ""
            },
            "8d78c0afadb2c8086f6747ef726141bdb6d7bae43436a78a6c9a942b0d0279e9": {
                "Name": "charming_sanderson",
                "EndpointID": "e11d13680f0b2d715ed430160412c7b9d078d61813212c4338bb7a597fe146a3",
                "MacAddress": "02:42:ac:14:00:02",
                "IPv4Address": "172.20.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]

So I tried to change the base URL with :

http://localhost

http://127.0.0.1

the ip of the network

the ip of the mock container

the name of the network

the name of the mock container

the endpoint ID of the mock

the WSL gateway and the WSL2 IP address

I don't have service name, because I don't have docker-compose... but I really tried a lot of things. And have no more ideas, I'm going mad


问:
Mapping data in Jenkins
I'm trying to pass data to a pipeline with a map which the point is just to provide app name and environment and I will get all the other data I need to my main pipeline

I'm passing data to my deployment pipeline like so:

```<code>env.project_info= [
  git_path:"",
  git: "",
  config_branch: "",
  team_name: ""
]
</code>```

Which works but I want to change it.
I'm trying to change it into a map in which I will pass only the app name and env and it will pass me all the data above.

Does someone have any tips on how to do it?

Title: Mapping data in Jenkins

Body:
I'm trying to pass data to a pipeline with a map which the point is just to provide app name and environment and I will get all the other data I need to my main pipeline

I'm passing data to my deployment pipeline like so:

env.project_info= [
  git_path:"",
  git: "",
  config_branch: "",
  team_name: ""
]

Which works but I want to change it.
I'm trying to change it into a map in which I will pass only the app name and env and it will pass me all the data above.

Does someone have any tips on how to do it?


问:
Hex colour display/picker selection in Chrome & Edge differ to Firefox
We have an application whereby users can apply their own colour branding.  This is applied via CSS variables that get overwritten as the page renders.  Users get standard colours if they don't rebrand.

I notice however that some colours display completely differently in Chrome/Edge than they do in Firefox.  We have observed this behaviour on three separate machines.

```<code>div {
  height: 5em;
  padding: 1em;
  margin: 1em;
}

.DivOne {
  background-color: #0093f0;
  /* Displays as #0996ec in Chrome, and then gets read back
     in as a different colour using colour picker */
}
</code>```

I isolated the differences in a fiddle and using the Windows PowerToys color picker, the following test was done on a single monitor with no colour profile/driver tweaks with the browsers side-by-side.

Note that Chrome on the left is not (seemingly) displaying the colour accurately:

Even stranger (to me) - if I inspect the coloured element in Chrome and use the development tools picker, Chrome actually reads it back in is a different colour:

Can anyone please explain the discrepancy and offer a solution/advice?

Updated

Changing my search terms, I see that this is a problem in Chrome that's arisen many times in the last decade caused by its own colour profile usage:

Fix weird colors in Chrome in just a few clicks

Color picker on chrome gives wrong values

However, based on that information I'm still unsure why:

Chrome would pick a colour differently to that which it displays, and

Chrome Flags settings states, "Forces Chrome to use a specific color profile instead of the color of the window's current monitor, as specified by the operating system" and that is on Default means there should be no difference between the two browsers

...so I am leaving the question open.

Rant alert: As this didn't used to be an issue, it seems totally unacceptable to force Chrome users to start changing colour profiles.

Body:
We have an application whereby users can apply their own colour branding.  This is applied via CSS variables that get overwritten as the page renders.  Users get standard colours if they don't rebrand.

I notice however that some colours display completely differently in Chrome/Edge than they do in Firefox.  We have observed this behaviour on three separate machines.

div {
  height: 5em;
  padding: 1em;
  margin: 1em;
}

.DivOne {
  background-color: #0093f0;
  /* Displays as #0996ec in Chrome, and then gets read back
     in as a different colour using colour picker */
}

I isolated the differences in a fiddle and using the Windows PowerToys color picker, the following test was done on a single monitor with no colour profile/driver tweaks with the browsers side-by-side.

Note that Chrome on the left is not (seemingly) displaying the colour accurately:

Even stranger (to me) - if I inspect the coloured element in Chrome and use the development tools picker, Chrome actually reads it back in is a different colour:

Can anyone please explain the discrepancy and offer a solution/advice?

Updated

Changing my search terms, I see that this is a problem in Chrome that's arisen many times in the last decade caused by its own colour profile usage:

Fix weird colors in Chrome in just a few clicks

Color picker on chrome gives wrong values

However, based on that information I'm still unsure why:

Chrome would pick a colour differently to that which it displays, and

Chrome Flags settings states, "Forces Chrome to use a specific color profile instead of the color of the window's current monitor, as specified by the operating system" and that is on Default means there should be no difference between the two browsers

...so I am leaving the question open.

Rant alert: As this didn't used to be an issue, it seems totally unacceptable to force Chrome users to start changing colour profiles.


问:
calculating total on form input with angular js
i found an error in my code, i want to make it calculate the value automatically based on what we input in the form. I want to calculate the total based on what I input, instead the system combines the data instead of calculating the amount. please help me guys.

this my ts script.

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
import { Subject } from 'rxjs';
import { takeUntil, tap } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ComposerServices } from 'app/modules/admin/recruitment/kandidat/compose/compose.service';
import Swal from 'sweetalert2';
import { Router } from '@angular/router';

@Component({
    selector: 'mailbox-compose',
    templateUrl: './compose.component.html',
    encapsulation: ViewEncapsulation.None
})
export class MailboxComposeComponent implements OnInit {
    composeForm: FormGroup;

    private _unsubscribeAll: Subject<any> = new Subject<any>();

    /**
     * Constructor
     */
    constructor(
        public matDialogRef: MatDialogRef<MailboxComposeComponent>,
        private _http: HttpClient,
        private _composerService: ComposerServices,
        private _formBuilder: FormBuilder,
        private _router: Router

    ) { }

    /**
     * On init
     */
    ngOnInit(): void {

        this.composeForm = this._formBuilder.group({
            jobscope: ['', [Validators.required]],
            comben: ['', [Validators.required]],
            adaptability: ['', [Validators.required]],
            mkerja: ['', [Validators.required]],
        });
    }

    /**
     * On destroy
     */
    ngOnDestroy(): void {
        this._unsubscribeAll.next(null);
        this._unsubscribeAll.complete();
    }

    // -----------------------------------------------------------------------------------------------------
    // @ Public methods
    // -----------------------------------------------------------------------------------------------------

    /**
     * Save and close
     */
    saveAndClose(): void {
        // Close the dialog
        this.matDialogRef.close();
    }
</code>```

Script .html

```<code><div class="flex flex-col -m-6 event-div-dialog" style="width: 1060px; height:100%;">
  <!-- Compose div -->
  <mat-dialog-content
    class="mat-dialog-content p-6 pb-0 m-0 flex sm:flex-row xs:flex-col flex-wrap justify-items-center">

    <form class="flex flex-col flex-auto overflow-y-auto mt-2" [formGroup]="composeForm">
      <div class="flex flex-row gap-12">
        <div class="row ">
          <div class="col-11 w-full">
            <mat-form-field class="mr-2 w-80" appearance="outline" style="font-size: 12px;">
              <mat-label style="font-size: 14px !important;">Jobscope
              </mat-label>
              <input matInput [formControlName]="'jobscope'" #jobscope>
            </mat-form-field>
            <mat-form-field class="mr-2 w-80" appearance="outline" style="font-size: 12px;">
              <mat-label style="font-size: 14px !important;">Comben
              </mat-label>
              <input matInput [formControlName]="'comben'" #comben>
            </mat-form-field>
          </div>
          <div class="row ">
            <mat-form-field class="mr-2 w-80" appearance="outline" style="font-size: 12px;">
              <mat-label style="font-size: 14px !important;">
                Total Score
              </mat-label>
              <input matInput type="number" [formControlName]="'score'" value="{{jobscope.value + comben.value}}">
            </mat-form-field>
          </div>
        </div>
      </div>
    </form>
  </mat-dialog-content>
</div>
</code>```

the result that I get now, when I input a value of 4 and input 4, the result that I get is 44 the result I want 8. please help

Body:
i found an error in my code, i want to make it calculate the value automatically based on what we input in the form. I want to calculate the total based on what I input, instead the system combines the data instead of calculating the amount. please help me guys.

this my ts script.

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
import { Subject } from 'rxjs';
import { takeUntil, tap } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ComposerServices } from 'app/modules/admin/recruitment/kandidat/compose/compose.service';
import Swal from 'sweetalert2';
import { Router } from '@angular/router';

@Component({
    selector: 'mailbox-compose',
    templateUrl: './compose.component.html',
    encapsulation: ViewEncapsulation.None
})
export class MailboxComposeComponent implements OnInit {
    composeForm: FormGroup;

    private _unsubscribeAll: Subject<any> = new Subject<any>();

    /**
     * Constructor
     */
    constructor(
        public matDialogRef: MatDialogRef<MailboxComposeComponent>,
        private _http: HttpClient,
        private _composerService: ComposerServices,
        private _formBuilder: FormBuilder,
        private _router: Router

    ) { }

    /**
     * On init
     */
    ngOnInit(): void {

        this.composeForm = this._formBuilder.group({
            jobscope: ['', [Validators.required]],
            comben: ['', [Validators.required]],
            adaptability: ['', [Validators.required]],
            mkerja: ['', [Validators.required]],
        });
    }

    /**
     * On destroy
     */
    ngOnDestroy(): void {
        this._unsubscribeAll.next(null);
        this._unsubscribeAll.complete();
    }

    // -----------------------------------------------------------------------------------------------------
    // @ Public methods
    // -----------------------------------------------------------------------------------------------------

    /**
     * Save and close
     */
    saveAndClose(): void {
        // Close the dialog
        this.matDialogRef.close();
    }

Script .html

  <mat-dialog-content
    class="mat-dialog-content p-6 pb-0 m-0 flex sm:flex-row xs:flex-col flex-wrap justify-items-center">

    <form class="flex flex-col flex-auto overflow-y-auto mt-2" [formGroup]="composeForm">

            <mat-form-field class="mr-2 w-80" appearance="outline" style="font-size: 12px;">
              <mat-label style="font-size: 14px !important;">Jobscope
              </mat-label>
              <input matInput [formControlName]="'jobscope'" #jobscope>
            </mat-form-field>
            <mat-form-field class="mr-2 w-80" appearance="outline" style="font-size: 12px;">
              <mat-label style="font-size: 14px !important;">Comben
              </mat-label>
              <input matInput [formControlName]="'comben'" #comben>
            </mat-form-field>

            <mat-form-field class="mr-2 w-80" appearance="outline" style="font-size: 12px;">
              <mat-label style="font-size: 14px !important;">
                Total Score
              </mat-label>
              <input matInput type="number" [formControlName]="'score'" value="{{jobscope.value + comben.value}}">
            </mat-form-field>

    </form>
  </mat-dialog-content>

the result that I get now, when I input a value of 4 and input 4, the result that I get is 44 the result I want 8. please help


问:
SageMaker Labelling job: Create_labelling_job() fails
I am trying to create a labelling job on SageMaker for labelling the images by drawing a bounding box around it. I have successfully created one from the AWS console but I am unable to make it successful using the boto3 function create_labeling_job() .

Here is the code and the function parameters I used. They are similar to the example from the GitHub amazon-sagemaker-examples but unfortunately it did not work as expected. I can create the job, label the images and the status of the job gets completed. But the output manifest file does not store the annotations numbers.

```<code>task_description = "Draw bounding box around the images"
task_keywords = ['Images', 'bounding boxes', 'object detection']
task_title = "Bounding Box task"
job_name = "test-labeling-job"
acs_arn = "arn:aws:lambda:eu-west-1:568282634449:function:ACS-BoundingBox"
prehuman_arn = "arn:aws:lambda:eu-west-1:568282634449:function:PRE-BoundingBox"

human_task_config = {
"AnnotationConsolidationConfig": {
"AnnotationConsolidationLambdaArn": acs_arn,
},
"PreHumanTaskLambdaArn": prehuman_arn,
"MaxConcurrentTaskCount": 1000, # 200 images will be sent at a time to the workteam.
"NumberOfHumanWorkersPerDataObject": 1, # 3 separate workers will be required to label each image.
"TaskAvailabilityLifetimeInSeconds": 864000, # Your workteam has 6 hours to complete all pending tasks.
"TaskDescription": task_description,
"TaskKeywords": task_keywords,
"TaskTimeLimitInSeconds": 3600, # Each image must be labeled within 5 minutes.
"TaskTitle": task_title,
"UiConfig": {
"UiTemplateS3Uri": "s3://bucket-name/bounding-box.liquid.html",
},
"WorkteamArn": "arn:aws:sagemaker:eu-west-1:xxxxxxxxx:workteam/private-crowd/Labellers"
}

ground_truth_request = {
"InputConfig": {
"DataSource": {
"S3DataSource": {
"ManifestS3Uri": "s3://bucket-name/manifest-vic-2.manifest",
}
},
"DataAttributes": {
"ContentClassifiers": []
},
},
"OutputConfig": {
"S3OutputPath": "s3://sagemaker-bucket-name/folder-name-07-12-2022/",
},
"StoppingConditions":{
'MaxPercentageOfInputDatasetLabeled': 100
},
"HumanTaskConfig": human_task_config,
"LabelingJobName": job_name,
"RoleArn": "arn:aws:iam::xxxxxxxxx:role/service-role/AmazonSageMaker-ExecutionRole-xxxxxxxxxx",
"LabelAttributeName": job_name,
"LabelCategoryConfigS3Uri": "s3://bucket-name/label-config.json",
}

sagemaker_client = boto3.client("sagemaker")
sagemaker_client.create_labeling_job(**ground_truth_request)
</code>```

My label config file looks like the following:

```<code>{
"document-version": "2018-11-28",
"labels": [{"label": "animal"}, {"label": "no-animal"}]
}
</code>```

The manifest file looks like:

```<code>{'source-ref': 's3://sagemaker-inout-folder/2022-10-10-12:50:59/A.jpg'}
{'source-ref': 's3://sagemaker-inout-folder/2022-10-10-12:50:59/B.jpg'}
{'source-ref': 's3://sagemaker-inout-folder/2022-10-10-12:50:59/C.jpg'}
</code>```

And the HTML file is a standard crowd liquid files taken from the github sagemaker examples:

```<code><script src="https://assets.crowd.aws/crowd-html-elements.js"></script>

<crowd-form>
  <crowd-bounding-box
    name="annotatedResult"
    src="{{ task.input.taskObject | grant_read_access }}"
    header="Draw bounding boxes around all the cats and dogs in this image"
    labels="['Animal', 'No-animal']"
  >
    <full-instructions header="Bounding Box Instructions" >
      <p>Use the bounding box tool to draw boxes around the requested target of interest:</p>
      <ol>
        <li>Draw a rectangle using your mouse over each instance of the target.</li>
        <li>Make sure the box does not cut into the target, leave a 2 - 3 pixel margin</li>
        <li>
          When targets are overlapping, draw a box around each object,
          include all contiguous parts of the target in the box.
          Do not include parts that are completely overlapped by another object.
        </li>
        <li>
          Do not include parts of the target that cannot be seen,
          even though you think you can interpolate the whole shape of the target.
        </li>
        <li>Avoid shadows, they're not considered as a part of the target.</li>
        <li>If the target goes off the screen, label up to the edge of the image.</li>
      </ol>
    </full-instructions>

    <short-instructions>
      Draw boxes around the requested target of interest.
    </short-instructions>
  </crowd-bounding-box>
</crowd-form>
</code>```

Once this function is executd, I am able to label the images and the labelling job status changes to 'COMPLETE'. But the output manifest files looks like the following:

```<code>{
   "source-ref": "s3://sagemaker-inout-folder/2022-10-10-12:50:59/A.jpg",
   "test-labeling-job": {
      "image_size": [
            { "width": 0, "height": 0, "depth": 3 } ],
      "annotations": [] },
   "test-labeling-job-metadata": {
        "objects": [],
        "class-map": {},
        "type": "groundtruth/object-detection",
        "human-annotated": "yes",
        "creation-date": "2022-12-01T08:09:07.933647",
        "job-name": "labeling-job/test-labeling-job"
   }
}
</code>```

The image size is weird and the annotations are empty.

Can someone help me if I am doing anything wrong and how do I make this work?

Thank you in advance!

Body:
I am trying to create a labelling job on SageMaker for labelling the images by drawing a bounding box around it. I have successfully created one from the AWS console but I am unable to make it successful using the boto3 function create_labeling_job() .

Here is the code and the function parameters I used. They are similar to the example from the GitHub amazon-sagemaker-examples but unfortunately it did not work as expected. I can create the job, label the images and the status of the job gets completed. But the output manifest file does not store the annotations numbers.

task_description = "Draw bounding box around the images"
task_keywords = ['Images', 'bounding boxes', 'object detection']
task_title = "Bounding Box task"
job_name = "test-labeling-job"
acs_arn = "arn:aws:lambda:eu-west-1:568282634449:function:ACS-BoundingBox"
prehuman_arn = "arn:aws:lambda:eu-west-1:568282634449:function:PRE-BoundingBox"

human_task_config = {
"AnnotationConsolidationConfig": {
"AnnotationConsolidationLambdaArn": acs_arn,
},
"PreHumanTaskLambdaArn": prehuman_arn,
"MaxConcurrentTaskCount": 1000, # 200 images will be sent at a time to the workteam.
"NumberOfHumanWorkersPerDataObject": 1, # 3 separate workers will be required to label each image.
"TaskAvailabilityLifetimeInSeconds": 864000, # Your workteam has 6 hours to complete all pending tasks.
"TaskDescription": task_description,
"TaskKeywords": task_keywords,
"TaskTimeLimitInSeconds": 3600, # Each image must be labeled within 5 minutes.
"TaskTitle": task_title,
"UiConfig": {
"UiTemplateS3Uri": "s3://bucket-name/bounding-box.liquid.html",
},
"WorkteamArn": "arn:aws:sagemaker:eu-west-1:xxxxxxxxx:workteam/private-crowd/Labellers"
}

ground_truth_request = {
"InputConfig": {
"DataSource": {
"S3DataSource": {
"ManifestS3Uri": "s3://bucket-name/manifest-vic-2.manifest",
}
},
"DataAttributes": {
"ContentClassifiers": []
},
},
"OutputConfig": {
"S3OutputPath": "s3://sagemaker-bucket-name/folder-name-07-12-2022/",
},
"StoppingConditions":{
'MaxPercentageOfInputDatasetLabeled': 100
},
"HumanTaskConfig": human_task_config,
"LabelingJobName": job_name,
"RoleArn": "arn:aws:iam::xxxxxxxxx:role/service-role/AmazonSageMaker-ExecutionRole-xxxxxxxxxx",
"LabelAttributeName": job_name,
"LabelCategoryConfigS3Uri": "s3://bucket-name/label-config.json",
}

sagemaker_client = boto3.client("sagemaker")
sagemaker_client.create_labeling_job(**ground_truth_request)

My label config file looks like the following:

{
"document-version": "2018-11-28",
"labels": [{"label": "animal"}, {"label": "no-animal"}]
}

The manifest file looks like:

{'source-ref': 's3://sagemaker-inout-folder/2022-10-10-12:50:59/A.jpg'}
{'source-ref': 's3://sagemaker-inout-folder/2022-10-10-12:50:59/B.jpg'}
{'source-ref': 's3://sagemaker-inout-folder/2022-10-10-12:50:59/C.jpg'}

And the HTML file is a standard crowd liquid files taken from the github sagemaker examples:

<crowd-form>
  <crowd-bounding-box
    name="annotatedResult"
    src="{{ task.input.taskObject | grant_read_access }}"
    header="Draw bounding boxes around all the cats and dogs in this image"
    labels="['Animal', 'No-animal']"
  >
    <full-instructions header="Bounding Box Instructions" >

Use the bounding box tool to draw boxes around the requested target of interest:

Draw a rectangle using your mouse over each instance of the target.

Make sure the box does not cut into the target, leave a 2 - 3 pixel margin

          When targets are overlapping, draw a box around each object,
          include all contiguous parts of the target in the box.
          Do not include parts that are completely overlapped by another object.

          Do not include parts of the target that cannot be seen,
          even though you think you can interpolate the whole shape of the target.

Avoid shadows, they're not considered as a part of the target.

If the target goes off the screen, label up to the edge of the image.

    </full-instructions>

    <short-instructions>
      Draw boxes around the requested target of interest.
    </short-instructions>
  </crowd-bounding-box>
</crowd-form>

Once this function is executd, I am able to label the images and the labelling job status changes to 'COMPLETE'. But the output manifest files looks like the following:

{
   "source-ref": "s3://sagemaker-inout-folder/2022-10-10-12:50:59/A.jpg",
   "test-labeling-job": {
      "image_size": [
            { "width": 0, "height": 0, "depth": 3 } ],
      "annotations": [] },
   "test-labeling-job-metadata": {
        "objects": [],
        "class-map": {},
        "type": "groundtruth/object-detection",
        "human-annotated": "yes",
        "creation-date": "2022-12-01T08:09:07.933647",
        "job-name": "labeling-job/test-labeling-job"
   }
}

The image size is weird and the annotations are empty.

Can someone help me if I am doing anything wrong and how do I make this work?

Thank you in advance!


问:
How to control ionic accordion vuejs cannot reading $el
I am trying to control the accordion expand or collapse but I cant use guide from docs it come out with below image error >>> IonicFrameWork Doc I am using same code with the guide.

```<code>const accordionGroup = ref(null);
  const toggleAccordion = () => {
    if (!accordionGroup.value) {
      return;
    }
    const nativeEl = accordionGroup.value.$el;

    if (nativeEl.value === 'second') {
      nativeEl.value = undefined;
    } else {
      nativeEl.value = 'second';
    }
  };
</code>```

//html

```<code><ion-accordion-group ref="accordionGroup" :value="['first']">
    <ion-accordion value="first">
      <ion-item slot="header" color="secondary">
        <ion-label>Click here select shop type</ion-label>
      </ion-item>
      <div slot="content">
        Hello World
      </div>
    </ion-accordion>
  </ion-accordion-group>
</code>```

Body:
I am trying to control the accordion expand or collapse but I cant use guide from docs it come out with below image error >>> IonicFrameWork Doc I am using same code with the guide.

const accordionGroup = ref(null);
  const toggleAccordion = () => {
    if (!accordionGroup.value) {
      return;
    }
    const nativeEl = accordionGroup.value.$el;

    if (nativeEl.value === 'second') {
      nativeEl.value = undefined;
    } else {
      nativeEl.value = 'second';
    }
  };

//html

<ion-accordion-group ref="accordionGroup" :value="['first']">
    <ion-accordion value="first">
      <ion-item slot="header" color="secondary">
        <ion-label>Click here select shop type</ion-label>
      </ion-item>

        Hello World

    </ion-accordion>
  </ion-accordion-group>


问:
Ingress Nginx giving 503 on digital ocean
I have a simple configuration of a deployment, service and ingress service

app-depl.yaml

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: app
  template:
    metadata:
      labels:
        app: app
    spec:
      containers:
        - name: app
          image: keysoutsourcedocker/app
---
apiVersion: v1
kind: Service
metadata:
  name: app-srv
spec:
  selector:
    app: app
  ports:
    - name: app
      protocol: TCP
      port: 3000
      targetPort: 3000
</code>```

ingress-srv.yaml

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: 'true'
spec:
  rules:
    - host: www.keyssoft.xyz
      http:
        paths:
          - path: /?(.*)
            pathType: Prefix
            backend:
              service:
                name: app-srv
                port:
                  number: 3000
</code>```

And my DNS config goes like this
enter image description here

But when i try to access www.keyssoft.xyz i get this 503 error
enter image description here

I've been on this for the past 14 hours. Any help would be appreciated.

Body:
I have a simple configuration of a deployment, service and ingress service

app-depl.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: app
  template:
    metadata:
      labels:
        app: app
    spec:
      containers:
        - name: app
          image: keysoutsourcedocker/app
---
apiVersion: v1
kind: Service
metadata:
  name: app-srv
spec:
  selector:
    app: app
  ports:
    - name: app
      protocol: TCP
      port: 3000
      targetPort: 3000

ingress-srv.yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: 'true'
spec:
  rules:
    - host: www.keyssoft.xyz
      http:
        paths:
          - path: /?(.*)
            pathType: Prefix
            backend:
              service:
                name: app-srv
                port:
                  number: 3000

And my DNS config goes like this
enter image description here

But when i try to access www.keyssoft.xyz i get this 503 error
enter image description here

I've been on this for the past 14 hours. Any help would be appreciated.


问:
error: (-215:Assertion failed) Yolov5 Readnet Error
```<code>from PyQt5 import QtGui, QtWidgets, uic
from PyQt5.QtGui import QPixmap
import sys
import cv2 #opencv-python==4.5.3
import time
from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QThread
from PyQt5.QtWidgets import QApplication, QWidget, QListWidget, QLabel, QVBoxLayout
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QPlainTextEdit,
                                QVBoxLayout, QWidget)
from PyQt5.QtCore import QProcess
import numpy as np
import sqlite3
from numpy.core.records import array
import torch

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

stop_threads = False
class VideoThread(QThread):
    CONFIDENCE_THRESHOLD = 0.2
    NMS_THRESHOLD = 0.4
    COLORS = [(0, 255, 255), (255, 255, 0), (0, 255, 0), (255, 0, 0)]
    frame_counter=0
    class_names = []
    with open("backup/coco.names",'r') as f:
        class_names = [cname.strip() for cname in f.readlines()]
    #net = torch.hub.load('C:/Users/Niko/Desktop/Versuch/backup/custom_yolov5s.yaml', 'custom', 'C:/Users/Niko/Desktop/Versuch/backup/best_Neu.pt', force_reload=true)
    net = cv2.dnn.readNetFromONNX(r'C:/Users/Niko/Desktop/Versuch/backup/best.onnx') #r'C:/Users/Niko/Desktop/Versuch/backup/yolov5s.onnx',
    #net = cv2.dnn.readNet("C:/Users/Niko/Desktop/Versuch/backup/yolov4-tiny-custom_NEU.cfg", r"C:/Users/Niko/Desktop/Versuch/backup/best_Neu.pt", 'custom', source = 'local', path='last' ) #sonst (backup/yolo.weights)"
    try:
        net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
        net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
        print("Using GPU")
    except print(0):
        print("Using CPU")

    model = cv2.dnn_DetectionModel(net)
    #model.setInputParams(size=(640,640), scale=1/255, swapRB=True) #416,416
    model.setBlob(size=(640,640), scale=1/255, swapRB=True) #416,416

    change_pixmap_signal = pyqtSignal(np.ndarray)
    #ekran_goruntusu_ates_signal = pyqtSignal(np.ndarray)
    screenshot_fire_signal = pyqtSignal(np.ndarray)
    #ekran_goruntusu_duman_signal = pyqtSignal(np.ndarray)
    screenshot_smoke_signal = pyqtSignal(np.ndarray)
    #konsol_signal=pyqtSignal(str)
    konsolen_signal=pyqtSignal(str)
    #nesne_ismi_signal = pyqtSignal(str,int)
    objektname_signal = pyqtSignal(str,int)
    def run(self):
        global stop_threads
        vc = cv2.VideoCapture("drohnenvideo_feuer1080.mp4")

        while cv2.waitKey(1) < 1:
            (grabbed, frame) = vc.read()
            if grabbed:
                frame=self.window_in(frame)
                self.change_pixmap_signal.emit(frame)
                if stop_threads:
                    break
        vc.release()

</code>```

I want to build an custom object detection and therefore trained a Yolov5 model on a custom data set. and recieved the best weights and converted them into .onnx. This Code is working for yolov4 but for yolov5 i converted it to .onnx but unfortunately it stills brings me an error

cv2.error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-sn_xpupm\opencv\modules\dnn\src\onnx\onnx_importer.cpp:2146: error: (-2:Unspecified error) in function 'cv::dnn::dnn4_v20210608::ONNXImporter::handleNode'

Node [Identity]:(onnx::Reshape_582) parse error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-sn_xpupm\opencv\modules\dnn\src\dnn.cpp:5298: error: (-215:Assertion failed) inputs.size() in function 'cv::dnn::dnn4_v20210608::Layer::getMemoryShapes'

Body:
from PyQt5 import QtGui, QtWidgets, uic
from PyQt5.QtGui import QPixmap
import sys
import cv2 #opencv-python==4.5.3
import time
from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QThread
from PyQt5.QtWidgets import QApplication, QWidget, QListWidget, QLabel, QVBoxLayout
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QPlainTextEdit,
                                QVBoxLayout, QWidget)
from PyQt5.QtCore import QProcess
import numpy as np
import sqlite3
from numpy.core.records import array
import torch

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

stop_threads = False
class VideoThread(QThread):
    CONFIDENCE_THRESHOLD = 0.2
    NMS_THRESHOLD = 0.4
    COLORS = [(0, 255, 255), (255, 255, 0), (0, 255, 0), (255, 0, 0)]
    frame_counter=0
    class_names = []
    with open("backup/coco.names",'r') as f:
        class_names = [cname.strip() for cname in f.readlines()]
    #net = torch.hub.load('C:/Users/Niko/Desktop/Versuch/backup/custom_yolov5s.yaml', 'custom', 'C:/Users/Niko/Desktop/Versuch/backup/best_Neu.pt', force_reload=true)
    net = cv2.dnn.readNetFromONNX(r'C:/Users/Niko/Desktop/Versuch/backup/best.onnx') #r'C:/Users/Niko/Desktop/Versuch/backup/yolov5s.onnx',
    #net = cv2.dnn.readNet("C:/Users/Niko/Desktop/Versuch/backup/yolov4-tiny-custom_NEU.cfg", r"C:/Users/Niko/Desktop/Versuch/backup/best_Neu.pt", 'custom', source = 'local', path='last' ) #sonst (backup/yolo.weights)"
    try:
        net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
        net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
        print("Using GPU")
    except print(0):
        print("Using CPU")

    model = cv2.dnn_DetectionModel(net)
    #model.setInputParams(size=(640,640), scale=1/255, swapRB=True) #416,416
    model.setBlob(size=(640,640), scale=1/255, swapRB=True) #416,416

    change_pixmap_signal = pyqtSignal(np.ndarray)
    #ekran_goruntusu_ates_signal = pyqtSignal(np.ndarray)
    screenshot_fire_signal = pyqtSignal(np.ndarray)
    #ekran_goruntusu_duman_signal = pyqtSignal(np.ndarray)
    screenshot_smoke_signal = pyqtSignal(np.ndarray)
    #konsol_signal=pyqtSignal(str)
    konsolen_signal=pyqtSignal(str)
    #nesne_ismi_signal = pyqtSignal(str,int)
    objektname_signal = pyqtSignal(str,int)
    def run(self):
        global stop_threads
        vc = cv2.VideoCapture("drohnenvideo_feuer1080.mp4")

        while cv2.waitKey(1) < 1:
            (grabbed, frame) = vc.read()
            if grabbed:
                frame=self.window_in(frame)
                self.change_pixmap_signal.emit(frame)
                if stop_threads:
                    break
        vc.release()

I want to build an custom object detection and therefore trained a Yolov5 model on a custom data set. and recieved the best weights and converted them into .onnx. This Code is working for yolov4 but for yolov5 i converted it to .onnx but unfortunately it stills brings me an error

cv2.error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-sn_xpupm\opencv\modules\dnn\src\onnx\onnx_importer.cpp:2146: error: (-2:Unspecified error) in function 'cv::dnn::dnn4_v20210608::ONNXImporter::handleNode'

Node [Identity]:(onnx::Reshape_582) parse error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-sn_xpupm\opencv\modules\dnn\src\dnn.cpp:5298: error: (-215:Assertion failed) inputs.size() in function 'cv::dnn::dnn4_v20210608::Layer::getMemoryShapes'


问:
SignalR send server request and return value client
I am working with .net core 3,1 SignalR server-client application

How can I call server method with return value from client, which was written in C#?

I don't know how to do this

```<code>public String GetResponseFromUser(String userId, String request)
{
    // Use requestId to be sure the response is on this request
    var requestId = Guid.NewGuid().ToString();

    var hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
    hubContext.Clients.User(userId).Request(requestId, request);

    // Wait for client to send response to the Hub's Response method
    var response = ...?

    return response;
}
</code>```

How can I wait for the client response and use this response in my method outside the hub?

Body:
I am working with .net core 3,1 SignalR server-client application

How can I call server method with return value from client, which was written in C#?

I don't know how to do this

public String GetResponseFromUser(String userId, String request)
{
    // Use requestId to be sure the response is on this request
    var requestId = Guid.NewGuid().ToString();

    var hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
    hubContext.Clients.User(userId).Request(requestId, request);

    // Wait for client to send response to the Hub's Response method
    var response = ...?

    return response;
}

How can I wait for the client response and use this response in my method outside the hub?


问:
XMI editing : generating xmi:id and xsi:type fields
I have generated an ecore instance editor like described here :
use Ecore/XMI editor for instance creation from Ecore metamodel

However, when I edit the xmi file, I miss the xmi:id and xsi:type fields for the created instance

The expected output would be as follow :

```<code><room
  xsi:type="hm:Room"
  xmi:id="_zr9fYLCXEeq4o4cu21tguw"
  name="room1"/>
</code>```

Any idea how to configure ecore so that the generated xmi file include these fields?

Thanks

Body:
I have generated an ecore instance editor like described here :
use Ecore/XMI editor for instance creation from Ecore metamodel

However, when I edit the xmi file, I miss the xmi:id and xsi:type fields for the created instance

The expected output would be as follow :

<room
  xsi:type="hm:Room"
  xmi:id="_zr9fYLCXEeq4o4cu21tguw"
  name="room1"/>

Any idea how to configure ecore so that the generated xmi file include these fields?

Thanks