问:
PySimpleGUI: How does one bind an element in a tab environment?
I have a cashbook program that makes use of TABS to separate receipt entries from expense entries. In both the 'Receipts' and 'Expenses' tabs there is an Input element for entering a money value. I want to bind the element so that when losing focus it converts the figure entered to a format with 2 decimal places. (see:event=='-RECAMNT-FOCUS OUT':). The problem is that when I run the code an error comes up stating that you cannot perform operations on an element until read() is called or finalize=True when window is created.
The binding works perfectly in a program with just a main window (without tabs). Can anyone please tell me how to solve this problem? I am unable to add 'finalize=True' where the window creation has 3 layouts.
window =sg.Window('Cash Book',layout).Layout(tabgrp).layout(layout3)

I am posting extracted code to show where the problem appears to arise.

```<code>import PySimpleGUI as sg
import tkinter as tk
from tkinter import ttk
from tkcalendar import Calendar, DateEntry
import sqlite3
import datetime as dt
import time

sg.ChangeLookAndFeel('GreenTan')#LightGrey

menu_def = [['File', ['Open', 'Save', 'Exit'  ]],
           ['Edit', ['Add a Patient','Add a Supplier']],
           ['Reports',['Fuel uplifts by registration','Fuel uplift by Town']],
           ['Help', 'About...'], ]

conn=sqlite3.connect(r'/home/bushbug/Databases/FSCashBook')
cur=conn.cursor()
query=cur.execute("SELECT DISTINCT(pName)from Patients Order by pName ASC")
patient_data=[]

for row in cur.fetchall():
    patient_data.append(row[0])
    cur.close()

conn=sqlite3.connect(r'/home/bushbug/Databases/FSCashBook')
cur=conn.cursor()
query=cur.execute("SELECT DISTINCT(sName)from Suppliers Order by sName ASC")
supp_data=[]

for row in cur.fetchall():
    supp_data.append(row[0])
    cur.close()

conn= sqlite3.connect(r'/home/bushbug/Databases/FSCashBook')
cur=conn.cursor()
query=cur.execute("SELECT IncCat from Analyse where Indicator = 'I' ")
I_Analyse_data=[]

for row in cur.fetchall():
    I_Analyse_data.append(row[0])
    #return data
    cur.close()

conn= sqlite3.connect(r'/home/bushbug/Databases/FSCashBook')
cur=conn.cursor()
query=cur.execute("SELECT IncCat from Analyse where Indicator = 'E' ")
E_Analyse_data=[]

for row in cur.fetchall():
    E_Analyse_data.append(row[0])
    #return data
    cur.close()

conn= sqlite3.connect(r'/home/bushbug/Databases/FSCashBook')
cur=conn.cursor()
query=("SELECT fBal from FSCashBook ORDER by Id DESC LIMIT 1")
result=cur.execute(query)

for row in result:
    Balance=row[0]

conn= sqlite3.connect(r'/home/bushbug/Databases/FSCashBook')
cur=conn.cursor()
query=("SELECT tDate from FSCashBook WHERE tInd = 'I' ORDER by Id DESC LIMIT 1 ")
result=cur.execute(query)

for row in result:
    LastDate=row[0]

layout1=[
[sg.T('Last transaction date',key='-RECTRANSDT-'),sg.In(LastDate,key='-IN4-', size=(10,1)),sg.T('Patient name:'),sg.Combo(patient_data,size=(15,1),key='-PATIENT-'),sg.Push(),sg.T('Amount'),sg.In(size=15,key='-RECAMNT-')],
[sg.T('')],
[sg.T('Document No:         '),sg.In(size=8,key='-RECDOC-'),sg.T(''),sg.T('Procedure'),sg.In(size=20,key='-PROC-'),sg.Push(),sg.T('Analysis:'),sg.Combo(I_Analyse_data,size=20,key='-RECANALYSE-')],
[sg.T('')],
[sg.CalendarButton('Choose receipt date',button_color='blue', target='-IN4-', format='%Y-%m-%d'),sg.Push(),sg.Button('Next Receipt',button_color='purple'),sg.Button('SaveRec',button_color='green')]]

layout2=[
[sg.T('Last transaction date'),sg.In(key='-IN5-', size=(10,1)),sg.T('Supplier name:'),sg.Combo(supp_data,size=20,key='-SUPPLIER-'),sg.Push(),sg.T('Amount'),sg.In(size=15,key='-EXPAMNT-')],
[sg.T('')],
[sg.T('Document No:         '),sg.In(size=8,key='-EXPDOC-'),sg.T(''),sg.T('Transaction details'),sg.In(size=20,key='-TRANSDET-'),sg.Push(),sg.T('Analysis:'),sg.Combo(E_Analyse_data,size=20,key='-EXPANALYSE-')],
[sg.T('')],
[sg.CalendarButton('Choose expense date',button_color='blue',  target='-IN5-', format='%Y-%m-%d'),sg.Push(),sg.Button('Next Expense',button_color='purple'),sg.Button('SaveExp',button_color='green')]]

tabgrp=[[sg.TabGroup([[sg.Tab('Receipts',layout1,key='-RECEIPTS-'),#,title_color='Green',border_width=10,background_color='White',tooltip='Enter receipts',element_justification='centre'),
sg.Tab('Expenses',layout2,key='-EXPENSES-')]], tab_location='topleft',
                       title_color='Red', tab_background_color='Purple',selected_title_color='Green',
                       selected_background_color='Gray', border_width=5), sg.Button('Close')]]
layout3=[
[sg.T('Closing balance: '), sg.In(size=10,key='_CLOSBAL_')]]

layout=[
[sg.Menu(menu_def, )],
[sg.Push(),sg.T('FootSmart Cash Book',font=('Verdana',24,'bold'),text_color='turquoise'),sg.Push()],
[sg.Push(),sg.T('Enter transaction details in one of the TABS below',font=('Verdana',18,'bold'),text_color ='turquoise'),sg.Push()],
[sg.T('')],
[sg.T('')],
[sg.T('')],
[sg.T('Opening balance: '), sg.In(Balance,size=10,key='_OPBAL_')]
]

window =sg.Window('Cash Book',layout).Layout(tabgrp).layout(layout3)

window['-RECAMNT-'].bind('<FocusOut>','FOCUS OUT')

while True:
    event, values = window.read()
    print(event, values)
    if event in (sg.WIN_CLOSED, 'Cancel','Close'):
        break

    elif event=='-RECAMNT-FOCUS OUT':
        try:
            frecamnt = (values['-RECAMNT-'])
            frecamnt = "{: .2f}".format(float(frecamnt))
            window.find_element('-RECAMNT-').update(frecamnt)
            print(frecamnt)
            #continue
window.close()
</code>```

答:
Many of the Window methods require you to either call Window.read or Window.Finalize (or set finalize=True in your Window call) before you call the method. This is because these 2 calls are what actually creates the window using the underlying GUI Framework. Prior to one of those calls, the methods are likely to crash as they will not yet have their underlying widgets created.

My suggestion

window =sg.Window('Cash Book',layout).Layout(tabgrp).layout(layout3)

window['-RECAMNT-'].bind('<FocusOut>','FOCUS OUT')
```
<p>should be replaced by</p>
<pre class="lang-py prettyprint-override"><code>layout += tabgrp + layout3
window = sg.Window('Cash Book', layout, finalize=True)
window['-RECAMNT-'].bind('<FocusOut>','FOCUS OUT')
</code>```

Body:
I have a cashbook program that makes use of TABS to separate receipt entries from expense entries. In both the 'Receipts' and 'Expenses' tabs there is an Input element for entering a money value. I want to bind the element so that when losing focus it converts the figure entered to a format with 2 decimal places. (see:event=='-RECAMNT-FOCUS OUT':). The problem is that when I run the code an error comes up stating that you cannot perform operations on an element until read() is called or finalize=True when window is created.
The binding works perfectly in a program with just a main window (without tabs). Can anyone please tell me how to solve this problem? I am unable to add 'finalize=True' where the window creation has 3 layouts.
window =sg.Window('Cash Book',layout).Layout(tabgrp).layout(layout3)

I am posting extracted code to show where the problem appears to arise.

import PySimpleGUI as sg
import tkinter as tk
from tkinter import ttk
from tkcalendar import Calendar, DateEntry
import sqlite3
import datetime as dt
import time

sg.ChangeLookAndFeel('GreenTan')#LightGrey

menu_def = [['File', ['Open', 'Save', 'Exit'  ]],
           ['Edit', ['Add a Patient','Add a Supplier']],
           ['Reports',['Fuel uplifts by registration','Fuel uplift by Town']],
           ['Help', 'About...'], ]

conn=sqlite3.connect(r'/home/bushbug/Databases/FSCashBook')
cur=conn.cursor()
query=cur.execute("SELECT DISTINCT(pName)from Patients Order by pName ASC")
patient_data=[]

for row in cur.fetchall():
    patient_data.append(row[0])
    cur.close()

conn=sqlite3.connect(r'/home/bushbug/Databases/FSCashBook')
cur=conn.cursor()
query=cur.execute("SELECT DISTINCT(sName)from Suppliers Order by sName ASC")
supp_data=[]

for row in cur.fetchall():
    supp_data.append(row[0])
    cur.close()

conn= sqlite3.connect(r'/home/bushbug/Databases/FSCashBook')
cur=conn.cursor()
query=cur.execute("SELECT IncCat from Analyse where Indicator = 'I' ")
I_Analyse_data=[]

for row in cur.fetchall():
    I_Analyse_data.append(row[0])
    #return data
    cur.close()

conn= sqlite3.connect(r'/home/bushbug/Databases/FSCashBook')
cur=conn.cursor()
query=cur.execute("SELECT IncCat from Analyse where Indicator = 'E' ")
E_Analyse_data=[]

for row in cur.fetchall():
    E_Analyse_data.append(row[0])
    #return data
    cur.close()

conn= sqlite3.connect(r'/home/bushbug/Databases/FSCashBook')
cur=conn.cursor()
query=("SELECT fBal from FSCashBook ORDER by Id DESC LIMIT 1")
result=cur.execute(query)

for row in result:
    Balance=row[0]

conn= sqlite3.connect(r'/home/bushbug/Databases/FSCashBook')
cur=conn.cursor()
query=("SELECT tDate from FSCashBook WHERE tInd = 'I' ORDER by Id DESC LIMIT 1 ")
result=cur.execute(query)

for row in result:
    LastDate=row[0]

