问:
Jest not found while running JEST in docker container
I have created below simple Dockerfile:

```<code>FROM node:16.7.0
WORKDIR /app
COPY . .
RUN npm install
# ENTRYPOINT [ "npm" ]
CMD ["sh", "-c", "tail -f /dev/null"]
</code>```

I have added a cmd line with "tail -f /dev/null" to check exactly what's the issue if I issue npm test inside the container.

As soon as I run npm test inside the container --> It throws me below error

```<code># npm test

> docker-jest@1.0.0 test
> jest --verbose

sh: 1: jest: not found
</code>```

my package.json

```<code>{
  "name": "docker-jest",
  "version": "1.0.0",
  "description": "Package for Jest",
  "scripts": {
    "test": "jest --verbose"
  },
  "Dependencies": {
    "@babel/node": "*",
    "@babel/core": "*",
    "@babel/preset-env": "*",
    "babel-jest": "*",
    "jest": "*"
  },
  "license": "ISC"
}
</code>```

sum.js

```<code>function sum(a, b) {
  return a + b;
}

module.exports = sum;
</code>```

sum.test.js

```<code>const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});
</code>```

Even if I disable CMD and enable ENTRYPOINT and after the build, if I issue:

```<code>docker run -it <imagename> test
</code>```

It throws me the same error, I see the npm install is installing but can't find the jest @ /usr/local/lib/node_modules/ as I see the node modules are deployed in location/usr/local/lib/node_modules/ inside the container, and if I issue jest it says jest not found. If I, run the same without the container it works fine. I mean just in the command line after running npm install and then npm run test.

Can anyone assist me with why I'm getting this error and how to fix it?

-----------UPDATE-------------
Found the fix, it was because of my corrupted package-lock file. When I tested in local without the docker, I somehow corrupted the lock file, and later stage when I build and try to run using docker, the corrupted lock file was causing a whole lot of issues. So I deleted it and again ran thru docker...It's working as expected.

答:
I had the same issue and the fix for me was running npm install -g jest (or yarn global add jest).

To add this to your package.json do the following:

```<code>"scripts: {
  "test": "npm install -g jest && jest --verbose"
},
</code>```

Body:
I have created below simple Dockerfile:

FROM node:16.7.0
WORKDIR /app
COPY . .
RUN npm install
# ENTRYPOINT [ "npm" ]
CMD ["sh", "-c", "tail -f /dev/null"]

I have added a cmd line with "tail -f /dev/null" to check exactly what's the issue if I issue npm test inside the container.

As soon as I run npm test inside the container --> It throws me below error

# npm test

> docker-jest@1.0.0 test
> jest --verbose

sh: 1: jest: not found

my package.json

{
  "name": "docker-jest",
  "version": "1.0.0",
  "description": "Package for Jest",
  "scripts": {
    "test": "jest --verbose"
  },
  "Dependencies": {
    "@babel/node": "*",
    "@babel/core": "*",
    "@babel/preset-env": "*",
    "babel-jest": "*",
    "jest": "*"
  },
  "license": "ISC"
}

sum.js

function sum(a, b) {
  return a + b;
}

module.exports = sum;

sum.test.js

const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

Even if I disable CMD and enable ENTRYPOINT and after the build, if I issue:

docker run -it <imagename> test

It throws me the same error, I see the npm install is installing but can't find the jest @ /usr/local/lib/node_modules/ as I see the node modules are deployed in location/usr/local/lib/node_modules/ inside the container, and if I issue jest it says jest not found. If I, run the same without the container it works fine. I mean just in the command line after running npm install and then npm run test.

Can anyone assist me with why I'm getting this error and how to fix it?

-----------UPDATE-------------
Found the fix, it was because of my corrupted package-lock file. When I tested in local without the docker, I somehow corrupted the lock file, and later stage when I build and try to run using docker, the corrupted lock file was causing a whole lot of issues. So I deleted it and again ran thru docker...It's working as expected.

Body:
I had the same issue and the fix for me was running npm install -g jest (or yarn global add jest).

To add this to your package.json do the following:

"scripts: {
  "test": "npm install -g jest && jest --verbose"
},


来源: stackexchange

问:
How to delete files and directories older than n days in linux
I have a directory named repository which has a number of files and sub directories. I want to find the files and directories which have not been modified since last 14 days so that I can delete those files and directories.
I have wrote this script but it is giving the directory name only </p>

```<code>#!/bin/sh

M2_REPO=/var/lib/jenkins/.m2/repository
echo $M2_REPO
OLDFILES=/var/lib/jenkins/.m2/repository/deleted_artifacts.txt
AGE=14

find "${M2_REPO}" -name '*' -atime +${AGE} -exec dirname {} \; >> ${OLDFILES}
</code>```

答:
I know this is a very old question but FWIW I solved the problem in two steps, first find and delete files older than N days, then find and delete empty directories.  I tried doing both in one step but the delete operation updates the modification time on the file's parent directory, and then the (empty) directory does not match the -mtime criteria any more!  Here's the solution with shell variables:

```<code>age=14
dir="/tmp/dirty"
find "$dir" -mtime "+$age" -delete && find "$dir" -type d -empty -delete
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a directory named repository which has a number of files and sub directories. I want to find the files and directories which have not been modified since last 14 days so that I can delete those files and directories.
I have wrote this script but it is giving the directory name only

#!/bin/sh

M2_REPO=/var/lib/jenkins/.m2/repository
echo $M2_REPO
OLDFILES=/var/lib/jenkins/.m2/repository/deleted_artifacts.txt
AGE=14

find "${M2_REPO}" -name '*' -atime +${AGE} -exec dirname {} \; >> ${OLDFILES}

Body:
I know this is a very old question but FWIW I solved the problem in two steps, first find and delete files older than N days, then find and delete empty directories.  I tried doing both in one step but the delete operation updates the modification time on the file's parent directory, and then the (empty) directory does not match the -mtime criteria any more!  Here's the solution with shell variables:

age=14
dir="/tmp/dirty"
find "$dir" -mtime "+$age" -delete && find "$dir" -type d -empty -delete

ContentLicense: CC BY-SA 4.0


问:
Return a yes or no if a value is matched on another column on a different sheet
I have an excel workbook with 2 sheets. One sheet is called Roster and sheet 2 is called Safety Meeting. On sheet 2(Safety Meeting) is a column with [Id#-name] for those who attended. How do I get “Yes” or “No”return on sheet 1(Roster) for those who attended on sheet 2(Safety Meeting). Also, Roster sheet only has ID# and on Safety Meeting sheet it has ID#andName, but I only need to match the ID number.
I was trying IF and MATCH functions, but having a column with ID numbers and name is throwing me off.</p>

答:
OK, so you have a sheet called Roster, and a sheet called Safety Meeting, and in the second sheet you have a column with ID and name, separated with a hyphen?

Option 1: the Roster sheet has the same names as the Safety Meeting sheet

Combine the ID and name on the Roster sheet in the same format as in Safety Meeting:

```<code>=A:A  & "-" & B:B        for Excel 2010
=@A:A & "-" & @B:B       for current version
Gives e.g. "24601-Valjean"
</code>```

MATCH this combined ID-name in the Safety Meeting column. I have named that column attendees

```<code>=MATCH(  A:A & "-" &  B:B, attendees, 0)    Excel 2010
=XMATCH(@A:A & "-" & @B:B, attendees)       Current
Gives row number if found or #N/A if not found
</code>```

Convert to TRUE/FALSE

```<code>=NOT( ISNA( MATCH( A:A & "-" &  B:B, attendees, 0)))      Excel 2010
=NOT( ISNA( MATCH(@A:A & "-" & @B:B, attendees, 0)))      Current
</code>```

Option 2: the Roster sheet does not have exactly the same names as Safety Meeting

Choose a helper column for the Safety Meeting attendees. This could be on the same sheet, or on a hidden sheet. I have named it attendee_id

Find the - in attendees:

```<code>=FIND("-",  attendees)    Excel 2010
=FIND("-", @attendees)    Current
</code>```

Get the first (that-many minus one) characters from attendees - this is the ID:

```<code>=LEFT( attendees, FIND("-",  attendees) - 1 )     Excel 2010
=LEFT(@attendees, FIND("-", @attendees) - 1 )     Current
</code>```

Look up Roster IDs in this helper column:

```<code>"At meeting?" column
=NOT( ISNA( MATCH( A:A, attendee_id, 0)))    Excel 2010
=NOT( ISNA( MATCH(@A:A, attendee_id, 0)))    Current
</code>```

Observe this didn't work:

The Roster IDs have numeric values, while attendee_id has text value. They must be made to match. Replace A:A with TEXT(A:A,0) to format the number as text.

```<code>=NOT( ISNA( MATCH( TEXT( A:A, 0), attendee_id, 0)))   Excel 2010
=NOT( ISNA( MATCH( TEXT(@A:A, 0), attendee_id, 0)))   Current
</code>```

Body:
OK, so you have a sheet called Roster, and a sheet called Safety Meeting, and in the second sheet you have a column with ID and name, separated with a hyphen?

Option 1: the Roster sheet has the same names as the Safety Meeting sheet

Combine the ID and name on the Roster sheet in the same format as in Safety Meeting:

=A:A  & "-" & B:B        for Excel 2010
=@A:A & "-" & @B:B       for current version
Gives e.g. "24601-Valjean"

MATCH this combined ID-name in the Safety Meeting column. I have named that column attendees

=MATCH(  A:A & "-" &  B:B, attendees, 0)    Excel 2010
=XMATCH(@A:A & "-" & @B:B, attendees)       Current
Gives row number if found or #N/A if not found

Convert to TRUE/FALSE

=NOT( ISNA( MATCH( A:A & "-" &  B:B, attendees, 0)))      Excel 2010
=NOT( ISNA( MATCH(@A:A & "-" & @B:B, attendees, 0)))      Current

Option 2: the Roster sheet does not have exactly the same names as Safety Meeting

Choose a helper column for the Safety Meeting attendees. This could be on the same sheet, or on a hidden sheet. I have named it attendee_id

Find the - in attendees:

=FIND("-",  attendees)    Excel 2010
=FIND("-", @attendees)    Current

Get the first (that-many minus one) characters from attendees - this is the ID:

=LEFT( attendees, FIND("-",  attendees) - 1 )     Excel 2010
=LEFT(@attendees, FIND("-", @attendees) - 1 )     Current

Look up Roster IDs in this helper column:

"At meeting?" column
=NOT( ISNA( MATCH( A:A, attendee_id, 0)))    Excel 2010
=NOT( ISNA( MATCH(@A:A, attendee_id, 0)))    Current

Observe this didn't work:

The Roster IDs have numeric values, while attendee_id has text value. They must be made to match. Replace A:A with TEXT(A:A,0) to format the number as text.

=NOT( ISNA( MATCH( TEXT( A:A, 0), attendee_id, 0)))   Excel 2010
=NOT( ISNA( MATCH( TEXT(@A:A, 0), attendee_id, 0)))   Current


问:
Workarounds to access the Readonly Textbox value on server side when changed through client side script
I have a Date Textbox in each row of a Grid View. As the users must not be allowed to put their own values in the text box, we have set the property as ReadOnly="true". And provided a calender java-script plug-in which sets the Textbox value. Now when I am trying to access the date Textbox on save click, the Textbox value is not persisted.

I knew about this issue and resolution for this too. We need to set the readonly attribute on server side to resolve this issue. But my biggest concern here is, I have placed the Textbox inside the Template field of Grid view. So I need to loop through each row of the Grid view, then get the reference to the date Textbox and then set the readonly attribute to readonly. Looks very cumbersome. Could anybody suggest other alternatives or work arounds.

Code as Below

```<code><asp:GridView ID="gv_sample" runat="server" AutoGenerateColumns="false">
 <Columns>
   <asp:TemplateField>
     <ItemTemplate>
      <table cellpadding="0" cellspacing="0" border="0">
       <tr>
        <td>
         <asp:TextBox runat="server" ID="txtByWhen" ReadOnly="true" CssClass="inputbox" Text='<%#Eval("ByWhen") %>'></asp:TextBox>
       </td>
        <td style="padding-left: 2px;">
         <img src="../Images/dateico.gif" alt="Select a date" title="Select a date"
         onclick="JavaScript:return showCalendar('<%#((GridViewRow)Container).FindControl("txtByWhen").ClientID %>','dd/mm/y');" />
      </td>
     </tr>
    </table>
   </ItemTemplate>
  </asp:TemplateField>
 </Columns>
