Question:
Sort tbody list which is populated with Javascript getList?

I have a router with a DHCP page which is not sorted by the internal IP number, instead it is fully random. I have full access to the html and javascript, and I can modify this without any issues. However I cannot figure out how to make the list sorted by IP-address by default. I have no need to be able to manually click and sort, I just want the list to always be sorted by IP-address.

I cannot figure out if it is possible to sort a getList, or if it has to be done in the randerBandlist function.

The list html:
```
                <table class="table">
                <thead>
                    <tr>
                        <th width="30"></th>
                        <th><%:设备名称%></th>
                        <th><%:IP地址%></th>
                        <th><%:MAC地址%></th>
                        <th width="150" class="center"><%:操作%></th>
                    </tr>
                </thead>
                <tbody id="bandlist">
                    <tr>
                        <td class="center" colspan="5"><%:查询中...%></td>
                    </tr>
                </tbody>
            </table>
```

This is the part that handles the list in question:
```
getList = function( callback ){
        $.getJSON('<%=luci.dispatcher.build_url("api", "xqnetwork","macbind_info")%>',{},function(rsp){
            if ( rsp.code != 0 ) {
                return;
            }
            callback( rsp );
        });
    },
    randerBandlist = function( rsp ){
        var tpl = $( '#tplbandlist' ).html(),
            container = $( '#bandlist' ),
            bandlistdata = rsp.list,
            tpldata = [],
            mac, ip, dname;
        currentList = {};
        if ( bandlistdata.length > 0 ) {
            for (var i = 0; i < bandlistdata.length; i++) {
                mac = bandlistdata[i].mac.toUpperCase();
                ip = bandlistdata[i].ip;
                dname = StringH.encode4Html( bandlistdata[i].name );
                tpldata.push({
                    dname: dname,
                    ip: ip,
                    mac: mac
                });
                currentList[ip] = 1;
            }
        }
        container.html( tpl.tmpl( {bandlist: tpldata} ) );
    },
return {
    init: function(){
        getList( randerBandlist );
        addEvent();
    }
}
```

Also included the full function, however I think the function above is the one that needs modifying:
```
var ModelDhcpband = (function(){
var lanIP = '<%=lanip%>',
    ipprefix = (function(ip){
        var arr = ip.split('.');
        arr.pop();
        return arr.join('.') + '.';
    })(lanIP),
    currentList = {},
    // get repeat set
    getRepeat = function( data ){
        data = data || [];
        var repeat = [];
        var _currentList = $.extend( {}, currentList);
        for (var i = 0; i < data.length; i++) {
            var v = data[i];
            if ( typeof( _currentList[v] ) == 'undefined' ) {
                _currentList[v] = 1;
            } else {
                repeat.push(v);
            }
        }
        return repeat;
    },
    getList = function( callback ){
        $.getJSON('<%=luci.dispatcher.build_url("api", "xqnetwork","macbind_info")%>',{},function(rsp){
            if ( rsp.code != 0 ) {
                return;
            }
            callback( rsp );
        });
    },
    randerBandlist = function( rsp ){
        var tpl = $( '#tplbandlist' ).html(),
            container = $( '#bandlist' ),
            bandlistdata = rsp.list,
            tpldata = [],
            mac, ip, dname;
        currentList = {};
        if ( bandlistdata.length > 0 ) {
            for (var i = 0; i < bandlistdata.length; i++) {
                mac = bandlistdata[i].mac.toUpperCase();
                ip = bandlistdata[i].ip;
                dname = StringH.encode4Html( bandlistdata[i].name );
                tpldata.push({
                    dname: dname,
                    ip: ip,
                    mac: mac
                });
                currentList[ip] = 1;
            }
        }
        container.html( tpl.tmpl( {bandlist: tpldata} ) );
    },
    randerDevlist = function( rsp ){
        var tpl = $( '#tpldevlist' ).html(),
            devlistdata = rsp.devicelist,
            tpldata = [],
            randerDom,
            mac, ip, dname, tag;
        if ( devlistdata.length > 0 ) {
            for (var i = 0; i < devlistdata.length; i++) {
                mac = devlistdata[i].mac.toUpperCase();
                ip = devlistdata[i].ip;
                iplast = (function( ip ){
                    var arr = ip.split('.');
                    return arr[arr.length - 1];
                })( ip );
                dname = StringH.encode4HtmlValue( devlistdata[i].name );
                tag = devlistdata[i].tag;
                if ( tag != 2 ) {
                    tpldata.push({
                        dname: dname,
                        ip: iplast,
                        mac: mac
                    });
                }
            }
        }
        randerDom = tpl.tmpl( {
            devlist: tpldata,
            ipprefix: ipprefix
        } );
        $.dialog({
            title: '<%:绑定设备%>',
            content: randerDom,
            lock: true,
            width: 828,
            padding: '30px'
        });
        $.pub( 'done', {id: '#addlist'} );
    },
    serializeForm = function( form ){
        var ips = $( '.ip', form ),
            dnames = $( '.dname', form ),
            macs = $( '.mac', form ),
            data = [],
            item;
        ips.each(function( idx, el ){
            item = {
                ip: ipprefix + $.trim( el.value ),
                mac: $.trim( macs.eq( idx ).val() ),
                name: $.trim( dnames.eq( idx ).val() )
            };
            data.push( item );
        });

        return ObjectH.stringify( data );
    }
    unbind = function( e, mac ){
        e.preventDefault();
        var that = this,
            $this = $(that),
            requestURL = '<%=luci.dispatcher.build_url("api", "xqnetwork", "mac_unbind")%>',
            requestData = {
                mac: mac
            };
        $.pub( 'loading:start' );
        $.ajax({
            url: requestURL,
            type: 'POST',
            data: requestData,
            dataType: 'json',
            success: function( rsp ){
                if ( rsp.code !== 0 ) {
                    $.alert( rsp.msg );
                } else {
                    getList( randerBandlist );
                    $( '#dellist' ).hide();
                }
                $.pub( 'loading:stop' );
            }
        });
    },
    addEvent = function(){
        // unband
        $('body').delegate( '.btn-unband' ,'click', function( e ){
            var that = this,
                $this = $( that ),
                mac = $this.attr('data-mac'),
                ok = function(){
                    unbind.call( that, e, mac );
                };
            $.confirm( '<%:你确定要解除此项绑定？%>', ok );
        });
        // band
        $( 'body' ).delegate( '#addbandlist', 'submit', function( e ){
            e.preventDefault();
            var form = e.target,
                formName = form.name,
                formels = $( 'input', form ),
                requestURL = '<%=luci.dispatcher.build_url("api", "xqnetwork", "mac_bind")%>',
                requestData,
                rules,
                name,
                display,
                validator,
                formdata,
                iplist = [],
                formdata,
                formdataojb,
                repeatIP,
                validerules = [];

            validator = Valid.checkAll( $('#addbandlist')[0] );

            if ( validator) {
                formdata = serializeForm( form );
                formdataojb = StringH.evalExp( formdata );
                for (var i = 0; i < formdataojb.length; i++) {
                    iplist.push(formdataojb[i]['ip']);
                }
                repeatIP = getRepeat( iplist );
                if ( repeatIP.length !== 0 ) {
                    $.alert( '<%:存在IP冲突，请检查输入项%>' + repeatIP.join(' , ') );
                    return;
                }

                requestData = {
                    data: formdata
                };
                $.pub( 'wait', {id: '#submitbandlist'} );
                $.ajax({
                    url: requestURL,
                    data: requestData,
                    type: 'POST',
                    dataType: 'json',
                    success: function( rsp ){
                        if ( rsp.code == 0 ) {
                            location.reload( 1 );
                        } else {
                            $.alert( rsp.msg );
                        }
                        $.pub( 'done', {id: '#submitbandlist'} );
                    }
                });
            }

        });

        // add a item
        $( 'body' ).delegate( '#addoneitem', 'click', function( e ){
            e.preventDefault();
            var tpl = $( '#tpldevitem' ).html(),
                form = $( '#banditems' ),
                btnSubmit = $( '#submitbandlist' ),
                lastidx = (function(){
                    if ( form.find('tr').length > 0 ) {
                        return form.find('tr:last').attr( 'data-idx' );
                    }
                    return 0;
                }()),
                lastidx = parseInt( lastidx, 10 ),
                item = tpl.tmpl({
                    idx: lastidx + 1,
                    ipprefix: ipprefix
                });
            if ( !isNaN( lastidx ) ) {
                form.append( item );
                if ( form.find( 'tr' ).length > 0 ) {
                    btnSubmit.show();
                } else {
                    btnSubmit.hide();
                }
            } else {
                $.alert('<%:出现异常，请刷新页面%>');
            }
        } );

        // del a item
        $( 'body' ).delegate( '.btn-del-item', 'click', function( e ){
            e.preventDefault();
            var tar = e.target,
                tr = $( tar ).parents( 'tr' ),
                form = $( '#banditems' ),
                btnSubmit = $( '#submitbandlist' ),
                isEmpty = (function(){
                    var empty = true;
                    tr.find('input').each(function(){
                        if ( this.value !== '') {
                            empty = false;
                            return false;
                        }
                    });
                    return empty;
                }()),
                ok = function(){
                    tr.remove();
                    if ( form.find( 'tr' ).length > 0 ) {
                        btnSubmit.show();
                    } else {
                        btnSubmit.hide();
                    }
                };
            if ( isEmpty ) {
                ok();
            } else {
                $.confirm( '<%:确定要删除这项数据吗%>', ok );
            }
        } );

        // open add dlg
        $( '#addlist' ).click(function( e ){
            e.preventDefault();
            $.pub( 'wait', {id: '#addlist'} );
            getList( randerDevlist );
        });

        // check for del
        $( 'body' ).delegate( '.bandmac', 'click', function( e ){
            if ( $('.bandmac:checked').length > 0 ) {
                $( '#dellist' ).show();
            } else {
                $( '#dellist' ).hide();
            }
        } );

        // del all
        $( '#dellist' ).on( 'click', function( e ){
            e.preventDefault();
            if ( $('.bandmac:checked').length == 0 ) {
                $.alert( '<%:你还未选择任何设备%>' );
                return;
            }
            var that = this,
                $this = $(that),
                mac = (function(){
                    var tmp = [];
                    $('.bandmac:checked').each(function(){
                        tmp.push( this.value );
                    });
                    return tmp.join( ';' );
                }()),
                ok = function(){
                    unbind.call( that, e, mac );
                };

            $.confirm( '<%:确认要解除选中项目的绑定关系？%>', ok );
        } );
    };

currentList[lanIP] = 1;

return {
    init: function(){
        getList( randerBandlist );

```