layout1=[
[sg.T('Last transaction date',key='-RECTRANSDT-'),sg.In(LastDate,key='-IN4-', size=(10,1)),sg.T('Patient name:'),sg.Combo(patient_data,size=(15,1),key='-PATIENT-'),sg.Push(),sg.T('Amount'),sg.In(size=15,key='-RECAMNT-')],
[sg.T('')],
[sg.T('Document No:         '),sg.In(size=8,key='-RECDOC-'),sg.T(''),sg.T('Procedure'),sg.In(size=20,key='-PROC-'),sg.Push(),sg.T('Analysis:'),sg.Combo(I_Analyse_data,size=20,key='-RECANALYSE-')],
[sg.T('')],
[sg.CalendarButton('Choose receipt date',button_color='blue', target='-IN4-', format='%Y-%m-%d'),sg.Push(),sg.Button('Next Receipt',button_color='purple'),sg.Button('SaveRec',button_color='green')]]

layout2=[
[sg.T('Last transaction date'),sg.In(key='-IN5-', size=(10,1)),sg.T('Supplier name:'),sg.Combo(supp_data,size=20,key='-SUPPLIER-'),sg.Push(),sg.T('Amount'),sg.In(size=15,key='-EXPAMNT-')],
[sg.T('')],
[sg.T('Document No:         '),sg.In(size=8,key='-EXPDOC-'),sg.T(''),sg.T('Transaction details'),sg.In(size=20,key='-TRANSDET-'),sg.Push(),sg.T('Analysis:'),sg.Combo(E_Analyse_data,size=20,key='-EXPANALYSE-')],
[sg.T('')],
[sg.CalendarButton('Choose expense date',button_color='blue',  target='-IN5-', format='%Y-%m-%d'),sg.Push(),sg.Button('Next Expense',button_color='purple'),sg.Button('SaveExp',button_color='green')]]

tabgrp=[[sg.TabGroup([[sg.Tab('Receipts',layout1,key='-RECEIPTS-'),#,title_color='Green',border_width=10,background_color='White',tooltip='Enter receipts',element_justification='centre'),
sg.Tab('Expenses',layout2,key='-EXPENSES-')]], tab_location='topleft',
                       title_color='Red', tab_background_color='Purple',selected_title_color='Green',
                       selected_background_color='Gray', border_width=5), sg.Button('Close')]]
layout3=[
[sg.T('Closing balance: '), sg.In(size=10,key='_CLOSBAL_')]]

layout=[
[sg.Menu(menu_def, )],
[sg.Push(),sg.T('FootSmart Cash Book',font=('Verdana',24,'bold'),text_color='turquoise'),sg.Push()],
[sg.Push(),sg.T('Enter transaction details in one of the TABS below',font=('Verdana',18,'bold'),text_color ='turquoise'),sg.Push()],
[sg.T('')],
[sg.T('')],
[sg.T('')],
[sg.T('Opening balance: '), sg.In(Balance,size=10,key='_OPBAL_')]
]

window =sg.Window('Cash Book',layout).Layout(tabgrp).layout(layout3)

window['-RECAMNT-'].bind('<FocusOut>','FOCUS OUT')

while True:
    event, values = window.read()
    print(event, values)
    if event in (sg.WIN_CLOSED, 'Cancel','Close'):
        break

    elif event=='-RECAMNT-FOCUS OUT':
        try:
            frecamnt = (values['-RECAMNT-'])
            frecamnt = "{: .2f}".format(float(frecamnt))
            window.find_element('-RECAMNT-').update(frecamnt)
            print(frecamnt)
            #continue
window.close()

Body:
Many of the Window methods require you to either call Window.read or Window.Finalize (or set finalize=True in your Window call) before you call the method. This is because these 2 calls are what actually creates the window using the underlying GUI Framework. Prior to one of those calls, the methods are likely to crash as they will not yet have their underlying widgets created.

My suggestion

window =sg.Window('Cash Book',layout).Layout(tabgrp).layout(layout3)

window['-RECAMNT-'].bind('<FocusOut>','FOCUS OUT')

should be replaced by

layout += tabgrp + layout3
window = sg.Window('Cash Book', layout, finalize=True)
window['-RECAMNT-'].bind('<FocusOut>','FOCUS OUT')


来源: stackexchange

问:
How to add CSS on specific element while using pseudo-class or pseudo element
This are 5 pieces a href and when hover unto them Hello World!! would show up unto there rigth side.. How can I make Hello World!!only show on Only Here when hover? Is there like

```<code><a style =":hover::after display: inline-block; content: "Hello World!!"; font-size: 16px; ... etc " href="#">
</code>```

POC coding argument of some sort to design specific element while using pseudo-class or pseudo element