</asp:GridView>
</code>```

答:
You are right, the solution is to set the Attribute in the Codebehind. (see this question)

You don't have to loop through the GridView, just do it in the RowCreated-Event:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    gv_sample.RowCreated += new GridViewRowEventHandler(gv_sample_RowCreated);
}

void gv_sample_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        TextBox txtByWhen = (TextBox)e.Row.FindControl("txtByWhen");
        txtByWhen.Attributes.Add("readonly", "readonly");
    }
}
</code>```

Body:
I have a Date Textbox in each row of a Grid View. As the users must not be allowed to put their own values in the text box, we have set the property as ReadOnly="true". And provided a calender java-script plug-in which sets the Textbox value. Now when I am trying to access the date Textbox on save click, the Textbox value is not persisted.

I knew about this issue and resolution for this too. We need to set the readonly attribute on server side to resolve this issue. But my biggest concern here is, I have placed the Textbox inside the Template field of Grid view. So I need to loop through each row of the Grid view, then get the reference to the date Textbox and then set the readonly attribute to readonly. Looks very cumbersome. Could anybody suggest other alternatives or work arounds.

Code as Below

<asp:GridView ID="gv_sample" runat="server" AutoGenerateColumns="false">
 <Columns>
   <asp:TemplateField>
     <ItemTemplate>

         <asp:TextBox runat="server" ID="txtByWhen" ReadOnly="true" CssClass="inputbox" Text='<%#Eval("ByWhen") %>'></asp:TextBox>

         <img src="../Images/dateico.gif" alt="Select a date" title="Select a date"
         onclick="JavaScript:return showCalendar('<%#((GridViewRow)Container).FindControl("txtByWhen").ClientID %>','dd/mm/y');" />

   </ItemTemplate>
  </asp:TemplateField>
 </Columns>
</asp:GridView>

Body:
You are right, the solution is to set the Attribute in the Codebehind. (see this question)

You don't have to loop through the GridView, just do it in the RowCreated-Event:

protected void Page_Load(object sender, EventArgs e)
{
    gv_sample.RowCreated += new GridViewRowEventHandler(gv_sample_RowCreated);
}

void gv_sample_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        TextBox txtByWhen = (TextBox)e.Row.FindControl("txtByWhen");
        txtByWhen.Attributes.Add("readonly", "readonly");
    }
}


问:
How to remove multiple non-siblings elements from array by indexes within one pass?
Array.prototype.splice() allows to remove multiple elements from array but if and only if theese elements are siblings. But what if no?

Suppose, we need to remove 2th, 5th and 8th elements from array (cont from 0).

const targetArray = [ "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india" ];
const indexesOfArrayElementWhichMustBeRemoved = [ 2, 5, 8 ];

for (const [ index, element ] of targetArray.entries()) {

    if (indexesOfArrayElementWhichMustBeRemoved.includes(index)) {
        // remove
    }

}
```
<p>Once we removed one element, the array will change and 5th element will not be 5th anymore.</p>
<p>Other approach is make elements empty first, and then remove empty elements:</p>
<pre class="lang-js prettyprint-override"><code>for (const i = 0; i < targetArray.length; i++)  {
    if (indexesOfArrayElementWhichMustBeRemoved.includes(i)) {
        delete targetArray[i]
    }
}

for (const [ index, element ] of targetArray.entries()) {
    if (typeof element === "undefined") {
        targetArray.splice[index, 1]
    }
}
</code>```

But this methodology does not match with "one pass" requirement and also will delete the element which had
"undefined" value initially.

答:
You could use filter, like this:

const sample = ['a', 'b', 'c', 'd', 'e', 'f']
const idx = [1, 3, 5];
const result = sample.filter((x, i) => idx.includes(i));
console.log(result);```
</div>
</div>
</p>
<p>Or if you want to specify which elements to remove, just do <code>!idx.includes(i)</code>.</p>
<p>If mutating the original array is a requirement, then the best technique is usually to iterate over the array backwards, and remove as you go. That changing indexes don't matter as much.</p>
```for(let i=array.length-1;i>=0;i--){
  // if ... array.splice
}
```

Body:
Array.prototype.splice() allows to remove multiple elements from array but if and only if theese elements are siblings. But what if no?

Suppose, we need to remove 2th, 5th and 8th elements from array (cont from 0).

const targetArray = [ "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india" ];
const indexesOfArrayElementWhichMustBeRemoved = [ 2, 5, 8 ];

for (const [ index, element ] of targetArray.entries()) {

    if (indexesOfArrayElementWhichMustBeRemoved.includes(index)) {
        // remove
    }

}

Once we removed one element, the array will change and 5th element will not be 5th anymore.

Other approach is make elements empty first, and then remove empty elements:

for (const i = 0; i < targetArray.length; i++)  {
    if (indexesOfArrayElementWhichMustBeRemoved.includes(i)) {
        delete targetArray[i]
    }
}

for (const [ index, element ] of targetArray.entries()) {
    if (typeof element === "undefined") {
        targetArray.splice[index, 1]
    }
}

But this methodology does not match with "one pass" requirement and also will delete the element which had
"undefined" value initially.

Body:
You could use filter, like this:

const sample = ['a', 'b', 'c', 'd', 'e', 'f']
const idx = [1, 3, 5];
const result = sample.filter((x, i) => idx.includes(i));
console.log(result);

Or if you want to specify which elements to remove, just do !idx.includes(i).

If mutating the original array is a requirement, then the best technique is usually to iterate over the array backwards, and remove as you go. That changing indexes don't matter as much.

for(let i=array.length-1;i>=0;i--){
  // if ... array.splice
}


问:
Why do I get syntax error when I try to do a pip install on CentOS 6?
I'm trying to install a python module called cymysql on a CentOS 6 system by commands like

yum install -y python-setuptools && easy_install pip && pip install cymysql

However I received an Error message saying there're a few lines got SyntaxError: invalid syntax ( see the error code as following)---It actually happened when I run the third command pip install cymysql

```<code>Traceback (most recent call last):
  File "/usr/local/bin/pip", line 11, in <module>
    load_entry_point('pip==21.0', 'console_scripts', 'pip')()
  File "build/bdist.linux-x86_64/egg/pkg_resources/__init__.py", line 561, in load_entry_point
  File "build/bdist.linux-x86_64/egg/pkg_resources/__init__.py", line 2631, in load_entry_point
  File "build/bdist.linux-x86_64/egg/pkg_resources/__init__.py", line 2291, in load
  File "build/bdist.linux-x86_64/egg/pkg_resources/__init__.py", line 2297, in resolve
  File "/usr/local/lib/python2.7/site-packages/pip-21.0-py2.7.egg/pip/_internal/cli/main.py", line 60
    sys.stderr.write(f"ERROR: {exc}")
                               ^
SyntaxError: invalid syntax
</code>```

Not so sure what's happening here, just wondering if anyone can help? (I enclosed the pip file and main.py here but I don't know where is the init.py file).BTW, It's centOS 6 but I have installed the Python 3.6.10 on the server.When I run the command python3.6 -V, I got

python3.6.10

FIY

PIP file Code:

```<code> #!/usr/bin/python
 # EASY-INSTALL-ENTRY-SCRIPT: 'pip==21.0','console_scripts','pip'
 __requires__ = 'pip==21.0'
 import re
 import sys
 from pkg_resources import load_entry_point

 if __name__ == '__main__':
   sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
   sys.exit(
       load_entry_point('pip==21.0', 'console_scripts', 'pip')()  //**THIS IS LINE 11**
   )
</code>```

Line 57 to 62 in Main.py

```<code>try:
    cmd_name, cmd_args = parse_command(args)
except PipError as exc:
    sys.stderr.write(f"ERROR: {exc}")  //**THIS IS LINE 60**
    sys.stderr.write(os.linesep)
    sys.exit(1)
