问:
Grid search with LightGBM example
I am trying to find the best parameters for a lightgbm model using GridSearchCV from sklearn.model_selection. I have not been able to find a solution that actually works.

I have managed to set up a partly working code:

```<code>import numpy as np
import pandas as pd
import lightgbm as lgb
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import KFold

np.random.seed(1)

train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
y = pd.read_csv('y.csv')
y = y.values.ravel()
print(train.shape, test.shape, y.shape)

categoricals = ['COL_A','COL_B']
indexes_of_categories = [train.columns.get_loc(col) for col in categoricals]

gkf = KFold(n_splits=5, shuffle=True, random_state=42).split(X=train, y=y)

param_grid = {
    'num_leaves': [31, 127],
    'reg_alpha': [0.1, 0.5],
    'min_data_in_leaf': [30, 50, 100, 300, 400],
    'lambda_l1': [0, 1, 1.5],
    'lambda_l2': [0, 1]
    }

lgb_estimator = lgb.LGBMClassifier(boosting_type='gbdt',  objective='binary', num_boost_round=2000, learning_rate=0.01, metric='auc',categorical_feature=indexes_of_categories)

gsearch = GridSearchCV(estimator=lgb_estimator, param_grid=param_grid, cv=gkf)
lgb_model = gsearch.fit(X=train, y=y)

print(lgb_model.best_params_, lgb_model.best_score_)
</code>```

This seems to be working but with a UserWarning:

categorical_feature keyword has been found in params and will be
  ignored. Please use categorical_feature argument of the Dataset
  constructor to pass this parameter.

I am looking for a working solution or perhaps a suggestion on how to ensure that lightgbm accepts categorical arguments in the above code

答:
In case you are struggling with how to pass the fit_params, which happened to me as well, this is how you should do that:</p>
```<code>fit_params = {'categorical_feature':indexes_of_categories}
clf = GridSearchCV(model, param_grid, cv=n_folds)
clf.fit(x_train, y_train, **fit_params)
</code>```

Title: Grid search with LightGBM example

Body:
I am trying to find the best parameters for a lightgbm model using GridSearchCV from sklearn.model_selection. I have not been able to find a solution that actually works.

I have managed to set up a partly working code:

import numpy as np
import pandas as pd
import lightgbm as lgb
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import KFold

np.random.seed(1)

train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
y = pd.read_csv('y.csv')
y = y.values.ravel()
print(train.shape, test.shape, y.shape)

categoricals = ['COL_A','COL_B']
indexes_of_categories = [train.columns.get_loc(col) for col in categoricals]

gkf = KFold(n_splits=5, shuffle=True, random_state=42).split(X=train, y=y)

param_grid = {
    'num_leaves': [31, 127],
    'reg_alpha': [0.1, 0.5],
    'min_data_in_leaf': [30, 50, 100, 300, 400],
    'lambda_l1': [0, 1, 1.5],
    'lambda_l2': [0, 1]
    }

lgb_estimator = lgb.LGBMClassifier(boosting_type='gbdt',  objective='binary', num_boost_round=2000, learning_rate=0.01, metric='auc',categorical_feature=indexes_of_categories)

gsearch = GridSearchCV(estimator=lgb_estimator, param_grid=param_grid, cv=gkf)
lgb_model = gsearch.fit(X=train, y=y)

print(lgb_model.best_params_, lgb_model.best_score_)

This seems to be working but with a UserWarning:

categorical_feature keyword has been found in params and will be
  ignored. Please use categorical_feature argument of the Dataset
  constructor to pass this parameter.

I am looking for a working solution or perhaps a suggestion on how to ensure that lightgbm accepts categorical arguments in the above code

Body:
In case you are struggling with how to pass the fit_params, which happened to me as well, this is how you should do that:

fit_params = {'categorical_feature':indexes_of_categories}
clf = GridSearchCV(model, param_grid, cv=n_folds)
clf.fit(x_train, y_train, **fit_params)


来源: stackexchange

问:
How to install package to a specific path contains a spece
i would like to install python package to a specific path. the problem is that path contains space as follows:

```<code>m:\ pip install --target=m:\s\a b\ package_name
</code>```

the package will not be installed in the designated path because the path contains space separating a nd b

please let me know how to solve this issue

答:
```<code>m:\ pip install package_name --target="m:\s\a b\package_name"
</code>```

This works on Windows machine.

ContentLicense: CC BY-SA 4.0

Body:
i would like to install python package to a specific path. the problem is that path contains space as follows:

m:\ pip install --target=m:\s\a b\ package_name

the package will not be installed in the designated path because the path contains space separating a nd b

please let me know how to solve this issue

Body:
m:\ pip install package_name --target="m:\s\a b\package_name"

This works on Windows machine.


问:
Android Geofence triggers on enter/exit with no error but no GEOFENCE_TRANSITION_ flag
I am monitoring for geofence transition using the code below

```<code>LocationServices.GeofencingApi
    .addGeofences(AssistApplication.getApiHelper().getClient(),
                  getGeofencingRequest(),
                  getPendingIntent(context,
                              GeofenceTransitionIntentService.class))
    .setResultCallback(this);
</code>```

This is how I build the GeofencingRequest

```<code>private GeofencingRequest getGeofencingRequest()
{
    return new GeofencingRequest.Builder()
            .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER |
                    GeofencingRequest.INITIAL_TRIGGER_EXIT)
            .addGeofence(getGeofence())
            .build();
}

private Geofence getGeofence()
{
    return new Geofence.Builder()
            .setRequestId(requestId)
            .setCircularRegion(latitude, longitude, 100)
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
                    Geofence.GEOFENCE_TRANSITION_EXIT)
            .build();
}
</code>```

The Geofence triggers correctly on enter and exit, but when I use getGeofenceTransition(), I am not getting any of the three GEOFENCE_TRANSITION_ flags.

```<code>protected void onHandleIntent(Intent intent)
{
    final GeofencingEvent event = GeofencingEvent.fromIntent(intent);
    if (event.hasError())
    {
        Log.e(TAG, getErrorMessage(event.getErrorCode()));
        return;
    }

    switch (event.getGeofenceTransition())
    {
        case Geofence.GEOFENCE_TRANSITION_EXIT:
            // Not triggered
            break;
        case Geofence.GEOFENCE_TRANSITION_ENTER:
        case Geofence.GEOFENCE_TRANSITION_DWELL:
            // Not triggered
            break;
        default:
            // Triggered on exit and enter
    }
}
</code>```

please advise on what I am missing here

答:
I've had the same issue working with geofences on Android 12. No transition (-1), no triggering location and no triggering geofences in the intent.

That was because I was using PendingIntent.FLAG_IMMUTABLE instead of PendingIntent.FLAG_MUTABLE when creating the pending intent.

So it should be created like this in the case of a broadcast intent:

```<code>PendingIntent.getBroadcast(
    context, 0,
    Intent(context, GeofenceBroadcastReceiver::class.java),
    PendingIntent.FLAG_UPDATE_CURRENT or
        (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else 0)
)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am monitoring for geofence transition using the code below

LocationServices.GeofencingApi
    .addGeofences(AssistApplication.getApiHelper().getClient(),
                  getGeofencingRequest(),
                  getPendingIntent(context,
                              GeofenceTransitionIntentService.class))
    .setResultCallback(this);

This is how I build the GeofencingRequest

private GeofencingRequest getGeofencingRequest()
{
    return new GeofencingRequest.Builder()
            .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER |
                    GeofencingRequest.INITIAL_TRIGGER_EXIT)
            .addGeofence(getGeofence())
            .build();
}

private Geofence getGeofence()
{
    return new Geofence.Builder()
            .setRequestId(requestId)
            .setCircularRegion(latitude, longitude, 100)
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
                    Geofence.GEOFENCE_TRANSITION_EXIT)
            .build();
}

The Geofence triggers correctly on enter and exit, but when I use getGeofenceTransition(), I am not getting any of the three GEOFENCE_TRANSITION_ flags.

protected void onHandleIntent(Intent intent)
{
    final GeofencingEvent event = GeofencingEvent.fromIntent(intent);
    if (event.hasError())
    {
        Log.e(TAG, getErrorMessage(event.getErrorCode()));
        return;
    }

    switch (event.getGeofenceTransition())
    {
        case Geofence.GEOFENCE_TRANSITION_EXIT:
            // Not triggered
            break;
        case Geofence.GEOFENCE_TRANSITION_ENTER:
        case Geofence.GEOFENCE_TRANSITION_DWELL:
            // Not triggered
            break;
        default:
            // Triggered on exit and enter
    }
}

please advise on what I am missing here

Body:
I've had the same issue working with geofences on Android 12. No transition (-1), no triggering location and no triggering geofences in the intent.

That was because I was using PendingIntent.FLAG_IMMUTABLE instead of PendingIntent.FLAG_MUTABLE when creating the pending intent.

So it should be created like this in the case of a broadcast intent:

PendingIntent.getBroadcast(
    context, 0,
    Intent(context, GeofenceBroadcastReceiver::class.java),
    PendingIntent.FLAG_UPDATE_CURRENT or
        (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else 0)
)


问:
Data factory cost reducing
How to reduce the costs of azure data factory (we have pipelines for data movement between tables, and triggers, datasets, alerts) ?

Thanks in advance,

答:
If you are using many copy activities to move data then the under settings tab you can change the default Data Integration Unit to be 2. The default is 4. This can make a big difference if you have many copy activities.
This will reduce the performance of the copy activity however.

.

Title: Data factory cost reducing


问:
How to get all PDF files from internal as well as external storage in Flutter?
I want to show All pdf files present in internal as well as external storage, So on tapping that particular file, i want to open that file in full screen dialog. </p>

答:
Here is my code to list files from the download folder

```<code> List<dynamic> filesList = [];
 Future listDir() async {
Directory dir =  Directory(
    '/storage/emulated/0/Download');

await for (FileSystemEntity entity
    in dir.list(recursive: true, followLinks: false)) {
  FileSystemEntityType type = await FileSystemEntity.type(entity.path);
  if (type == FileSystemEntityType.file &&
      entity.path.endsWith('.pdf')) {
    filesList.add(entity.path);
  }
}
return filesList;}
</code>```

Body:
Here is my code to list files from the download folder

 List<dynamic> filesList = [];
 Future listDir() async {
Directory dir =  Directory(
    '/storage/emulated/0/Download');

await for (FileSystemEntity entity
    in dir.list(recursive: true, followLinks: false)) {
  FileSystemEntityType type = await FileSystemEntity.type(entity.path);
  if (type == FileSystemEntityType.file &&
      entity.path.endsWith('.pdf')) {
    filesList.add(entity.path);
  }
}
return filesList;}


Title: Cut off text instead of going into a new line - Batch

Body:
I am trying to display cmdtext.txt in a batch file. I want it to just cut off (just as shown below) when there is no space left instead of going into a new line, because it ruins the "style" and the actual purpose of this file. (The batch file runs maximized, so the text would have enough space to display)

________/\\\\\\\\\__/\\\\____________/\\\\__/\\\\\\\\\\\\___________________/\\\\\\\\\\\\\\\______________________________/\\\\\\___________________________________________________________________________________________________________________________________________
______/\\\////////__\/\\\\\\________/\\\\\\_\/\\\////////\\\________________\///////\\\/////______________________________\////\\\__________________________________________________________________________________________________________________________________________
_____/\\\/___________\/\\\//\\\____/\\\//\\\_\/\\\______\//\\\_____________________\/\\\______________________________________\/\\\_________________________________________________________________________________________________________________________________________
_____/\\\_____________\/\\\\///\\\/\\\/_\/\\\_\/\\\_______\/\\\__/\\\\\\\\\\\_______\/\\\___________/\\\\\________/\\\\\_______\/\\\_____/\\\\\\\\\\________________________________________________________________________________________________________________________
_____\/\\\_____________\/\\\__\///\\\/___\/\\\_\/\\\_______\/\\\_\///////////________\/\\\_________/\\\///\\\____/\\\///\\\_____\/\\\____\/\\\//////________________________________________________________________________________________________________________________
______\//\\\____________\/\\\____\///_____\/\\\_\/\\\_______\/\\\_____________________\/\\\________/\\\__\//\\\__/\\\__\//\\\____\/\\\____\/\\\\\\\\\\______________________________________________________________________________________________________________________
________\///\\\__________\/\\\_____________\/\\\_\/\\\_______/\\\______________________\/\\\_______\//\\\__/\\\__\//\\\__/\\\_____\/\\\____\////////\\\_____________________________________________________________________________________________________________________
___________\////\\\\\\\\\_\/\\\_____________\/\\\_\/\\\\\\\\\\\\/_______________________\/\\\________\///\\\\\/____\///\\\\\/____/\\\\\\\\\__/\\\\\\\\\\____________________________________________________________________________________________________________________
_______________\/////////__\///______________\///__\////////////_________________________\///___________\/////________\/////_____\/////////__\//////////____________________________________________________________________________________________________________________

Body:
Batch has no builtins for tasks like this. When you wish to format or restrict output, you need to consider what steps you need to take to achieve the goal.

First, consider what information you need. In this task, you need:

The width of the console in columns

Acquire this by iterating over the mode command with a for /f loop

The data to format

Next, For the purpose of restricting output to the consoles width, Substing modification can be used to trim the data you are formatting to the consoles width:

@Echo off
Call:Header
Set /A Y=lines,X=columns
Timeout /t 2 /NoBreak
mode 90,30
Call:Header
Timeout /t 2 /NoBreak
mode %X%,%Y%
Goto:Eof

:Header
(Set LF=^

%= Empty lines above required =%)
 Setlocal EnableDelayedExpansion
 For /f "tokens=1,2 Delims=: " %%G in ('mode ^| findstr /li "col lin"')Do Set "$%%G=%%H"
 Set "Output="
 For /f "usebackq tokens=1 delims=:1;" %%G in (`type "%~f0" ^| %SystemRoot%\System32\findstr.exe /blc:":1;" "%~f0"`) Do (
  Set "Line=%%G"
  Set "Output=!Output!!Line:~0,%$Columns%!!LF!"
 )
 Echo(!Output!
 For /f "tokens=1,2 Delims=;" %%G in ("lines=!$lines!;Columns=!$Columns!")Do Endlocal & (
  Set "%%G"
  Set "%%H"
 )
Exit /b

:1;________/\\\\\\\\\__/\\\\____________/\\\\__/\\\\\\\\\\\\___________________/\\\\\\\\\\\\\\\______________________________/\\\\\\___________________________________________________________________________________________________________________________________________
:1;______/\\\////////__\/\\\\\\________/\\\\\\_\/\\\////////\\\________________\///////\\\/////______________________________\////\\\__________________________________________________________________________________________________________________________________________
:1;_____/\\\/___________\/\\\//\\\____/\\\//\\\_\/\\\______\//\\\_____________________\/\\\______________________________________\/\\\_________________________________________________________________________________________________________________________________________
:1;_____/\\\_____________\/\\\\///\\\/\\\/_\/\\\_\/\\\_______\/\\\__/\\\\\\\\\\\_______\/\\\___________/\\\\\________/\\\\\_______\/\\\_____/\\\\\\\\\\________________________________________________________________________________________________________________________
:1;_____\/\\\_____________\/\\\__\///\\\/___\/\\\_\/\\\_______\/\\\_\///////////________\/\\\_________/\\\///\\\____/\\\///\\\_____\/\\\____\/\\\//////________________________________________________________________________________________________________________________
:1;______\//\\\____________\/\\\____\///_____\/\\\_\/\\\_______\/\\\_____________________\/\\\________/\\\__\//\\\__/\\\__\//\\\____\/\\\____\/\\\\\\\\\\______________________________________________________________________________________________________________________
:1;________\///\\\__________\/\\\_____________\/\\\_\/\\\_______/\\\______________________\/\\\_______\//\\\__/\\\__\//\\\__/\\\_____\/\\\____\////////\\\_____________________________________________________________________________________________________________________
:1;___________\////\\\\\\\\\_\/\\\_____________\/\\\_\/\\\\\\\\\\\\/_______________________\/\\\________\///\\\\\/____\///\\\\\/____/\\\\\\\\\__/\\\\\\\\\\____________________________________________________________________________________________________________________
:1;_______________\/////////__\///______________\///__\////////////_________________________\///___________\/////________\/////_____\/////////__\//////////____________________________________________________________________________________________________________________


问:
Distinct Linq search query
I have a table say TABLEA

ID
Description
regNumber

001
iphone
9890

002
iphone pro max
9890

003
iphone se
9890

004
iphone
7847

008
samsung
9432

009
samsung s10
9432

010
orange
34

Problem
Get all the regNumber that matches and display as a consolidated data (single data)

Acceptable solution
For example if someone search for an id with '001' get all the SAME regNumber like this

Desc
regNumber
Total number of reg

iphone
9890
3

Part Solution
I have listed all the regNumber like this:

```<code>var listOfRegs = _db.Table.Select(x=>x.regNumber).toList();
</code>```

I now need to find a way to iterate this list to group how many times a regNumber matches which is the problem I'm having but something like this:

```<code>foreach(var i in listOfRegs)
{
  //find a way to group/list distinct regNumbers which is why I'm asking?

}
</code>```

It's easier if the query was to search for the regNumber which you can pass through the action something like this:

```<code>var listOfRegs = _db.TABLE.where (a.regNumber==
model.regNumberSearched).Select(x=>x.regNumber).Distinct().ToList();

//this works fine
</code>```

But the problem is that I'm not passing that regNumber Instead just got a list of regNumber that matches 'ID' from the table and as u can see from the table ID is always
unique so passing model.id (the id being pass) will always only output a unique regNumber
rather than counting all matches.
so how do I proceed please?

答:
You can use GroupBy() and project the result into an anonymous type:

```<code>var groupedData = _db.Table.GroupBy(x => x.regNumber)  // group by regNumber
                           .Select(g => new
                           {
                               Desc = g.First().Desc,  // use the first Desc
                               RegNumber = g.Key,      // RegNumber is the group Key
                               Count = g.Count()       // number of elements in group
                           })
                           .ToList();
</code>```

This will give you output similar to:

Desc
RegNumber
Count

iphone
9890
3

samsung
9432
2

orange
34
1

If you have a list of Table IDs to filter on, say listOfIds, you can filter that first to get all associated regNumber, then use the list of regNumbers to group the data:

```<code>List<int> listOfIds = // your list of Table Ids from the DB
// get your list of regNumbers based on table IDs
var listOfRegNumbers = _db.Table.Where(t => listOfIds.Any(id => id == t.Id))
                                .Select(t => t.regNumber)
                                .Distinct();
// group the data
var groupedData = _db.Table.Where(x => listOfRegNumbers.Any(id => id == x.regNumber))
                           .GroupBy(x => x.regNumber)  // group by regNumber
                           .Select(g => new
                           {
                               Desc = g.First().Desc,  // use the first Desc
                               RegNumber = g.Key,      // RegNumber is the group Key
                               Count = g.Count()       // number of elements in group
                           })
                           .ToList();
</code>```

However, I not sure that's required for your case. Using List<string> would work above too, depending on your data type of the column.

Here is an online demo (adapted from Prasad Telkikar's - thank you!).

Title: Distinct Linq search query

Body:
I have a table say TABLEA

ID
Description
regNumber

001
iphone
9890

002
iphone pro max
9890

003
iphone se
9890

004
iphone
7847

008
samsung
9432

009
samsung s10
9432

010
orange
34

Problem
Get all the regNumber that matches and display as a consolidated data (single data)

Acceptable solution
For example if someone search for an id with '001' get all the SAME regNumber like this

Desc
regNumber
Total number of reg

iphone
9890
3

Part Solution
I have listed all the regNumber like this:

var listOfRegs = _db.Table.Select(x=>x.regNumber).toList();

I now need to find a way to iterate this list to group how many times a regNumber matches which is the problem I'm having but something like this:

foreach(var i in listOfRegs)
{
  //find a way to group/list distinct regNumbers which is why I'm asking?

}

It's easier if the query was to search for the regNumber which you can pass through the action something like this:

var listOfRegs = _db.TABLE.where (a.regNumber==
model.regNumberSearched).Select(x=>x.regNumber).Distinct().ToList();

//this works fine

But the problem is that I'm not passing that regNumber Instead just got a list of regNumber that matches 'ID' from the table and as u can see from the table ID is always
unique so passing model.id (the id being pass) will always only output a unique regNumber
rather than counting all matches.
so how do I proceed please?

Body:
You can use GroupBy() and project the result into an anonymous type:

var groupedData = _db.Table.GroupBy(x => x.regNumber)  // group by regNumber
                           .Select(g => new
                           {
                               Desc = g.First().Desc,  // use the first Desc
                               RegNumber = g.Key,      // RegNumber is the group Key
                               Count = g.Count()       // number of elements in group
                           })
                           .ToList();

This will give you output similar to:

Desc
RegNumber
Count

iphone
9890
3

samsung
9432
2

orange
34
1

If you have a list of Table IDs to filter on, say listOfIds, you can filter that first to get all associated regNumber, then use the list of regNumbers to group the data:

List<int> listOfIds = // your list of Table Ids from the DB
// get your list of regNumbers based on table IDs
var listOfRegNumbers = _db.Table.Where(t => listOfIds.Any(id => id == t.Id))
                                .Select(t => t.regNumber)
                                .Distinct();
// group the data
var groupedData = _db.Table.Where(x => listOfRegNumbers.Any(id => id == x.regNumber))
                           .GroupBy(x => x.regNumber)  // group by regNumber
                           .Select(g => new
                           {
                               Desc = g.First().Desc,  // use the first Desc
                               RegNumber = g.Key,      // RegNumber is the group Key
                               Count = g.Count()       // number of elements in group
                           })
                           .ToList();

However, I not sure that's required for your case. Using List<string> would work above too, depending on your data type of the column.

Here is an online demo (adapted from Prasad Telkikar's - thank you!).


问:
How to getCurrentPageNumber() in Itext 7
In Itext 5, PdfWriter used to have a method called getCurrentPageNumber().
Itext 7 does not have it anymore.

How can I get the current page number since the entire pdf is going to use the same Document instance ( PdfDocument pdfDocument = new PdfDocument(writer))from start to end?

Use case: An apllication written using itext5 needs to be rewritten using itext7.
Our app generates PDF files for our customer's monthly bills.

Structure of the pdf:

Create document:

```<code> PdfWriter writer = new PdfWriter(new FileOutputStream(filename));
 PdfDocument pdfDocument = new PdfDocument(writer);
 Document document = new Document(pdfDocument, PageSize.A4);
 document.setMargins(235, 35, 0, 38);
 buildBody(pdfData, document, writer);
