答:
Fix your code with</p>
```<code>data[~data.conserve_score.astype(str).str.contains(".")]
</code>```

Title: How to remove rows with "." in python?

Body:
here is my data:

>>> data
            chr      1t        2                 exp        conserve_score       cd         re
1013       chr1     142200     142220          -0.121027      0.0270625         0.0  0.000000
1014       chr1     142220     142240          -0.120995  0.02331578947         0.0  0.000000
1015       chr1     142240     142260          -0.149517  0.03235294118         0.0  0.000000
1308       chr1     169180     169200          -0.182448              .         0.0  0.000000
2046       chr1     439360     439380          -0.112148          0.142         0.0  0.803303
...         ...        ...        ...                ...            ...         ...       ...
150209142  chr5  180756500  180756520           0.145244        0.28205         0.0  0.968969
150209143  chr5  180756520  180756540           0.164834         0.3497         0.0  0.968969
150209144  chr5  180756540  180756560           0.160763   0.3825555556         0.0  0.968969
150209145  chr5  180756560  180756580           0.160709   0.3932857143         0.0  0.968969
150209146  chr5  180756580  180756600           0.160709   0.3829444444         0.0  0.968969

some rows has values . and I want to remove those rows

I tried

>>> data[data.conserve_score.str.contains(".")==False]
Empty DataFrame
Index: []

but in float numbers, there are also "." ...
How to make it works?

Thanks

Body:
Fix your code with

data[~data.conserve_score.astype(str).str.contains(".")]


来源: stackexchange

问:
How to extract end code value from given strings
How to get last code value of string

```<code>Emp-Code-001 //Result 001

Sub-000123 //Result 000123

JOB-ABC-BJ-212-0012 //Result  0012
</code>```

How to pick out end value of code number from given strings.

Here what I did:

```<code>func truncateHyphens(id: String){

    let finalString = id
    var trucatedString =id

    let substringToLastIndexOfChar = trucatedString.lastIndexOfCharacter("-") ?? 0
    let otherRange = trucatedString.index(trucatedString.startIndex, offsetBy: substringToLastIndexOfChar + 1)..<trucatedString.endIndex
    trucatedString.removeSubrange(otherRange)
    print(finalString.replacingOccurrences(of: trucatedString, with: ""))

}

public extension String {
    func lastIndexOfCharacter(_ c: Character) -> Int? {
        guard let index = range(of: String(c), options: .backwards)?.lowerBound else
            { return nil }
        return distance(from: startIndex, to: index)
    }
}

self.truncateHyphens(id: "JOB-ABC-BJ-212-12340012") // Result 12340012
</code>```

It works but I felt not an ideal Solution.

How to optimise the above code?

答:
Alternative solution with Regular Expression.

The pattern searches for a hyphen plus one or more digits (\\d+) at the end of the string ($). Finally the hyphen will be dropped.

If the pattern cannot be found the function returns nil.

```<code>func truncateHyphens(id: String) -> String? {
    let regex = try! NSRegularExpression(pattern: "-\\d+$")
    guard let match = regex.firstMatch(in: id) else { return nil }
    let range = Range(match.range, in: id)!
    return String(id[range].dropFirst())
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to get last code value of string

Emp-Code-001 //Result 001

Sub-000123 //Result 000123

JOB-ABC-BJ-212-0012 //Result  0012

How to pick out end value of code number from given strings.

Here what I did:

func truncateHyphens(id: String){

    let finalString = id
    var trucatedString =id

    let substringToLastIndexOfChar = trucatedString.lastIndexOfCharacter("-") ?? 0
    let otherRange = trucatedString.index(trucatedString.startIndex, offsetBy: substringToLastIndexOfChar + 1)..<trucatedString.endIndex
    trucatedString.removeSubrange(otherRange)
    print(finalString.replacingOccurrences(of: trucatedString, with: ""))

}

public extension String {
    func lastIndexOfCharacter(_ c: Character) -> Int? {
        guard let index = range(of: String(c), options: .backwards)?.lowerBound else
            { return nil }
        return distance(from: startIndex, to: index)
    }
}

self.truncateHyphens(id: "JOB-ABC-BJ-212-12340012") // Result 12340012

It works but I felt not an ideal Solution.

How to optimise the above code?

Body:
Alternative solution with Regular Expression.

The pattern searches for a hyphen plus one or more digits (\\d+) at the end of the string ($). Finally the hyphen will be dropped.

If the pattern cannot be found the function returns nil.

func truncateHyphens(id: String) -> String? {
    let regex = try! NSRegularExpression(pattern: "-\\d+$")
    guard let match = regex.firstMatch(in: id) else { return nil }
    let range = Range(match.range, in: id)!
    return String(id[range].dropFirst())
}


问:
JScrollPane scrolling with arrow keys
I've a JTextArea component inside JScrollPane and the text area is not editable. I would like to enable scrolling of the text area with up and down arrow keys (i.e. pressing the arrow keys will scroll the text area by one line). Any ideas how to achieve this? </p>

答:
All I had to do was to make the scroll pane request focus on mouse enter (as explained in this answer).

var scrollPane = new JScrollBar(jPanelCanvas);
scrollPane.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseEntered(MouseEvent e) {
        // this seems to enable key navigation
        if ((e.getComponent() instanceof JScrollPane)) {
            e.getComponent().requestFocus();
        }
    }
});
```

However I'm not sure on how to tweak the actions of these keys. Maybe by tweaking the actions on the JScrollPane directly as mentioned by tinca's answer.

The call to scrollPane.getActionMap() are showing the following actions defined

"unitScrollRight" -> {BasicScrollPaneUI$Actions@4310}

"unitScrollDown" -> {BasicScrollPaneUI$Actions@4312}

"scrollDown" -> {BasicScrollPaneUI$Actions@4314}

"scrollHome" -> {BasicScrollPaneUI$Actions@4316}

"scrollRight" -> {BasicScrollPaneUI$Actions@4318}

"scrollUp" -> {BasicScrollPaneUI$Actions@4320}

"unitScrollLeft" -> {BasicScrollPaneUI$Actions@4322}

"unitScrollUp" -> {BasicScrollPaneUI$Actions@4324}

"scrollEnd" -> {BasicScrollPaneUI$Actions@4326}

"scrollLeft" -> {BasicScrollPaneUI$Actions@4328}

ContentLicense: CC BY-SA 2.5

Title: JScrollPane scrolling with arrow keys

Body:
All I had to do was to make the scroll pane request focus on mouse enter (as explained in this answer).

var scrollPane = new JScrollBar(jPanelCanvas);
scrollPane.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseEntered(MouseEvent e) {
        // this seems to enable key navigation
        if ((e.getComponent() instanceof JScrollPane)) {
            e.getComponent().requestFocus();
        }
    }
});

However I'm not sure on how to tweak the actions of these keys. Maybe by tweaking the actions on the JScrollPane directly as mentioned by tinca's answer.

The call to scrollPane.getActionMap() are showing the following actions defined

"unitScrollRight" -> {BasicScrollPaneUI$Actions@4310}

"unitScrollDown" -> {BasicScrollPaneUI$Actions@4312}

"scrollDown" -> {BasicScrollPaneUI$Actions@4314}

"scrollHome" -> {BasicScrollPaneUI$Actions@4316}

"scrollRight" -> {BasicScrollPaneUI$Actions@4318}

"scrollUp" -> {BasicScrollPaneUI$Actions@4320}

"unitScrollLeft" -> {BasicScrollPaneUI$Actions@4322}

"unitScrollUp" -> {BasicScrollPaneUI$Actions@4324}

"scrollEnd" -> {BasicScrollPaneUI$Actions@4326}

"scrollLeft" -> {BasicScrollPaneUI$Actions@4328}


问:
how to send token while post request
have a great day, i have a silly problem, don't mind as i am noob. ok my problem is, i have a token which i received after i login, now i have to post a data but for that i have to include this token in my header, but i don't know how to....

here is my token, which i received after login as response

```<code>{
  "token": "8d18265645a87d608868a127f373558ac2e131a6"
}
</code>```

Here, i have to implement in flutter

```<code>apiData.ApiData app = apiData.ApiData();
  final String apiURl = app.api;
  SharedPreferences pref = await SharedPreferences.getInstance();
  String? email = pref.getString("useremail");
  String? token = pref.getString('token');
  String date = DateFormat("yyyy-MM-dd").format(DateTime.now());
  String time = DateFormat("Hms").format(DateTime.now());
  print(time);
  print(date);
  dynamic response =
      await http.post(Uri.parse(apiURl + "/api/user-log/"), body: {
    'user': email,
    'start_time': time,
    'start_date': date,
  });`
</code>```

答:
```<code>final response = await http.get(
  Uri.parse(apiURl + "/api/user-log/"),
  body: {}
  headers: {
    HttpHeaders.authorizationHeader: "<Your token here>",
  },
);
</code>```

Documentation here

Title: how to send token while post request

Body:
have a great day, i have a silly problem, don't mind as i am noob. ok my problem is, i have a token which i received after i login, now i have to post a data but for that i have to include this token in my header, but i don't know how to....

here is my token, which i received after login as response

{
  "token": "8d18265645a87d608868a127f373558ac2e131a6"
}

Here, i have to implement in flutter

apiData.ApiData app = apiData.ApiData();
  final String apiURl = app.api;
  SharedPreferences pref = await SharedPreferences.getInstance();
  String? email = pref.getString("useremail");
  String? token = pref.getString('token');
  String date = DateFormat("yyyy-MM-dd").format(DateTime.now());
  String time = DateFormat("Hms").format(DateTime.now());
  print(time);
  print(date);
  dynamic response =
      await http.post(Uri.parse(apiURl + "/api/user-log/"), body: {
    'user': email,
    'start_time': time,
    'start_date': date,
  });`

Body:
final response = await http.get(
  Uri.parse(apiURl + "/api/user-log/"),
  body: {}
  headers: {
    HttpHeaders.authorizationHeader: "<Your token here>",
  },
);

Documentation here


问:
Problem with the DevExpress XtraGridView control
I have one xtragrid control on my devxpress form .  I've created the columns of my grid at runtime when i load the form . I'm developing the Field chooser for my grid view which is situated on the same form. For that i used the repositoryItemCheckedComboBoxEditcontrol & in that control i added the column names which will be present in the xtragrid.

Basically i created the columns to the xtragrid with the Visible property to false. When user checks particular column name by using repositoryItemCheckedComboBoxEdit  then i set the Visible to true & again if user unchecked the column name then again i set the visible to false. & while creating column i set the width of the column.

Problem which i'm facing is that if user select the all fields from the repositoryItemCheckedComboBoxEdit  then the grid control should show the horizontal scroll bar automatically when require.

And another problem is that with the columns is besides setting the width of the column, it is not showing the required width of that column . it shrinks that all column width .

code which i use for creating column to the xtragridview at run time is as follows -

```<code> public void AddGridColumn(string fieldName, string caption, int nRowWidth, RepositoryItem Item, object oCollection, string DisplayMember, string ValueMember, string format, FormatType type)
        {
            DevExpress.XtraGrid.Columns.GridColumn column = ColumnView.Columns.AddField(fieldName);
            column.Caption = caption;
            column.ColumnEdit = Item;
            column.DisplayFormat.FormatType = type;
            column.DisplayFormat.FormatString = format;
            column.VisibleIndex =  ColumnView.VisibleColumns.Count;
            column.Width = nRowWidth;
        }
</code>```