</code>```

答:
Do not go over pip version 20 on a Centos 6 system, otherwise wheels with precompiled c libraries will break.
Long story short, do this first:

```<code>pip install --upgrade pip==20.1.0
</code>```

After that you can install cymysql

Body:
I'm trying to install a python module called cymysql on a CentOS 6 system by commands like

yum install -y python-setuptools && easy_install pip && pip install cymysql

However I received an Error message saying there're a few lines got SyntaxError: invalid syntax ( see the error code as following)---It actually happened when I run the third command pip install cymysql

Traceback (most recent call last):
  File "/usr/local/bin/pip", line 11, in <module>
    load_entry_point('pip==21.0', 'console_scripts', 'pip')()
  File "build/bdist.linux-x86_64/egg/pkg_resources/__init__.py", line 561, in load_entry_point
  File "build/bdist.linux-x86_64/egg/pkg_resources/__init__.py", line 2631, in load_entry_point
  File "build/bdist.linux-x86_64/egg/pkg_resources/__init__.py", line 2291, in load
  File "build/bdist.linux-x86_64/egg/pkg_resources/__init__.py", line 2297, in resolve
  File "/usr/local/lib/python2.7/site-packages/pip-21.0-py2.7.egg/pip/_internal/cli/main.py", line 60
    sys.stderr.write(f"ERROR: {exc}")
                               ^
SyntaxError: invalid syntax

Not so sure what's happening here, just wondering if anyone can help? (I enclosed the pip file and main.py here but I don't know where is the init.py file).BTW, It's centOS 6 but I have installed the Python 3.6.10 on the server.When I run the command python3.6 -V, I got

python3.6.10

FIY

PIP file Code:

 #!/usr/bin/python
 # EASY-INSTALL-ENTRY-SCRIPT: 'pip==21.0','console_scripts','pip'
 __requires__ = 'pip==21.0'
 import re
 import sys
 from pkg_resources import load_entry_point

 if __name__ == '__main__':
   sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
   sys.exit(
       load_entry_point('pip==21.0', 'console_scripts', 'pip')()  //**THIS IS LINE 11**
   )

Line 57 to 62 in Main.py

try:
    cmd_name, cmd_args = parse_command(args)
except PipError as exc:
    sys.stderr.write(f"ERROR: {exc}")  //**THIS IS LINE 60**
    sys.stderr.write(os.linesep)
    sys.exit(1)

Body:
Do not go over pip version 20 on a Centos 6 system, otherwise wheels with precompiled c libraries will break.
Long story short, do this first:

pip install --upgrade pip==20.1.0

After that you can install cymysql


问:
Django Rest Framework Am I doing it right?
I have studied DRF myself and one question bothers me, unfortunately I have no one to ask and this question bothers me all the time. Is writing application logic in views (as in the attached code) a good approach? When sending a query to the server with the intention, for example, to accept an order, I have to update the values from models other than the order or carry out validation of statuses, change the data on their basis. In the first tutorials from which I learned, among others, JustDjango all logic is in the view. However, after writing some code and watching other tutorials, I feel that this is not the right approach. Should not save and update models be done through a serializer? If so, whether through one large serializer or several smaller serializers.</p>
```<code>class ZK_AddUpdateItemWithInstaReservation(APIView):
permission_classes = (IsAuthenticated,)
def post(self, request, *args, **kwargs):
    pzitem_id = request.data.get('pzitem_id')
    ordered_quantity  = request.data.get('ordered_quantity')
    order_id = request.data.get('order_id')
    user_id = request.data.get('user_id')
    item_id = request.data.get('item_id')

    if ordered_quantity:
        if int(ordered_quantity) < 0:
            return Response({'error': 'Próbujesz zamówić ujemną wartość'})
    try:
        item = Item.objects.get(id=item_id)
    except:
        return Response({'error': 'Item with given id does not exists'})
    try:
        order = Order.objects.get(id=order_id)
    except:
        return Response({'error': 'Order with given id does not exist'})
    if order.status not in ['SD', 'WTZ']:
        return Response({'message': 'Nie można zmieniać ilości na zamówionym zamówieniu lub w realizacji'})
    order.status = 'WTZ'
    order.save()
    # ORDERED ITEM WITHOUT PZITEM ON STOCK
    if not pzitem_id:
        # CHECK IF ORDER CONTAINS ORDERITEM
        try:
            orderitem = OrderItem.objects.get(pzitem=None, order=order, item=item)
            prev_ordered_quantity = orderitem.quantity
            # UPDATE ORDER ITEM VALUES
            orderitem.quantity = ordered_quantity
            orderitem.quantity_do_wydania = ordered_quantity
            orderitem.status = 'ZBR'
            orderitem.save()
            # UPDATE ITEM VALUES
            item = Item.objects.get(id=orderitem.item_id)
            prev_item_not_ordered_plus_qty_prevordered = item.quantity_not_ordered + prev_ordered_quantity
            item.quantity_not_ordered = int(prev_item_not_ordered_plus_qty_prevordered) - int(ordered_quantity)
            item.save()
            return Response({'message': 'Zaktualizowano ilość przedmiotu bez rezerwacji stanu'})
        except:
            # IF NOT CREATE ONE
            orderitem = OrderItem.objects.create(user_id=user_id, pzitem=None, item=item, quantity=ordered_quantity, quantity_do_wydania=ordered_quantity, status='ZBR', order=order)
            orderitem.save()
            # UPDATE ITEM VALUES
            item = Item.objects.get(id=orderitem.item_id)
            item.quantity_not_ordered -= int(ordered_quantity)
            item.save()
            return Response({'messsage': 'Dodano nowy przedmiot do zamowienia, status bez rezerwacji stanu.'})
    # ORDERED WITH STOCK
    else:
        try:
            pzitem = PZItem.objects.get(id=pzitem_id)
        except:
            return Response({'error': 'Nie znaleziono pzitem z podanym pzitem_id'})
        # CHECK IF ORDER CONTAINS ORDERITEM
        try:
            orderitem = OrderItem.objects.get(pzitem=pzitem, order=order, item=item)
            prev_ordered_quantity = orderitem.quantity
            if int(ordered_quantity) <= prev_ordered_quantity + orderitem.pzitem.quantity_available_to_order:
                prev_ordered_quantity = orderitem.quantity
                # UPDATE ORDER ITEM VALUES
                orderitem.status = 'ZZR'
                orderitem.quantity = ordered_quantity
                orderitem.quantity_do_wydania = ordered_quantity
                orderitem.save()

                # UPDATE ITEM VALUES
                item = Item.objects.get(id=orderitem.item_id)
                prev_item_not_ordered_plus_qty_prevordered = item.quantity_not_ordered + prev_ordered_quantity
                item.quantity_not_ordered = int(prev_item_not_ordered_plus_qty_prevordered) - int(ordered_quantity)
                item.save()
                # UPDATE PZITEM VALUES
                prev_pzitem_quantity_ordered = int(orderitem.pzitem.quantity_ordered)
                orderitem.pzitem.quantity_ordered =  int(orderitem.pzitem.quantity_ordered) - int(prev_ordered_quantity) + int(ordered_quantity)
                orderitem.pzitem.save()
                return Response({'message': 'Zaktualizowano ilość przedmiotu z rezerwacją stanu'})
            else:
                return Response({'warning': 'Zamówiono więcej niż dostępne'})
        except:
            # IF NOT CREATE ONE
            if int(ordered_quantity) or 0 <= pzitem.quantity_available_to_order:
                orderitem = OrderItem.objects.create(user_id=user_id, pzitem=pzitem, item=item, quantity=ordered_quantity, quantity_do_wydania=ordered_quantity, status='ZZR', order=order)
                orderitem.save()
                # UPDATE ITEM VALUES
                item = Item.objects.get(id=orderitem.item_id)
                item.quantity_not_ordered -= int(ordered_quantity)
                item.save()
                # UPDATE PZITEM VALUES
                orderitem.pzitem.quantity_ordered += int(ordered_quantity)
                orderitem.pzitem.save()
                return Response({'messsage': 'Dodano nowy przedmiot do zamowienia, status zamówiono z rezerwacją stanu.'})
            else:
                return Response({'warning': 'Zamówiono więcej niż dostępne'})
</code>```

答:
In my opinion, there are a few things wrong with the code in your case:

As you wrote, saving the data should be done through the serializer.
In my opinion, it should be one serializer that will write data in one transaction.

In case of errors you should not return status code 200, just one of the 4XX errors

If you want to reduce or enlarge the model field:

```<code>item.quantity_not_ordered -= int(ordered_quantity)
</code>```

u should use
https://docs.djangoproject.com/en/4.0/ref/models/expressions/#avoiding-race-conditions-using-f

You shouldn't use

```<code>try:
  foo()
except:
  pass