Explanation: The core code for sorting the array of objects containing IP addresses before rendering the DHCP list is located in the randerBandlist function. The tpldata itself needs to be sorted before pushing objects into the tpldata array, and a related method needs to be used. It will sort by each digit of the IP address.

As far as I understand, this is the part of your code preparing the list of
objects containing the ip address before rendering:

    if ( bandlistdata.length > 0 ) {
        for (var i = 0; i < bandlistdata.length; i++) {
            mac = bandlistdata[i].mac.toUpperCase();
            ip = bandlistdata[i].ip;
            dname = StringH.encode4Html( bandlistdata[i].name );
            tpldata.push({
                dname: dname,
                ip: ip,
                mac: mac
            });
            currentList[ip] = 1;
        }
    }

So the route you are looking for is sorting the ` tpldata ` array before
calling:

    container.html( tpl.tmpl( {bandlist: tpldata} ) );

This is how you could sort the array, by calling the [ sort
](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) array method with
a callback that will split the octets of each ip address to compare and will
evalute their parts individually to determine which one comes first:

    const array = [
      { ip: "192.168.1.1" },
      { ip: "10.0.0.1" },
      { ip: "192.168.1.2" },
      { ip: "172.16.0.1" }
    ];

    array.sort((a, b) => {
      //splitting the parts of ip address held by a and b
      const aParts = a.ip.split('.').map(Number);
      const bParts = b.ip.split('.').map(Number);

      //comparing the parts of the ip address a and b to determine which comes first
      for (let i = 0; i < 4; i++) {
        if (aParts[i] !== bParts[i]) {
          return aParts[i] - bParts[i];
        }
      }

      //ips are the same
      return 0;
    });

    console.log(array);

So in your scenario just replace ` array ` with ` tpldata ` and call ` sort `
just before setting the container html.


Question:
setattr for `__call__` method of an object doesn't work in Python

I though that for python object `obj()` is equivalent to `obj.__call__()`. But it looks like it doesn't hold when `setattr` was used.

```
In [46]: class A:
    ...:     def __call__(self):
    ...:         return 1
    ...:

In [47]: a = A()

In [48]: a()
Out[48]: 1

In [49]: a.__call__()
Out[49]: 1

In [50]: getattr(a, '__call__')
Out[50]: <bound method A.__call__ of <__main__.A object at 0x10a3d2a00>>

In [51]: setattr(a, '__call__', lambda: 100)

In [52]: a()
Out[52]: 1

In [53]: a.__call__()
Out[53]: 100
```

Why is it so? And how I can set the `call` method in runtime?

Notice in Python version is 3.9.18 and 3.11.4

The snippet of code above, I'd expected a() returns 100

Explanation: The programmar thought that "obj() is equivalent to obj.__call__()". However, after using setattr(a, 'call', lambda: 100) to try to set a new __call__ attribute for instance a, the result shows that a() still returns 1, and only a.call() returns the newly set 100. Hence the correct way of running implicit calls to special methods is needed.

The issue is because ` __call__ ` is defined at the class level, not at the
instance level. See the documentation (from Python 2, when this was
introduced) [ here
](https://docs.python.org/2/reference/datamodel.html#special-method-lookup-
for-new-style-classes) .

You'd need to make sure to define an instance-level call function and apply `
setattr ` to that:

    class MyClass:
        def __call__(self, *args, **kwargs):
            return self._call(self, *args, **kwargs)

    >>> a = MyClass()
    >>> setattr(a, '_call', lambda self: 100)
    >>> a()
    100

Or, you can patch the class itself, if you want every instance of ` MyClass()
` to have the exact same ` __call__ ` function. However, consider carefully if
you want to do this:

    >>> setattr(MyClass, __call__, lambda self: "foo")
    >>> a()
    "foo"

**Explanation:** Prioritising the class definition of ` __call__ ` over any
instance-specific definition is common to the various special method
names/operator overloads in Python's [ data model
](https://docs.python.org/3/reference/datamodel.html#special-method-names) .

It comes from when new-style classes were introduced in Python 2. To quote the
"order of precedence" introduced in ( [ PEP 252
](https://peps.python.org/pep-0252/) ):

> There’s a conflict between names stored in the instance dict and names
> stored in the type dict. If both dicts have an entry with the same key,
> which one should we return? [...]
>
>   1. Look in the type dict. If you find a data descriptor, use its get()
> method to produce the result. This takes care of special attributes like
> **dict** and **class** .
>   2. Look in the instance dict. If you find anything, that’s it. (This takes
> care of the requirement that normally the instance dict overrides the class
> dict.)
>

The "type dict" refers to class-level definitions, such as the MyClass' `
__call__ ` definition, while the "instance dict" refers to values we have set
on a specific instance of ` MyClass ` , such as ` a ` above.

In your question, the initial ` __call__ ` definition is coming from step 1
(the type dict), while any values you set like so are set in the instance
dict, which has lower priority:

    setattr(a, '__call__', lambda self: 100)
    a.__call__ = lambda self: 100

You can find more information about how this came to be in [ this related
StackOverflow question ](https://stackoverflow.com/a/53835975/7662085) which
also points to [ this interesting external article
](https://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/#object-
attribute-lookup) .


Question:
How to replace all CRLF of a text file with ; with W10 cmd batch file that can use Sed, Awk (Gnuwin32)

I have this input with CRLF line endings:
```
1019
1020
1028
1021
```

I want to remove `CRLF` at end of each lines using `sed`, (or `awk`) from `Gnuwin32` using a Windows 10 batch script, (not Powershell).

I want to get the following result inside a text file, without any semicolon or CRLF at the end:
```
1019;1020;1028;1021
```

It doesn't work with the following lines in the batch file, (it seems there is a problem with GNUwin32 Sed that adds new CRLF at end of each processed line):
```
REM This to generate the input example :
(echo 1019& echo 1020& echo 1028& echo 1021) > test_in.txt

REM This is the first try for getting the desired 1-line output with semicolumn :
(echo 1019& echo 1020& echo 1028& echo 1021) | .\GnuWin32\bin\sed -e "s/ *$//g" | .\GnuWin32\bin\sed -e "s/\r\n/;/" > test_out.txt

REM This is the second try for getting the desired 1-line output with semicolumn :
REM (echo 1019& echo 1020& echo 1028& echo 1021) | .\GnuWin32\bin\sed -e "s/ *$//g" | .\GnuWin32\bin\sed -b -e "s/\x0d\x0a/;/g" > test_out.txt

REM This is the third try for getting the desired 1-line output with semicolumn :
REM (echo 1019& echo 1020& echo 1028& echo 1021) | .\GnuWin32\bin\sed -e "s/ *$//g" | .\GnuWin32\bin\awk "{gsub(\"\\\\r\\\\n\",\";\")};1" > test_out.txt

REM This is the fourth try for getting the desired 1-line output with semicolumn :
REM (echo 1019& echo 1020& echo 1028& echo 1021) | .\GnuWin32\bin\sed -e "s/ *$//g" | .\GnuWin32\bin\awk -v FS="\r\n" -v OFS=";" -v RS="\\$\\$\\$\\$" -v ORS="\r\n" "{$1=$1}1" > test_out.txt
```

Explanation: The programmer tries to remove CRLF at end of each lines using sed and/or awk and replace CRLF with semicolumn. However, both 2 could not generate the desired answer. Therefore, another viable command line needs to be added to the combination of commands that can do this text line processing task correctly.

As you are on Windows, here is a pure batch solution:

    @echo off
    setlocal enabledelayedexpansion
    del test_out.txt 2>nul
    REM This to generate the input example :
    (echo 1019& echo 1020& echo 1028& echo 1021) > test_in.txt

    set "delimiter="
    (for /f %%a in (test_in.txt) do (
     <nul set /p "=!delimiter!%%a" & set "delimiter=;"
    ))>test_out.txt
    REM when you need a CRLF at the end of the line:
    echo/>>test_out.txt

This uses a trick to write without a line ending: ` <nul set /p =string ` and
redirects the whole loop in one go to the resulting file (which does access
the disk only once, instead of once per line, which in turn makes it _much_
faster on big input files (not noticeable with your mere ~100 lines though))


Question:
GitHub Actions: how can I run a workflow created on a non-'master' branch from the 'workflow_dispatch' event?

For actions working on a third party repository, I would like to be able to create an action on a branch and execute it on the workflow_dispatch event. I have not succeeded in doing this, but I have discovered the following:

The Action tab will change the branch where it finds workflows and action code based on the branch relating to the last executed workflow. e.g. if some workflow is executed from the Action tab using the Run Workflow button and the Use Workflow From dropdown is set to some branch, Branch-A, then the contents of the Workflows panel on the left hand side of the Actions tab will be taken from Branch-A's version of .github/.
The This workflow has a workflow_dispatch event trigger. text does not change with the branch. It seems to be taken from master. Alternatively, it may be being taken from the last set of results. I have not tested for that because either way it is not helpful behaviour.
The workaround is the execute on a push event which is OK, but that seems out of kilter with GitHub's high standards of design.

Does the above sound a) about right and b) whichever way you look at it, not optimal behaviour? Or, is there a better approach to building and testing actions?

Explanation: The programmar wants to run a workflow created on a non-master branch from the `workflow_dispatch` event. He has tried several methods, but he is not sure whether they are correct. A better approach is required.

You can run a workflow that is still in development in a branch ` branch-name
` from the command line, with the GitHub CLI. The [ documentation
](https://docs.github.com/en/actions/managing-workflow-runs/manually-running-
a-workflow#running-a-workflow-using-github-cli) says:

> To run a workflow on a branch other than the repository's default branch,
> use the --ref flag.
>
> ` gh workflow run workflow-name --ref branch-name `

To list valid workflow names, use ` gh workflow list ` .

To add input parameters, run it like this:

` gh workflow run workflow-name --ref branch-name -f myparameter=myvalue `


Question:
Trying to delete entries gives: Inconsistent datatypes: expected %s got %s" in Oracle

I am trying to delete some entries based on 'name'. I have a table t1 with different columns, one of them being name and of type NCLOB. I have a method to delete these entries in Java, and I am using a named query. My question is, how can I solve the NCLOB issue so I'll be able to remove the data. I don't want to change the column type. The name query looks like this: `DELETE FROM table1 t1 WHERE t1.name = :name` How can I solve this?

Explanation: When trying to delete an entry based on the 'name' column in Oracle, an error is encountered, that is "Expected data type does not match actual data type: expected %s actual %s". The programmar is trying to delete some entries in table t1 where the name column is of type NCLOB. He/she is using a method in Java and a named query to perform the delete operation with the query statement: `DELETE FROM table1 t1 WHERE t1.name = :name`. To resolve the "Inconsistent datatypes" error that occurs when deleting an NCLOB type name column entry in Oracle, you can use the DBMS_LOB package. The DBMS_LOB package should be used to compare NCLOB data instead of using the = operator directly.

You cannot apply an equality predicate to a LOB of any kind. Instead, either
substring out and cast a ` nvarchar2 ` and apply the predicate to it, or use `
dbms_lob.compare ` , or use ` LIKE ` without a ` % ` :

    delete from table1 t1 where dbms_lob.compare(t1.name,:name) = 0

or

    delete from table1 t1 WHERE CAST(SUBSTR(t1.name,1,2000) AS nvarchar2(2000)) = :name

or

    delete from table1 t1 where t1.name like :name

But while this works, it raises the more important question of why you are
using a LOB datatype for an identifier column. The fact that you find yourself
doing this suggests that a LOB is the incorrect datatype for your needs. The
above DMLs will work, but will not perform well. LOBs are meant for
unstructured data that should not contain pieces of information that are
programmatically meaningful.


Question:
How to keep the shell window open after running a PowerShell script?

I have a very short PowerShell script that connects to a server and imports the AD module. I'd like to run the script simply by double clicking, but I'm afraid the window immediately closes after the last line.

How can I sort this out?

Explanation: The programmer want to keep the windows open after the script finishes running. The relevant article is required to solve this.

You basically have 3 options to prevent the PowerShell Console window from
closing, that I describe [ in more detail on my blog post
](http://blog.danskingdom.com/keep-powershell-console-window-open-after-
script-finishes-running/) .

  1. **One-time Fix:** Run your script from the PowerShell Console, or launch the PowerShell process using the -NoExit switch. e.g. ` PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1" `
  2. **Per-script Fix:** Add a prompt for input to the end of your script file. e.g. ` Read-Host -Prompt "Press Enter to exit" `
  3. **Global Fix:** Change your registry key by adding the ` -NoExit ` switch to always leave the PowerShell Console window open after the script finishes running.

    Registry Key: HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command
    Description: Key used when you right-click a .ps1 file and choose Open With -> Windows PowerShell.
    Default Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1"
    Desired Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "& \"%1\""

    Registry Key: HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command
    Description: Key used when you right-click a .ps1 file and choose Run with PowerShell (shows up depending on which Windows OS and Updates you have installed).
    Default Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
    Desired Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & \"%1\""