code for the field chooser is as follows -
I used this function for filling the items of the repositoryItemCheckedComboBoxEdit  control

```<code>private void FieldCollection()
    {
        allFields = new ArrayList();
        columnNames = new Dictionary<string, string>();
        allFields.Clear();
        repositoryItemCheckedComboBoxEdit1.Items.Clear();
        for (int i = 0; i < gvBase.Columns.Count; i++)
        {
            allFields.Add(gvBase.Columns[i].Caption );
            if (gvBase.Columns[i].FieldName != "ContactID")
            {
                if (gvBase.Columns[i].Visible == true)
                {
                    if (gvBase.Columns[i].Caption != "Label1" && gvBase.Columns[i].Caption != "Label2" && gvBase.Columns[i].Caption != "Label3" && gvBase.Columns[i].Caption != "Label4" && gvBase.Columns[i].Caption != "Label5")
                        repositoryItemCheckedComboBoxEdit1.Items.Add(gvBase.Columns[i].Caption, CheckState.Checked);
                    if (!columnNames.ContainsKey(gvBase.Columns[i].Caption))
                        columnNames.Add(gvBase.Columns[i].Caption, gvBase.Columns[i].FieldName);
                }
                else
                {
                    if (gvBase.Columns[i].Caption != "Label1" && gvBase.Columns[i].Caption != "Label2" && gvBase.Columns[i].Caption != "Label3" && gvBase.Columns[i].Caption != "Label4" && gvBase.Columns[i].Caption != "Label5")

                        repositoryItemCheckedComboBoxEdit1.Items.Add(gvBase.Columns[i].Caption, CheckState.Unchecked);
                    if (!columnNames.ContainsKey(gvBase.Columns[i].FieldName))
                        columnNames.Add(gvBase.Columns[i].Caption, gvBase.Columns[i].FieldName);

                }
            }
        }
        cmbFieldChooser.EditValue = "";
    }
</code>```

this is used for the repositoryItemCheckedComboBoxEdit control event -

```<code>private void cmbFieldChooser_EditValueChanged(object sender, EventArgs e)
        {
            ArrayList temp = new ArrayList();
            temp.AddRange(allFields);

            string[] strFields = cmbFieldChooser.EditValue.ToString().Split(',');
            for (int i = 0; i < strFields.Length; i++)
            {
                if (temp.Contains(strFields[i].Trim()))
                    temp.Remove(strFields[i].Trim());
                if (strFields[i] != "")
                {
                    if (columnNames.ContainsKey(strFields[i].Trim()))
                    {
                        if (gvBase.Columns[columnNames[strFields[i].Trim()]].Visible == false)
                        {
                            gvBase.Columns[columnNames[strFields[i].Trim()]].Visible = true;
                            gvBase.Columns[columnNames[strFields[i].Trim()]].BestFit();

                        }
                    }
                }
            }
            if (temp.Count < 20)
            {
                for (int j = 0; j < temp.Count; j++)
                {
                    if (columnNames.ContainsKey(temp[j].ToString().Trim()))
                    {
                        gvBase.Columns[columnNames[temp[j].ToString().Trim()]].Visible = false;
                    }
                }
            }
            cmbFieldChooser.EditValue = repositoryItemCheckedComboBoxEdit1.GetCheckedItems();
            if ((cmbFieldChooser.EditValue.ToString()).Split(',').Length > 5)
            {
                gvBase.OptionsView.ColumnAutoWidth = false;
                gvBase.BestFitColumns();
                gvBase.HorzScrollVisibility = ScrollVisibility.Always;
            }
            else
            {
                gvBase.OptionsView.ColumnAutoWidth = true;
                gvBase.HorzScrollVisibility = ScrollVisibility.Never;
            }

        }
</code>```

How to resolve this problem?

thanks.

答:
How many columns do you have in your Grid?

I see you have code there to turn off the ColumnAutoWidth once you go past 5 columns (ie 6 columns or more). Have you debugged this condition to ensure the ColumnAutoWidth is indeed being turned off?

As per BestFitColumns Help Doc the BestFitColumns will only calculate for the first n rows as per the BestFitMaxRowCount property unless it it set to -1, could this be a cause?

The other thing that seems a little odd if that you are setting the EditValue of cmdFieldChooser within the cmdFieldChooser_EditValueChanged event... why so?

ContentLicense: CC BY-SA 3.0

Body:
I have one xtragrid control on my devxpress form .  I've created the columns of my grid at runtime when i load the form . I'm developing the Field chooser for my grid view which is situated on the same form. For that i used the repositoryItemCheckedComboBoxEditcontrol & in that control i added the column names which will be present in the xtragrid.

Basically i created the columns to the xtragrid with the Visible property to false. When user checks particular column name by using repositoryItemCheckedComboBoxEdit  then i set the Visible to true & again if user unchecked the column name then again i set the visible to false. & while creating column i set the width of the column.

Problem which i'm facing is that if user select the all fields from the repositoryItemCheckedComboBoxEdit  then the grid control should show the horizontal scroll bar automatically when require.

And another problem is that with the columns is besides setting the width of the column, it is not showing the required width of that column . it shrinks that all column width .

code which i use for creating column to the xtragridview at run time is as follows -

 public void AddGridColumn(string fieldName, string caption, int nRowWidth, RepositoryItem Item, object oCollection, string DisplayMember, string ValueMember, string format, FormatType type)
        {
            DevExpress.XtraGrid.Columns.GridColumn column = ColumnView.Columns.AddField(fieldName);
            column.Caption = caption;
            column.ColumnEdit = Item;
            column.DisplayFormat.FormatType = type;
            column.DisplayFormat.FormatString = format;
            column.VisibleIndex =  ColumnView.VisibleColumns.Count;
            column.Width = nRowWidth;
        }

code for the field chooser is as follows -
I used this function for filling the items of the repositoryItemCheckedComboBoxEdit  control

private void FieldCollection()
    {
        allFields = new ArrayList();
        columnNames = new Dictionary<string, string>();
        allFields.Clear();
        repositoryItemCheckedComboBoxEdit1.Items.Clear();
        for (int i = 0; i < gvBase.Columns.Count; i++)
        {
            allFields.Add(gvBase.Columns[i].Caption );
            if (gvBase.Columns[i].FieldName != "ContactID")
            {
                if (gvBase.Columns[i].Visible == true)
                {
                    if (gvBase.Columns[i].Caption != "Label1" && gvBase.Columns[i].Caption != "Label2" && gvBase.Columns[i].Caption != "Label3" && gvBase.Columns[i].Caption != "Label4" && gvBase.Columns[i].Caption != "Label5")
                        repositoryItemCheckedComboBoxEdit1.Items.Add(gvBase.Columns[i].Caption, CheckState.Checked);
                    if (!columnNames.ContainsKey(gvBase.Columns[i].Caption))
                        columnNames.Add(gvBase.Columns[i].Caption, gvBase.Columns[i].FieldName);
                }
                else
                {
                    if (gvBase.Columns[i].Caption != "Label1" && gvBase.Columns[i].Caption != "Label2" && gvBase.Columns[i].Caption != "Label3" && gvBase.Columns[i].Caption != "Label4" && gvBase.Columns[i].Caption != "Label5")

                        repositoryItemCheckedComboBoxEdit1.Items.Add(gvBase.Columns[i].Caption, CheckState.Unchecked);
                    if (!columnNames.ContainsKey(gvBase.Columns[i].FieldName))
                        columnNames.Add(gvBase.Columns[i].Caption, gvBase.Columns[i].FieldName);

                }
            }
        }
        cmbFieldChooser.EditValue = "";
    }

this is used for the repositoryItemCheckedComboBoxEdit control event -

private void cmbFieldChooser_EditValueChanged(object sender, EventArgs e)
        {
            ArrayList temp = new ArrayList();
            temp.AddRange(allFields);

            string[] strFields = cmbFieldChooser.EditValue.ToString().Split(',');
            for (int i = 0; i < strFields.Length; i++)
            {
                if (temp.Contains(strFields[i].Trim()))
                    temp.Remove(strFields[i].Trim());
                if (strFields[i] != "")
                {
                    if (columnNames.ContainsKey(strFields[i].Trim()))
                    {
                        if (gvBase.Columns[columnNames[strFields[i].Trim()]].Visible == false)
                        {
                            gvBase.Columns[columnNames[strFields[i].Trim()]].Visible = true;
                            gvBase.Columns[columnNames[strFields[i].Trim()]].BestFit();

                        }
                    }
                }
            }
            if (temp.Count < 20)
            {
                for (int j = 0; j < temp.Count; j++)
                {
                    if (columnNames.ContainsKey(temp[j].ToString().Trim()))
                    {
                        gvBase.Columns[columnNames[temp[j].ToString().Trim()]].Visible = false;
                    }
                }
            }
            cmbFieldChooser.EditValue = repositoryItemCheckedComboBoxEdit1.GetCheckedItems();
            if ((cmbFieldChooser.EditValue.ToString()).Split(',').Length > 5)
            {
                gvBase.OptionsView.ColumnAutoWidth = false;
                gvBase.BestFitColumns();
                gvBase.HorzScrollVisibility = ScrollVisibility.Always;
            }
            else
            {
                gvBase.OptionsView.ColumnAutoWidth = true;
                gvBase.HorzScrollVisibility = ScrollVisibility.Never;
            }

        }

How to resolve this problem?

thanks.


问:
trying to create a little color picker, why is context.getImageData() returning only zeros when i use flex display in css?
i created a gradient in javascript,

```<code>var colorCanvas = document.getElementById('color_canvas');
var ColorCtx = colorCanvas .getContext('2d');

var color = 'rgba(0,0,255,1)';
    let gradientH = ColorCtx .createLinearGradient(0, 0, ColorCtx.canvas.width, 0);
    gradientH.addColorStop(0, '#fff');
    gradientH.addColorStop(1, color);
    ColorCtx .fillStyle = gradientH;
    ColorCtx .fillRect(0, 0, ColorCtx.canvas.width, ColorCtx.canvas.height);

    let gradientV = ColorCtx .createLinearGradient(0, 0, 0, 300);
    gradientV.addColorStop(0, 'rgba(0,0,0,0)');
    gradientV.addColorStop(1, '#000');
    ColorCtx .fillStyle = gradientV;
    ColorCtx .fillRect(0, 0, ColorCtx.canvas.width,
    ColorCtx .canvas.height);
</code>```

the above creates a gradient.

```<code>colorCanvas.addEventListener('click',function(event){
    let x = event.clientX;
    let y = event.clientY;
    pixel = ColorCtx.getImageData(x,y,1,1);   // Read pixel Color
    let rgb = `rgba(${pixel.data[0]},${pixel.data[1]},${pixel.data[2]},${pixel.data[3]})`;
    console.log(rgb);
    document.getElementById('pick').style = 'background-color: ' + rgb;
    document.querySelector('.picked-color').style = 'background-color: ' + rgb;

});
</code>```

the event listener is suppose to pick a color from mouse position and make it the background color of the two divs

```<code>document.getElementById('pick').style = 'background-color: ' + rgb;
document.querySelector('.picked-color').style = 'background-color: ' + rgb;
</code>```

but the pixel = ColorCtx.getImageData(x,y,1,1); only returns an array of zeros

答:
Figured it out my self,

