问:
How to pass int,float etc. from dynamic string INSERT INTO function in SQL Server
I made a dynamic table name but table parameters want to string type all params.

I did cast all parameters but I get an error. I tried all the ways
for instance +70+ or N'70', Cast(70 int), etc  but I couldn't do it Do you have an idea for this question

```<code>CREATE PROCEDURE TEST
    @FIRMNUMBER VARCHAR(10),
    @PERIODNUMBER VARCHAR(10),
    @FCHNO VARCHAR(16),
    @DCDNO VARCHAR(16),
    @DATE VARCHAR(20),
    @CLINTREF INT,
    @SLSMNREF INT,
    @BRANCH INT,
    @GENEXP1 VARCHAR(20),
    @GENEXP2 VARCHAR(20),
    @CREDIT FLOAT
AS
    DECLARE @Sql NVARCHAR(MAX);
    DECLARE @TABLENAME NVARCHAR(40);

    SET @FIRMNUMBER = REPLACE(STR(@FIRMNUMBER, 3), SPACE(1), '0')
    SET @PERIODNUMBER = REPLACE(STR(@PERIODNUMBER, 2), SPACE(1), '0')

    SET @TABLENAME = 'LG_' + @FIRMNUMBER + '_' + @PERIODNUMBER + '_CLFICHE'

    SET @Sql = N'INSERT INTO ' + QUOTENAME(@TABLENAME) + '( FICHENO, DATE_, DOCODE, TRCODE, SPECCODE, CYPHCODE, BRANCH, DEPARTMENT, GENEXP1, GENEXP2, GENEXP3, GENEXP4, GENEXP5, GENEXP6, DEBIT, CREDIT, REPDEBIT,

REPCREDIT, CAPIBLOCK_CREATEDBY, CAPIBLOCK_CREADEDDATE, CAPIBLOCK_CREATEDHOUR, CAPIBLOCK_CREATEDMIN, CAPIBLOCK_CREATEDSEC, CAPIBLOCK_MODIFIEDBY,

CAPIBLOCK_MODIFIEDDATE, CAPIBLOCK_MODIFIEDHOUR, CAPIBLOCK_MODIFIEDMIN, CAPIBLOCK_MODIFIEDSEC, ACCOUNTED, INVOREF, CASHACCREF, CASHCENREF, PRINTCNT, CANCELLED,

CANCELLEDACC, ACCFICHEREF, GENEXCTYP, LINEEXCTYP, TEXTINC, SITEID, RECSTATUS, ORGLOGICREF, WFSTATUS, TIME, CLCARDREF, BANKACCREF, BNACCREF, BNCENTERREF, TRADINGGRP,

POSCOMMACCREF, POSCOMMCENREF, POINTCOMMACCREF, POINTCOMMCENREF, PROJECTREF, STATUS, WFLOWCRDREF, ORGLOGOID, AFFECTCOLLATRL, GRPFIRMTRANS, AFFECTRISK,

POSTERMINALNR, POSTERMINALNUM, APPROVE, APPROVEDATE, SALESMANREF, CSTRANSREF, DOCDATE, GUID, DEVIR, PRINTDATE, FOREXIM, TYPECODE, EINVOICE, HOUR_, MINUTE_, DEDUCTCODE

,ELECTDOC, NOTIFYCRDREF, GIBACCFICHEREF

)

VALUES ( '+@FCHNO+' ,'+@DATE+' , '' , 70 , '' , '' ,'+Cast(@BRANCH as int)+' , 0,'+@GENEXP1+','+@GENEXP2+', '' , '', '' ,

'', 0,'+@CREDIT +', 0,'+@CREDIT+', '+1+', '+GETDATE()+', 0, 32, 34, 0, '',0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0,

0, 1, 0, 0, '+1704971+', '+2012+', 0, 0, 0, '', 0, 0, 0,

0, 0, 0, 0, '', 0, 0 , '+1+', 0, '', 0, '','+@SLSMNREF+', 0,

'','+Cast(NEWID() as nvarchar(50))+', 0 , '', 0, '', 0, 0, 0, ''

, 0,0, 0

)'

EXEC sp_executesql @Sql

exec TEST '7','9','073','BLGNO' ,'2022-2-2',14  ,2  ,0  ,'ACIK1','ACIK2', 120.23```
```

答:
This is how you do it.

Int , Float values should be concatenated to dynamic query only after casting it as varchar. That is the problem in your query above here ('+Cast(@BRANCH as int)+'. This will not work because you are trying to concatenate a int value to varchar string.

Varchar, text, String , date or datetime values should be concatenated such that these values should be enclosed in single quotes.

To demonstrate, I took one column each of int , float and date type in my table below.

```<code>Create table temp( name varchar(200), ColumnA int, ColumnB float, ColumnC date)

declare @sql varchar(2000), @name varchar(10)='xyz', @colA int = 1, @colB float = 1.2, @colC datetime = getdate()