See my blog for more information and a script to download that will make the
registry change for you.


Question:
Typing a function param to be any JSON serializable object

what would be the best type for this function?
I want basically any input type that` json.dumps` can process (with or without `JSONEncoder`)

For now i'm using `Union[List[Any], Dict[Any, Any]]` but it's not exhaustive and mypy complains `Explicit "Any" is not allowed`.

```
import json
from typing import List, Dict
from datetime import date

def my_function_doing_stuff_then_serializing(input: Union[List[Any], Dict[Any, Any]], **kwargs) -> None:
    json.dumps(input, **kwargs)
```

so I can do this

```
import json
from datetime import date
from somewhere import my_function_doing_stuff_then_serializing

class DateEncoder(json.JSONEncoder):
    def default(self, obj: Any) -> Any:
        if isinstance(obj, date):
            return obj.isoformat()
        return super().default(obj)

my_function_doing_stuff_then_serializing([date.today()], cls=DateEncoder)
```

Explanation: The programmer wants to type a function parameter to be any JSON serializable object. The current choice has an error `Explicit "Any" is not allowed`. Therefore, a special marker, which is defined inside Python, is required indicating that an assignment should be recognized as a proper type alias definition by type checkers.

Using a current version of mypy, you can now use recursive a ` TypeAlias ` ,
which is a "special marker indicating that an assignment should be recognized
as a proper type alias definition by type checkers".

In your case, you could do either:

    from typing import List, Dict, Union
    JsonType = Union[None, int, str, bool, List[JsonType], Dict[str, JsonType]]

or, using the TypeAlias marker for checkers:

    from typing import List, Dict, Union, TypeAlias
    JsonType: TypeAlias = Union[None, int, str, bool, List[JsonType], Dict[str, JsonType]]