let rect = event.target.getBoundingClientRect();
    let x = event.clientX - rect.left; // x position within the element.
    let y = event.clientY - rect.top; // y position within the element
```

Figured I was trying to get the mouse position but not within the intended element, thats why the color picker was not working, with the code above included, it works as I intended.

Body:
i created a gradient in javascript,

var colorCanvas = document.getElementById('color_canvas');
var ColorCtx = colorCanvas .getContext('2d');

var color = 'rgba(0,0,255,1)';
    let gradientH = ColorCtx .createLinearGradient(0, 0, ColorCtx.canvas.width, 0);
    gradientH.addColorStop(0, '#fff');
    gradientH.addColorStop(1, color);
    ColorCtx .fillStyle = gradientH;
    ColorCtx .fillRect(0, 0, ColorCtx.canvas.width, ColorCtx.canvas.height);

    let gradientV = ColorCtx .createLinearGradient(0, 0, 0, 300);
    gradientV.addColorStop(0, 'rgba(0,0,0,0)');
    gradientV.addColorStop(1, '#000');
    ColorCtx .fillStyle = gradientV;
    ColorCtx .fillRect(0, 0, ColorCtx.canvas.width,
    ColorCtx .canvas.height);

the above creates a gradient.

colorCanvas.addEventListener('click',function(event){
    let x = event.clientX;
    let y = event.clientY;
    pixel = ColorCtx.getImageData(x,y,1,1);   // Read pixel Color
    let rgb = `rgba(${pixel.data[0]},${pixel.data[1]},${pixel.data[2]},${pixel.data[3]})`;
    console.log(rgb);
    document.getElementById('pick').style = 'background-color: ' + rgb;
    document.querySelector('.picked-color').style = 'background-color: ' + rgb;

});

the event listener is suppose to pick a color from mouse position and make it the background color of the two divs

document.getElementById('pick').style = 'background-color: ' + rgb;
document.querySelector('.picked-color').style = 'background-color: ' + rgb;

but the pixel = ColorCtx.getImageData(x,y,1,1); only returns an array of zeros

Body:
Figured it out my self,

let rect = event.target.getBoundingClientRect();
    let x = event.clientX - rect.left; // x position within the element.
    let y = event.clientY - rect.top; // y position within the element

Figured I was trying to get the mouse position but not within the intended element, thats why the color picker was not working, with the code above included, it works as I intended.


问:
Why is video.srcObject not working with WebRTC?
Here's my simple code

import React, { useState, useEffect, useRef } from "react";
import io from "socket.io-client";

import Navbar from "../../components/Navbar";

export default function ViewerRoom() {
  const [socket, setSocket] = useState(null);
  const localVid = useRef();
  const remoteVid = useRef();

  useEffect(() => {
    const init = async () => {
      //Get URL Params
      const searchParams = new URL(window.location).searchParams;
      const proxy = searchParams.get("v");

      //Define Streams
      const localStream = await navigator.mediaDevices.getUserMedia({
        video: true,
        audio: true,
      });
      let remoteStream = new MediaStream();

      //Create RTCPeerConnection
      const servers = {
        iceServers: [
          {
            urls: [
              "stun:stun1.l.google.com:19302",
              "stun:stun1.2.google.com:19302",
            ],
          },
        ],
        iceCandidatePoolSize: 10,
      };
      let pc = new RTCPeerConnection(servers);

      //Add the tracks
      localStream.getTracks().forEach((track) => {
        pc.addTrack(track, localStream);
      });

      //Pull the tracks from the remote stream
      pc.ontrack = (event) => {
        event.streams[0].getTracks().forEach((track) => {
          remoteStream.addTrack(track);
        });
      };

      //Initialize Socket
      const newSocket = io("http://localhost:1829");
      setSocket(newSocket);

      //Create Data object
      const data = {
        id: proxy,
      };

      //Join Call
      newSocket.emit("join", JSON.stringify(data));

      //Joined Call Auth Callback
      newSocket.on("join-call", (buffer) => {
        //Deserialize
        const data = JSON.parse(buffer);

        //Get that SDP
        const answer = data.offer;
        const remoteDescription = new RTCSessionDescription(answer);
        pc.setRemoteDescription(remoteDescription);

        //Get the Ice Candidates and loop over and add them
        data.iceCandidates.map((ice) => {
          const candidate = new RTCIceCandidate(ice);
          pc.addIceCandidate(candidate);
        });
      });

      localVid.current.srcObject = localStream;
      remoteVid.current.srcObject = remoteStream;
    };
    init();
  }, []);
  return (
    <>
      <Navbar />

        <>
          <video
            ref={localVid}
            muted
            id="local"
            autoPlay
            width={600}
            height={480}
          />
          <video
            ref={remoteVid}
            id="remote"
            autoPlay
            width={600}
            height={480}
            style={{ marginLeft: "150px" }}
          />
        </>

    </>
  );
}
```

Everything works. The socket connects, peer.ontrack gets fired, the stream gets updated, everything. But the video doesn't display in the UI. The local video gets displayed, but not the remote one. What's wrong? Is it a bug in the browser API? Is it something in my code? I've been scratching my head for hours but I can't get a solution for this problem

If it helps, I'm using React and Es6. Please give a solution

答:
I think the remote video element doesn't play because autoplay doesn't work unless the element is also muted. But calling play() programmatically should work.

```<code>// ...
localVid.current.srcObject = localStream;
remoteVid.current.srcObject = remoteStream;
remoteVid.current.play();
</code>```

Body:
Here's my simple code

import React, { useState, useEffect, useRef } from "react";
import io from "socket.io-client";

import Navbar from "../../components/Navbar";

export default function ViewerRoom() {
  const [socket, setSocket] = useState(null);
  const localVid = useRef();
  const remoteVid = useRef();

  useEffect(() => {
    const init = async () => {
      //Get URL Params
      const searchParams = new URL(window.location).searchParams;
      const proxy = searchParams.get("v");

      //Define Streams
      const localStream = await navigator.mediaDevices.getUserMedia({
        video: true,
        audio: true,
      });
      let remoteStream = new MediaStream();

      //Create RTCPeerConnection
      const servers = {
        iceServers: [
          {
            urls: [
              "stun:stun1.l.google.com:19302",
              "stun:stun1.2.google.com:19302",
            ],
          },
        ],
        iceCandidatePoolSize: 10,
      };
      let pc = new RTCPeerConnection(servers);

      //Add the tracks
      localStream.getTracks().forEach((track) => {
        pc.addTrack(track, localStream);
      });

      //Pull the tracks from the remote stream
      pc.ontrack = (event) => {
        event.streams[0].getTracks().forEach((track) => {
          remoteStream.addTrack(track);
        });
      };

      //Initialize Socket
      const newSocket = io("http://localhost:1829");
      setSocket(newSocket);

      //Create Data object
      const data = {
        id: proxy,
      };

      //Join Call
      newSocket.emit("join", JSON.stringify(data));

      //Joined Call Auth Callback
      newSocket.on("join-call", (buffer) => {
        //Deserialize
        const data = JSON.parse(buffer);

        //Get that SDP
        const answer = data.offer;
        const remoteDescription = new RTCSessionDescription(answer);
        pc.setRemoteDescription(remoteDescription);

        //Get the Ice Candidates and loop over and add them
        data.iceCandidates.map((ice) => {
          const candidate = new RTCIceCandidate(ice);
          pc.addIceCandidate(candidate);
        });
      });

      localVid.current.srcObject = localStream;
      remoteVid.current.srcObject = remoteStream;
    };
    init();
  }, []);
  return (
    <>
      <Navbar />

        <>
          <video
            ref={localVid}
            muted
            id="local"
            autoPlay
            width={600}
            height={480}
          />
          <video
            ref={remoteVid}
            id="remote"
            autoPlay
            width={600}
            height={480}
            style={{ marginLeft: "150px" }}
          />
        </>

    </>
  );
}

Everything works. The socket connects, peer.ontrack gets fired, the stream gets updated, everything. But the video doesn't display in the UI. The local video gets displayed, but not the remote one. What's wrong? Is it a bug in the browser API? Is it something in my code? I've been scratching my head for hours but I can't get a solution for this problem

If it helps, I'm using React and Es6. Please give a solution

Body:
I think the remote video element doesn't play because autoplay doesn't work unless the element is also muted. But calling play() programmatically should work.

// ...
localVid.current.srcObject = localStream;
remoteVid.current.srcObject = remoteStream;
remoteVid.current.play();


问:
How can i protect routes in my reactjs project?
i need help to protect routes in my reactjs project , i want that only a loged user can access to Home Page, and only not loged user can access to the signin and signup forms</p>
```<code>import "./App.css";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Navbar from "./components/Navbar";
import SignInForm from "./pages/SignInForm";
import SignUpForm from "./pages/SignUpForm";
import Wallet from "./components/Wallet";
import Welcome from "./pages/Welcome";
import Home from "./pages/Home";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Welcome></Welcome>}></Route>
        <Route path="/signin" element={<Navbar></Navbar>}>
          <Route index element={<SignInForm></SignInForm>}></Route>
        </Route>
        <Route path="/signup" element={<Navbar></Navbar>}>
          <Route index element={<SignUpForm></SignUpForm>}></Route>
        </Route>
        <Route path="/wallet" element={<Navbar></Navbar>}>
          <Route index element={<Wallet></Wallet>}></Route>
        </Route>
        <Route path="/home" element={<Navbar></Navbar>}>
          <Route index element={<Home></Home>}></Route>
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

export default App;
</code>```

答:
Make a component like below and adjust it to your requirement.

```<code>
import React from "react";
import { Redirect, Route } from "react-router-dom";
import auth from "../services/authService";

function ProtectedRoute({ path, component: Component, render, ...rest }) {
  return (
    <Route
      {...rest}
      render={(props) => {
        if (!auth.getCurrentUser())
          return (
            <Redirect
              to={{
                pathname: "/login",
                state: { from: props.location },
              }}
            />
          );
        return Component ? <Component {...props} /> : render(props);
      }}
    />
  );
}

export default ProtectedRoute;

</code>```

then wrap the route like this

```<code>  <ProtectedRoute path="/wallet" element={<Navbar></Navbar>}/>

</code>```

Body:
i need help to protect routes in my reactjs project , i want that only a loged user can access to Home Page, and only not loged user can access to the signin and signup forms

import "./App.css";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Navbar from "./components/Navbar";
import SignInForm from "./pages/SignInForm";
import SignUpForm from "./pages/SignUpForm";
import Wallet from "./components/Wallet";
import Welcome from "./pages/Welcome";
import Home from "./pages/Home";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Welcome></Welcome>}></Route>
        <Route path="/signin" element={<Navbar></Navbar>}>
          <Route index element={<SignInForm></SignInForm>}></Route>
        </Route>
        <Route path="/signup" element={<Navbar></Navbar>}>
          <Route index element={<SignUpForm></SignUpForm>}></Route>
        </Route>
        <Route path="/wallet" element={<Navbar></Navbar>}>
          <Route index element={<Wallet></Wallet>}></Route>
        </Route>
        <Route path="/home" element={<Navbar></Navbar>}>
          <Route index element={<Home></Home>}></Route>
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

export default App;

Body:
Make a component like below and adjust it to your requirement.

import React from "react";
import { Redirect, Route } from "react-router-dom";
import auth from "../services/authService";

