问:
Removing rows in Excel file after import
Hello I have a json file that was created from results in Postman.  I have used C# to take this json file and convert it to a csv.  I am now trying to take it one step further by only returning rows that start with a specific string.  So, for example, on the first nine rows I see the following in the first column:

Get Token

Create SR ACH Setup

TC - ACH Setup

Get Token

Create SR ACH Disbursement

TC - ACH Disbursement

Get Token

Create SR ACH Receipt

TC - ACH Receipt

I have hundreds more rows in this column but you get the general idea

I only want rows in the csv that start with 'TC'.  So if it does not start with TC I want the rows removed.  What I have been doing is just formatting the csv as a table and then removing anything that does not start with a 'TC'.  This process does work but looking at a faster way to do this.

Here is my current code:

```<code>using Aspose.Cells;
using Aspose.Cells.Utility;
using DocumentFormat.OpenXml.Spreadsheet;
using Microsoft.AspNet.SignalR.Json;
using Newtonsoft.Json;

// create a blank Workbook object
var workbook = new Aspose.Cells.Workbook();
var worksheet = workbook.Worksheets[0];

//Read json file
string jsonInput = File.ReadAllText(@"C:\Users\kruepb\Desktop\Automation\22-5\Margin_22_5");

// set JsonLayoutOptions for formatting
JsonLayoutOptions options = new JsonLayoutOptions();
options.ArrayAsTable = true;

// Import JSON Data
Aspose.Cells.Utility.JsonUtility.ImportData(jsonInput, worksheet.Cells, 1, 0, options);

//Format sheet
worksheet.Cells.DeleteRows(0, 3);
worksheet.Cells.DeleteColumns(0, 9, false);
worksheet.Cells.DeleteColumn(2);
worksheet.Cells.DeleteColumns(3, 5000, false);

//Add headers
worksheet.Cells["A1"].PutValue("Name");
worksheet.Cells["B1"].PutValue("URL");
worksheet.Cells["C1"].PutValue("Passed?");
worksheet.Cells["D1"].PutValue("Output");

// save CSV file
workbook.Save(@"C:\Users\kruepb\Desktop\Automation\22-5\Margin_22_5.csv");
</code>```

Body:
Hello I have a json file that was created from results in Postman.  I have used C# to take this json file and convert it to a csv.  I am now trying to take it one step further by only returning rows that start with a specific string.  So, for example, on the first nine rows I see the following in the first column:

Get Token

Create SR ACH Setup

TC - ACH Setup

Get Token

Create SR ACH Disbursement

TC - ACH Disbursement

Get Token

Create SR ACH Receipt

TC - ACH Receipt

I have hundreds more rows in this column but you get the general idea

I only want rows in the csv that start with 'TC'.  So if it does not start with TC I want the rows removed.  What I have been doing is just formatting the csv as a table and then removing anything that does not start with a 'TC'.  This process does work but looking at a faster way to do this.

Here is my current code:

using Aspose.Cells;
using Aspose.Cells.Utility;
using DocumentFormat.OpenXml.Spreadsheet;
using Microsoft.AspNet.SignalR.Json;
using Newtonsoft.Json;

// create a blank Workbook object
var workbook = new Aspose.Cells.Workbook();
var worksheet = workbook.Worksheets[0];

//Read json file
string jsonInput = File.ReadAllText(@"C:\Users\kruepb\Desktop\Automation\22-5\Margin_22_5");

// set JsonLayoutOptions for formatting
JsonLayoutOptions options = new JsonLayoutOptions();
options.ArrayAsTable = true;

// Import JSON Data
Aspose.Cells.Utility.JsonUtility.ImportData(jsonInput, worksheet.Cells, 1, 0, options);

//Format sheet
worksheet.Cells.DeleteRows(0, 3);
worksheet.Cells.DeleteColumns(0, 9, false);
worksheet.Cells.DeleteColumn(2);
worksheet.Cells.DeleteColumns(3, 5000, false);

//Add headers
worksheet.Cells["A1"].PutValue("Name");
worksheet.Cells["B1"].PutValue("URL");
worksheet.Cells["C1"].PutValue("Passed?");
worksheet.Cells["D1"].PutValue("Output");

// save CSV file
workbook.Save(@"C:\Users\kruepb\Desktop\Automation\22-5\Margin_22_5.csv");


来源: stackexchange

问:
Const inside P tag pushes other text around depending on own size
A gif of the issue: https://gyazo.com/01c2844693f6c8c506ff6022d101df04

i want **{myAge}** to not push rest of the
 tag around when its own size changes

is it possible to set a fixed length that it always has?

I have tried setting a min length of 13 characters, if the string is under 13 characters  it adds a "0" to end as compensation but sometimes it doesn't work.

Below is the code for my
 tag

```<code><p id="infoText">
Hello my friends, my name is <strong> Robin </strong> i'm
  <strong id="myAge" >  **{myAge}**  </strong>
  years old and live in
</code>```

here is my function that calculates {myAge}

```<code>function getAge(date) {
  var today = new Date();
  var birthDate = new Date(date);
  var ageMS = today.getTime() - birthDate.getTime();

  var ageString = ageMS / 31556952000;

  var age = ageString.toString();

  var newage = age.slice(0, -6);
  // Adding a 0 as compensation to have  a fixed size of the string.
  // even if i add multiple if statements < 11 + "00" , < 10 + "000" etc it still doesnt work.

  if (newage.length < 12) {
    newage = newage + "0";
  }

  console.log(newage.length);
  return newage;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
A gif of the issue: https://gyazo.com/01c2844693f6c8c506ff6022d101df04

i want **{myAge}** to not push rest of the
 tag around when its own size changes

is it possible to set a fixed length that it always has?

I have tried setting a min length of 13 characters, if the string is under 13 characters  it adds a "0" to end as compensation but sometimes it doesn't work.

Below is the code for my
 tag

Hello my friends, my name is  Robin  i'm
    **{myAge}**
  years old and live in

here is my function that calculates {myAge}

function getAge(date) {
  var today = new Date();
  var birthDate = new Date(date);
  var ageMS = today.getTime() - birthDate.getTime();

  var ageString = ageMS / 31556952000;

  var age = ageString.toString();

  var newage = age.slice(0, -6);
  // Adding a 0 as compensation to have  a fixed size of the string.
  // even if i add multiple if statements < 11 + "00" , < 10 + "000" etc it still doesnt work.

  if (newage.length < 12) {
    newage = newage + "0";
  }

  console.log(newage.length);
  return newage;
}


问:
How to safely finish xCode command line tool running
I have a c++ program which serves to convert serial port data and send it to a MIDI port. Effectively a program that acts a service to run indefinitely. I have used other command line commands such as flask run or sqlite3 which can be terminated with ^c, yet I don't know how to properly implement this.

Currently I am ending the program through the stop button in the upper left corner of xCode. Though this means that I any cleanup commands do not get executed.

```<code>tcdrain(fileDescriptor);
close(fileDescriptor);
</code>```

Body:
I have a c++ program which serves to convert serial port data and send it to a MIDI port. Effectively a program that acts a service to run indefinitely. I have used other command line commands such as flask run or sqlite3 which can be terminated with ^c, yet I don't know how to properly implement this.

Currently I am ending the program through the stop button in the upper left corner of xCode. Though this means that I any cleanup commands do not get executed.

tcdrain(fileDescriptor);
close(fileDescriptor);


问:
Install rJava library fail to find path
I try to install rJava package using this way in windows

```<code>install.packages("rJava")
Installing package into ‘C:/Users/User/AppData/Local/R/win-library/4.2’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.2/rJava_1.0-6.zip'
Content type 'application/zip' length 1245703 bytes (1.2 MB)
downloaded 1.2 MB

package ‘rJava’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\User\AppData\Local\Temp\RtmpOqiB8n\downloaded_packages
</code>```

And when I try to call the library I receive this error

```<code>library(rJava)
</code>```

Error: package or namespace load failed for ‘rJava’:
.onLoad failed in loadNamespace() for 'rJava', details:
call: inDL(x, as.logical(local), as.logical(now), ...)
error: unable to load shared object 'C:/Users/User/AppData/Local/R/win-library/4.2/rJava/libs/x64/rJava.dll':
LoadLibrary failure:  The specified device could not be found. unit

How is it possible to install this library with an alternative way or is there anything I could fix?

Title: Install rJava library fail to find path

Body:
I try to install rJava package using this way in windows

install.packages("rJava")
Installing package into ‘C:/Users/User/AppData/Local/R/win-library/4.2’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.2/rJava_1.0-6.zip'
Content type 'application/zip' length 1245703 bytes (1.2 MB)
downloaded 1.2 MB

package ‘rJava’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\User\AppData\Local\Temp\RtmpOqiB8n\downloaded_packages

And when I try to call the library I receive this error

library(rJava)

Error: package or namespace load failed for ‘rJava’:
.onLoad failed in loadNamespace() for 'rJava', details:
call: inDL(x, as.logical(local), as.logical(now), ...)
error: unable to load shared object 'C:/Users/User/AppData/Local/R/win-library/4.2/rJava/libs/x64/rJava.dll':
LoadLibrary failure:  The specified device could not be found. unit

How is it possible to install this library with an alternative way or is there anything I could fix?


问:
How to configure linuxptp to set the system clock according to the time of a remote Grand Master using 1588?
I have an Ubuntu with linuxptp connected to a PTP Grand Master device which supports IEEE1588.
I want to set the Ubuntu's system clock according to the GM clock.
I don't understand how to combine ptp4l and phc2sys to do that with all the possible command line options and config files options of both tools.
Can someone give an example?</p>


问:
Error sending file via telegram bot on aiogram
The function should send a gif image to the user, but when you enter the start command an error pops up:

aiogram.exceptions.TelegramBadRequest: Bad Request: invalid file HTTP URL specified: Wrong URL host
```
<p>Once I solved such a problem, but unfortunately I forgot how, I ran out of solutions. Help me please</p>
<p>Function: start.py</p>
<pre class="lang-py prettyprint-override"><code>async def start_command(message: Message):
    await message.answer_animation(animation=open('app\images\logo.gif', "rb"), caption="Hello, mate!")
</code>```

Register handler: main.py

dp.message.register(start_command, CommandStart())
```

Body:
The function should send a gif image to the user, but when you enter the start command an error pops up:

aiogram.exceptions.TelegramBadRequest: Bad Request: invalid file HTTP URL specified: Wrong URL host