</code>```

For every page I use an IEventHandler for the Start and another one for the End of the pages to add some data at the Header and Footer.

```<code> pdfDocument.addEventHandler(PdfDocumentEvent.START_PAGE, new
 StartPageHandler<>(pdfData, document, this));
 pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new
 EndPageHandler<>(pdfData, document, this));
</code>```

3.Each IEventHandler instance has this format(except the rectangle values):

```<code>Rectangle rectangle = new Rectangle(51, 50, 500, 60); (This is for the END_PAGE)
Rectangle[] columns = new Rectangle[] {rectangle};
document.setRenderer(new ColumnDocumentRenderer(document, columns));
document.add(lineSeparatorHeader);
document.add(paragraphInfo); // information used in the Header/Footer
</code>```

The buildBody(pdfData, document, writer) method (from step 1) was using the writer.getCurrentPageNumber() method in order to check if the content we wanted to add has exceeded the space on the page and has passed on another page. If it passed on another page, I would have to add some extra information (somehow as a title in the body of the page) before the rest of the content is added. (It used to work with itext5)

答:
Considering that the code you want to port apparently used the iText 5 PdfDocument/PdfWriter pattern, the current page number in that code always was the currently last page number, i.e. the current number of pages in the document being created.

In iText 7 these numbers are not automatically the same; if you port the code keeping the general architecture, though, those numbers most likely will remain the same in your iText 7 code, too.

In iText 7 you can get the current number of pages from the PdfDocument in question:

```<code>PdfDocument pdfDocument = ...;
...
int currentNamberOfPages = pdfDocument.getNumberOfPages();
</code>```

Currently your buildBody method signature does not include the PdfDocument (which made sense in iText 5). For iText 7 you should consider changing the signature to include the PdfDocument. Most likely, though, you won't need the PdfWriter anymore which you then can exclude.

If you need to keep that method signature for some obscure reason, you can retrieve the PdfDocument from the Document using the getPdfDocument method.

Body:
In Itext 5, PdfWriter used to have a method called getCurrentPageNumber().
Itext 7 does not have it anymore.

How can I get the current page number since the entire pdf is going to use the same Document instance ( PdfDocument pdfDocument = new PdfDocument(writer))from start to end?

Use case: An apllication written using itext5 needs to be rewritten using itext7.
Our app generates PDF files for our customer's monthly bills.

Structure of the pdf:

Create document:

 PdfWriter writer = new PdfWriter(new FileOutputStream(filename));
 PdfDocument pdfDocument = new PdfDocument(writer);
 Document document = new Document(pdfDocument, PageSize.A4);
 document.setMargins(235, 35, 0, 38);
 buildBody(pdfData, document, writer);

For every page I use an IEventHandler for the Start and another one for the End of the pages to add some data at the Header and Footer.

 pdfDocument.addEventHandler(PdfDocumentEvent.START_PAGE, new
 StartPageHandler<>(pdfData, document, this));
 pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new
 EndPageHandler<>(pdfData, document, this));

3.Each IEventHandler instance has this format(except the rectangle values):

Rectangle rectangle = new Rectangle(51, 50, 500, 60); (This is for the END_PAGE)
Rectangle[] columns = new Rectangle[] {rectangle};
document.setRenderer(new ColumnDocumentRenderer(document, columns));
document.add(lineSeparatorHeader);
document.add(paragraphInfo); // information used in the Header/Footer

The buildBody(pdfData, document, writer) method (from step 1) was using the writer.getCurrentPageNumber() method in order to check if the content we wanted to add has exceeded the space on the page and has passed on another page. If it passed on another page, I would have to add some extra information (somehow as a title in the body of the page) before the rest of the content is added. (It used to work with itext5)

Body:
Considering that the code you want to port apparently used the iText 5 PdfDocument/PdfWriter pattern, the current page number in that code always was the currently last page number, i.e. the current number of pages in the document being created.

In iText 7 these numbers are not automatically the same; if you port the code keeping the general architecture, though, those numbers most likely will remain the same in your iText 7 code, too.

In iText 7 you can get the current number of pages from the PdfDocument in question:

PdfDocument pdfDocument = ...;
...
int currentNamberOfPages = pdfDocument.getNumberOfPages();

Currently your buildBody method signature does not include the PdfDocument (which made sense in iText 5). For iText 7 you should consider changing the signature to include the PdfDocument. Most likely, though, you won't need the PdfWriter anymore which you then can exclude.

If you need to keep that method signature for some obscure reason, you can retrieve the PdfDocument from the Document using the getPdfDocument method.


问:
Change colors of IconButton
I have the following widget implemented:

```<code>TextFormField(
                  controller: _loginPageViewModel.passwordTEC,
                  obscureText: true,
                  decoration: InputDecoration(
                    hintText: S.of(context).password,
                    suffixIcon: IconButton(
                      onPressed: _loginPageViewModel.passwordTEC.clear,
                      icon: const Icon(Icons.clear),
                    ),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return S.of(context).passwordValidation;
                    }
                    return null;
                  },
                )
</code>```

At the same time I'm implementing ThemeData. I managed to changed the border color of InputDecoration, whether the TextFormField has focus or not, but the color of suffixIcon is different. Which parameters of ThemeData are connected to the color of the suffixIcon, both in normal state and when in focus? Cheers

答:
Try this

theme: ThemeData().copyWith(   colorScheme:
ThemeData().colorScheme.copyWith(
primary: Colors.green,   ), ),

Title: Change colors of IconButton

Body:
I have the following widget implemented:

TextFormField(
                  controller: _loginPageViewModel.passwordTEC,
                  obscureText: true,
                  decoration: InputDecoration(
                    hintText: S.of(context).password,
                    suffixIcon: IconButton(
                      onPressed: _loginPageViewModel.passwordTEC.clear,
                      icon: const Icon(Icons.clear),
                    ),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return S.of(context).passwordValidation;
                    }
                    return null;
                  },
                )

At the same time I'm implementing ThemeData. I managed to changed the border color of InputDecoration, whether the TextFormField has focus or not, but the color of suffixIcon is different. Which parameters of ThemeData are connected to the color of the suffixIcon, both in normal state and when in focus? Cheers


问:
How to change default PM2 table name user to administartor?
PM2 table configuration server of nest-js</p>

答:
step:1 PM2-configuration:

1.npm install -g pm2

2.pm2 list

3.pm2 status

4.pm2 start dist/main.js --name appname

5.pm2 save

6.pm2 monit

7.pm2 logs

8.pm2 kill

step-2 If u want the the saved app:

9.pm2 resurrect

step-3 ecosystem-file configuration:

10.pm2 start ecosystem.config.js


问:
How to avoid misrepresented data by 3 days in the rolling mean graph in python?
I calculated 7day_rolling_avg because irregularities in covid data by this code:

```<code>covid_df['7day_rolling_avg'] = covid_df['New cases'].rolling(7).mean()
</code>```

But, by plotting a graph on top of each other new graph can be seen misrepresented by 3-4 days.

Code:

```<code>covid_df[covid_df["Country"]=="India"]['New cases'].plot()
covid_df[covid_df["Country"]=="India"]['7day_rolling_avg'].plot()
plt.legend()
plt.show()
</code>```

Output:

Can someone give me any idea how can I fix it?

答:
use center=True in rolling

```<code>covid_df['7day_rolling_avg'] = covid_df['New cases'].rolling(7, center=True).mean()
</code>```

Output:

Body:
I calculated 7day_rolling_avg because irregularities in covid data by this code:

covid_df['7day_rolling_avg'] = covid_df['New cases'].rolling(7).mean()

But, by plotting a graph on top of each other new graph can be seen misrepresented by 3-4 days.

Code:

covid_df[covid_df["Country"]=="India"]['New cases'].plot()
covid_df[covid_df["Country"]=="India"]['7day_rolling_avg'].plot()
plt.legend()
plt.show()

Output:

Can someone give me any idea how can I fix it?

Body:
use center=True in rolling

covid_df['7day_rolling_avg'] = covid_df['New cases'].rolling(7, center=True).mean()

Output:


问:
How to underline two div's consecutively?
I've got 2
s that each gather their text from some JS that I've written.
But I want the end-result to look like in the following image. And I can't figure out how to do that.

I can consolidate them into a single  but then I have the issue of needing to apply two different weights to a single
, which also wracks my brain.

So basically I want text with 2 different font-weights to be underlined with no interruption.

I've tried the following, and a lot of googling:

```<code>div.parentDiv {
    text-decoration-line : underline;
}
</code>```

答:
I guess you wanted to both the div text to be underlined.

body {
  font-family: sans-serif;
  background: #dedede;
  padding: 48px;
}

.parent {
  display: flex;
  flex-direction: row;
  text-decoration: underline;
  font-weight: 600;
}

.child1 {
  color: red;
}
.child2 {
  color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>                <div class="parent">
                        <div class="child1">Good Reviews</div>
                        <div class="child2">(30)</div>
                </div></code>```

However to achieve the result you want you can use  .

body {
  font-family: sans-serif;
  background: #dedede;
  padding: 48px;
}