a:hover::after {
  display: inline-block;
  content: "Hello World!!";
  font-size: 16px;
  font-weight: bold;
  padding-left: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Not Here<br>
Not Here<br>
Only Here<br>
Not Here<br>
Not Here<br></code>```

答:
Is this what you want to chieve?

a.hello:hover::after {
  display: inline-block;
  content: "Hello World!!";
  font-size: 16px;
  font-weight: bold;
  padding-left: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Not Here<br>
Not Here<br>
Only Here<br>
Not Here<br>
Not Here<br></code>```

ContentLicense: CC BY-SA 4.0

Body:
This are 5 pieces a href and when hover unto them Hello World!! would show up unto there rigth side.. How can I make Hello World!!only show on Only Here when hover? Is there like

POC coding argument of some sort to design specific element while using pseudo-class or pseudo element

a:hover::after {
  display: inline-block;
  content: "Hello World!!";
  font-size: 16px;
  font-weight: bold;
  padding-left: 5px;
}

Not Here

Not Here

Only Here

Not Here

Not Here

Body:
Is this what you want to chieve?

a.hello:hover::after {
  display: inline-block;
  content: "Hello World!!";
  font-size: 16px;
  font-weight: bold;
  padding-left: 5px;
}

<a href="#">Not Here</a><br>
<a href="#">Not Here</a><br>
<a class="hello" href="#">Only Here</a><br>
<a href="#">Not Here</a><br>
<a href="#">Not Here</a><br>


问:
SQL to compare 2 joins to the same table
I have a table that maps accounts to users. Accounts can have multiple users. User can be in multiple accounts.

```<code>account_id  | user_id
------------+---------
1234          a
1234          b
5678          c
6789          a
</code>```

For example, here user "a" is in accounts 1234 and 6789.

I have another table with account details.

```<code>account_id  | status     | ...
------------+------------+-----
1234          ACTIVE
5678          ACTIVE
6789          SUSPENDED
</code>```

I want to know all the users who are ACTIVE in one account while SUSPENDED in another account. (Any mix, if they're in more than 2 accounts.) In the above example, user "a" is ACTIVE in 1234 and SUSPENDED in 6789.

My attempt started as...

```<code>SELECT user_id FROM mappings
LEFT JOIN account_details AS x ON account_id = x.id AND x.status = 'ACTIVE'
LEFT JOIN account_details AS y ON account_id = y.id AND y.status = 'SUSPENDED'
</code>```

But that seems wrong and I don't know how I'd ensure the 2 joins are linked to the same user. There must be a different way to approach this problem that I'm not seeing.

Thanks for any hints.

答:
You can join the tables to aggregate by user and set the condition in the HAVING clause:

```<code>SELECT m.user_id
FROM mappings m INNER JOIN account_details a
ON a.account_id = m.account_id
WHERE a.status IN ('ACTIVE', 'SUSPENDED')
GROUP BY m.user_id
HAVING COUNT(DISTINCT a.status) = 2;
</code>```

If 'ACTIVE' and 'SUSPENDED' are the only possible values of the column status then you can omit the WHERE clause.

See the demo.

Body:
I have a table that maps accounts to users. Accounts can have multiple users. User can be in multiple accounts.

account_id  | user_id
------------+---------
1234          a
1234          b
5678          c
6789          a

For example, here user "a" is in accounts 1234 and 6789.

I have another table with account details.

account_id  | status     | ...
------------+------------+-----
1234          ACTIVE
5678          ACTIVE
6789          SUSPENDED

I want to know all the users who are ACTIVE in one account while SUSPENDED in another account. (Any mix, if they're in more than 2 accounts.) In the above example, user "a" is ACTIVE in 1234 and SUSPENDED in 6789.

My attempt started as...

SELECT user_id FROM mappings
LEFT JOIN account_details AS x ON account_id = x.id AND x.status = 'ACTIVE'
LEFT JOIN account_details AS y ON account_id = y.id AND y.status = 'SUSPENDED'

But that seems wrong and I don't know how I'd ensure the 2 joins are linked to the same user. There must be a different way to approach this problem that I'm not seeing.

Thanks for any hints.

Body:
You can join the tables to aggregate by user and set the condition in the HAVING clause:

SELECT m.user_id
FROM mappings m INNER JOIN account_details a
ON a.account_id = m.account_id
WHERE a.status IN ('ACTIVE', 'SUSPENDED')
GROUP BY m.user_id
HAVING COUNT(DISTINCT a.status) = 2;

If 'ACTIVE' and 'SUSPENDED' are the only possible values of the column status then you can omit the WHERE clause.

See the demo.


问:
Unable to activate instance of type Xamarin.Forms.Platform.Android.FastRenderers.FrameRenderer
I am having a issue with a Android app when I click a button that talks to the webservice and then click another button I get this exception.

Unable to activate instance of type
Xamarin.Forms.Platform.Android.FastRenderers.FrameRenderer from native
handle 0x7fcb566738 (key_handle 0x3ed634c).

The Exception appears to be coming from the following xaml

```<code>  <Frame x:Name="TileFrame" Margin="5" Grid.Column="0" Grid.Row="0"
           BindingContext="{x:Reference this}"
           effects:TouchEffect.Command="{Binding TapTile}"
           effects:TouchEffect.CommandParameter="{Binding}">
            <StackLayout VerticalOptions="Center">

                <Label
                    BindingContext="{x:Reference this}"
                    Text="{Binding Title}"
                    FontSize="20"
                    LineHeight="1"
                    FontAttributes="Bold"
                    TextTransform="Uppercase"
                    HorizontalTextAlignment="Center"
                    Opacity="1"
                    Margin="5, 0" />
            </StackLayout>
        </Frame>
</code>```

if I change the frame to a button I get the following exception

```<code>   <Button x:Name="TileFrame" Margin="5" Grid.Column="0" Grid.Row="0"
           BindingContext="{x:Reference this}"
           effects:TouchEffect.Command="{Binding TapTile}"
           effects:TouchEffect.CommandParameter="{Binding}">

        </Button>
</code>```

Unable to activate instance of type
Xamarin.Forms.Platform.Android.FastRenderers.ButtonRenderer from
native handle 0x7fcb55a1d8 (key_handle 0x46ac678).

I have found this on git hub but its from 2020 and I see to be having the same issue and so far the work arounds do not solve my issue

https://github.com/xamarin/Xamarin.Forms/issues/9136

答:
So after lots of digging. The app was doing things with the UI and not always on the UI thread. So wrapping the code in the following code it provided more stability for the app.

```<code>MainThread.BeginInvokeOnMainThread(() =>
{
    // Code to run on the main thread
});
</code>```

https://learn.microsoft.com/en-us/xamarin/essentials/main-thread

Body:
I am having a issue with a Android app when I click a button that talks to the webservice and then click another button I get this exception.

Unable to activate instance of type
Xamarin.Forms.Platform.Android.FastRenderers.FrameRenderer from native
handle 0x7fcb566738 (key_handle 0x3ed634c).

The Exception appears to be coming from the following xaml

  <Frame x:Name="TileFrame" Margin="5" Grid.Column="0" Grid.Row="0"
           BindingContext="{x:Reference this}"
           effects:TouchEffect.Command="{Binding TapTile}"
           effects:TouchEffect.CommandParameter="{Binding}">
            <StackLayout VerticalOptions="Center">

            </StackLayout>
        </Frame>

if I change the frame to a button I get the following exception

   <Button x:Name="TileFrame" Margin="5" Grid.Column="0" Grid.Row="0"
           BindingContext="{x:Reference this}"
           effects:TouchEffect.Command="{Binding TapTile}"
           effects:TouchEffect.CommandParameter="{Binding}">

        </Button>

Unable to activate instance of type
Xamarin.Forms.Platform.Android.FastRenderers.ButtonRenderer from
native handle 0x7fcb55a1d8 (key_handle 0x46ac678).

I have found this on git hub but its from 2020 and I see to be having the same issue and so far the work arounds do not solve my issue

https://github.com/xamarin/Xamarin.Forms/issues/9136

Body:
So after lots of digging. The app was doing things with the UI and not always on the UI thread. So wrapping the code in the following code it provided more stability for the app.

MainThread.BeginInvokeOnMainThread(() =>
{
    // Code to run on the main thread
});

https://learn.microsoft.com/en-us/xamarin/essentials/main-thread


问:
Failed to load config "react" to extend from
I am trying to create a react app without using create-react-app using the following website:

https://www.freecodecamp.org/news/how-to-set-up-deploy-your-react-app-from-scratch-using-webpack-and-babel-a669891033d4/

however, I keep getting this error that says

WARNING in ./src/index.js
Module Warning (from ./node_modules/eslint-loader/dist/cjs.js):
Failed to load config "react" to extend from.

I have tried installing all the dependencies and have spent hours googling an answer, but I can't seem to figure out the problem.

This is my package.json:

```<code>{
  "name": "xxx",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --mode development",
    "format": "prettier --write \"src/**/*.js\"",
    "eslint-fix": "eslint --fix \"src/**/*.js\"",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/plugin-proposal-class-properties": "^7.10.4",
    "react": "^16.13.1",
    "react-bootstrap": "^1.3.0",
    "react-dom": "^16.13.1"
  },
  "devDependencies": {
    "@babel/core": "^7.11.6",
    "@babel/preset-env": "^7.11.5",
    "@babel/preset-react": "^7.10.4",
    "babel-eslint": "^10.1.0",
    "babel-loader": "^8.1.0",
    "css-loader": "^4.3.0",
    "eslint": "^7.9.0",
    "eslint-config-react": "^1.1.7",
    "eslint-loader": "^4.0.2",
    "eslint-plugin-react": "^7.20.6",
    "html-webpack-plugin": "^4.4.1",
    "less": "^3.12.2",
    "less-loader": "^7.0.1",
    "prettier": "2.1.1",
    "style-loader": "^1.2.1",
    "webpack": "^4.44.1",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  }
}
</code>```

this is my webpack.config.js:

```<code>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: './src/index.js',
    output: {
      // path: __dirname + '/dist',
      path: path.resolve(__dirname, 'build'),
      publicPath: '/',
      filename: 'bundle.js'
    },
    devServer: {
      contentBase: './build'
    },
    module: {
      rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader', 'eslint-loader']
      },
      {
        test: /\.less$/,
        use: [
          'style-loader',
          'css-loader',
          'less-loader',
        ],
      }
      ]
    },
    plugins: [
        new HtmlWebpackPlugin({
          template: path.resolve('./index.html'),
        })],
  };
</code>```

this is my .eslintrc:

```<code>  {
  "parser": "babel-eslint",
  "extends": "react",
  "env": {
    "browser": true,
    "node": true
  },
  "settings": {
    "react": {
      "version": "detect"
    }
  }
}
</code>```

and this is my .babelrc:

```<code>{
    "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
    ],
    "plugins": [
      "@babel/plugin-proposal-class-properties"
    ]
  }
</code>```

Does anyone have any suggestions? I am wracking my brain trying to figure this out and I am having a lot of trouble. It loads the webpage, however, react isn't utilized at all.

Thank you in advance!! I really appreciate all your help.

答:
If you cloned the repo from GitHub or any other version control system, try adding this file .eslintrc.json to your root folder. Don't forget the . at the beginning.

The first answer works like a charm as well. Just thought I would add mine as well.

Body:
I am trying to create a react app without using create-react-app using the following website:

https://www.freecodecamp.org/news/how-to-set-up-deploy-your-react-app-from-scratch-using-webpack-and-babel-a669891033d4/

however, I keep getting this error that says

WARNING in ./src/index.js
Module Warning (from ./node_modules/eslint-loader/dist/cjs.js):
Failed to load config "react" to extend from.

I have tried installing all the dependencies and have spent hours googling an answer, but I can't seem to figure out the problem.

This is my package.json:

{
  "name": "xxx",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --mode development",
    "format": "prettier --write \"src/**/*.js\"",
    "eslint-fix": "eslint --fix \"src/**/*.js\"",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/plugin-proposal-class-properties": "^7.10.4",
    "react": "^16.13.1",
    "react-bootstrap": "^1.3.0",
    "react-dom": "^16.13.1"
  },
  "devDependencies": {
    "@babel/core": "^7.11.6",
    "@babel/preset-env": "^7.11.5",
    "@babel/preset-react": "^7.10.4",
    "babel-eslint": "^10.1.0",
    "babel-loader": "^8.1.0",
    "css-loader": "^4.3.0",
    "eslint": "^7.9.0",
    "eslint-config-react": "^1.1.7",
    "eslint-loader": "^4.0.2",
    "eslint-plugin-react": "^7.20.6",
    "html-webpack-plugin": "^4.4.1",
    "less": "^3.12.2",
    "less-loader": "^7.0.1",
    "prettier": "2.1.1",
    "style-loader": "^1.2.1",
    "webpack": "^4.44.1",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  }
}

this is my webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: './src/index.js',
    output: {
      // path: __dirname + '/dist',
      path: path.resolve(__dirname, 'build'),
      publicPath: '/',
      filename: 'bundle.js'
    },
    devServer: {
      contentBase: './build'
    },
    module: {
      rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader', 'eslint-loader']
      },
      {
        test: /\.less$/,
        use: [
          'style-loader',
          'css-loader',
          'less-loader',
        ],
      }
      ]
    },
    plugins: [
        new HtmlWebpackPlugin({
          template: path.resolve('./index.html'),
        })],
  };

this is my .eslintrc:

  {
  "parser": "babel-eslint",
  "extends": "react",
  "env": {
    "browser": true,
    "node": true
  },
  "settings": {
    "react": {
      "version": "detect"
    }
  }
}

and this is my .babelrc:

{
    "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
    ],
    "plugins": [
      "@babel/plugin-proposal-class-properties"
    ]
  }

Does anyone have any suggestions? I am wracking my brain trying to figure this out and I am having a lot of trouble. It loads the webpage, however, react isn't utilized at all.

Thank you in advance!! I really appreciate all your help.


问:
BASH SHELL SCRIPT to split a big xml file into multiple small files
I have a an XML file in below format

```<code><?xml version="1.0" encoding="utf-8" ?>
<parent>
    <child>
        <code></code>
        <text></text>
    </child>
    <child>
        <code></code>
        <text></text>
    </child>
 </parent>
</code>```

I need a BASH SHELL script to split this main xml file into multiple small XML files which should have contents from the <child> to </child> tag. File names could be parent file name plus a running serial number such as _1 for ex:20110721_1.xml etc..
Please help me with the script.

答:
Not pure answer but you can tune this yourself:

```<code>csplit -ksf part. src.xml /\<child\>/ "{100}" 2>/dev/null
</code>```

This command will split src.xml using regexp /\<child\>/ as a delimiter and produce 1..100 part.* files.
You need to play with regexp though...

ContentLicense: CC BY-SA 3.0

Body:
I have a an XML file in below format

<?xml version="1.0" encoding="utf-8" ?>
<parent>
    <child>

        <text></text>
    </child>
    <child>

        <text></text>
    </child>
 </parent>

I need a BASH SHELL script to split this main xml file into multiple small XML files which should have contents from the <child> to </child> tag. File names could be parent file name plus a running serial number such as _1 for ex:20110721_1.xml etc..
Please help me with the script.

Body:
Not pure answer but you can tune this yourself:

csplit -ksf part. src.xml /\<child\>/ "{100}" 2>/dev/null

This command will split src.xml using regexp /\<child\>/ as a delimiter and produce 1..100 part.* files.
You need to play with regexp though...


问:
Subsetting one list based on another list and then finding position of the maxima
UPDATED:
I have two lists that look like this:

```<code>MyList1<-list(c(0,1,1,1),c(1,1,2,0))
MyList2<-list(c(4,5,6,2),c(5,5,2,5))
</code>```

What I want to find are the positions in MyList2 of the maxima but only where the corresponding positions in MyList1 are >0. The result would be:

```<code>Result<-list(c(3),c())
</code>```

To explain further where this result comes from, if you first subset the second list where MyList1>0 then you would have:

```<code>list(c(5,6,2),c(5,5,2))
</code>```

The maximum element across both lists is 6 which only exists in list 1:

```<code>list(c(6),c())
</code>```

The position of this in MyList2 are:

```<code>list(c(3),c())
</code>```

I'm not sure of the best way to get to this desired result.

答:
Using mapply, you can do this:

m <- max(unlist(MyList2)[unlist(MyList1) > 0])
mapply(function(x,y) which(x == m & y > 0), MyList2, MyList1)

# [[1]]
# [1] 3
#
# [[2]]
# integer(0)
```
<hr />
<p>With <code>purrr::map2</code>:</p>
<pre class="lang-r prettyprint-override"><code>purrr::map2(MyList2, MyList1, function(x,y) which(x == m & y > 0))

#or

purrr::map2(MyList2, MyList1, ~ which(.x == m & .y > 0))
</code>```

data