Once I solved such a problem, but unfortunately I forgot how, I ran out of solutions. Help me please

Function: start.py

async def start_command(message: Message):
    await message.answer_animation(animation=open('app\images\logo.gif', "rb"), caption="Hello, mate!")

Register handler: main.py

dp.message.register(start_command, CommandStart())


问:
Set datasource at runtime ActiveReports 10
I try to set datasource at runtime in my report of Activereports 10.

i have this code in the script :

'''

Sub ActiveReport_ReportStart

```<code>Dim connectionString = “Data Source=PC\SQLEXPRESS;Initial Catalog=Contratti;Integrated    Security=True”

Dim con As SqlConnection = New SqlConnection(connectionString)
con.Open()

Dim _strSQL As String = "Select id , cod from customers"

Dim _cm As New SqlClient.SqlCommand(_strSQL, con)

Dim _dt As New DataTable
Dim _da As New SqlClient.SqlDataAdapter(_cm)
_da.Fill(_dt)
_dt.TableName = "customers"
Me.DataSource = _dt
</code>```

End Sub

'''

I have the error :

localhost:52620

Error: Report Script Compile Error on line 50 :

‘DataSource’ non è un membro di ‘Script.ReportScript’

What can i control ?

i’d like load my datatable at runtime and set it to the report .

Thank you

Body:
I try to set datasource at runtime in my report of Activereports 10.

i have this code in the script :

'''

Sub ActiveReport_ReportStart

Dim connectionString = “Data Source=PC\SQLEXPRESS;Initial Catalog=Contratti;Integrated    Security=True”

Dim con As SqlConnection = New SqlConnection(connectionString)
con.Open()

Dim _strSQL As String = "Select id , cod from customers"

Dim _cm As New SqlClient.SqlCommand(_strSQL, con)

Dim _dt As New DataTable
Dim _da As New SqlClient.SqlDataAdapter(_cm)
_da.Fill(_dt)
_dt.TableName = "customers"
Me.DataSource = _dt

End Sub

'''

I have the error :

localhost:52620

Error: Report Script Compile Error on line 50 :

‘DataSource’ non è un membro di ‘Script.ReportScript’

What can i control ?

i’d like load my datatable at runtime and set it to the report .

Thank you


问:
Kubernetes define timeout beetween two services with Istio
I'm studying how Istio works and in particular I'm looking at timeouts.

I followed this guide provided by Istio Docs, where the following VirtualService gets defined:

```<code>apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: reviews
spec:
  hosts:
  - reviews
  http:
  - route:
    - destination:
        host: reviews
        subset: v2
    timeout: 0.5s
</code>```

If I understood well, every call to ratings service get a 0.5s timeout. I was wondering if it's possible to define timeout only in the communication beetween (for example) a pod and a service, and not for every call received by the service

Body:
I'm studying how Istio works and in particular I'm looking at timeouts.

I followed this guide provided by Istio Docs, where the following VirtualService gets defined:

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: reviews
spec:
  hosts:
  - reviews
  http:
  - route:
    - destination:
        host: reviews
        subset: v2
    timeout: 0.5s

If I understood well, every call to ratings service get a 0.5s timeout. I was wondering if it's possible to define timeout only in the communication beetween (for example) a pod and a service, and not for every call received by the service


问:
Kustomize + Helm error on chart semver requirements
I'm attempting to install the argo-cd helm chart with kustomize using the --enable-helm feature.

This results in a kubeVersion compatibility error. I am confused by this result as the version of kubernetes client and server are both greater than the v1.20.0 required version.

I re-produced this test on a new fresh clean VM which has only ever had the versions shown below.

Where could it be reading in the kubernetes v1.20.0 from and how can I fix that?

Error

kc2admin@kargo:~/argocd$ kubectl kustomize --enable-helm .
error: Error: chart requires kubeVersion: >=1.22.0-0 which is incompatible with Kubernetes v1.20.0
```
<h4>Versions</h4>
<pre class="lang-bash prettyprint-override"><code>kc2admin@kargo:~/argocd$ kubectl version --short
Client Version: v1.26.0
Kustomize Version: v4.5.7
Server Version: v1.25.4
</code>```

Kustomization

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: argocd
helmCharts:
- name: argo-cd
  releaseName: argocd
  valuesFile: values.yaml
  version: 5.16.13
  repo: https://argoproj.github.io/argo-helm
  includeCRDs: true
```
<h4>Steps to reproduce</h4>
<pre class="lang-bash prettyprint-override"><code># Create a directory
mkdir argocd && cd argocd

# Create an empty values file
touch values.yaml

# Write the kustomize file
cat <<EOF > Kustomization
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: argocd
helmCharts:
- name: argo-cd
  releaseName: argocd
  valuesFile: values.yaml
  version: 5.16.13
  repo: https://argoproj.github.io/argo-helm
  includeCRDs: true
EOF

# build the manifests with kustomize
kubectl kustomize --enable-helm .
</code>```

Solution

Update from helm v3.6.3 to v3.10.3 as helm template is compiled to fallback to an assumed kubeVersion which it was originally compiled for.

Body:
I'm attempting to install the argo-cd helm chart with kustomize using the --enable-helm feature.

This results in a kubeVersion compatibility error. I am confused by this result as the version of kubernetes client and server are both greater than the v1.20.0 required version.

I re-produced this test on a new fresh clean VM which has only ever had the versions shown below.

Where could it be reading in the kubernetes v1.20.0 from and how can I fix that?

Error

kc2admin@kargo:~/argocd$ kubectl kustomize --enable-helm .
error: Error: chart requires kubeVersion: >=1.22.0-0 which is incompatible with Kubernetes v1.20.0

Versions

kc2admin@kargo:~/argocd$ kubectl version --short
Client Version: v1.26.0
Kustomize Version: v4.5.7
Server Version: v1.25.4

Kustomization

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: argocd
helmCharts:
- name: argo-cd
  releaseName: argocd
  valuesFile: values.yaml
  version: 5.16.13
  repo: https://argoproj.github.io/argo-helm
  includeCRDs: true

Steps to reproduce

# Create a directory
mkdir argocd && cd argocd

# Create an empty values file
touch values.yaml

# Write the kustomize file
cat <<EOF > Kustomization
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: argocd
helmCharts:
- name: argo-cd
  releaseName: argocd
  valuesFile: values.yaml
  version: 5.16.13
  repo: https://argoproj.github.io/argo-helm
  includeCRDs: true
EOF

# build the manifests with kustomize
kubectl kustomize --enable-helm .

Solution

Update from helm v3.6.3 to v3.10.3 as helm template is compiled to fallback to an assumed kubeVersion which it was originally compiled for.


问:
How to find and format multiple matching words with Regex in Word document using VB script
I have a word document in which I have to do the formatting of the words using VB script. The text can be as follows :

```<code>hello <bu ABC bu>,   We are pleased to confirm our offer of employment to you. The terms and conditions that will apply to your employment with are set forth in this letter and Exhibit A attached hereto and incorporated herein by reference together, the “Agreement”
</code>```

  You have been offered and accepted the position of  , presently reporting to . Your start date is expected to be

The words which are written inside tag  needs to be bold and underlined. Currently I have written a VBscript which will find the text given as argument and make it bold and underline as required.

But to make the solution/script more dynamic, I want the script to match Regular Expression pattern which I have written : (?<=(<bu))[a-zA-Z0-9 -:/\[]()]+(?=(bu>))

The script I have written :

```<code>Option Explicit

Function Macro1()

    Dim strFilePath
    strFilePath = "C:\Users\<UserID>\Documents\OfferLetterTemplate.docx"

    Dim strTextToReplace
    strTextToReplace = "<bu XYZ bu>"

    Dim Word, objDoc, objSelection

    Set Word = CreateObject("Word.Application")
    Word.Visible = True

    Dim wordfile
    Set wordfile = Word.Documents.Open(strFilePath)

    Set objDoc = Word.ActiveDocument
    Set objSelection = Word.Selection

    objSelection.Find.Forward = True
    objSelection.Find.MatchWholeWord = False
    objSelection.Find.ClearFormatting
    objSelection.Find.Replacement.ClearFormatting
    objSelection.Find.Replacement.Font.Bold = True
    objSelection.Find.Replacement.Font.Underline = True
    objSelection.Find.Text = strTextToReplace
    objSelection.Find.Replacement.Text = ""

    objSelection.Find.Execute , , , , , , , 0, , , 2

    wordfile.save
    Word.Quit

End Function

call Macro1
</code>```

Can someone help me how I can search for the RegEx which I have given above and format all the matching occurrences at once?

Body:
I have a word document in which I have to do the formatting of the words using VB script. The text can be as follows :

hello <bu ABC bu>,   We are pleased to confirm our offer of employment to you. The terms and conditions that will apply to your employment with are set forth in this letter and Exhibit A attached hereto and incorporated herein by reference together, the “Agreement”

  You have been offered and accepted the position of  , presently reporting to . Your start date is expected to be

The words which are written inside tag  needs to be bold and underlined. Currently I have written a VBscript which will find the text given as argument and make it bold and underline as required.

But to make the solution/script more dynamic, I want the script to match Regular Expression pattern which I have written : (?<=(<bu))[a-zA-Z0-9 -:/\[]()]+(?=(bu>))

The script I have written :

Option Explicit

Function Macro1()

    Dim strFilePath
    strFilePath = "C:\Users\<UserID>\Documents\OfferLetterTemplate.docx"

    Dim strTextToReplace
    strTextToReplace = "<bu XYZ bu>"

    Dim Word, objDoc, objSelection

    Set Word = CreateObject("Word.Application")
    Word.Visible = True

    Dim wordfile
    Set wordfile = Word.Documents.Open(strFilePath)

    Set objDoc = Word.ActiveDocument
    Set objSelection = Word.Selection

    objSelection.Find.Forward = True
    objSelection.Find.MatchWholeWord = False
    objSelection.Find.ClearFormatting
    objSelection.Find.Replacement.ClearFormatting
    objSelection.Find.Replacement.Font.Bold = True
    objSelection.Find.Replacement.Font.Underline = True
    objSelection.Find.Text = strTextToReplace
    objSelection.Find.Replacement.Text = ""

    objSelection.Find.Execute , , , , , , , 0, , , 2

    wordfile.save
    Word.Quit

End Function

call Macro1

Can someone help me how I can search for the RegEx which I have given above and format all the matching occurrences at once?