</code>```

It is good practice to explicitly catch any exceptions that may occur

Body:
I have studied DRF myself and one question bothers me, unfortunately I have no one to ask and this question bothers me all the time. Is writing application logic in views (as in the attached code) a good approach? When sending a query to the server with the intention, for example, to accept an order, I have to update the values from models other than the order or carry out validation of statuses, change the data on their basis. In the first tutorials from which I learned, among others, JustDjango all logic is in the view. However, after writing some code and watching other tutorials, I feel that this is not the right approach. Should not save and update models be done through a serializer? If so, whether through one large serializer or several smaller serializers.

class ZK_AddUpdateItemWithInstaReservation(APIView):
permission_classes = (IsAuthenticated,)
def post(self, request, *args, **kwargs):
    pzitem_id = request.data.get('pzitem_id')
    ordered_quantity  = request.data.get('ordered_quantity')
    order_id = request.data.get('order_id')
    user_id = request.data.get('user_id')
    item_id = request.data.get('item_id')

    if ordered_quantity:
        if int(ordered_quantity) < 0:
            return Response({'error': 'Próbujesz zamówić ujemną wartość'})
    try:
        item = Item.objects.get(id=item_id)
    except:
        return Response({'error': 'Item with given id does not exists'})
    try:
        order = Order.objects.get(id=order_id)
    except:
        return Response({'error': 'Order with given id does not exist'})
    if order.status not in ['SD', 'WTZ']:
        return Response({'message': 'Nie można zmieniać ilości na zamówionym zamówieniu lub w realizacji'})
    order.status = 'WTZ'
    order.save()
    # ORDERED ITEM WITHOUT PZITEM ON STOCK
    if not pzitem_id:
        # CHECK IF ORDER CONTAINS ORDERITEM
        try:
            orderitem = OrderItem.objects.get(pzitem=None, order=order, item=item)
            prev_ordered_quantity = orderitem.quantity
            # UPDATE ORDER ITEM VALUES
            orderitem.quantity = ordered_quantity
            orderitem.quantity_do_wydania = ordered_quantity
            orderitem.status = 'ZBR'
            orderitem.save()
            # UPDATE ITEM VALUES
            item = Item.objects.get(id=orderitem.item_id)
            prev_item_not_ordered_plus_qty_prevordered = item.quantity_not_ordered + prev_ordered_quantity
            item.quantity_not_ordered = int(prev_item_not_ordered_plus_qty_prevordered) - int(ordered_quantity)
            item.save()
            return Response({'message': 'Zaktualizowano ilość przedmiotu bez rezerwacji stanu'})
        except:
            # IF NOT CREATE ONE
            orderitem = OrderItem.objects.create(user_id=user_id, pzitem=None, item=item, quantity=ordered_quantity, quantity_do_wydania=ordered_quantity, status='ZBR', order=order)
            orderitem.save()
            # UPDATE ITEM VALUES
            item = Item.objects.get(id=orderitem.item_id)
            item.quantity_not_ordered -= int(ordered_quantity)
            item.save()
            return Response({'messsage': 'Dodano nowy przedmiot do zamowienia, status bez rezerwacji stanu.'})
    # ORDERED WITH STOCK
    else:
        try:
            pzitem = PZItem.objects.get(id=pzitem_id)
        except:
            return Response({'error': 'Nie znaleziono pzitem z podanym pzitem_id'})
        # CHECK IF ORDER CONTAINS ORDERITEM
        try:
            orderitem = OrderItem.objects.get(pzitem=pzitem, order=order, item=item)
            prev_ordered_quantity = orderitem.quantity
            if int(ordered_quantity) <= prev_ordered_quantity + orderitem.pzitem.quantity_available_to_order:
                prev_ordered_quantity = orderitem.quantity
                # UPDATE ORDER ITEM VALUES
                orderitem.status = 'ZZR'
                orderitem.quantity = ordered_quantity
                orderitem.quantity_do_wydania = ordered_quantity
                orderitem.save()

                # UPDATE ITEM VALUES
                item = Item.objects.get(id=orderitem.item_id)
                prev_item_not_ordered_plus_qty_prevordered = item.quantity_not_ordered + prev_ordered_quantity
                item.quantity_not_ordered = int(prev_item_not_ordered_plus_qty_prevordered) - int(ordered_quantity)
                item.save()
                # UPDATE PZITEM VALUES
                prev_pzitem_quantity_ordered = int(orderitem.pzitem.quantity_ordered)
                orderitem.pzitem.quantity_ordered =  int(orderitem.pzitem.quantity_ordered) - int(prev_ordered_quantity) + int(ordered_quantity)
                orderitem.pzitem.save()
                return Response({'message': 'Zaktualizowano ilość przedmiotu z rezerwacją stanu'})
            else:
                return Response({'warning': 'Zamówiono więcej niż dostępne'})
        except:
            # IF NOT CREATE ONE
            if int(ordered_quantity) or 0 <= pzitem.quantity_available_to_order:
                orderitem = OrderItem.objects.create(user_id=user_id, pzitem=pzitem, item=item, quantity=ordered_quantity, quantity_do_wydania=ordered_quantity, status='ZZR', order=order)
                orderitem.save()
                # UPDATE ITEM VALUES
                item = Item.objects.get(id=orderitem.item_id)
                item.quantity_not_ordered -= int(ordered_quantity)
                item.save()
                # UPDATE PZITEM VALUES
                orderitem.pzitem.quantity_ordered += int(ordered_quantity)
                orderitem.pzitem.save()
                return Response({'messsage': 'Dodano nowy przedmiot do zamowienia, status zamówiono z rezerwacją stanu.'})
            else:
                return Response({'warning': 'Zamówiono więcej niż dostępne'})

Body:
In my opinion, there are a few things wrong with the code in your case:

As you wrote, saving the data should be done through the serializer.
In my opinion, it should be one serializer that will write data in one transaction.

In case of errors you should not return status code 200, just one of the 4XX errors

If you want to reduce or enlarge the model field:

item.quantity_not_ordered -= int(ordered_quantity)

u should use
https://docs.djangoproject.com/en/4.0/ref/models/expressions/#avoiding-race-conditions-using-f

You shouldn't use

try:
  foo()
except:
  pass

It is good practice to explicitly catch any exceptions that may occur


问:
Setting center of borderpane form another controller class
I have Borderpane as homePane (its fxml file is home.fxml). At first in center of homePane i have a HBox which contains a button   called delivery. When the user clicks this button, the center of homePane switchs to display the list of customers.
It works !

The code of homeController :

```<code>public class HomeController {

@FXML
private BorderPane homePane;

@FXML
public void deliveryBtnClicked (){
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/fragments/customers.fxml"));
    homePane.getChildren().remove(homePane.getCenter());
    try {
        Pane pane = loader.load();
        homePane.setCenter(pane);

    }catch (IOException e){
        System.out.println(e.getMessage());
    }
}

public BorderPane getHomePane() {
    return homePane;
}
}
</code>```

The new Pane contains the table of customers and a button called order. It has own Controller :

```<code>public class CustomerController {

    @FXML
    public void loadOrderView() throws IOException {
        Customer customer = customerTable.getSelectionModel().getSelectedItem();
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("/home.fxml"));
        loader.load();

        HomeController homeController =  loader.getController();
        BorderPane homePane = homeController.getHomePane();

        homePane.getChildren().remove(homePane.getCenter());
        System.out.println(homePane.getCenter());
        FXMLLoader loader1 = new FXMLLoader(getClass().getResource("/fragments/order.fxml"));
        Pane orderView = loader1.load();
        homePane.setCenter(orderView);
        System.out.println(homePane.getCenter());
     }
}
</code>```

When user clicks the button order, the order-view have to be loaded in the center of homePane.
the print command shows that the homePane center after removed is null and then after loaded gets new view.

```<code>null
AnchorPane@755b1503
</code>```

But in running Programm its doen't show the order view. I have set onAction of button order to loadOrderView. This is definitive not the problem.

答:
You can navigate the scene graph as shown in another answer, and this is a perfectly good solution for a small application.

For larger applications, where you might need more flexibility in terms of the ability to change, e.g., how the layout is managed, consider using a MVC/MVVM type of approach. Start with a model class that maintains the current view state:

```<code>public class ViewModel {

    public enum View {
        CUSTOMER(ViewModel.class.getResource("/fragments/customer.fxml")),
        ORDER(ViewModel.class.getResource("/fragments/order.fxml"));

        private final URL resource ;

        private View(URL resource) {
            this.resource = resource ;
        }

        public URL getResource() {
            return resource ;
        }
    }

    private final ObjectProperty<View> currentView = new SimpleObjectProperty<>();

    public ObjectProperty<View> currentViewProperty() {
        return currentView ;
    }

    public final View getCurrentView() {
        return currentViewProperty().get();
    }

    public final void setCurrentView(View currentView) {
        currentViewProperty().set(currentView);
    }
}
</code>```

Make your controllers implement an interface that allows them to have a reference to a ViewModel:

```<code>public interface ViewModelObserver {
    public void setViewModel(ViewModel model);
}
</code>```

Your HomeController, assuming it is loaded once and the home page is always shown, can create a single instance of the ViewModel, observe it, update the border pane, and pass the instance to other controllers when they are loaded:

```<code>public class HomeController  {

    private final ViewModel viewModel = new ViewModel();

    @FXML
    private BorderPane homePane;

    @FMXL
    public void initialize() {
        viewModel.currentViewProperty().addListener((obs, oldView, newView) -> {
            try {
                FXMLLoader loader = new FXMLLoader(newView.getResource());
                Parent root = loader.load();
                Object controller = loader.getController();
                if (controller instanceof ViewModelObserver) {
                    ((ViewModelObserver)controller).setViewModel(viewModel);
                }
                homePane.setCenter(root);
            } catch (Exception exc) {
                exc.printStackTrace();
            }
        });
    }

    @FXML
    public void deliveryBtnClicked (){
        viewModel.setCurrentView(ViewModel.View.CUSTOMER);
    }

}
</code>```

Then make the controllers for the FXML "fragments" implement ViewModelObserver. They can simply update the current view, and the home controller will load and display it:

```<code>public class CustomerController implements ViewModelObserver {

    private ViewModel viewModel ;

    @Override
    public void setViewModel(ViewModel viewModel) {
        this.viewModel = viewModel ;
    }

    @FXML
    public void loadOrderView() throws IOException {
        viewModel.setCurrentView(ViewModel.View.ORDER);
     }
}
</code>```

You may need to include other properties in your view model, e.g. to give access to the Customer instance etc.

Body:
I have Borderpane as homePane (its fxml file is home.fxml). At first in center of homePane i have a HBox which contains a button   called delivery. When the user clicks this button, the center of homePane switchs to display the list of customers.
It works !

The code of homeController :

public class HomeController {

@FXML
private BorderPane homePane;

@FXML
public void deliveryBtnClicked (){
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/fragments/customers.fxml"));
    homePane.getChildren().remove(homePane.getCenter());
    try {
        Pane pane = loader.load();
        homePane.setCenter(pane);

    }catch (IOException e){
        System.out.println(e.getMessage());
    }
}

public BorderPane getHomePane() {
    return homePane;
}
}

The new Pane contains the table of customers and a button called order. It has own Controller :

public class CustomerController {

    @FXML
    public void loadOrderView() throws IOException {
        Customer customer = customerTable.getSelectionModel().getSelectedItem();
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("/home.fxml"));
        loader.load();

        HomeController homeController =  loader.getController();
        BorderPane homePane = homeController.getHomePane();

        homePane.getChildren().remove(homePane.getCenter());
        System.out.println(homePane.getCenter());
        FXMLLoader loader1 = new FXMLLoader(getClass().getResource("/fragments/order.fxml"));
        Pane orderView = loader1.load();
        homePane.setCenter(orderView);
        System.out.println(homePane.getCenter());
     }
}

When user clicks the button order, the order-view have to be loaded in the center of homePane.
the print command shows that the homePane center after removed is null and then after loaded gets new view.

null
AnchorPane@755b1503

But in running Programm its doen't show the order view. I have set onAction of button order to loadOrderView. This is definitive not the problem.

Body:
You can navigate the scene graph as shown in another answer, and this is a perfectly good solution for a small application.

For larger applications, where you might need more flexibility in terms of the ability to change, e.g., how the layout is managed, consider using a MVC/MVVM type of approach. Start with a model class that maintains the current view state:

public class ViewModel {

    public enum View {
        CUSTOMER(ViewModel.class.getResource("/fragments/customer.fxml")),
        ORDER(ViewModel.class.getResource("/fragments/order.fxml"));

        private final URL resource ;

        private View(URL resource) {
            this.resource = resource ;
        }

        public URL getResource() {
            return resource ;
        }
    }

    private final ObjectProperty<View> currentView = new SimpleObjectProperty<>();

    public ObjectProperty<View> currentViewProperty() {
        return currentView ;
    }

    public final View getCurrentView() {
        return currentViewProperty().get();
    }

    public final void setCurrentView(View currentView) {
        currentViewProperty().set(currentView);
    }
}

Make your controllers implement an interface that allows them to have a reference to a ViewModel:

public interface ViewModelObserver {
    public void setViewModel(ViewModel model);
}

Your HomeController, assuming it is loaded once and the home page is always shown, can create a single instance of the ViewModel, observe it, update the border pane, and pass the instance to other controllers when they are loaded:

public class HomeController  {

    private final ViewModel viewModel = new ViewModel();

    @FXML
    private BorderPane homePane;

    @FMXL
    public void initialize() {
        viewModel.currentViewProperty().addListener((obs, oldView, newView) -> {
            try {
                FXMLLoader loader = new FXMLLoader(newView.getResource());
                Parent root = loader.load();
                Object controller = loader.getController();
                if (controller instanceof ViewModelObserver) {
                    ((ViewModelObserver)controller).setViewModel(viewModel);
                }
                homePane.setCenter(root);
            } catch (Exception exc) {
                exc.printStackTrace();
            }
        });
    }

    @FXML
    public void deliveryBtnClicked (){
        viewModel.setCurrentView(ViewModel.View.CUSTOMER);
    }

}

Then make the controllers for the FXML "fragments" implement ViewModelObserver. They can simply update the current view, and the home controller will load and display it:

public class CustomerController implements ViewModelObserver {

    private ViewModel viewModel ;

    @Override
    public void setViewModel(ViewModel viewModel) {
        this.viewModel = viewModel ;
    }

    @FXML
    public void loadOrderView() throws IOException {
        viewModel.setCurrentView(ViewModel.View.ORDER);
     }
}

You may need to include other properties in your view model, e.g. to give access to the Customer instance etc.


问:
Switch tabs using Selenium WebDriver with Java
Using Selenium WebDriver with Java.
I am trying to automate a functionality where I have to open a new tab do some operations there and come back to previous tab (Parent).
I used switch handle but it's not working.
And one strange thing the two tabs are having same window handle due to which I am not able to switch between tabs.

However when I am trying with different Firefox windows it works, but for tab it's not working.

How can I switch tabs?
Or, how can I switch tabs without using window handle as window handle is same of both tabs in my case?

(I have observed that when you open different tabs in same window, window handle remains same)

答:
String mainWindow = driver.getWindowHandle();
seleniumHelper.switchToChildWindow();
..
..//your assertion steps

seleniumHelper.switchToWindow(mainWindow);


问:
Laravel - Non-static method should not be called statically
I have recently started using laravel for work and I boumped into many issues I cannot stil solve.
I have looked over many many topics and already anwered questions but none of those have helped me with my issue
So, I get this error trying to do 'php artisan serve'
"Non-static method Illuminate\Cache\RateLimiter::for() should not be called statically"

So I went up looking at the code, this is the RateLimiter.php code that gives me the error

```<code>protected function configureRateLimiting()
   {
       RateLimiter::for('api', function (Request $request) {
           return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
       });
   }
</code>```

the error is at the 2nd line of this code, in the RateLimiter:: etc

I get those errors in the CMD

app/Providers/RouteServiceProvider.php:59
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Non-static method Illuminate\Cache\RateLimiter::for() should not be called statically", "myPathToTheProject/app/Providers/RouteServiceProvider.php", [])

app/Providers/RouteServiceProvider.php:38
App\Providers\RouteServiceProvider::configureRateLimiting()

the function is called like this
$this->configureRateLimiting();

hoping you can help me, I will give more infos if are needed

答:
I found out the problem. You need to import the facade, and when you auto-import, it tends to get the wrong package.
Look at the imports. If you find:

```<code>use Illuminate\Cache\RateLimiter;
</code>```

You should replace with

```<code>use Illuminate\Support\Facades\RateLimiter;
</code>```

Worked for me!

Body:
I have recently started using laravel for work and I boumped into many issues I cannot stil solve.
I have looked over many many topics and already anwered questions but none of those have helped me with my issue
So, I get this error trying to do 'php artisan serve'
"Non-static method Illuminate\Cache\RateLimiter::for() should not be called statically"

So I went up looking at the code, this is the RateLimiter.php code that gives me the error

protected function configureRateLimiting()
   {
       RateLimiter::for('api', function (Request $request) {
           return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
       });
   }

the error is at the 2nd line of this code, in the RateLimiter:: etc

I get those errors in the CMD

app/Providers/RouteServiceProvider.php:59
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Non-static method Illuminate\Cache\RateLimiter::for() should not be called statically", "myPathToTheProject/app/Providers/RouteServiceProvider.php", [])

app/Providers/RouteServiceProvider.php:38
App\Providers\RouteServiceProvider::configureRateLimiting()

the function is called like this
$this->configureRateLimiting();

hoping you can help me, I will give more infos if are needed

Body:
I found out the problem. You need to import the facade, and when you auto-import, it tends to get the wrong package.
Look at the imports. If you find:

use Illuminate\Cache\RateLimiter;

You should replace with

use Illuminate\Support\Facades\RateLimiter;

Worked for me!


问:
How to take top 3 elements in each group using Entity Framework
I have the data in the source table.

And I want to get this kind of result in list using lambda expression and Entity Framework. I don't know how to do it. I need to get top 3 rows in for each CategoryId.

Probably using something like this:

```<code>context.GroupBy(x => x.CategoryId)
       .Select(group => new {
                                CategoryId = group.Key,
                                NameId = group.Select(x => x.NameId),
                                group.OrderByDescending(e => e.Count).Take(3)
                            })
       .ToListAsync()