And [ as mentioned in this discussion
](https://github.com/python/typing/issues/182) , there are many more ways to
define such aliases according to your specific needs.


Question:
Hamcrest matcher for checking return value of method in collection

`hasProperty` can be used with `hasItem` to check for the value of a given property, eg:
```
Matcher hasName = Matchers.<Person>hasProperty("name", is("Winkleburger"));
assertThat(names, hasItem(hasName));
```

This is fine when name is a property, ie: there is a method called `getName()`.

Is there a matcher that will check a method that isn't a property? ie: in this case, it will check the return value of the method `name()` rather than `getName()`, for items in the collection.

Explanation: The question is about using the Hamcrest matcher to check the return value of a method in a collection, not the value of a property. The sample code uses hasProperty and hasItem matchers to check the value of the name property of the Person object. Need a matcher to check that a method is not a property, or be able to assist the matcher.

You can use another Hamcrest built-in for this, a [ FeatureMatcher
](http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/FeatureMatcher.html)
. These are designed to be combined with other matchers after they transform
your input into something else. So in your case you would do something like
this:

    @Test
    public void test1() {
        List<Person> names = new ArrayList<>();
        names.add(new Person("Bob"));
        names.add(new Person("i"));

        assertThat(names, hasItem(name(equalTo("Winkleburger"))));
    }

    private FeatureMatcher<Person, String> name(Matcher<String> matcher) {
        return new FeatureMatcher<Person, String>(matcher, "name", "name") {
            @Override
            protected String featureValueOf(Person actual) {
                return actual.name();
            }
        };
    }

The benefit you'll get with this over a custom matcher is that it's fully
reusable and composable with other matchers as all it does is the data-
extraction then defers to whatever other matcher you want. You're also going
to get appropriate diagnostics, e.g. in the above example you will if you
change the assert to a value that's not present you will receive:

    java.lang.AssertionError:
        Expected: a collection containing name "Batman"
        but: name was "Bob", name was "Winkleburger"


Question:
Can javascript sort like windows?

I need a way in Javascript to sort strings as in Windows but it seems it's impossible.

Windows explorer sorts like this:
```
1.jpg - 2.jpg - 3.jpg - ....
```

While Javascript sorts like this:
```
1.jpg - 10.jpg - 11.jpg - 2.jpg -...
```

Windows sorts based on the numeral value in the filename while Javascript just sorts by a characters' ASCII code.

Sometimes filenames aren't just numbers or text but a combination of both, e.G.:
```
"mark 01 in school.jpg"
"mark 02 in school.jpg"
"john 05 in theater.jpg"
```

What I need is a Javascript function that sorts like shown above.

My question is: is there a function in JS or how can I implement one on my own?

Explanation: A JS function or related algorithm that can sort strings like what Windows can do is required.

You will have to write your own sort function and pass it as argument to sort
method. Simple example:

    your_array.sort(sortfunction)

    function sortfunction(a, b){
         var num1 = extractNumberFrom(a);
         var num2 = extractNumberFrom(b);
         return num1 - num2;
    }


Question:
How can I subtract a number from string elements in R?

I have a long string. The part is
```
x <- "Text1 q10_1 text2 q17 text3 q22_5 ..."
```

How can I subtract 1 from each number after "q" letter to obtain the following?
```
y <- "Text1 q9_1 text2 q16 text3 q21_5 ..."
```

I can extract all my numbers from x:
```
numbers <- stringr::str_extract_all(x, "(?<=q)\\d+")
numbers <- as.integer(numbers[[1]]) - 1
```

But how can I update x with these new numbers?

The following is not working
```
stringr::str_replace_all(x, "(?<=q)\\d+", as.character(numbers))
```

Explanation: The programmar wants to subtract 1 from each number after "q" letter. The use of regular expressions is recommended to have a solution, which can capture the part of the string wanted to replace, and perform the modification and reinsertion operation.

I learned today that ` stringr::str_replace_all ` will take a function:

    stringr::str_replace_all(
      x,
      "(?<=q)\\d+",
      \(x) as.character(as.integer(x) - 1)
    )


Question:
Model translation in Django Rest Framework

I'm developing an API with Django Rest Framework, and I'd need some models with a few fields that should support translation in multiple languages then, of course, serializers should have to retrieve the field with the expected language. I've thought about two options: adding extra fields to the model (one field for language) or creating another model with all texts in every language. On the other hand, I've seen that there are some libraries such as django-modeltranslation that are intended to solve that issue, however, I'd like to know some opinions about them. What do you think? What would you recommend to me?

Thank you very much

Explanation: Design options for implementing a multilingual translation model in the Django Rest Framework are addressed through the use of third-party libraries such as django-modeltranslation. The related notes need to be found and looked at carefully.

As per [ documentation ](https://django-
modeltranslation.readthedocs.io/en/latest/caveats.html#using-in-combination-
with-django-rest-framework) ,

##  Using in combination with django-rest-framework

When creating a new viewset , make sure to override get_queryset method, using
queryset as a property won’t work because it is being evaluated once, before
any language was set.

##  ****

So depending on your needs you can create a class inheriting from drf (for
example ` ViewSet ` ), obtaining the language code from request and replacing
the ` get_queryset ` method to filter by language.

##  EDIT

To implement this, you would typically:

Detect the language from the request, using either the URL, query parameters,
or headers. Modify the queryset in the get_queryset method of your viewset to
filter or annotate results with the correct translation, based on the detected
language. For example:

    from django.utils.translation import get_language
    from rest_framework import viewsets

    class YourModelViewSet(viewsets.ModelViewSet):
        queryset = YourModel.objects.all()
        serializer_class = YourModelSerializer

        def get_queryset(self):
            lang = get_language()
            # Adjust the query based on the language, e.g., filtering or annotating
            return super().get_queryset().filter(language=lang)


Question:
Lossy compression method: uint16 to a uint8?

I'm looking for suggestions on lossy data compression methods. I need to compress a uint16 to a uint8 such that the resolution loss increases with increasing uint16 values. I am currently using the following:

```
def log2_compress(x: np.uint16) -> np.uint8:
    # Add l to avoid log2(0)
    y = math.log2(x + 1)
    # log2(1) = 0.
    # log2(65536) = 16.
    # Scale from [0,16] to [0,255].
    return np.uint8((y / 16) * 255)
```

This is simple but has the downside that it is wasteful on the `uint8` side, namely

```
log2_compress(0) = 0
log2_compress(1) = 15
log2_compress(2) = 25
```
so `[1,14]`, `[16,24]`, etc. aren't used. Can someone suggest a method similar to `log2_compress` but uses more (all?) of the `uint8` bits? I am not really concerned about performance either.

Explanation: There is a need for a method of lossy compression of uint16 to uint8, which requires that the loss of resolution increases as the value of uint16 increases. The log2_compress method currently used is simple but has a low utilisation rate in the uint8 range. One possible approach is to use mathematical graphical analyses, such as rising slopes implying smaller uint16 input values.

Depending on what you mean by

> such that the resolution loss increases with increasing ` uint16 ` values

you might want to try different compression functions. Without any further
information about the context, we will assume that you are looking for an
increasing [ concave function
](https://en.wikipedia.org/wiki/Concave_function) to map [0~65535] to [0~255].

You can try first the function ` sqrt ` :

    def sqrt_compress(x: np.uint16) -> np.uint8:
        return np.uint8(math.sqrt(x))

If the smoothness of this function is not exactly what you need, you can try
other powers rather that 1/2 for the square root. You can add the power as a
parameter ` p ` that will have effect on the smoothness of the compression
function:

    def power_compress_p(x: np.uint16, p: float = 2) -> np.uint8:
        """Compression function. Higher value of p use less bits."""
        return np.uint8(2 ** (8 - 16 / p) * x ** (1 / p))

For your use case, use ` p > 1 ` .

The power functions obviously are not the only compression that exist, you
could use a dictionary to define a map function if you want better control
over the granularity.


Question:
How can I get LLM to only respond in JSON strings?

This is how I am defining the executor
```
const executor = await initializeAgentExecutorWithOptions(tools, model, {
  agentType: 'chat-conversational-react-description',
  verbose: false,
});
```

Whenever I prompt the AI I have this statement at the end.
```
type SomeObject = {
  field1: number,
  field2: number,
}

- It is very critical that you answer only as the above object and JSON stringify it as a single string.
  Don't include any other verbose explanatiouns and don't include the markdown syntax anywhere.
```

The `SomeObject` is just an example. Usually it will have a proper object type. When I use the `executor` to get a response from the AI, half the time I get the proper JSON string, but the other half the times are the AI completely ignoring my instructions and gives me a long verbose answer in just plain English...

How can I make sure I always get the structured data answer I want? Maybe using the `agentType: 'chat-conversational-react-description'` isn't the right approach here?

Explanation: The programmar wanted to a guaranteed way to ensure the output is JSON. However his problem was solved in a feature update from Openai, and the article in question needs to be found.

##  Update Nov. 6, 2023

OpenAI announced today a new “JSON Mode” at the DevDay Keynote. When activated
the model will only generate responses using the ` JSON ` format.

You can refer to the official docs [ here
](https://platform.openai.com/docs/guides/text-generation/json-mode) .

##  Original Answer

That's a great question and ` LangChain ` provides an easy solution. Look at
LangChain's ` Output Parsers ` if you want a quick answer. It is the
recommended way to process LLM output into a specified format.

Here's the official link from the docs:

  * **JavaScript** : [ https://js.langchain.com/docs/modules/model_io/output_parsers/ ](https://js.langchain.com/docs/modules/model_io/output_parsers/)
  * Python: [ https://python.langchain.com/docs/modules/model_io/output_parsers/ ](https://python.langchain.com/docs/modules/model_io/output_parsers/)

* * *

Side note: I wrote an introductory tutorial about this particular issue but
for Python, so if anyone else is interested in more details you can [ check it
out here ](https://www.gettingstarted.ai/how-to-langchain-output-parsers-
convert-text-to-objects/) .

The example below does not use ` initializeAgentExecutorWithOptions ` , but
will ensure that the output is processed as ` JSON ` without specifying this
explicitly in your system prompt.

##  How it works

In order to tell LangChain that we'll need to convert the LLM response to a `
JSON ` output, we'll need to define a ` StructuredOutputParser ` and pass it
to our ` chain ` .

###  Defining our ` parser ` :

Here's an example:

    // Let's define our parser
    const parser = StructuredOutputParser.fromZodSchema(
      z.object({
        field1: z.string().describe("first field"),
        field2: z.string().describe("second field")
      })
    );

###  Adding it to our ` Chain ` :

    // We can then add it to our chain
    const chain = RunnableSequence.from([
      PromptTemplate.fromTemplate(...),
      new OpenAI({ temperature: 0 }),
      parser, // <-- this line
    ]);

###  Invoking our chain with ` format_instructions ` :

    // Finally, we'll pass the format instructions to the invoke method
    const response = await chain.invoke({
      question: "What is the capital of France?",
      format_instructions: parser.getFormatInstructions(), // <-- this line
    });

Go ahead and log the ` parser.getFormatInstructions() ` method before you call
` invoke ` if you'd like to see the output.

When we pass ` parser.getFormatInstructions() ` to the ` format_instructions `
property, this lets LangChain append the desired ` JSON ` schema that we
defined in step 1 to our prompt before sending it to the large language model.

As a final point, it is absolutely **critical** to make sure your query/prompt
is relevant and produces values that could be interpreted as the properties in
your object ` SomeObject ` that are defined in the ` parser ` .

Please give this a try, and let me know if you're able to consistently output
` JSON ` .


Question:
Enqueue javascript with type="module"

I want to use `countUp.js` on my custom theme in Wordpress.

When I add the file with `wp_enqueue_script()`, I get an error:

```
Uncaught SyntaxError: Unexpected token 'export'
```

I've read that it can be fixed by setting `type="module"` on the `<script>` tag, but I don't know how to do that as that option doesn't exist in `wp_enqueue_script()`...

Can anyone help me?

Explanation: In order to properly load JavaScript files with ES6 module syntax in WordPress (such as countUp.js), it is necessary to explore the hook functions and filter mechanisms provided by WordPress. These built-in tools allow developers to modify and extend core functionality at specific stages of execution. Consider using the script_loader_tag filter to inject the type="module" attribute into the output <script> tag by adding an appropriate callback function. This approach provides an elegant solution without modifying the core code, taking full advantage of WordPress' powerful extensibility. Of course, the implementation details need to review the WordPress hook function usage and parameters, and with the existing theme framework compatibility and other factors to weigh.

One can add attributes to a script by applying filter ' [ script_loader_tag
](https://developer.wordpress.org/reference/hooks/script_loader_tag/) '.

Use ` add_filter('script_loader_tag', 'add_type_attribute' , 10, 3); ` to add
the filter.

Define the callback function like the example given on the link above:

    function add_type_attribute($tag, $handle, $src) {
        // if not your script, do nothing and return original $tag
        if ( 'your-script-handle' !== $handle ) {
            return $tag;
        }
        // change the script tag by adding type="module" and return it.
        $tag = '<script type="module" src="' . esc_url( $src ) . '"></script>';
        return $tag;
    }


Question:
python packages installing order

when we install python packages using pip, sometimes it installs some other packages. for example installing torch requires installing numpy. imagine in a requirements.txt file there are packages with their versions, but not in a right order. how can we realize the right order? (for example if numpy version is specified as 1.1 but previous package in the list automatically installs numpy of last version!)

I installed librosa==0.9.2 which installed scipy 1.10 during its installation. but after that there is scipy=1.8 in the list. doesn't it make a conflict?

Explanation: When managing Python package dependencies and installation order within a project, relying solely on a requirements.txt file may lead to version conflicts and other issues. The need to explore a more standardized way of organizing project metadata is becoming increasingly apparent. An emerging standard worth considering could potentially provide a more controlled and deterministic solution, allowing developers to more precisely constrain dependency package versions during environment setup, thereby effectively avoiding potential package version conflicts. This standard is required.

Installation order should not matter at all if you use modern tools (Python,
pip, etc.) and libraries that are packaged with modern techniques ( [ `
[build-system] ` section in ` pyproject.toml `
](https://packaging.python.org/en/latest/specifications/declaring-build-
dependencies/) ).

In the case that you are presenting, it could be that _pip_ had to build
_librosa_ (because no compatible _wheel_ could be found). _pip_ does builds in
ephemeral one-time-use isolated virtual environments, so maybe _pip_ used
_scipy 1.10_ to build _librosa_ . But what was installed in your actual
virtual environment was a different version of _scipy_ ( _1.8_ ), it is not an
issue in itself. There are some cases, where a library is only compatible at
run-time with the library it was built with.


Question:
Is there a fiber api in .net?

Out of more curiosity than anything I've been looking for a set of C#/.net classes to support fibers/co-routines (the win32 version) and haven't had any luck.

Does anybody know of such a beast?

Explanation: The programmer wants to look for C#/.net classes to support fibers/co-routines. Please check if such a class exists, if not, the official documentation should provide the reason.

No. There isn't a Fiber API in the Framework. I suspect this is because there
is little advantage to using them - even the [ fiber API page
](http://msdn.microsoft.com/en-us/library/ms682661%28VS.85%29.aspx) (native)
mentions:

> In general, fibers do not provide advantages over a well-designed
> multithreaded application.

.NET makes it so much easier to develop a "well-designed" multithreaded
application that I suspect there is little use for a fiber API.


Question:
How do I compare strings in Java?

I've been using the `==` operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into `.equals()` instead, and it fixed the bug.

Is `==` bad? When should it and should it not be used? What's the difference?

Explanation: The programmer want to know the deep difference between `.equals()` and `==` in Java for String comparsion. The definition of `.equals()` needs to be rechecked carefully. The official explanantion is required.

` == ` tests for reference equality (whether they are the same object).

` .equals() ` tests for value equality (whether they contain the same data).

[ Objects.equals()
](http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#equals\(java.lang.Object,%20java.lang.Object\))
checks for ` null ` before calling ` .equals() ` so you don't have to
(available as of JDK7, also available in [ Guava
](https://github.com/google/guava/wiki/CommonObjectUtilitiesExplained#equals)
).

Consequently, if you want to test whether two strings have the same value you
will probably want to use ` Objects.equals() ` .

    // These two have the same value
    new String("test").equals("test") // --> true

    // ... but they are not the same object
    new String("test") == "test" // --> false

    // ... neither are these
    new String("test") == new String("test") // --> false

    // ... but these are because literals are interned by
    // the compiler and thus refer to the same object
    "test" == "test" // --> true

    // ... string literals are concatenated by the compiler
    // and the results are interned.
    "test" == "te" + "st" // --> true

    // ... but you should really just call Objects.equals()
    Objects.equals("test", new String("test")) // --> true
    Objects.equals(null, "test") // --> false
    Objects.equals(null, null) // --> true

From the Java Language Specification [ JLS 15.21.3. Reference Equality
Operators ` == ` and ` != `
](https://docs.oracle.com/javase/specs/jls/se21/html/jls-15.html#jls-15.21.3)
:

> While ` == ` may be used to compare references of type ` String ` , such an
> equality test determines whether or not the two operands refer to the same `
> String ` object. The result is ` false ` if the operands are distinct `
> String ` objects, even if they contain the same sequence of characters ( [
> §3.10.5
> ](https://docs.oracle.com/javase/specs/jls/se21/html/jls-3.html#jls-3.10.5)
> , [ §3.10.6
> ](https://docs.oracle.com/javase/specs/jls/se21/html/jls-3.html#jls-3.10.6)
> ). The contents of two strings ` s ` and ` t ` can be tested for equality by
> the method invocation ` s.equals(t) ` .

You almost **always** want to use ` Objects.equals() ` . In the **rare**
situation where you **know** you're dealing with [ interned
](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#intern--)
strings, you _can_ use ` == ` .

From [ JLS 3.10.5. _String Literals_
](https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.5) :

> Moreover, a string literal always refers to the _same_ instance of class `
> String ` . This is because string literals - or, more generally, strings
> that are the values of constant expressions ( [ §15.28
> ](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28) )
> - are "interned" so as to share unique instances, using the method `
> String.intern ` .

Similar examples can also be found in [ JLS 3.10.5-1
](https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#d5e1634) .

###  Other Methods To Consider

[ String.equalsIgnoreCase()
](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#equalsIgnoreCase-
java.lang.String-) value equality that ignores case. Beware, however, that
this method can have unexpected results in various locale-related cases, see [
this question ](https://stackoverflow.com/questions/44238749/equalsignorecase-
not-working-as-intended) .

[ String.contentEquals()
](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#contentEquals-
java.lang.CharSequence-) compares the content of the ` String ` with the
content of any ` CharSequence ` (available since Java 1.5). Saves you from
having to turn your StringBuffer, etc into a String before doing the equality
comparison, but leaves the null checking to you.


Question:
Event binding on dynamically created elements?

I have a bit of code where I am looping through all the select boxes on a page and binding a .hover event to them to do a bit of twiddling with their width on mouse on/off.

This happens on page ready and works just fine.

The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound.

I have found this plugin (jQuery Live Query Plugin), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.

Explanation: Explore how to use jQuery to bind events to dynamically created elements without introducing additional plugin libraries. Initially, when the page is loaded, the loop binds the .hover event to the existing select element successfully, but subsequent select elements added dynamically via Ajax or DOM cannot bind the event automatically. Need a jQuery built-in method or other technical solutions, can be achieved on the dynamic elements of the event binding, so as to unify the management of all select elements of the interactive behaviour.

**As of jQuery 1.7** you should use [ ` jQuery.fn.on `
](https://api.jquery.com/on/#on-events-selector-data-handler) with the
selector parameter filled:

    $(staticAncestors).on(eventName, dynamicChild, function() {});

_Explanation:_

This is called event delegation and works as followed. The event is attached
to a static parent ( ` staticAncestors ` ) of the element that should be
handled. This jQuery handler is triggered every time the event triggers on
this element or one of the descendant elements. The handler then checks if the
element that triggered the event matches your selector ( ` dynamicChild ` ).
When there is a match then your custom handler function is executed.

* * *

**Prior to this** , the recommended approach was to use [ ` live() `
](http://api.jquery.com/live) :

    $(selector).live( eventName, function(){} );

However, ` live() ` was deprecated in 1.7 in favour of ` on() ` , and
completely removed in 1.9. The ` live() ` signature:

    $(selector).live( eventName, function(){} );

... can be replaced with the following [ ` on() ` ](http://api.jquery.com/on/)
signature:

    $(document).on( eventName, selector, function(){} );

* * *

For example, if your page was dynamically creating elements with the class
name ` dosomething ` you would bind the event to **a parent which already
exists** (this is the nub of the problem here, you need something that exists
to bind to, don't bind to the dynamic content), this can be (and the easiest
option) is ` document ` . Though bear in mind [ ` document ` may not be the
most efficient option ](https://stackoverflow.com/questions/12824549/should-
all-jquery-events-be-bound-to-document) .

    $(document).on('mouseover mouseout', '.dosomething', function(){
        // what you want to happen when mouseover and mouseout
        // occurs on elements that match '.dosomething'
    });

Any parent that exists at the time the event is bound is fine. For example

    $('.buttons').on('click', 'button', function(){
        // do something here
    });

would apply to

    <div class="buttons">
        <!-- <button>s that are generated dynamically and added here -->
    </div>


Question:
How to access the correct `this` inside a callback

I have a constructor function which registers an event handler:
```
function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', function () {
        alert(this.data);
    });
}

// Mock transport object
var transport = {
    on: function(event, callback) {
        setTimeout(callback, 1000);
    }
};

// called as
var obj = new MyConstructor('foo', transport);
```

However, I'm not able to access the `data` property of the created object inside the callback. It looks like `this` does not refer to the object that was created, but to another one.

I also tried to use an object method instead of an anonymous function:
```
function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', this.alert);
}

MyConstructor.prototype.alert = function() {
    alert(this.name);
};
```

but it exhibits the same problems.

How can I access the correct object?

Explanation: In the constructor `MyConstructor`, the event listener is registered via `transport.on('data', callback)`, but the `callback` function does not have access to the data property of the `MyConstructor` instance internally, and `this` points to some other object. The same problem exists even if the callback is defined as a `MyConstructor.prototype.alert` instance method. A solution needs to be explored by fully checking the relative documentation.

##  What you should know about ` this `

` this ` (aka "the context") is a special keyword inside each function and its
value only depends on _how_ the function was called, not how/when/where it was
defined. It is not affected by lexical scopes like other variables (except for
arrow functions, see below). Here are some examples:

    function foo() {
        console.log(this);
    }

    // normal function call
    foo(); // `this` will refer to `window`

    // as object method
    var obj = {bar: foo};
    obj.bar(); // `this` will refer to `obj`

    // as constructor function
    new foo(); // `this` will refer to an object that inherits from `foo.prototype`

To learn more about ` this ` , have a look at the [ MDN documentation
](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Operators/this) .

* * *

##  How to refer to the correct ` this `

###  Use [ arrow functions ](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)

ECMAScript 6 introduced _arrow functions_ , which can be thought of as lambda
functions. They don't have their own ` this ` binding. Instead, ` this ` is
looked up in scope just like a normal variable. That means you don't have to
call ` .bind ` . That's not the only special behavior they have, please refer
to the MDN documentation for more information.

    function MyConstructor(data, transport) {
        this.data = data;
        transport.on('data', () => alert(this.data));
    }

###  Don't use ` this `

You actually don't want to access ` this ` in particular, but _the object it
refers to_ . That's why an easy solution is to simply create a new variable
that also refers to that object. The variable can have any name, but common
ones are ` self ` and ` that ` .

    function MyConstructor(data, transport) {
        this.data = data;
        var self = this;
        transport.on('data', function() {
            alert(self.data);
        });
    }

Since ` self ` is a normal variable, it obeys lexical scope rules and is
accessible inside the callback. This also has the advantage that you can
access the ` this ` value of the callback itself.

###  Explicitly set ` this ` of the callback - part 1

It might look like you have no control over the value of ` this ` because its
value is set automatically, but that is actually not the case.

Every function has the method [ ` .bind ` _ [docs]  _
](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) , which returns
a new function with ` this ` bound to a value. The function has exactly the
same behavior as the one you called ` .bind ` on, only that ` this ` was set
by you. No matter how or when that function is called, ` this ` will always
refer to the passed value.

    function MyConstructor(data, transport) {
        this.data = data;
        var boundFunction = (function() { // parenthesis are not necessary
            alert(this.data);             // but might improve readability
        }).bind(this); // <- here we are calling `.bind()`
        transport.on('data', boundFunction);
    }

In this case, we are binding the callback's ` this ` to the value of `
MyConstructor ` 's ` this ` .

**Note:** When a binding context for jQuery, use [ ` jQuery.proxy ` _ [docs]
_ ](http://api.jquery.com/jQuery.proxy/) instead. The reason to do this is so
that you don't need to store the reference to the function when unbinding an
event callback. jQuery handles that internally.

###  Set ` this ` of the callback - part 2

Some functions/methods which accept callbacks also accept a value to which the
callback's ` this ` should refer to. This is basically the same as binding it
yourself, but the function/method does it for you. [ ` Array#map ` _ [docs]  _
](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) is such a method.
Its signature is:

    array.map(callback[, thisArg])