问:
Dedup node_modules for a number of Vue applications
As a teacher I frequently have to look at students projekcts. A couple of courses deal with a Vue3 application and I end up with multiple similar if not equal node_modules folders for each students project. Is there away to prevent duplication of the contents of all these folders?


问:
I want to create audit log using fastapi in python
I have created a few tables in sqlalchemy. I want to build an audit log for these tables to capture the history. Whenever a table is updated with values or inserted values, these logs needs to be captured in another audit table. How could I achieve this using sqlalchemy.

from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import mapper
from sqlalchemy import event
from models import user_log

@event.listens_for(Usermodel, "after_insert")
def insert_user_log(mapper, connection, target):
    po =user_log
    connection.exicute(po.insert().values(user_id=target.id, action='insert'))

@event.listen_for(user,"after update")
def update_user_log(mapper,connection,target):
    po=user_log
    connection.exicute(po.insert().values(user_id=target.id,action='update'))

@event.listen_for(Usermodel,"after delete")
def update_user_log(mapper,connection,target):
    po=user_log
    connection.exicute(po.insert().values(user_id=target.id,action='delete'))

```


问:
How do you pass properties via MenuItemLink in react-admin?
Is there a way to pass properties down to components that get loaded via MenuItemLink? I tried using "state" prop to the component that gets loaded via the "to" property in MenuItemLink, but it is returning undefined when I print it out using:</p>
```<code>const location = useLocation();
console.log('location.state', location.state);
</code>```

Body:
Is there a way to pass properties down to components that get loaded via MenuItemLink? I tried using "state" prop to the component that gets loaded via the "to" property in MenuItemLink, but it is returning undefined when I print it out using:

const location = useLocation();
console.log('location.state', location.state);


问:
I can't manage to communicate across Activities using intents
In my MainActivity onCreate I have a button listener which switches to a second activity:

```<code>    editorLink.setOnClickListener {
        val intent = Intent(this, EditorActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent)
    }
</code>```

In my second activity I have another button listener which attempts to switch back to the first activity, passing it some new data:

```<code>    saveButton.setOnClickListener {
        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        intent.putExtra("my_data", "my data from other activity");
        startActivity(intent)
    }
</code>```

Then in my MainActivity onStart I attempt to read the extra data:

```<code>if (intent.extras != null) {
   myData =  intent.extras!!.getString("my_data")
}
</code>```

However the intent.extras is always null here.

I have put Logger calls everywhere and I am sure all the above code is being run and the data being added to extras is a valid string.

Body:
In my MainActivity onCreate I have a button listener which switches to a second activity:

    editorLink.setOnClickListener {
        val intent = Intent(this, EditorActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent)
    }

In my second activity I have another button listener which attempts to switch back to the first activity, passing it some new data:

    saveButton.setOnClickListener {
        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        intent.putExtra("my_data", "my data from other activity");
        startActivity(intent)
    }

Then in my MainActivity onStart I attempt to read the extra data:

if (intent.extras != null) {
   myData =  intent.extras!!.getString("my_data")
}

However the intent.extras is always null here.

I have put Logger calls everywhere and I am sure all the above code is being run and the data being added to extras is a valid string.


问:
Reactjs: Stop autoscrolling when component is not mounted
I have a react app, and I have a two routes, /home and /items which renders ListComponent
Items have a bool property scrollHere, which I am using to scroll to a list item automatically and it works well with the code as shown below. The problem that I have is that when I go back to /home then it tries to scroll down to the position that list item was. How can I prevent this behaviour?

export const ListComponent = (items: ItemObject) => {
  const itemToScroll = useRef<null | HTMLDivElement>(null);
  const mounted = useRef(false);

  useEffect(() => {
    if (!mounted.current) {
      mounted.current = true;
    } else {
      scrollToItem();
    }
  });

  const scrollToItem = () => {
    itemToScroll.current?.scrollIntoView({ behavior: "smooth" });
  };

  return (

        {
        items.map(item =>
          item.scrollHere ? (
{itemName}
) : <></>
        }

  );
};
```


问:
Flask WTForms_SQLAlchemy and populating selected on choice SelectMultipleField
Using Flask with WTForms and SQLAlchemy to try and make life easier for what should be a simple test recording tool, but I've been stuck and at this point for a while and not getting anywhere with searching. I'm at the point of just want to code up the form myself, so I'm hopeful for a second look.  I've tried to knock this down to just the relevant parts of the code.

Blank forms save fine, edits save fine, but in edit mode the SelectMultipleField will not show selected the values that were returned by the SQLAlchemy query result (all other fields are fine and do populate). Using a print() in the python, I can see the saved values are returning from the Query.

The only thing that I can think of is that the SelectMultipleField is defined with empty choices but the choices ares then populated after class instantiation, but before the form is rendered. Not finding anything that indicates a different way to do this... but I can say that QuerySelectMultipleField won't work for me because of how I have to build the active test list.

Using:

```<code>Package            Version
------------------ -------
Flask              1.1.2
Flask-SQLAlchemy   2.4.4
Flask-WTF          0.14.3
Jinja2             2.11.3
pysqlite3          0.4.5
SQLAlchemy         1.3.23
Werkzeug           1.0.1
WTForms            2.3.3
WTForms-SQLAlchemy 0.3
</code>```

I have my form definition:

```<code>class MyForm(FlaskForm):
    rep_name = StringField(
        'Tester\'s Name',
        validators=[validators.InputRequired(), validators.Length(max=50)]
    )
    notes = TextAreaField(
        'Notes',
        validators=[validators.Length(max=255)]
    )

    supported_tests = SelectMultipleField(
        'Supported Tests',
        choices = [],
        validators=[validators.InputRequired()]
    )
</code>```

My db model:

```<code>class SupportedTests(db.Model):
    __tablename__ = 'supportedtestlkup'
    test = db.Column(db.String(64), primary_key=True)
    tester_id = db.Column(db.Integer, db.ForeignKey('testers.id'), nullable=False, primary_key=True)

class Testers(db.Model):
    __tablename__ = 'testers'
    id = db.Column(db.Integer, primary_key=True)
    rep_name = db.Column(db.String(50))
    notes = db.Column(db.String(255))
    supported_tests = db.relationship("SupportedTests", backref=db.backref("supportedtestlkup", order_by=id), cascade="all, delete-orphan", lazy=True)
</code>```

My flask app:

```<code>@app.route('/setup', methods=['GET', 'POST'])
def doSetup():

    Entry = dal.Testers.query.get(int(EditID))
    Form = forms.MyForm(request.form, obj=Entry)
    Form.supported_tests.choices = get_active_tests()
...
    print('Entry.Tests =', Entry.supported_tests )
    return render_template(
        'setup.html',
        form=Form,
    )
</code>```

Looking at the HTML output, the MultiSelect value does match the values in the list that python prints.

```<code><select class="form-control" id="supported_tests" multiple name="supported_tests" required size="10">
<option value="1.5">Test Five</option>

Entry.Tests = [1.0, 1.2, 1.5]
</code>```

Thoughts appreciated...

-- Update --

Rethinking this, I may just be missing is how to properly fill the Form.supported_tests.choices... If I try to use the SupportedTests object to fill the choices, I get an error "cannot unpack non-iterable" so it doesn't take that.  If I use a list of (value, name) for choices, then I get "'str' object has no attribute '_sa_instance_state'".

I have tried to add a loop on the Form.supported_tests.data to put the data into SupportedTests class instances, and this kinda works... but I'm back to not having anything selected when you go to the form.

Overwriting the Form.supported_tests.data does get me the fields selected on the form, but then the edit of the form never saves any changes because forcing Form.supported_tests.data overwrites anything incoming from request.form.

Body:
Using Flask with WTForms and SQLAlchemy to try and make life easier for what should be a simple test recording tool, but I've been stuck and at this point for a while and not getting anywhere with searching. I'm at the point of just want to code up the form myself, so I'm hopeful for a second look.  I've tried to knock this down to just the relevant parts of the code.

Blank forms save fine, edits save fine, but in edit mode the SelectMultipleField will not show selected the values that were returned by the SQLAlchemy query result (all other fields are fine and do populate). Using a print() in the python, I can see the saved values are returning from the Query.

The only thing that I can think of is that the SelectMultipleField is defined with empty choices but the choices ares then populated after class instantiation, but before the form is rendered. Not finding anything that indicates a different way to do this... but I can say that QuerySelectMultipleField won't work for me because of how I have to build the active test list.

Using:

Package            Version
------------------ -------
Flask              1.1.2
Flask-SQLAlchemy   2.4.4
Flask-WTF          0.14.3
Jinja2             2.11.3
pysqlite3          0.4.5
SQLAlchemy         1.3.23
Werkzeug           1.0.1
WTForms            2.3.3
WTForms-SQLAlchemy 0.3

I have my form definition:

class MyForm(FlaskForm):
    rep_name = StringField(
        'Tester\'s Name',
        validators=[validators.InputRequired(), validators.Length(max=50)]
    )
    notes = TextAreaField(
        'Notes',
        validators=[validators.Length(max=255)]
    )

    supported_tests = SelectMultipleField(
        'Supported Tests',
        choices = [],
        validators=[validators.InputRequired()]
    )

My db model:

class SupportedTests(db.Model):
    __tablename__ = 'supportedtestlkup'
    test = db.Column(db.String(64), primary_key=True)
    tester_id = db.Column(db.Integer, db.ForeignKey('testers.id'), nullable=False, primary_key=True)

class Testers(db.Model):
    __tablename__ = 'testers'
    id = db.Column(db.Integer, primary_key=True)
    rep_name = db.Column(db.String(50))
    notes = db.Column(db.String(255))
    supported_tests = db.relationship("SupportedTests", backref=db.backref("supportedtestlkup", order_by=id), cascade="all, delete-orphan", lazy=True)

My flask app:

@app.route('/setup', methods=['GET', 'POST'])
def doSetup():

    Entry = dal.Testers.query.get(int(EditID))
    Form = forms.MyForm(request.form, obj=Entry)
    Form.supported_tests.choices = get_active_tests()
...
    print('Entry.Tests =', Entry.supported_tests )
    return render_template(
        'setup.html',
        form=Form,
    )

Looking at the HTML output, the MultiSelect value does match the values in the list that python prints.

<select class="form-control" id="supported_tests" multiple name="supported_tests" required size="10">
<option value="1.5">Test Five</option>

Entry.Tests = [1.0, 1.2, 1.5]