MyList1<-list(c(0,1,1,1),c(1,1,2,0))
MyList2<-list(c(4,5,6,2),c(5,5,2,5))
```

Body:
UPDATED:
I have two lists that look like this:

MyList1<-list(c(0,1,1,1),c(1,1,2,0))
MyList2<-list(c(4,5,6,2),c(5,5,2,5))

What I want to find are the positions in MyList2 of the maxima but only where the corresponding positions in MyList1 are >0. The result would be:

Result<-list(c(3),c())

To explain further where this result comes from, if you first subset the second list where MyList1>0 then you would have:

list(c(5,6,2),c(5,5,2))

The maximum element across both lists is 6 which only exists in list 1:

list(c(6),c())

The position of this in MyList2 are:

list(c(3),c())

I'm not sure of the best way to get to this desired result.

Body:
Using mapply, you can do this:

m <- max(unlist(MyList2)[unlist(MyList1) > 0])
mapply(function(x,y) which(x == m & y > 0), MyList2, MyList1)

# [[1]]
# [1] 3
#
# [[2]]
# integer(0)

With purrr::map2:

purrr::map2(MyList2, MyList1, function(x,y) which(x == m & y > 0))

#or

purrr::map2(MyList2, MyList1, ~ which(.x == m & .y > 0))

data

MyList1<-list(c(0,1,1,1),c(1,1,2,0))
MyList2<-list(c(4,5,6,2),c(5,5,2,5))


问:
The type or namespace name 'Bind' and 'Include' in .Net Core
I am migrating a .Net Application to .Net Core. In .Net Application, we were using bind and include keyword on the top of a model class for the LoginInfo as below:

```<code>[Bind(Include = "UserName,Password")]
</code>```

But after conversion, it is showing this error:

The type or namespace name 'Bind' and 'Include' could not be found.

Can you suggest what can be added in place of those keywords in .Net core MVC.

答:
The Bind attribute exists in the Microsoft.AspNetCore.Mvc namespace meaning that you need to import it like this:

```<code>using Microsoft.AspNetCore.Mvc;
</code>```

If that isn't working, likely because this class exists in a class library outside of your ASP.NET Core web project, then you need to add a framework reference to Microsoft.AspNetCore.App. To do this, edit your csproj file and add this:

```<code><ItemGroup>
  <FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
</code>```

See here for more details.

Finally, you don't need to name the Include parameter, so it should simply look like this:

```<code>[Bind("UserName,Password")]
public class LoginInfo
{
    //snip...
</code>```

Body:
I am migrating a .Net Application to .Net Core. In .Net Application, we were using bind and include keyword on the top of a model class for the LoginInfo as below:

[Bind(Include = "UserName,Password")]

But after conversion, it is showing this error:

The type or namespace name 'Bind' and 'Include' could not be found.

Can you suggest what can be added in place of those keywords in .Net core MVC.

Body:
The Bind attribute exists in the Microsoft.AspNetCore.Mvc namespace meaning that you need to import it like this:

using Microsoft.AspNetCore.Mvc;

If that isn't working, likely because this class exists in a class library outside of your ASP.NET Core web project, then you need to add a framework reference to Microsoft.AspNetCore.App. To do this, edit your csproj file and add this:

<ItemGroup>
  <FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

See here for more details.

Finally, you don't need to name the Include parameter, so it should simply look like this:

[Bind("UserName,Password")]
public class LoginInfo
{
    //snip...


问:
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed; boundary
Currently I'm inline of writing a code that will be listening to a directory. when the directory is updated with .apk file, I'll send a mail with this .apk file to a gmail account. I'm using Jnotify and JAVA Mail in my program.

The Error I'm getting is,

```<code>javax.mail.MessagingException: IOException while sending message;
  nested exception is:
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed; boundary="----=_Part_0_145238.1392728439484"
</code>```

I looked for the solutions given in the stackoverflow for help but none of them where helpful.

Thanks in Advance

```<code>public void fileCreated(int wd, String rootPath, String name) {
    print("created " + rootPath + " : " + name);

    if (name.contains(".apk"))
      SendEmail(name);
    else
        System.out.println("Not the APK file");
}

void SendEmail(String strname){
    String Path = "D:/POC/Email/apk folder/"+strname;
    System.out.println("Path->" + Path);

    Properties props = new Properties();
    props.put("mail.smtp.host","173.194.78.108");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth","true");
    props.put("mail.smtp.port","465");

    System.out.println("Properties has been set properly");

    Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication("SenderEmailID@gmail.com", "senderPassword");
            }
        }
    );

    System.out.println("Session Created successfully");

    try{
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("SenderEmailID@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("ToReceiverEmailID@gmail.com"));
        message.setSubject("Android : " + strname);

        MimeBodyPart msgbody = new MimeBodyPart();
        msgbody.setText("This is the message content which is sent using JAVA MAIL 1.4.5");
        Multipart mulpart = new MimeMultipart();
        mulpart.addBodyPart(msgbody);

        //Attachement Starts here.
        msgbody = new MimeBodyPart();
        javax.activation.DataSource source = new FileDataSource(Path);
        msgbody.setDataHandler(new DataHandler(source));
        msgbody.setFileName(strname);
        message.setContent(mulpart);

        System.out.println("Attached the message going to start transporting the mail");

        //If I've the code before sending the email is getting sent but without attachment.
        //Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );

        Transport.send(message);
        System.out.println("Mail Sent successfully");
    }
    catch(MessagingException msg){
        msg.printStackTrace();
    }
    catch(Exception e){
        e.printStackTrace();
    }
}
</code>```

答:
If anyone encountered the problem after including Apache Tika 2, it could be due to a mail dependency embedded in Tika.

We manage to fix the issue by adding a Maven exclusion, leaving only javax.mail on classpath. Something like:

```<code><dependency>
  <groupId>org.apache.tika</groupId>
  <artifactId>tika-parsers-standard-package</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcmail-jdk15on</artifactId>
    </exclusion>
  </exclusions>
</dependency>
</code>```

Body:
Currently I'm inline of writing a code that will be listening to a directory. when the directory is updated with .apk file, I'll send a mail with this .apk file to a gmail account. I'm using Jnotify and JAVA Mail in my program.

The Error I'm getting is,

javax.mail.MessagingException: IOException while sending message;
  nested exception is:
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed; boundary="----=_Part_0_145238.1392728439484"

I looked for the solutions given in the stackoverflow for help but none of them where helpful.

Thanks in Advance

public void fileCreated(int wd, String rootPath, String name) {
    print("created " + rootPath + " : " + name);

    if (name.contains(".apk"))
      SendEmail(name);
    else
        System.out.println("Not the APK file");
}

void SendEmail(String strname){
    String Path = "D:/POC/Email/apk folder/"+strname;
    System.out.println("Path->" + Path);

    Properties props = new Properties();
    props.put("mail.smtp.host","173.194.78.108");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth","true");
    props.put("mail.smtp.port","465");

    System.out.println("Properties has been set properly");

    Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication("SenderEmailID@gmail.com", "senderPassword");
            }
        }
    );

    System.out.println("Session Created successfully");

    try{
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("SenderEmailID@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("ToReceiverEmailID@gmail.com"));
        message.setSubject("Android : " + strname);

        MimeBodyPart msgbody = new MimeBodyPart();
        msgbody.setText("This is the message content which is sent using JAVA MAIL 1.4.5");
        Multipart mulpart = new MimeMultipart();
        mulpart.addBodyPart(msgbody);

        //Attachement Starts here.
        msgbody = new MimeBodyPart();
        javax.activation.DataSource source = new FileDataSource(Path);
        msgbody.setDataHandler(new DataHandler(source));
        msgbody.setFileName(strname);
        message.setContent(mulpart);

        System.out.println("Attached the message going to start transporting the mail");

        //If I've the code before sending the email is getting sent but without attachment.
        //Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );

        Transport.send(message);
        System.out.println("Mail Sent successfully");
    }
    catch(MessagingException msg){
        msg.printStackTrace();
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

Body:
If anyone encountered the problem after including Apache Tika 2, it could be due to a mail dependency embedded in Tika.

We manage to fix the issue by adding a Maven exclusion, leaving only javax.mail on classpath. Something like:

<dependency>
  <groupId>org.apache.tika</groupId>
  <artifactId>tika-parsers-standard-package</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcmail-jdk15on</artifactId>
    </exclusion>
  </exclusions>
</dependency>


问:
Something from string in list python
I have a list with keywords id = ['pop','ppp','cre'] and now I am going through a bunch of files/large strings and if any of these keywords are in these files than I have to be able to do something...

like:

```<code>id = ['pop','ppp','cre']
if id in dataset:
         print id
</code>```

But i think now all of these 3 or later maybe more have to be in the dataset and not just only one.

答:
Since you mentioned that you need to check any word within dataset then I think any() built-in method will help:

```<code>if any(word in dataset for word in id):
    # do something
</code>```

Or:

```<code>if [word for word in id if word in dataset]:
    # do something
</code>```

And:

```<code>if filter(lambda word: word in dataset, id):
    # do something
</code>```

Title: Something from string in list python

Body:
I have a list with keywords id = ['pop','ppp','cre'] and now I am going through a bunch of files/large strings and if any of these keywords are in these files than I have to be able to do something...

like:

id = ['pop','ppp','cre']
if id in dataset:
         print id

But i think now all of these 3 or later maybe more have to be in the dataset and not just only one.

Body:
Since you mentioned that you need to check any word within dataset then I think any() built-in method will help:

if any(word in dataset for word in id):
    # do something

Or:

if [word for word in id if word in dataset]:
    # do something

And:

if filter(lambda word: word in dataset, id):
    # do something


问:
How to use the useState() with specific strings ("this" | "that")
I am trying to use the useState in React-native with TypeScript and want to use specific strings that can be used in a component. How can I do this?

I have this:

```<code>                                             |
                                             \/
const [getViewState, setViewState] = useState();
                 |
                 \/
<Icon name={getViewState} size={25} color={COLORS.light_gray}></Icon>

</code>```
```<code>type props = {
  style?: StyleProp<ImageStyle>;
  name: "add" | "check" | "down" | "home" | "lock" | "right" | "search" | "settings" | "user" | "grid" | "list";
  size: number;
  color: string;
  onPress?: Function;
};```
```

答:
If I've understood what you're trying to do, above where you've written the type for your Icon component's props, you can separate out the string type:

type IconName = 'add' | 'check' | 'down' // etc.

interface IconProps {
  name: IconName
  size: number
  // etc.
}
```
<p>And then, you can pass a type parameter to your <code>useState</code> call</p>
<pre class="lang-js prettyprint-override"><code>const [name, setName] = useState<IconName>('add')
                                    ^

<Icon name={name} size={25} color={COLORS.light_gray} />
</code>```

Body:
I am trying to use the useState in React-native with TypeScript and want to use specific strings that can be used in a component. How can I do this?

I have this:

                                             |
                                             \/
const [getViewState, setViewState] = useState();
                 |
                 \/
<Icon name={getViewState} size={25} color={COLORS.light_gray}></Icon>