</code>```

答:
```<code>var list = context
    .GroupBy(x => x.CategoryId)
    .SelectMany(group => group.OrderByDescending(e => e.Count).Take(3))
    .OrderByDescending(e => e.Count)
    .ToListAsync();
</code>```

If you want an anonymous type:

```<code>var list = context
    .GroupBy(x => x.CategoryId)
    .SelectMany(group => group.OrderByDescending(e => e.Count).Take(3))
    .Select(x => new
    {
        x.CategoryId,
        x.NameId,
        x.Count
    })
    .OrderByDescending(x => x.Count)
    .ToListAsync();
</code>```

Body:
I have the data in the source table.

And I want to get this kind of result in list using lambda expression and Entity Framework. I don't know how to do it. I need to get top 3 rows in for each CategoryId.

Probably using something like this:

context.GroupBy(x => x.CategoryId)
       .Select(group => new {
                                CategoryId = group.Key,
                                NameId = group.Select(x => x.NameId),
                                group.OrderByDescending(e => e.Count).Take(3)
                            })
       .ToListAsync()

Body:
var list = context
    .GroupBy(x => x.CategoryId)
    .SelectMany(group => group.OrderByDescending(e => e.Count).Take(3))
    .OrderByDescending(e => e.Count)
    .ToListAsync();

If you want an anonymous type:

var list = context
    .GroupBy(x => x.CategoryId)
    .SelectMany(group => group.OrderByDescending(e => e.Count).Take(3))
    .Select(x => new
    {
        x.CategoryId,
        x.NameId,
        x.Count
    })
    .OrderByDescending(x => x.Count)
    .ToListAsync();


问:
Testing recursive calls in Jest
I'm currently testing a Fibonacci algorithm that uses memoization+recursion.

```<code>function memoization(num, hash = {'0': 0, '1':1}) {
  if (!hash.hasOwnProperty(num)) {
    hash[num] = memoization(num-1,hash) + memoization(num-2,hash);
  }
  return hash[num];
}
</code>```

I want to test the memoization aspect of the function in Jest to ensure that the function is properly using the hash and not doing redundant work:

```<code>test('is never run on the same input twice', ()=>{
    fib.memoization = jest.fn(fib.memoization);
    fib.memoization(30);
    expect(allUniqueValues(fib.memoization.mock.calls)).toBeTruthy();
  });
</code>```

However, the mock.calls only reports this function being called once with the initial parameter value and doesn't keep track of the additional recursive calls. Any ideas?

答:
I've found out that it works as expected if you turn memoization() into an arrow function:

fib.js

```<code>// Don't import module in itself

export const memoization = (num, hash = { '0': 0, '1': 1 }) => {
    if (hash[num - 1] === undefined) {
        hash[num - 1] = memoization(num - 1, hash); // <= call memoization as you would, without module
    }
    return hash[num - 1] + hash[num - 2];
};
</code>```

fib.test.js

```<code>describe('memoization', () => {
    it('should memoize correctly', () => {
        const mock = jest.spyOn(fib, 'memoization');

        const result = fib.memoization(50);
        expect(result).toBe(12586269025);
        expect(mock).toHaveBeenCalledTimes(49);

        mock.mockRestore();
    });
});
</code>```

Title: Testing recursive calls in Jest

Body:
I'm currently testing a Fibonacci algorithm that uses memoization+recursion.

function memoization(num, hash = {'0': 0, '1':1}) {
  if (!hash.hasOwnProperty(num)) {
    hash[num] = memoization(num-1,hash) + memoization(num-2,hash);
  }
  return hash[num];
}

I want to test the memoization aspect of the function in Jest to ensure that the function is properly using the hash and not doing redundant work:

test('is never run on the same input twice', ()=>{
    fib.memoization = jest.fn(fib.memoization);
    fib.memoization(30);
    expect(allUniqueValues(fib.memoization.mock.calls)).toBeTruthy();
  });

However, the mock.calls only reports this function being called once with the initial parameter value and doesn't keep track of the additional recursive calls. Any ideas?

Body:
I've found out that it works as expected if you turn memoization() into an arrow function:

fib.js

// Don't import module in itself

export const memoization = (num, hash = { '0': 0, '1': 1 }) => {
    if (hash[num - 1] === undefined) {
        hash[num - 1] = memoization(num - 1, hash); // <= call memoization as you would, without module
    }
    return hash[num - 1] + hash[num - 2];
};

fib.test.js

describe('memoization', () => {
    it('should memoize correctly', () => {
        const mock = jest.spyOn(fib, 'memoization');

        const result = fib.memoization(50);
        expect(result).toBe(12586269025);
        expect(mock).toHaveBeenCalledTimes(49);

        mock.mockRestore();
    });
});


问:
How to add the results of chi-square calculations and Fisher's exact test to the table in R
Let's take reproducible example from last my question

```<code>AE=structure(list(TRTGROUP_E1_C18 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L), AETERM = c("increase in lymphocytes", "increase in lymphocytes",
"increase in abs. lymphocytes", "increase in lymphocytes", "decrease in abs. neutrophils",
"decrease in neutrophils", "decrease in abs. monocytes", "decrease in monocytes",
"increase in lymphocytes", "decrease in hemoglobin", "decrease in neutrophils",
"decrease in abs. monocytes ")), class = "data.frame", row.names = c(NA,
-12L))
</code>```

I can build frequency tables as I was told.

```<code>library(table1)

table1(~AETERM | TRTGROUP_E1_C18, data = AE) This is good format.
</code>```

However, now I need to calculate the p-value between treatment groups(TRTGROUP_E1_C18) for adverse events. For each AE, I can calculate using  simple commands fisher.test() or chisq.test(), but it's cumbersome and inconvenient. That is. First, for example, I need to calculate the statistics between groups for decrease abs.monocytes, then dy decrease in abs. neutrophils and so on, the list of AEs can be overwhelming. How to make these stat tests were calculated for all AEs between groups at once, so that for each AE, I do not write a separate line manually and copy the result to a table? And how to make 2 columns appear when generating a table (a very convenient format for me), one with the chi-square calculation, and the other with Fisher's exact test.
Like this desired result.

Any help is very important

答:
If you're looking for the Chi-squared and Fisher tests of all pairs of values in AETERM, then the best way would probably be to write a function to do that.  Here's what I would suggest.  This makes the original table and produces the relevant tests for all pairs of values.

AE=structure(list(TRTGROUP_E1_C18 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                      1L, 2L, 2L, 2L, 2L),
                  AETERM = c("increase in lymphocytes", "increase in lymphocytes",
                            "increase in abs. lymphocytes", "increase in lymphocytes", "decrease in abs. neutrophils",
                            "decrease in neutrophils", "decrease in abs. monocytes", "decrease in monocytes",
                            "increase in lymphocytes", "decrease in hemoglobin", "decrease in neutrophils",
                            "decrease in abs. monocytes")), class = "data.frame", row.names = c(NA,
                                                                                -12L))

library(table1)
#>
#> Attaching package: 'table1'
#> The following objects are masked from 'package:base':
#>
#>     units, units<-
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

y <- "AETERM"
x <- "TRTGROUP_E1_C18"
test_combs <- function(x, y, data, ...){
  xvals <- data[[x]]
  yvals <- data[[y]]
  form <- as.formula(paste0("~", y, " | ", x))
  tab <- table1(form, data=data)
  uny <- unique(yvals)
  combs <- combn(length(uny), 2)
  l <- lapply(1:ncol(combs), function(i){
    ind <- which(yvals %in% c(uny[combs[1,i]], uny[combs[2,i]]))
    if(sd(xvals[ind]) != 0 & !is.na(sd(xvals[ind]))){
      x2 <- chisq.test(table(xvals[ind], yvals[ind]))[c("estimate", "p.value")]
      f <- fisher.test(table(xvals[ind], yvals[ind]))[c("estimate", "p.value")]
      x2 <- sapply(x2, function(x)ifelse(is.null(x), NA, x))
      f <- sapply(f, function(x)ifelse(is.null(x), NA, x))
      tibble(lev1 = uny[combs[1,i]],
                 lev2 = uny[combs[2,i]],
                 X2_stat = x2[1],
                 x2_pval = x2[2],
                 Fisher_stat = f[1],
                 Fisher_pval = f[2])
    }else{
      tibble(lev1 = uny[combs[1,i]],
                 lev2 = uny[combs[2,i]],
                 X2_stat = NA,
                 x2_pval = NA,
                 Fisher_stat = NA,
                 Fisher_pval = NA)
    }
  })
  return(list(table = tab,
         tests = as.data.frame(bind_rows(l))))

}
test_combs("TRTGROUP_E1_C18", "AETERM", AE)
#> $table
#>
#> $tests
#>                            lev1                         lev2 X2_stat  x2_pval
#> 1       increase in lymphocytes increase in abs. lymphocytes      NA 1.000000
#> 2       increase in lymphocytes decrease in abs. neutrophils      NA 1.000000
#> 3       increase in lymphocytes      decrease in neutrophils      NA 1.000000
#> 4       increase in lymphocytes   decrease in abs. monocytes      NA 1.000000
#> 5       increase in lymphocytes        decrease in monocytes      NA 1.000000
#> 6       increase in lymphocytes       decrease in hemoglobin      NA 0.819477
#> 7  increase in abs. lymphocytes decrease in abs. neutrophils      NA       NA
#> 8  increase in abs. lymphocytes      decrease in neutrophils      NA 1.000000
#> 9  increase in abs. lymphocytes   decrease in abs. monocytes      NA 1.000000
#> 10 increase in abs. lymphocytes        decrease in monocytes      NA       NA
#> 11 increase in abs. lymphocytes       decrease in hemoglobin      NA 1.000000
#> 12 decrease in abs. neutrophils      decrease in neutrophils      NA 1.000000
#> 13 decrease in abs. neutrophils   decrease in abs. monocytes      NA 1.000000
#> 14 decrease in abs. neutrophils        decrease in monocytes      NA       NA
#> 15 decrease in abs. neutrophils       decrease in hemoglobin      NA 1.000000
#> 16      decrease in neutrophils   decrease in abs. monocytes      NA 1.000000
#> 17      decrease in neutrophils        decrease in monocytes      NA 1.000000
#> 18      decrease in neutrophils       decrease in hemoglobin      NA 1.000000
#> 19   decrease in abs. monocytes        decrease in monocytes      NA 1.000000
#> 20   decrease in abs. monocytes       decrease in hemoglobin      NA 1.000000
#> 21        decrease in monocytes       decrease in hemoglobin      NA 1.000000
#>    Fisher_stat Fisher_pval
#> 1          Inf         1.0
#> 2          Inf         1.0
#> 3     0.408248         1.0
#> 4     0.408248         1.0
#> 5          Inf         1.0
#> 6     0.000000         0.4
#> 7           NA          NA
#> 8     0.000000         1.0
#> 9     0.000000         1.0
#> 10          NA          NA
#> 11    0.000000         1.0
#> 12         Inf         1.0
#> 13    0.000000         1.0
#> 14          NA          NA
#> 15         Inf         1.0
#> 16    1.000000         1.0
#> 17         Inf         1.0
#> 18    0.000000         1.0
#> 19    0.000000         1.0
#> 20         Inf         1.0
#> 21    0.000000         1.0
```