Thoughts appreciated...

-- Update --

Rethinking this, I may just be missing is how to properly fill the Form.supported_tests.choices... If I try to use the SupportedTests object to fill the choices, I get an error "cannot unpack non-iterable" so it doesn't take that.  If I use a list of (value, name) for choices, then I get "'str' object has no attribute '_sa_instance_state'".

I have tried to add a loop on the Form.supported_tests.data to put the data into SupportedTests class instances, and this kinda works... but I'm back to not having anything selected when you go to the form.

Overwriting the Form.supported_tests.data does get me the fields selected on the form, but then the edit of the form never saves any changes because forcing Form.supported_tests.data overwrites anything incoming from request.form.


问:
DAX - SUMMARIZE based on SWITCH statement
I have SKUs data with some financial information. I have grouped the SKUs in 4 categories using a measure with SWITCH. Now I would like to summarise the information (e.g. total revenues of the products in each category) but I cannot get the summary to add up to the correct value.

Data model:

FactTable: fact table containing financial information (product code, revenue, profit, period, etc.)

DimSKU: mapping table with SKUs data (product code, brand, segment, etc.)

DimDates: date table (period, months, etc.)

Creating 4 product categories:
(using a measure and not a calculated column as the users can use a dropdown list and select different periods)

```<code>My Quadrants =
VAR
    Quadrants =
    SWITCH(
        TRUE(),
        AND([SKU_profit] >= [Total_profit], [SKU_growth] >= [Total_growth]), "Maintain",
        AND([SKU_profit] <  [Total_profit], [SKU_growth] <  [Total_growth]), "Address",
        AND([SKU_profit] >= [Total_profit], [SKU_growth] <  [Total_growth]), "Grow",
        AND([SKU_profit] <  [Total_profit], [SKU_growth] >= [Total_growth]), "Investigate"
    )
RETURN
    Quadrants
</code>```

Calculating YTD sales:

```<code>YTD revenue =
VAR
    YTD_revenue = TOTALYTD(SUM(FactTable[Revenue]), DimDates[Date])
RETURN
    YTD_revenue
</code>```

Summarising data:

I can add the measure to a visual like a table and it works perfectly fine as long as I also display all the SKUs. Ideally, I would like a summary like the following:

```<code>MyQuadrants / Revenue
Maintain / 1,000
Address / 250
Grow / 500
Investigate / 350
</code>```

I would be grateful if anyone could point me in the right direction.

Thanks all.

Edit

I have managed to make it work thanks to David's suggestion. See below for reference.

Creating configuration table

```<code>ConfigTable =
VAR
    Total_profit = [Total_profit]
VAR
    Total_growth = [Total_growth]
RETURN
    {
        ("Maintain", Total_profit, 1, Total_growth, 1),
        ("Address", 0, Total_profit, 0, Total_growth),
        ("Grow", Total_profit, 1, 0, Total_growth),
        ("Investigate", 0, Total_profit, Total_growth, 1)
    }

// 5 columns: quadrant, min profit, max profit, min growth, max growth
// Use table constructor to use variables
</code>```

Creating measure

```<code>YTD revenue (segmented) =
CALCULATE(
    [YTD revenue],
    FILTER(
        VALUES(DimSKU),
        NOT ISEMPTY(
                FILTER(
                    ConfigTable,
                    (
                    [SKU_profit] >= ConfigTable[min profit] &&
                    [SKU_profit] <  ConfigTable[max profit] &&
                    [SKU_growth] >= ConfigTable[min growth] &&
                    [SKU_growth] <  ConfigTable[min growth]
                    )
                )
     )
)
</code>```

Body:
I have SKUs data with some financial information. I have grouped the SKUs in 4 categories using a measure with SWITCH. Now I would like to summarise the information (e.g. total revenues of the products in each category) but I cannot get the summary to add up to the correct value.

Data model:

FactTable: fact table containing financial information (product code, revenue, profit, period, etc.)

DimSKU: mapping table with SKUs data (product code, brand, segment, etc.)

DimDates: date table (period, months, etc.)

Creating 4 product categories:
(using a measure and not a calculated column as the users can use a dropdown list and select different periods)

My Quadrants =
VAR
    Quadrants =
    SWITCH(
        TRUE(),
        AND([SKU_profit] >= [Total_profit], [SKU_growth] >= [Total_growth]), "Maintain",
        AND([SKU_profit] <  [Total_profit], [SKU_growth] <  [Total_growth]), "Address",
        AND([SKU_profit] >= [Total_profit], [SKU_growth] <  [Total_growth]), "Grow",
        AND([SKU_profit] <  [Total_profit], [SKU_growth] >= [Total_growth]), "Investigate"
    )
RETURN
    Quadrants

Calculating YTD sales:

YTD revenue =
VAR
    YTD_revenue = TOTALYTD(SUM(FactTable[Revenue]), DimDates[Date])
RETURN
    YTD_revenue

Summarising data:

I can add the measure to a visual like a table and it works perfectly fine as long as I also display all the SKUs. Ideally, I would like a summary like the following:

MyQuadrants / Revenue
Maintain / 1,000
Address / 250
Grow / 500
Investigate / 350

I would be grateful if anyone could point me in the right direction.

Thanks all.

Edit

I have managed to make it work thanks to David's suggestion. See below for reference.

Creating configuration table

ConfigTable =
VAR
    Total_profit = [Total_profit]
VAR
    Total_growth = [Total_growth]
RETURN
    {
        ("Maintain", Total_profit, 1, Total_growth, 1),
        ("Address", 0, Total_profit, 0, Total_growth),
        ("Grow", Total_profit, 1, 0, Total_growth),
        ("Investigate", 0, Total_profit, Total_growth, 1)
    }

// 5 columns: quadrant, min profit, max profit, min growth, max growth
// Use table constructor to use variables

Creating measure