type props = {
  style?: StyleProp<ImageStyle>;
  name: "add" | "check" | "down" | "home" | "lock" | "right" | "search" | "settings" | "user" | "grid" | "list";
  size: number;
  color: string;
  onPress?: Function;
};```

Body:
If I've understood what you're trying to do, above where you've written the type for your Icon component's props, you can separate out the string type:

type IconName = 'add' | 'check' | 'down' // etc.

interface IconProps {
  name: IconName
  size: number
  // etc.
}

And then, you can pass a type parameter to your useState call

const [name, setName] = useState<IconName>('add')
                                    ^

<Icon name={name} size={25} color={COLORS.light_gray} />


答:
useState Accepts a Generic type.

type MyType = "str1" | "str2"

useState<MyType | null>(null)

Thus you can spicify what kind of state you want.

In your example:

const [getViewState, setViewState] = useState<"string1" | "string2">("string1")
```

Title: How to use the useState() with specific strings ("this" | "that")


问:
React Hook error : Invalid hook call: mismatching versions of React and the renderer or breaking the Rules of Hooks or more than one copy of React
I'm fairly new to react and using hooks. I'm using downshift plugin and want to show a MultiSelection dropdown. I'm using hooks to do that but I keep getting this error in the browser:

Invalid hook call. Hooks can only be called inside of the body of a
function component. This could happen for one of the following
reasons:

You might have mismatching versions of React and the renderer (such as
React DOM) You might be breaking the Rules of Hooks You might have
more than one copy of React in the same app See for tips about how to
debug and fix this problem.

I have read the doc and checked for any rules broken but as per my knowledge everything is correct.
Here is my function that uses hooks:

```<code>import React, { useState } from 'react'
import { useCombobox, useMultipleSelection } from 'downshift'

const DropdownMultipleCombobox=()=> {
const [inputValue, setInputValue] = useState('')
const {
    getSelectedItemProps,
    getDropdownProps,
    addSelectedItem,
    removeSelectedItem,
    selectedItems,
} = useMultipleSelection({ initialSelectedItems: [Demoitems[0], Demoitems[1]] })
const getFilteredItems = (Demoitems) =>
    Demoitems.filter(
        (item) =>
            selectedItems.indexOf(item) < 0 &&
            item.toLowerCase().startsWith(inputValue.toLowerCase()),
    )
const {
    isOpen,
    getToggleButtonProps,
    getLabelProps,
    getMenuProps,
    getInputProps,
    getComboboxProps,
    highlightedIndex,
    getItemProps,
    selectItem,
} = useCombobox({
    inputValue,
    Demoitems: getFilteredItems(Demoitems),
    onStateChange: ({ inputValue, type, selectedItem }) => {
        switch (type) {
            case useCombobox.stateChangeTypes.InputChange:
                setInputValue(inputValue)
                break
            case useCombobox.stateChangeTypes.InputKeyDownEnter:
            case useCombobox.stateChangeTypes.ItemClick:
            case useCombobox.stateChangeTypes.InputBlur:
                if (selectedItem) {
                    setInputValue('')
                    addSelectedItem(selectedItem)
                    selectItem(null)
                }

                break
            default:
                break
        }
    },
})
return (
    <div>
        <label {...getLabelProps()}>Choose some elements:</label>
        <div style={comboboxWrapperStyles}>
            {selectedItems.map((selectedItem, index) => (
                <span
                    style={selectedItemStyles}
                    key={`selected-item-${index}`}
                    {...getSelectedItemProps({ selectedItem, index })}
                >
                    {selectedItem}
                    <span
                        style={selectedItemIconStyles}
                        onClick={() => removeSelectedItem(selectedItem)}
                    >
                        ✕
                    </span>
                </span>
            ))}
            <div style={comboboxStyles} {...getComboboxProps()}>
                <input
                    {...getInputProps(getDropdownProps({ preventKeyAction: isOpen }))}
                />
                <button {...getToggleButtonProps()} aria-label={'toggle menu'}>
                    ↓
                </button>
            </div>
        </div>
        <ul {...getMenuProps()} style={menuMultipleStyles}>
            {isOpen &&
                getFilteredItems(Demoitems).map((item, index) => (
                    <li
                        style={
                            highlightedIndex === index ? { backgroundColor: '#bde4ff' } : {}
                        }
                        key={`${item}${index}`}
                        {...getItemProps({ item, index })}
                    >
                        {item}
                    </li>
                ))}
        </ul>
    </div>
)
}

export default DropdownMultipleCombobox;
</code>```

my React component where I call the function :

```<code>export class TypeItemCollection extends React.Component {
render() {
    return (<DropdownMultipleCombobox/>)
}
}
</code>```

my package.json:

```<code>{
"dependencies": {
"@emotion/react": "^11.7.1",
"@emotion/styled": "^11.6.0",
"babel-types": "^6.26.0",
"browserify": "^17.0.0",
"downshift": "^6.1.7",
"emotion": "^9.2.12",
"emotion-server": "^9.2.12",
"moment": "^2.29.1",
"moment-datetime": "0.0.2",
"react": "^16.8.2",
"react-datepicker": "^4.6.0",
"react-datetime": "^3.1.1",
"react-dom": "^16.8.2",
"react-emotion": "^9.2.12",
"react-helmet": "^6.0.0",
"react-jss": "^8.6.1",
"react-router-dom": "^5.0.0",
"react-scripts": "^5.0.0",
"react-select": "^3.2.0",
"reactstrap": "^8.0.0",
"styled-components": "^4.0.0"
 },
 "devDependencies": {
"@babel/cli": "^7.16.0",
"@babel/core": "^7.16.5",
"@babel/plugin-proposal-class-properties": "^7.16.7",
"@babel/plugin-transform-react-jsx": "^7.16.5",
"@babel/preset-env": "^7.16.5",
"@babel/preset-react": "^7.16.5",
"@testing-library/react": "^12.1.2",
"babel-jest": "^27.4.5",
"babel-loader": "^8.2.3",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
"babel-plugin-transform-export-extensions": "^6.22.0",
"babel-preset-es2015": "^6.24.1",
"babelify": "^10.0.0",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.6",
"eslint-plugin-react-hooks": "^4.3.0",
"jest": "^27.4.5",
"react-test-renderer": "^17.0.2",
"typescript": "^4.5.4",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1"
}
}
</code>```

Please let me know where I'm going wrong here. Thanks.

答: I found out that I had an extra copy of React running, after removing it hooks worked!!</p>

Body:
I'm fairly new to react and using hooks. I'm using downshift plugin and want to show a MultiSelection dropdown. I'm using hooks to do that but I keep getting this error in the browser:

Invalid hook call. Hooks can only be called inside of the body of a
function component. This could happen for one of the following
reasons:

You might have mismatching versions of React and the renderer (such as
React DOM) You might be breaking the Rules of Hooks You might have
more than one copy of React in the same app See for tips about how to
debug and fix this problem.

I have read the doc and checked for any rules broken but as per my knowledge everything is correct.
Here is my function that uses hooks:

import React, { useState } from 'react'
import { useCombobox, useMultipleSelection } from 'downshift'

const DropdownMultipleCombobox=()=> {
const [inputValue, setInputValue] = useState('')
const {
    getSelectedItemProps,
    getDropdownProps,
    addSelectedItem,
    removeSelectedItem,
    selectedItems,
} = useMultipleSelection({ initialSelectedItems: [Demoitems[0], Demoitems[1]] })
const getFilteredItems = (Demoitems) =>
    Demoitems.filter(
        (item) =>
            selectedItems.indexOf(item) < 0 &&
            item.toLowerCase().startsWith(inputValue.toLowerCase()),
    )
const {
    isOpen,
    getToggleButtonProps,
    getLabelProps,
    getMenuProps,
    getInputProps,
    getComboboxProps,
    highlightedIndex,
    getItemProps,
    selectItem,
} = useCombobox({
    inputValue,
    Demoitems: getFilteredItems(Demoitems),
    onStateChange: ({ inputValue, type, selectedItem }) => {
        switch (type) {
            case useCombobox.stateChangeTypes.InputChange:
                setInputValue(inputValue)
                break
            case useCombobox.stateChangeTypes.InputKeyDownEnter:
            case useCombobox.stateChangeTypes.ItemClick:
            case useCombobox.stateChangeTypes.InputBlur:
                if (selectedItem) {
                    setInputValue('')
                    addSelectedItem(selectedItem)
                    selectItem(null)
                }

                break
            default:
                break
        }
    },
})
return (

        Choose some elements:

            {selectedItems.map((selectedItem, index) => (
                <span
                    style={selectedItemStyles}
                    key={`selected-item-${index}`}
                    {...getSelectedItemProps({ selectedItem, index })}
                >
                    {selectedItem}
                     removeSelectedItem(selectedItem)}
                    >
                        ✕

            ))}

                <input
                    {...getInputProps(getDropdownProps({ preventKeyAction: isOpen }))}
                />
                <button {...getToggleButtonProps()} aria-label={'toggle menu'}>
                    ↓
                </button>

            {isOpen &&
                getFilteredItems(Demoitems).map((item, index) => (
                    <li
                        style={
                            highlightedIndex === index ? { backgroundColor: '#bde4ff' } : {}
                        }
                        key={`${item}${index}`}
                        {...getItemProps({ item, index })}
                    >
                        {item}

                ))}

)
}

export default DropdownMultipleCombobox;

my React component where I call the function :

export class TypeItemCollection extends React.Component {
render() {
    return (<DropdownMultipleCombobox/>)
}
}

my package.json:

{
"dependencies": {
"@emotion/react": "^11.7.1",
"@emotion/styled": "^11.6.0",
"babel-types": "^6.26.0",
"browserify": "^17.0.0",
"downshift": "^6.1.7",
"emotion": "^9.2.12",
"emotion-server": "^9.2.12",
"moment": "^2.29.1",
"moment-datetime": "0.0.2",
"react": "^16.8.2",
"react-datepicker": "^4.6.0",
"react-datetime": "^3.1.1",
"react-dom": "^16.8.2",
"react-emotion": "^9.2.12",
"react-helmet": "^6.0.0",
"react-jss": "^8.6.1",
"react-router-dom": "^5.0.0",
"react-scripts": "^5.0.0",
"react-select": "^3.2.0",
"reactstrap": "^8.0.0",
"styled-components": "^4.0.0"
 },
 "devDependencies": {
"@babel/cli": "^7.16.0",
"@babel/core": "^7.16.5",
"@babel/plugin-proposal-class-properties": "^7.16.7",
"@babel/plugin-transform-react-jsx": "^7.16.5",
"@babel/preset-env": "^7.16.5",
"@babel/preset-react": "^7.16.5",
"@testing-library/react": "^12.1.2",
"babel-jest": "^27.4.5",
"babel-loader": "^8.2.3",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
"babel-plugin-transform-export-extensions": "^6.22.0",
"babel-preset-es2015": "^6.24.1",
"babelify": "^10.0.0",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.6",
"eslint-plugin-react-hooks": "^4.3.0",
"jest": "^27.4.5",
"react-test-renderer": "^17.0.2",
"typescript": "^4.5.4",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1"
}
}