Created on 2022-02-10 by the reprex package (v2.0.1)

Body:
Let's take reproducible example from last my question

AE=structure(list(TRTGROUP_E1_C18 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L), AETERM = c("increase in lymphocytes", "increase in lymphocytes",
"increase in abs. lymphocytes", "increase in lymphocytes", "decrease in abs. neutrophils",
"decrease in neutrophils", "decrease in abs. monocytes", "decrease in monocytes",
"increase in lymphocytes", "decrease in hemoglobin", "decrease in neutrophils",
"decrease in abs. monocytes ")), class = "data.frame", row.names = c(NA,
-12L))

I can build frequency tables as I was told.

library(table1)

table1(~AETERM | TRTGROUP_E1_C18, data = AE) This is good format.

However, now I need to calculate the p-value between treatment groups(TRTGROUP_E1_C18) for adverse events. For each AE, I can calculate using  simple commands fisher.test() or chisq.test(), but it's cumbersome and inconvenient. That is. First, for example, I need to calculate the statistics between groups for decrease abs.monocytes, then dy decrease in abs. neutrophils and so on, the list of AEs can be overwhelming. How to make these stat tests were calculated for all AEs between groups at once, so that for each AE, I do not write a separate line manually and copy the result to a table? And how to make 2 columns appear when generating a table (a very convenient format for me), one with the chi-square calculation, and the other with Fisher's exact test.
Like this desired result.

Any help is very important

Body:
If you're looking for the Chi-squared and Fisher tests of all pairs of values in AETERM, then the best way would probably be to write a function to do that.  Here's what I would suggest.  This makes the original table and produces the relevant tests for all pairs of values.

AE=structure(list(TRTGROUP_E1_C18 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                      1L, 2L, 2L, 2L, 2L),
                  AETERM = c("increase in lymphocytes", "increase in lymphocytes",
                            "increase in abs. lymphocytes", "increase in lymphocytes", "decrease in abs. neutrophils",
                            "decrease in neutrophils", "decrease in abs. monocytes", "decrease in monocytes",
                            "increase in lymphocytes", "decrease in hemoglobin", "decrease in neutrophils",
                            "decrease in abs. monocytes")), class = "data.frame", row.names = c(NA,
                                                                                -12L))

library(table1)
#>
#> Attaching package: 'table1'
#> The following objects are masked from 'package:base':
#>
#>     units, units<-
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

y <- "AETERM"
x <- "TRTGROUP_E1_C18"
test_combs <- function(x, y, data, ...){
  xvals <- data[[x]]
  yvals <- data[[y]]
  form <- as.formula(paste0("~", y, " | ", x))
  tab <- table1(form, data=data)
  uny <- unique(yvals)
  combs <- combn(length(uny), 2)
  l <- lapply(1:ncol(combs), function(i){
    ind <- which(yvals %in% c(uny[combs[1,i]], uny[combs[2,i]]))
    if(sd(xvals[ind]) != 0 & !is.na(sd(xvals[ind]))){
      x2 <- chisq.test(table(xvals[ind], yvals[ind]))[c("estimate", "p.value")]
      f <- fisher.test(table(xvals[ind], yvals[ind]))[c("estimate", "p.value")]
      x2 <- sapply(x2, function(x)ifelse(is.null(x), NA, x))
      f <- sapply(f, function(x)ifelse(is.null(x), NA, x))
      tibble(lev1 = uny[combs[1,i]],
                 lev2 = uny[combs[2,i]],
                 X2_stat = x2[1],
                 x2_pval = x2[2],
                 Fisher_stat = f[1],
                 Fisher_pval = f[2])
    }else{
      tibble(lev1 = uny[combs[1,i]],
                 lev2 = uny[combs[2,i]],
                 X2_stat = NA,
                 x2_pval = NA,
                 Fisher_stat = NA,
                 Fisher_pval = NA)
    }
  })
  return(list(table = tab,
         tests = as.data.frame(bind_rows(l))))

}
test_combs("TRTGROUP_E1_C18", "AETERM", AE)
#> $table
#>
#> $tests
#>                            lev1                         lev2 X2_stat  x2_pval
#> 1       increase in lymphocytes increase in abs. lymphocytes      NA 1.000000
#> 2       increase in lymphocytes decrease in abs. neutrophils      NA 1.000000
#> 3       increase in lymphocytes      decrease in neutrophils      NA 1.000000
#> 4       increase in lymphocytes   decrease in abs. monocytes      NA 1.000000
#> 5       increase in lymphocytes        decrease in monocytes      NA 1.000000
#> 6       increase in lymphocytes       decrease in hemoglobin      NA 0.819477
#> 7  increase in abs. lymphocytes decrease in abs. neutrophils      NA       NA
#> 8  increase in abs. lymphocytes      decrease in neutrophils      NA 1.000000
#> 9  increase in abs. lymphocytes   decrease in abs. monocytes      NA 1.000000
#> 10 increase in abs. lymphocytes        decrease in monocytes      NA       NA
#> 11 increase in abs. lymphocytes       decrease in hemoglobin      NA 1.000000
#> 12 decrease in abs. neutrophils      decrease in neutrophils      NA 1.000000
#> 13 decrease in abs. neutrophils   decrease in abs. monocytes      NA 1.000000
#> 14 decrease in abs. neutrophils        decrease in monocytes      NA       NA
#> 15 decrease in abs. neutrophils       decrease in hemoglobin      NA 1.000000
#> 16      decrease in neutrophils   decrease in abs. monocytes      NA 1.000000
#> 17      decrease in neutrophils        decrease in monocytes      NA 1.000000
#> 18      decrease in neutrophils       decrease in hemoglobin      NA 1.000000
#> 19   decrease in abs. monocytes        decrease in monocytes      NA 1.000000
#> 20   decrease in abs. monocytes       decrease in hemoglobin      NA 1.000000
#> 21        decrease in monocytes       decrease in hemoglobin      NA 1.000000
#>    Fisher_stat Fisher_pval
#> 1          Inf         1.0
#> 2          Inf         1.0
#> 3     0.408248         1.0
#> 4     0.408248         1.0
#> 5          Inf         1.0
#> 6     0.000000         0.4
#> 7           NA          NA
#> 8     0.000000         1.0
#> 9     0.000000         1.0
#> 10          NA          NA
#> 11    0.000000         1.0
#> 12         Inf         1.0
#> 13    0.000000         1.0
#> 14          NA          NA
#> 15         Inf         1.0
#> 16    1.000000         1.0
#> 17         Inf         1.0
#> 18    0.000000         1.0
#> 19    0.000000         1.0
#> 20         Inf         1.0
#> 21    0.000000         1.0

Created on 2022-02-10 by the reprex package (v2.0.1)


答:
The usual answer here is to loop backward, or if you have to loop forward, keep track of how many you've removed and adjust the index you're checking accodringly. But, in both cases, you'll still be doing multiple passes through the array, because splice itself is a loop — it has to loop from the index you're deleting at right the way to the end of the array, moving the entries around.

So the other usual answer is: Use filter, which makes a single pass. filter creates a new array, but that's usually just fine.

If you have to modify the original array and you don't want multiple loops (some hidden away inside splice), you can create your own operation instead that copies the elements necessary as it goes, in a single pass:

```<code>function removeIndexes(array, indexes) {
    let read = 0;
    let write = 0;
    while (read < array.length) {
        if (!indexesOfArrayElementWhichMustBeRemoved.includes(read)) {
            array[write++] = array[read];
        }
        ++read;
    }
    if (read !== write) {
        // Array got shorter
        array.length = write;
    }
    return array;
}
</code>```

Live Example:

const targetArray = [ "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india" ];
const indexesOfArrayElementWhichMustBeRemoved = [ 2, 5, 8 ];

function removeIndexes(array, indexes) {
    let read = 0;
    let write = 0;
    while (read < array.length) {
        if (!indexesOfArrayElementWhichMustBeRemoved.includes(read)) {
            array[write++] = array[read];
        }
        ++read;
    }
    if (read !== write) {
        // Array got shorter
        array.length = write;
    }
    return array;
}
removeIndexes(targetArray, indexesOfArrayElementWhichMustBeRemoved);

console.log(targetArray);```
</div>
</div>
</p>
<p>For completeness, here's going backward:</p>
```for (let index = targetArray.length - 1; index >= 0; --index) {
    if (indexesOfArrayElementWhichMustBeRemoved.includes(index)) {
        targetArray.splice(index, 1); // Note that this is an inner loop
    }
}
```
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const targetArray = [ "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india" ];
const indexesOfArrayElementWhichMustBeRemoved = [ 2, 5, 8 ];

for (let index = targetArray.length - 1; index >= 0; --index) {
    if (indexesOfArrayElementWhichMustBeRemoved.includes(index)) {
        targetArray.splice(index, 1); // Note that this is an inner loop
    }
}

console.log(targetArray);</code>```

and here's keeping track of how many you removed:

```<code>let removed = 0;
for (let index = 0; index < targetArray.length; ) {
    if (indexesOfArrayElementWhichMustBeRemoved.includes(index + removed)) {
        targetArray.splice(index, 1); // Note that this is an inner loop
        ++removed;
    } else {
        ++index;
    }
}
</code>```

const targetArray = [ "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india" ];
const indexesOfArrayElementWhichMustBeRemoved = [ 2, 5, 8 ];

let removed = 0;
for (let index = 0; index < targetArray.length; ) {
    if (indexesOfArrayElementWhichMustBeRemoved.includes(index + removed)) {
        targetArray.splice(index, 1); // Note that this is an inner loop
        ++removed;
    } else {
        ++index;
    }
}

console.log(targetArray);```
</div>
</div>
</p>
<p>and here's <code>filter</code>:</p>
```const replacement = targetArray.filter((_, index) => !indexesOfArrayElementWhichMustBeRemoved.includes(index));
```
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const targetArray = [ "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india" ];
const indexesOfArrayElementWhichMustBeRemoved = [ 2, 5, 8 ];

const replacement = targetArray.filter((_, index) => !indexesOfArrayElementWhichMustBeRemoved.includes(index));

console.log(replacement);</code>```

Title: How to remove multiple non-siblings elements from array by indexes within one pass?

Body:
The usual answer here is to loop backward, or if you have to loop forward, keep track of how many you've removed and adjust the index you're checking accodringly. But, in both cases, you'll still be doing multiple passes through the array, because splice itself is a loop — it has to loop from the index you're deleting at right the way to the end of the array, moving the entries around.

So the other usual answer is: Use filter, which makes a single pass. filter creates a new array, but that's usually just fine.

If you have to modify the original array and you don't want multiple loops (some hidden away inside splice), you can create your own operation instead that copies the elements necessary as it goes, in a single pass:

function removeIndexes(array, indexes) {
    let read = 0;
    let write = 0;
    while (read < array.length) {
        if (!indexesOfArrayElementWhichMustBeRemoved.includes(read)) {
            array[write++] = array[read];
        }
        ++read;
    }
    if (read !== write) {
        // Array got shorter
        array.length = write;
    }
    return array;
}

Live Example:

const targetArray = [ "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india" ];
const indexesOfArrayElementWhichMustBeRemoved = [ 2, 5, 8 ];

function removeIndexes(array, indexes) {
    let read = 0;
    let write = 0;
    while (read < array.length) {
        if (!indexesOfArrayElementWhichMustBeRemoved.includes(read)) {
            array[write++] = array[read];
        }
        ++read;
    }
    if (read !== write) {
        // Array got shorter
        array.length = write;
    }
    return array;
}
removeIndexes(targetArray, indexesOfArrayElementWhichMustBeRemoved);

console.log(targetArray);

For completeness, here's going backward:

for (let index = targetArray.length - 1; index >= 0; --index) {
    if (indexesOfArrayElementWhichMustBeRemoved.includes(index)) {
        targetArray.splice(index, 1); // Note that this is an inner loop
    }
}

const targetArray = [ "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india" ];
const indexesOfArrayElementWhichMustBeRemoved = [ 2, 5, 8 ];

for (let index = targetArray.length - 1; index >= 0; --index) {
    if (indexesOfArrayElementWhichMustBeRemoved.includes(index)) {
        targetArray.splice(index, 1); // Note that this is an inner loop
    }
}

console.log(targetArray);

and here's keeping track of how many you removed:

let removed = 0;
for (let index = 0; index < targetArray.length; ) {
    if (indexesOfArrayElementWhichMustBeRemoved.includes(index + removed)) {
        targetArray.splice(index, 1); // Note that this is an inner loop
        ++removed;
    } else {
        ++index;
    }
}

const targetArray = [ "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india" ];
const indexesOfArrayElementWhichMustBeRemoved = [ 2, 5, 8 ];

let removed = 0;
for (let index = 0; index < targetArray.length; ) {
    if (indexesOfArrayElementWhichMustBeRemoved.includes(index + removed)) {
        targetArray.splice(index, 1); // Note that this is an inner loop
        ++removed;
    } else {
        ++index;
    }
}

console.log(targetArray);

and here's filter:

const replacement = targetArray.filter((_, index) => !indexesOfArrayElementWhichMustBeRemoved.includes(index));

const targetArray = [ "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india" ];
const indexesOfArrayElementWhichMustBeRemoved = [ 2, 5, 8 ];

const replacement = targetArray.filter((_, index) => !indexesOfArrayElementWhichMustBeRemoved.includes(index));

console.log(replacement);


问:
Live() function not working with some elements
I'm trying to bind some change events to a select element which has been previously been transformed by jqTransform (http://www.dfc-e.com/metiers/multimedia/opensource/jqtransform/).

As change() function does not work after this transformation, I've followed this excellent advice from Code-Pal. Then I'm trying to apply a click function with the live() event (as future forms will be called with Ajax).

So far I've got this, which does not work:

```<code>$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper ul li a").live('click', function(e) {
console.log("Testing");
});
</code>```

Strangely, this DOES work:

```<code>$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper ul li a").bind('click', function(e) {
console.log("Testing");
});
</code>```

And even this:

```<code>$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper").live('click', function(e) {
console.log("Testing");
});
</code>```

So it's not that jqTransform is still not loaded. For some reason, live() stops working as soon as I'm selecting elements from a list. Any idea of what could be happening?

This is the html code after the jqtransform:

```<code><div class="jqTransformSelectWrapper" style="z-index: 10; width: 194px;">
  <div>
    <span style="width: 179px;">Tarjeta estándar</span>
    <a class="jqTransformSelectOpen" href="#"></a>
  </div>
  <ul style="width: 192px; display: none; visibility: visible; height: 125px; overflow: hidden;">
    <li>
      <a class="selected" index="0" href="#">Tarjeta estándar</a>
    </li>
    <li>
      <a index="1" href="#">Tarjetas cantos redondos</a>
    </li>
    <li>
      <a index="2" href="#">Tarjetas doble</a>
    </li>
    <li>
      <a index="3" href="#">Tarjeta PVC</a>
    </li>
    <li>
      <a index="4" href="#">Tarjeta adhesiva</a>
    </li>
  </ul>

  <select id="id-subproducto" class="jqTransformHidden" name="subproducto" style="">
    <option value="1">Tarjeta estándar</option>
    <option value="2">Tarjetas cantos redondos</option>
    <option value="3">Tarjetas doble</option>
    <option value="4">Tarjeta PVC</option>
    <option value="5">Tarjeta adhesiva</option>
  </select>
</div>
</code>```

Thanks in advance!

答:
If you're having trouble with jQuery live you might want to check out delegate instead.

Also have a look at Why You Should Never Use jQuery Live

Body:
I'm trying to bind some change events to a select element which has been previously been transformed by jqTransform (http://www.dfc-e.com/metiers/multimedia/opensource/jqtransform/).

As change() function does not work after this transformation, I've followed this excellent advice from Code-Pal. Then I'm trying to apply a click function with the live() event (as future forms will be called with Ajax).

So far I've got this, which does not work:

$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper ul li a").live('click', function(e) {
console.log("Testing");
});

Strangely, this DOES work:

$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper ul li a").bind('click', function(e) {
console.log("Testing");
});

And even this:

$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper").live('click', function(e) {
console.log("Testing");
});

So it's not that jqTransform is still not loaded. For some reason, live() stops working as soon as I'm selecting elements from a list. Any idea of what could be happening?

This is the html code after the jqtransform:

    Tarjeta estándar

      Tarjeta estándar

      Tarjetas cantos redondos

      Tarjetas doble

      Tarjeta PVC

      Tarjeta adhesiva

  <select id="id-subproducto" class="jqTransformHidden" name="subproducto" style="">
    <option value="1">Tarjeta estándar</option>
    <option value="2">Tarjetas cantos redondos</option>
    <option value="3">Tarjetas doble</option>
    <option value="4">Tarjeta PVC</option>
    <option value="5">Tarjeta adhesiva</option>
  </select>

Thanks in advance!


问:
How to get the values of dictionary python?
I have the below python dictionary stored as dictPython

```<code>{
    "paging": {"count": 10, "start": 0, "links": []},
    "elements": [
        {
            "organizationalTarget~": {
                "vanityName": "vv",
                "localizedName": "ViV",
                "name": {
                    "localized": {"en_US": "ViV"},
                    "preferredLocale": {"country": "US", "language": "en"},
                },
                "primaryOrganizationType": "NONE",
                "locations": [],
                "id": 109,
            },
            "role": "ADMINISTRATOR",

        },
    ],
}
</code>```

I need to get the values of vanityName, localizedName and also the values from name->localized and name->preferredLocale.

I tried dictPython.keys() and it returned dict_keys(['paging', 'elements']).

Also I tried dictPython.values() and it returned me what is inside of the parenthesis({}).

I need to get [vv, ViV, ViV, US, en]

答:
I am writing this in a form of answer, so I can get to explain it better without the comments characters limit

a dict in python is an efficient key/value structure or data type
for example dict_ = {'key1': 'val1', 'key2': 'val2'} to fetch key1 we can do it in 2 different ways

dict_.get(key1) this returns the value of the key in this case val1, this method has its advantage, that if the key1 is wrong or not found it returns None so no exceptions are raised. You can do dict_.get(key1, 'returning this string if the key is not found')

dict_['key1'] doing the same .get(...) but will raise a KeyError if the key is not found

So to answer your question after this introduction,
a dict can be thought of as nested dictionaries and/or objects inside of one another
to get your values you can do the following

```<code># Fetch base dictionary to make code more readable
base_dict = dict_["elements"][0]["organizationalTarget~"]
# fetch name_dict following the same approach as above code
name_dict = base_dict["name"]
localized_dict = name_dict["localized"]
preferred_locale_dict = name_dict ["preferredLocale"]
</code>```

so now we fetch all of the wanted data in their corresponding locations from your given dictionary, now to print the results, we can do the following

```<code>results_arr = []
for key1, key2 in zip(localized_dict, preferredLocale_dict):
    results_arr.append(localized_dict.get(key1))
    results_arr.append(preferred_locale_dict.get(key2))

print(results_arr)
</code>```

Body:
I have the below python dictionary stored as dictPython

{
    "paging": {"count": 10, "start": 0, "links": []},
    "elements": [
        {
            "organizationalTarget~": {
                "vanityName": "vv",
                "localizedName": "ViV",
                "name": {
                    "localized": {"en_US": "ViV"},
                    "preferredLocale": {"country": "US", "language": "en"},
                },
                "primaryOrganizationType": "NONE",
                "locations": [],
                "id": 109,
            },
            "role": "ADMINISTRATOR",

        },
    ],
}

I need to get the values of vanityName, localizedName and also the values from name->localized and name->preferredLocale.

I tried dictPython.keys() and it returned dict_keys(['paging', 'elements']).

Also I tried dictPython.values() and it returned me what is inside of the parenthesis({}).

I need to get [vv, ViV, ViV, US, en]

Body:
I am writing this in a form of answer, so I can get to explain it better without the comments characters limit

a dict in python is an efficient key/value structure or data type
for example dict_ = {'key1': 'val1', 'key2': 'val2'} to fetch key1 we can do it in 2 different ways

dict_.get(key1) this returns the value of the key in this case val1, this method has its advantage, that if the key1 is wrong or not found it returns None so no exceptions are raised. You can do dict_.get(key1, 'returning this string if the key is not found')

dict_['key1'] doing the same .get(...) but will raise a KeyError if the key is not found

So to answer your question after this introduction,
a dict can be thought of as nested dictionaries and/or objects inside of one another
to get your values you can do the following

# Fetch base dictionary to make code more readable
base_dict = dict_["elements"][0]["organizationalTarget~"]
# fetch name_dict following the same approach as above code
name_dict = base_dict["name"]
localized_dict = name_dict["localized"]
preferred_locale_dict = name_dict ["preferredLocale"]

so now we fetch all of the wanted data in their corresponding locations from your given dictionary, now to print the results, we can do the following

results_arr = []
for key1, key2 in zip(localized_dict, preferredLocale_dict):
    results_arr.append(localized_dict.get(key1))
    results_arr.append(preferred_locale_dict.get(key2))

print(results_arr)


问:
SSBO CPU mapping returning correct data, but data is 'different' to the SSBO on GPU
I've run into an issue while attempting to use SSBOs as follows:

```<code>    GLuint lightSSBO;
    glGenBuffers(1, &lightSSBO);
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, lightSSBO);
    glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(int) + sizeof(LightData) * 10, NULL, GL_DYNAMIC_DRAW);

    glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, sizeof(int), &lightCount);
    glBufferSubData(GL_SHADER_STORAGE_BUFFER, sizeof(int), sizeof(LightData) * lights.size(), &lights[0]);

    void* ptr = glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY);

    std::cout << "lightCount value = " << *(int*)ptr << "\n";
    std::cout << "First Light: \n";
    ptr = (int*)ptr + 1;
    std::cout << "\tType: " << *(unsigned int*)ptr << "\n";
    ptr = (int*)ptr + 1;
    std::cout << "\tPosition: " << vec4ToString((glm::vec4*)ptr) << "\n";
    ptr = (float*)ptr + 4;
    std::cout << "\tDirection: " << vec4ToString((glm::vec4*)ptr) << "\n";
    ptr = (float*)ptr + 4;
    std::cout << "\tColour: " << vec4ToString((glm::vec4*)ptr) << "\n";
    ptr = (float*)ptr + 4;
    std::cout << "\tSize: " << *(float*)ptr << "\n";

    glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
</code>```