function ProtectedRoute({ path, component: Component, render, ...rest }) {
  return (
    <Route
      {...rest}
      render={(props) => {
        if (!auth.getCurrentUser())
          return (
            <Redirect
              to={{
                pathname: "/login",
                state: { from: props.location },
              }}
            />
          );
        return Component ? <Component {...props} /> : render(props);
      }}
    />
  );
}

export default ProtectedRoute;

then wrap the route like this

  <ProtectedRoute path="/wallet" element={<Navbar></Navbar>}/>


问:
How to get if statement to print a value inside array
In this example, I am trying to make it so that if variable == one of the values in the array, it prints "This Works".

```<code>array = [1, 2]

one = 1
two = 2

def trying():
    if one == array:
        print("This Works")

print(trying())
</code>```

I understand that one and array isn't the same, but how do I go about getting one and the value 1 to equal, so that this code works

答:
Try with in instead of ==,

```<code>array = [1, 2]

one = 1
two = 2

def trying():
    if one in array:
        print("This Works")

print(trying())
</code>```

Body:
In this example, I am trying to make it so that if variable == one of the values in the array, it prints "This Works".

array = [1, 2]

one = 1
two = 2

def trying():
    if one == array:
        print("This Works")

print(trying())

I understand that one and array isn't the same, but how do I go about getting one and the value 1 to equal, so that this code works

Body:
Try with in instead of ==,

array = [1, 2]

one = 1
two = 2

def trying():
    if one in array:
        print("This Works")

print(trying())


问:
Python - How do i delete more than one character on python using slice method, find and rfind
I need some help in removing two sets of curly brackets with string.Right now it's only removing one set. I tired to use find and rfind to find the first and last occurence of the string index and using slice method to cut out the curly brackets but it can only remove one set of it.

It should work something like that

Input: {fefeef}this{feofeow}.4849

Output this.4849

Here is my code

```<code> def help_mmtf():

       while True:

           user_input = input("Filename?")
           text_input = str(user_input)

           if (text_input !=""):

                word = text_input

                index1 = word.find("{")
                index2 = word.find("}")
                print(index1)
                print(index2)

                index3 = word.rfind("{")
                index4 = word.rfind("}")

                print(index3)
                print(index4)

                splice_input = text_input[:index1] + text_input[index4+1:]
                print(f'"{splice_input}"')

      else:

               break

</code>```

答:
You can use sub

```<code>import re

def help_mmtf():
    while True:

        user_input = input("Filename?")
        text_input = str(user_input)

        if (text_input != ""):
            word = text_input

            splice_input = re.sub("\{.*?\}", "", word)
            print(f'"{splice_input}"')

        else:

         break
</code>```

Time complexity: O(2^m + n).

or you can use the for loop

```<code>def help_mmtf():
    while True:

        user_input = input("Filename?")
        text_input = str(user_input)

        if (text_input != ""):
            splice_input = ''

            paren = 0
            for ch in text_input:

                if ch == '{':
                    paren = paren + 1
                    splice_input = splice_input

                elif (ch == '}') and paren:
                    splice_input = splice_input
                    paren = paren - 1

                elif not paren:
                    splice_input += ch

            print(splice_input)

        else:

         break
</code>```

Time complexity: O(n).

Body:
I need some help in removing two sets of curly brackets with string.Right now it's only removing one set. I tired to use find and rfind to find the first and last occurence of the string index and using slice method to cut out the curly brackets but it can only remove one set of it.

It should work something like that

Input: {fefeef}this{feofeow}.4849

Output this.4849

Here is my code

 def help_mmtf():

       while True:

           user_input = input("Filename?")
           text_input = str(user_input)

           if (text_input !=""):

                word = text_input

                index1 = word.find("{")
                index2 = word.find("}")
                print(index1)
                print(index2)

                index3 = word.rfind("{")
                index4 = word.rfind("}")

                print(index3)
                print(index4)

                splice_input = text_input[:index1] + text_input[index4+1:]
                print(f'"{splice_input}"')

      else:

               break

Body:
You can use sub

import re

def help_mmtf():
    while True:

        user_input = input("Filename?")
        text_input = str(user_input)

        if (text_input != ""):
            word = text_input

            splice_input = re.sub("\{.*?\}", "", word)
            print(f'"{splice_input}"')

        else:

         break

Time complexity: O(2^m + n).

or you can use the for loop

def help_mmtf():
    while True:

        user_input = input("Filename?")
        text_input = str(user_input)

        if (text_input != ""):
            splice_input = ''

            paren = 0
            for ch in text_input:

                if ch == '{':
                    paren = paren + 1
                    splice_input = splice_input

                elif (ch == '}') and paren:
                    splice_input = splice_input
                    paren = paren - 1

                elif not paren:
                    splice_input += ch

            print(splice_input)

        else:

         break

Time complexity: O(n).


问:
Wizad like control in xamarin form
Hi I am newbie to xamarin.form where I have to include following control as bellow something like wizard to get collection of steps from user to do a operation.

In xamarin forms are there anything like this as out of the box ? if so what it is ? if there is not such a thing how to start to build it ?

When I google that
System.Web.UI.WebControls.Wizard
say it has something like this but I could not understand how to integrate with it.does it possible to do with this.

答:
Just use a Frame:</p>
```<code><StackLayout>
    <Frame x:Name="Step001">
        <Label Text="My Stuff" />
    </Frame>
    <Frame x:Name="Step002">
        <Label Text="My Stuff" />
    </Frame>
</StackLayout>

private void setupStep001(bool isVisibleStep){
    Step001.IsVisible = isVisibleStep;
    Step002.IsVisible = !isVisibleStep;
}
</code>```

Title: Wizad like control in xamarin form

Body:
Just use a Frame:

<StackLayout>
    <Frame x:Name="Step001">
        <Label Text="My Stuff" />
    </Frame>
    <Frame x:Name="Step002">
        <Label Text="My Stuff" />
    </Frame>
</StackLayout>

private void setupStep001(bool isVisibleStep){
    Step001.IsVisible = isVisibleStep;
    Step002.IsVisible = !isVisibleStep;
}


问:
How to mention the team-tag when sending message in channel
Currently, I have a chat-bot app that sends the message on the channel.

Also, it is capable of tagging a user. The below code is responsible for sending user mentioned message.

```<code>await turnContext.sendActivity(
 {
    text: `Hello <at>@${members[0].dispName}</at>`,
    entities: [
                {
                            type: 'mention',
                            mentioned: {
                                id: members[0].userName,
                                name: members[0].dispName,
                            },
                            text: `<at>@${members[0].dispName}</at>`,
                }
    ],
});
</code>```

Further, I am trying to mention the Team Tag. Is there a way I can pass the team-id or something else to mention the Tag

Note: Team tag means - tag in a team

答:
Now you can create/Get teams tags using Beta Graph API.
Reference doc: Create teamworkTag - Microsoft Graph beta | Microsoft Docs

You can also get the created tags using below Beta Graph API:
GET /teams/{team-Id}/tags
List teamworkTags - Microsoft Graph beta | Microsoft Docs

You can also send the message with mentioning teams tag using below API
Post request: https://graph.microsoft.com/v1.0/teams/{team id}/channels/{channel id}/messages

Message body:

```<code>{
  "subject": "This is very urgent!",
  "importance": "urgent",
  "body": {
    "contentType": "html",
    "content": "Programmatically mentioning of Tagged users <at id=\"0\">String_1234</at>"
  },
  "mentions": [
    {
      "id": 0,
      "mentionText": "String_1234",
      "mentioned": {
        "tag": {
          "@odata.type": "#microsoft.graph.teamworkTagIdentity",
          "id": ""/*tag id*/,
          "displayName": ""/* tag name*/
        }
      }
    }
  ]
}
</code>```

Body:
Currently, I have a chat-bot app that sends the message on the channel.

Also, it is capable of tagging a user. The below code is responsible for sending user mentioned message.

await turnContext.sendActivity(
 {
    text: `Hello <at>@${members[0].dispName}</at>`,
    entities: [
                {
                            type: 'mention',
                            mentioned: {
                                id: members[0].userName,
                                name: members[0].dispName,
                            },
                            text: `<at>@${members[0].dispName}</at>`,
                }
    ],
});

Further, I am trying to mention the Team Tag. Is there a way I can pass the team-id or something else to mention the Tag

Note: Team tag means - tag in a team

Body:
Now you can create/Get teams tags using Beta Graph API.
Reference doc: Create teamworkTag - Microsoft Graph beta | Microsoft Docs

You can also get the created tags using below Beta Graph API:
GET /teams/{team-Id}/tags
List teamworkTags - Microsoft Graph beta | Microsoft Docs

You can also send the message with mentioning teams tag using below API
Post request: https://graph.microsoft.com/v1.0/teams/{team id}/channels/{channel id}/messages

Message body:

{
  "subject": "This is very urgent!",
  "importance": "urgent",
  "body": {
    "contentType": "html",
    "content": "Programmatically mentioning of Tagged users <at id=\"0\">String_1234</at>"
  },
  "mentions": [
    {
      "id": 0,
      "mentionText": "String_1234",
      "mentioned": {
        "tag": {
          "@odata.type": "#microsoft.graph.teamworkTagIdentity",
          "id": ""/*tag id*/,
          "displayName": ""/* tag name*/
        }
      }
    }
  ]
}


答:
This is how I did it, basically, you wrap the route and check if the user is authenticated, if he's not, redirect back to where he should be.
This uses react-router v6, you can find more information about it in the authentication section of the official docs. They have a very good example on stackblitz, you should take a look at that.

```<code>import { useIsAuthenticated } from "your-auth-package"
import { Navigate, useLocation } from "react-router";

const AuthenticatedRoute = ({ children }) => {
  const isAuthenticated = useIsAuthenticated();
  const location = useLocation();

  // not logged in
  if (!isAuthenticated) {
    console.log("not authenticated");
    return <Navigate to="/" state={{ from: location }} replace />;
  }

  return children;
};
</code>```
```<code><BrowserRouter>
  <Routes>
    <Route
      path="/dashboard"
      element={
        <AuthenticatedRoute>
          <Dashboard />
        </AuthenticatedRoute>
      }
    />
  </Routes>
</BrowserRouter>
</code>```

Title: How can i protect routes in my reactjs project?

Body:
This is how I did it, basically, you wrap the route and check if the user is authenticated, if he's not, redirect back to where he should be.
This uses react-router v6, you can find more information about it in the authentication section of the official docs. They have a very good example on stackblitz, you should take a look at that.

import { useIsAuthenticated } from "your-auth-package"
import { Navigate, useLocation } from "react-router";

const AuthenticatedRoute = ({ children }) => {
  const isAuthenticated = useIsAuthenticated();
  const location = useLocation();

  // not logged in
  if (!isAuthenticated) {
    console.log("not authenticated");
    return <Navigate to="/" state={{ from: location }} replace />;
  }

  return children;
};

<BrowserRouter>
  <Routes>
    <Route
      path="/dashboard"
      element={
        <AuthenticatedRoute>
          <Dashboard />
        </AuthenticatedRoute>
      }
    />
  </Routes>
</BrowserRouter>


问:
VB.Net - Write Records To Access Quickly
I have a large number of records to add to a Access database in realtime.  The items are temperatures, water flows etc from electronic instruments.

The code I have is below, can it be improved or is there a different way to add records more quickly - currently, 10,000 records takes approx. 10secs.

I am currently simulating the data to prove the concept of adding large number of records.

Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As New OleDbDataAdapter
Dim sql As String

connetionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Neil Cooley\Desktop\Database1.accdb"

connection.Open()

Dim stop_watch_1 As New Stopwatch
Dim getDate As Date = Date.Now

For i As Integer = 1 To 10000 Step 1
  sql = "INSERT INTO Lines VALUES('TAG " & i.ToString & "','" & i.ToString & "','192','" & getDate & "')"

  oledbAdapter.InsertCommand = New OleDbCommand(sql, connection)
  oledbAdapter.InsertCommand.ExecuteNonQuery()
Next
stop_watch_1.Stop()
MsgBox("Row(s) Inserted !! - " & stop_watch_1.ElapsedMilliseconds.ToString)
```

答:
I would try using a data table - it should run faster.

Say, try like this:

```<code>   Dim sqlCon As New OleDbConnection(My.Settings.AccessDB)

    Dim strSql As String = "SELECT * FROM tblBig WHERE ID = 0"
    Dim cmdSQL As New OleDbCommand(strSQL, sqlCon)

    Dim rstData = New DataTable
    sqlCon.Open()
    rstData.Load(cmdSQL.ExecuteReader)

    Dim da As New OleDbDataAdapter(cmdSQL)
    Dim daU As New OleDbCommandBuilder(da)

    Dim stop_watch_1 As New Stopwatch
    Dim getDate As Date = Date.Now

    stop_watch_1.Start()

    For i As Integer = 1 To 10000

        Dim MyNewRow = rstData.NewRow

        MyNewRow("City") = "City" & i
        MyNewRow("FirstName") = "FirstName " & i
        MyNewRow("LastName") = "LastName " & i

        rstData.Rows.Add(MyNewRow)

        If (i Mod 500) = 0 Then
            'Debug.Print("data write" & stop_watch_1.ElapsedMilliseconds / 1000)
            da.Update(rstData)
            rstData.Clear()
        End If
    Next

    ' write data back to database
    da.Update(rstData)

    sqlCon.Close()

    stop_watch_1.Stop()

    MsgBox("Row(s) Inserted !! - " & stop_watch_1.ElapsedMilliseconds / 1000)
</code>```

I have it set to write out in above every 500 rows.

However, you are getting about 1,000 rows per second, and I not at all sure you going to increase that rate - it is VERY good rates you already seeing, and I can't say the above is going to help much.

edit: I feel the need for speed!!! SUPER FAST!!!

Ok, if you want to bring this down from 10 seconds to 1/3 of a second?

by-pass the .net providers. Hit the database DIRECT with the native DAO object library. You get about 30 times faster.

So, try this:

```<code>Imports Microsoft.Office.Interop.Access
</code>```

and then do this:

```<code>   Dim dbE As New Dao.DBEngine
    Dim db As Dao.Database

    db = dbE.OpenDatabase("C:\test\test44.accdb")

    Dim rstData As Dao.Recordset

    rstData = db.OpenRecordset("tblBig")

    Dim stop_watch_1 As New Stopwatch
    stop_watch_1.Start()

    For i As Integer = 1 To 10000

        rstData.AddNew()
        rstData("City").Value = "City" & i
        rstData("FirstName").Value = "FirstName " & i
        rstData("LastName").Value = "LastName " & i
        rstData.Update()

    Next

    db.Close()

    stop_watch_1.Stop()
    MsgBox("Row(s) Inserted !! - " & stop_watch_1.ElapsedMilliseconds / 1000)