set @sql = 'Insert into temp (name,ColumnA, ColumnB, ColumnC) values ('''+@name+''','+cast(@colA as varchar)+','+cast(@colB as varchar)+','''+convert(varchar(10),@colC,120)+''')'
print(@sql)
exec(@sql)
</code>```

Since I printed the query string before executing it, you see the insert statement below which is getting executed using exec.

```<code>Insert into temp (name,ColumnA, ColumnB, ColumnC) values ('xyz',1,1.2,'2022-02-12')
1 rows affected
</code>```

Body:
I made a dynamic table name but table parameters want to string type all params.

I did cast all parameters but I get an error. I tried all the ways
for instance +70+ or N'70', Cast(70 int), etc  but I couldn't do it Do you have an idea for this question

CREATE PROCEDURE TEST
    @FIRMNUMBER VARCHAR(10),
    @PERIODNUMBER VARCHAR(10),
    @FCHNO VARCHAR(16),
    @DCDNO VARCHAR(16),
    @DATE VARCHAR(20),
    @CLINTREF INT,
    @SLSMNREF INT,
    @BRANCH INT,
    @GENEXP1 VARCHAR(20),
    @GENEXP2 VARCHAR(20),
    @CREDIT FLOAT
AS
    DECLARE @Sql NVARCHAR(MAX);
    DECLARE @TABLENAME NVARCHAR(40);

    SET @FIRMNUMBER = REPLACE(STR(@FIRMNUMBER, 3), SPACE(1), '0')
    SET @PERIODNUMBER = REPLACE(STR(@PERIODNUMBER, 2), SPACE(1), '0')

    SET @TABLENAME = 'LG_' + @FIRMNUMBER + '_' + @PERIODNUMBER + '_CLFICHE'

    SET @Sql = N'INSERT INTO ' + QUOTENAME(@TABLENAME) + '( FICHENO, DATE_, DOCODE, TRCODE, SPECCODE, CYPHCODE, BRANCH, DEPARTMENT, GENEXP1, GENEXP2, GENEXP3, GENEXP4, GENEXP5, GENEXP6, DEBIT, CREDIT, REPDEBIT,

REPCREDIT, CAPIBLOCK_CREATEDBY, CAPIBLOCK_CREADEDDATE, CAPIBLOCK_CREATEDHOUR, CAPIBLOCK_CREATEDMIN, CAPIBLOCK_CREATEDSEC, CAPIBLOCK_MODIFIEDBY,

CAPIBLOCK_MODIFIEDDATE, CAPIBLOCK_MODIFIEDHOUR, CAPIBLOCK_MODIFIEDMIN, CAPIBLOCK_MODIFIEDSEC, ACCOUNTED, INVOREF, CASHACCREF, CASHCENREF, PRINTCNT, CANCELLED,

CANCELLEDACC, ACCFICHEREF, GENEXCTYP, LINEEXCTYP, TEXTINC, SITEID, RECSTATUS, ORGLOGICREF, WFSTATUS, TIME, CLCARDREF, BANKACCREF, BNACCREF, BNCENTERREF, TRADINGGRP,

POSCOMMACCREF, POSCOMMCENREF, POINTCOMMACCREF, POINTCOMMCENREF, PROJECTREF, STATUS, WFLOWCRDREF, ORGLOGOID, AFFECTCOLLATRL, GRPFIRMTRANS, AFFECTRISK,

POSTERMINALNR, POSTERMINALNUM, APPROVE, APPROVEDATE, SALESMANREF, CSTRANSREF, DOCDATE, GUID, DEVIR, PRINTDATE, FOREXIM, TYPECODE, EINVOICE, HOUR_, MINUTE_, DEDUCTCODE

,ELECTDOC, NOTIFYCRDREF, GIBACCFICHEREF

)

VALUES ( '+@FCHNO+' ,'+@DATE+' , '' , 70 , '' , '' ,'+Cast(@BRANCH as int)+' , 0,'+@GENEXP1+','+@GENEXP2+', '' , '', '' ,

'', 0,'+@CREDIT +', 0,'+@CREDIT+', '+1+', '+GETDATE()+', 0, 32, 34, 0, '',0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0,

0, 1, 0, 0, '+1704971+', '+2012+', 0, 0, 0, '', 0, 0, 0,

0, 0, 0, 0, '', 0, 0 , '+1+', 0, '', 0, '','+@SLSMNREF+', 0,

'','+Cast(NEWID() as nvarchar(50))+', 0 , '', 0, '', 0, 0, 0, ''

, 0,0, 0

)'

EXEC sp_executesql @Sql

exec TEST '7','9','073','BLGNO' ,'2022-2-2',14  ,2  ,0  ,'ACIK1','ACIK2', 120.23```

Body:
This is how you do it.

Int , Float values should be concatenated to dynamic query only after casting it as varchar. That is the problem in your query above here ('+Cast(@BRANCH as int)+'. This will not work because you are trying to concatenate a int value to varchar string.

Varchar, text, String , date or datetime values should be concatenated such that these values should be enclosed in single quotes.

To demonstrate, I took one column each of int , float and date type in my table below.

Create table temp( name varchar(200), ColumnA int, ColumnB float, ColumnC date)

declare @sql varchar(2000), @name varchar(10)='xyz', @colA int = 1, @colB float = 1.2, @colC datetime = getdate()

set @sql = 'Insert into temp (name,ColumnA, ColumnB, ColumnC) values ('''+@name+''','+cast(@colA as varchar)+','+cast(@colB as varchar)+','''+convert(varchar(10),@colC,120)+''')'
print(@sql)
exec(@sql)

Since I printed the query string before executing it, you see the insert statement below which is getting executed using exec.

Insert into temp (name,ColumnA, ColumnB, ColumnC) values ('xyz',1,1.2,'2022-02-12')
1 rows affected


来源: stackexchange

问:
Interchangeable dictionary
I wish to have a dictionary that is interchangeable i.e. values are mapped with keys & keys are mapped with value so that if we know one element, the other partner can be known. In python dict, using keys, we can get values but not vice-versa. How can I achieve this?
Note: For interchangeability, there has to be a 1-1 mapping between key: value & value: key.

Example:

```<code>key = {'a':'1','b':'2','c':'3'}
So, I should be able to get 1 for key['a'] & 'a' for key['1']
</code>```

答:
One possible way to that is... you can simply updated existing dictionary as it contains all the opposite key-value pairs, as follows:

dict1 = {'a': '1','b' :'2','c': '3'}
dict2 = dict(zip(dict1.values(), dict1.keys())) # create value-key pair dictionary

dict1.update(dict2) # combining dict2 with dict1
print(dict1)
#{'a': '1', 'b': '2', 'c': '3', '1': 'a', '2': 'b', '3': 'c'}
```

However, you should be careful of to use this because there might be duplicated keys and values each others.

ContentLicense: CC BY-SA 4.0

Title: Interchangeable dictionary

Body:
I wish to have a dictionary that is interchangeable i.e. values are mapped with keys & keys are mapped with value so that if we know one element, the other partner can be known. In python dict, using keys, we can get values but not vice-versa. How can I achieve this?
Note: For interchangeability, there has to be a 1-1 mapping between key: value & value: key.

Example:

key = {'a':'1','b':'2','c':'3'}
So, I should be able to get 1 for key['a'] & 'a' for key['1']

Body:
One possible way to that is... you can simply updated existing dictionary as it contains all the opposite key-value pairs, as follows:

dict1 = {'a': '1','b' :'2','c': '3'}
dict2 = dict(zip(dict1.values(), dict1.keys())) # create value-key pair dictionary

dict1.update(dict2) # combining dict2 with dict1
print(dict1)
#{'a': '1', 'b': '2', 'c': '3', '1': 'a', '2': 'b', '3': 'c'}

However, you should be careful of to use this because there might be duplicated keys and values each others.


问:
unable to list all video files in android
I want to list all the video files in sdcard and internal storage. The problem is that it is only accessing videos that are present in the root folder and not in the internal folders.Currently I only have one video in Path: /storage/emulated/0 and all the videos that are present inside these sub folders are not available.

```<code> String path = Environment.getExternalStorageDirectory().toString();
    Log.e("TAG", "Path: " + path); => Path: /storage/emulated/0
    File directory = new File(path);
    File[] files = directory.listFiles();
    assert files != null;
    Log.e("TAG", "Size: "+ files.length);

    for (int i = 0; i < files.length; i++)
    {
        if (files[i].getName().contains(".mp4")){
            Log.e("TAG", "FileName:" + files[i].getName());
        }
    }

MediaScannerConnection.scanFile(this, new String[]{String.valueOf(getAllMedia())},
        new String[]{"video/*"},
        new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
                //Do something
                HashSet<String> videoItemHashSet = new HashSet<>();
                String[] projection = {MediaStore.Video.VideoColumns.DATA,
                        MediaStore.Video.Media.DISPLAY_NAME};
                Cursor cursor = getApplicationContext().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                        projection, null, null, null);
                try {
                    cursor.moveToFirst();
                    do {
                        videoItemHashSet.add((cursor.getString
                                (cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA))));
                    } while (cursor.moveToNext());

                    cursor.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ArrayList<String> downloadedList = new ArrayList<>(videoItemHashSet);

            }
        });
</code>```

答:
You should visit the folder recursively.

Sample: How to recursively scan directories in Android

A better way to get all the videos on the phone:

```<code>    public ArrayList<String> getAllMedia(Context context) {
        HashSet<String> videoItemHashSet = new HashSet<>();
        String[] projection = {MediaStore.Video.VideoColumns.DATA, MediaStore.Video.Media.DISPLAY_NAME};

        Uri collection;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
        } else {
            collection = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        }
        Cursor cursor = context.getContentResolver().query(collection, projection, null, null, null);
        try {

            if (cursor.getCount() > 0) {
                cursor.moveToFirst();
                do {
                    videoItemHashSet.add((cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA))));
                } while (cursor.moveToNext());
            }

            cursor.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        ArrayList<String> downloadedList = new ArrayList<>(videoItemHashSet);
        return downloadedList;
    }

</code>```

Don't forget to request the android.permission.READ_EXTERNAL_STORAGE permission.

If you cannot find the newest videos in the cursor, try refresh the MediaStore manually:

```<code>MediaScannerConnection.scanFile(
                this, new String[]{"/sdcard/DCIM/ or other folders"}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {

                    }
                });
</code>```

Doc: https://developer.android.com/training/data-storage/shared/media

Body:
I want to list all the video files in sdcard and internal storage. The problem is that it is only accessing videos that are present in the root folder and not in the internal folders.Currently I only have one video in Path: /storage/emulated/0 and all the videos that are present inside these sub folders are not available.

 String path = Environment.getExternalStorageDirectory().toString();
    Log.e("TAG", "Path: " + path); => Path: /storage/emulated/0
    File directory = new File(path);
    File[] files = directory.listFiles();
    assert files != null;
    Log.e("TAG", "Size: "+ files.length);

    for (int i = 0; i < files.length; i++)
    {
        if (files[i].getName().contains(".mp4")){
            Log.e("TAG", "FileName:" + files[i].getName());
        }
    }

MediaScannerConnection.scanFile(this, new String[]{String.valueOf(getAllMedia())},
        new String[]{"video/*"},
        new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
                //Do something
                HashSet<String> videoItemHashSet = new HashSet<>();
                String[] projection = {MediaStore.Video.VideoColumns.DATA,
                        MediaStore.Video.Media.DISPLAY_NAME};
                Cursor cursor = getApplicationContext().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                        projection, null, null, null);
                try {
                    cursor.moveToFirst();
                    do {
                        videoItemHashSet.add((cursor.getString
                                (cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA))));
                    } while (cursor.moveToNext());

                    cursor.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ArrayList<String> downloadedList = new ArrayList<>(videoItemHashSet);

            }
        });

Body:
You should visit the folder recursively.

Sample: How to recursively scan directories in Android

A better way to get all the videos on the phone:

    public ArrayList<String> getAllMedia(Context context) {
        HashSet<String> videoItemHashSet = new HashSet<>();
        String[] projection = {MediaStore.Video.VideoColumns.DATA, MediaStore.Video.Media.DISPLAY_NAME};

        Uri collection;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
        } else {
            collection = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        }
        Cursor cursor = context.getContentResolver().query(collection, projection, null, null, null);
        try {

            if (cursor.getCount() > 0) {
                cursor.moveToFirst();
                do {
                    videoItemHashSet.add((cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA))));
                } while (cursor.moveToNext());
            }

            cursor.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        ArrayList<String> downloadedList = new ArrayList<>(videoItemHashSet);
        return downloadedList;
    }

Don't forget to request the android.permission.READ_EXTERNAL_STORAGE permission.

If you cannot find the newest videos in the cursor, try refresh the MediaStore manually:

MediaScannerConnection.scanFile(
                this, new String[]{"/sdcard/DCIM/ or other folders"}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {

                    }
                });

Doc: https://developer.android.com/training/data-storage/shared/media


问:
How to select last populated cell in table column
I am learning how to use macros/vba and used the record macros function to understand how this works.  For the part "Range("A31").Activate" how do I make it select the last populated cell? Since this column changes everyday- I would like to the code copy the data from this table to another.</p>
```<code>Sub PurshToOutput()
    Range("Inputtable[[#Headers],[UPC]]").Select
    Selection.End(xlDown).Select
    Range(Selection, Selection.End(xlUp)).Select
    Range("Inputtable[UPC]").Select
    Range("A31").Activate
    Selection.Copy
    Sheets("OUTPUT").Select
    Range("Outputtable[UPC]").Select
    ActiveSheet.Paste
End Sub
</code>```

答:
The problem with your code is that it is bringing unnecessary complication in my opinion.
All you have to do is select the column header for which you need the last cell value. Go to the last cell, copy & paste it in the desired locaion.

You can try this to copy the last cell value:

```<code>Range("inputtable[[#Headers],[UPC]]").Select
   Selection.End(xlDown).Select
   Selection.Copy
</code>```

Body:
I am learning how to use macros/vba and used the record macros function to understand how this works.  For the part "Range("A31").Activate" how do I make it select the last populated cell? Since this column changes everyday- I would like to the code copy the data from this table to another.

Sub PurshToOutput()
    Range("Inputtable[[#Headers],[UPC]]").Select
    Selection.End(xlDown).Select
    Range(Selection, Selection.End(xlUp)).Select
    Range("Inputtable[UPC]").Select
    Range("A31").Activate
    Selection.Copy
    Sheets("OUTPUT").Select
    Range("Outputtable[UPC]").Select
    ActiveSheet.Paste
End Sub

Body:
The problem with your code is that it is bringing unnecessary complication in my opinion.
All you have to do is select the column header for which you need the last cell value. Go to the last cell, copy & paste it in the desired locaion.

You can try this to copy the last cell value:

Range("inputtable[[#Headers],[UPC]]").Select
   Selection.End(xlDown).Select
   Selection.Copy


问:
Qt slot still receives signals after disconnecting
I have such problem. In my threaded application I need to disconnect slot and reconnect signal to another slot. Unfortunately if new signals send before disconnecting it will be handled in the old slot. Such behaviour is not described in Qt documentation and looks like a bug. So here example code how to reproduce this.

void Tester::start()
{
    connect(this, &Tester::signal, this, &Tester::slot, Qt::ConnectionType::QueuedConnection);

    QTimer::singleShot(0, this, [=]() {
        emit signal();
        emit signal();
    });

    QTimer::singleShot(1000, this, [=]() {
        emit signal();
    });

    QTimer::singleShot(2000, qApp, &QCoreApplication::quit);
}

void Tester::slot()
{
    qDebug() << "Invoke slot";
    disconnect(this, &Tester::signal, this, &Tester::slot);
    connect(this, &Tester::signal, this, &Tester::slot2);
}

void Tester::slot2()
{
    qDebug() << "Invoke slot2";
}
```
<p>Output:</p>
```Invoke slot
Invoke slot
Invoke slot2
Invoke slot2
```
<p>I expect</p>
```Invoke slot
Invoke slot2
Invoke slot2
```

So there is a way to fix this in global sense? Or I can only to handle this in each particular case?

答: By setting the connection as a queued connection, you’ve deferred the invitation of the slot until later. By the time slot runs for the first time, you’ve already called the second emit, queueing a second call to slot. If you want your first timer callback to wait until the slot invocation is complete before returning from the emit (thereby doing it on the subsequent state of the signal), don’t use a queued connection.

Body:
I have such problem. In my threaded application I need to disconnect slot and reconnect signal to another slot. Unfortunately if new signals send before disconnecting it will be handled in the old slot. Such behaviour is not described in Qt documentation and looks like a bug. So here example code how to reproduce this.

void Tester::start()
{
    connect(this, &Tester::signal, this, &Tester::slot, Qt::ConnectionType::QueuedConnection);

    QTimer::singleShot(0, this, [=]() {
        emit signal();
        emit signal();
    });

    QTimer::singleShot(1000, this, [=]() {
        emit signal();
    });

    QTimer::singleShot(2000, qApp, &QCoreApplication::quit);
}

void Tester::slot()
{
    qDebug() << "Invoke slot";
    disconnect(this, &Tester::signal, this, &Tester::slot);
    connect(this, &Tester::signal, this, &Tester::slot2);
}

void Tester::slot2()
{
    qDebug() << "Invoke slot2";
}

Output:

Invoke slot
Invoke slot
Invoke slot2
Invoke slot2

I expect

Invoke slot
Invoke slot2
Invoke slot2

So there is a way to fix this in global sense? Or I can only to handle this in each particular case?


问:
JS redirect based on browser language
I'm using this test code:

```<code><script type="type/javascript">

$( document ).ready(function(){
    var userLang = navigator.language || navigator.userLanguage;
    if (userLang == "fr") {
        window.location.href = "www.facebook.com"
    }
    else if(userLang == "de"){
       window.location.href = "www.facebook.com"
    }
    else {
        window.location.href = "www.google.com"
    }
});
</script>
</code>```

But nothing happens. I must be dumb?

You can see it here:
URL removed

答:
```<code>// Better code in terms of lines of code and avoiding if conditions.

const sites = {
'fr': 'https://www.facebook.com',
'de': 'https://www.google.com',
};

const userLang = navigator.language || navigator.userLanguage;
window.location.href = sites[userLang];
</code>```

Title: JS redirect based on browser language

Body:
I'm using this test code:

But nothing happens. I must be dumb?

You can see it here:
URL removed


问:
Running feval() on a complex matrix
I am following Varodom Toochinda (a.k.a Dew)'s tutorial here. But I want to vectorize this piece of code:

f = linspace(0.01, 1, 1000); // frequency vector (Hz)
w = 2 * %pi * f;  // convert to rad/s
Pmag = zeros(1, 1000); Pph = zeros(1, 1000);
for k=1:1000, // compute P(jw) at each frequency point
  P = 1 / (-10 * w(k)^2 + 0.1 * %i * w(k));
  [Pmag(k), Pph(k)] = polar(P);
end
```
<p>to</p>
<pre class="lang-matlab prettyprint-override"><code>f = linspace(0.01, 1, 1000); // frequency vector (Hz)
w = 2 * %pi * f;  // convert to rad/s
P = 1 ./ (-10 * w.^2 + 0.1 * %i * w);
[Pmag, Pph_rad] = feval(P, polar);
</code>```

but I get the

feval: Wrong number of output argument(s): 1 expected.

error. and if I try just the feval(P, polar) command, I get the

feval: Wrong type for input argument #1 : A real matrix expected.

error message. I would appreciate it if you could help me know what is the problem and how I can resolve it.

答:
As (quite poorly but anyway) documented in the feval() help page :

f is an [external] (function or routine) accepting on one or two arguments which are supposed to be real.

Accepted synopses are
z = feval(x,y,f) and z = feval(x,f)
that support only one output argument. So,[Pmag, Pph_rad] = feval(P, polar); can't be a legal call.

For your user case, since polar works only in a matricial way that is not the required one, just avoid it:

```<code>P = 1 ./ (-10 * w.^2 + 0.1 * %i * w);
[Pmag, Pph] = (abs(P), atan(imag(P),real(P)));
</code>```

About polar evolutions, do not hesitate to comment the reports #13486 and #16806.

Title: Running feval() on a complex matrix

Body:
I am following Varodom Toochinda (a.k.a Dew)'s tutorial here. But I want to vectorize this piece of code:

f = linspace(0.01, 1, 1000); // frequency vector (Hz)
w = 2 * %pi * f;  // convert to rad/s
Pmag = zeros(1, 1000); Pph = zeros(1, 1000);
for k=1:1000, // compute P(jw) at each frequency point
  P = 1 / (-10 * w(k)^2 + 0.1 * %i * w(k));
  [Pmag(k), Pph(k)] = polar(P);
end

to

f = linspace(0.01, 1, 1000); // frequency vector (Hz)
w = 2 * %pi * f;  // convert to rad/s
P = 1 ./ (-10 * w.^2 + 0.1 * %i * w);
[Pmag, Pph_rad] = feval(P, polar);

but I get the

feval: Wrong number of output argument(s): 1 expected.

error. and if I try just the feval(P, polar) command, I get the

feval: Wrong type for input argument #1 : A real matrix expected.

error message. I would appreciate it if you could help me know what is the problem and how I can resolve it.

Body:
As (quite poorly but anyway) documented in the feval() help page :

f is an [external] (function or routine) accepting on one or two arguments which are supposed to be real.

Accepted synopses are
z = feval(x,y,f) and z = feval(x,f)
that support only one output argument. So,[Pmag, Pph_rad] = feval(P, polar); can't be a legal call.

For your user case, since polar works only in a matricial way that is not the required one, just avoid it:

P = 1 ./ (-10 * w.^2 + 0.1 * %i * w);
[Pmag, Pph] = (abs(P), atan(imag(P),real(P)));

About polar evolutions, do not hesitate to comment the reports #13486 and #16806.


问:
How to get sha1 using cmd?
I tried a Lot of possibilities and I can't find the sha1 in my computer.
I tried this:</p>
```<code>java.lang.Exception: Keystore file does not exist: ~/.android/debug.keystore/mystore.keystore
        at java.base/sun.security.tools.keytool.Main.doCommands(Main.java:915)
        at java.base/sun.security.tools.keytool.Main.run(Main.java:415)
        at java.base/sun.security.tools.keytool.Main.main(Main.java:408)

 /c/Program Files/Java/jdk-17.0.2/bin

  keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore -alias androiddebugkey -
  storepass android -keypass android
</code>```

答:
After too many possibilities explored, I came to find a solution.

Go to vs code,

Then cd android

After that **.\gradlew** signingRepor

You will find the sha1 code.

Title: How to get sha1 using cmd?

Body:
I tried a Lot of possibilities and I can't find the sha1 in my computer.
I tried this:

java.lang.Exception: Keystore file does not exist: ~/.android/debug.keystore/mystore.keystore
        at java.base/sun.security.tools.keytool.Main.doCommands(Main.java:915)
        at java.base/sun.security.tools.keytool.Main.run(Main.java:415)
        at java.base/sun.security.tools.keytool.Main.main(Main.java:408)

 /c/Program Files/Java/jdk-17.0.2/bin

  keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore -alias androiddebugkey -
  storepass android -keypass android


问:
Detecting application becoming going to the background and coming back to the foreground
I have a macOS app that needs to do some cleanups when the app looses focus (goes to the background), and some reloading of stuff when the it gains focus again (the app is now back in the foreground).

I have tried this code, both on the views and on the main app scene:

```<code>struct ContentView: View {
    @Environment(\.scenePhase) var scenePhase

    var body: some View {
        Text("Hello, world!")
            .padding()
            .onChange(of: scenePhase) { newPhase in
                if newPhase == .active {
                    print("Active")
                } else if newPhase == .inactive {
                    print("Inactive")
                } else if newPhase == .background {
                    print("Background")
                }
            }
    }
}
</code>```

But I only receive an active state. Nothing else.
I have also tried:

```<code>.onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { (_) in
          print("UIApplication: active")
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { (_) in
          print("UIApplication: background")
}
</code>```

But I can't get it to work.

How can I detect when the application goes to the background, and then the user brings it back to the front to work on it?

EDIT:

I created an appdelegate and it triggers, but only sometimes

```<code>class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidBecomeActive(_ aNotification: Notification) {
        print(">> app coming back, reloading data...")
    }

}
</code>```

答:
The original code I wrote worked:

```<code>.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification))
</code>```

Added this as to the view:

```<code>struct ContentView: View {

        var body: some View {
            Text("Hello, world!")
                .padding()
                .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) {
                     print("coming back!")
                 }
    }
</code>```

But I had the project being Multiplatform and it was creating some issues. I turned the project into a macOS only project and it worked.

Body:
I have a macOS app that needs to do some cleanups when the app looses focus (goes to the background), and some reloading of stuff when the it gains focus again (the app is now back in the foreground).

I have tried this code, both on the views and on the main app scene:

struct ContentView: View {
    @Environment(\.scenePhase) var scenePhase

    var body: some View {
        Text("Hello, world!")
            .padding()
            .onChange(of: scenePhase) { newPhase in
                if newPhase == .active {
                    print("Active")
                } else if newPhase == .inactive {
                    print("Inactive")
                } else if newPhase == .background {
                    print("Background")
                }
            }
    }
}

But I only receive an active state. Nothing else.
I have also tried:

.onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { (_) in
          print("UIApplication: active")
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { (_) in
          print("UIApplication: background")
}

But I can't get it to work.

How can I detect when the application goes to the background, and then the user brings it back to the front to work on it?

EDIT:

I created an appdelegate and it triggers, but only sometimes

class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidBecomeActive(_ aNotification: Notification) {
        print(">> app coming back, reloading data...")
    }

}

Body:
The original code I wrote worked:

.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification))

Added this as to the view:

struct ContentView: View {

        var body: some View {
            Text("Hello, world!")
                .padding()
                .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) {
                     print("coming back!")
                 }
    }

But I had the project being Multiplatform and it was creating some issues. I turned the project into a macOS only project and it worked.


问:
Rendering a Vue app in Shadow DOM using Custom Element
So I have a full featured (Routing etc) Vue 3 app that I need to embed on random page somewhere, but I don't want to use an iframe for various reasons so I'm looking to achieve this using Shadow DOM and Custom Element.

The way I thought it would work:

✅ Build the Vue App

✅ Publish the dist folder

✅ Create a Custom Element

✅ Create Shadow DOM in the constructor

✅ Load dist/index.html

❌ Vue App renders in Shadow DOM

... except it doesn't. Everything technically works but the Vue app doesn't render at all.

What am I missing?

My attempt: https://stackblitz.com/edit/javascript-7trm5i?devtoolsheight=33&file=index.html

Edited to add:

Same result even if I deploy the app to a service like Vercel and use it as src.

答:
You can not have multiple html, body, head tags in single document, so the html parser ignores the html, head and body tags of the Vue app.

Before:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue Cart</title>

    <link rel="modulepreload" href="https://vue-cart-ayoc0w7nv-eozzy.vercel.app/assets/vendor.ab0eb239.js">
    <link rel="stylesheet" href="https://vue-cart-ayoc0w7nv-eozzy.vercel.app/assets/index.8fd7686d.css">

```
<p>After parsing:</p>
<pre class="lang-html prettyprint-override"><code>    <meta charset="UTF-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue Cart</title>
    <script type="module" crossorigin src="https://vue-cart-ayoc0w7nv-eozzy.vercel.app/assets/index.0f5a3d92.js"></script>
    <link rel="modulepreload" href="https://vue-cart-ayoc0w7nv-eozzy.vercel.app/assets/vendor.ab0eb239.js">
    <link rel="stylesheet" href="https://vue-cart-ayoc0w7nv-eozzy.vercel.app/assets/index.8fd7686d.css">
    <div id="app"></div>
</code>```

So ultimately the html structure changes from the original one which Vue Virtual DOM can not work with.

So I don't think you can use Shadow DOM like an iframe.

Body:
You can not have multiple html, body, head tags in single document, so the html parser ignores the html, head and body tags of the Vue app.

Before:

<!DOCTYPE html>
<html lang="en" data-theme="bumblebee">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue Cart</title>
    <script type="module" crossorigin src="https://vue-cart-ayoc0w7nv-eozzy.vercel.app/assets/index.0f5a3d92.js"></script>
    <link rel="modulepreload" href="https://vue-cart-ayoc0w7nv-eozzy.vercel.app/assets/vendor.ab0eb239.js">
    <link rel="stylesheet" href="https://vue-cart-ayoc0w7nv-eozzy.vercel.app/assets/index.8fd7686d.css">
  </head>
  <body>
    <div id="app"></div>

  </body>
</html>

After parsing:

    <meta charset="UTF-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue Cart</title>
    <script type="module" crossorigin src="https://vue-cart-ayoc0w7nv-eozzy.vercel.app/assets/index.0f5a3d92.js"></script>
    <link rel="modulepreload" href="https://vue-cart-ayoc0w7nv-eozzy.vercel.app/assets/vendor.ab0eb239.js">
    <link rel="stylesheet" href="https://vue-cart-ayoc0w7nv-eozzy.vercel.app/assets/index.8fd7686d.css">
    <div id="app"></div>

So ultimately the html structure changes from the original one which Vue Virtual DOM can not work with.

So I don't think you can use Shadow DOM like an iframe.


问:
discord.py how to get the integer from a message
so I am making a bot using discord.py and I am making a coinflip function for it but I want to use

```<code>if message.content == "g! coinflip":
  await message.channel.send("<the coinflip function>")
</code>```

instead of

```<code>@bot.command()
async def coinflip():
  await message.channel.send("<the coinflip function>")
</code>```

because the prefix for it is g! and in discord I want the command to look something like this g! coinflip 10000 but obviously the user will pick the amount they want to gamble which is what makes it hard, but yeah if you can help please do

答:
If you insist on using the on_message event, one method you could try would be to use the .split() method. Then, you can check if there are enough arguments or not. After that, you can turn the last argument, which would be the number, into an integer. Though not shown here, you should check if the last argument is actually an integer first, otherwise you will receive errors. The code is shown below.

if message.content.lower() == "g! coinflip":
    con = message.content.lower().split(" ")
    # returned con example: ["g!", "coinflip", "3"]
    if len(con) < 3:
        await message.channel.send("Not enough arguments! Please give a number") # send the necessary feedback
        return # end this function
    elif len(con) > 3:
        await message.channel.send("Too many arguments! Please only give a number")
        return

    num = int(con[-1]) # turn the last number into an integer
    # then use this number for the rest of your function
```

Body:
so I am making a bot using discord.py and I am making a coinflip function for it but I want to use

if message.content == "g! coinflip":
  await message.channel.send("<the coinflip function>")

instead of

@bot.command()
async def coinflip():
  await message.channel.send("<the coinflip function>")

because the prefix for it is g! and in discord I want the command to look something like this g! coinflip 10000 but obviously the user will pick the amount they want to gamble which is what makes it hard, but yeah if you can help please do


问:
Reusing passwords from ~/.couchapp.conf for different applications' .couchapprc
The manual at http://couchapp.org/page/couchapp-config says that you can store passwords in ~/.couchapp.conf. However, the db url is acutally the url to the specific database. If there are two applications in different databases, say /db1 and /db2, then we'd have to have this:

```<code>{
  "env" : {
    "default" : {
      "db" : "http://admin:pass@localhost:5984/db1"
    }
  }
}
</code>```

and:

```<code>{
  "env" : {
    "default" : {
      "db" : "http://admin:pass@localhost:5984/db2"
    }
  }
}
</code>```

but I don't see how this can be merged into one (unless instead of default a hack is used to add one "environment" per DB, e.g. default-db1 and default-db2 and such).

How can I combine this into one, so e.g. I specify db1 and db2 within .couchapprc files in respective applications or something similar?

答:
I can't test it right now, but I think you should simply merge the two environments giving them different names (e.g. "env1", and "env2"):

```<code>{
  "env" : {
    "env1" : {
      "db" : "http://admin:pass@localhost:5984/db1"
    },
    "env2" : {
      "db" : "http://admin:pass@localhost:5984/db2"
    }
  }
}
</code>```

Then pass the environment as the last command line argument: couchapp push env1.

However I think the easiest solution is to put the info in .couchapprc in the root of the project, then add it to .gitignore, .htignore, or whatever you use for version control.

ContentLicense: CC BY-SA 3.0

Body:
The manual at http://couchapp.org/page/couchapp-config says that you can store passwords in ~/.couchapp.conf. However, the db url is acutally the url to the specific database. If there are two applications in different databases, say /db1 and /db2, then we'd have to have this:

{
  "env" : {
    "default" : {
      "db" : "http://admin:pass@localhost:5984/db1"
    }
  }
}

and:

{
  "env" : {
    "default" : {
      "db" : "http://admin:pass@localhost:5984/db2"
    }
  }
}

but I don't see how this can be merged into one (unless instead of default a hack is used to add one "environment" per DB, e.g. default-db1 and default-db2 and such).

How can I combine this into one, so e.g. I specify db1 and db2 within .couchapprc files in respective applications or something similar?

Body:
I can't test it right now, but I think you should simply merge the two environments giving them different names (e.g. "env1", and "env2"):

{
  "env" : {
    "env1" : {
      "db" : "http://admin:pass@localhost:5984/db1"
    },
    "env2" : {
      "db" : "http://admin:pass@localhost:5984/db2"
    }
  }
}

Then pass the environment as the last command line argument: couchapp push env1.

However I think the easiest solution is to put the info in .couchapprc in the root of the project, then add it to .gitignore, .htignore, or whatever you use for version control.


问:
vscode jumps to a specific volume afer reopen in container
I have a nice project with a .devcontainer config. Since the vscode update to 1.63 I have some trouble with the docker setup. Now I'm using the newest 1.64.0

I just want to build a new container with a clean volume an start in a fresh environment.

What happens is, that a new container is starting and I see some stuff from another container.
Same if I clone a git repo into a container volume.

Why are some containers connected with the same volume for the workspace?

Why do I fall back every time to the same volume?

In the devcontainer.json I set:

```<code>"workspaceFolder": "/workspace",
"workspaceMount": "source=remote-workspace,target=/workspace,type=volume",
</code>```

答:
To build a new devcontainer in a fresh environment you can install devcotainer cli and trigger build manually.

I'm used to mount workspace as bind mount (on windows with wsl2 files) insted of volume mount, i think that the main issue is the volume name: if both project has "source=remote-workspace" the volume will be detected as the same.

With nodejs where I want to keep node_modules folder inside container, I have done a double mount following this official vscode guide for this usecase.

So I have left workspaceMount as a default bindmount than I have added a volue that override a specific folder.

{
  "mounts": [
    //      vvvvvvvvvvv name must be unique
    "source=projectname-node_modules,target=${containerWorkspaceFolder}/node_modules,type=volume"
  ]
}
```

The results is:

every file / is server by container

but all inside ${containerWorkspaceFolder} is served by bind mount

but all inside ${containerWorkspaceFolder}/node_modules is server by named volumes

Body:
I have a nice project with a .devcontainer config. Since the vscode update to 1.63 I have some trouble with the docker setup. Now I'm using the newest 1.64.0

I just want to build a new container with a clean volume an start in a fresh environment.

What happens is, that a new container is starting and I see some stuff from another container.
Same if I clone a git repo into a container volume.

Why are some containers connected with the same volume for the workspace?

Why do I fall back every time to the same volume?

In the devcontainer.json I set:

"workspaceFolder": "/workspace",
"workspaceMount": "source=remote-workspace,target=/workspace,type=volume",

Body:
To build a new devcontainer in a fresh environment you can install devcotainer cli and trigger build manually.

I'm used to mount workspace as bind mount (on windows with wsl2 files) insted of volume mount, i think that the main issue is the volume name: if both project has "source=remote-workspace" the volume will be detected as the same.

With nodejs where I want to keep node_modules folder inside container, I have done a double mount following this official vscode guide for this usecase.

So I have left workspaceMount as a default bindmount than I have added a volue that override a specific folder.

{
  "mounts": [
    //      vvvvvvvvvvv name must be unique
    "source=projectname-node_modules,target=${containerWorkspaceFolder}/node_modules,type=volume"
  ]
}

The results is:

every file / is server by container

but all inside ${containerWorkspaceFolder} is served by bind mount

but all inside ${containerWorkspaceFolder}/node_modules is server by named volumes


问:
RealityKit - how to send data from CPU to custom material shaders?
In my project, I need to send custom structured data buffer from CPU to shaders in every frame. In SceneKit this can be done using setValue(_:forKey:) or handleBinding(ofBufferNamed:frequency:handler:) on a SCNProgram object. However in RealityKit I only found one custom value property that can be used to send data, like:

```<code>customMaterial.custom.value = SIMD4<Float>(x: 0.25, y: 0.25, z: 0.25, w: 1.0)
</code>```

I know possibly I could use the material constants like roughness or specular kind of values to store more custom data but that doesn't allow other data format other than just some 4 component vectors (And this method seems dirty and confused)

How can I send more customizable data to the shader program or is it even possible to do this in the current version of RealityKit?

答:
You can create your own custom collection to store any number of values:

```<code>import Metal
import RealityKit

public extension CustomMaterial.Custom {
    struct Keeper {
        static var _computedPty: [SIMD4<Float>] = []
    }
    var collection: [SIMD4<Float>] {
        get { return Keeper._computedPty }
        set { Keeper._computedPty = newValue }
    }
}
</code>```

Swift part

```<code>var material = try! CustomMaterial(surfaceShader: shading,
                                geometryModifier: modifier,
                                   lightingModel: .lit)

material.custom.collection += [SIMD4<Float>(1.0, 0.5, 1.0, 0.0)]
material.custom.collection += [SIMD4<Float>(0.3, 0.7, 0.9, 1.0)]
material.custom.collection += [SIMD4<Float>(0.0, 0.0, 0.0, 0.4)]

print(material.custom.collection[0][1])     //  0.5
print(material.custom.collection[1][2])     //  0.9
print(material.custom.collection[2][3])     //  0.4
</code>```

Metal part

array<packed_float4, 12> customized = params.uniforms().custom_collection()[2];
```

To implement a Metal part, you need to create a buffer for sharing data between Metal shaders' methods and Swift ViewController. Read this excellent post to find out how to do that.

Body:
In my project, I need to send custom structured data buffer from CPU to shaders in every frame. In SceneKit this can be done using setValue(_:forKey:) or handleBinding(ofBufferNamed:frequency:handler:) on a SCNProgram object. However in RealityKit I only found one custom value property that can be used to send data, like:

customMaterial.custom.value = SIMD4<Float>(x: 0.25, y: 0.25, z: 0.25, w: 1.0)

I know possibly I could use the material constants like roughness or specular kind of values to store more custom data but that doesn't allow other data format other than just some 4 component vectors (And this method seems dirty and confused)

How can I send more customizable data to the shader program or is it even possible to do this in the current version of RealityKit?

Body:
You can create your own custom collection to store any number of values:

import Metal
import RealityKit

public extension CustomMaterial.Custom {
    struct Keeper {
        static var _computedPty: [SIMD4<Float>] = []
    }
    var collection: [SIMD4<Float>] {
        get { return Keeper._computedPty }
        set { Keeper._computedPty = newValue }
    }
}

Swift part

var material = try! CustomMaterial(surfaceShader: shading,
                                geometryModifier: modifier,
                                   lightingModel: .lit)

material.custom.collection += [SIMD4<Float>(1.0, 0.5, 1.0, 0.0)]
material.custom.collection += [SIMD4<Float>(0.3, 0.7, 0.9, 1.0)]
material.custom.collection += [SIMD4<Float>(0.0, 0.0, 0.0, 0.4)]

print(material.custom.collection[0][1])     //  0.5
print(material.custom.collection[1][2])     //  0.9
print(material.custom.collection[2][3])     //  0.4

Metal part

array<packed_float4, 12> customized = params.uniforms().custom_collection()[2];

To implement a Metal part, you need to create a buffer for sharing data between Metal shaders' methods and Swift ViewController. Read this excellent post to find out how to do that.


问:
Class constructor FormControl cannot be invoked without 'new'
I have a simple Angular 13 repo where @ng-stack/forms is used like

```<code>import { Component } from '@angular/core';
import { FormControl } from '@ng-stack/forms';

@Component({
  selector: 'app-root',
})
export class AppComponent {
  control = new FormControl<string>('');
}
</code>```

When I run Jest test I got an error:

```<code>> example-app-v13@13.0.0 test
> jest --no-cache

 FAIL  src/app/app.component.spec.ts
  AppComponent
    × should create the app (54 ms)

  ● AppComponent › should create the app

    TypeError: Class constructor FormControl cannot be invoked without 'new'

       7 | })
       8 | export class AppComponent {
    >  9 |   control = new FormControl<string>('');
         |             ^
      10 | }
      11 |

      at new FormControl (node_modules/projects/forms/src/lib/form-control.ts:42:5)
      at new AppComponent (src/app/app.component.ts:9:13)
      at NodeInjectorFactory.AppComponent_Factory [as factory] (ng:\AppComponent\ɵfac.js:5:10)
      at src/app/app.component.spec.ts:16:29

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        5.825 s
Ran all test suites.
</code>```

Can anyone explain where is this error coming from and how to fix it?

答:
Github link

Found something on angular-cli issues about your error, please take a look.

Body:
I have a simple Angular 13 repo where @ng-stack/forms is used like

import { Component } from '@angular/core';
import { FormControl } from '@ng-stack/forms';

@Component({
  selector: 'app-root',
})
export class AppComponent {
  control = new FormControl<string>('');
}

When I run Jest test I got an error:

> example-app-v13@13.0.0 test
> jest --no-cache

 FAIL  src/app/app.component.spec.ts
  AppComponent
    × should create the app (54 ms)

  ● AppComponent › should create the app

    TypeError: Class constructor FormControl cannot be invoked without 'new'

       7 | })
       8 | export class AppComponent {
    >  9 |   control = new FormControl<string>('');
         |             ^
      10 | }
      11 |

      at new FormControl (node_modules/projects/forms/src/lib/form-control.ts:42:5)
      at new AppComponent (src/app/app.component.ts:9:13)
      at NodeInjectorFactory.AppComponent_Factory [as factory] (ng:\AppComponent\ɵfac.js:5:10)
      at src/app/app.component.spec.ts:16:29

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        5.825 s
Ran all test suites.

Can anyone explain where is this error coming from and how to fix it?


问:
What is the proper way to spy on a method call using Jest in Angular for a single exported function from an ES6 file?
```<code>helpers.ts

export function doThing() {
// some stuff
}
</code>```
```<code>myClass.ts
___

import { doThing } from './helpers.ts'

class myClass {

function someFunction(firstArg, secondArg) {
  const thing = someThirdThing;
  doThing(firstArg, secondArg, someThirdArg);
 }
}
</code>```

What I've tried

```<code>myClass.spec.ts

import * as helpers from './helpers.ts'

describe('someFunction' () => {
 it('calls doThing with the correct parameters', () => {
  spyOn(helpers, 'doThing');
  const myClass = new MyClass();

  myClass.someFunction(first, second);

  expect(helpers.doThing).toHaveBeenCalledWith(first, second, someThirdThing);
 }
}
___

</code>```

What I end up with when I debug is that I can see that my debugger is getting into the actual method itself, which is fine because I expect jest to call the actual implementation for the spy. However I get a 'Expected: my assertation, 'calls: 0'

I've run myself pretty crazy and consider myself at least half decent at tests. But for the life of me when it comes to spying on exported functions that aren't injected through classes, I end up bewildered.

I've looked at: SpyOn individually exported ES6 functions but from my understanding it doesn't track because my example has different modules. Thank you in advance for kindness in your response.

答:
i think its better to mock the function call when testing the parent function like this:

```<code>describe('someFunction' () => {
 it('calls doThing with the correct parameters', () => {
  jest.spyOn(helpers, 'doThing').mockImplementation;
  const myClass = new MyClass();

  myClass.someFunction(first, second);

  expect(helpers.doThing).toHaveBeenCalledWith(first, second, someThirdThing);
 }
}
</code>```

you can test the "doThing" function in a seperate unit test helper.spec.ts.

PS. in a newer version of jest i need to use jest.spyOn(class, 'fucntion').mockImplementation. In an older version i was using spyOn(class, 'function').and.stub(); maybe because of jasmine types.

Body:
helpers.ts

export function doThing() {
// some stuff
}

myClass.ts
___

import { doThing } from './helpers.ts'

class myClass {

function someFunction(firstArg, secondArg) {
  const thing = someThirdThing;
  doThing(firstArg, secondArg, someThirdArg);
 }
}

What I've tried

myClass.spec.ts

import * as helpers from './helpers.ts'

describe('someFunction' () => {
 it('calls doThing with the correct parameters', () => {
  spyOn(helpers, 'doThing');
  const myClass = new MyClass();

  myClass.someFunction(first, second);

  expect(helpers.doThing).toHaveBeenCalledWith(first, second, someThirdThing);
 }
}
___

What I end up with when I debug is that I can see that my debugger is getting into the actual method itself, which is fine because I expect jest to call the actual implementation for the spy. However I get a 'Expected: my assertation, 'calls: 0'

I've run myself pretty crazy and consider myself at least half decent at tests. But for the life of me when it comes to spying on exported functions that aren't injected through classes, I end up bewildered.

I've looked at: SpyOn individually exported ES6 functions but from my understanding it doesn't track because my example has different modules. Thank you in advance for kindness in your response.

Body:
i think its better to mock the function call when testing the parent function like this:

describe('someFunction' () => {
 it('calls doThing with the correct parameters', () => {
  jest.spyOn(helpers, 'doThing').mockImplementation;
  const myClass = new MyClass();

  myClass.someFunction(first, second);

  expect(helpers.doThing).toHaveBeenCalledWith(first, second, someThirdThing);
 }
}

you can test the "doThing" function in a seperate unit test helper.spec.ts.

PS. in a newer version of jest i need to use jest.spyOn(class, 'fucntion').mockImplementation. In an older version i was using spyOn(class, 'function').and.stub(); maybe because of jasmine types.


问:
Is there a shorthand for tuple assignment in a for loop in Python?
Wondering if there is a shorter version of the following in Python 3:

```<code>a = [(1,2), (2,3), (1,4)]
for e in a:
    n1, n2 = e
    ...
</code>```

Access to all three variables e, n1, n2 within the for-loop is required.

Thought of something like the following, but it isn't working.

```<code>for n1,n2=e in a:
    ...
</code>```

The question has more of an academic character. I know it is not of a great importance.

答:
The most likely syntax would be

```<code>for (n1, n2) as e in a:
    ...
</code>```

but, alas, no, this is not legal Python. You can still do

```<code>for (n1, n2), e in zip(a, a):
    ...
</code>```

Body:
Wondering if there is a shorter version of the following in Python 3:

a = [(1,2), (2,3), (1,4)]
for e in a:
    n1, n2 = e
    ...

Access to all three variables e, n1, n2 within the for-loop is required.

Thought of something like the following, but it isn't working.

for n1,n2=e in a:
    ...

The question has more of an academic character. I know it is not of a great importance.

Body:
The most likely syntax would be

for (n1, n2) as e in a:
    ...

but, alas, no, this is not legal Python. You can still do

for (n1, n2), e in zip(a, a):
    ...


问:
Terraform AWS Provider Error: Value for unconfigurable attribute. Can't configure a value for "acl": its value will be decided automatically
Just today, whenever I run terraform apply, I see an error something like this: Can't configure a value for "lifecycle_rule": its value will be decided automatically based on the result of applying this configuration.

It was working yesterday.

Following is the command I run: terraform init && terraform apply

Following is the list of initialized provider plugins:

- Finding latest version of hashicorp/archive...
- Finding latest version of hashicorp/aws...
- Finding latest version of hashicorp/null...
- Installing hashicorp/null v3.1.0...
- Installed hashicorp/null v3.1.0 (signed by HashiCorp)
- Installing hashicorp/archive v2.2.0...
- Installed hashicorp/archive v2.2.0 (signed by HashiCorp)
- Installing hashicorp/aws v4.0.0...
- Installed hashicorp/aws v4.0.0 (signed by HashiCorp)
```
<p>Following are the errors:</p>
<pre class="lang-sh prettyprint-override"><code>Acquiring state lock. This may take a few moments...
Releasing state lock. This may take a few moments...
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 1, in resource "aws_s3_bucket" "this":
│    1: resource "aws_s3_bucket" "this" {
│
│ Can't configure a value for "lifecycle_rule": its value will be decided
│ automatically based on the result of applying this configuration.
╵
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 1, in resource "aws_s3_bucket" "this":
│    1: resource "aws_s3_bucket" "this" {
│
│ Can't configure a value for "server_side_encryption_configuration": its
│ value will be decided automatically based on the result of applying this
│ configuration.
╵
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 3, in resource "aws_s3_bucket" "this":
│    3:   acl    = "private"
│
│ Can't configure a value for "acl": its value will be decided automatically
│ based on the result of applying this configuration.
╵
ERRO[0012] 1 error occurred:
        * exit status 1
</code>```

My code is as follows:

```<code>resource "aws_s3_bucket" "this" {
  bucket = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"
  acl    = "private"

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        kms_master_key_id = data.aws_kms_key.s3.arn
        sse_algorithm     = "aws:kms"
      }
    }
  }

  lifecycle_rule {
    id      = "backups"
    enabled = true

    prefix = "backups/"

    transition {
      days          = 90
      storage_class = "GLACIER_IR"
    }

    transition {
      days          = 180
      storage_class = "DEEP_ARCHIVE"
    }

    expiration {
      days = 365
    }
  }

  tags = {
    Name        = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"
    Environment = var.environment
  }
}
</code>```

答:
For Terragrunt/Terraform users:

As others have mentioned, AWS Provider upgraded to 4.0. Breaking changes are delineated here (under the git 4.0 tag): GitHub | terraform-provider-aws | v4.0.0

Note the breaking changes to s3. I found 39 references of aws_s3_bucket on the page. The reality is some of us don't have time to address all the breaking changes for our current projects. I have found version 3.74.1 to be quite effective.

To restrict all your Terraform projects which are configured with Terragrunt, inside the root terragrunt.hcl file of your terragrunt repo, you can specify the following:

```<code>generate "versions" {
    path      = "versions_override.tf"
    if_exists = "overwrite_terragrunt"
    contents  = <<EOF
    terraform {
        required_providers {
        aws = {
            version = "= 3.74.1"
            source = "hashicorp/aws"
        }
        }
    }
EOF
}
</code>```

In effect, Terragrunt will generate a versions_override.tf terraform config file which will define the explicit version of 3.74.1.

Body:
Just today, whenever I run terraform apply, I see an error something like this: Can't configure a value for "lifecycle_rule": its value will be decided automatically based on the result of applying this configuration.

It was working yesterday.

Following is the command I run: terraform init && terraform apply

Following is the list of initialized provider plugins:

- Finding latest version of hashicorp/archive...
- Finding latest version of hashicorp/aws...
- Finding latest version of hashicorp/null...
- Installing hashicorp/null v3.1.0...
- Installed hashicorp/null v3.1.0 (signed by HashiCorp)
- Installing hashicorp/archive v2.2.0...
- Installed hashicorp/archive v2.2.0 (signed by HashiCorp)
- Installing hashicorp/aws v4.0.0...
- Installed hashicorp/aws v4.0.0 (signed by HashiCorp)

Following are the errors:

Acquiring state lock. This may take a few moments...
Releasing state lock. This may take a few moments...
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 1, in resource "aws_s3_bucket" "this":
│    1: resource "aws_s3_bucket" "this" {
│
│ Can't configure a value for "lifecycle_rule": its value will be decided
│ automatically based on the result of applying this configuration.
╵
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 1, in resource "aws_s3_bucket" "this":
│    1: resource "aws_s3_bucket" "this" {
│
│ Can't configure a value for "server_side_encryption_configuration": its
│ value will be decided automatically based on the result of applying this
│ configuration.
╵
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 3, in resource "aws_s3_bucket" "this":
│    3:   acl    = "private"
│
│ Can't configure a value for "acl": its value will be decided automatically
│ based on the result of applying this configuration.
╵
ERRO[0012] 1 error occurred:
        * exit status 1

My code is as follows:

resource "aws_s3_bucket" "this" {
  bucket = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"
  acl    = "private"

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        kms_master_key_id = data.aws_kms_key.s3.arn
        sse_algorithm     = "aws:kms"
      }
    }
  }

  lifecycle_rule {
    id      = "backups"
    enabled = true

    prefix = "backups/"

    transition {
      days          = 90
      storage_class = "GLACIER_IR"
    }

    transition {
      days          = 180
      storage_class = "DEEP_ARCHIVE"
    }

    expiration {
      days = 365
    }
  }

  tags = {
    Name        = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"
    Environment = var.environment
  }
}

Body:
For Terragrunt/Terraform users:

As others have mentioned, AWS Provider upgraded to 4.0. Breaking changes are delineated here (under the git 4.0 tag): GitHub | terraform-provider-aws | v4.0.0

Note the breaking changes to s3. I found 39 references of aws_s3_bucket on the page. The reality is some of us don't have time to address all the breaking changes for our current projects. I have found version 3.74.1 to be quite effective.

To restrict all your Terraform projects which are configured with Terragrunt, inside the root terragrunt.hcl file of your terragrunt repo, you can specify the following:

generate "versions" {
    path      = "versions_override.tf"
    if_exists = "overwrite_terragrunt"
    contents  = <<EOF
    terraform {
        required_providers {
        aws = {
            version = "= 3.74.1"
            source = "hashicorp/aws"
        }
        }
    }
EOF
}

In effect, Terragrunt will generate a versions_override.tf terraform config file which will define the explicit version of 3.74.1.


问:
How to select random option from dropdown in cypress
I am trying to choose a random option from a dropdown list.
No answers i found so far helped.
I have no issues selecting a specific option, since all values have IDs set.

This is simple/straightforward and its working:

```<code>const log = new loginPage()
            log.visit()
            log.loginEmail('test')
            log.loginPassword('test')
            log.submit()
            cy.get('#link-new-application').click()
            cy.get('#control-nationality').click()
            cy.get('#option-nationality-DZA').click()
</code>```

Any advice for random selection? I am a beginner so any help would be much appreciated.

This is HTML:

答:
Cypress comes with Lodash baked in.

Lodesh brings a lot handy utility methods, with the sample method you can get a random item from a collection.

https://docs.cypress.io/api/utilities/_#Syntax

https://lodash.com/docs#sample

cy.get('id^="option-nationality-"]')
  .then(options => {
    cy.get(Cypress._.sample(options)).click()
})
```

Body:
I am trying to choose a random option from a dropdown list.
No answers i found so far helped.
I have no issues selecting a specific option, since all values have IDs set.

This is simple/straightforward and its working:

const log = new loginPage()
            log.visit()
            log.loginEmail('test')
            log.loginPassword('test')
            log.submit()
            cy.get('#link-new-application').click()
            cy.get('#control-nationality').click()
            cy.get('#option-nationality-DZA').click()

Any advice for random selection? I am a beginner so any help would be much appreciated.

This is HTML:


问:
Perl, disable buffering input
There is a file:

```<code>:~$ cat fff
qwerty
asdf
qwerty
zxcvb
</code>```

There is a script:

```<code>:~$ cat 1.pl
#!/usr/bin/perl
print <STDIN>
</code>```

The command works as expected:

```<code>:~$ cat fff | perl -e 'system("./1.pl")'
qwerty
asdf
qwerty
zxcvb
</code>```

But this command will not work as expected: the first <STDIN> reads all the data, not a single line. How to disable buffering for <STDIN>?

```<code>:~$ cat fff | perl -e '$_ = <STDIN>; system("./1.pl")'
:~$
</code>```

答:
Use perl -ne

or while(<STDIN>){do something with $_}

You probably don't mean "buffering" (which is disabled by doing $|++) - you are incorrectly slurping all of STDIN into $_ because you forgot to wrap it in a loop.

Title: Perl, disable buffering input

Body:
There is a file:

:~$ cat fff
qwerty
asdf
qwerty
zxcvb

There is a script:

:~$ cat 1.pl
#!/usr/bin/perl
print <STDIN>

The command works as expected:

:~$ cat fff | perl -e 'system("./1.pl")'
qwerty
asdf
qwerty
zxcvb

But this command will not work as expected: the first <STDIN> reads all the data, not a single line. How to disable buffering for <STDIN>?

:~$ cat fff | perl -e '$_ = <STDIN>; system("./1.pl")'
:~$


问:
Updating the y data of plt.fill_between()
So, I'd like to set the 2 y data of a fillbetween object, equivalent to setting the (1) y data of a Line2D with some_line.set_ydata(new_y).

A naïve attempt results in this error:

```<code>AttributeError: 'PolyCollection' object has no attribute 'set_ydata'.
</code>```

Is there a way to directly access and set the data of a PolyCollection?

Below is matplotlib's Slider demo with the added parts at lines 21 & 55 to show the issue I want to solve.

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button

# The parametrized function to be plotted
def f(t, amplitude, frequency):
    return amplitude * np.sin(2 * np.pi * frequency * t)

t = np.linspace(0, 1, 1000)

# Define initial parameters
init_amplitude = 5
init_frequency = 3

# Create the figure and the line that we will manipulate
fig, ax = plt.subplots()
line, = plt.plot(t, f(t, init_amplitude, init_frequency), lw=2)

# added part
fill = plt.fill_between(t, 0, f(t, init_amplitude, init_frequency))

ax.set_xlabel('Time [s]')

# adjust the main plot to make room for the sliders
plt.subplots_adjust(left=0.25, bottom=0.25)

# Make a horizontal slider to control the frequency.
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03])
freq_slider = Slider(
    ax=axfreq,
    label='Frequency [Hz]',
    valmin=0.1,
    valmax=30,
    valinit=init_frequency,
)

# Make a vertically oriented slider to control the amplitude
axamp = plt.axes([0.1, 0.25, 0.0225, 0.63])
amp_slider = Slider(
    ax=axamp,
    label="Amplitude",
    valmin=0,
    valmax=10,
    valinit=init_amplitude,
    orientation="vertical"
)

# The function to be called anytime a slider's value changes
def update(val):
    line.set_ydata(f(t, amp_slider.val, freq_slider.val))

    # added part
    fill.set_ydata(0, f(t, amp_slider.val, freq_slider.val))

    fig.canvas.draw_idle()

# register the update function with each slider
freq_slider.on_changed(update)
amp_slider.on_changed(update)

# Create a `matplotlib.widgets.Button` to reset the sliders to initial values.
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', hovercolor='0.975')

def reset(event):
    freq_slider.reset()
    amp_slider.reset()
button.on_clicked(reset)

plt.show()
</code>```

答:
Matplotlib's fill_between does not return a Line2D object but a PolyCollection. So, we have to update the vertices of the included path, and the easiest way to calculate the new vertices is to draw an invisible dummy object and extract the vertices in the modified update function:

```<code>def update(val):
        #optional preventing autoscaling of y-axis
        ax.autoscale(False)
        #create invisible dummy object to extract the vertices
        dummy = ax.fill_between(t, 0, f(t, amp_slider.val, freq_slider.val), alpha=0)
        dp = dummy.get_paths()[0]
        dummy.remove()
        #update the vertices of the PolyCollection
        fill.set_paths([dp.vertices])

        fig.canvas.draw_idle()
</code>```

Apart from the modified update function, I have only removed the line plot because it does not add anything to your plot if you have the filled path object. MCVE code:

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button

def f(t, amplitude, frequency):
    return amplitude * np.sin(2 * np.pi * frequency * t)

t = np.linspace(0, 1, 1000)

# Define initial parameters
init_amplitude = 5
init_frequency = 3

# Create the figure and the line that we will manipulate
fig, ax = plt.subplots()

# added part
fill = plt.fill_between(t, 0, f(t, init_amplitude, init_frequency))

ax.set_xlabel('Time [s]')

# adjust the main plot to make room for the sliders
plt.subplots_adjust(left=0.25, bottom=0.25)

# Make a horizontal slider to control the frequency.
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03])
freq_slider = Slider(
    ax=axfreq,
    label='Frequency [Hz]',
    valmin=0.1,
    valmax=30,
    valinit=init_frequency,
)

# Make a vertically oriented slider to control the amplitude
axamp = plt.axes([0.1, 0.25, 0.0225, 0.63])
amp_slider = Slider(
    ax=axamp,
    label="Amplitude",
    valmin=0,
    valmax=10,
    valinit=init_amplitude,
    orientation="vertical"
)

# The function to be called anytime a slider's value changes
def update(val):
    #optional preventing autoscaling of y-axis
    ax.autoscale(False)
    #create invisible dummy object to extract the vertices
    dummy = ax.fill_between(t, 0, f(t, amp_slider.val, freq_slider.val), alpha=0)
    dp = dummy.get_paths()[0]
    dummy.remove()
    #update the vertices of the PolyCollection
    fill.set_paths([dp.vertices])

    fig.canvas.draw_idle()

# register the update function with each slider
freq_slider.on_changed(update)
amp_slider.on_changed(update)

# Create a `matplotlib.widgets.Button` to reset the sliders to initial values.
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', hovercolor='0.975')

def reset(event):
    freq_slider.reset()
    amp_slider.reset()
button.on_clicked(reset)

plt.show()
</code>```

Body:
So, I'd like to set the 2 y data of a fillbetween object, equivalent to setting the (1) y data of a Line2D with some_line.set_ydata(new_y).

A naïve attempt results in this error:

AttributeError: 'PolyCollection' object has no attribute 'set_ydata'.

Is there a way to directly access and set the data of a PolyCollection?

Below is matplotlib's Slider demo with the added parts at lines 21 & 55 to show the issue I want to solve.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button

# The parametrized function to be plotted
def f(t, amplitude, frequency):
    return amplitude * np.sin(2 * np.pi * frequency * t)

t = np.linspace(0, 1, 1000)

# Define initial parameters
init_amplitude = 5
init_frequency = 3

# Create the figure and the line that we will manipulate
fig, ax = plt.subplots()
line, = plt.plot(t, f(t, init_amplitude, init_frequency), lw=2)

# added part
fill = plt.fill_between(t, 0, f(t, init_amplitude, init_frequency))

ax.set_xlabel('Time [s]')

# adjust the main plot to make room for the sliders
plt.subplots_adjust(left=0.25, bottom=0.25)

# Make a horizontal slider to control the frequency.
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03])
freq_slider = Slider(
    ax=axfreq,
    label='Frequency [Hz]',
    valmin=0.1,
    valmax=30,
    valinit=init_frequency,
)

# Make a vertically oriented slider to control the amplitude
axamp = plt.axes([0.1, 0.25, 0.0225, 0.63])
amp_slider = Slider(
    ax=axamp,
    label="Amplitude",
    valmin=0,
    valmax=10,
    valinit=init_amplitude,
    orientation="vertical"
)

# The function to be called anytime a slider's value changes
def update(val):
    line.set_ydata(f(t, amp_slider.val, freq_slider.val))

    # added part
    fill.set_ydata(0, f(t, amp_slider.val, freq_slider.val))

    fig.canvas.draw_idle()

# register the update function with each slider
freq_slider.on_changed(update)
amp_slider.on_changed(update)

# Create a `matplotlib.widgets.Button` to reset the sliders to initial values.
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', hovercolor='0.975')

def reset(event):
    freq_slider.reset()
    amp_slider.reset()
button.on_clicked(reset)

plt.show()

Body:
Matplotlib's fill_between does not return a Line2D object but a PolyCollection. So, we have to update the vertices of the included path, and the easiest way to calculate the new vertices is to draw an invisible dummy object and extract the vertices in the modified update function:

def update(val):
        #optional preventing autoscaling of y-axis
        ax.autoscale(False)
        #create invisible dummy object to extract the vertices
        dummy = ax.fill_between(t, 0, f(t, amp_slider.val, freq_slider.val), alpha=0)
        dp = dummy.get_paths()[0]
        dummy.remove()
        #update the vertices of the PolyCollection
        fill.set_paths([dp.vertices])

        fig.canvas.draw_idle()

Apart from the modified update function, I have only removed the line plot because it does not add anything to your plot if you have the filled path object. MCVE code:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button

def f(t, amplitude, frequency):
    return amplitude * np.sin(2 * np.pi * frequency * t)

t = np.linspace(0, 1, 1000)

# Define initial parameters
init_amplitude = 5
init_frequency = 3

# Create the figure and the line that we will manipulate
fig, ax = plt.subplots()

# added part
fill = plt.fill_between(t, 0, f(t, init_amplitude, init_frequency))

ax.set_xlabel('Time [s]')

# adjust the main plot to make room for the sliders
plt.subplots_adjust(left=0.25, bottom=0.25)

# Make a horizontal slider to control the frequency.
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03])
freq_slider = Slider(
    ax=axfreq,
    label='Frequency [Hz]',
    valmin=0.1,
    valmax=30,
    valinit=init_frequency,
)

# Make a vertically oriented slider to control the amplitude
axamp = plt.axes([0.1, 0.25, 0.0225, 0.63])
amp_slider = Slider(
    ax=axamp,
    label="Amplitude",
    valmin=0,
    valmax=10,
    valinit=init_amplitude,
    orientation="vertical"
)

# The function to be called anytime a slider's value changes
def update(val):
    #optional preventing autoscaling of y-axis
    ax.autoscale(False)
    #create invisible dummy object to extract the vertices
    dummy = ax.fill_between(t, 0, f(t, amp_slider.val, freq_slider.val), alpha=0)
    dp = dummy.get_paths()[0]
    dummy.remove()
    #update the vertices of the PolyCollection
    fill.set_paths([dp.vertices])

    fig.canvas.draw_idle()

# register the update function with each slider
freq_slider.on_changed(update)
amp_slider.on_changed(update)

# Create a `matplotlib.widgets.Button` to reset the sliders to initial values.
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', hovercolor='0.975')

def reset(event):
    freq_slider.reset()
    amp_slider.reset()
button.on_clicked(reset)

plt.show()


问:
Azure Function temp file
When getting content from an endpoint in Azure Functions, I used to be able to save stuff locally and then handle that stuff before passing it to output in Azure Functions.

Now I have this setup:

1: What happens, when I call my endpoint

2: My function code

3: My call to the function

4: The contents of C:\Local\Temp AFTER the function has been called

According to my function code (2) the file C:\local\Temp\cspcustomer.parquet should exist, but when trying to read the file I obviously get an error.

Furthermore, when looking at the actual contents of C:\local\Temp in Kudu (4), the file is not really there.

My question is, where is my file, so I can continue my work?

答:
Turns out this issue will be fixed once the PowerShell workeer is updated: https://github.com/Azure/azure-functions-powershell-worker/issues/733

The PowerShell version in Azure Function is a bit behind. It will be updated to 7.2 as required by the module.

Title: Azure Function temp file


问:
Interchangeable dictionary
I wish to have a dictionary that is interchangeable i.e. values are mapped with keys & keys are mapped with value so that if we know one element, the other partner can be known. In python dict, using keys, we can get values but not vice-versa. How can I achieve this?
Note: For interchangeability, there has to be a 1-1 mapping between key: value & value: key.

Example:

```<code>key = {'a':'1','b':'2','c':'3'}
So, I should be able to get 1 for key['a'] & 'a' for key['1']
</code>```

答:
Assuming that there will be never collosion (i.e. keys and values are disjoint sets) then you can create "mirror" dict then harness collections.ChainMap as follows

```<code>import collections
key = {'a':'1','b':'2','c':'3'}
rev_key = dict(i[::-1] for i in key.items())
final = collections.ChainMap(key,rev_key)
print(final['a'])
print(final['3'])
print(final['c'])
</code>```

output

```<code>1
c
3
</code>```

WARNING: this solution assumes you want to use final only for reading. It does not support reflection of value you insert (e.g. final['d'] = '4' will NOT cause final['4'] to become 'd')

Title: Interchangeable dictionary

Body:
I wish to have a dictionary that is interchangeable i.e. values are mapped with keys & keys are mapped with value so that if we know one element, the other partner can be known. In python dict, using keys, we can get values but not vice-versa. How can I achieve this?
Note: For interchangeability, there has to be a 1-1 mapping between key: value & value: key.

Example:

key = {'a':'1','b':'2','c':'3'}
So, I should be able to get 1 for key['a'] & 'a' for key['1']

Body:
Assuming that there will be never collosion (i.e. keys and values are disjoint sets) then you can create "mirror" dict then harness collections.ChainMap as follows

import collections
key = {'a':'1','b':'2','c':'3'}
rev_key = dict(i[::-1] for i in key.items())
final = collections.ChainMap(key,rev_key)
print(final['a'])
print(final['3'])
print(final['c'])

output

1
c
3

WARNING: this solution assumes you want to use final only for reading. It does not support reflection of value you insert (e.g. final['d'] = '4' will NOT cause final['4'] to become 'd')


问:
Bundle multiple safeTransferFrom calls into single transaction
is there a chance to bundle multiple NFT transfers into single transaction so user has to confirm only once? I am trying to implement bulk NFT transfer function

```<code>    for(let i = 0; i < nftCount; i++) {
      contract.methods.safeTransferFrom(from, to, userNFT[0][i]).send({ from: account });
    }
</code>```

This works great, but user has to approve every transfer and if he tries to transfer 100 NFTs it is very annoying and expensive gas.

Are there any better ways to do that bulk transfer on single go?

答:
If you're dealing with the problem of multiple approve for NFT transfer, then I suggest you could take a glance at the setApprovalForAll.

https://docs.openzeppelin.com/contracts/4.x/api/token/erc721#IERC721-setApprovalForAll-address-bool-

The function describes that you could authorize the contract (maybe a marketplace) you trust to transfer all the NFT tokens you own on your behalf. Therefore, you don't need to do "approve" for each token.

Body:
is there a chance to bundle multiple NFT transfers into single transaction so user has to confirm only once? I am trying to implement bulk NFT transfer function

    for(let i = 0; i < nftCount; i++) {
      contract.methods.safeTransferFrom(from, to, userNFT[0][i]).send({ from: account });
    }

This works great, but user has to approve every transfer and if he tries to transfer 100 NFTs it is very annoying and expensive gas.

Are there any better ways to do that bulk transfer on single go?


问:
Next.JS links do not work after exporting static HTML
I am new to NEXT.JS and I am having some trouble deploying a static site. I have a component Nav.tsx that looks like this:

```<code>const Nav = () => {
    return (
        <nav className='nav p-3 border-bottom'>
            <Link href='/' passHref>
                <a className='pointer my-auto h2'>Blog </a>
            </Link>
            <Link href='/about' passHref>
                <a className='ms-5 pointer lead my-auto'>Who We Are</a>
            </Link>
            <Link href='/services' passHref>
                <a className='ms-5 pointer lead my-auto'>Services</a>
            </Link>
            <Link href='/contact' passHref>
                <a className='ms-5 pointer lead my-auto'>Contact</a>
            </Link>
        </nav>
    );
};
export default Nav;
</code>```

When I run my development server locally, I can use those links to navigate around my site. But when I build, using next build && next export the links do not work for navigation. All of those links (/about, /services, /contact) are files in my pages directory. Have I written something incorrect in Nav.tsx, or am I misunderstanding how NEXT works? Thank you!

答:
Update 2022-02-14

This can be solved by applying {trailingSlash: true} inside the next.config.js. See How to deal with NextJS exporting files with .html extension but in<Link> there is no .html for details.

Original answer (which does NOT work)

I encountered the same problem very recently and found out that this can be solved by moving other non-index pages such as pages/search.js into pages/search/index.js. No need for hacking via .htaccess and so on.

However, you'll need to update your relative imports so Next.js will still be able to compile, such as:

import styles from '../styles/Home.module.css';
```
<p>to</p>
<pre class="lang-js prettyprint-override"><code>import styles from '../../styles/Home.module.css';
</code>```

Body:
I am new to NEXT.JS and I am having some trouble deploying a static site. I have a component Nav.tsx that looks like this:

const Nav = () => {
    return (

            <Link href='/' passHref>
                Blog
            </Link>
            <Link href='/about' passHref>
                Who We Are
            </Link>
            <Link href='/services' passHref>
                Services
            </Link>
            <Link href='/contact' passHref>
                Contact
            </Link>

    );
};
export default Nav;

When I run my development server locally, I can use those links to navigate around my site. But when I build, using next build && next export the links do not work for navigation. All of those links (/about, /services, /contact) are files in my pages directory. Have I written something incorrect in Nav.tsx, or am I misunderstanding how NEXT works? Thank you!

Body:
Update 2022-02-14

This can be solved by applying {trailingSlash: true} inside the next.config.js. See How to deal with NextJS exporting files with .html extension but in<Link> there is no .html for details.

Original answer (which does NOT work)

I encountered the same problem very recently and found out that this can be solved by moving other non-index pages such as pages/search.js into pages/search/index.js. No need for hacking via .htaccess and so on.

However, you'll need to update your relative imports so Next.js will still be able to compile, such as:

import styles from '../styles/Home.module.css';

to

import styles from '../../styles/Home.module.css';


问:
Vaadin formlayout won't centre
I'm building a registration form in Vaadin 22 and I want the FormLayout to be in the centre of the page horizontally.

The headlingLabel centres correctly but the form is always to the left hand side of the page.
If I remove the setMaxWidth of the form the form fills the full width of the page.

package dev.onepub.ui.views.authed;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.checkbox.Checkbox;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.formlayout.FormLayout.ResponsiveStep;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.Route;

import dev.onepub.dao.DaoMember;
import dev.onepub.entity.enums.ActionEnum;
import dev.onepub.session.MemberSession;
import dev.onepub.ui.DefaultView;
import dev.onepub.ui.OnePubLayout;
import dev.onepub.ui.crud.Access;

/// Place holder for the re-registration process.

@Access(required = ActionEnum.notRequired)
@Route(value = "Register", layout = OnePubLayout.class)
public class RegistrationView extends VerticalLayout
{
    private transient Logger logger = LogManager.getLogger();

    private static final long serialVersionUID = 1L;
    public static final String NAME = "Register";
    public static final String LABEL = "register";

    TextField firstName = new TextField("First name");
    TextField lastName = new TextField("Last name");
    TextField email = new TextField("Preferred Email");
    TextField publisher = new TextField("Organisation Name");

    Checkbox subscribe = new Checkbox("Subscribe to periodic newsletters for product features, tips and tricks.");
    Checkbox terms = new Checkbox();

    Button signup = new Button("Signup");

    private Binder<Registration> binder = new Binder<>(Registration.class);

    public RegistrationView()
    {

        this.setSizeFull();
        // this.setMargin(false);

        HorizontalLayout heading = new HorizontalLayout();
        heading.setWidth("100%");
        Label headingLabel = new Label("Please confirm the following details");
        this.add(headingLabel);

        final var form = new FormLayout();
        this.add(form);
        this.setAlignItems(Alignment.CENTER);
        this.setJustifyContentMode(JustifyContentMode.START);
        form.setMaxWidth("800px");

        terms.setLabelAsHtml(
                "I agree to both the terms and conditions, and the privacy policy.");

        form.add(firstName, lastName, email, publisher, subscribe, terms, signup);
        form.setColspan(email, 2);
        form.setColspan(publisher, 2);
        form.setColspan(subscribe, 2);
        form.setColspan(terms, 2);
        form.setColspan(signup, 2);

        form.setResponsiveSteps(
                // Use one column by default
                new ResponsiveStep("0", 1),
                // Use two columns, if layout's width exceeds 500px
                new ResponsiveStep("500px", 2));

        binder.bindInstanceFields(this);

        final var member = MemberSession.getCurrent().loggedInMember;

        final var registration = new Registration(member);
        binder.setBean(registration);

        signup.addClickListener(event -> save());

    }

    private void save()
    {
        Registration registration = binder.getBean();
        final var member = new DaoMember().findByEntity(MemberSession.getCurrent().loggedInMember);
        member.setFirstname(registration.firstName);
        member.setSurname(registration.lastName);
        member.setPreferredEmail(registration.email);
        member.getPublisher().setName(registration.publisher);
        member.setAcceptedTerms(terms.getValue());
        member.setSubcribed(subscribe.getValue());

        UI.getCurrent().navigate(DefaultView.class);

    }

}
```

答:
Add this form.getStyle().set("align-self", "center");

Explanation

If you inspect the vaadin-form-layout element, you'll discover 2 things:

It automatically sets align-self to stretch which basically makes it try to fill up the available space of the parent.

max-width: 100%

You can override those Behavior by setting align-self to center and setting a width to the form using form.setWidth("WIDTH");.

Title: Vaadin formlayout won't centre


问:
Drupal 7 - Insert taxonomy into node object
I have a script which successfully creates new nodes. But I'm having trouble setting the taxonomy before saving.

I believe in Drupal 6 I would use this method.

```<code>$cat1_tid = taxonomy_get_term_by_name($data[$i]['cat1']);
$cat2_tid = taxonomy_get_term_by_name($data[$i]['cat2']);
$cat3_tid = taxonomy_get_term_by_name($data[$i]['cat3']);
$node->taxonomy = array($cat1_tid, $cat2_tid, $cat3_tid);
</code>```

I think in Drupal 7 I would do this (my field name is Catalog)

```<code>$node->taxonomy_catalog['und'][0] = array($term1Obj, $term2Obj);
</code>```

taxonomy_get_term_by_name doesn't seem to return the correct object to insert into the node object.

If anyone can shed some light, appreciated.

Thanks

EDIT

Solution:

```<code>// Taxonomy
$categories = array($data[$i]['cat1'], $data[$i]['cat2'], $data[$i]['cat3']);
foreach ($categories as $key => $category) {
  if ($term = taxonomy_get_term_by_name($category)) {
    $terms_array = array_keys($term);
    $node->taxonomy_catalog[LANGUAGE_NONE][$key]['tid'] = $terms_array['0'];
  }
}
</code>```

答:
Here you are, this code successfully add a new term to the node before the node is created.</p>

```<code>$my_term_name = 'micky';
    $term_array = taxonomy_get_term_by_name($my_term_name);
    if($term_array == array()){
        //empty term ..
        $term->name = $my_term_name;
        $term->vid = 1;
    taxonomy_term_save($term);
    $term_array = taxonomy_get_term_by_name($my_term_name);
    }
    //get the first index of the array .
    foreach ($term_array as $tid => $term_object)break;
    $node->field_tag['und'][$tid] = (array)$term_object;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a script which successfully creates new nodes. But I'm having trouble setting the taxonomy before saving.

I believe in Drupal 6 I would use this method.

$cat1_tid = taxonomy_get_term_by_name($data[$i]['cat1']);
$cat2_tid = taxonomy_get_term_by_name($data[$i]['cat2']);
$cat3_tid = taxonomy_get_term_by_name($data[$i]['cat3']);
$node->taxonomy = array($cat1_tid, $cat2_tid, $cat3_tid);

I think in Drupal 7 I would do this (my field name is Catalog)

$node->taxonomy_catalog['und'][0] = array($term1Obj, $term2Obj);

taxonomy_get_term_by_name doesn't seem to return the correct object to insert into the node object.

If anyone can shed some light, appreciated.

Thanks

EDIT

Solution:

// Taxonomy
$categories = array($data[$i]['cat1'], $data[$i]['cat2'], $data[$i]['cat3']);
foreach ($categories as $key => $category) {
  if ($term = taxonomy_get_term_by_name($category)) {
    $terms_array = array_keys($term);
    $node->taxonomy_catalog[LANGUAGE_NONE][$key]['tid'] = $terms_array['0'];
  }
}

Body:
Here you are, this code successfully add a new term to the node before the node is created.

$my_term_name = 'micky';
    $term_array = taxonomy_get_term_by_name($my_term_name);
    if($term_array == array()){
        //empty term ..
        $term->name = $my_term_name;
        $term->vid = 1;
    taxonomy_term_save($term);
    $term_array = taxonomy_get_term_by_name($my_term_name);
    }
    //get the first index of the array .
    foreach ($term_array as $tid => $term_object)break;
    $node->field_tag['und'][$tid] = (array)$term_object;


问:
Add newline after each key, value using JSON.stringify()
I want to add a newline after each key value pair in an object using JSON.stringify()

In my actual code I will be getting a lot of key value pairs and having the new lines makes it easier to read.

Example code is:

```<code>let test = {'key' : ['one', 'two', 'three'], 'keyTwo' : ['one', 'two', 'three']}

let testOne = JSON.stringify(test, null, '\t')

console.log(testOne)
</code>```

outputs:

```<code>{
        "key": [
                "one",
                "two",
                "three"
        ],
        "keyTwo": [
                "one",
                "two",
                "three"
        ]
}
</code>```

I want:

```<code>{
        "key": [
                "one",
                "two",
                "three"
        ],
                                   // <----- newline here
        "keyTwo": [
                "one",
                "two",
                "three"
        ]
}
</code>```

I have tried

```<code>let test = {'key' : ['one', 'two', 'three'] + "\\n", 'keyTwo' : ['one', 'two', 'three']+ "\\n"}

let testOne = JSON.stringify(test, null, '\t\n')
</code>```

Neither work

答:
const test = {'key' : ['one', 'two', 'three'], 'keyTwo' : ['one', 'two', 'three'], 'keyThree' : ['one', 'two', 'three']}

const testOne = JSON
    .stringify(test, null, "\t")
    .replaceAll(
        "],\n\t\"",
        "],\n\n\t\""
    );
console.log(testOne);```

Body:
I want to add a newline after each key value pair in an object using JSON.stringify()

In my actual code I will be getting a lot of key value pairs and having the new lines makes it easier to read.

Example code is:

let test = {'key' : ['one', 'two', 'three'], 'keyTwo' : ['one', 'two', 'three']}

let testOne = JSON.stringify(test, null, '\t')

console.log(testOne)

outputs:

{
        "key": [
                "one",
                "two",
                "three"
        ],
        "keyTwo": [
                "one",
                "two",
                "three"
        ]
}

I want:

{
        "key": [
                "one",
                "two",
                "three"
        ],
                                   // <----- newline here
        "keyTwo": [
                "one",
                "two",
                "three"
        ]
}

I have tried

let test = {'key' : ['one', 'two', 'three'] + "\\n", 'keyTwo' : ['one', 'two', 'three']+ "\\n"}

let testOne = JSON.stringify(test, null, '\t\n')

Neither work