In the code excerpt above, ptr outputs the correct values I've assigned to lightCount and to lights[0], meaning the buffer ostensibly has the correct data. However, when I try to access beyond lightCount on the GPU (Lights[0]), I get incorrect values. For example, Lights[0].Colour simply returns (0,0,0,?), despite displaying correctly as (1,0.2,0.2,1) throught ptr above.

```<code>struct LightData
{
    uint Type;
    vec4 Position;
    vec4 Direction;
    vec4 Colour;
    float Size;
};

layout (std430, binding = 0) buffer LightBuffer
{
   int LightCount;
   LightData[] Lights;
};

void main()
{
   FragColor = Lights[0].Colour;
}
</code>```

And the output of the console for completeness: (The correct values)

```<code>lightCount value = 1
First Light:
        Type: 1
        Position: 0.000000, 0.000000, 0.000000, 1.000000
        Direction: -0.707107, 0.000000, -0.707107, 1.000000
        Colour: 1.000000, 0.200000, 0.200000, 1.000000
        Size: 0
</code>```

Note: Changing the shader colour to be Position is still not correct and does not change if I change the underlying data, indicating that the Light array is either not making it to the GPU or I'm accessing it incorrectly somehow.

Does anyone know why this is happening? Additionally, I'm confused as to the meaning/options for glBufferData's final GLenum parameter, even https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_storage_buffer_object.txt doesn't seem to mention it.

答:
GLSL structs and C++ structs have different rules on alignment. For structs, the spec states:

If the member is a structure, the base alignment of the structure is N, where
N is the largest base alignment value of any of its members, and rounded
up to the base alignment of a vec4. The individual members of this substructure are then assigned offsets by applying this set of rules recursively,
where the base offset of the first member of the sub-structure is equal to the
aligned offset of the structure. The structure may have padding at the end;
the base offset of the member following the sub-structure is rounded up to
the next multiple of the base alignment of the structure.

Let's analyze the struct:

```<code>struct LightData
{
    uint Type;
    vec4 Position;
    vec4 Direction;
    vec4 Colour;
    float Size;
};
</code>```

The largest member is a vec4 (=16 byte alignment). That means that the whole struct also needs to be aligned to 16 bytes. The members of the struct have a size of 4 + 3 * 16 + 4 = 56 bytes. The next bigger multiple of 16 is 64 which means that all structs need additional 8bytes of padding at the end.

Since you have an additional member int LightCount; before the first struct, you also need to add padding between them to ensure that the first struct starts at a 16 byte offset.

The C++ struct that matches your glsl buffer definition should thus look like:

```<code>struct LightData
{
    unsigned int Type;
    vec4 Position;
    vec4 Direction;
    vec4 Colour;
    float Size;
    int padding[2];
}

struct Buffer
{
    int LightCount;
    int padding[3];
    Light Lights[NUM_LIGHTS];
}
</code>```

Body:
I've run into an issue while attempting to use SSBOs as follows:

    GLuint lightSSBO;
    glGenBuffers(1, &lightSSBO);
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, lightSSBO);
    glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(int) + sizeof(LightData) * 10, NULL, GL_DYNAMIC_DRAW);

    glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, sizeof(int), &lightCount);
    glBufferSubData(GL_SHADER_STORAGE_BUFFER, sizeof(int), sizeof(LightData) * lights.size(), &lights[0]);

    void* ptr = glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY);

    std::cout << "lightCount value = " << *(int*)ptr << "\n";
    std::cout << "First Light: \n";
    ptr = (int*)ptr + 1;
    std::cout << "\tType: " << *(unsigned int*)ptr << "\n";
    ptr = (int*)ptr + 1;
    std::cout << "\tPosition: " << vec4ToString((glm::vec4*)ptr) << "\n";
    ptr = (float*)ptr + 4;
    std::cout << "\tDirection: " << vec4ToString((glm::vec4*)ptr) << "\n";
    ptr = (float*)ptr + 4;
    std::cout << "\tColour: " << vec4ToString((glm::vec4*)ptr) << "\n";
    ptr = (float*)ptr + 4;
    std::cout << "\tSize: " << *(float*)ptr << "\n";

    glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);

In the code excerpt above, ptr outputs the correct values I've assigned to lightCount and to lights[0], meaning the buffer ostensibly has the correct data. However, when I try to access beyond lightCount on the GPU (Lights[0]), I get incorrect values. For example, Lights[0].Colour simply returns (0,0,0,?), despite displaying correctly as (1,0.2,0.2,1) throught ptr above.

struct LightData
{
    uint Type;
    vec4 Position;
    vec4 Direction;
    vec4 Colour;
    float Size;
};

layout (std430, binding = 0) buffer LightBuffer
{
   int LightCount;
   LightData[] Lights;
};

void main()
{
   FragColor = Lights[0].Colour;
}

And the output of the console for completeness: (The correct values)

lightCount value = 1
First Light:
        Type: 1
        Position: 0.000000, 0.000000, 0.000000, 1.000000
        Direction: -0.707107, 0.000000, -0.707107, 1.000000
        Colour: 1.000000, 0.200000, 0.200000, 1.000000
        Size: 0

Note: Changing the shader colour to be Position is still not correct and does not change if I change the underlying data, indicating that the Light array is either not making it to the GPU or I'm accessing it incorrectly somehow.

Does anyone know why this is happening? Additionally, I'm confused as to the meaning/options for glBufferData's final GLenum parameter, even https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_storage_buffer_object.txt doesn't seem to mention it.

Body:
GLSL structs and C++ structs have different rules on alignment. For structs, the spec states:

If the member is a structure, the base alignment of the structure is N, where
N is the largest base alignment value of any of its members, and rounded
up to the base alignment of a vec4. The individual members of this substructure are then assigned offsets by applying this set of rules recursively,
where the base offset of the first member of the sub-structure is equal to the
aligned offset of the structure. The structure may have padding at the end;
the base offset of the member following the sub-structure is rounded up to
the next multiple of the base alignment of the structure.

Let's analyze the struct:

struct LightData
{
    uint Type;
    vec4 Position;
    vec4 Direction;
    vec4 Colour;
    float Size;
};

The largest member is a vec4 (=16 byte alignment). That means that the whole struct also needs to be aligned to 16 bytes. The members of the struct have a size of 4 + 3 * 16 + 4 = 56 bytes. The next bigger multiple of 16 is 64 which means that all structs need additional 8bytes of padding at the end.

Since you have an additional member int LightCount; before the first struct, you also need to add padding between them to ensure that the first struct starts at a 16 byte offset.

The C++ struct that matches your glsl buffer definition should thus look like:

struct LightData
{
    unsigned int Type;
    vec4 Position;
    vec4 Direction;
    vec4 Colour;
    float Size;
    int padding[2];
}

struct Buffer
{
    int LightCount;
    int padding[3];
    Light Lights[NUM_LIGHTS];
}


问:
how can i redirect my error message from console to file in Python
I need to redirect my error message from the console to a file. For this example, I need to insert the error message into a file:

```<code>Traceback (most recent call last):
  File "C:/Users/", line 5, in <module>
    1/0
ZeroDivisionError: division by zero"
</code>```

I have already tried to do something like this:

```<code>from contextlib import redirect_stdout

with open('error.txt', 'w') as f:
    with redirect_stdout(f):
        1/0
        print('here is my error')
</code>```

答:
You need to catch the error or your application will fail:</p>
```<code>from contextlib import redirect_stdout

with open('error.txt', 'w') as f:
    try:
        1/0
    except ZeroDivisionError as e:
        f.write(e)
</code>```

Body:
I need to redirect my error message from the console to a file. For this example, I need to insert the error message into a file:

Traceback (most recent call last):
  File "C:/Users/", line 5, in <module>
    1/0
ZeroDivisionError: division by zero"

I have already tried to do something like this:

from contextlib import redirect_stdout

with open('error.txt', 'w') as f:
    with redirect_stdout(f):
        1/0
        print('here is my error')

Body:
You need to catch the error or your application will fail:

from contextlib import redirect_stdout

with open('error.txt', 'w') as f:
    try:
        1/0
    except ZeroDivisionError as e:
        f.write(e)


问:
VS2022 Hot Reload unconditionally restarts application after changes
for C# there's this option in VS for hot reloading, to automatically rebuild and restart the application. This is usually necessary when the changes couldn't be applied while the application was running. In practice, this happens a lot when you have a syntax error and press save. Unfortunately, I checked the option "always rebuild when changes can't be applied while running the application" (I don't remember the exact name of this option). So now, each time when I have a syntax error and accidentally save the file, it exits the application I'm debugging, while I could have easily fixed the syntax error and saved again, without restarting.

Is there a way to restore this setting such that the dialog pops up again, asking me whether I want to continue editing or restart the application? I believe this dialog is called "rude edit". I tried to find the option in the settings of Visual Studio, but could not find it.
A work-around is to disable hot reloading on file save, and manually triggering the hot reload after I save a file, but I'd rather have the old behavior.

答:
Apparently, this setting persists during the lifetime of a single VS session, and is reset if you restart it. I should have read it better before clicking the checkbox.

Hot Reload dialog

For completeness, the caption of the checkbox is "Always rebuild when updates cannot be automatically applied. This checkbox will be reset when the solution is closed."


问:
Combine multple aggregation queries into a single query
How can I combine these four queries into a single query?

select count(ornon_id) as DEC_AUTH_Y from tbbu_policies where DECL_AUTH_REQ_FLAG = 'Y' and status_code = 'ACTI';

select count(ornon_id) as DEC_AUTH_N from tbbu_policies where DECL_AUTH_REQ_FLAG = 'N'and  status_code = 'ACTI';

select count(ornon_id) as INV_AUTH_Y from tbbu_policies where INV_AUTH_REQ_FLAG = 'Y' and status_code = 'ACTI';

select count(ornon_id) as INV_AUTH_N from tbbu_policies where INV_AUTH_REQ_FLAG = 'N'  and status_code = 'ACTI';
```

答:
You can use case-when based strategy with four columns, like this:

```<code>select
SUM(
CASE
    WHEN DECL_AUTH_REQ_FLAG = 'Y' THEN 1
    ELSE 0
END) as firstcount,
SUM(
CASE
    WHEN DECL_AUTH_REQ_FLAG = 'N' THEN 1
    ELSE 0
END) as secondcount,
SUM(
CASE
    WHEN INV_AUTH_REQ_FLAG = 'Y' THEN 1
    ELSE 0
END) as thirdcount,
SUM(
CASE
    WHEN INV_AUTH_REQ_FLAG = 'N' THEN 1
    ELSE 0
END) as fourthcount
from tbbu_policies
where status_code = 'ACTI' and
      (not (ornon_id is null));
</code>```

Body:
You can use case-when based strategy with four columns, like this:

select
SUM(
CASE
    WHEN DECL_AUTH_REQ_FLAG = 'Y' THEN 1
    ELSE 0
END) as firstcount,
SUM(
CASE
    WHEN DECL_AUTH_REQ_FLAG = 'N' THEN 1
    ELSE 0
END) as secondcount,
SUM(
CASE
    WHEN INV_AUTH_REQ_FLAG = 'Y' THEN 1
    ELSE 0
END) as thirdcount,
SUM(
CASE
    WHEN INV_AUTH_REQ_FLAG = 'N' THEN 1
    ELSE 0
END) as fourthcount
from tbbu_policies
where status_code = 'ACTI' and
      (not (ornon_id is null));