</code>```

You find a min of 30x faster - even more. So, DIRECT use of the data engine, and by-passing all of the .net providers? You EASY insert 10,000 rows in WELL UNDER 1 second.

Body:
I would try using a data table - it should run faster.

Say, try like this:

   Dim sqlCon As New OleDbConnection(My.Settings.AccessDB)

    Dim strSql As String = "SELECT * FROM tblBig WHERE ID = 0"
    Dim cmdSQL As New OleDbCommand(strSQL, sqlCon)

    Dim rstData = New DataTable
    sqlCon.Open()
    rstData.Load(cmdSQL.ExecuteReader)

    Dim da As New OleDbDataAdapter(cmdSQL)
    Dim daU As New OleDbCommandBuilder(da)

    Dim stop_watch_1 As New Stopwatch
    Dim getDate As Date = Date.Now

    stop_watch_1.Start()

    For i As Integer = 1 To 10000

        Dim MyNewRow = rstData.NewRow

        MyNewRow("City") = "City" & i
        MyNewRow("FirstName") = "FirstName " & i
        MyNewRow("LastName") = "LastName " & i

        rstData.Rows.Add(MyNewRow)

        If (i Mod 500) = 0 Then
            'Debug.Print("data write" & stop_watch_1.ElapsedMilliseconds / 1000)
            da.Update(rstData)
            rstData.Clear()
        End If
    Next

    ' write data back to database
    da.Update(rstData)

    sqlCon.Close()

    stop_watch_1.Stop()

    MsgBox("Row(s) Inserted !! - " & stop_watch_1.ElapsedMilliseconds / 1000)

I have it set to write out in above every 500 rows.

However, you are getting about 1,000 rows per second, and I not at all sure you going to increase that rate - it is VERY good rates you already seeing, and I can't say the above is going to help much.

edit: I feel the need for speed!!! SUPER FAST!!!

Ok, if you want to bring this down from 10 seconds to 1/3 of a second?

by-pass the .net providers. Hit the database DIRECT with the native DAO object library. You get about 30 times faster.

So, try this:

Imports Microsoft.Office.Interop.Access

and then do this:

   Dim dbE As New Dao.DBEngine
    Dim db As Dao.Database

    db = dbE.OpenDatabase("C:\test\test44.accdb")

    Dim rstData As Dao.Recordset

    rstData = db.OpenRecordset("tblBig")

    Dim stop_watch_1 As New Stopwatch
    stop_watch_1.Start()

    For i As Integer = 1 To 10000

        rstData.AddNew()
        rstData("City").Value = "City" & i
        rstData("FirstName").Value = "FirstName " & i
        rstData("LastName").Value = "LastName " & i
        rstData.Update()

    Next

    db.Close()

    stop_watch_1.Stop()
    MsgBox("Row(s) Inserted !! - " & stop_watch_1.ElapsedMilliseconds / 1000)

You find a min of 30x faster - even more. So, DIRECT use of the data engine, and by-passing all of the .net providers? You EASY insert 10,000 rows in WELL UNDER 1 second.


问:
c# - Change color of groups in ObjectListView
When building groups in ObjectListView, how do I change the color of the group? In default groups are shown with a dark blue line in dark blue forecolor. How can I change it?</p>

答:
You can achieve this with a regular winforms Listview as below:

Imports System.ComponentModel
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Runtime.InteropServices
Imports System.Windows.Forms

<ToolboxItem(False)>
Public Class ListViewExt
    Inherits ListView

    Private _groupHeadingBackColor As Color = Color.Gray
    Public Property GroupHeadingBackColor() As Color
        Get
            Return _groupHeadingBackColor
        End Get
        Set(ByVal value As Color)
            _groupHeadingBackColor = value
        End Set
    End Property

    Private _groupHeadingForeColor As Color = Color.Black
    Public Property GroupHeadingForeColor() As Color
        Get
            Return _groupHeadingForeColor
        End Get
        Set(ByVal value As Color)
            _groupHeadingForeColor = value
        End Set
    End Property

    Private _groupHeadingFont As Font = Me.Font
    Public Property GroupHeadingFont() As Font
        Get
            Return _groupHeadingFont
        End Get
        Set(ByVal value As Font)
            _groupHeadingFont = value
        End Set
    End Property

    Private _separatorColor As Color
    Public Property SeparatorColor() As Color
        Get
            Return _separatorColor
        End Get
        Set(ByVal value As Color)
            _separatorColor = value
        End Set
    End Property

    Public Const LVCDI_ITEM = &H0
    Public Const LVCDI_GROUP = &H1
    Public Const LVCDI_ITEMSLIST = &H2

    Public Const LVM_FIRST = &H1000
    Public Const LVM_GETGROUPRECT = (LVM_FIRST + 98)
    Public Const LVM_ENABLEGROUPVIEW = (LVM_FIRST + 157)
    Public Const LVM_SETGROUPINFO = (LVM_FIRST + 147)
    Public Const LVM_GETGROUPINFO = (LVM_FIRST + 149)
    Public Const LVM_REMOVEGROUP = (LVM_FIRST + 150)
    Public Const LVM_MOVEGROUP = (LVM_FIRST + 151)
    Public Const LVM_GETGROUPCOUNT = (LVM_FIRST + 152)
    Public Const LVM_GETGROUPINFOBYINDEX = (LVM_FIRST + 153)
    Public Const LVM_MOVEITEMTOGROUP = (LVM_FIRST + 154)

    Public Const WM_LBUTTONUP = &H202

    <StructLayout(LayoutKind.Sequential)>
    Public Structure NMHDR
        Public hwndFrom As IntPtr
        Public idFrom As IntPtr
        Public code As Integer
    End Structure

    <StructLayout(LayoutKind.Sequential)>
    Public Structure RECT
        Public left As Integer
        Public top As Integer
        Public right As Integer
        Public bottom As Integer
    End Structure

    <StructLayout(LayoutKind.Sequential)>
    Public Structure NMCUSTOMDRAW
        Public hdr As NMHDR
        Public dwDrawStage As Integer
        Public hdc As IntPtr
        Public rc As RECT
        Public dwItemSpec As IntPtr
        Public uItemState As UInteger
        Public lItemlParam As IntPtr
    End Structure

    <StructLayout(LayoutKind.Sequential)>
    Public Structure NMLVCUSTOMDRAW
        Public nmcd As NMCUSTOMDRAW
        Public clrText As Integer
        Public clrTextBk As Integer
        Public iSubItem As Integer
        Public dwItemType As Integer
        Public clrFace As Integer
        Public iIconEffect As Integer
        Public iIconPhase As Integer
        Public iPartId As Integer
        Public iStateId As Integer
        Public rcText As RECT
        Public uAlign As UInteger
    End Structure

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)>
    Public Structure LVGROUP
        Public cbSize As UInteger
        Public mask As UInteger
        '<MarshalAs(UnmanagedType.LPTStr)>
        'Public pszHeader As String
        Public pszHeader As IntPtr
        Public cchHeader As Integer
        '<MarshalAs(UnmanagedType.LPTStr)>
        'Public pszFooter As String
        Public pszFooter As IntPtr
        Public cchFooter As Integer
        Public iGroupId As Integer
        Public stateMask As UInteger
        Public state As UInteger
        Public uAlign As UInteger

        '<MarshalAs(UnmanagedType.LPTStr)>
        'Public pszSubtitle As String
        Public pszSubtitle As IntPtr
        Public cchSubtitle As UInteger
        '<MarshalAs(UnmanagedType.LPTStr)>
        'Public pszTask As String
        Public pszTask As IntPtr
        Public cchTask As UInteger
        '<MarshalAs(UnmanagedType.LPTStr)>
        'Public pszDescriptionTop As String
        Public pszDescriptionTop As IntPtr
        Public cchDescriptionTop As UInteger
        '<MarshalAs(UnmanagedType.LPTStr)>
        'Public pszDescriptionBottom As String
        Public pszDescriptionBottom As IntPtr
        Public cchDescriptionBottom As UInteger
        Public iTitleImage As Integer
        Public iExtendedImage As Integer
        Public iFirstItem As Integer
        Public cItems As UInteger
        '<MarshalAs(UnmanagedType.LPTStr)>
        'Public pszSubsetTitle As String
        Public pszSubsetTitle As IntPtr
        Public cchSubsetTitle As UInteger
    End Structure

    <Flags>
    Public Enum CDRF
        CDRF_DODEFAULT = &H0
        CDRF_NEWFONT = &H2
        CDRF_SKIPDEFAULT = &H4
        CDRF_DOERASE = &H8
        CDRF_SKIPPOSTPAINT = &H100
        CDRF_NOTIFYPOSTPAINT = &H10
        CDRF_NOTIFYITEMDRAW = &H20
        CDRF_NOTIFYSUBITEMDRAW = &H20
        CDRF_NOTIFYPOSTERASE = &H40
    End Enum

    <Flags>
    Public Enum CDDS
        CDDS_PREPAINT = &H1
        CDDS_POSTPAINT = &H2
        CDDS_PREERASE = &H3
        CDDS_POSTERASE = &H4
        CDDS_ITEM = &H10000
        CDDS_ITEMPREPAINT = (CDDS_ITEM Or CDDS_PREPAINT)
        CDDS_ITEMPOSTPAINT = (CDDS_ITEM Or CDDS_POSTPAINT)
        CDDS_ITEMPREERASE = (CDDS_ITEM Or CDDS_PREERASE)
        CDDS_ITEMPOSTERASE = (CDDS_ITEM Or CDDS_POSTERASE)
        CDDS_SUBITEM = &H20000
    End Enum

    Public Const LVGF_NONE = &H0
    Public Const LVGF_HEADER = &H1
    Public Const LVGF_FOOTER = &H2
    Public Const LVGF_STATE = &H4
    Public Const LVGF_ALIGN = &H8
    Public Const LVGF_GROUPID = &H10

    Public Const LVGF_SUBTITLE = &H100 'pszSubtitle is valid
    Public Const LVGF_TASK = &H200 'pszTask is valid
    Public Const LVGF_DESCRIPTIONTOP = &H400 'pszDescriptionTop is valid
    Public Const LVGF_DESCRIPTIONBOTTOM = &H800 'pszDescriptionBottom is valid
    Public Const LVGF_TITLEIMAGE = &H1000 'iTitleImage is valid
    Public Const LVGF_EXTENDEDIMAGE = &H2000 'iExtendedImage is valid
    Public Const LVGF_ITEMS = &H4000 'iFirstItem and cItems are valid
    Public Const LVGF_SUBSET = &H8000 'pszSubsetTitle is valid
    Public Const LVGF_SUBSETITEMS = &H10000 'readonly, cItems holds count of items in visible subset, iFirstItem is valid

    Public Const LVGS_NORMAL = &H0
    Public Const LVGS_COLLAPSED = &H1
    Public Const LVGS_HIDDEN = &H2
    Public Const LVGS_NOHEADER = &H4
    Public Const LVGS_COLLAPSIBLE = &H8
    Public Const LVGS_FOCUSED = &H10
    Public Const LVGS_SELECTED = &H20
    Public Const LVGS_SUBSETED = &H40
    Public Const LVGS_SUBSETLINKFOCUSED = &H80

    Public Const LVGA_HEADER_LEFT = &H1
    Public Const LVGA_HEADER_CENTER = &H2
    Public Const LVGA_HEADER_RIGHT = &H4 'Don't forget to validate exclusivity
    Public Const LVGA_FOOTER_LEFT = &H8
    Public Const LVGA_FOOTER_CENTER = &H10
    Public Const LVGA_FOOTER_RIGHT = &H20 'Don't forget to validate exclusivity

    Public Const LVGGR_GROUP = 0 ' Entire expanded group
    Public Const LVGGR_HEADER = 1  ' Header only (collapsed group)
    Public Const LVGGR_LABEL = 2  ' Label only
    Public Const LVGGR_SUBSETLINK = 3  'subset link only

    <DllImport("User32.dll", EntryPoint:="SendMessageW", SetLastError:=True)>
    Public Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Integer, ByRef lParam As IntPtr) As Integer
    End Function

    <DllImport("User32.dll", EntryPoint:="SendMessageW", SetLastError:=True)>
    Public Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Integer, ByRef lParam As LVGROUP) As Integer
    End Function

    <DllImport("User32.dll", EntryPoint:="SendMessageW", SetLastError:=True)>
    Public Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Integer, ByRef lParam As RECT) As Integer
    End Function

    <DllImport("User32.dll", EntryPoint:="PostMessageW", SetLastError:=True)>
    Public Shared Function PostMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Integer, ByRef lParam As IntPtr) As Integer
    End Function

    Public Function SetGroupInfo(ByVal hWnd As IntPtr, nGroupID As Integer, nSate As UInteger) As Integer
        Dim lvg As LVGROUP = New LVGROUP()
        lvg.cbSize = CUInt(Marshal.SizeOf(lvg))
        lvg.mask = LVGF_STATE Or LVGF_GROUPID Or LVGF_HEADER
        ' for test
        Dim nRet2 As Integer = SendMessage(hWnd, LVM_GETGROUPINFO, nGroupID, lvg)

        lvg.state = nSate
        lvg.mask = LVGF_STATE
        nRet2 = SendMessage(hWnd, LVM_SETGROUPINFO, nGroupID, lvg)
        Return -1
    End Function

    Protected Overrides Sub WndProc(ByRef m As Message)
        If m.Msg = WM_REFLECT + WM_NOFITY Then
            Dim pnmhdr = CType(m.GetLParam(GetType(NMHDR)), NMHDR)
            If pnmhdr.code = NM_CUSTOMDRAW Then
                Dim pnmlv = CType(m.GetLParam(GetType(NMLVCUSTOMDRAW)), NMLVCUSTOMDRAW)
                Select Case pnmlv.nmcd.dwDrawStage
                    Case CDDS.CDDS_PREPAINT
                        If (pnmlv.dwItemType = LVCDI_GROUP) Then
                            Dim rectHeader As RECT = New RECT()
                            rectHeader.top = LVGGR_HEADER
                            Dim nItem As Integer = CInt(pnmlv.nmcd.dwItemSpec)
                            'If (nItem = 0) Then
                            Dim nRet As Integer = SendMessage(m.HWnd, LVM_GETGROUPRECT, nItem, rectHeader)
                            Using g As Graphics = Graphics.FromHdc(pnmlv.nmcd.hdc)

                                Dim rect As New Rectangle(rectHeader.left, rectHeader.top, rectHeader.right - rectHeader.left, rectHeader.bottom - rectHeader.top)

                                'Dim linGrBrush As New LinearGradientBrush(New System.Drawing.Point(0, 0), New System.Drawing.Point(rectHeader.right, rectHeader.bottom), Color.Blue, Color.LightCyan)
                                Dim BgBrush As New SolidBrush(_groupHeadingBackColor)
                                g.FillRectangle(BgBrush, rect)

                                Dim lvg As LVGROUP = New LVGROUP()
                                lvg.cbSize = CUInt(Marshal.SizeOf(lvg))
                                lvg.mask = LVGF_STATE Or LVGF_GROUPID Or LVGF_HEADER
                                Dim nRet2 As Integer = SendMessage(m.HWnd, LVM_GETGROUPINFO, nItem, lvg)
                                Dim sText = Marshal.PtrToStringUni(lvg.pszHeader)

                                Dim textSize As SizeF = g.MeasureString(sText, _groupHeadingFont)

                                Dim RectHeightMiddle As Integer = CInt((rect.Height - textSize.Height) / 2)

                                rect.Offset(10, RectHeightMiddle)

                                Using drawBrush As New SolidBrush(_groupHeadingForeColor)

                                    g.DrawString(sText, _groupHeadingFont, drawBrush, rect)
                                    rect.Offset(0, -RectHeightMiddle)

                                    Using lineBrush As New SolidBrush(_separatorColor)
                                        g.DrawLine(New Pen(lineBrush), rect.X + g.MeasureString(sText, _groupHeadingFont).Width + 10,
                                                                    rect.Y + CInt(rect.Height / 2),
                                                                    rect.X + CInt(rect.Width * 95 / 100),
                                                                    rect.Y + CInt(rect.Height / 2))

                                    End Using
                                End Using
                            End Using
                            m.Result = New IntPtr(CDRF.CDRF_SKIPDEFAULT)
                            'End If
                        Else
                            m.Result = New IntPtr(CDRF.CDRF_NOTIFYITEMDRAW)
                        End If
                    Case CDDS.CDDS_ITEMPREPAINT
                        m.Result = New IntPtr(CDRF.CDRF_NOTIFYSUBITEMDRAW Or CDRF.CDRF_NOTIFYPOSTPAINT)
                    Case CDDS.CDDS_ITEMPOSTPAINT
                End Select
            End If
            Return
        Else
            MyBase.WndProc(m)
        End If
    End Sub

    Private Const NM_FIRST As Integer = 0
    Private Const NM_CLICK As Integer = NM_FIRST - 2
    Private Const NM_CUSTOMDRAW As Integer = NM_FIRST - 12
    Private Const WM_REFLECT As Integer = &H2000
    Private Const WM_NOFITY As Integer = &H4E
End Class
```


问:
Get dict's value by key name in Django Tempaltes
in my view.py I have a function with field: context ={'user':user, 'user_gpds':user_gpds, 'team':team, 'team_gpds':team_gpds}
which I return:

```<code>return render(request, 'app/team_gpd_page/team_gpds.html', context)
</code>```

in my templates I have next code:

```<code>{% for gpd in {{context|key:team_gpds}} %}
            <tr>
                <td><a class="nav-link" href="/gpd/{{gpd.employee.end_user_id}}">GPD</a></td>
                <td>{{gpd.employee}}</td>
                <td>{{gpd.gpd_year}}</td>
                <td>{{gpd.gpd_start}}</td>
                <td>{{gpd.gpd_end}}</td>
                <td>{{gpd.gpd_status}}</td>
            </tr>
            {% endfor %}
</code>```

But in result I have had an empty fields. I am also trying context.team_gpds and context.get('team_gpds'). What I am doing wrong?

答:
If team_gpds is querysets then you can loop through querysets as

```<code>{% for gpd in team_gpds %}
   <tr>
       <td><a class="nav-link" href="/gpd/{{gpd.employee.end_user_id}}">GPD</a></td>
       <td>{{gpd.employee}}</td>
       <td>{{gpd.gpd_year}}</td>
       <td>{{gpd.gpd_start}}</td>
       <td>{{gpd.gpd_end}}</td>
       <td>{{gpd.gpd_status}}</td>
    </tr>
{% endfor %}
</code>```

Body:
in my view.py I have a function with field: context ={'user':user, 'user_gpds':user_gpds, 'team':team, 'team_gpds':team_gpds}
which I return:

return render(request, 'app/team_gpd_page/team_gpds.html', context)

in my templates I have next code:

{% for gpd in {{context|key:team_gpds}} %}

                GPD
                {{gpd.employee}}
                {{gpd.gpd_year}}
                {{gpd.gpd_start}}
                {{gpd.gpd_end}}
                {{gpd.gpd_status}}

            {% endfor %}

But in result I have had an empty fields. I am also trying context.team_gpds and context.get('team_gpds'). What I am doing wrong?

Body:
If team_gpds is querysets then you can loop through querysets as