The first argument is the callback and the second argument is the value ` this
` should refer to. Here is a contrived example:

    var arr = [1, 2, 3];
    var obj = {multiplier: 42};

    var new_arr = arr.map(function(v) {
        return v * this.multiplier;
    }, obj); // <- here we are passing `obj` as second argument

**Note:** Whether or not you can pass a value for ` this ` is usually
mentioned in the documentation of that function/method. For example, [
jQuery's ` $.ajax ` method _ [docs]  _ ](http://api.jquery.com/jQuery.ajax/)
describes an option called ` context ` :

> This object will be made the context of all Ajax-related callbacks.

* * *

##  Common problem: Using object methods as callbacks/event handlers

Another common manifestation of this problem is when an object method is used
as callback/event handler. Functions are first-class citizens in JavaScript
and the term "method" is just a colloquial term for a function that is a value
of an object property. But that function doesn't have a specific link to its
"containing" object.

Consider the following example:

    function Foo() {
        this.data = 42,
        document.body.onclick = this.method;
    }

    Foo.prototype.method = function() {
        console.log(this.data);
    };

The function ` this.method ` is assigned as click event handler, but if the `
document.body ` is clicked, the value logged will be ` undefined ` , because
inside the event handler, ` this ` refers to the ` document.body ` , not the
instance of ` Foo ` .
As already mentioned at the beginning, what ` this ` refers to depends on how
the function is **called** , not how it is **defined** .
If the code was like the following, it might be more obvious that the function
doesn't have an implicit reference to the object:

    function method() {
        console.log(this.data);
    }

    function Foo() {
        this.data = 42,
        document.body.onclick = this.method;
    }

    Foo.prototype.method = method;

**The solution** is the same as mentioned above: If available, use ` .bind `
to explicitly bind ` this ` to a specific value

    document.body.onclick = this.method.bind(this);

or explicitly call the function as a "method" of the object, by using an
anonymous function as callback / event handler and assign the object ( ` this
` ) to another variable:

    var self = this;
    document.body.onclick = function() {
        self.method();
    };

or use an arrow function:

    document.body.onclick = () => this.method();


Question:
How can I disable UWP WebView2's drag and drop?

In my `UWP` application, I use a webview2 (from "Microsoft.UI.Xaml.Controls"). And the web content shown inside of it can be drag-and-drop.

I want to disable this "drag-and-drop" feature, and I tried a lot of ways, but all failed. E.g., `AllowDrop="False" CanDrag="False"`

How can I do it?

XAML code:
```
xmlns:controls="using:Microsoft.UI.Xaml.Controls"

 <controls:WebView2 x:Name="_WebView2" Height="370" Width="792"
     NavigationStarting="WebView2_NavigationStarting"/>
```

C#:
```
await _WebView2.EnsureCoreWebView2Async();
_WebView2.CoreWebView2.Navigate(sourceStr);
```

Explanation: WebView2 displays web content that can be dragged and dropped, and now want to turn this feature off. However, attempts such as AllowDrop="False" CanDrag="False" fail. Please provide XAML and C# code samples.

Try this:

    await _WebView2.EnsureCoreWebView2Async();
    _WebView2.CoreWebView2.Controller.AllowExternalDrop = false;

It works in my test application. You can see [ the documentation
](https://learn.microsoft.com/en-
us/dotnet/api/microsoft.web.webview2.core.corewebview2controller.allowexternaldrop?view=webview2-dotnet-1.0.2365.46)
.


Question:
java.lang.OutOfMemoryError: Java heap space

I am getting the following error on execution of a multi-threading program
```
java.lang.OutOfMemoryError: Java heap space
```

The above error occured in one of the threads.

1. Upto my knowledge, Heap space is occupied by instance variables only. If this is correct, then why this error occurred after running fine for sometime as space for instance variables are alloted at the time of object creation.

2. Is there any way to increase the heap space?

3. What changes should I made to my program so that It will grab less heap space?

Explanation: During the execution of a multi-threaded Java programme, the error "java.lang.OutOfMemoryError: Java heap space" is encountered. A way to increase the heap space size of the Java Virtual Machine needs to be found.

If you want to increase your heap space, you can use ` java -Xms<initial heap
size> -Xmx<maximum heap size> ` on the command line. By default, the values
are based on the JRE version and system configuration. You can find out [ more
about the VM options on the Java website
](http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp) .

However, I would recommend profiling your application to find out why your
heap size is being eaten. NetBeans has a [ very good profiler
](http://profiler.netbeans.org/) included with it. I believe it uses the [ `
jvisualvm `
](http://java.sun.com/javase/6/docs/technotes/guides/visualvm/index.html)
under the hood. With a profiler, you can try to find where many objects are
being created, when objects get garbage collected, and more.


Question:
Getting Error during build: RollupError: expression expected after migrating from vue-cli to vite

I just migrated from vue-cli to vite. Serving locally works fine, but during the build, I got the following error:
```
x Build failed in 221ms
error during build:
RollupError: Expression expected
    at getRollupError (file:///home/pc/Desktop/proj/node_modules/rollup/dist/es/shared/parseAst.js:379:41)
    at ParseError.initialise (file:///home/pc/pc/proj/node_modules/rollup/dist/es/shared/node-entry.js:11172:28)
    at convertNode (file:///home/officeubuntu23/pc/proj/node_modules/rollup/dist/es/shared/node-entry.js:12914:10)
    at convertProgram (file:///home/officeubuntu23/pc/proj/node_modules/rollup/dist/es/shared/node-entry.js:12234:12)
    at Module.setSource (file:///home/officeubuntu23/pc/proj/node_modules/rollup/dist/es/shared/node-entry.js:14073:24)
    at async ModuleLoader.addModuleSource (file:///home/pc/Desktop/proj/node_modules/rollup/dist/es/shared/node-entry.js:18712:13)
```

I have tried updating node and npm, reinstalling rollup and doing `npm update` and `npm install`.

Explanation: Build errors can be related to mismatched configurations after migration, incompatible dependency versions, build scripts not updated, etc. There needs to be relevant guidance documentation to help programmers sift through the errors step by step.

We encountered that exact same error on my team as well. A team member was
using Linux, so he set up some symlinks to a few required resources. The rest
of us were using Windows, so the symlinks didn't play nice with Windows/Vite.

Try checking your project for simlinks and see if that is causing the error.


Question:
r convert month year to ordered numeric

I have a dataset with column where the values are month year in format like this
```
 M_Yr
 March 1990
 April 1990
 May   1990
 June  1990
 July  1990
 Aug   1990
 Sept  1990
 Oct   1990
 Nov   1990
 Dec   1990
 Jan   1991
 Feb   1991
 March 1991
 April 1991
 May   1991
 June  1991
 July  1991
 Aug   1991
 Sept  1991
 Oct   1991
 Nov   1991
 Dec   1991
```

I tried this approach.
```
df$Col1 <- as.numeric(df$M_Yr)
```

This does converts the `month Year` variable to numeric but the order is scrambled and not in right sequence. So I am wondering what is an efficient way to create this numeric variable without writing a lengthy `case_when` statement.

Any suggestion is much appreciated. Thanks.

Explanation: This is a question about how to convert month and year values to an ordered numeric format. The given dataset contains a column "M_Yr" with values in the format "Month Year" as strings, e.g. "March 1990". The goal is to convert these values to an ordered numeric representation without using a lengthy case_when statement. A possible solution is to leverage functions from a relative package, which is specifically designed for working with dates and times, making it convenient to parse and manipulate month and year information.

[ Stack Overflow  ](https://stackoverflow.com)

  1. [ About ](https://stackoverflow.co/)
  2. Products
  3. [ OverflowAI ](https://stackoverflow.co/teams/ai/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav-bar&utm_content=overflowai)

  1. [ Stack Overflow for Teams  Where developers & technologists share private knowledge with coworkers  ](https://stackoverflow.co/teams/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-for-teams)
  2. [ Advertising & Talent  Reach devs & technologists worldwide about your product, service or employer brand  ](https://stackoverflow.co/advertising/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-advertising)
  3. [ OverflowAI  GenAI features for Teams  ](https://stackoverflow.co/teams/ai/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=overflow-ai)
  4. [ OverflowAPI  Train & fine-tune LLMs  ](https://stackoverflow.co/api-solutions/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=overflow-api)
  5. [ Labs  The future of collective knowledge sharing  ](https://stackoverflow.co/labs/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=labs)
  6. [ About the company ](https://stackoverflow.co/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=about-the-company) [ Visit the blog ](https://stackoverflow.blog/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=blog)

Loading…

  1. ###  [ current community ](https://stackoverflow.com)

     * [ Stack Overflow  ](https://stackoverflow.com)

[ help ](https://stackoverflow.com/help) [ chat
](https://chat.stackoverflow.com/?tab=site&host=stackoverflow.com)

     * [ Meta Stack Overflow  ](https://meta.stackoverflow.com)

###  your communities

[ Sign up
](https://stackoverflow.com/users/signup?ssrc=site_switcher&returnurl=https%3a%2f%2fstackoverflow.com%2fquestions%2f78322853%2fr-
convert-month-year-to-ordered-numeric) or [ log in
](https://stackoverflow.com/users/login?ssrc=site_switcher&returnurl=https%3a%2f%2fstackoverflow.com%2fquestions%2f78322853%2fr-
convert-month-year-to-ordered-numeric) to customize your list.

###  [ more stack exchange communities ](https://stackexchange.com/sites)

[ company blog ](https://stackoverflow.blog)

  2.   3. [ Log in ](https://stackoverflow.com/users/login?ssrc=head&returnurl=https%3a%2f%2fstackoverflow.com%2fquestions%2f78322853%2fr-convert-month-year-to-ordered-numeric)
  4. [ Sign up ](https://stackoverflow.com/users/signup?ssrc=head&returnurl=https%3a%2f%2fstackoverflow.com%2fquestions%2f78322853%2fr-convert-month-year-to-ordered-numeric)

  1.     1. [ Home  ](/)
    2. [ Questions  ](/questions)
    3. [ Tags  ](/tags)
    4.     5. [ Users  ](/users)
    6. [ Companies  ](https://stackoverflow.com/jobs/companies?so_medium=stackoverflow&so_source=SiteNav)
    7. [ Labs  ](javascript:void\(0\))
    8. [ Jobs  ](/jobs?source=so-left-nav)
    9. [ Discussions  ](/beta/discussions)
    10. [ Collectives  ](javascript:void\(0\))

    11. Communities for your favorite technologies. [ Explore all Collectives ](/collectives-all)

  2. Teams

Now available on Stack Overflow for Teams!  AI features where you work:
search, IDE, and chat.

[ Learn more
](https://stackoverflow.co/teams/ai/?utm_medium=referral&utm_source=stackoverflow-
community&utm_campaign=side-bar&utm_content=overflowai-learn-more) [ Explore
Teams
](https://stackoverflow.co/teams/?utm_medium=referral&utm_source=stackoverflow-
community&utm_campaign=side-bar&utm_content=explore-teams)

  3. [ Teams  ](javascript:void\(0\))
  4. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. [ Explore Teams ](https://stackoverflow.co/teams/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams-compact)

#####  Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you
use most.

[ Learn more about Collectives ](/collectives)

**Teams**

Q&A for work

Connect and share knowledge within a single location that is structured and
easy to search.

[ Learn more about Teams ](https://stackoverflow.co/teams/)

Get early access and see previews of new features.

[ Learn more about Labs ](https://stackoverflow.co/labs/)

#  Page not found

This question was  removed from Stack Overflow for reasons of moderation  .
Please refer to the help center for [ possible explanations why a question
might be removed ](/help/deleted-questions) .

Here are some similar questions that might be relevant:

  * [ Why is subtracting these two epoch-milli Times (in year 1927) giving a strange result? ](/questions/6841333/why-is-subtracting-these-two-epoch-milli-times-in-year-1927-giving-a-strange-r)
  * [ Get the current year in JavaScript ](/questions/6002254/get-the-current-year-in-javascript)
  * [ How to check if a String is numeric in Java ](/questions/1102891/how-to-check-if-a-string-is-numeric-in-java)
  * [ Convert a Unix timestamp to time in JavaScript ](/questions/847185/convert-a-unix-timestamp-to-time-in-javascript)
  * [ MySQL Query GROUP BY day / month / year ](/questions/508791/mysql-query-group-by-day-month-year)
  * [ How do I use PHP to get the current year? ](/questions/64003/how-do-i-use-php-to-get-the-current-year)
  * [ Year and Month columns issue SQL ](/questions/68964132/year-and-month-columns-issue-sql)
  * [ How to allow only numeric (0-9) in HTML inputbox using jQuery? ](/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery)
  * [ Get month name from Date ](/questions/1643320/get-month-name-from-date)
  * [ Is there a function to change my months column from int to text without it showing NA ](/questions/74943727/is-there-a-function-to-change-my-months-column-from-int-to-text-without-it-showi)

Try a [ Google Search
](http://www.google.com/search?q=site:stackoverflow.com/questions+r+convert+month+year+to+ordered+numeric)

Try [ searching for similar questions
](/search?q=r%20convert%20month%20year%20to%20ordered%20numeric)

Browse our [ recent questions ](/questions)

Browse our [ popular tags ](/tags)

If you feel something is missing that should be here, [ contact us ](/contact)
.


Question:
Calculate weighted average by date in R

I'm new to R and having some difficulty aggregating by date. I have time-series data with multiple price and quantity entries per date. The actual data is more complex, but it looks something like this:
```
price<-c(1.50,3,1.50,3,3,2.90,3)
quantity<-c(10,5,10,5,5,5,5)
date<-c('01/09/21','01/09/21','01/16/21','01/16/21','01/23/21','01/30/21','01/30/21')
df<-data.frame(date,price,quantity)
```

```
date        price        quantity
01/09/21        1.5        10
01/09/21        3        5
01/16/21        1.5        10
01/16/21        3        5
01/23/21        3        5
01/30/21        2.9        5
01/30/21        3        5
```

I'd like to create a new data frame with only the four individual dates and a single price value for each. To do so, I'm trying to calculate the weighted average of price on each individual date, similar to the example below:
```
date        price_weighted
01/09/21        2
01/16/21        2
01/23/21        3
01/30/21        2.95
```

I've tried using `price_weighted<-aggregate(price~date,df,weighted.mean)`, which returns something similar to what I want, but for some reason it's calculating the average price rather than the weighted average. Any suggestions would be appreciated!

Explanation: This is a question about calculating the weighted average of prices grouped by date in R. The given data frame contains multiple entries of prices and quantities for the same date. The goal is to create a new data frame with a single row for each unique date and the corresponding single weighted average price value calculated. Although attempting to use the weighted.mean function did not yield the expected result, other functions and data manipulation techniques provided by R can be explored to calculate the correct weighted average based on the grouped dates and their associated price and quantity data.


Question:
How to convert MJD time in UTC (only date, no time) in order to make a plot

I have a list of MJD time. I need to convert it in list UTC but only the date (year/month/day) and no time, so a list that I can use to make a plot with time in x-axis. Thanks

I tried with astropy and the command Time('list',forma='mjd').iso but i have also the time, and I am not able to delete.

Explanation: Utilizing the appropriate date and time formatting tools or libraries, when converting MJD values to dates, it is necessary to specify outputting only the date portion without including the time part. This may involve using specific formatting parameters or methods to control the output format.

I would utilize the ` subfmt ` specification to extract only the data and not
the time as follows. I created an array of MJD times and then convert them to
UTC and derive only the dates as follows

    from astropy.time import Time
    import numpy as np

    mjd_array = np.arange(51545,51550,1)
    time_array = Time(mjd_array,format='mjd')

    print(time_array.to_value(format='iso', subfmt='date')

This prints the following as output

    ['2000-01-02' '2000-01-03' '2000-01-04' '2000-01-05' '2000-01-06']

This should cover your use case I believe. Alternatively if I followed what
you were doing I would end print this and that will have both date and time

    print(time_array.to_value(format='iso')

    ['2000-01-02 00:00:00.000' '2000-01-03 00:00:00.000'
     '2000-01-04 00:00:00.000' '2000-01-05 00:00:00.000'
     '2000-01-06 00:00:00.000']


Question:
applying strsplit on data.frame results in unexpected output

I have one dataframe an two functions:

My dataframe:
```
s_words<-c("one,uno","two,dos","three,tres","four,cuatro")
n_nums<-c(10,20,30,40)
df1 <- data.frame(n_nums,s_words)
> df1
  n_nums     s_words
1     10     one,uno
2     20     two,dos
3     30  three,tres
4     40 four,cuatro
```

My two functions:
```
f_op1 <- function(s_input) {
  s_ret = paste0("***",s_input,"***")
  return(s_ret)
}

f_op2 <- function(s_input) {
    a_segments=unlist(strsplit(s_input,split="\\W+"))
    s_eng = a_segments[1]
    s_spa = a_segments[2]
    s_ret = paste0("*",s_eng,"***",s_spa,"*")
  return(s_ret)
}
```

When I apply my functions on the dataframe ....
```
df1$s_op1 <- f_op1(df1$s_words)
df1$s_op2 <- f_op2(df1$s_words)
```

I get this:
```
> df1
  n_nums     s_words             s_op1       s_op2
1     10     one,uno     ***one,uno*** *one***uno*
2     20     two,dos     ***two,dos*** *one***uno*
3     30  three,tres  ***three,tres*** *one***uno*
4     40 four,cuatro ***four,cuatro*** *one***uno*
```

But I need this, something like:
```
> df1
  n_nums     s_words             s_op1           s_op2
1     10     one,uno     ***one,uno***     *one***uno*
2     20     two,dos     ***two,dos***     *two***dos*
3     30  three,tres  ***three,tres***  *three***tres*
4     40 four,cuatro ***four,cuatro*** *four***cuatro*
```

f_op2 is only for demonstration purposes, in reality it is more complex and uses "strsplit". I think there is some problem with strsplit, but I'm not sure, I'm begginer in R language. Thanks in advance for your explanations.

I have searched a lot for help but I can't find the solution.

Explanation: When working with dataframes in R, difficulties were encountered with string manipulation, in particular when attempting to apply a specific string splitting and processing function to each element in the column, the output was not as expected. More appropriate methods need to be explored to ensure that the function acts correctly on each element to achieve the desired output format.

` library(tidyverse) `

Alternative approach - just mutate 2 new columns instead of writing a function
for each column

    df1 %>%
      mutate(s_op1 = str_c("***", s_words, "***")) %>%
      mutate(s_op2 = str_c("*", str_replace(s_words, ",", "***"), "*"))


Question:
Trying to subscribe to oneSignal in a React Native App

Hello I have created a new 17.1 ReactNative app and have incorporated OneSignal.

According to the example it should subscribe but it does not.

I am also testing this on a physical device.

This runs, no errors and i get the prompt the first time to allow notifications.

But the user is not subscribed.

I tried adding
```
OneSignal.sendTag('my app id', true);
```

but got the error sendTag is undefined

my code looks like
```
const App = () => {

 // Remove this method to stop OneSignal Debugging
 OneSignal.Debug.setLogLevel(LogLevel.Verbose);

 // OneSignal Initialization
 OneSignal.initialize("ONESIGNAL_APP_ID");

 // requestPermission will show the native iOS or Android notification permission prompt.
 // We recommend removing the following code and instead using an In-App Message to prompt for notification permission
 OneSignal.Notifications.requestPermission(true);

 // Method for listening for notification clicks
 OneSignal.Notifications.addEventListener('click', (event) => {
   console.log('OneSignal: notification clicked:', event);
 });

 const isDarkMode = useColorScheme() === 'dark';
 const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
 };

 return (
   <SafeAreaView style={backgroundStyle}>
      <StatusBar
         barStyle={isDarkMode ? 'light-content' : 'dark-content'}
         backgroundColor={backgroundStyle.backgroundColor}
      />
    <ScrollView
    contentInsetAdjustmentBehavior="automatic"
    style={backgroundStyle}>
    <Header />
    <View
      style={{
        backgroundColor: isDarkMode ? Colors.black : Colors.white,
      }}>
      <Button
        title="Press me"
        onPress={subscribe}
      />
      <LearnMoreLinks />
    </View>
    </ScrollView>
   </SafeAreaView>
 );
 };
```

Explanation: After initialising OneSignal correctly, you need to call the appropriate method to subscribe the user to receive push notifications. Setting up the correct application ID before initialising OneSignal ensures that the OneSignal service gets valid application credentials and can subscribe users to push notifications for that application.

I use

        OneSignal.setAppId("ONESIGNAL_APP_ID")

instead of

        OneSignal.initialize("ONESIGNAL_APP_ID")

To assign a user / phone to the OneSignal application. Maybe this could help!


Question:
Bot renaming user by user's command

I've been having a problem with some project I 've been doing for the last 3-4 days on discord. It has to do with bots of course and the language I chose is javascript (discord.js).

So, the thing seems kinda simple but I am really stuck in this cause I have only a little experience with javascript.

The bot is supposed to read two values on a message, those values are a string and a number. The bot will simply nickname you the string and that number.

example: User says: john123 40 bot: renaming the user as " John123 | 40 "

The nicknaming command and such are the easy part, the hard one for me is how should I tell the bot "take the string, put it left of the "|", take the number, put it right of the "|" ". I mean the bot can't even read them. Here is my try:

```
var name = message.content.includes(String)
var number = message.content.includes("1"|| "2"|| "3"|| "4"|| "5"|| "6"|| "7"|| "8"|| "9"|| "10"|| "11"|| "12"|| "13"|| "14"|| "15"|| "16"|| "17"|| "18"|| "19"|| "20"|| "21"|| "22"|| "23"|| "24"|| "25"|| "26"|| "27"|| "28"|| "29"|| "30"|| "31"|| "32"|| "33"|| "34"|| "35"|| "36"|| "37"|| "38"|| "39"|| "40")

function theNaming (name, number){
message.member.setNickname('name'|' number')
.then(console.log)
.catch(console.error);
}
```

(the level is supposed to not go higher than 40 so, I thought it may work inside the include)

Explanation: A new nickname needs to be set for a user based on the string and number in the message entered by the user, in the format "String | Number". Functions for character manipulation are required.

> How should I tell the bot "take the string, put it left of the "|", take the
> number, put it right of the "|" ". I mean the bot can't even read them.

The bot can read them if you pass the message in proper format. Your question
should have mentioned that ` name ` and ` number ` will be separated by space.
This is how the bot recognizes ` name ` and ` number ` from entered message.

[ String.split() ](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/String/split) can be use to
split the message string into ` name ` and ` number ` .

    var message = "john123 40";
    var words = message.split(' '); // Using space as the separator.

    console.log(words);

Now ` words ` array contains strings from the message which are separated by
space. And you can access them using their index.

    var name = words[0];
    var number = words[1];

Then pass them as arguments to the naming function like ` theNaming(name,
number); `


Question:
undefined kafka components for Go kafka

I was trying to install one of my go files. But I bumped into this error
```
C:\mygoproject>go install kafkapublisher.go

\#command-line-arguments
.\kafkapublisher.go:8:65: undefined: kafka.Message

.\kafkapublisher.go:10:19: undefined: kafka.NewProducer

.\kafkapublisher.go:10:38: undefined: kafka.ConfigMap

.\kafkapublisher.go:17:31: undefined: kafka.Event

.\kafkapublisher.go:19:26: undefined: kafka.Message
```

On my kafkapublisher.go file, I already imported the kafka dependency:
```
    import (
        "github.com/confluentinc/confluent-kafka-go/kafka"
        "log"
    )
```

even on my `go.mod` file
```
    module mymodule

    go 1.12

    require (
        github.com/aws/aws-lambda-go v1.15.0
        github.com/confluentinc/confluent-kafka-go v1.3.0
    )
```

Explanation: Kafka Go client is based on the C library. Therefore, the relative flag needs to be changed to go to use C libraries for kafka client.

I was facing the same issues.

Kafka Go client is based on the C library. So setting flag ` CGO_ENABLED=1 `
will enable go to use C libraries for kafka client.

Hope it saves someone's time.


Question:
Python requests module with multithread

Currently, I am developing the astrophotometric software for multiple telescopes. For this, I constructed a mother computer connected with multiple telescopes and these telescopes can be controlled by HTTP protocol. For synchronized operation, I am trying to control these multiple telescopes simultaneously with multithreading.
However, when I retrieve image data (110MB for each, ~1.2GB for total) from multiple telescopes (10 telescopes), the data transfer speed is much slower than I expected. For seamless operation, we have 10G connection with the mother computer, and 1G connection with 10 telescopes. I expected ~9Gbps data transfer speed when 10 telescopes transfer the data simultaneously, but only 1.5Gbps achieved.

For simple test, I extracted the part of the code and check the time consumption.
```
import requests
import time
from astropy.time import Time
def request_imagearray(cam):
    client_trans_id = 1
    client_id = 1
    attribute = 'imagearray'

    url = f"{cam.device.base_url}/{attribute}"
    hdrs = {'accept' : 'application/imagebytes'}
    # Make Host: header safe for IPv6
    if(cam.device.address.startswith('[') and cam.device.address.startswith('[::1]')):
        hdrs['Host'] = f'{cam.device.address.split("%")[0]}]'
    pdata = {
            "ClientTransactionID": f"{client_trans_id}",
            "ClientID": f"{client_id}"
            }

    print('START:',Time.now(), cam.device.address)
    start = time.time()
    response = requests.request("GET","%s/%s" % (cam.device.base_url, attribute), params=pdata, headers=hdrs, verify = False)

    print('consumed time:', time.time() - start, cam.device.address)
# %%

unitnumlist = [1,2,3,5,6,7,8,9,10,11]
camlist = []
for unitnum in unitnumlist:
    #camlist.append(mainCamera(unitnum))
    Thread(target = request_imagearray, kwargs = dict(cam = mainCamera(unitnum))).start()
#%%
```

and the output is
```
START: 2024-04-15 07:49:59.067946 10.0.106.6:11111
START: 2024-04-15 07:49:59.382973 10.0.106.7:11112
START: 2024-04-15 07:49:59.541495 10.0.106.8:11113
START: 2024-04-15 07:49:59.647055 10.0.106.10:11111
START: 2024-04-15 07:49:59.788433 10.0.106.11:11111
START: 2024-04-15 07:49:59.897876 10.0.106.12:11111
START: 2024-04-15 07:50:00.009254 10.0.106.13:11111
START: 2024-04-15 07:50:00.157893 10.0.106.14:11111
START: 2024-04-15 07:50:00.347704 10.0.106.16:11111
START: 2024-04-15 07:50:00.544626 10.0.106.9:11111
consumed time: 5.96204686164856 10.0.106.6:11111
consumed time: 7.304373502731323 10.0.106.7:11112
consumed time: 7.58618688583374 10.0.106.8:11113
consumed time: 7.617574453353882 10.0.106.10:11111
consumed time: 7.678117990493774 10.0.106.11:11111
consumed time: 7.76300311088562 10.0.106.12:11111
consumed time: 7.636215925216675 10.0.106.14:11111
consumed time: 7.785021066665649 10.0.106.13:11111
consumed time: 7.338518857955933 10.0.106.9:11111
consumed time: 11.309057235717773 10.0.106.16:11111
```

The comsumed time is much longer than I expected. I expected ~3sec for all data transferred. It seems that multithreads starts to request "request.get" at the same time, but all the data is not transferred at the same time.

Explanation: While the use of multiple threads is intended to achieve parallelism, the frequent creation and destruction of request session objects can introduce additional overheads and reduce overall performance. In contrast, maintaining a pool of request sessions and reusing session objects across multiple threads reduces the overhead of connection establishment and resource allocation.

Use ` requests.Session ` to open one connection instead of reopen it every `
request.request ` .

I would also suggest using [ ThreadPoolExecutor
](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor)
for a more convenient threading interface

    import time
    from concurrent.futures.thread import ThreadPoolExecutor
    from itertools import repeat

    import requests
    from astropy.time import Time

    def request_imagearray(cam, _session):
        client_trans_id = 1
        client_id = 1
        attribute = 'imagearray'

        url = f"{cam.device.base_url}/{attribute}"
        hdrs = {'accept': 'application/imagebytes'}
        # Make Host: header safe for IPv6
        if cam.device.address.startswith('[') and cam.device.address.startswith('[::1]'):
            hdrs['Host'] = f'{cam.device.address.split("%")[0]}]'
        pdata = {
            "ClientTransactionID": f"{client_trans_id}",
            "ClientID": f"{client_id}"
        }

        print('START:', Time.now(), cam.device.address)
        start = time.time()
        response = _session.get(url, params=pdata, headers=hdrs, verify=False)
        print('consumed time:', time.time() - start, cam.device.address)

    unitnumlist = [1, 2, 3, 5, 6, 7, 8, 9, 10, 11]
    camlist = [mainCamera(unitnum) for unitnum in unitnumlist]
    with requests.Session() as session:
        with ThreadPoolExecutor(max_workers=max(len(unitnumlist), 1)) as executor:
            results = executor.map(request_imagearray, camlist, repeat(session))

The assignment to ` results ` is in case ` request_imagearray ` returns
something.


Question:
writing code to determine how many pages will be printed based on the string of p

I am programming a printer like program in python and the question write a function "count_pages(p) that returns how many pages will be printed based on the string p

I tried doing the count_pages function to return how many pages. the arguments and return value are

"5-7, 2" 4

"12-18, 20-20" 8

"18-12, 20-20, 5-6"

I ran into the error of:
```
Traceback (most recent call last):
  File "C:/Users/19013/Desktop/1900/printer_party.py", line 19, in <module>
    print(count_pages('5-7, 2'))  # Expected output: 4
  File "C:/Users/19013/Desktop/1900/printer_party.py", line 11, in count_pages
    start, end = map(int, r.split('-'))
ValueError: not enough values to unpack (expected 2, got 1)
```

```
def count_pages(p):
    # Split the input string by commas
    ranges = p.split(', ')

    # Initialize the total page count
    total_pages = 0

    # Iterate through each range
    for r in ranges:
        # Split the range by hyphen
        start, end = map(int, r.split('-'))

        # Add the number of pages in this range to the total
        total_pages += end - start + 1

    return total_pages

# Example usage
print(count_pages('5-7, 2'))  # Expected output: 4
print(count_pages('12-18, 20-20'))  # Expected output: 8
print(count_pages('18-12, 20-20, 5-6'))  # Expected output: 10
```

Explanation: The problem is to write a Python function `count_pages(p)` to determine how many pages the supplied string will print. The string consists of a range of page numbers separated by hyphens and individual page numbers separated by commas. The function needs to return the total number of pages printed. A way to facilitate string parsing is needed.

If not using ` re ` module then you need to deal explicitly with 2 conditions
that are missed in your code: 1. end comes before start in the range; 2. there
is no range just a single number:

    def count_pages(p):
        # Split the input string by commas
        ranges = p.split(', ')

        # Initialize the total page count
        total_pages = 0

        # Iterate through each range
        for r in ranges:
            # Split the range by hyphen
            if '-' in r:
                start, end = map(int, r.split('-'))
                total_pages += abs(end - start) + 1  # in case end<start

            else:
                total_pages += 1  # no range, just a value

        return total_pages

gives:

    4
    8
    10


Question:
Pydantic - How to subclass a builtin type

I'm trying to make a subclass of timedelta that expects to receive milliseconds instead of seconds, but it's not currently working.

Am I going against the grain? Is there a "right" way to achieve this with Pydantic? Or do I somehow need to tell Pydantic that `MillisecondTimedelta` is just a `timedelta`..

```
from datetime import timedelta

from pydantic import BaseModel

class MillisecondTimedelta(timedelta):
    @classmethod
    def __get_validators__(cls):
        # timedelta expects seconds
        yield lambda v: v / 1000
        yield cls

class MyModel(BaseModel):
    td: MillisecondTimedelta

data = {
    "td": 7598040,
}

print(MyModel(**data))
```

Results in:
```
Traceback (most recent call last):
  File "main.py", line 14, in <module>
    class MyModel(BaseModel):
  File "pydantic/main.py", line 262, in pydantic.main.ModelMetaclass.__new__
  File "pydantic/fields.py", line 315, in pydantic.fields.ModelField.infer
  File "pydantic/fields.py", line 284, in pydantic.fields.ModelField.__init__
  File "pydantic/fields.py", line 362, in pydantic.fields.ModelField.prepare
  File "pydantic/fields.py", line 541, in pydantic.fields.ModelField.populate_validators
  File "pydantic/class_validators.py", line 255, in pydantic.class_validators.prep_validators
  File "pydantic/class_validators.py", line 238, in pydantic.class_validators.make_generic_validator
  File "/usr/lib/python3.8/inspect.py", line 3105, in signature
    return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
  File "/usr/lib/python3.8/inspect.py", line 2854, in from_callable
    return _signature_from_callable(obj, sigcls=cls,
  File "/usr/lib/python3.8/inspect.py", line 2384, in _signature_from_callable
    raise ValueError(
ValueError: no signature found for builtin type <class '__main__.MillisecondTimedelta'>
```

Explanation: Programmer creates a timedelta subclass in Pydantic that expects to receive milliseconds instead of seconds, and wants to resolve an error caused by Pydantic's inability to generate signatures for built-in types. The solution is to recheck the documentation of the referenced built-in function to fill in the missing parts.

As shown [ on the doc page of ` __get_validators__() ` ](https://pydantic-
docs.helpmanual.io/usage/types/#custom-data-types) , you need to yield one or
more validators.

The modified class is reported below; the problem was that Pydantic
understands (for a timedelta field) int and floats as seconds [ (source)
](https://pydantic-docs.helpmanual.io/usage/types/#datetime-types) .

    class MillisecondTimedelta(timedelta):
        @classmethod
        def __get_validators__(cls):
            yield cls.validate

        @classmethod
        def validate(cls, v):
            if any(isinstance(v, t) for t in (int, float)):
                return cls(milliseconds=v)

Now everything should work correctly.

    >>> data = {"td": 1000}
    >>> print(MyModel(**data))
    td=MillisecondTimedelta(seconds=1)

EDIT: Without a custom class and a validator, it's possible to use a function
to edit the value to assign to the class constructor; it's required to
decorate this function, [ as seen here ](https://pydantic-
docs.helpmanual.io/usage/validators/)

    class MyModel(BaseModel):
        td: timedelta

        @validator('td')
        def convert_to_ms(cls, v):
            return v / 1000

Also this solution is working:

    >>> data = {"td": 3000}
    >>> print(MyModel(**data))
    td=datetime.timedelta(seconds=3)