.child1 {
  text-decoration: underline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>                <div>
                        <span class="child1">Good Reviews   (30)</span>
                </div></code>```

Body:
I've got 2
s that each gather their text from some JS that I've written.
But I want the end-result to look like in the following image. And I can't figure out how to do that.

I can consolidate them into a single  but then I have the issue of needing to apply two different weights to a single
, which also wracks my brain.

So basically I want text with 2 different font-weights to be underlined with no interruption.

I've tried the following, and a lot of googling:

div.parentDiv {
    text-decoration-line : underline;
}

Body:
I guess you wanted to both the div text to be underlined.

body {
  font-family: sans-serif;
  background: #dedede;
  padding: 48px;
}

.parent {
  display: flex;
  flex-direction: row;
  text-decoration: underline;
  font-weight: 600;
}

.child1 {
  color: red;
}
.child2 {
  color: green;
}

                <div class="parent">
                        <div class="child1">Good Reviews</div>
                        <div class="child2">(30)</div>
                </div>

However to achieve the result you want you can use &nbsp;.

body {
  font-family: sans-serif;
  background: #dedede;
  padding: 48px;
}

.child1 {
  text-decoration: underline;
}

                <div>
                        <span class="child1">Good Reviews&nbsp;&nbsp;&nbsp;(30)</span>
                </div>


问:
How do you enable the escape key close functionality in a Twitter Bootstrap modal?
I followed the instructions for the Twitter Bootstrap modal on their main documentation page
 and used the data-keyboard="true" syntax mentioned but the escape key does not close the modal window.
  Is there something else I'm missing?

Code:

```<code><a href="#my-modal" data-keyboard="true" data-toggle="modal">Open Modal</a>

<div class='modal fade hide' id='my-modal'>
  <div class='modal-body'>
    <div>Test</div>
  </div>
</div>
</code>```

答:
let modals = []</p>
```<code>        $(document).keyup(function(e) {
            if((e.key=='Escape' || e.key=='Esc' || e.keyCode==27) && modals.length) {
                $(".modal[modal='" + modals.pop() + "']").modal('hide')
            }
        })

        $(".modal").on("shown.bs.modal", e => {
            const id = modals.length
            modals.push(id)
            $(e.target).attr("modal", id)
        })
</code>```

Body:
I followed the instructions for the Twitter Bootstrap modal on their main documentation page
 and used the data-keyboard="true" syntax mentioned but the escape key does not close the modal window.
  Is there something else I'm missing?

Code:

Open Modal

Test

Body:
let modals = []

        $(document).keyup(function(e) {
            if((e.key=='Escape' || e.key=='Esc' || e.keyCode==27) && modals.length) {
                $(".modal[modal='" + modals.pop() + "']").modal('hide')
            }
        })

        $(".modal").on("shown.bs.modal", e => {
            const id = modals.length
            modals.push(id)
            $(e.target).attr("modal", id)
        })


问:
How do I connect different namespaces and modules in Python
I'm developing a physical model using Python. I right now have four files (I suppose I can call them modules but I really am no Python expert) in one folder. Right now it works just fine but after reading a bit it turned out the way I do it could lead to errors when further expanding my model (by using from ... import* statement).

(1) initialize: Does nothing except for calling the plot() module with some information about what to plot. Here I would like to set some initial parameters which won't change during the computation and pass them to the compute module. Imports plot

(2) compute: Contains initial values (which I actually want to set in initialize module) and all the computation algorithm. During computation, functions which are stored in functions module are being called a lot. Imports  functions

(3) functions: Contains actual physical functions.

(4) plot: Contains all the plots. Imports everything from compute (from compute import *)

Originally I only had the compute and the functions module. When I started plotting however, the compute module became too big (in my eyes) so I wanted to split. I realized I would need to pass all the variables I calculated in compute (quite a few) as arguments to the plot module. Or alternatively import the compute module with a prefix (e.g. import compute as com --> com.variable). I didn't like both options too much. So i decided to use the from compute import * statement, which allows me to use the same variable names as originally defined in compute. This looks a lot cleaner to me and makes it easier to read to variable names.

The problem is, when importing compute into my plot module (to get all the variable names) the code in compute is executed. But I would like to call compute from my initialize module to set up the initial parameters. However If i do so i would need to call compute twice, which takes a lot more time. Besides that, from ... import * apparently is not a good choice.
I'm grateful for any suggestions.

答:
for namespace you can check python document
and for module put command in terminal

pip install (module name)

example:-

pip install flask
#the flask module is automatically download in your system


问:
How to update a user using the 'Ion Auth' authentication library in CodeIgniter 4 framework
Below is my code snippet. I want to reduce the balance of a user in the database using Codeigniter 4?

```<code>dd($this->ionAuth->update($this->ionAuth->users()->row()->id, ['balance' => 1000]));
</code>```

*I'm using Ion Auth for updating.
It's just a big burden when updating the database using modelling data.

答:
look here authentcate library for ci4

```<code>https://github.com/lonnieezell/myth-auth
</code>```

go there  download it

ionAuth is not compablitablke with ci4

Body:
Below is my code snippet. I want to reduce the balance of a user in the database using Codeigniter 4?

dd($this->ionAuth->update($this->ionAuth->users()->row()->id, ['balance' => 1000]));

*I'm using Ion Auth for updating.
It's just a big burden when updating the database using modelling data.

Body:
look here authentcate library for ci4

https://github.com/lonnieezell/myth-auth

go there  download it

ionAuth is not compablitablke with ci4


问:
Transition don't work with min-height property
I tried to make smooth transition while box is changing height, but when i use min-height, which is very important to me, transition dont work, here is example code that i make to make sure that this problem dont show only on my page but everywhere.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.main {
  width: 100%;
  height: 100vh;
  background-color: #F4EEA9;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  width: 50%;
  min-height: 10vh;
  box-shadow: rgba(0, 0, 0, 0.25) 0px 14px 28px, rgba(0, 0, 0, 0.22) 0px 10px 10px;
  padding: 20px;
  transition: 0.5s;
}

.box:hover {
  height: 50vh;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="style.css">
  <title>TEST</title>
</head>

<body>
  <div class="main">
    <div class="box">
      <h1>Hello World</h1>
      <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Cupiditate mollitia numquam est voluptas rem, voluptates dolore a rerum amet eos quae eum laudantium exercitationem quas quasi vel quia perferendis consectetur sit omnis. Placeat, nisi deleniti.
        Facere architecto, possimus veritatis quo molestiae temporibus vero vel recusandae, iusto ullam nostrum quia voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt nesciunt ratione consectetur corrupti laboriosam aliquid,
        beatae atque laborum deleniti adipisci esse blanditiis cum facere sequi voluptatibus, molestias eos sint tempore quia, quo cumque quasi. Repellat quas quaerat soluta officia voluptatum dolorum nobis a iure voluptatem id, cumque corporis voluptas
        nesciunt.</p>
    </div>
  </div>
</body>

</html></code>```

答:
You have to add init height value first to make it work.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.main {
  width: 100%;
  height: 100vh;
  background-color: #F4EEA9;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  width: 50%;
  min-height: 12vh;
  box-shadow: rgba(0, 0, 0, 0.25) 0px 14px 28px, rgba(0, 0, 0, 0.22) 0px 10px 10px;
  padding: 20px;
  transition: 0.5s;
  /* adjust this value */
  height: 0;
  overflow: auto;
}

.box:hover {
  height: 50vh;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="style.css">
  <title>TEST</title>
</head>

<body>
  <div class="main">
    <div class="box">
      <h1>Hello World</h1>
      <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Cupiditate mollitia numquam est voluptas rem, voluptates dolore a rerum amet eos quae eum laudantium exercitationem quas quasi vel quia perferendis consectetur sit omnis. Placeat, nisi deleniti.
        Facere architecto, possimus veritatis quo molestiae temporibus vero vel recusandae, iusto ullam nostrum quia voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt nesciunt ratione consectetur corrupti laboriosam aliquid,
        beatae atque laborum deleniti adipisci esse blanditiis cum facere sequi voluptatibus, molestias eos sint tempore quia, quo cumque quasi. Repellat quas quaerat soluta officia voluptatum dolorum nobis a iure voluptatem id, cumque corporis voluptas
        nesciunt.</p>
    </div>
  </div>
</body>

</html></code>```

Body:
I tried to make smooth transition while box is changing height, but when i use min-height, which is very important to me, transition dont work, here is example code that i make to make sure that this problem dont show only on my page but everywhere.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.main {
  width: 100%;
  height: 100vh;
  background-color: #F4EEA9;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  width: 50%;
  min-height: 10vh;
  box-shadow: rgba(0, 0, 0, 0.25) 0px 14px 28px, rgba(0, 0, 0, 0.22) 0px 10px 10px;
  padding: 20px;
  transition: 0.5s;
}

.box:hover {
  height: 50vh;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <link rel="stylesheet" href="style.css">
  <title>TEST</title>

Hello World

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Cupiditate mollitia numquam est voluptas rem, voluptates dolore a rerum amet eos quae eum laudantium exercitationem quas quasi vel quia perferendis consectetur sit omnis. Placeat, nisi deleniti.
        Facere architecto, possimus veritatis quo molestiae temporibus vero vel recusandae, iusto ullam nostrum quia voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt nesciunt ratione consectetur corrupti laboriosam aliquid,
        beatae atque laborum deleniti adipisci esse blanditiis cum facere sequi voluptatibus, molestias eos sint tempore quia, quo cumque quasi. Repellat quas quaerat soluta officia voluptatum dolorum nobis a iure voluptatem id, cumque corporis voluptas
        nesciunt.

Body:
You have to add init height value first to make it work.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.main {
  width: 100%;
  height: 100vh;
  background-color: #F4EEA9;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  width: 50%;
  min-height: 12vh;
  box-shadow: rgba(0, 0, 0, 0.25) 0px 14px 28px, rgba(0, 0, 0, 0.22) 0px 10px 10px;
  padding: 20px;
  transition: 0.5s;
  /* adjust this value */
  height: 0;
  overflow: auto;
}

.box:hover {
  height: 50vh;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="style.css">
  <title>TEST</title>
</head>

<body>
  <div class="main">
    <div class="box">
      <h1>Hello World</h1>
      <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Cupiditate mollitia numquam est voluptas rem, voluptates dolore a rerum amet eos quae eum laudantium exercitationem quas quasi vel quia perferendis consectetur sit omnis. Placeat, nisi deleniti.
        Facere architecto, possimus veritatis quo molestiae temporibus vero vel recusandae, iusto ullam nostrum quia voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt nesciunt ratione consectetur corrupti laboriosam aliquid,
        beatae atque laborum deleniti adipisci esse blanditiis cum facere sequi voluptatibus, molestias eos sint tempore quia, quo cumque quasi. Repellat quas quaerat soluta officia voluptatum dolorum nobis a iure voluptatem id, cumque corporis voluptas
        nesciunt.</p>
    </div>
  </div>
</body>

</html>


问:
Why am I getting errors while adding launcher icon in flutter project?
So, I am trying change the default flutter launcher icon with my one. I am using the flutter_launcher_icons: ^0.9.2 from pub.dev.
The code in pubspec.yaml:

```<code>dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  hexcolor: ^2.0.5
  google_fonts: ^2.1.0
  flutter_neumorphic: ^3.2.0
  flutter_launcher_icons: ^0.9.2

dev_dependencies:
  flutter_lints: ^1.0.4
  flutter_test:
    sdk: flutter

flutter_icons:
  image_path: "assets/icon/icon.png"
  android: true
  ios: true
</code>```

But when I am running flutter pub run flutter_launcher_icons:main, I am getting error saying:

```<code>  ════════════════════════════════════════════
     FLUTTER LAUNCHER ICONS (v0.9.1)
  ════════════════════════════════════════════

✓ Successfully generated launcher icons
Unhandled exception:
FormatException: Invalid number (at character 1)

^

#0      int._handleFormatError (dart:core-patch/integers_patch.dart:129:7)
#1      int.parse (dart:core-patch/integers_patch.dart:55:14)
#2      minSdk (package:flutter_launcher_icons/android.dart:309:18)
#3      createIconsFromConfig (package:flutter_launcher_icons/main.dart:94:47)
#4      createIconsFromArguments (package:flutter_launcher_icons/main.dart:60:7)
#5      main (file:///C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_launcher_icons-0.9.2/bin/main.dart:6:26)
#6      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:295:32)
#7      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
pub finished with exit code 255
</code>```

And the Icon doesn't change.

What probably the problem?

=> I mean, coz it worked many times before...

答:
I faced the same problem and found a solution

1.Add dependancy as below [pubspec.yaml]

```<code>dependencies:
  flutter:
    sdk: flutter
  flutter_launcher_icons: ^0.9.2  // add lib as here
</code>```

2. add below line [pubspec.yaml]

```<code>flutter_icons:
  image_path: "assets/launcher_icon.png"
  android: true
  ios: true
  remove_alpha_ios: true
</code>```

3.Open local.properties file and add below line [android\local.properties]

```<code>flutter.minSdkVersion=21
</code>```

4.Now go to app/build.gradle file and add this if not present: [app level > build.gradle]

```<code>def flutterMinSdkVersion = localProperties.getProperty('flutter.minSdkVersion')
if (flutterMinSdkVersion == null) {
    flutterMinSdkVersion = flutter.minSdkVersion.toString()
}
</code>```

5.Then go to defaultConfig in build.gradle [go to below same file]

replace this line >  minSdkVersion flutter.minSdkVersion

with this > minSdkVersion flutterMinSdkVersion

6. go to build.gradle and save

7. go to local.properties and save

8. go to android studio and run below

```<code>flutter pub get

flutter pub run flutter_launcher_icons:main
</code>```

It will work :) !

Body:
So, I am trying change the default flutter launcher icon with my one. I am using the flutter_launcher_icons: ^0.9.2 from pub.dev.
The code in pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  hexcolor: ^2.0.5
  google_fonts: ^2.1.0
  flutter_neumorphic: ^3.2.0
  flutter_launcher_icons: ^0.9.2

dev_dependencies:
  flutter_lints: ^1.0.4
  flutter_test:
    sdk: flutter

flutter_icons:
  image_path: "assets/icon/icon.png"
  android: true
  ios: true

But when I am running flutter pub run flutter_launcher_icons:main, I am getting error saying:

  ════════════════════════════════════════════
     FLUTTER LAUNCHER ICONS (v0.9.1)
  ════════════════════════════════════════════

✓ Successfully generated launcher icons
Unhandled exception:
FormatException: Invalid number (at character 1)

^

#0      int._handleFormatError (dart:core-patch/integers_patch.dart:129:7)
#1      int.parse (dart:core-patch/integers_patch.dart:55:14)
#2      minSdk (package:flutter_launcher_icons/android.dart:309:18)
#3      createIconsFromConfig (package:flutter_launcher_icons/main.dart:94:47)
#4      createIconsFromArguments (package:flutter_launcher_icons/main.dart:60:7)
#5      main (file:///C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_launcher_icons-0.9.2/bin/main.dart:6:26)
#6      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:295:32)
#7      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
pub finished with exit code 255

And the Icon doesn't change.

What probably the problem?

=> I mean, coz it worked many times before...

Body:
I faced the same problem and found a solution

1.Add dependancy as below [pubspec.yaml]

dependencies:
  flutter:
    sdk: flutter
  flutter_launcher_icons: ^0.9.2  // add lib as here

2. add below line [pubspec.yaml]

flutter_icons:
  image_path: "assets/launcher_icon.png"
  android: true
  ios: true
  remove_alpha_ios: true

3.Open local.properties file and add below line [android\local.properties]

flutter.minSdkVersion=21

4.Now go to app/build.gradle file and add this if not present: [app level > build.gradle]

def flutterMinSdkVersion = localProperties.getProperty('flutter.minSdkVersion')
if (flutterMinSdkVersion == null) {
    flutterMinSdkVersion = flutter.minSdkVersion.toString()
}

5.Then go to defaultConfig in build.gradle [go to below same file]

replace this line >  minSdkVersion flutter.minSdkVersion

with this > minSdkVersion flutterMinSdkVersion

6. go to build.gradle and save

7. go to local.properties and save

8. go to android studio and run below

flutter pub get

flutter pub run flutter_launcher_icons:main

It will work :) !


问:
Disable 2 submit buttons in single form after clicking button
when having two submit buttons named submit and nopay, only one is working at a time. I need to disable both buttons after clicking and submitting the form.

```<code><form enctype="multipart/form-data" method="post" action="
    <?php echo base_url();?>user/Purchases_ctrl/create_vendor_payment" onsubmit='disableButton()'>
  <div class="d-flex content-block mb-2 pt-4 justify-content-center">
    <button type="submit" name="submit" value="submit" id="submit" class="btn btn-outline-custom w-30 btn-sm submit-btn mr-3">Submit</button>
    <button type="submit" id="nopay" name="nopay" value="nopay" class="btn btn-outline-custom w-30 btn-sm submit-btn">No Vendor Payments Today</button>
  </div>
</form>

<script>
  function disableButton() {
    var submit = document.getElementById('submit');
    var nopay = document.getElementById('nopay');
    submit.disabled = true;
    submit.innerText = 'SUBMITTING';
    nopay.disabled = true;
    nopay.innerText = 'No Vendor Payments Today';
  }
</script>
</code>```

答:
<!DOCTYPE html>

    <title>Disable button using disabled property</title>

Click the button to submit data!

        <input type="submit" value="Submit" id="btClickMe"
            onclick="disableButton(); this.disabled = true;" />
            <input type="submit" value="submit" onclick="disableButton(); this.disabled=true;" >

```

Body:
when having two submit buttons named submit and nopay, only one is working at a time. I need to disable both buttons after clicking and submitting the form.

<form enctype="multipart/form-data" method="post" action="
    <?php echo base_url();?>user/Purchases_ctrl/create_vendor_payment" onsubmit='disableButton()'>

    <button type="submit" name="submit" value="submit" id="submit" class="btn btn-outline-custom w-30 btn-sm submit-btn mr-3">Submit</button>
    <button type="submit" id="nopay" name="nopay" value="nopay" class="btn btn-outline-custom w-30 btn-sm submit-btn">No Vendor Payments Today</button>

</form>

Body:
<!DOCTYPE html>
<html>
<head>
    <title>Disable button using disabled property</title>
</head>
<body>
    <p>Click the button to submit data!</p>
    <p>
        <input type="submit" value="Submit" id="btClickMe"
            onclick="disableButton(); this.disabled = true;" />
            <input type="submit" value="submit" onclick="disableButton(); this.disabled=true;" >
    </p>
    <p id="msg"></p>
</body>
<script>
    function disableButton() {
        var msg = document.getElementById('msg');
        var inputs = document.getElementsByTagName("INPUT");
            for (var i = 0; i < inputs.length; i++) {
                if (inputs[i].type == "submit") {
                    inputs[i].disabled = true;
                }
            }
        msg.innerHTML = 'Data submitted and the button disabled &#9786;';
    }
</script>
</html>


问:
$(this).find("a").attr("onclick"); onclick giving invalid character
I m creating a dynamic tab using Jquery its working fine but giving error for anchor tag onclick error is invalid character.
See the javascript:

```<code>$(document).ready(function(){

    //when page loads...
    $(".tab_content").hide(); //hide all content
    $("ol.tabs li:first").addClass("active").show();  //Activate first tab
    $(".tab_content:first").show(); // show first tab content

    //on click event
    $("ol.tabs li").click(function(){
        $("ol.tabs li").removeClass("active"); //remove any "active" class
        $(this).addClass("active"); // add "active" class to selected tabs
        $(".tab_content").hide(); // hide all tab content
        //var activeTab = $(this).find("a").attr("href"); // find href attribute value to identify the active tab + content
        var activeTab = $(this).find("a").attr("onclick"); // find href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); // fadeIn the active ID content
        alert(activeTab);
        return false;
    });

});
</code>```

And the HTML:

```<code><div>
    <div id="tab1" class="tab_content">01</div>
    <div id="tab2" class="tab_content">02</div>
    <div id="tab3" class="tab_content">03</div>
</div>
<ol class="tabs">
    <li><a onclick="#tab1">Unique benefits</a></li>
    <li><a onclick="#tab2">Insurance</a></li>
    <li><a onclick="#tab3">Business Loan</a></li>
</ol>
</code>```

If i use var activeTab = $(this).find("a").attr("href");

Its work fine.
Help out

答:
The onclick attribute is an event handler attribute is the same as what you are doing in this line of code on your script:

$("ol.tabs li").click(

See: http://reference.sitepoint.com/html/event-attributes/onclick

In other words you are assigning the handling of the click event to a script by the name of '#tab1'
The hash tag is an 'illegal' script char.

To accomplish what you want there are a few thinks you can do.
First use a data attribute.

```<code><ol class="tabs">
        <li><a data-tab-name="#tab1">Unique benefits</a></li>
        <li><a data-tab-name="#tab2">Insurance</a></li>
        <li><a data-tab-name="#tab3">Business Loan</a></li>
</ol>
</code>```

And them change your js line to:

```<code>var activeTab = $(this).find("a").attr("data-tab-name");
</code>```

On a related note I will change a few more things on your script.
Since you are attaching the event handler to the onclick event of the list item I will add the attribute to the list item as follow.

```<code><ol class="tabs">
        <li data-tab-name="#tab1"><a>Unique benefits</a></li>
        <li data-tab-name="#tab2"><a>Insurance</a></li>
        <li data-tab-name="#tab3"><a>Business Loan</a></li>
</ol>
</code>```

That allows me to cahnge the js line to this:

```<code>var activeTab = $(this).attr("data-tab-name");
</code>```

What should improve performance a bit but more important makes the code more readable.

Hope this helps.

Body:
I m creating a dynamic tab using Jquery its working fine but giving error for anchor tag onclick error is invalid character.
See the javascript:

$(document).ready(function(){

    //when page loads...
    $(".tab_content").hide(); //hide all content
    $("ol.tabs li:first").addClass("active").show();  //Activate first tab
    $(".tab_content:first").show(); // show first tab content

    //on click event
    $("ol.tabs li").click(function(){
        $("ol.tabs li").removeClass("active"); //remove any "active" class
        $(this).addClass("active"); // add "active" class to selected tabs
        $(".tab_content").hide(); // hide all tab content
        //var activeTab = $(this).find("a").attr("href"); // find href attribute value to identify the active tab + content
        var activeTab = $(this).find("a").attr("onclick"); // find href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); // fadeIn the active ID content
        alert(activeTab);
        return false;
    });

});

And the HTML:

01

02

03

Unique benefits

Insurance

Business Loan

If i use var activeTab = $(this).find("a").attr("href");

Its work fine.
Help out

Body:
The onclick attribute is an event handler attribute is the same as what you are doing in this line of code on your script:

$("ol.tabs li").click(

See: http://reference.sitepoint.com/html/event-attributes/onclick

In other words you are assigning the handling of the click event to a script by the name of '#tab1'
The hash tag is an 'illegal' script char.

To accomplish what you want there are a few thinks you can do.
First use a data attribute.

<ol class="tabs">
        <li><a data-tab-name="#tab1">Unique benefits</a></li>
        <li><a data-tab-name="#tab2">Insurance</a></li>
        <li><a data-tab-name="#tab3">Business Loan</a></li>
</ol>

And them change your js line to:

var activeTab = $(this).find("a").attr("data-tab-name");

On a related note I will change a few more things on your script.
Since you are attaching the event handler to the onclick event of the list item I will add the attribute to the list item as follow.

<ol class="tabs">
        <li data-tab-name="#tab1"><a>Unique benefits</a></li>
        <li data-tab-name="#tab2"><a>Insurance</a></li>
        <li data-tab-name="#tab3"><a>Business Loan</a></li>
</ol>

That allows me to cahnge the js line to this:

var activeTab = $(this).attr("data-tab-name");

What should improve performance a bit but more important makes the code more readable.

Hope this helps.


问:
MySQL database query INSERT and TRUNCATE
How can I solve with query:
I want to calculate out the cubic meter for the whole table in tbale1 and insert the total cubic meter in table2 with the wood type and dimension A. After the data is inserted in to table2 table1 all data need to be cleand out (delet from table).

teble1

wood
dimension A
dimension B
dimension C

poplar
2.5
0.5
0.029

poplar
2.5
0.35
0.029

table2

wood
dimension A
cubic

poplar
2.5
0.0616

答:
Guessing you want to calculate the cubic meter for each wood and dimensionA, you can do so while also inserting them into table2 with:

```<code>INSERT INTO table2
(SELECT t1.wood, t1.dimensionA, ROUND(SUM(t1.dimensionA * t1.dimensionB * t1.dimensionC),5)
FROM table1 t1
GROUP BY wood,dimensionA);
</code>```

About the second part (cleaning out the data),I dont really understand the purpose of doing so but you can do it simply by using DELETE FROM table1

small fiddle i used for testing.

Body:
Guessing you want to calculate the cubic meter for each wood and dimensionA, you can do so while also inserting them into table2 with:

INSERT INTO table2
(SELECT t1.wood, t1.dimensionA, ROUND(SUM(t1.dimensionA * t1.dimensionB * t1.dimensionC),5)
FROM table1 t1
GROUP BY wood,dimensionA);

About the second part (cleaning out the data),I dont really understand the purpose of doing so but you can do it simply by using DELETE FROM table1

small fiddle i used for testing.


问:
Is there any valid method to duplicate sockaddr?
Lets assume that I have used getaddrinfo and resolved an address successfully:

```<code>//...
s = getaddrinfo(NULL, argv[1], &hints, &result);
if (s != 0)
    return -1;

if (result != nullptr) {
    // ....
}

freeaddrinfo(result);
</code>```

in this case, result->ai_addr and result->ai_addrlen refer to a sockaddr structure and its size(which is based on its type). Now assume that we want to duplicate this sockaddr in C++. What is the best valid approach to do so? I wrote this code, but I'm not sure if it is UB-free:

```<code>auto deleter = [](void* buf) { if (buf) free(buf); };

auto buf = malloc(result->ai_addrlen);
if (buf) {
    memcpy(buf, result->ai_addr, result->ai_addrlen);
}

std::unique_ptr<sockaddr, decltype(deleter)> myptr(static_cast<sockaddr*>(buf), deleter);
</code>```

Is this a valid C++ code?

答:
Why reinvent the wheel? Use boost::asio (and use vcpkg to install it).

```<code>// create address from string
auto someaddress=boost::asio::make_address("127.0.0.1");

// make a copy
boost::asio::ip::address copy=someaddress;
</code>```

Body:
Lets assume that I have used getaddrinfo and resolved an address successfully:

//...
s = getaddrinfo(NULL, argv[1], &hints, &result);
if (s != 0)
    return -1;

if (result != nullptr) {
    // ....
}

freeaddrinfo(result);

in this case, result->ai_addr and result->ai_addrlen refer to a sockaddr structure and its size(which is based on its type). Now assume that we want to duplicate this sockaddr in C++. What is the best valid approach to do so? I wrote this code, but I'm not sure if it is UB-free:

auto deleter = [](void* buf) { if (buf) free(buf); };

auto buf = malloc(result->ai_addrlen);
if (buf) {
    memcpy(buf, result->ai_addr, result->ai_addrlen);
}

std::unique_ptr<sockaddr, decltype(deleter)> myptr(static_cast<sockaddr*>(buf), deleter);

Is this a valid C++ code?

Body:
Why reinvent the wheel? Use boost::asio (and use vcpkg to install it).

// create address from string
auto someaddress=boost::asio::make_address("127.0.0.1");

// make a copy
boost::asio::ip::address copy=someaddress;


问:
How can I remote debug a PWA that has been "added to homescreen" on Android?
I have installed a PWA on my Android device and I want to remotely debug it in Chrome on my desktop.  When I connect to my device in Chrome dev tools, all I see are the tabs open in Chrome on my Android device.  I do not see the instance of the PWA that has been installed - "added to homescreen"  Is there any way to debug the installed instance?</p>

答: I was having the same problem. Turns out that PWAs that were open before you connected remote debugger will not show up. Simply close the app and start it after connecting the debugger.</p>


Title: Issue displaying inline SVG as src attribute to <img> tag

Body:
SVG alone works, but not as inline with src attribute to  tag.

<img src='data:image/svg+xml;charset=utf-8,<svg width="19" height="19" viewBox="0 0 19 19" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0 9.14453C0 9.60156 0.175781 10.0234 0.492188 10.3398L7.91016 17.7578C8.57812 18.4258 9.66797 18.4258 10.3008 17.7578L17.4727 10.5859C18.1406 9.95312 18.1406 8.86328 17.4727 8.19531L10.0547 0.777344C9.73828 0.460938 9.31641 0.25 8.85938 0.25H1.6875C0.738281 0.25 0 1.02344 0 1.9375V9.14453ZM3.9375 2.5C4.85156 2.5 5.625 3.27344 5.625 4.1875C5.625 5.13672 4.85156 5.875 3.9375 5.875C2.98828 5.875 2.25 5.13672 2.25 4.1875C2.25 3.27344 2.98828 2.5 3.9375 2.5Z" fill="#D40026"/></svg>'/>

Body:
You have to escape all characters that can be used in a URI

In modern browsers you only need to escape the # character in SVG

That means #D40026 needs to become %23D40026

See: https://yoksel.github.io/url-encoder/

<svg width="19" height="19" viewBox="0 0 190 190" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0 91C0 96 2 100 5 103L79 178C86 184 97 184 103 178L175 106C181 100 181 89 175 82L101 8C97 5 93 3 89 3H17C7 3 0 10 0 19V91ZM39 25C49 25 56 33 56 42 56 51 49 59 39 59 30 59 23 51 23 42 23 33 30 25 39 25Z"
fill="#D40026"/>
</svg>

<img src='data:image/svg+xml;charset=utf-8,<svg width="19" height="19" viewBox="0 0 190 190" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0 91C0 96 2 100 5 103L79 178C86 184 97 184 103 178L175 106C181 100 181 89 175 82L101 8C97 5 93 3 89 3H17C7 3 0 10 0 19V91ZM39 25C49 25 56 33 56 42 56 51 49 59 39 59 30 59 23 51 23 42 23 33 30 25 39 25Z"
fill="firebrick"/></svg>'/>

<img src='data:image/svg+xml;charset=utf-8,<svg width="19" height="19" viewBox="0 0 190 190" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0 91C0 96 2 100 5 103L79 178C86 184 97 184 103 178L175 106C181 100 181 89 175 82L101 8C97 5 93 3 89 3H17C7 3 0 10 0 19V91ZM39 25C49 25 56 33 56 42 56 51 49 59 39 59 30 59 23 51 23 42 23 33 30 25 39 25Z"
fill="%23D40026"/></svg>'/>


问:
How do I add asp tags using xmldocument?
```<code><asp:TableCell>
      <asp:Localize ID="lblPlntnextOneCtrlRes" meta:resourcekey="lblPlntnextOneCtrlRes" runat="server" />
      <asp:Button ID="cmdPlntAcceptnextOneCtrlRes" meta:resourcekey="cmdPlntAcceptnextOneCtrlRes" OnClick="cmdQualAccept_Click" runat="server" Text="Accept" Visible="True" />
    </asp:TableCell>
  </asp:TableRow>
</asp:Table>
</code>```

I'd like to get that sort of output using xmldocument, but I keep getting a namespace error for asp: and meta:

currently when I produce the markup, I end up with this (but would like to make it look like the above):

```<code><TableCell>
      <Localize ID="lblPlntnextOneCtrlRes" resourcekey="lblPlntnextOneCtrlRes" runat="server" />
      <Button ID="cmdPlntAcceptnextOneCtrlRes" resourcekey="cmdPlntAcceptnextOneCtrlRes" OnClick="cmdQualAccept_Click" runat="server" Text="Accept" Visible="True" />
    </TableCell>
  </TableRow>
</Table>
</code>```

Here's some of code I'm using to create the markup:

```<code>Dim markupRoot As XmlElement = markup.DocumentElement

Dim rowElement As XmlElement = markup.CreateElement("TableRow")
Dim cellElement As XmlElement = markup.CreateElement("TableCell")
Dim contentElement As XmlElement = markup.CreateElement("Localize")
contentElement.SetAttribute("ID", "tag" & ctrlName & "DescRes")
contentElement.SetAttribute("resourcekey", "tag" & ctrlName & "DescRes")
contentElement.SetAttribute("runat", "server")

cellElement.AppendChild(contentElement)
rowElement.AppendChild(cellElement)

cellElement = markup.CreateElement("TableCell")
contentElement = markup.CreateElement("Localize")
contentElement.SetAttribute("ID", "tag" & ctrlName & "NoteRes")
contentElement.SetAttribute("resourcekey", "tag" & ctrlName & "NoteRes")
contentElement.SetAttribute("runat", "server")

cellElement.AppendChild(contentElement)
rowElement.AppendChild(cellElement)
</code>```

答:
The way I've found to set up default namespaces is the following:

Resultant xml (note: the namespaces in the root node were manually added) -

```<code><?xml version="1.0" encoding="utf-8"?>
<Root xmlns:asp="http://admin.test.com/asp" xmlns:meta="http://admin.test.com/meta" xmlns:cc1="http://admin.test.com/cc1">
<cc1:TabContainer ID="wfwContainer" runat="server" AutoPostBack="True" ActiveTabIndex="0">
    <cc1:TabPanel ID="wfwTab" runat="server" HeaderText="">
      <HeaderTemplate>
        <asp:Localize ID="tagwfwRes" meta:resourcekey="tagwfwRes" runat="server" />
      </HeaderTemplate>
      <ContentTemplate />
    </cc1:TabPanel>
  </cc1:TabContainer>
</Root>
</code>```

Code that produces the xml -

```<code>Protected Sub createMarkupForTabs()

    Dim markup As XmlDocument = New XmlDocument()
    Dim truePath As String = Server.MapPath("Test.xml")

    markup.Load(truePath)

    Dim markupRoot As XmlElement = markup.DocumentElement

    Dim tabContainerElement As XmlElement = markup.CreateElement("cc1", "TabContainer", "http://admin.test.com/cc1")
    Dim tabElement As XmlElement = markup.CreateElement("cc1", "TabPanel", "http://admin.test.com/cc1")

    Dim headTempElement As XmlElement = markup.CreateElement("HeaderTemplate")
    Dim headerContentElement As XmlElement = markup.CreateElement("asp", "Localize", "http://admin.test.com/asp")
    Dim contentTempElement As XmlElement = markup.CreateElement("ContentTemplate")

    headerContentElement.SetAttribute("ID", "tag" & mainTabName.Text & "" & "Res")
    headerContentElement.SetAttribute("resourcekey", "http://admin.test.com/meta", "tag" & mainTabName.Text & "" & "Res")
    headerContentElement.SetAttribute("runat", "server")

    headTempElement.AppendChild(headerContentElement)

    tabElement.SetAttribute("ID", mainTabName.Text & "" & "Tab")
    tabElement.SetAttribute("runat", "server")
    tabElement.SetAttribute("HeaderText", "")

    tabElement.AppendChild(headTempElement)
    tabElement.AppendChild(contentTempElement)

    tabContainerElement.SetAttribute("ID", mainTabName.Text & "Container")
    tabContainerElement.SetAttribute("runat", "server")
    tabContainerElement.SetAttribute("AutoPostBack", "True")
    tabContainerElement.SetAttribute("ActiveTabIndex", "0")

    tabContainerElement.AppendChild(tabElement)

    markupRoot.AppendChild(tabContainerElement)

    markup.Save(truePath)
End Sub
</code>```

Body:
<asp:TableCell>
      <asp:Localize ID="lblPlntnextOneCtrlRes" meta:resourcekey="lblPlntnextOneCtrlRes" runat="server" />
      <asp:Button ID="cmdPlntAcceptnextOneCtrlRes" meta:resourcekey="cmdPlntAcceptnextOneCtrlRes" OnClick="cmdQualAccept_Click" runat="server" Text="Accept" Visible="True" />
    </asp:TableCell>
  </asp:TableRow>
</asp:Table>

I'd like to get that sort of output using xmldocument, but I keep getting a namespace error for asp: and meta:

currently when I produce the markup, I end up with this (but would like to make it look like the above):

<TableCell>
      <Localize ID="lblPlntnextOneCtrlRes" resourcekey="lblPlntnextOneCtrlRes" runat="server" />
      <Button ID="cmdPlntAcceptnextOneCtrlRes" resourcekey="cmdPlntAcceptnextOneCtrlRes" OnClick="cmdQualAccept_Click" runat="server" Text="Accept" Visible="True" />
    </TableCell>
  </TableRow>

Here's some of code I'm using to create the markup:

Dim markupRoot As XmlElement = markup.DocumentElement

Dim rowElement As XmlElement = markup.CreateElement("TableRow")
Dim cellElement As XmlElement = markup.CreateElement("TableCell")
Dim contentElement As XmlElement = markup.CreateElement("Localize")
contentElement.SetAttribute("ID", "tag" & ctrlName & "DescRes")
contentElement.SetAttribute("resourcekey", "tag" & ctrlName & "DescRes")
contentElement.SetAttribute("runat", "server")

cellElement.AppendChild(contentElement)
rowElement.AppendChild(cellElement)

cellElement = markup.CreateElement("TableCell")
contentElement = markup.CreateElement("Localize")
contentElement.SetAttribute("ID", "tag" & ctrlName & "NoteRes")
contentElement.SetAttribute("resourcekey", "tag" & ctrlName & "NoteRes")
contentElement.SetAttribute("runat", "server")

cellElement.AppendChild(contentElement)
rowElement.AppendChild(cellElement)

Body:
The way I've found to set up default namespaces is the following:

Resultant xml (note: the namespaces in the root node were manually added) -

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:asp="http://admin.test.com/asp" xmlns:meta="http://admin.test.com/meta" xmlns:cc1="http://admin.test.com/cc1">
<cc1:TabContainer ID="wfwContainer" runat="server" AutoPostBack="True" ActiveTabIndex="0">
    <cc1:TabPanel ID="wfwTab" runat="server" HeaderText="">
      <HeaderTemplate>
        <asp:Localize ID="tagwfwRes" meta:resourcekey="tagwfwRes" runat="server" />
      </HeaderTemplate>
      <ContentTemplate />
    </cc1:TabPanel>
  </cc1:TabContainer>
</Root>

Code that produces the xml -

Protected Sub createMarkupForTabs()

    Dim markup As XmlDocument = New XmlDocument()
    Dim truePath As String = Server.MapPath("Test.xml")

    markup.Load(truePath)

    Dim markupRoot As XmlElement = markup.DocumentElement

    Dim tabContainerElement As XmlElement = markup.CreateElement("cc1", "TabContainer", "http://admin.test.com/cc1")
    Dim tabElement As XmlElement = markup.CreateElement("cc1", "TabPanel", "http://admin.test.com/cc1")

    Dim headTempElement As XmlElement = markup.CreateElement("HeaderTemplate")
    Dim headerContentElement As XmlElement = markup.CreateElement("asp", "Localize", "http://admin.test.com/asp")
    Dim contentTempElement As XmlElement = markup.CreateElement("ContentTemplate")

    headerContentElement.SetAttribute("ID", "tag" & mainTabName.Text & "" & "Res")
    headerContentElement.SetAttribute("resourcekey", "http://admin.test.com/meta", "tag" & mainTabName.Text & "" & "Res")
    headerContentElement.SetAttribute("runat", "server")

    headTempElement.AppendChild(headerContentElement)

    tabElement.SetAttribute("ID", mainTabName.Text & "" & "Tab")
    tabElement.SetAttribute("runat", "server")
    tabElement.SetAttribute("HeaderText", "")

    tabElement.AppendChild(headTempElement)
    tabElement.AppendChild(contentTempElement)

    tabContainerElement.SetAttribute("ID", mainTabName.Text & "Container")
    tabContainerElement.SetAttribute("runat", "server")
    tabContainerElement.SetAttribute("AutoPostBack", "True")
    tabContainerElement.SetAttribute("ActiveTabIndex", "0")

    tabContainerElement.AppendChild(tabElement)

    markupRoot.AppendChild(tabContainerElement)

    markup.Save(truePath)
End Sub


问:
temp array overwriting original array in loop
I have a temporary array so that the original array won't be overwritten in each loop. I know that's not what it is actually doing, but I have no other explanation...

```<code>e = .95
f = .95
g = .95
h = .95

for a in range(0,10):
    e = e + .01
    for b in range(0,10):
        f = f + .01
        for c in range(0,10):
            g = g + .01
            for d in range(0,10):
                h = h + .01
                adj = []
                temp2 = original
                for x in temp2:
                    print x
                    x[0] = x[0] * e
                    x[4] = x[4] * e
                    x[1] = x[1] * f
                    x[5] = x[5] * f
                    x[2] = x[2] * g
                    x[6] = x[6] * g
                    x[3] = x[3] * h
                    x[7] = x[7] * h
                    x[8] = x[8] * e
                    x[12] = x[12] * e
                    x[9] = x[9] * f
                    x[13] = x[13] * f
                    x[10] = x[10] * g
                    x[14] = x[14] * g
                    x[11] = x[11] * h
                    x[15] = x[15] * h
                    adj.append(sum(x))
</code>```

When I print x, it is increasing as if it is not a temporary variable.

答:
The temporary array is not a separate array.
I like to fix this by creating the temporary array as an empty array first and then adding the contents of the original array to it.

This can be done like this:

```<code>original = ["apple", "banana", "orange"]
tempArray = []
tempArray += original
</code>```

Now "tempArray" will have the contents of the original array but will not overwrite "original".

Body:
I have a temporary array so that the original array won't be overwritten in each loop. I know that's not what it is actually doing, but I have no other explanation...

e = .95
f = .95
g = .95
h = .95

for a in range(0,10):
    e = e + .01
    for b in range(0,10):
        f = f + .01
        for c in range(0,10):
            g = g + .01
            for d in range(0,10):
                h = h + .01
                adj = []
                temp2 = original
                for x in temp2:
                    print x
                    x[0] = x[0] * e
                    x[4] = x[4] * e
                    x[1] = x[1] * f
                    x[5] = x[5] * f
                    x[2] = x[2] * g
                    x[6] = x[6] * g
                    x[3] = x[3] * h
                    x[7] = x[7] * h
                    x[8] = x[8] * e
                    x[12] = x[12] * e
                    x[9] = x[9] * f
                    x[13] = x[13] * f
                    x[10] = x[10] * g
                    x[14] = x[14] * g
                    x[11] = x[11] * h
                    x[15] = x[15] * h
                    adj.append(sum(x))

When I print x, it is increasing as if it is not a temporary variable.

Body:
The temporary array is not a separate array.
I like to fix this by creating the temporary array as an empty array first and then adding the contents of the original array to it.

This can be done like this:

original = ["apple", "banana", "orange"]
tempArray = []
tempArray += original

Now "tempArray" will have the contents of the original array but will not overwrite "original".


问:
Highchart react - x axis draggable
Is there a way to make x axis interactively draggable from left to right or vice versa? For ex, Percent x axis can be draggable from left to right or right to left

答:
First of all, you need to create or find some element that will be used as a hook. Next, use mousemove to translate the axis and do a cleanup in mouseup event callback. For example:

```<code>const chart = Highcharts.chart('container', {...});

chart.customLine = chart.renderer.path([
        'M',
        chart.plotLeft,
        chart.plotTop,
        'L',
        chart.plotLeft,
        chart.plotTop + chart.plotHeight
    ]).attr({
        stroke: '#ff00ff',
        'stroke-width': 7
    })
    .on('mousedown', function() {
        chart.isDraggingAxis = true;
    })
    .add();

chart.container.addEventListener('mousemove', function(e) {
    if (chart.isDraggingAxis) {
        const yAxis = chart.yAxis[0];

        chart.customLine.translate(e.x - chart.plotLeft);
        yAxis.labelGroup.translate(e.x - chart.plotLeft);
    }
});

document.addEventListener('mouseup', function(e) {
    if (chart.isDraggingAxis) {
        chart.isDraggingAxis = false;
    }
});
</code>```

Live demo: http://jsfiddle.net/BlackLabel/jervfkoc/

API Reference: https://api.highcharts.com/class-reference/Highcharts.SVGElement#translate

Title: Highchart react - x axis draggable

Body:
First of all, you need to create or find some element that will be used as a hook. Next, use mousemove to translate the axis and do a cleanup in mouseup event callback. For example:

const chart = Highcharts.chart('container', {...});

chart.customLine = chart.renderer.path([
        'M',
        chart.plotLeft,
        chart.plotTop,
        'L',
        chart.plotLeft,
        chart.plotTop + chart.plotHeight
    ]).attr({
        stroke: '#ff00ff',
        'stroke-width': 7
    })
    .on('mousedown', function() {
        chart.isDraggingAxis = true;
    })
    .add();

chart.container.addEventListener('mousemove', function(e) {
    if (chart.isDraggingAxis) {
        const yAxis = chart.yAxis[0];

        chart.customLine.translate(e.x - chart.plotLeft);
        yAxis.labelGroup.translate(e.x - chart.plotLeft);
    }
});

document.addEventListener('mouseup', function(e) {
    if (chart.isDraggingAxis) {
        chart.isDraggingAxis = false;
    }
});

Live demo: http://jsfiddle.net/BlackLabel/jervfkoc/

API Reference: https://api.highcharts.com/class-reference/Highcharts.SVGElement#translate


答:
It can be done by making the underline apply to both the .parentDiv and to its child
s, as in this example:

div.parentDiv,
div.parentDiv>div {
  text-decoration-line: underline;
}

div.div1 {
  display: inline-block;
  font-weight: bold;
}

div.div2 {
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parentDiv">
  <div class="div1">
    Good reviews
  </div>
  <div class="div2">
    (30)
  </div>
</div></code>```

Note that in some browsers the underline may not cross through the bottom of the parenthesis the way it does in your example image. If you absolutely need that, then that can't easily be achieved using regular text formatting CSS; you'd need to add extra elements (or pseudo-elements) with custom border formatting.

Title: How to underline two div's consecutively?

Body:
I've got 2
s that each gather their text from some JS that I've written.
But I want the end-result to look like in the following image. And I can't figure out how to do that.

I can consolidate them into a single  but then I have the issue of needing to apply two different weights to a single
, which also wracks my brain.

So basically I want text with 2 different font-weights to be underlined with no interruption.

I've tried the following, and a lot of googling:

div.parentDiv {
    text-decoration-line : underline;
}

Body:
It can be done by making the underline apply to both the .parentDiv and to its child <div>s, as in this example:

div.parentDiv,
div.parentDiv>div {
  text-decoration-line: underline;
}

div.div1 {
  display: inline-block;
  font-weight: bold;
}

div.div2 {
  display: inline-block;
}

<div class="parentDiv">
  <div class="div1">
    Good reviews
  </div>
  <div class="div2">
    (30)
  </div>
</div>

Note that in some browsers the underline may not cross through the bottom of the parenthesis the way it does in your example image. If you absolutely need that, then that can't easily be achieved using regular text formatting CSS; you'd need to add extra elements (or pseudo-elements) with custom border formatting.


问:
How do I remove all control characters in a string in Java?
My REST API, which is build with Spring in Java, produces an invalid JSON object, because it contains multiple breaks in a string, which lead to the problem, that the string has an unexpected end and the rest doesn't count as part of the string anymore, example:

```<code>{
   "status": "Success",
   "message": "Lorem ipsum",
   "data": {
      "correct": [
         {
            "record": "ULTRA LONG
                 XML STRING
                       WITH BREAKS",
            "code": 0,
            "errors": []
         }
      ]
   }
}
</code>```

The error arises in the data -> correct -> record string field, because it contains breaks which splits the original string.

My API endpoint serializes the above JSON like this:

```<code>@PostMapping(value="/check-records",
    consumes=MediaType.APPLICATION_JSON_VALUE,
    produces=MediaType.APPLICATION_JSON_VALUE)
public Response checkRecords(@RequestBody(required=true) Records records) {
   // Check records
   return new Response("Success", "Lorem ipsum", data);
}
</code>```

Response is a class, which automatically gets serialized into a JSON object after returning. data is a map in order to create the above JSON structure.

I couldn't find any suitable solution for my problem yet. Does anybody has an idea how I could remove all breaks, spaces or control characters before I serialize the JSON object?

I appreciate any kind of help, sheers! :)

答:
Thanks to @pringi. He suggested to use a regex to remove all control characters in Java before I serialize the JSON object.

```<code>String record = orginalRecord.replaceAll("[\\\\p{Cntrl}^\\r\\n\\t]+", "")
</code>```

You can find more informations about regex in the original question: How to remove control characters from java string?

Body:
My REST API, which is build with Spring in Java, produces an invalid JSON object, because it contains multiple breaks in a string, which lead to the problem, that the string has an unexpected end and the rest doesn't count as part of the string anymore, example:

{
   "status": "Success",
   "message": "Lorem ipsum",
   "data": {
      "correct": [
         {
            "record": "ULTRA LONG
                 XML STRING
                       WITH BREAKS",
            "code": 0,
            "errors": []
         }
      ]
   }
}

The error arises in the data -> correct -> record string field, because it contains breaks which splits the original string.

My API endpoint serializes the above JSON like this:

@PostMapping(value="/check-records",
    consumes=MediaType.APPLICATION_JSON_VALUE,
    produces=MediaType.APPLICATION_JSON_VALUE)
public Response checkRecords(@RequestBody(required=true) Records records) {
   // Check records
   return new Response("Success", "Lorem ipsum", data);
}

Response is a class, which automatically gets serialized into a JSON object after returning. data is a map in order to create the above JSON structure.

I couldn't find any suitable solution for my problem yet. Does anybody has an idea how I could remove all breaks, spaces or control characters before I serialize the JSON object?

I appreciate any kind of help, sheers! :)

Body:
Thanks to @pringi. He suggested to use a regex to remove all control characters in Java before I serialize the JSON object.

String record = orginalRecord.replaceAll("[\\\\p{Cntrl}^\\r\\n\\t]+", "")

You can find more informations about regex in the original question: How to remove control characters from java string?


问:
All possible combinations of data in a single table in alphabetical order
I'm trying to write a simple SQL query to show all possible combinations of data in a single table. Here's the table:

id
fruit

1
apple

2
orange

3
pear

4
plum

I've only got as fair as pairing all the data using CROSS JOIN: "apple,orange", "apple,pear" etc.

```<code>SELECT t1.fruit, t2.fruit
FROM fruits t1
CROSS JOIN fruits t2
WHERE t1.fruit < t2.fruit
</code>```

Instead I'm looking for all unique combinations in alphabetical order, e.g.

apple

apple,orange

apple,orange,pear

apple,orange,pear,plum

apple,pear

apple,plum

apple,orange,plum

apple,pear,plum

orange

orange,pear

orange,pear,plum

orange,plum

pear

pear,plum

plum

i.e. as long as a combination exists once, it doesn't need to appear again in a different order, e.g. with apple,orange, there is no need for orange,apple

答:
EDIT: This query doesn't give all the possible combinations.

Below query should work:

```<code>WITH RECURSIVE cte AS (
    SELECT A.id,
        CONCAT(A.fruit,',',GROUP_CONCAT(B.fruit ORDER BY B.id)) AS combinations,
        COUNT(*) AS count_of_delims
    FROM fruits A
    INNER JOIN fruits B
    ON A.id<B.id
    GROUP BY A.id,A.fruit

    UNION ALL

    SELECT id,
        SUBSTRING_INDEX(combinations,',',count_of_delims),
        count_of_delims-1
    FROM cte
    WHERE count_of_delims>0
)
SELECT combinations FROM cte ORDER BY id;
</code>```

Here is a working example in DB Fiddle.

Body:
I'm trying to write a simple SQL query to show all possible combinations of data in a single table. Here's the table:

id
fruit

1
apple

2
orange

3
pear

4
plum

I've only got as fair as pairing all the data using CROSS JOIN: "apple,orange", "apple,pear" etc.

SELECT t1.fruit, t2.fruit
FROM fruits t1
CROSS JOIN fruits t2
WHERE t1.fruit < t2.fruit

Instead I'm looking for all unique combinations in alphabetical order, e.g.

apple

apple,orange

apple,orange,pear

apple,orange,pear,plum

apple,pear

apple,plum

apple,orange,plum

apple,pear,plum

orange

orange,pear

orange,pear,plum

orange,plum

pear

pear,plum

plum

i.e. as long as a combination exists once, it doesn't need to appear again in a different order, e.g. with apple,orange, there is no need for orange,apple

Body:
EDIT: This query doesn't give all the possible combinations.

Below query should work:

WITH RECURSIVE cte AS (
    SELECT A.id,
        CONCAT(A.fruit,',',GROUP_CONCAT(B.fruit ORDER BY B.id)) AS combinations,
        COUNT(*) AS count_of_delims
    FROM fruits A
    INNER JOIN fruits B
    ON A.id<B.id
    GROUP BY A.id,A.fruit

    UNION ALL

    SELECT id,
        SUBSTRING_INDEX(combinations,',',count_of_delims),
        count_of_delims-1
    FROM cte
    WHERE count_of_delims>0
)
SELECT combinations FROM cte ORDER BY id;

Here is a working example in DB Fiddle.


问:
SQL convert String date of style d-MMM-yyyy to DATE
I'm importing a CSV file and one of the fields is a non-standard date string with entries like 7-Dec-2021

Any ideas for to convert this into a DATETIME object that I can insert into my SQL table? Standard CAST/CONVERT didn't work.

Microsoft SQL Server 2012 - 11.0.2100.60

答:
I am guessing that you are using a LOGIN where its language isn't English based, and as a result 'Dec' (and/or other months) isn't recognised as a valid month name.

You can specify your language to be used for the batch and then CONVERT:

SET LANGUAGE BRITISH;

SELECT TRY_CONVERT(date,'7-Dec-2021',106);
```


问:
Raise an Error if input is an empty list in Python function
I have got the following function which has to check if the input_list is empty.

```<code>def prepare_data(
    input_list: List[np.ndarray], data: Union[np.ndarray, Dict[str, np.ndarray]]
) -> Dict[str, np.ndarray]:
    """[summary]
    Function to dynamically preprare input data to in correct input format for ONNX InferenceSession (dict)
    Parameters
    ----------
    input_list : List[np.ndarray]
        [description]
    data : Union[np.ndarray, Dict[str, np.ndarray]]
        Data for Inferencession which can be an np.array or dictionary with multiple np.arrays

    Returns
    -------
    Dict[str, np.ndarray]
        Dynamic input_feed as dictionary
    """
    if len(input_list) == 0:
        raise IndexError("input_list is not allowed to be an empty list") # Wrong?

    if len(input_list) > 1:
        input_feed = {}
        for feed in input_list:
            input_feed[feed] = data.get(feed)
    else:
        input_feed = {input_list[0]: data}
    return input_feed
</code>```

I tried to solve it with raise IndexError, but I am not sure if that´s the best way or might not even work as expected.

The function has to stop executing if an empty list is passed. What is a good pythonic way to do this?

答:
First of all your if condition is wrong. It should be

```<code>if len(input_list) == 0:
</code>```

Secondly, error handling in python is done using try except blocks. You can do it like this:

```<code>try:
    # do something that might raise an exception
except IndexError:
    print("Exception raised")
    sys.exit() # if you want the program to end
</code>```

Note: you need to import sys first if you want to use sys.exit

Body:
I have got the following function which has to check if the input_list is empty.

def prepare_data(
    input_list: List[np.ndarray], data: Union[np.ndarray, Dict[str, np.ndarray]]
) -> Dict[str, np.ndarray]:
    """[summary]
    Function to dynamically preprare input data to in correct input format for ONNX InferenceSession (dict)
    Parameters
    ----------
    input_list : List[np.ndarray]
        [description]
    data : Union[np.ndarray, Dict[str, np.ndarray]]
        Data for Inferencession which can be an np.array or dictionary with multiple np.arrays

    Returns
    -------
    Dict[str, np.ndarray]
        Dynamic input_feed as dictionary
    """
    if len(input_list) == 0:
        raise IndexError("input_list is not allowed to be an empty list") # Wrong?

    if len(input_list) > 1:
        input_feed = {}
        for feed in input_list:
            input_feed[feed] = data.get(feed)
    else:
        input_feed = {input_list[0]: data}
    return input_feed

I tried to solve it with raise IndexError, but I am not sure if that´s the best way or might not even work as expected.

The function has to stop executing if an empty list is passed. What is a good pythonic way to do this?

Body:
First of all your if condition is wrong. It should be

if len(input_list) == 0:

Secondly, error handling in python is done using try except blocks. You can do it like this:

try:
    # do something that might raise an exception
except IndexError:
    print("Exception raised")
    sys.exit() # if you want the program to end

Note: you need to import sys first if you want to use sys.exit


问:
Configure @Autowired from application.yml
We have some beans that are conditional

```<code>@Service
@ConditionalOnProperties("${condition}")
class Foo {
 ...
}
</code>```

We want to be able to autowire those bean based on the same condition, is there a way to do something like:

```<code>@Autowired(required="${condition}")
private Foo foo;
</code>```

Is there a way to obtains such result using properties from application.yml ?

答:
You can create a Foo as bean with @ConditionalOnProperty(value = "condition", havingValue = "true") like below

```<code>@Configuration
public class BasicConfig {

    @Bean
    @ConditionalOnProperty(value = "condition", havingValue = "true")
    public Foo foo() {
        return new Foo();
    }
}
</code>```

Inject this foo bean as

```<code>    @Autowired(required = false)
    private Foo foo;
</code>```

@Autowired(required = false) is for make this field as optional.

Whenever condition satisfied, here foo will have value otherwise it will be null.

Body:
We have some beans that are conditional

@Service
@ConditionalOnProperties("${condition}")
class Foo {
 ...
}

We want to be able to autowire those bean based on the same condition, is there a way to do something like:

@Autowired(required="${condition}")
private Foo foo;

Is there a way to obtains such result using properties from application.yml ?

Body:
You can create a Foo as bean with @ConditionalOnProperty(value = "condition", havingValue = "true") like below

@Configuration
public class BasicConfig {

    @Bean
    @ConditionalOnProperty(value = "condition", havingValue = "true")
    public Foo foo() {
        return new Foo();
    }
}

Inject this foo bean as

    @Autowired(required = false)
    private Foo foo;

@Autowired(required = false) is for make this field as optional.

Whenever condition satisfied, here foo will have value otherwise it will be null.


问:
pyqt5_tools designer.exe does not exist
I have installed PyQT5 by command pip install pyqt5 pyqt5-tools. Then I want to show path for designer.exe. However I could not found that in C:\Users\User\AppData\Local\Programs\Python\Python38\Lib\site-packages\pyqt5_tools directory. These are content of that folder.

答:
I found it on path
venv\Lib\site-packages\qt5_applications\Qt\bin</p>

Title: pyqt5_tools designer.exe does not exist