{% for gpd in team_gpds %}
   <tr>
       <td><a class="nav-link" href="/gpd/{{gpd.employee.end_user_id}}">GPD</a></td>
       <td>{{gpd.employee}}</td>
       <td>{{gpd.gpd_year}}</td>
       <td>{{gpd.gpd_start}}</td>
       <td>{{gpd.gpd_end}}</td>
       <td>{{gpd.gpd_status}}</td>
    </tr>
{% endfor %}


问:
Set GTK Application Title
I've created a GTK 4 app using Gtk-rs. In all the tutorials and documentation I read through to create it, I saw that I should make the application_id something unique such as "org.rk.Counter", which is what I have chosen. Unfortunately, that shows up as the application name in the dock. Here is my code:

```<code>fn main() {
        // Create a new application
        let app = Application::builder()
            .application_id("org.rk.Counter")
            .build();

        // Load CSS and connect to "activate" signal of "app"
        app.connect_startup(|_| load_css());
        app.connect_activate(build_ui);

        // Run the application
        app.run();
    }

fn build_ui(app: &Application) {
    // ...

    let window = ApplicationWindow::builder()
        .application(app)
        .title("rkCounter")
        .child(&main_grid)
        .build();

    window.set_default_size(290, 380);

    window.present();
}
</code>```

The window has the correct title, as set in build_ui(), but here is how it displays on the icon:

How can I change the title for the icon? Should I disregard the advice I saw and change the .application_id()?

答:
The way you create the application id is correct. It's really just meant as a way of uniquely identifying your application.

What you're looking for here is glib::functions::set_application_name()

Title: Set GTK Application Title

Body:
I've created a GTK 4 app using Gtk-rs. In all the tutorials and documentation I read through to create it, I saw that I should make the application_id something unique such as "org.rk.Counter", which is what I have chosen. Unfortunately, that shows up as the application name in the dock. Here is my code:

fn main() {
        // Create a new application
        let app = Application::builder()
            .application_id("org.rk.Counter")
            .build();

        // Load CSS and connect to "activate" signal of "app"
        app.connect_startup(|_| load_css());
        app.connect_activate(build_ui);

        // Run the application
        app.run();
    }

fn build_ui(app: &Application) {
    // ...

    let window = ApplicationWindow::builder()
        .application(app)
        .title("rkCounter")
        .child(&main_grid)
        .build();

    window.set_default_size(290, 380);

    window.present();
}

The window has the correct title, as set in build_ui(), but here is how it displays on the icon:

How can I change the title for the icon? Should I disregard the advice I saw and change the .application_id()?


问:
Dbeaver no active connection
Running Dbeaver 21.3.0 on ubuntu linux 21.1.  The problem I have is that when trying to execute a query I get a "no active connection error".  However in the Database navigator screen I have an active remote ms-sql-server connection, can see the overall database, and all files in it, can check all of their column properties etc.  How do I get this particular script to associate with that particular database?  I'd also like to have it automatically associated the next time I open the script?</p>

答: Updating @Tomek's answer: After choosing set active connection you need to select the DB you want to work with. And it appears there is no way for now to auto-link your SQL script with certain DB, so you need to choose active connection for any new or opened SQL script.

Title: Dbeaver no active connection


问:
How to solve "java.lang.NoClassDefFoundError: io/reactivex/rxjava3/core/Observer"
I am trying to run suite using testNG but I got this error :
I search some information on this issue on this site and the web
but with no success.

```<code>[RemoteTestNG] detected TestNG version 7.4.0
java.lang.NoClassDefFoundError: io/reactivex/rxjava3/core/Observer
    at resources.ExtentReporterNG.getReportObject(ExtentReporterNG.java:14)
    at ShufersalMiron.Sprod.Listeners.<init>(Listeners.java:22)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
    at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128)
    at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:350)
    at java.base/java.lang.Class.newInstance(Class.java:645)
    at org.testng.internal.InstanceCreator.newInstance(InstanceCreator.java:30)
    at org.testng.TestNG.addListeners(TestNG.java:964)
    at org.testng.TestNG.initializeConfiguration(TestNG.java:924)
    at org.testng.TestNG.initializeEverything(TestNG.java:1012)
    at org.testng.remote.support.RemoteTestNG6_12.initialize(RemoteTestNG6_12.java:22)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:98)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.ClassNotFoundException: io.reactivex.rxjava3.core.Observer
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:606)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    ... 17 more
</code>```

TestNG :

```<code><?xml version="1.0" encoding="UTF-8"?>

    <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
    <suite name="Suite">
    <listeners>
    <listener class-name="ShufersalMiron.Sprod.Listeners"/>
    </listeners>
    <test name="Test1">
    <classes>
    <class name="ShufersalMiron.Sprod.PA_Coupons"/>
    </classes>
    </test> <!-- Test -->
    <test  name="Test2">
    <classes>
    <class name="ShufersalMiron.Sprod.PA_SupermeCoins"/>
    </classes>
    </test> <!-- Test -->
    </suite> <!-- Suite -->
</code>```

I search for an answer in the net but with no success.

Can someone help me with this issue please ?

答:
This issue looks like not related to TestNG.

It just appeared within TestNG lifecycle, so testng is mentioned in the error.

The line, which throws the error is:

```<code>at resources.ExtentReporterNG.getReportObject(ExtentReporterNG.java:14)
</code>```

and this is your project class, but from ExtentReporterNG name I guess you are using

https://github.com/extent-framework/extentreports-java tool for generation the report.

And the error message:

```<code>"java.lang.NoClassDefFoundError: io/reactivex/rxjava3/core/Observer"
</code>```

means that the issue is related to io.reactivex.rxjava3 dependency.

And extentreports-java has this dependency in pom.xml.

https://github.com/extent-framework/extentreports-java/blob/master/pom.xml

```<code><dependency>
    <groupId>io.reactivex.rxjava3</groupId>
    <artifactId>rxjava</artifactId>
    <version>3.0.4</version>
</dependency>
</code>```

Conclusion

I believe you have some other dependency in the project, which has another version of io.reactivex and the final resolved dependency doesn't contain io/reactivex/rxjava3/core/Observer class.

So, I suggest to add this dependency explicitly to the project pom.

```<code><dependency>
    <groupId>io.reactivex.rxjava3</groupId>
    <artifactId>rxjava</artifactId>
    <version>3.0.4</version>
</dependency>
</code>```

Investigate Maven Dependency Conflicts

Add this plugin with next configuration to your pom (<plugins>..</plugins>)

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-enforcer-plugin</artifactId>
    <version>3.0.0</version>
    <configuration>
        <rules><DependencyConvergence/></rules>
    </configuration>
</plugin>
</code>```

and execute:

```<code>mvn enforcer:enforce
</code>```

This will print all potential dependency issues.

Look for lines with

```<code>io.reactivex
</code>```

There are should be dependencies, which introduces the potential

```<code>java.lang.NoClassDefFoundError: io/reactivex/rxjava3/core/Observer
</code>```

error.

Body:
I am trying to run suite using testNG but I got this error :
I search some information on this issue on this site and the web
but with no success.

[RemoteTestNG] detected TestNG version 7.4.0
java.lang.NoClassDefFoundError: io/reactivex/rxjava3/core/Observer
    at resources.ExtentReporterNG.getReportObject(ExtentReporterNG.java:14)
    at ShufersalMiron.Sprod.Listeners.<init>(Listeners.java:22)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
    at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128)
    at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:350)
    at java.base/java.lang.Class.newInstance(Class.java:645)
    at org.testng.internal.InstanceCreator.newInstance(InstanceCreator.java:30)
    at org.testng.TestNG.addListeners(TestNG.java:964)
    at org.testng.TestNG.initializeConfiguration(TestNG.java:924)
    at org.testng.TestNG.initializeEverything(TestNG.java:1012)
    at org.testng.remote.support.RemoteTestNG6_12.initialize(RemoteTestNG6_12.java:22)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:98)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.ClassNotFoundException: io.reactivex.rxjava3.core.Observer
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:606)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    ... 17 more

TestNG :

<?xml version="1.0" encoding="UTF-8"?>

    <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
    <suite name="Suite">
    <listeners>
    <listener class-name="ShufersalMiron.Sprod.Listeners"/>
    </listeners>
    <test name="Test1">
    <classes>
    <class name="ShufersalMiron.Sprod.PA_Coupons"/>
    </classes>
    </test>
    <test  name="Test2">
    <classes>
    <class name="ShufersalMiron.Sprod.PA_SupermeCoins"/>
    </classes>
    </test>
    </suite>

I search for an answer in the net but with no success.

Can someone help me with this issue please ?

Body:
This issue looks like not related to TestNG.

It just appeared within TestNG lifecycle, so testng is mentioned in the error.

The line, which throws the error is:

at resources.ExtentReporterNG.getReportObject(ExtentReporterNG.java:14)

and this is your project class, but from ExtentReporterNG name I guess you are using

https://github.com/extent-framework/extentreports-java tool for generation the report.

And the error message:

"java.lang.NoClassDefFoundError: io/reactivex/rxjava3/core/Observer"

means that the issue is related to io.reactivex.rxjava3 dependency.

And extentreports-java has this dependency in pom.xml.

https://github.com/extent-framework/extentreports-java/blob/master/pom.xml

<dependency>
    <groupId>io.reactivex.rxjava3</groupId>
    <artifactId>rxjava</artifactId>
    <version>3.0.4</version>
</dependency>

Conclusion

I believe you have some other dependency in the project, which has another version of io.reactivex and the final resolved dependency doesn't contain io/reactivex/rxjava3/core/Observer class.

So, I suggest to add this dependency explicitly to the project pom.

<dependency>
    <groupId>io.reactivex.rxjava3</groupId>
    <artifactId>rxjava</artifactId>
    <version>3.0.4</version>
</dependency>

Investigate Maven Dependency Conflicts

Add this plugin with next configuration to your pom (<plugins>..</plugins>)

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-enforcer-plugin</artifactId>
    <version>3.0.0</version>
    <configuration>
        <rules><DependencyConvergence/></rules>
    </configuration>
</plugin>

and execute:

mvn enforcer:enforce

This will print all potential dependency issues.

Look for lines with

io.reactivex

There are should be dependencies, which introduces the potential

java.lang.NoClassDefFoundError: io/reactivex/rxjava3/core/Observer

error.


问:
How can I debug the cause when I get 401 when calling an OAuth authenticated web api point in ASP.NET
I have an ASP.NET Web API project in (running on .NET 4.8 - not .NET Core). I have setup 'Bearer token' authentication by adding:

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType))
     }
 }
</code>```

And in Startup.cs:

```<code>public class Startup1
{
    public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

        app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    TokenValidationParameters = new TokenValidationParameters()
                                                {
                                                    ValidateIssuer = true,
                                                    ValidIssuer = "https://www.example.com", //some string, normally web url,
                                                }
                });
    }
}
</code>```

And in my controller method, I add [Authorize] in my controller API.

But when I call the endpoint in my browser, I checked that it has a bearer token in the http header. The body of the http response is

"Message":"Authorization has been denied for this request."

How can I debug my issue? as I don't see any exception or any message in log.

答:
Could you add these parameters in your code and try:

```<code>app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,
            AllowedAudiences = new[] { "Any" },
            IssuerSecurityKeyProviders = new IIssuerSecurityKeyProvider[] {
                new SymmetricKeyIssuerSecurityKeyProvider(issuer, secret)
            }
        });

var issuer = ConfigurationManager.AppSettings["issuer"];
var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);
</code>```