Please let me know where I'm going wrong here. Thanks.


问:
Fluentd + azure data explorer cluster
I'm working on fluentd setup in kubernetes. In kubernetes I have a number of applications which are writing some logs into stdout. I can filter, parse, and send logs to azure blob storage. But I want the logs from blob storage to be ingested into azure data explorer cluster. In data explorer cluster I have a database and table which has some schema defined, already. The question is how do I modify event from fluentd in such a way that it's going to meet the table schema? Is it possible at all? Maybe there are some alternative ways of creating such setup?</p>

答: Take a look at ingestion mappings, you can pick the properties that you care about and route them to the applicable columns and when a new property arrives you can change the mapping and the table schema will automatically be updated.</p>

Title: Fluentd + azure data explorer cluster


问:
Run powershell with parameters and hide flag
According to the AHK Docs on Run, it accepts the following syntax:

Run, Target , WorkingDir, Options, OutputVarPID
```
<p>Where <code>Options</code> can include:</p>
<blockquote>
<ul>
<li><strong><code>Max</code></strong>: launch maximized</li>
<li><strong><code>Min</code></strong>: launch minimized</li>
<li><strong><code>Hide</code></strong>: launch hidden (cannot be used in combination with either of the above)</li>
</ul>
</blockquote>
<p>I have shortcut bound to a powershell script like this:</p>
```^4::
Run, pwsh -WindowStyle Hidden -Command "Stop-ElgatoKeyLight -Host 192.168.1"
Return
```
<p>However, as noted in Powershell -WindowStyle Hidden still shows a window briefly, this doesn't prevent a brief flash of the console starting up</p>
<p>I can't quite seem to get the syntax right when adding <code>hide</code>. When I try this:</p>
```Run, pwsh, -WindowStyle Hidden -Command "Stop-ElgatoKeyLight -Host 192.168.1", Hide
```

I get the following error:

Q: How can I use the hide flag on the run command while still passing params into powershell?

答:
You want to run:

```<code>Run, pwsh -Command "Stop-ElgatoKeyLight -Host 192.168.1", , Hide
</code>```

Or using the modern expression syntax:

```<code>Run, % "pwsh -Command ""Stop-ElgatoKeyLight -Host 192.168.1""", , Hide
</code>```

The way your code is currently written:

```<code>Run, pwsh, -WindowStyle Hidden -Command "Stop-ElgatoKeyLight -Host 192.168.1", Hide
</code>```

As you pointed out, the parameters are Target, WorkingDir, Options, OutputVarPID, so you're trying to launch pwsh in the directory -WindowStyle Hidden -Command "Stop-ElgatoKeyLight -Host 192.168.1".

Body:
According to the AHK Docs on Run, it accepts the following syntax:

Run, Target , WorkingDir, Options, OutputVarPID

Where Options can include:

Max: launch maximized

Min: launch minimized

Hide: launch hidden (cannot be used in combination with either of the above)

I have shortcut bound to a powershell script like this:

^4::
Run, pwsh -WindowStyle Hidden -Command "Stop-ElgatoKeyLight -Host 192.168.1"
Return

However, as noted in Powershell -WindowStyle Hidden still shows a window briefly, this doesn't prevent a brief flash of the console starting up

I can't quite seem to get the syntax right when adding hide. When I try this:

Run, pwsh, -WindowStyle Hidden -Command "Stop-ElgatoKeyLight -Host 192.168.1", Hide

I get the following error:

Q: How can I use the hide flag on the run command while still passing params into powershell?

Body:
You want to run:

Run, pwsh -Command "Stop-ElgatoKeyLight -Host 192.168.1", , Hide

Or using the modern expression syntax:

Run, % "pwsh -Command ""Stop-ElgatoKeyLight -Host 192.168.1""", , Hide

The way your code is currently written:

Run, pwsh, -WindowStyle Hidden -Command "Stop-ElgatoKeyLight -Host 192.168.1", Hide

As you pointed out, the parameters are Target, WorkingDir, Options, OutputVarPID, so you're trying to launch pwsh in the directory -WindowStyle Hidden -Command "Stop-ElgatoKeyLight -Host 192.168.1".


问:
How to make a webApi a Windows service by adding Start, Stop and Restart event handling in .Net 6?
How to make a webApi a Windows service by adding Start, Stop and Restart event handling in .Net 6?
In .Net 5 and before that, I usually make an AppStartup like this:

```<code>public interface IAppStartup
    {
        Task StartAsync();
        Task StopAsync();
        Task RestartService(IHostedService hostedService);
    }

public class AppStartup : IAppStartup
    {
        private readonly string[] _args;
        private readonly CancellationTokenSource _cancellationTokenSource = new();
        private IHost _host;
        private static AppStartup _appStartup;

        private AppStartup(string[] args)
        {
            _args = args;
        }

        public async Task StartAsync()
        {
            try
            {
                _host = CreateHostBuilder(_args).Build();

                var setting = _host.Services.GetService<AppSettings>();
                if (setting != null)
                {
                    ///
                }

                await _host.RunAsync(_cancellationTokenSource.Token);
            }
            catch (Exception e)
            {
                ///
                throw;
            }
        }

        public async Task StopAsync()
        {
            try
            {
                await _host.StopAsync(_cancellationTokenSource.Token);
            }
            catch (Exception e)
            {
                ///
                throw;
            }
        }

        public async Task RestartService(IHostedService hostedService)
        {
            if (hostedService!=null)
            {
                await hostedService.StopAsync(_cancellationTokenSource.Token);
                await hostedService.StartAsync(_cancellationTokenSource.Token);
            }
        }
    }

</code>```

Now in .Net 6, I am confused because there is no Startup method anymore to call.
Please kindly advise me of any solution you use to add Windows service functionalities into a web API project.

答:
Both .NET 5 and .NET 6 have support for the Windows Service lifetime, which hooks into Start/Stop for you. So it's essentially just this in your Program.cs:

```<code>host = CreateHostBuilder(args)
    .UseWindowsService(...)
    .Build();

var setting = host.Services.GetService<AppSettings>();
if (setting != null)
{
  ///
}

await host.RunAsync();
</code>```

Body:
How to make a webApi a Windows service by adding Start, Stop and Restart event handling in .Net 6?
In .Net 5 and before that, I usually make an AppStartup like this:

public interface IAppStartup
    {
        Task StartAsync();
        Task StopAsync();
        Task RestartService(IHostedService hostedService);
    }

public class AppStartup : IAppStartup
    {
        private readonly string[] _args;
        private readonly CancellationTokenSource _cancellationTokenSource = new();
        private IHost _host;
        private static AppStartup _appStartup;

        private AppStartup(string[] args)
        {
            _args = args;
        }

        public async Task StartAsync()
        {
            try
            {
                _host = CreateHostBuilder(_args).Build();

                var setting = _host.Services.GetService<AppSettings>();
                if (setting != null)
                {
                    ///
                }

                await _host.RunAsync(_cancellationTokenSource.Token);
            }
            catch (Exception e)
            {
                ///
                throw;
            }
        }

        public async Task StopAsync()
        {
            try
            {
                await _host.StopAsync(_cancellationTokenSource.Token);
            }
            catch (Exception e)
            {
                ///
                throw;
            }
        }

        public async Task RestartService(IHostedService hostedService)
        {
            if (hostedService!=null)
            {
                await hostedService.StopAsync(_cancellationTokenSource.Token);
                await hostedService.StartAsync(_cancellationTokenSource.Token);
            }
        }
    }

Now in .Net 6, I am confused because there is no Startup method anymore to call.
Please kindly advise me of any solution you use to add Windows service functionalities into a web API project.

Body:
Both .NET 5 and .NET 6 have support for the Windows Service lifetime, which hooks into Start/Stop for you. So it's essentially just this in your Program.cs:

host = CreateHostBuilder(args)
    .UseWindowsService(...)
    .Build();

var setting = host.Services.GetService<AppSettings>();
if (setting != null)
{
  ///
}

await host.RunAsync();


问:
Is it possible to query MySQL to get only fields that contain duplicate/repeating strings?
What I mean is, I have table with a "list" column. The data that goes into the "list" is related to addresses, so I sometimes get repeated zip codes for one record in that field.

For example, "12345,12345,12345,12456".

I want to know if it's possible to construct a query that would find the records that have an unknown string that duplicates within the field, such that I would get the records like "12345,12345,12345,12456", but not ones like "12345,45678,09876".

I hope that makes sense.

答:
Yes, it is possible. You need to use a numbers table to convert your delimited string into rows, then use group by to find duplicates, e.g.

```<code>CREATE TABLE T (ID INT, List VARCHAR(100));
INSERT INTO T (ID, List)
VALUES (1, '12345,12345,12345,12456'), (2, '12345,45678,09876');

SELECT
  T.ID,
  SUBSTRING_INDEX(SUBSTRING_INDEX(T.list, ',', n.Number), ',', -1) AS ListItem
FROM T
    INNER JOIN
    (   SELECT 1 AS Number UNION ALL
        SELECT 2 UNION ALL
        SELECT 3 UNION ALL
        SELECT 4 UNION ALL
        SELECT 5
    ) AS n
        ON CHAR_LENGTH(T.list)-CHAR_LENGTH(REPLACE(T.list, ',', ''))>=n.Number-1
GROUP BY T.ID, ListItem
HAVING COUNT(*) > 1;
</code>```

If you don't have a numbers table you can create one in a derived query as I have above with UNION ALL

Example on DB Fiddle

With that being said, this is almost certainly not the right way to store your data, you should instead use a child table, e.g.

```<code>CREATE TABLE ListItems
(
      MainTableId INT NOT NULL, --Foreign Key to your current table
      ItemName VARCHAR(10) NOT NULL -- Or whatever data type you need
);
</code>```

Then your query is much more simple:

```<code>SELECT T.ID, li.ItemName
FROM    T
        INNER JOIN ListItems AS li
            ON li.MainTableId = T.ID
GROUP BY T.ID, li.ItemName
HAVING COUNT(*) > 1;
</code>```

If you need to recreate your original format, this is easily done with GROUP_CONCAT():

```<code>SELECT T.ID,
        GROUP_CONCAT(li.ItemName) AS List
FROM    T
        INNER JOIN ListItems AS li
            ON li.MainTableId = T.ID