YTD revenue (segmented) =
CALCULATE(
    [YTD revenue],
    FILTER(
        VALUES(DimSKU),
        NOT ISEMPTY(
                FILTER(
                    ConfigTable,
                    (
                    [SKU_profit] >= ConfigTable[min profit] &&
                    [SKU_profit] <  ConfigTable[max profit] &&
                    [SKU_growth] >= ConfigTable[min growth] &&
                    [SKU_growth] <  ConfigTable[min growth]
                    )
                )
     )
)


问:
How do I fix an error when fetching user information?
This is what I have right now:

```<code>@app.route("/<int:userId>")
async def getInfo(userId:int):
  user = await bot.fetch_user(userId)
</code>```

but it returns this error:

```<code>Traceback (most recent call last):
  File "/home/runner/-/venv/lib/python3.8/site-packages/flask/app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/runner/-/venv/lib/python3.8/site-packages/flask/app.py", line 1822, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/runner/-/venv/lib/python3.8/site-packages/flask/app.py", line 1820, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/runner/-/venv/lib/python3.8/site-packages/flask/app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/home/runner/-/venv/lib/python3.8/site-packages/asgiref/sync.py", line 240, in __call__
    return call_result.result()
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/concurrent/futures/_base.py", line 437, in result
    return self.__get_result()
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/concurrent/futures/_base.py", line 389, in __get_result
    raise self._exception
  File "/home/runner/-/venv/lib/python3.8/site-packages/asgiref/sync.py", line 306, in main_wrap
    result = await self.awaitable(*args, **kwargs)
  File "main.py", line 19, in getInfo
    user = await bot.fetch_user(userId)
  File "/home/runner/-/venv/lib/python3.8/site-packages/discord/client.py", line 1790, in fetch_user
    data = await self.http.get_user(user_id)
  File "/home/runner/-/venv/lib/python3.8/site-packages/discord/http.py", line 624, in request
    async with self.__session.request(method, url, **kwargs) as response:
  File "/home/runner/-/venv/lib/python3.8/site-packages/aiohttp/client.py", line 1141, in __aenter__
    self._resp = await self._coro
  File "/home/runner/-/venv/lib/python3.8/site-packages/aiohttp/client.py", line 467, in _request
    with timer:
  File "/home/runner/-/venv/lib/python3.8/site-packages/aiohttp/helpers.py", line 700, in __enter__
    raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task
</code>```

How do I get basic info on the requested user, even if the bot cannot see the user (isn't in a mutual guild)?

Body:
This is what I have right now:

@app.route("/<int:userId>")
async def getInfo(userId:int):
  user = await bot.fetch_user(userId)

but it returns this error:

Traceback (most recent call last):
  File "/home/runner/-/venv/lib/python3.8/site-packages/flask/app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/runner/-/venv/lib/python3.8/site-packages/flask/app.py", line 1822, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/runner/-/venv/lib/python3.8/site-packages/flask/app.py", line 1820, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/runner/-/venv/lib/python3.8/site-packages/flask/app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/home/runner/-/venv/lib/python3.8/site-packages/asgiref/sync.py", line 240, in __call__
    return call_result.result()
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/concurrent/futures/_base.py", line 437, in result
    return self.__get_result()
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/concurrent/futures/_base.py", line 389, in __get_result
    raise self._exception
  File "/home/runner/-/venv/lib/python3.8/site-packages/asgiref/sync.py", line 306, in main_wrap
    result = await self.awaitable(*args, **kwargs)
  File "main.py", line 19, in getInfo
    user = await bot.fetch_user(userId)
  File "/home/runner/-/venv/lib/python3.8/site-packages/discord/client.py", line 1790, in fetch_user
    data = await self.http.get_user(user_id)
  File "/home/runner/-/venv/lib/python3.8/site-packages/discord/http.py", line 624, in request
    async with self.__session.request(method, url, **kwargs) as response:
  File "/home/runner/-/venv/lib/python3.8/site-packages/aiohttp/client.py", line 1141, in __aenter__
    self._resp = await self._coro
  File "/home/runner/-/venv/lib/python3.8/site-packages/aiohttp/client.py", line 467, in _request
    with timer:
  File "/home/runner/-/venv/lib/python3.8/site-packages/aiohttp/helpers.py", line 700, in __enter__
    raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task

How do I get basic info on the requested user, even if the bot cannot see the user (isn't in a mutual guild)?


问:
Converting expansive wide dataframe to concise long dataframe efficiently
I have a database that expands horizontally with different lengths.

Example Data

Database Goal

I have a for loop that works and iterates through and appends each set to a new row in a new dataframe, however the data set is growing increasingly larger and this is slowing down. I've tried melt, wide_to_long, stack across several other threads. I tend to lose the data or cannot pivot out the melt to the needed columns.

I thought I had previously found a similar problem on stack overflow of address history, but can no longer find it. This is my current for loop that works and gives the results needed.

def df_transpose(df):
    new_df = []

    for index, row in df.iterrows():
        ID = row.loc['User ID']

        i = 0
        while True:

            try:
                Street = row.loc['Address.{}.Street'.format(i)]

            except KeyError:
                break
            # if we encounter another kind of error, raise it. it's helpful to see
            except Exception as e:
                raise e

            City = row.loc['Address.{}.City'.format(i)]
            State = row.loc['Address.{}.State'.format(i)]

            position = i

            new_df.append([ID, Street, City, State, position])
            i += 1
```


问:
Alias to dependent type only allows class types on GCC 12, but allows fundamental types on most other compilers
I found that the code snippet below compiles fine on gcc 11, clang, and MSVC, but starting with gcc 12.1, it gives the error:

using Y = typename Derived::template X<1>;  // offending line
```
<p><code>error: 'class Derived<T>::X<1>' resolves to 'Base<double>::X<1>' {aka 'double'}, which is not a class type</code></p>
<p>Why does the alias need to resolve to a class type for this to be a properly formed alias?</p>
<p>Minimal Example Code (godbolt):</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>

template <typename T>
struct Base {
  template <int I>
  using X = T;
};

template <typename T>
struct Derived : public Base<T> {
  using Y = typename Derived::template X<1>;
};

struct O {};

int main() {
  std::cout << typeid(Derived<double>::Y).name() << std::endl;  // error
  std::cout << typeid(Derived<O>::Y).name() << std::endl;       // works
}
</code>```

In the code in question, I'm trying to create an alias to a parent's (templated) alias, but it only works when the alias resolves to a class type.  Of course, something like using Y = double; is perfectly legal, and when any of Base, Derived, or X are not templated it also seems to work fine, so how come this particular combination of dependent types makes it so that X<something> is no longer allowed to resolve to e.g. arithmetic types, and only on gcc 12.1 and up?

I skimmed through the gcc 12 change list but didn't see anything that struck out to me as related.

(I'm using c++11 but it that doesn't seem to be relevant as it also occurs when specifying c++14, 17, 0x)

Body:
I found that the code snippet below compiles fine on gcc 11, clang, and MSVC, but starting with gcc 12.1, it gives the error:

using Y = typename Derived::template X<1>;  // offending line

error: 'class Derived<T>::X<1>' resolves to 'Base<double>::X<1>' {aka 'double'}, which is not a class type

Why does the alias need to resolve to a class type for this to be a properly formed alias?

Minimal Example Code (godbolt):

#include <iostream>

template <typename T>
struct Base {
  template <int I>
  using X = T;
};

template <typename T>
struct Derived : public Base<T> {
  using Y = typename Derived::template X<1>;
};

struct O {};

int main() {
  std::cout << typeid(Derived<double>::Y).name() << std::endl;  // error
  std::cout << typeid(Derived<O>::Y).name() << std::endl;       // works
}

In the code in question, I'm trying to create an alias to a parent's (templated) alias, but it only works when the alias resolves to a class type.  Of course, something like using Y = double; is perfectly legal, and when any of Base, Derived, or X are not templated it also seems to work fine, so how come this particular combination of dependent types makes it so that X<something> is no longer allowed to resolve to e.g. arithmetic types, and only on gcc 12.1 and up?

I skimmed through the gcc 12 change list but didn't see anything that struck out to me as related.

(I'm using c++11 but it that doesn't seem to be relevant as it also occurs when specifying c++14, 17, 0x)


问:
Count python dataclass instances
what is the best way to achieve class counter implementation with dataclass

```<code>class geeks:

    # this is used to print the number
    # of instances of a class
    counter = 0

    # constructor of geeks class
    def __init__(self,name):

        self.name = name

        # increment
        geeks.counter += 1
</code>```

with dataclass:

```<code>@dataclass
class geeks:
    name : str
</code>```

Title: Count python dataclass instances

Body:
what is the best way to achieve class counter implementation with dataclass

class geeks:

    # this is used to print the number
    # of instances of a class
    counter = 0

    # constructor of geeks class
    def __init__(self,name):

        self.name = name

        # increment
        geeks.counter += 1

with dataclass:

@dataclass
class geeks:
    name : str


问:
Deploying Data with containers across multiple environments
I wondered if I could pick your brains regarding deploying data across environments with containers... I have a hard time understanding the "standard" deployment process.

Let me set the scene:
You're running a CMS on your local development environment and you have two containers - a database container that runs MySQL and links to a volume (that stores the data), and the CMS container that links to it. All fine.

Now, I can deploy through GitLab/GitHub CI/CD by pushing any code changes to the repo in the CMS container - which will rebuild an image and push it to a 'Staging' environment (via a container registry). That's fine too.
Here's the issue - what's the standard accepted way of deploying the DATA in the database to the 'Staging' environment? Particularly through CI/CD?

I understand that having a cloudDB is best practice on staging/production, which again, is totally ok for me to do, but short of writing some Bash scripts to sqldump and rsync the data, I can't see how people do it with standard CI/CD pipelines.

Am I missing something here?


问:
How to compare header columns in different sheets using VBA
I am trying to come up with a dynamic way to compare header columns in multiple sheets to make sure all sheets have the same headers. Column counts may vary so I don't want to hardcode the range, instead I am trying to write something that would check for columns (UsedRange) that are not empty to do the comparison

I tried below but then I am getting an error saying

"Conversion from type 'Object(,)' to type 'String' is not valid"

```<code>range1 = xlBook.Sheets("Sheet1").UsedRange.Columns.Value

range2 = xlBook.Sheets("Sheet2").UsedRange.Columns.Value
</code>```

' If I could get the values then I was planning to do following

if range1 <> range2

MsgBxx .......

End if

Body:
I am trying to come up with a dynamic way to compare header columns in multiple sheets to make sure all sheets have the same headers. Column counts may vary so I don't want to hardcode the range, instead I am trying to write something that would check for columns (UsedRange) that are not empty to do the comparison

I tried below but then I am getting an error saying

"Conversion from type 'Object(,)' to type 'String' is not valid"

range1 = xlBook.Sheets("Sheet1").UsedRange.Columns.Value

range2 = xlBook.Sheets("Sheet2").UsedRange.Columns.Value

' If I could get the values then I was planning to do following

if range1 <> range2

MsgBxx .......

End if


问:
How Do I Make a Field Either fields.Dict or Specify a Schema?
I have a field on a schema that should be a specific schema based on a value in that field if it exists. To elaborate, the field should be fields.Dict() if it doesn't contain a version property. Otherwise, the schema should be retrieved from a map

def pricing_schema_serialization(base_object, parent_obj):
    # Use dictionary access to support using this function to look up schema for both both serialization directions,
    # and test data
    if type(base_object) is not dict:
        object_dict = base_object.__dict__
    else:
        object_dict = base_object

    pricing_version = object_dict.get("version", None)
    if pricing_version in version_to_schema:
        return version_to_schema[pricing_version]() # Works fine

    return fields.Dict(missing=dict, default=dict) # Produces error

class Product:
    # pricing = fields.Dict(missing=dict, default=dict) # This worked
    pricing = PolyField(
        serialization_schema_selector=pricing_schema_serialization,
        deserialization_schema_selector=pricing_schema_serialization,
        required=False,
        missing=dict,
        default=dict,
    )
```
<p>This is the error produced:</p>
```{'pricing': ["Unable to use schema. Ensure there is a deserialization_schema_selector and that it returns a schema when the function is passed in {}. This is the class I got. Make sure it is a schema: <class 'marshmallow.fields.Dict'>"]}
```

I saw that marhmallow 3.x has a from_dict() method. Unfortunately, we're stuck on 2.x.

Things I tried:

The code above

Creating my own from_dict class method following the same implementation here. Same result

Body:
I have a field on a schema that should be a specific schema based on a value in that field if it exists. To elaborate, the field should be fields.Dict() if it doesn't contain a version property. Otherwise, the schema should be retrieved from a map

def pricing_schema_serialization(base_object, parent_obj):
    # Use dictionary access to support using this function to look up schema for both both serialization directions,
    # and test data
    if type(base_object) is not dict:
        object_dict = base_object.__dict__
    else:
        object_dict = base_object

    pricing_version = object_dict.get("version", None)
    if pricing_version in version_to_schema:
        return version_to_schema[pricing_version]() # Works fine

    return fields.Dict(missing=dict, default=dict) # Produces error

class Product:
    # pricing = fields.Dict(missing=dict, default=dict) # This worked
    pricing = PolyField(
        serialization_schema_selector=pricing_schema_serialization,
        deserialization_schema_selector=pricing_schema_serialization,
        required=False,
        missing=dict,
        default=dict,
    )

This is the error produced:

{'pricing': ["Unable to use schema. Ensure there is a deserialization_schema_selector and that it returns a schema when the function is passed in {}. This is the class I got. Make sure it is a schema: <class 'marshmallow.fields.Dict'>"]}

I saw that marhmallow 3.x has a from_dict() method. Unfortunately, we're stuck on 2.x.

Things I tried:

The code above

Creating my own from_dict class method following the same implementation here. Same result


问:
Why are the icons different if they have the same FaceID?
I get the icons for popup menus with two different codes. Why are they different if they have the same FaceID?

Not only the type of icons (one type Excel 2003 and another Excel 365) There are also different icons, as we can be seen in the image.

What code should I use in my popup menu to get the Excel 365 style?

I create my popup menu with this code and I can't get the Excel 365 icon:

```<code>With Application.CommandBars.Add(Name:=gsMENUNOTES, _
  Position:=msoBarPopup, MenuBar:=False, Temporary:=True)
    With .Controls.Add(Type:=msoControlButton)
        .Caption = "New note"
        .OnAction = "NewNote"
        .FaceId = 4385
    End With
End With
</code>```

This is the code to get the icons (Excel 365 type) on the Ribbon (https://stackoverflow.com/a/18364215/11185212)

```<code>Option Explicit

Const APP_NAME = "FaceIDs (Browser)"

' The number of icons to be displayed in a set.
Const ICON_SET = 30

Sub BarOpen()
  Dim xBar As CommandBar
  Dim xBarPop As CommandBarPopup
  Dim bCreatedNew As Boolean
  Dim n As Integer, m As Integer
  Dim k As Integer

  On Error Resume Next
  ' Try to get a reference to the 'FaceID Browser' toolbar if it exists and delete it:
  Set xBar = CommandBars(APP_NAME)
  On Error GoTo 0
  If Not xBar Is Nothing Then
    xBar.Delete
    Set xBar = Nothing
  End If

  Set xBar = CommandBars.Add(Name:=APP_NAME, Temporary:=True) ', Position:=msoBarLeft
  With xBar
    .Visible = True
    '.Width = 80
    For k = 0 To 4 ' 5 dropdowns, each for about 1000 FaceIDs
      Set xBarPop = .Controls.Add(Type:=msoControlPopup) ', Before:=1
      With xBarPop
        .BeginGroup = True
        If k = 0 Then
          .Caption = "Face IDs " & 1 + 1000 * k & " ... "
        Else
          .Caption = 1 + 1000 * k & " ... "
        End If
        n = 1
        Do
          With .Controls.Add(Type:=msoControlPopup) '34 items * 30 items = 1020 faceIDs
            .Caption = 1000 * k + n & " ... " & 1000 * k + n + ICON_SET - 1
            For m = 0 To ICON_SET - 1
              With .Controls.Add(Type:=msoControlButton) '
                .Caption = "ID=" & 1000 * k + n + m
                .FaceId = 1000 * k + n + m
              End With
            Next m
          End With
          n = n + ICON_SET
        Loop While n < 1000 ' or 1020, some overlapp
      End With
    Next k
  End With 'xBar
End Sub
</code>```

And this is the code to get the icons (Excel 2003 type) on the sheet (https://www.mrexcel.com/board/threads/face-id-in-column-with-their-names-in-excel-sheet-using-vba.567230/)

```<code>Option Explicit

Sub exa()
    Dim CB          As CommandBar
    Dim ctl         As CommandBarButton
    Dim strCBName   As String
    Dim wbTemp      As Workbook
    Dim wks         As Worksheet
    Dim rngInput    As Range
    Dim i           As Long

    Application.ScreenUpdating = False

    Set wbTemp = Workbooks.Add(xlWBATWorksheet)
    wbTemp.SaveAs ThisWorkbook.Path & "\FaceID.xlsx"
    Dim NID As Long
    Dim NSheet As Long
    For NSheet = 1 To 5
        '// Add a temp commandbar, make it a popup (which we won't show); add a temp control //
        Set CB = CommandBars.Add(Position:=msoBarPopup, MenuBar:=False, Temporary:=True)

        Set ctl = CB.Controls.Add(Type:=msoControlButton, Temporary:=True)
        strCBName = CB.Name

        Set wks = wbTemp.Worksheets(NSheet)
        Dim vlFrom As Long
        vlFrom = ((NSheet - 1) * 50 * 20) + 1
        Dim vlTo As Long
        vlTo = NSheet * 50 * 20
        wks.Name = "F.ID " & vlFrom & "-" & vlTo
        Dim Col As Integer
        For Col = 2 To 40 Step 2
            Dim LCol As String
            LCol = Split(wks.Cells(1, Col).Address, "$")(1)
            Set rngInput = wks.Range(LCol & ":" & LCol)

            rngInput.Offset(, -1).ColumnWidth = 3
            rngInput.ColumnWidth = 8
            rngInput.HorizontalAlignment = xlRight

            On Error Resume Next
            For i = 1 To 50
                NID = NID + 1
                ctl.FaceId = NID
                ctl.CopyFace
                rngInput.Cells(i).PasteSpecial
                rngInput.Cells(i).Value = NID
            Next i
        Next Col
        '// just so the last image pasted doesn't stay selected//
        Application.GoTo wks.Cells(1, 1)
        wbTemp.Sheets.Add After:=wbTemp.Sheets(wbTemp.Sheets.Count)
        'Debug.Print NSheet
        'DoEvents
        '// Kill the temp cbar and ctrl //
        Set CB = CommandBars(strCBName)
        On Error GoTo 0

        If Not CB Is Nothing Then
            CB.Delete
        Else
            MsgBox "ACK!  I lost a toolbar!", 0, vbNullString
        End If
    Next NSheet

    wbTemp.Save

End Sub
</code>```

Body:
I get the icons for popup menus with two different codes. Why are they different if they have the same FaceID?

Not only the type of icons (one type Excel 2003 and another Excel 365) There are also different icons, as we can be seen in the image.

What code should I use in my popup menu to get the Excel 365 style?

I create my popup menu with this code and I can't get the Excel 365 icon:

With Application.CommandBars.Add(Name:=gsMENUNOTES, _
  Position:=msoBarPopup, MenuBar:=False, Temporary:=True)
    With .Controls.Add(Type:=msoControlButton)
        .Caption = "New note"
        .OnAction = "NewNote"
        .FaceId = 4385
    End With
End With

This is the code to get the icons (Excel 365 type) on the Ribbon (https://stackoverflow.com/a/18364215/11185212)

Option Explicit

Const APP_NAME = "FaceIDs (Browser)"

' The number of icons to be displayed in a set.
Const ICON_SET = 30

Sub BarOpen()
  Dim xBar As CommandBar
  Dim xBarPop As CommandBarPopup
  Dim bCreatedNew As Boolean
  Dim n As Integer, m As Integer
  Dim k As Integer

  On Error Resume Next
  ' Try to get a reference to the 'FaceID Browser' toolbar if it exists and delete it:
  Set xBar = CommandBars(APP_NAME)
  On Error GoTo 0
  If Not xBar Is Nothing Then
    xBar.Delete
    Set xBar = Nothing
  End If

  Set xBar = CommandBars.Add(Name:=APP_NAME, Temporary:=True) ', Position:=msoBarLeft
  With xBar
    .Visible = True
    '.Width = 80
    For k = 0 To 4 ' 5 dropdowns, each for about 1000 FaceIDs
      Set xBarPop = .Controls.Add(Type:=msoControlPopup) ', Before:=1
      With xBarPop
        .BeginGroup = True
        If k = 0 Then
          .Caption = "Face IDs " & 1 + 1000 * k & " ... "
        Else
          .Caption = 1 + 1000 * k & " ... "
        End If
        n = 1
        Do
          With .Controls.Add(Type:=msoControlPopup) '34 items * 30 items = 1020 faceIDs
            .Caption = 1000 * k + n & " ... " & 1000 * k + n + ICON_SET - 1
            For m = 0 To ICON_SET - 1
              With .Controls.Add(Type:=msoControlButton) '
                .Caption = "ID=" & 1000 * k + n + m
                .FaceId = 1000 * k + n + m
              End With
            Next m
          End With
          n = n + ICON_SET
        Loop While n < 1000 ' or 1020, some overlapp
      End With
    Next k
  End With 'xBar
End Sub

And this is the code to get the icons (Excel 2003 type) on the sheet (https://www.mrexcel.com/board/threads/face-id-in-column-with-their-names-in-excel-sheet-using-vba.567230/)

Option Explicit

Sub exa()
    Dim CB          As CommandBar
    Dim ctl         As CommandBarButton
    Dim strCBName   As String
    Dim wbTemp      As Workbook
    Dim wks         As Worksheet
    Dim rngInput    As Range
    Dim i           As Long

    Application.ScreenUpdating = False

    Set wbTemp = Workbooks.Add(xlWBATWorksheet)
    wbTemp.SaveAs ThisWorkbook.Path & "\FaceID.xlsx"
    Dim NID As Long
    Dim NSheet As Long
    For NSheet = 1 To 5
        '// Add a temp commandbar, make it a popup (which we won't show); add a temp control //
        Set CB = CommandBars.Add(Position:=msoBarPopup, MenuBar:=False, Temporary:=True)

        Set ctl = CB.Controls.Add(Type:=msoControlButton, Temporary:=True)
        strCBName = CB.Name

        Set wks = wbTemp.Worksheets(NSheet)
        Dim vlFrom As Long
        vlFrom = ((NSheet - 1) * 50 * 20) + 1
        Dim vlTo As Long
        vlTo = NSheet * 50 * 20
        wks.Name = "F.ID " & vlFrom & "-" & vlTo
        Dim Col As Integer
        For Col = 2 To 40 Step 2
            Dim LCol As String
            LCol = Split(wks.Cells(1, Col).Address, "$")(1)
            Set rngInput = wks.Range(LCol & ":" & LCol)

            rngInput.Offset(, -1).ColumnWidth = 3
            rngInput.ColumnWidth = 8
            rngInput.HorizontalAlignment = xlRight

            On Error Resume Next
            For i = 1 To 50
                NID = NID + 1
                ctl.FaceId = NID
                ctl.CopyFace
                rngInput.Cells(i).PasteSpecial
                rngInput.Cells(i).Value = NID
            Next i
        Next Col
        '// just so the last image pasted doesn't stay selected//
        Application.GoTo wks.Cells(1, 1)
        wbTemp.Sheets.Add After:=wbTemp.Sheets(wbTemp.Sheets.Count)
        'Debug.Print NSheet
        'DoEvents
        '// Kill the temp cbar and ctrl //
        Set CB = CommandBars(strCBName)
        On Error GoTo 0

        If Not CB Is Nothing Then
            CB.Delete
        Else
            MsgBox "ACK!  I lost a toolbar!", 0, vbNullString
        End If
    Next NSheet

    wbTemp.Save

End Sub


问:
Modifying List Cell only when it appears on screen and pause when it is not on screen in swiftUI
Can we modify List Cell only when it appears on screen and pause when it is not on screen in SwiftUI?

```<code>struct MyListView: View {
    @State private var items: [Int] = (0..<30).map { _ in 0 }
    @State private var timer: Timer?

    var body: some View {
        List {
            ForEach(items, id: \.self) { item in
                Text("\(item)")
            }
        }
        .onAppear {
            self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
                for i in 0..<self.items.count {
                    self.items[i] += 5
                }
            }
        }
    }
}
</code>```

I'm trying onAppear Method, but it is updating the whole List View regardless of the list cell is on screen or not. I just want my specific cells to update when they are on screen and pause updating when they are not on screen.

Body:
Can we modify List Cell only when it appears on screen and pause when it is not on screen in SwiftUI?

struct MyListView: View {
    @State private var items: [Int] = (0..<30).map { _ in 0 }
    @State private var timer: Timer?

    var body: some View {
        List {
            ForEach(items, id: \.self) { item in
                Text("\(item)")
            }
        }
        .onAppear {
            self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
                for i in 0..<self.items.count {
                    self.items[i] += 5
                }
            }
        }
    }
}

I'm trying onAppear Method, but it is updating the whole List View regardless of the list cell is on screen or not. I just want my specific cells to update when they are on screen and pause updating when they are not on screen.


问:
Redirect IP and Port to another IP and Port only for specific application
So, im playing an online game that is gonna be shut down. To prevent this game dying from the internet, i created packet sniffer that is able to steal all the outgoing and incooming packets. I simply coded C# TCP listener that records all the packets. The problem is the following. Lets say the game is trying to reach this IP 90.90.90.18 <- this is the server of the game. So i want somehow to force the game to connect to 127.0.0.1 instead, which is my localhost. And my packet sniffer is listening at 127.0.0.1 for any incooming/outgoing packets. After it analizes the packets it sends them back to the original server.
Here is a picture of the situation.

https://i.postimg.cc/B61hpbfg/1.png

NOTE: I want to make IP forwarding only for that specific game!! I tried the netsh command

```<code>netsh int ip add addr 1 90.90.90.18/32 st=ac sk=tr
</code>```

Which makes all applications that wana connect to this IP, connect to 127.0.0.1 instead. But this way i can never send the original packet to 90.90.90.18 .... so, any suggestions?

Body:
So, im playing an online game that is gonna be shut down. To prevent this game dying from the internet, i created packet sniffer that is able to steal all the outgoing and incooming packets. I simply coded C# TCP listener that records all the packets. The problem is the following. Lets say the game is trying to reach this IP 90.90.90.18 <- this is the server of the game. So i want somehow to force the game to connect to 127.0.0.1 instead, which is my localhost. And my packet sniffer is listening at 127.0.0.1 for any incooming/outgoing packets. After it analizes the packets it sends them back to the original server.
Here is a picture of the situation.

https://i.postimg.cc/B61hpbfg/1.png

NOTE: I want to make IP forwarding only for that specific game!! I tried the netsh command

netsh int ip add addr 1 90.90.90.18/32 st=ac sk=tr

Which makes all applications that wana connect to this IP, connect to 127.0.0.1 instead. But this way i can never send the original packet to 90.90.90.18 .... so, any suggestions?


问:
When I try to save I get enospc Error VSCODE
when I try to save one of the file of my workspace it gave me this error:

"Failed to save 'style.css': The content of the file is newer. Please compare your version with the file contents or overwrite the content of the file with your changes."

I'm a WINDOWS 10 user, and a newbie so I don't really know what to do about it, of course I have a lot of free space on my pc

I tried to restart the software first and than the computer.


问:
Nothing happens when using I.attachFile to upload a document , can you suggest what I should do
Is a drag-and-drop field required for the I.attachFile('element', 'filePath') to work? Because currently nothing happens when I try using the attachFile method. No error message or any issues displayed even when using --verbose.

This is the element where I try to attach my file //input[@type='file']. I also verified that I have the correct fileName and filePath since I tried using a wrong file name and it returned an error.

I am currently using:

codeceptjs: ^3.3.6,
playwright: ^1.19.0
I tried changing the file I'm about to upload to see if my file is the problem, but when I do upload the file manually in the page it works as expected; but when trying to do it in my code, nothing happens.

Expected: The uploaded file's name should be displayed
Actual: Nothing happens; no file name displayed; no error message returned in the logs

i expected the file to be uploaded.


问:
What is the most optimal way of using media queries for responsiveness if I am using single custom created styled component
I have defined this component, and I am using it everywhere in my project to avoid repetitive style definitions:

```<code>import React from "react";
import styled from "styled-components";

const FlexibleContainer = styled.div`
  display: ${(props) => (props.display ? props.display : "flex")};
  justify-content: ${(props) => props.jc && props.jc};
  align-items: ${(props) => props.ai && props.ai};
  flex-direction: ${(props) => props.fd && props.fd};
  flex-wrap: ${(props) => props.wrap && props.wrap};
  gap: ${(props) => props.gap && props.gap};
  row-gap: ${(props) => props.rg && props.rg};
  column-gap: ${(props) => props.cg && props.cg};
  position: ${(props) => props.pos && props.pos};
  border-radius: ${(props) => props.br && props.br};
  padding: ${(props) => props.pddn && props.pddn};
  padding-top: ${(props) => props.pt && props.pt};
  padding-right: ${(props) => props.pr && props.pr};
  padding-bottom: ${(props) => props.pb && props.pb};
  padding-left: ${(props) => props.pl && props.pl};
  margin: ${(props) => props.mrgn && props.mrgn};
  margin-top: ${(props) => props.mt && props.mt};
  margin-right: ${(props) => props.mr && props.mr};
  margin-bottom: ${(props) => props.mb && props.mb};
  margin-left: ${(props) => props.ml && props.ml};
  background-color: ${(props) => props.bg && props.bg};
  height: ${(props) => props.h && props.h};
  width: ${(props) => props.w && props.w};
  max-width: ${(props) => props.maxW && props.maxW};
  max-height: ${(props) => props.maxH && props.maxH};
  min-width: ${(props) => props.minW && props.minW};
  min-height: ${(props) => props.minH && props.minH};
`
const Container = (props) => {
  return <FlexibleContainer {...props}>{props.children}</FlexibleContainer>;
};
export default Container;
</code>```

And this is the way I use it:

```<code>return (
    <Container gap="30px" ai="start">
      <LeftBar
        handler={handleSetSuggestionsIDs}
        suggestions={props.suggestions}
      />
      <Container gap="24px" fd="column" w="100%" minW="0px">
        <TopBar
          suggestions={suggestionIDs.map((id) =>
            props.suggestions.find((suggestion) => suggestion.id === id)
          )}
          handler={handleSetSuggestionsIDs}
        />
        {suggestionIDs.length ? (
          <Suggestions
            suggestions={suggestionIDs.map((id) =>
              props.suggestions.find((suggestion) => suggestion.id === id)
            )}
            handler={props.handler}
          />
        ) : (
          <NoFeedBackScreen />
        )}
      </Container>
    </Container>
  );`
</code>```

Now I have to make it responsive for mobile and tablet screen sizes, and I cannot think of any method that would not make the JSX ugly. I have thought of using CSS modules with media queries, but if I do that now and keep creating new styles with class names the whole point of using styled components does not make sense anymore. On the other hand, if I create different props for mobile and tablet, or add ternary comparisons to each occurrence of Container, this would again lead to messy JSX filled with styles.

Body:
I have defined this component, and I am using it everywhere in my project to avoid repetitive style definitions:

import React from "react";
import styled from "styled-components";

const FlexibleContainer = styled.div`
  display: ${(props) => (props.display ? props.display : "flex")};
  justify-content: ${(props) => props.jc && props.jc};
  align-items: ${(props) => props.ai && props.ai};
  flex-direction: ${(props) => props.fd && props.fd};
  flex-wrap: ${(props) => props.wrap && props.wrap};
  gap: ${(props) => props.gap && props.gap};
  row-gap: ${(props) => props.rg && props.rg};
  column-gap: ${(props) => props.cg && props.cg};
  position: ${(props) => props.pos && props.pos};
  border-radius: ${(props) => props.br && props.br};
  padding: ${(props) => props.pddn && props.pddn};
  padding-top: ${(props) => props.pt && props.pt};
  padding-right: ${(props) => props.pr && props.pr};
  padding-bottom: ${(props) => props.pb && props.pb};
  padding-left: ${(props) => props.pl && props.pl};
  margin: ${(props) => props.mrgn && props.mrgn};
  margin-top: ${(props) => props.mt && props.mt};
  margin-right: ${(props) => props.mr && props.mr};
  margin-bottom: ${(props) => props.mb && props.mb};
  margin-left: ${(props) => props.ml && props.ml};
  background-color: ${(props) => props.bg && props.bg};
  height: ${(props) => props.h && props.h};
  width: ${(props) => props.w && props.w};
  max-width: ${(props) => props.maxW && props.maxW};
  max-height: ${(props) => props.maxH && props.maxH};
  min-width: ${(props) => props.minW && props.minW};
  min-height: ${(props) => props.minH && props.minH};
`
const Container = (props) => {
  return <FlexibleContainer {...props}>{props.children}</FlexibleContainer>;
};
export default Container;

And this is the way I use it:

return (
    <Container gap="30px" ai="start">
      <LeftBar
        handler={handleSetSuggestionsIDs}
        suggestions={props.suggestions}
      />
      <Container gap="24px" fd="column" w="100%" minW="0px">
        <TopBar
          suggestions={suggestionIDs.map((id) =>
            props.suggestions.find((suggestion) => suggestion.id === id)
          )}
          handler={handleSetSuggestionsIDs}
        />
        {suggestionIDs.length ? (
          <Suggestions
            suggestions={suggestionIDs.map((id) =>
              props.suggestions.find((suggestion) => suggestion.id === id)
            )}
            handler={props.handler}
          />
        ) : (
          <NoFeedBackScreen />
        )}
      </Container>
    </Container>
  );`

Now I have to make it responsive for mobile and tablet screen sizes, and I cannot think of any method that would not make the JSX ugly. I have thought of using CSS modules with media queries, but if I do that now and keep creating new styles with class names the whole point of using styled components does not make sense anymore. On the other hand, if I create different props for mobile and tablet, or add ternary comparisons to each occurrence of Container, this would again lead to messy JSX filled with styles.


问:
Unable to resolve class org.jenkinsci.plugins.workflow.libs.GlobalLibraries in Jenkins
I am trying to take use of Pipeline: Groovy Libraries Jenkins plugin, however each time I try to use some classes from the plugin I am getting a following error:

```<code>15:53:52  [Pipeline] End of Pipeline
15:53:52  ERROR: startup failed:
15:53:52  _48_modeltDevelopJenkinsCasc.groovy: 19: unable to resolve class org.jenkinsci.plugins.workflow.libs.GlobalLibraries
15:53:52   @ line 19, column 1.
15:53:52     import org.jenkinsci.plugins.workflow.libs.GlobalLibraries
15:53:52     ^
15:53:52
15:53:52  _48_modeltDevelopJenkinsCasc.groovy: 20: unable to resolve class org.jenkinsci.plugins.workflow.libs.LibraryCachingConfiguration
15:53:52   @ line 20, column 1.
15:53:52     import org.jenkinsci.plugins.workflow.libs.LibraryCachingConfiguration
15:53:52     ^
15:53:52
15:53:52  2 errors
15:53:52
15:53:52  Finished: FAILURE
</code>```

I have the plugin installed and enabled in the plugins' management section. It is even more confusing to me because if I try to create some plugin class instances in the console like

```<code>import org.jenkinsci.plugins.workflow.libs.GlobalLibraries
import org.jenkinsci.plugins.workflow.libs.LibraryCachingConfiguration

def test = new LibraryCachingConfiguration(10, "test")
</code>```

then it works

```<code>Result: LibraryCachingConfiguration{refreshTimeMinutes=10, excludedVersions=test}
</code>```

Executing Jenkins build locally also works fine. Does anyone have any clue what could cause the issue?

Body:
I am trying to take use of Pipeline: Groovy Libraries Jenkins plugin, however each time I try to use some classes from the plugin I am getting a following error:

15:53:52  [Pipeline] End of Pipeline
15:53:52  ERROR: startup failed:
15:53:52  _48_modeltDevelopJenkinsCasc.groovy: 19: unable to resolve class org.jenkinsci.plugins.workflow.libs.GlobalLibraries
15:53:52   @ line 19, column 1.
15:53:52     import org.jenkinsci.plugins.workflow.libs.GlobalLibraries
15:53:52     ^
15:53:52
15:53:52  _48_modeltDevelopJenkinsCasc.groovy: 20: unable to resolve class org.jenkinsci.plugins.workflow.libs.LibraryCachingConfiguration
15:53:52   @ line 20, column 1.
15:53:52     import org.jenkinsci.plugins.workflow.libs.LibraryCachingConfiguration
15:53:52     ^
15:53:52
15:53:52  2 errors
15:53:52
15:53:52  Finished: FAILURE

I have the plugin installed and enabled in the plugins' management section. It is even more confusing to me because if I try to create some plugin class instances in the console like

import org.jenkinsci.plugins.workflow.libs.GlobalLibraries
import org.jenkinsci.plugins.workflow.libs.LibraryCachingConfiguration

def test = new LibraryCachingConfiguration(10, "test")

then it works

Result: LibraryCachingConfiguration{refreshTimeMinutes=10, excludedVersions=test}

Executing Jenkins build locally also works fine. Does anyone have any clue what could cause the issue?


问:
Dialogflow CX(sending custom pay)
I am using Dialogflow CX and I need to send array elements from Google cloud function to CX Bot, as Custom payload chips response.  i.e One chip per array element should be shown in the CX Bot.
The length of the array is not fixed and varies.   Please suggest how can I achieve this.

I am able to send when I use something like arr[0] ,  or arr[1], but here the case is the length of the array is not fixed but varies.

Title: Dialogflow CX(sending custom pay)


问:
Use PHP To Fill In Named fields in PDF (Ideally on Linux Server)
I have a PDF that has named fields - I'm looking to use PHP on Linux (for a web application) to fill variable data into my PDF with prenamed fields.

In the past I did this on .NET with this product, but I'm looking to do this on Linux - https://www.websupergoo.com/products.aspx#abcpdf

Does anyone have any suggestions on a library or product to do this? I see a lot of depreciated products out there, but looking for something that can be used in production with support.

Thanks in advance for your help!

-NJ

I tried a number of PHP libraries, but most have been depreciated  - none that I've found so far have allowed me to post to fields on Linux.


问:
Node JS MariaDB Program runs forever?
The following program runs forever and never exits. It appears to hang when conn.end() is called. I have no idea why. This is taken from the example code. Why does it hang and never exit?

```<code>const mariadb = require('mariadb');

const pool = mariadb.createPool({
    host: '127.0.0.1',
    user: 'admin',
    password: 'adminpassword',
    port: 3306,
    connectionLimit: 5,
    connectTimeout: 1000
});

async function asyncFunction() {
    let conn;
    try {
        console.log('get connection');
        conn = await pool.getConnection();
        const rows = await conn.query("SELECT 1 as val");
        console.log(rows);
        console.log('done with that');
    } catch (err) {
        console.log('got error');
        throw err;
    } finally {
        if (conn) {
            console.log('please end');
            return conn.end();
        } else {
            console.log('nothing to end');
        }
    }

    console.log('exit?');
}

asyncFunction();
</code>```

Title: Node JS MariaDB Program runs forever?

Body:
The following program runs forever and never exits. It appears to hang when conn.end() is called. I have no idea why. This is taken from the example code. Why does it hang and never exit?

const mariadb = require('mariadb');

const pool = mariadb.createPool({
    host: '127.0.0.1',
    user: 'admin',
    password: 'adminpassword',
    port: 3306,
    connectionLimit: 5,
    connectTimeout: 1000
});

async function asyncFunction() {
    let conn;
    try {
        console.log('get connection');
        conn = await pool.getConnection();
        const rows = await conn.query("SELECT 1 as val");
        console.log(rows);
        console.log('done with that');
    } catch (err) {
        console.log('got error');
        throw err;
    } finally {
        if (conn) {
            console.log('please end');
            return conn.end();
        } else {
            console.log('nothing to end');
        }
    }

    console.log('exit?');
}

asyncFunction();


问:
I'm cloning Uber, I'm having an error in "requestLocationUpdates", trying to access my current location(Driver Location)
I'm trying to clone Uber, I want to access the driver current location, but when implementing  LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest,this); Iam getting an error as follow:

Cannot resolve method 'requestLocationUpdates(com.google.android.gms.common.api.GoogleApiClient, android.location.LocationRequest, com.example.codingcafe.cab.DriversMapActivity)'

This is my class, I tried to add LocationListener to the implements, I changed the gms-location implementation in the build.gradle, nothing worked

```<code>package com.example.codingcafe.cab;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationRequest;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;

import com.example.codingcafe.cab.databinding.ActivityDriversMapBinding;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.LocationListener;

public class DriversMapActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        com.google.android.gms.location.LocationListener{

    private GoogleMap mMap;
    private ActivityDriversMapBinding binding;
    GoogleApiClient googleApiClient;
    Location LastLocation;
    LocationRequest locationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityDriversMapBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,17));
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            locationRequest = new LocationRequest.Builder( 1000)
                    .setMinUpdateIntervalMillis(500)
                    .setQuality(LocationRequest.QUALITY_HIGH_ACCURACY)
                    .setMaxUpdateDelayMillis(1000)
                    .build();

        }

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest,this);

        //it will handle the refreshment of the location
        //if we dont call it we will get location only once

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {

    }
}
</code>```

Body:
I'm trying to clone Uber, I want to access the driver current location, but when implementing  LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest,this); Iam getting an error as follow:

Cannot resolve method 'requestLocationUpdates(com.google.android.gms.common.api.GoogleApiClient, android.location.LocationRequest, com.example.codingcafe.cab.DriversMapActivity)'

This is my class, I tried to add LocationListener to the implements, I changed the gms-location implementation in the build.gradle, nothing worked

package com.example.codingcafe.cab;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationRequest;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;

import com.example.codingcafe.cab.databinding.ActivityDriversMapBinding;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.LocationListener;

public class DriversMapActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        com.google.android.gms.location.LocationListener{

    private GoogleMap mMap;
    private ActivityDriversMapBinding binding;
    GoogleApiClient googleApiClient;
    Location LastLocation;
    LocationRequest locationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityDriversMapBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,17));
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            locationRequest = new LocationRequest.Builder( 1000)
                    .setMinUpdateIntervalMillis(500)
                    .setQuality(LocationRequest.QUALITY_HIGH_ACCURACY)
                    .setMaxUpdateDelayMillis(1000)
                    .build();

        }

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest,this);

        //it will handle the refreshment of the location
        //if we dont call it we will get location only once

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {

    }
}


问:
CountVectorizer not working in ColumnTransformer
Combining CountVectorizer() with ColumnTransformer() gives me an error. Here is a reproduced case:

```<code>from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd

# Create a sample data frame
df = pd.DataFrame({
    'corpus': ['This is the first document.', 'This document is the second document.', 'And this is the third one.',
               'Is this the first document?', 'I have the fourth document'],
    'word_length': [27, 37, 26, 27, 26]
})

text_feature = ["corpus"]
count_transformer = CountVectorizer()

# Create the ColumnTransformer
ct = ColumnTransformer(transformers=[
    ("count", count_transformer, text_feature)],
    remainder='passthrough')

ct.fit_transform(df)

</code>```

The output says:

```<code>ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 1 and the array at index 1 has size 5
</code>```

I tried the code below which does the job but is doesn't scale easily as ColumnTransformer().

np.c_[count_transformer.fit_transform(df["corpus"]).toarray(), df["word_length"].values].
The result is the numpy array below:

```<code>
array([[ 0,  1,  1,  0,  0,  1,  0,  0,  1,  0,  1, 27],
         0,  2,  0,  0,  0,  1,  0,  1,  1,  0,  1, 37],
         1,  0,  0,  0,  0,  1,  1,  0,  1,  1,  1, 26],
         0,  1,  1,  0,  0,  1,  0,  0,  1,  0,  1, 27],
         0,  1,  0,  1,  1,  0,  0,  0,  1,  0,  0, 26]], dtype=int64)
</code>```

Body:
Combining CountVectorizer() with ColumnTransformer() gives me an error. Here is a reproduced case:

from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd

# Create a sample data frame
df = pd.DataFrame({
    'corpus': ['This is the first document.', 'This document is the second document.', 'And this is the third one.',
               'Is this the first document?', 'I have the fourth document'],
    'word_length': [27, 37, 26, 27, 26]
})

text_feature = ["corpus"]
count_transformer = CountVectorizer()

# Create the ColumnTransformer
ct = ColumnTransformer(transformers=[
    ("count", count_transformer, text_feature)],
    remainder='passthrough')

ct.fit_transform(df)

The output says:

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 1 and the array at index 1 has size 5

I tried the code below which does the job but is doesn't scale easily as ColumnTransformer().

np.c_[count_transformer.fit_transform(df["corpus"]).toarray(), df["word_length"].values].
The result is the numpy array below:

array([[ 0,  1,  1,  0,  0,  1,  0,  0,  1,  0,  1, 27],
         0,  2,  0,  0,  0,  1,  0,  1,  1,  0,  1, 37],
         1,  0,  0,  0,  0,  1,  1,  0,  1,  1,  1, 26],
         0,  1,  1,  0,  0,  1,  0,  0,  1,  0,  1, 27],
         0,  1,  0,  1,  1,  0,  0,  0,  1,  0,  0, 26]], dtype=int64)