Add these parameters in App config file:

```<code><appSettings>
  <add key="issuer" value="http://localhost:xxx/"/>
  <add key="secret" value="YourToken"/>
</appSettings>
</code>```

Body:
I have an ASP.NET Web API project in (running on .NET 4.8 - not .NET Core). I have setup 'Bearer token' authentication by adding:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType))
     }
 }

And in Startup.cs:

public class Startup1
{
    public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

        app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    TokenValidationParameters = new TokenValidationParameters()
                                                {
                                                    ValidateIssuer = true,
                                                    ValidIssuer = "https://www.example.com", //some string, normally web url,
                                                }
                });
    }
}

And in my controller method, I add [Authorize] in my controller API.

But when I call the endpoint in my browser, I checked that it has a bearer token in the http header. The body of the http response is

"Message":"Authorization has been denied for this request."

How can I debug my issue? as I don't see any exception or any message in log.

Body:
Could you add these parameters in your code and try:

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,
            AllowedAudiences = new[] { "Any" },
            IssuerSecurityKeyProviders = new IIssuerSecurityKeyProvider[] {
                new SymmetricKeyIssuerSecurityKeyProvider(issuer, secret)
            }
        });

var issuer = ConfigurationManager.AppSettings["issuer"];
var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);

Add these parameters in App config file:

<appSettings>
  <add key="issuer" value="http://localhost:xxx/"/>
  <add key="secret" value="YourToken"/>
</appSettings>


问:
How can I access local variables from inside a C++11 anonymous function?
I'm doing a simple normalization on a vector (weights), trying to make use of STL algorithms to make the code as clean as possible (I realize this is pretty trivial with for loops):

```<code>float tot = std::accumulate(weights.begin(), weights.end(), 0.0);
std::transform(weights.begin(), weights.end(), [](float x)->float{return(x/tot);});
</code>```

At present, tot is not visible to the anonymous function, so this doesn't compile. What's the best way of making a local variable visible to the anonymous function?

答:
The lambda can "capture" variables from the ambient scope:

```<code>[ ..., N, ... ](int a, int b) -> int  { return (a + b) * N; }
 ^^^^^^^^^^^^^  ^^^^^^^^^^^^     ^^^^
 captured vars  local params     ret.type
</code>```

You can capture by value or by reference, and you can use the special syntax [=] and [&] to capture anything from the ambient scope, i.e. anything you actually end up using.

Body:
I'm doing a simple normalization on a vector (weights), trying to make use of STL algorithms to make the code as clean as possible (I realize this is pretty trivial with for loops):

float tot = std::accumulate(weights.begin(), weights.end(), 0.0);
std::transform(weights.begin(), weights.end(), [](float x)->float{return(x/tot);});

At present, tot is not visible to the anonymous function, so this doesn't compile. What's the best way of making a local variable visible to the anonymous function?

Body:
The lambda can "capture" variables from the ambient scope:

[ ..., N, ... ](int a, int b) -> int  { return (a + b) * N; }
 ^^^^^^^^^^^^^  ^^^^^^^^^^^^     ^^^^
 captured vars  local params     ret.type

You can capture by value or by reference, and you can use the special syntax [=] and [&] to capture anything from the ambient scope, i.e. anything you actually end up using.


问:
Add Computed Column with Liquibase
How can I add a computed column in liquibase? When I run the following SQL in a sql tag I get the computed value I'm expecting:

```<code>ALTER TABLE TableName
ADD ComputedColumn AS (CASE WHEN DateColumn1 IS NULL OR DateColumn2 IS NULL
THEN 0
ELSE DATEDIFF(DAY, DateColumn1, DateColumn2) END)
</code>```

How do I do this without using an sql tag? I am able to get a column created with the following yaml:

- addColumn:
      tableName: TableName
      columns:
        - column:
            name: ComputedColumn
            type: tinyint
            constraints:
              nullable: true
            defaultValueComputed:  0
            valueComputed:  DATEDIFF(DAY, DateColumn1, DateColumn2) END

However the column type is not Computed like when I run the raw SQL.

答:
I had to fixup helpful @Philipp's answer with modifySql as Liquibase 3.x kept generating empty type placeholder [] for SQL Server like in

ALTER TABLE [dbo].[TableName] ADD ComputedColumn as (case when ((([fieldFlagOne]+(0))+([fieldFlagTwo]+(0)))+([fieldFlagThree]+(0)))=(3) then (1) else (0) end) []

that led to [S1000][1038] An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Add a name or single space as the alias name. error:

```<code>- addColumn:
  tableName: TableName
  columns:
    - column:
        name: ComputedColumn as (case when ((([fieldFlagOne]+(0))+([fieldFlagTwo]+(0)))+([fieldFlagThree]+(0)))=(3) then (1) else (0) end)
        computed: true
        type: ""
        constraints:
          nullable: true
- modifySql:
    replace:
      replace: "[]"
      with: ""
</code>```

Title: Add Computed Column with Liquibase

Body:
How can I add a computed column in liquibase? When I run the following SQL in a sql tag I get the computed value I'm expecting:

ALTER TABLE TableName
ADD ComputedColumn AS (CASE WHEN DateColumn1 IS NULL OR DateColumn2 IS NULL
THEN 0
ELSE DATEDIFF(DAY, DateColumn1, DateColumn2) END)

How do I do this without using an sql tag? I am able to get a column created with the following yaml:

- addColumn:
      tableName: TableName
      columns:
        - column:
            name: ComputedColumn
            type: tinyint
            constraints:
              nullable: true
            defaultValueComputed:  0
            valueComputed:  DATEDIFF(DAY, DateColumn1, DateColumn2) END

However the column type is not Computed like when I run the raw SQL.

Body:
I had to fixup helpful @Philipp's answer with modifySql as Liquibase 3.x kept generating empty type placeholder [] for SQL Server like in

ALTER TABLE [dbo].[TableName] ADD ComputedColumn as (case when ((([fieldFlagOne]+(0))+([fieldFlagTwo]+(0)))+([fieldFlagThree]+(0)))=(3) then (1) else (0) end) []

that led to [S1000][1038] An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Add a name or single space as the alias name. error:

- addColumn:
  tableName: TableName
  columns:
    - column:
        name: ComputedColumn as (case when ((([fieldFlagOne]+(0))+([fieldFlagTwo]+(0)))+([fieldFlagThree]+(0)))=(3) then (1) else (0) end)
        computed: true
        type: ""
        constraints:
          nullable: true
- modifySql:
    replace:
      replace: "[]"
      with: ""


问:
Json to excel using power query
I have some json on a website that i want to convert to excel using the power query option from web. But  I ran into a small problem. My json looks like this:

```<code>[
    {
        "id" : 1,
        "visitors" : 26,
        "some_number" : 1,
        "value" : 3500
    },
    {
        "id" : 2,
        "visitors" : 21,
        "some_number" : 5,
        "value" : 2000
    }
]
</code>```

but when i use from web i get this:

I can drill down into a record,convert it to a table, transpose and use first row as header but then i get just one row. How can i get all of my data to the table and not just one row?

答:
I have Excel Professional 2016 and I don't see the JSON option, but I can get to it via the "Other Sources" query option. Here are all the steps to convert a JSON array to a table.

Data > New Query > From Other Sources > From Web

Enter URL : "file:///C:/temp/document.json", (or a http web url) Press OK

A row is displayed with a "items" property and List type,

Click on "List", the items in list are displayed

Press "To Table" button in upper left corner, Press OK in next
dialog

A table with one column named "Column1" is displayed

Press the button next to the column name (has left and right arrows
on it)

Properties in the row object are selected

Uncheck "User Original column name as prefix", Press "OK"

Press "Close & Load" button in upper left corner

my file looks like

```<code> {
   "items": [{
       "code": "1",
       "name": "first"
     }, {
       "code": "2",
       "name": "second"
     }, {
       "code": "3",
       "name": "third"
     },
   ]
 }
</code>```

Title: Json to excel using power query

Body:
I have some json on a website that i want to convert to excel using the power query option from web. But  I ran into a small problem. My json looks like this:

[
    {
        "id" : 1,
        "visitors" : 26,
        "some_number" : 1,
        "value" : 3500
    },
    {
        "id" : 2,
        "visitors" : 21,
        "some_number" : 5,
        "value" : 2000
    }
]

but when i use from web i get this:

I can drill down into a record,convert it to a table, transpose and use first row as header but then i get just one row. How can i get all of my data to the table and not just one row?

Body:
I have Excel Professional 2016 and I don't see the JSON option, but I can get to it via the "Other Sources" query option. Here are all the steps to convert a JSON array to a table.

Data > New Query > From Other Sources > From Web

Enter URL : "file:///C:/temp/document.json", (or a http web url) Press OK

A row is displayed with a "items" property and List type,

Click on "List", the items in list are displayed

Press "To Table" button in upper left corner, Press OK in next
dialog

A table with one column named "Column1" is displayed

Press the button next to the column name (has left and right arrows
on it)

Properties in the row object are selected

Uncheck "User Original column name as prefix", Press "OK"

Press "Close & Load" button in upper left corner

my file looks like

 {
   "items": [{
       "code": "1",
       "name": "first"
     }, {
       "code": "2",
       "name": "second"
     }, {
       "code": "3",
       "name": "third"
     },
   ]
 }


问:
Subscript indices must either be real positive integers or logicals error with mean function in matlab
I have a giant data array where in every row I want to extract specific columns and then average the numbers I extract. This is my code:

```<code>for i=1:1000
    temp=data(i,:);
    index_data=temp([1,10,11,12,19]); %columns I want to extract
    data_final(i,1)=mean(index_data(~isnan(index_data)));
end
</code>```

I get an error on the first iteration. The array that is extracted is

```<code>[NaN NaN NaN NaN 15.64]
</code>```

And what I get when I type index_data(~isnan(index_data)) is 15.64, what I'd expect. However, I get an error of

```<code>??? Subscript indices must either be real positive integers or logicals.
Error in ==> mean(index_data(~isnan(index_data)))
</code>```

Calling this from the command line yields the same error. However, if I try with the covariance function (cov) I don't the get the error. This seems really weird to me!

Thanks for your help!

答:
I suspect that you have defined a variable mean with the same name as the built-in function. You can check using:

```<code>which mean
</code>```

To solve the problem, delete the variable from memory: clear mean, then correct all references of this variable...

Body:
I have a giant data array where in every row I want to extract specific columns and then average the numbers I extract. This is my code:

for i=1:1000
    temp=data(i,:);
    index_data=temp([1,10,11,12,19]); %columns I want to extract
    data_final(i,1)=mean(index_data(~isnan(index_data)));
end

I get an error on the first iteration. The array that is extracted is

[NaN NaN NaN NaN 15.64]

And what I get when I type index_data(~isnan(index_data)) is 15.64, what I'd expect. However, I get an error of

??? Subscript indices must either be real positive integers or logicals.
Error in ==> mean(index_data(~isnan(index_data)))

Calling this from the command line yields the same error. However, if I try with the covariance function (cov) I don't the get the error. This seems really weird to me!

Thanks for your help!

Body:
I suspect that you have defined a variable mean with the same name as the built-in function. You can check using:

which mean

To solve the problem, delete the variable from memory: clear mean, then correct all references of this variable...