GROUP BY T.ID;
</code>```

Example on DB Fiddle

Body:
Yes, it is possible. You need to use a numbers table to convert your delimited string into rows, then use group by to find duplicates, e.g.

CREATE TABLE T (ID INT, List VARCHAR(100));
INSERT INTO T (ID, List)
VALUES (1, '12345,12345,12345,12456'), (2, '12345,45678,09876');

SELECT
  T.ID,
  SUBSTRING_INDEX(SUBSTRING_INDEX(T.list, ',', n.Number), ',', -1) AS ListItem
FROM T
    INNER JOIN
    (   SELECT 1 AS Number UNION ALL
        SELECT 2 UNION ALL
        SELECT 3 UNION ALL
        SELECT 4 UNION ALL
        SELECT 5
    ) AS n
        ON CHAR_LENGTH(T.list)-CHAR_LENGTH(REPLACE(T.list, ',', ''))>=n.Number-1
GROUP BY T.ID, ListItem
HAVING COUNT(*) > 1;

If you don't have a numbers table you can create one in a derived query as I have above with UNION ALL

Example on DB Fiddle

With that being said, this is almost certainly not the right way to store your data, you should instead use a child table, e.g.

CREATE TABLE ListItems
(
      MainTableId INT NOT NULL, --Foreign Key to your current table
      ItemName VARCHAR(10) NOT NULL -- Or whatever data type you need
);

Then your query is much more simple:

SELECT T.ID, li.ItemName
FROM    T
        INNER JOIN ListItems AS li
            ON li.MainTableId = T.ID
GROUP BY T.ID, li.ItemName
HAVING COUNT(*) > 1;

If you need to recreate your original format, this is easily done with GROUP_CONCAT():

SELECT T.ID,
        GROUP_CONCAT(li.ItemName) AS List
FROM    T
        INNER JOIN ListItems AS li
            ON li.MainTableId = T.ID
GROUP BY T.ID;

Example on DB Fiddle


问:
How to use temporary object that is passed to super constructor?
```<code>interface I

open class Base(protected val i: I)

class Impl: I
class Derived(args:Bundle): Base( Impl(args) ) { // here I create an instance of Impl
    private val my: Impl // See my question
}
</code>```

My Base class depends on an interface I. But the implementation Impl is created in Derived class. I want to use Impl object in Derived class too. I can see the Base implementation and cast super.i to Impl but I don't want to depends on Base's implementation details. Can I store Impl somewhere to restore in to Derived.my member? I have a restriction from the library: a class has to have a constructor with args:Bundle argument, no more or less

答:
If you are opposed to simply casting the superclass's property i as Impl, you could do this using a secondary constructor and making your primary constructor private:

```<code>class Derived private constructor(private val my: Impl): Base(my) {

    constructor(args: Bundle): this(Impl(args))

}
</code>```

Body:
interface I

open class Base(protected val i: I)

class Impl: I
class Derived(args:Bundle): Base( Impl(args) ) { // here I create an instance of Impl
    private val my: Impl // See my question
}

My Base class depends on an interface I. But the implementation Impl is created in Derived class. I want to use Impl object in Derived class too. I can see the Base implementation and cast super.i to Impl but I don't want to depends on Base's implementation details. Can I store Impl somewhere to restore in to Derived.my member? I have a restriction from the library: a class has to have a constructor with args:Bundle argument, no more or less

Body:
If you are opposed to simply casting the superclass's property i as Impl, you could do this using a secondary constructor and making your primary constructor private:

class Derived private constructor(private val my: Impl): Base(my) {

    constructor(args: Bundle): this(Impl(args))

}


问:
Transform table in SQL
can you please help with the question:

How do I transform a table in this format:

to this:

Thanks in advance!

答:
You can do:</p>
```<code>select person, 'Salary' as metric, salary as metric_value from t
union all
select person, 'Spend', spend from t
</code>```

Title: Transform table in SQL

Body:
You can do:

select person, 'Salary' as metric, salary as metric_value from t
union all
select person, 'Spend', spend from t


问:
Best approach to upgrade TFS 2015 to TFS 2018?
We currently have TFS set up on three Win2012 servers:   app server, build server, deployment server.

It is using SQL Server 2014 which is on a separate server (let's call it SQL1).   We have a SQL 2017 server (SQL2) that is not in use but can be used to migrate databases there.

Our plan is to upgrade to TFS 2018.   Since TFS 2018 does not support SQL 2017, What is the best approach here?

In-place upgrade TFS 2015 to TFS 2017 (which supports SQL 2014).     Then upgrade SQL 2014 to SQL 2017 on SQL1.   Once SQL upgrade is done, then we can do another in-place upgrade to TFS 2018.

Migrate existing TFS databases from SQL1 to SQL2 server.   Upgrade TFS 2015 directly to 2018 and point to databases on new SQL 2017 server.

Backup SQL1 databases. Upgrade SQL1 to SQL 2017.  Restore databases.   In-place upgrade TFS 2015 directly to TFS 2018.

What would be the best approach here?   Thanks.

答:
I recommend the following:

Spin up fresh Windows 2019 or 2022 servers.

Install SQL Server 2019 on one of 'm.

Install Azure DevOps Servers 2020 or 2022 on the other.

Restore the databases on the SQL server.

Run the configuration wizard on the Azure DevOps Server and have it perform the upgrade.

In most cases this process can run in a couple of hours if you've prepared all the machines and accounts, DNS entries etc.


问:
How to get response body from Express.js server using Supertest?
I started to write some tests for my application and I have issues to read/get response from the server. I tried many things but nothing really worked, can someone help me please ?

```<code>// /api/checkCreds
exports.checkCreds = async function(req, res){
//validation
if(!await User.checkCreds(req.body.username, req.body.password)){
    var result = {error: true, data: "Incorrect"}
    res.sendStatus = 401;
    return res.send(JSON.stringify(result));
}
</code>```

If credentials sent to the server aren't matching, return a response with "Incorrect" message back to the user.
In the test I'm trying to get data from the server to check if properties are matching the expected output.

```<code>    //test.js
    it("We should fail with HTTP code 401 because incorrect data is passed (username='incorrect' password='incorrect')", function(done){
       supertest(app)
       .post('/api/checkCreds')
       .send({username: 'incorrect', password: 'incorrect'})
       .expect({error: true, data: "Incorrect"})
       .expect(401, done);
   });
</code>```

When ran, test fails because expected properties are different from the response sent by the server, which is an empty object {}.

Any help is appreciated.

答:
While trying to fix my issue, I noticed that in the HTTP response, Content-Type header was set to text/plain and my server was returning JSON, so that probably was the thing that confused supertest.

I think that res.send() sets the header to text/plain by default and I had to manually set the header value to application/json by using res.type('json'). At that point I was able to read the response body without an issue.
I also learned that res.json() sets the Content-Type header to application/json by default, so you don't need to do it manually like with res.send().

Working code:

```<code>// /api/checkCreds
if(!await User.checkCreds(req.body.username, req.body.password)){
    var result = {error: true, data: "Incorrect"}
    return res.status(401).json(result);
}

//test.js
it("We should fail with HTTP code 401 because incorrect data is passed (username='incorrect' password='incorrect')", function(done){
    supertest(app)
    .post('/api/checkCreds')
    .set('Content-type', 'application/json')
    .send({username: 'incorrect', password: 'incorrect'})
    .expect(401)
    .expect(function(res){
        console.log(res.body);
    })
    .end(done);
});
</code>```

Feel free to correct me if I stated something that isn't quite right.

Body:
I started to write some tests for my application and I have issues to read/get response from the server. I tried many things but nothing really worked, can someone help me please ?

// /api/checkCreds
exports.checkCreds = async function(req, res){
//validation
if(!await User.checkCreds(req.body.username, req.body.password)){
    var result = {error: true, data: "Incorrect"}
    res.sendStatus = 401;
    return res.send(JSON.stringify(result));
}

If credentials sent to the server aren't matching, return a response with "Incorrect" message back to the user.
In the test I'm trying to get data from the server to check if properties are matching the expected output.

    //test.js
    it("We should fail with HTTP code 401 because incorrect data is passed (username='incorrect' password='incorrect')", function(done){
       supertest(app)
       .post('/api/checkCreds')
       .send({username: 'incorrect', password: 'incorrect'})
       .expect({error: true, data: "Incorrect"})
       .expect(401, done);
   });

When ran, test fails because expected properties are different from the response sent by the server, which is an empty object {}.

Any help is appreciated.

Body:
While trying to fix my issue, I noticed that in the HTTP response, Content-Type header was set to text/plain and my server was returning JSON, so that probably was the thing that confused supertest.

I think that res.send() sets the header to text/plain by default and I had to manually set the header value to application/json by using res.type('json'). At that point I was able to read the response body without an issue.
I also learned that res.json() sets the Content-Type header to application/json by default, so you don't need to do it manually like with res.send().

Working code:

// /api/checkCreds
if(!await User.checkCreds(req.body.username, req.body.password)){
    var result = {error: true, data: "Incorrect"}
    return res.status(401).json(result);
}

//test.js
it("We should fail with HTTP code 401 because incorrect data is passed (username='incorrect' password='incorrect')", function(done){
    supertest(app)
    .post('/api/checkCreds')
    .set('Content-type', 'application/json')
    .send({username: 'incorrect', password: 'incorrect'})
    .expect(401)
    .expect(function(res){
        console.log(res.body);
    })
    .end(done);
});

Feel free to correct me if I stated something that isn't quite right.


问:
use json list element inside a jinja statement using js or jquery
this is my code:

```<code>                $("select").change(function(){
                $.post("/sort", {sort:$(this).val()}, function(table_data)
                {
                    for (let i in table_data)
                    {
                        var tr = $("<tr/>");
                        var filename = table_data[i].filename;
                        var size = table_data[i].size;
                        var uploaded = table_data[i].upload_time;
                        tr.append("<td>"+filename+"</td>");
                        tr.append("<td>"+size+"</td>");
                        tr.append("<td>"+uploaded+"</td>");
                        **tr.append("<td>"+"<a href='{{url_for('.download', filename=***filename***)}}'>"+'Download'+"</a>"+"</td>")**;
                        tr.appendTo(table);
                    }
</code>```

Interestingly the jinja statement inside the js statement works, the browser directs to that path, but the filename remains None, because the server, which is using python flask, cannot resolve the value sent from here which is a js variable. Table_data is a json that was returned from the server using jsonify in response to an ajax call. My question is if there's any way to use that 'filename' js variable inside that jinja statement, or perhaps convert it to a jinja variable. Thanks.

答:
As I wrote in my comment, it is only possible to pass variables from Jinja to JavaScript when the page is served. This time has already passed during the AJAX request.

I think the best solution is to construct the url with url_for on the server and transfer it via JSON with the record. So your requirements should be met.

I wrote you a small example, which is based on your question.

All folders in the application's static folder are listed and made available to the user for selection. If he selects a directory, file information and the download URL are queried via Ajax. The information is then displayed in a table.

Flask (app.py)

```<code>import os
from datetime import datetime
from flask import Flask
from flask import (
    jsonify,
    render_template,
    request,
    send_from_directory,
    url_for
)

app = Flask(__name__)

@app.route('/')
def index():
    # List all folders in the static folder.
    folders = [file \
        for file in os.listdir(app.static_folder) \
        if os.path.isdir(os.path.join(app.static_folder, file))
    ]
    return render_template('index.html', **locals())

@app.route('/stats', methods=['POST'])
def stats():
    # Return stats of all files in the selected folder.
    if 'target' in request.form:
        data = []
        target = request.form['target']
        try:
            for filename in os.listdir(os.path.join(app.static_folder, target)):
                filepath = os.path.join(app.static_folder, target, filename)
                data.append(
                    {
                        'filename': filename,
                        'filesize': os.path.getsize(filepath),
                        'filetime': datetime.fromtimestamp(os.path.getmtime(filepath)).isoformat(),
                        'filedest': url_for('.download', filename=os.path.join(target, filename))
                    }
                )
            return jsonify(data)
        except OSError: pass
    return '', 400

@app.route('/download/<path:filename>')
def download(filename):
    return send_from_directory(app.static_folder, filename)
</code>```

HTML (templates/index.html)

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>
    <select name="target">
      <option disabled selected value>-- select an option --</option>
      {% for folder in folders -%}
      <option value="{{folder}}">{{folder}}</option>
      {% endfor -%}
    </select>

    <table id="my-table" style="width: 100%"></table>

    <script
      src="https://code.jquery.com/jquery-3.6.0.min.js"
      integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
      crossorigin="anonymous"></script>

    <script type="text/javascript">
      ((uri) => {
        $(document).ready(function() {
          $('select[name="target"]').change(function(evt) {
            $('table#my-table').empty();
            $.post(uri, { target: $(this).val() })
              .done(function(data) {
                data.forEach(info => {
                  const { filename, filesize, filetime, filedest } = info;
                  const row = $('<tr/>');
                  row.html(`
                    <td>${filename}</td>
                    <td>${filesize}</td>
                    <td>${filetime}</td>
                    <td><a href="${filedest}">Download</a></td>
                  `)
                  row.appendTo($('table#my-table'));
                });
              });
          })
        });
      })({{ url_for('.stats') | tojson }});
    </script>
  </body>
</html>
</code>```

Body:
this is my code:

                $("select").change(function(){
                $.post("/sort", {sort:$(this).val()}, function(table_data)
                {
                    for (let i in table_data)
                    {
                        var tr = $("
");
                        var filename = table_data[i].filename;
                        var size = table_data[i].size;
                        var uploaded = table_data[i].upload_time;
                        tr.append(""+filename+"	");
                        tr.append(""+size+"	");
                        tr.append(""+uploaded+"	");
                        **tr.append(""+""+'Download'+""+"	")**;
                        tr.appendTo(table);
                    }

Interestingly the jinja statement inside the js statement works, the browser directs to that path, but the filename remains None, because the server, which is using python flask, cannot resolve the value sent from here which is a js variable. Table_data is a json that was returned from the server using jsonify in response to an ajax call. My question is if there's any way to use that 'filename' js variable inside that jinja statement, or perhaps convert it to a jinja variable. Thanks.

Body:
As I wrote in my comment, it is only possible to pass variables from Jinja to JavaScript when the page is served. This time has already passed during the AJAX request.

I think the best solution is to construct the url with url_for on the server and transfer it via JSON with the record. So your requirements should be met.

I wrote you a small example, which is based on your question.

All folders in the application's static folder are listed and made available to the user for selection. If he selects a directory, file information and the download URL are queried via Ajax. The information is then displayed in a table.

Flask (app.py)

import os
from datetime import datetime
from flask import Flask
from flask import (
    jsonify,
    render_template,
    request,
    send_from_directory,
    url_for
)

app = Flask(__name__)

@app.route('/')
def index():
    # List all folders in the static folder.
    folders = [file \
        for file in os.listdir(app.static_folder) \
        if os.path.isdir(os.path.join(app.static_folder, file))
    ]
    return render_template('index.html', **locals())

@app.route('/stats', methods=['POST'])
def stats():
    # Return stats of all files in the selected folder.
    if 'target' in request.form:
        data = []
        target = request.form['target']
        try:
            for filename in os.listdir(os.path.join(app.static_folder, target)):
                filepath = os.path.join(app.static_folder, target, filename)
                data.append(
                    {
                        'filename': filename,
                        'filesize': os.path.getsize(filepath),
                        'filetime': datetime.fromtimestamp(os.path.getmtime(filepath)).isoformat(),
                        'filedest': url_for('.download', filename=os.path.join(target, filename))
                    }
                )
            return jsonify(data)
        except OSError: pass
    return '', 400

@app.route('/download/<path:filename>')
def download(filename):
    return send_from_directory(app.static_folder, filename)

HTML (templates/index.html)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>
    <select name="target">
      <option disabled selected value>-- select an option --</option>
      {% for folder in folders -%}
      <option value="{{folder}}">{{folder}}</option>
      {% endfor -%}
    </select>

    <table id="my-table" style="width: 100%"></table>

    <script
      src="https://code.jquery.com/jquery-3.6.0.min.js"
      integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
      crossorigin="anonymous"></script>

    <script type="text/javascript">
      ((uri) => {
        $(document).ready(function() {
          $('select[name="target"]').change(function(evt) {
            $('table#my-table').empty();
            $.post(uri, { target: $(this).val() })
              .done(function(data) {
                data.forEach(info => {
                  const { filename, filesize, filetime, filedest } = info;
                  const row = $('<tr/>');
                  row.html(`
                    <td>${filename}</td>
                    <td>${filesize}</td>
                    <td>${filetime}</td>
                    <td><a href="${filedest}">Download</a></td>
                  `)
                  row.appendTo($('table#my-table'));
                });
              });
          })
        });
      })({{ url_for('.stats') | tojson }});
    </script>
  </body>
</html>


问:
iOS Simulator crashes when clicking on Map
So I have an issue only with the simulator for iOS, I can interact with the map for about two seconds before the whole app crashes...

When I use my own device, it works fine...

here's a gif: https://gyazo.com/67a5d7f10586d0368eb631346122867b

Here is my implementation:

import React, { useEffect } from "react";
import { StatusBar } from "react-native";
import MapboxGL from "@react-native-mapbox-gl/maps";

function MapScreen() {
    const context = useEquipment();

    // const { deployedEquipment } = context!;

    const defaultCameraCoordinates = {
        latitude: context?.location?.latitude ?? 0,
        longitude: context?.location?.longitude ?? 0,
    };

    return (
        <>
            <StatusBar animated={true} backgroundColor="black" barStyle="dark-content" />
            <MapboxGL.MapView style={styles.map}>
            </MapboxGL.MapView>
        </>
    );
}

```
<p>The error from the device:</p>
<blockquote>
<p>Application Specific Information:
dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot
terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[0]'
abort() called
CoreSimulator 783.5 - Device: iPhone 13 (D63AEBAD-44FF-4884-8F91-259CAEA4FC7F) - Runtime: iOS 15.2 (19C51) - DeviceType: iPhone 13</p>
</blockquote>
<p><strong>Podfile:</strong></p>
<pre class="lang-js prettyprint-override"><code>require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '11.0'

target 'DigiCatchRN' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => true
  )

  target 'DigiCatchRNTests' do
    inherit! :complete
    # Pods for testing
  end

  pre_install do |installer|
    $RNMBGL.pre_install(installer) #mapbox
  end

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.
  use_flipper!()

  post_install do |installer|
    react_native_post_install(installer)
    __apply_Xcode_12_5_M1_post_install_workaround(installer)

    $RNMBGL.pre_install(installer) # mapbox
  end
end
</code>```

答: I finally found a solution for this, and it turns out that my simulator runs ios 15.2 crashed. When I downloaded another version below this version. In my case 13.5. It finally works :)</p>

Body:
So I have an issue only with the simulator for iOS, I can interact with the map for about two seconds before the whole app crashes...

When I use my own device, it works fine...

here's a gif: https://gyazo.com/67a5d7f10586d0368eb631346122867b

Here is my implementation:

import React, { useEffect } from "react";
import { StatusBar } from "react-native";
import MapboxGL from "@react-native-mapbox-gl/maps";

function MapScreen() {
    const context = useEquipment();

    // const { deployedEquipment } = context!;

    const defaultCameraCoordinates = {
        latitude: context?.location?.latitude ?? 0,
        longitude: context?.location?.longitude ?? 0,
    };

    return (
        <>
            <StatusBar animated={true} backgroundColor="black" barStyle="dark-content" />
            <MapboxGL.MapView style={styles.map}>
            </MapboxGL.MapView>
        </>
    );
}

The error from the device:

Application Specific Information:
dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot
terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[0]'
abort() called
CoreSimulator 783.5 - Device: iPhone 13 (D63AEBAD-44FF-4884-8F91-259CAEA4FC7F) - Runtime: iOS 15.2 (19C51) - DeviceType: iPhone 13

Podfile:

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '11.0'

target 'DigiCatchRN' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => true
  )

  target 'DigiCatchRNTests' do
    inherit! :complete
    # Pods for testing
  end

  pre_install do |installer|
    $RNMBGL.pre_install(installer) #mapbox
  end

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.
  use_flipper!()

  post_install do |installer|
    react_native_post_install(installer)
    __apply_Xcode_12_5_M1_post_install_workaround(installer)

    $RNMBGL.pre_install(installer) # mapbox
  end
end


问:
Silverlight 3 - dataform errorsummary with RIA validation
I got a dataform partially working with RIA services (I can fetch and edit data).

The problem is that I added validation to my RIA service fields. Ex: from my metadata.cs file

[StringLength ( 50, ErrorMessage= "bad data dude!" , MinimumLength=4)]
public string Title;

In the dataform, when a user enters data violating the above rule, an exception is thrown saying "bad data dude!" which is sort of OK. The problem is that I would like the data form to show this message in the error summary?

What am I doing wrong?

答:
FYI: Also, just found out this only occurs when debugging with Visual Studio.

I can get everything working correctly if I run without debugging (Ctrl + F5)

A better solution exists?

OwnerDisplayName: vidalsasoon

ContentLicense: CC BY-SA 2.5


问:
Bootstrap's tooltip doesn't disappear after button click & mouseleave
I have a problem with bootstrap's tooltip : When I click on a button, tooltip stays even if is the cursor is outside of the button. I have looked into the manual - Bootstrap's tooltip and if I'm clicking on the buttons, I see the same problem. Is there any solution to fix this? Just tried in latest FF, IE.</p>

答:
To me, works only when I put this code. P.S.: I'm using Bootstrap 4.

$("body").tooltip({
    selector: '[data-toggle=tooltip]',
    trigger: 'hover'
}).on('click mousedown mouseup', '[data-toggle="tooltip"], [title]:not([data-toggle="popover"])', function () {
    $('[data-toggle="tooltip"], [title]:not([data-toggle="popover"])').tooltip('hide');
});

```