问:
PHP; MySQL JOIN query on large datasets gets slower as WHERE conditions update
So this might be a bit silly, but the alternative I was using is worse.  I am trying to write an excel sheet using data from my database and a PHP tool called Box/Spout. The thing is that Box/Spout reads rows one at a time, and they are not retrieved via index ( e.g. rows[10], rows[42], rows[156] )

I need to retrieve data from the database in the order the rows come out.  I have a database with a list of customers, that came in via Import and I have to write them into the excel spreadsheet.  They have phone numbers, emails, and an address.  Sorry for the confusion... :/  So I compiled this fairly complex query:

```<code>SELECT
      `Import`.`UniqueID`,
      `Import`.`RowNum`,
      `People`.`PeopleID`,
      `People`.`First`,
      `People`.`Last`,
      GROUP_CONCAT(
        DISTINCT CONCAT_WS(',', `PhonesTable`.`Phone`, `PhonesTable`.`Type`)
          ORDER BY `PhonesTable`.`PhoneID` DESC
          SEPARATOR ';'
      ) AS `Phones`,
      GROUP_CONCAT(
        DISTINCT CONCAT_WS(',', `EmailsTable`.`Email`)
          ORDER BY `EmailsTable`.`EmailID` DESC
          SEPARATOR ';'
      ) AS `Emails`,
      `Properties`.`Address1`,
      `Properties`.`city`,
      `Properties`.`state`,
      `Properties`.`PostalCode5`,
      ...(17 more `People` Columns)...,
      FROM `T_Import` AS `Import`
      LEFT JOIN `T_CustomerStorageJoin` AS `CustomerJoin`
        ON `Import`.`UniqueID` = `CustomerJoin`.`ImportID`
      LEFT JOIN `T_People` AS `People`
        ON `CustomerJoin`.`PersID`=`People`.`PeopleID`
      LEFT JOIN `T_JoinPeopleIDPhoneID` AS `PeIDPhID`
        ON `People`.`PeopleID` = `PeIDPhID`.`PeopleID`
      LEFT JOIN `T_Phone` AS `PhonesTable`
        ON `PeIDPhID`.`PhoneID`=`PhonesTable`.`PhoneID`
      LEFT JOIN `T_JoinPeopleIDEmailID` AS `PeIDEmID`
        ON `People`.`PeopleID` = `PeIDEmID`.`PeopleID`
      LEFT JOIN `T_Email` AS `EmailsTable`
        ON `PeIDEmID`.`EmailID`=`EmailsTable`.`EmailID`
      LEFT JOIN `T_JoinPeopleIDPropertyID` AS `PeIDPrID`
        ON `People`.`PeopleID` = `PeIDPrID`.`PeopleID`
        AND `PeIDPrID`.`PropertyCP`='CurrentImported'
      LEFT JOIN `T_Property` AS `Properties`
        ON `PeIDPrID`.`PropertyID`=`Properties`.`PropertyID`
      WHERE `Import`.`CustomerCollectionID`=$ccID
        AND `RowNum` >= $rnOffset
        AND `RowNum` < $rnLimit
      GROUP BY `RowNum`;
</code>```

So I have indexes on every ON segment, and the WHERE segment.  When RowNumber is like around 0->2500 in value, the query runs great and executes within a couple seconds.  But it seems like the query execution time exponentially multiplies the larger RowNumber gets.

I have an EXPLAIN here: and at pastebin( https://pastebin.com/PksYB4n2 )

```<code>id  select_type table         partitions  type    possible_keys                     key                   key_len   ref                                          rows    filtered    Extra
1   SIMPLE      Import        NULL        ref     CustomerCollectionID,RowNumIndex  CustomerCollectionID  4         const                                        48108   8.74        Using index condition; Using where; Using filesort;
1   SIMPLE      CustomerJoin  NULL        ref     ImportID                          ImportID              4         MyDatabase.Import.UniqueID                       1   100         NULL
1   SIMPLE      People        NULL        eq_ref  PRIMARY,PeopleID                  PRIMARY               4         MyDatabase.CustomerJoin.PersID                   1   100         NULL
1   SIMPLE      PeIDPhID      NULL        ref     PeopleID                          PeopleID              5         MyDatabase.People.PeopleID                       8   100         NULL
1   SIMPLE      PhonesTable   NULL        eq_ref  PRIMARY,PhoneID,PhoneID_2         PRIMARY               4         MyDatabase.PeIDPhID.PhoneID                      1   100         NULL
1   SIMPLE      PeIDEmID      NULL        ref     PeopleID                          PeopleID              5         MyDatabase.People.PeopleID                       5   100         NULL
1   SIMPLE      EmailsTable   NULL        eq_ref  PRIMARY,EmailID,DupeDeleteSelect  PRIMARY               4         MyDatabase.PeIDEmID.EmailID                      1   100         NULL
1   SIMPLE      PeIDPrID      NULL        ref     PeopleMSCP,PeopleID,PropertyCP    PeopleMSCP            5         MyDatabase.People.PeopleID                       4   100         Using where
1   SIMPLE      Properties    NULL        eq_ref  PRIMARY,PropertyID                PRIMARY               4         MyDatabase.PeIDPrID.PropertyID                   1   100         NULL
</code>```

I apologize if the formatting is absolutely terrible.  I'm not sure what good formatting looks like so I may have jumbled it a bit on accident, plus the tabs got screwed up.

What I want to know is how to speed up the query time.  The databases are very large, like in the 10s of millions of rows.  And they aren't always like this as our tables are constantly changing, however I would like to be able to handle it when they are.

I tried using LIMIT 2000, 1000 for example, but I know that it's less efficient than using an indexed column.  So I switched over to RowNumber.  I feel like this was a good decision, but it seems like MySQL is still looping every single row before the offset variable which kind of defeats the purpose of my index... I think?  I'm not sure.  I also basically split this particular query into about 10 singular queries, and ran them one by one, for each row of the excel file.  It takes a LONG time...  TOO LONG.   This is fast, but, obviously I'm having a problem.

Any help would be greatly appreciated, and thank you ahead of time.  I'm sorry again for my lack of post organization.

答:
(I'm listing this as a separate Answer since it is orthogonal to my other Answer.)

I call this the "explode-implode" syndrome.  The query does a JOIN, getting a bunch of rows, thereby generating several rows, and puts multiple rows into an intermediate table.  Then the GROUP BY implodes back to down to the original set of rows.

Let me focus on a portion of the query that could be reformulated to provide a performance improvement:

```<code>SELECT ...
      GROUP_CONCAT(
        DISTINCT CONCAT_WS(',', `EmailsTable`.`Email`)
          ORDER BY `EmailsTable`.`EmailID` DESC
          SEPARATOR ';'
      ) AS `Emails`,
      ...
    FROM ...
      LEFT JOIN `T_Email` AS `EmailsTable`
        ON `PeIDEmID`.`EmailID`=`EmailsTable`.`EmailID`
      ...
    GROUP BY `RowNum`;
</code>```

Instead, move the table and aggregation function into a subquery

```<code>SELECT ...
      ( SELECT GROUP_CONCAT(
                DISTINCT CONCAT_WS(',', `Email`)
                    ORDER BY `EmailID` DESC
                    SEPARATOR ';' )
            FROM T_Email
            WHERE `PeIDEmID`.`EmailID` = `EmailID`
      ) AS `Emails`,
      ...
   FROM ...
      -- and Remove:  LEFT JOIN `T_Email` ON ...
      ...
      -- and possibly Remove:  GROUP BY ...;
</code>```

Ditto for PhonesTable.

(It is unclear whether the GROUP BY can be removed; other things may need it.)

Body:
So this might be a bit silly, but the alternative I was using is worse.  I am trying to write an excel sheet using data from my database and a PHP tool called Box/Spout. The thing is that Box/Spout reads rows one at a time, and they are not retrieved via index ( e.g. rows[10], rows[42], rows[156] )

I need to retrieve data from the database in the order the rows come out.  I have a database with a list of customers, that came in via Import and I have to write them into the excel spreadsheet.  They have phone numbers, emails, and an address.  Sorry for the confusion... :/  So I compiled this fairly complex query:

SELECT
      `Import`.`UniqueID`,
      `Import`.`RowNum`,
      `People`.`PeopleID`,
      `People`.`First`,
      `People`.`Last`,
      GROUP_CONCAT(
        DISTINCT CONCAT_WS(',', `PhonesTable`.`Phone`, `PhonesTable`.`Type`)
          ORDER BY `PhonesTable`.`PhoneID` DESC
          SEPARATOR ';'
      ) AS `Phones`,
      GROUP_CONCAT(
        DISTINCT CONCAT_WS(',', `EmailsTable`.`Email`)
          ORDER BY `EmailsTable`.`EmailID` DESC
          SEPARATOR ';'
      ) AS `Emails`,
      `Properties`.`Address1`,
      `Properties`.`city`,
      `Properties`.`state`,
      `Properties`.`PostalCode5`,
      ...(17 more `People` Columns)...,
      FROM `T_Import` AS `Import`
      LEFT JOIN `T_CustomerStorageJoin` AS `CustomerJoin`
        ON `Import`.`UniqueID` = `CustomerJoin`.`ImportID`
      LEFT JOIN `T_People` AS `People`
        ON `CustomerJoin`.`PersID`=`People`.`PeopleID`
      LEFT JOIN `T_JoinPeopleIDPhoneID` AS `PeIDPhID`
        ON `People`.`PeopleID` = `PeIDPhID`.`PeopleID`
      LEFT JOIN `T_Phone` AS `PhonesTable`
        ON `PeIDPhID`.`PhoneID`=`PhonesTable`.`PhoneID`
      LEFT JOIN `T_JoinPeopleIDEmailID` AS `PeIDEmID`
        ON `People`.`PeopleID` = `PeIDEmID`.`PeopleID`
      LEFT JOIN `T_Email` AS `EmailsTable`
        ON `PeIDEmID`.`EmailID`=`EmailsTable`.`EmailID`
      LEFT JOIN `T_JoinPeopleIDPropertyID` AS `PeIDPrID`
        ON `People`.`PeopleID` = `PeIDPrID`.`PeopleID`
        AND `PeIDPrID`.`PropertyCP`='CurrentImported'
      LEFT JOIN `T_Property` AS `Properties`
        ON `PeIDPrID`.`PropertyID`=`Properties`.`PropertyID`
      WHERE `Import`.`CustomerCollectionID`=$ccID
        AND `RowNum` >= $rnOffset
        AND `RowNum` < $rnLimit
      GROUP BY `RowNum`;

So I have indexes on every ON segment, and the WHERE segment.  When RowNumber is like around 0->2500 in value, the query runs great and executes within a couple seconds.  But it seems like the query execution time exponentially multiplies the larger RowNumber gets.

I have an EXPLAIN here: and at pastebin( https://pastebin.com/PksYB4n2 )

id  select_type table         partitions  type    possible_keys                     key                   key_len   ref                                          rows    filtered    Extra
1   SIMPLE      Import        NULL        ref     CustomerCollectionID,RowNumIndex  CustomerCollectionID  4         const                                        48108   8.74        Using index condition; Using where; Using filesort;
1   SIMPLE      CustomerJoin  NULL        ref     ImportID                          ImportID              4         MyDatabase.Import.UniqueID                       1   100         NULL
1   SIMPLE      People        NULL        eq_ref  PRIMARY,PeopleID                  PRIMARY               4         MyDatabase.CustomerJoin.PersID                   1   100         NULL
1   SIMPLE      PeIDPhID      NULL        ref     PeopleID                          PeopleID              5         MyDatabase.People.PeopleID                       8   100         NULL
1   SIMPLE      PhonesTable   NULL        eq_ref  PRIMARY,PhoneID,PhoneID_2         PRIMARY               4         MyDatabase.PeIDPhID.PhoneID                      1   100         NULL
1   SIMPLE      PeIDEmID      NULL        ref     PeopleID                          PeopleID              5         MyDatabase.People.PeopleID                       5   100         NULL
1   SIMPLE      EmailsTable   NULL        eq_ref  PRIMARY,EmailID,DupeDeleteSelect  PRIMARY               4         MyDatabase.PeIDEmID.EmailID                      1   100         NULL
1   SIMPLE      PeIDPrID      NULL        ref     PeopleMSCP,PeopleID,PropertyCP    PeopleMSCP            5         MyDatabase.People.PeopleID                       4   100         Using where
1   SIMPLE      Properties    NULL        eq_ref  PRIMARY,PropertyID                PRIMARY               4         MyDatabase.PeIDPrID.PropertyID                   1   100         NULL

I apologize if the formatting is absolutely terrible.  I'm not sure what good formatting looks like so I may have jumbled it a bit on accident, plus the tabs got screwed up.

What I want to know is how to speed up the query time.  The databases are very large, like in the 10s of millions of rows.  And they aren't always like this as our tables are constantly changing, however I would like to be able to handle it when they are.

I tried using LIMIT 2000, 1000 for example, but I know that it's less efficient than using an indexed column.  So I switched over to RowNumber.  I feel like this was a good decision, but it seems like MySQL is still looping every single row before the offset variable which kind of defeats the purpose of my index... I think?  I'm not sure.  I also basically split this particular query into about 10 singular queries, and ran them one by one, for each row of the excel file.  It takes a LONG time...  TOO LONG.   This is fast, but, obviously I'm having a problem.

Any help would be greatly appreciated, and thank you ahead of time.  I'm sorry again for my lack of post organization.

Body:
(I'm listing this as a separate Answer since it is orthogonal to my other Answer.)

I call this the "explode-implode" syndrome.  The query does a JOIN, getting a bunch of rows, thereby generating several rows, and puts multiple rows into an intermediate table.  Then the GROUP BY implodes back to down to the original set of rows.

Let me focus on a portion of the query that could be reformulated to provide a performance improvement:

SELECT ...
      GROUP_CONCAT(
        DISTINCT CONCAT_WS(',', `EmailsTable`.`Email`)
          ORDER BY `EmailsTable`.`EmailID` DESC
          SEPARATOR ';'
      ) AS `Emails`,
      ...
    FROM ...
      LEFT JOIN `T_Email` AS `EmailsTable`
        ON `PeIDEmID`.`EmailID`=`EmailsTable`.`EmailID`
      ...
    GROUP BY `RowNum`;

Instead, move the table and aggregation function into a subquery

SELECT ...
      ( SELECT GROUP_CONCAT(
                DISTINCT CONCAT_WS(',', `Email`)
                    ORDER BY `EmailID` DESC
                    SEPARATOR ';' )
            FROM T_Email
            WHERE `PeIDEmID`.`EmailID` = `EmailID`
      ) AS `Emails`,
      ...
   FROM ...
      -- and Remove:  LEFT JOIN `T_Email` ON ...
      ...
      -- and possibly Remove:  GROUP BY ...;

Ditto for PhonesTable.

(It is unclear whether the GROUP BY can be removed; other things may need it.)


来源: stackexchange

问:
Monitoring Amazon S3 logs with Splunk?
We have a large extended network of users that we track using badges. The total traffic is in the neighborhood of 60 Million impressions a month. We are currently considering switching from a fairly slow, database-based logging solution (custom-built on PHP—messy...) to a simple log-based alternative that relies on Amazon S3 logs and Splunk.

After using Splunk for some other analyisis tasks, I really like it. But it's not clear how to set up a source like S3 with the system. It seems that remote sources require the Universal Forwarder installed, which is not an option there.

Any ideas on this?

答:
You use Splunk Add-On for AWS.

This is what I understand,

Create a Splunk instance. Use the website version or the on-premise
AMI of splunk to create an EC2 where splunk is running.

Install Splunk Add-On for AWS application on the EC2.

Based on the input logs type (e.g. Cloudtrail logs, Config logs, generic logs, etc) configure the Add-On and supply AWS account id or IAM Role, etc parameters.

The Add-On will automatically ping AWS S3 source and fetch the latest logs after specified amount of time (default to 30 seconds).

For generic use case (like ours), you can try and configure Generic S3 input for Splunk

ContentLicense: CC BY-SA 3.0

Title: Monitoring Amazon S3 logs with Splunk?

ContentLicense: CC BY-SA 4.0


问:
Looking for a regex pattern between a range of 0.1 to 24. Need to allow for 2 decimal places
I can't seem to get a regex to work that will allow a user to enter a float between the range of 0.1 to 24.  I need to allow 2 decimal places and it must be greater than 0 and less than 24.    </p>

Body:
How about this:

^(?:24\.00)|^(?:(?:(?:[0-9])|(?:[0-1][0-9])|(?:2[0-3]))\.\d\d?)

As seen here


问:
Colorful Squares Python Program Using Nested Loops with Turtle
I'm trying to create a program in python that draw columns and rows of squares. There can only be 3 rows and 3-12 columns. The user must input how many columns they want and what 3 colors they want the rows to be. I'm struggling with how to line up the rows underneath each other and how to make it centered on the screen. I'm also struggling with how to make each row a different color. Any suggestions would help. Thank you!
This is what I have so far.

```<code>import turtle

ROWS = 3
OFFSET = 10
cols = int(input('How many columns to display (3-12)? '))

color1 = input('What is the first color? ')
color2 = input('What is the second color? ')
color3 = input('What is the third color? ')

if cols < 3 or cols > 12:
  print('Error! Number of columns must be in range of 3 to 12.')

elif color1 == color2 or color1 == color3:
  print('Error! All the colors must be different!')
elif color2 == color1 or color2 == color3:
  print('Error! All the colors must be different!')
elif color3 == color1 or color3 == color2:
  print('Error! All the colors must be different!')
else:
  for r in range(ROWS):
    y = turtle.ycor() - 115
    x = turtle.xcor()
    turtle.penup()
    turtle.goto(x,y)
    turtle.pendown()
    turtle.fillcolor(color1)
    turtle.begin_fill()
    for c in range(cols):
      x = turtle.xcor() + 95
      y = turtle.ycor()
      turtle.penup()
      turtle.goto(x,y)
      turtle.pendown()
      for side in range(4):
        turtle.forward(50)
        turtle.left(90)
    turtle.end_fill()
</code>```

Example of what it needs to look like

答:
Your input verification needs work and hopefully the example below will help with that.  As far as centering on the screen, you need to make the code dynamic, so constants like:

```<code>y = turtle.ycor() - 115
x = turtle.xcor() + 95
turtle.forward(50)
</code>```

Aren't doing you any good.  You need to compute these values based on the number of columns, the width of the window, and the size of your borders and gaps.

Since you should be doing this lab yourself, I'm going to provide a working example that won't be of direct use to you as it uses stamping and your problem appears to be based on drawing.  (One difference is where the turtle is when it initiates drawing a box.)  But you'll be able to see the calculations necessary to properly center and line up your boxes:

```<code>from turtle import Screen, Turtle

ROWS = 3
CURSOR_SIZE = 20  # base unit for cursor resizing

columns = -1

while not 3 <= columns <= 12:
    columns = int(input('How many columns to display (3-12)? '))
    if not 3 <= columns <= 12:
        print('Error! Number of columns must be in range of 3 to 12.')

color = input('What is the first color? ')

colors = [color]

while color in colors:
    color = input('What is the second color? ')
    if color in colors:
        print('Error! All the colors must be different!')

colors.append(color)

while color in colors:
    color = input('What is the third color? ')
    if color in colors:
        print('Error! All the colors must be different!')

colors.append(color)

screen = Screen()

# assumptions: there is a one box size border on each side and
# the gap between boxes, vertical and horizontal, is 1/2 box

# dimensions are based on number of columns and window width
box_size = screen.window_width() / ((columns - 1) * 1.5 + 3)

turtle = Turtle()
turtle.hideturtle()
turtle.shape('square')
turtle.shapesize(box_size / CURSOR_SIZE)  # make the turtle our standard box
turtle.penup()

y = box_size * 1.5  # y center of top-most boxes

for row in range(ROWS):
    turtle.fillcolor(colors[row])

    x = -box_size * (columns * 3/4 - 3/4)  # x center of left-most boxes

    turtle.goto(x, y)

    for column in range(columns):

        turtle.stamp()

        x += box_size * 1.5  # move by a box and a gap

        turtle.setx(x)

    y -= box_size * 1.5  # move by a box and a gap

screen.exitonclick()
</code>```

Note how all the user's inputs have been corrected and/or redundancy checked before the code moves onto drawing boxes:

If you haven't learned about arrays like colors yet, you should still be able to do the color checks and assignments, it'll just take additional code.

Body:
I'm trying to create a program in python that draw columns and rows of squares. There can only be 3 rows and 3-12 columns. The user must input how many columns they want and what 3 colors they want the rows to be. I'm struggling with how to line up the rows underneath each other and how to make it centered on the screen. I'm also struggling with how to make each row a different color. Any suggestions would help. Thank you!
This is what I have so far.

import turtle

ROWS = 3
OFFSET = 10
cols = int(input('How many columns to display (3-12)? '))

color1 = input('What is the first color? ')
color2 = input('What is the second color? ')
color3 = input('What is the third color? ')

if cols < 3 or cols > 12:
  print('Error! Number of columns must be in range of 3 to 12.')

elif color1 == color2 or color1 == color3:
  print('Error! All the colors must be different!')
elif color2 == color1 or color2 == color3:
  print('Error! All the colors must be different!')
elif color3 == color1 or color3 == color2:
  print('Error! All the colors must be different!')
else:
  for r in range(ROWS):
    y = turtle.ycor() - 115
    x = turtle.xcor()
    turtle.penup()
    turtle.goto(x,y)
    turtle.pendown()
    turtle.fillcolor(color1)
    turtle.begin_fill()
    for c in range(cols):
      x = turtle.xcor() + 95
      y = turtle.ycor()
      turtle.penup()
      turtle.goto(x,y)
      turtle.pendown()
      for side in range(4):
        turtle.forward(50)
        turtle.left(90)
    turtle.end_fill()

Example of what it needs to look like

Body:
Your input verification needs work and hopefully the example below will help with that.  As far as centering on the screen, you need to make the code dynamic, so constants like:

y = turtle.ycor() - 115
x = turtle.xcor() + 95
turtle.forward(50)

Aren't doing you any good.  You need to compute these values based on the number of columns, the width of the window, and the size of your borders and gaps.

Since you should be doing this lab yourself, I'm going to provide a working example that won't be of direct use to you as it uses stamping and your problem appears to be based on drawing.  (One difference is where the turtle is when it initiates drawing a box.)  But you'll be able to see the calculations necessary to properly center and line up your boxes:

from turtle import Screen, Turtle

ROWS = 3
CURSOR_SIZE = 20  # base unit for cursor resizing

columns = -1

while not 3 <= columns <= 12:
    columns = int(input('How many columns to display (3-12)? '))
    if not 3 <= columns <= 12:
        print('Error! Number of columns must be in range of 3 to 12.')

color = input('What is the first color? ')

colors = [color]

while color in colors:
    color = input('What is the second color? ')
    if color in colors:
        print('Error! All the colors must be different!')

colors.append(color)

while color in colors:
    color = input('What is the third color? ')
    if color in colors:
        print('Error! All the colors must be different!')

colors.append(color)

screen = Screen()

# assumptions: there is a one box size border on each side and
# the gap between boxes, vertical and horizontal, is 1/2 box

# dimensions are based on number of columns and window width
box_size = screen.window_width() / ((columns - 1) * 1.5 + 3)

turtle = Turtle()
turtle.hideturtle()
turtle.shape('square')
turtle.shapesize(box_size / CURSOR_SIZE)  # make the turtle our standard box
turtle.penup()

y = box_size * 1.5  # y center of top-most boxes

for row in range(ROWS):
    turtle.fillcolor(colors[row])

    x = -box_size * (columns * 3/4 - 3/4)  # x center of left-most boxes

    turtle.goto(x, y)

    for column in range(columns):

        turtle.stamp()

        x += box_size * 1.5  # move by a box and a gap

        turtle.setx(x)

    y -= box_size * 1.5  # move by a box and a gap

screen.exitonclick()

Note how all the user's inputs have been corrected and/or redundancy checked before the code moves onto drawing boxes:

If you haven't learned about arrays like colors yet, you should still be able to do the color checks and assignments, it'll just take additional code.


问:
PHP array key sum value if exist in loop with dynamic value
I create of Tree (Bill of Materials) from SQL and i'm make calculation of product. I have few if in if and if in if etc. I want to display sumamry of all individual part number with total quantitny which i'm calculating dynamicly. So, before loop and function if. i'm created three variables:

```<code>$TablicaMiH = array();
$TablicaBo = array();
$TablicaAss = array();
</code>```

when I meet the conditions, which depend on the if function, each of them performs operations of adding to the array. this is:

```<code>$TablicaMiH += [$SqlCheckAssyResultShowQ['PartNumber'] => $multipler];
</code>```

or

```<code>$TablicaBo += [$SqlCheckAssyResultShowQ['PartNumber'] => $multipler];
</code>```

or

```<code>$TablicaAssy += [$SqlCheckAssyResultShowQ['PartNumber'] => $multipler];
</code>```

The commands execute correctly as needed, but they do not add the sum value from the $ multipler variable to me, they only do individual PartNumbers and take the last value from the $ multipler variable

here is the result of what was received from the script:

```<code>Tablica MiH:
Array ( [333/E8093] => 2 [332/F2592] => 3 [332/F3144] => 9 [332/F3147] => 21 [332/F2684] => 8 [333/D1641] => 12 [333/D1202] => 22 [332/F2588] => 1 [333/E7883] => 1 [333/E8131] => 1 )

Tablica BO:
Array ( [826/10381] => 12 [331/30854] => 7 [332/F3213] => 4 [123/06090] => 84 [1315/0307Z] => 1 [823/10874] => 1 [333/E7939] => 4 [813/10186] => 2 [332/H3476] => 3 [32/920300] => 11 [332/F3282] => 1 [32/926051] => 1 )

Tablica Ass:
Array ( [2th] => 1 [3TH] => 1 [4th] => 1 [5th] => 1 [6th] => 1 [7th] => 1 [8th] => 1 [9th] => 1 [10Th] => 1 [IN_1TH] => 1 )
</code>```

and result what i need to have:

```<code>$TablicaMiH
332/F2588||5
332/F2592||10
332/F2684||9
332/F3144||27
332/F3147||38
333/D1202||40
333/D1641||16
333/E7883||1
333/E8093||12
333/E8131||1

Tablica BO:
123/06090||85
1315/0307Z||1
32/920300||11
32/926051||1
331/30854||20
332/f3213||29
332/F3282||1
332/H3476||3
333/E7939||4
813/10186||3
823/10874||1
826/10381||13

Tablica Ass:
10Th||1
1TH||1
2TH||1
3TH||1
4th||1
5th||1
6th||1
7th||1
8th||1
9th||1
IN_1TH||1
</code>```

I Hope you understand me what i mean, and you can help me, thank you

Example to understand my problem:

```<code><?php

$exampleArraY = array(
            "PartNumber1" => 1,
            "PartNumber2" => 1,
            "PartNumber3" => 1,
            "PartNumber4" => 1,
            "PartNumber5" => 1,
            "PartNumber6" => 1,
            );

$value = "PartNumber1";
$value2 = "PartNumber2";
$value3 = "PartNumber3";
$value4 = "PartNumber4";
$value5 = "PartNumber5";
$value6 = "PartNumber6";
$value7 = "PartNumber7";

$multipler = 1;

if(in_array($value, $exampleArraY)){
    $exampleArraY[$value][1] += $multipler;
}else {
    $exampleArraY += [$value => $multipler];
}
if(in_array($value2, $exampleArraY)){
    $exampleArraY[$value2][1] += $multipler;
}else {
    $exampleArraY += [$value2 => $multipler];
}
if(in_array($value3, $exampleArraY)){
    $exampleArraY[$value3][1] += $multipler;
}else {
    $exampleArraY += [$value3 => $multipler];
}
if(in_array($value4, $exampleArraY)){
    $exampleArraY[$value4][1] += $multipler;
}else {
    $exampleArraY += [$value4 => $multipler];
}
if(in_array($value5, $exampleArraY)){
    $exampleArraY[$value5][1] += $multipler;
}else {
    $exampleArraY += [$value5 => $multipler];
}
if(in_array($value6, $exampleArraY)){
    $exampleArraY[$value6][1] += $multipler;
}else {
    $exampleArraY += [$value6 => $multipler];
}
if(in_array($value7, $exampleArraY)){
    $exampleArraY[$value7][1] += $multipler;
}else {
    $exampleArraY += [$value7 => $multipler];
}

print_r($exampleArraY);

?>
</code>```

Result:

```<code>Array ( [PartNumber1] => 1 [PartNumber2] => 1 [PartNumber3] => 1 [PartNumber4] => 1 [PartNumber5] => 1 [PartNumber6] => 1 )
</code>```

Desired Result:

```<code>Array ( [PartNumber1] => 2 [PartNumber2] => 2 [PartNumber3] => 2 [PartNumber4] => 2 [PartNumber5] => 2 [PartNumber6] => 2  [PartNumber7] => 1 )
</code>```

答:
If I understand the problem correctly, you might be looking for something like this:</p>

```<code>    // create the starting array
    $TablicaMiH = [];

    // ... do interesting things... in a loop most likely....

    // if we dont have a value for this key yet, set it to 0
    if (!isset($TablicaMiH[$SqlCheckAssyResultShowQ['PartNumber']])) {
        $TablicaMiH[$SqlCheckAssyResultShowQ['PartNumber']] = 0;
    }
    // now add the multiplier for this part number
    $TablicaMiH[$SqlCheckAssyResultShowQ['PartNumber']] += $multipler;
</code>```

Body:
I create of Tree (Bill of Materials) from SQL and i'm make calculation of product. I have few if in if and if in if etc. I want to display sumamry of all individual part number with total quantitny which i'm calculating dynamicly. So, before loop and function if. i'm created three variables:

$TablicaMiH = array();
$TablicaBo = array();
$TablicaAss = array();

when I meet the conditions, which depend on the if function, each of them performs operations of adding to the array. this is:

$TablicaMiH += [$SqlCheckAssyResultShowQ['PartNumber'] => $multipler];

or

$TablicaBo += [$SqlCheckAssyResultShowQ['PartNumber'] => $multipler];

or

$TablicaAssy += [$SqlCheckAssyResultShowQ['PartNumber'] => $multipler];

The commands execute correctly as needed, but they do not add the sum value from the $ multipler variable to me, they only do individual PartNumbers and take the last value from the $ multipler variable

here is the result of what was received from the script:

Tablica MiH:
Array ( [333/E8093] => 2 [332/F2592] => 3 [332/F3144] => 9 [332/F3147] => 21 [332/F2684] => 8 [333/D1641] => 12 [333/D1202] => 22 [332/F2588] => 1 [333/E7883] => 1 [333/E8131] => 1 )

Tablica BO:
Array ( [826/10381] => 12 [331/30854] => 7 [332/F3213] => 4 [123/06090] => 84 [1315/0307Z] => 1 [823/10874] => 1 [333/E7939] => 4 [813/10186] => 2 [332/H3476] => 3 [32/920300] => 11 [332/F3282] => 1 [32/926051] => 1 )

Tablica Ass:
Array ( [2th] => 1 [3TH] => 1 [4th] => 1 [5th] => 1 [6th] => 1 [7th] => 1 [8th] => 1 [9th] => 1 [10Th] => 1 [IN_1TH] => 1 )

and result what i need to have:

$TablicaMiH
332/F2588||5
332/F2592||10
332/F2684||9
332/F3144||27
332/F3147||38
333/D1202||40
333/D1641||16
333/E7883||1
333/E8093||12
333/E8131||1

Tablica BO:
123/06090||85
1315/0307Z||1
32/920300||11
32/926051||1
331/30854||20
332/f3213||29
332/F3282||1
332/H3476||3
333/E7939||4
813/10186||3
823/10874||1
826/10381||13

Tablica Ass:
10Th||1
1TH||1
2TH||1
3TH||1
4th||1
5th||1
6th||1
7th||1
8th||1
9th||1
IN_1TH||1

I Hope you understand me what i mean, and you can help me, thank you

Example to understand my problem:

<?php

$exampleArraY = array(
            "PartNumber1" => 1,
            "PartNumber2" => 1,
            "PartNumber3" => 1,
            "PartNumber4" => 1,
            "PartNumber5" => 1,
            "PartNumber6" => 1,
            );

$value = "PartNumber1";
$value2 = "PartNumber2";
$value3 = "PartNumber3";
$value4 = "PartNumber4";
$value5 = "PartNumber5";
$value6 = "PartNumber6";
$value7 = "PartNumber7";

$multipler = 1;

if(in_array($value, $exampleArraY)){
    $exampleArraY[$value][1] += $multipler;
}else {
    $exampleArraY += [$value => $multipler];
}
if(in_array($value2, $exampleArraY)){
    $exampleArraY[$value2][1] += $multipler;
}else {
    $exampleArraY += [$value2 => $multipler];
}
if(in_array($value3, $exampleArraY)){
    $exampleArraY[$value3][1] += $multipler;
}else {
    $exampleArraY += [$value3 => $multipler];
}
if(in_array($value4, $exampleArraY)){
    $exampleArraY[$value4][1] += $multipler;
}else {
    $exampleArraY += [$value4 => $multipler];
}
if(in_array($value5, $exampleArraY)){
    $exampleArraY[$value5][1] += $multipler;
}else {
    $exampleArraY += [$value5 => $multipler];
}
if(in_array($value6, $exampleArraY)){
    $exampleArraY[$value6][1] += $multipler;
}else {
    $exampleArraY += [$value6 => $multipler];
}
if(in_array($value7, $exampleArraY)){
    $exampleArraY[$value7][1] += $multipler;
}else {
    $exampleArraY += [$value7 => $multipler];
}

print_r($exampleArraY);

?>

Result:

Array ( [PartNumber1] => 1 [PartNumber2] => 1 [PartNumber3] => 1 [PartNumber4] => 1 [PartNumber5] => 1 [PartNumber6] => 1 )

Desired Result:

Array ( [PartNumber1] => 2 [PartNumber2] => 2 [PartNumber3] => 2 [PartNumber4] => 2 [PartNumber5] => 2 [PartNumber6] => 2  [PartNumber7] => 1 )

Body:
If I understand the problem correctly, you might be looking for something like this:

    // create the starting array
    $TablicaMiH = [];

    // ... do interesting things... in a loop most likely....

    // if we dont have a value for this key yet, set it to 0
    if (!isset($TablicaMiH[$SqlCheckAssyResultShowQ['PartNumber']])) {
        $TablicaMiH[$SqlCheckAssyResultShowQ['PartNumber']] = 0;
    }
    // now add the multiplier for this part number
    $TablicaMiH[$SqlCheckAssyResultShowQ['PartNumber']] += $multipler;


问:
How to create a multi-conditional 1D dataframe from a multi dimensional dataframe
I have a table with scores for each product that needed to be sold for 10 days and availability of each product (totally number of products = 10)

```<code>A   B   C   D
20  56  12  65
80  13  76  51
24  81  56  90
67  12  65  87
45  23  67  50
62  32  23  75
76  34  67  67
23  45  32  98
24  67  34  12
56  53  32  78
</code>```

Product availability

```<code>A   3
B   2
C   3
D   2
</code>```

First I had to rank each product and prioritize what I need to sell for each day. I was able to do that by

```<code>import pandas as pd
df = pd.read_csv('test.csv')

new_df = pd.DataFrame()
num = len(list(df))
for i in range(1,num+1)  :
    new_df['Max'+str(i)] = df.T.apply(lambda x: x.nlargest(i).idxmin())

print(new_df)
</code>```

That gives me

```<code>  Max1 Max2 Max3 Max4
0    D    B    A    C
1    A    C    D    B
2    D    B    C    A
3    D    A    C    B
4    C    D    A    B
5    D    A    B    C
6    A    C    C    B
7    D    B    C    A
8    B    C    A    D
9    D    A    B    C
</code>```

now comes the hard part how do i create a table that contains the product to be sold for each day looking at the Max1 column but also keeping track of the availability. If the product is not available then chose the next maximum. The final df should look like this.

```<code>0   D
1   A
2   D
3   A
4   C
5   A
6   C
7   B
8   B
9   C
</code>```

Breaking my head over this. Any help is appreciated. Thanks.

答:
```<code>import pandas as pd
df1=pd.read_csv('file1',sep='\s+',header=None,names=['product','available'])
print df1
df2=pd.read_csv('file2',sep='\s+')
print df2

maxy=[]
for i in range(len(df2)):
    if df1['available'][df1['product']==df2['Max1'][i]].values[0]>0:
        maxy.append(df2['Max1'][i])
        df1['available'][df1['product']==df2['Max1'][i]]=df1['available'][df1['product']==df2['Max1'][i]].values[0]-1
    elif df1['available'][df1['product']==df2['Max2'][i]].values[0]>0:
        maxy.append(df2['Max2'][i])
        df1['available'][df1['product']==df2['Max2'][i]]=df1['available'][df1['product']==df2['Max2'][i]].values[0]-1
    elif df1['available'][df1['product']==df2['Max3'][i]].values[0]>0:
        maxy.append(df2['Max3'][i])
        df1['available'][df1['product']==df2['Max3'][i]]=df1['available'][df1['product']==df2['Max3'][i]].values[0]-1
    elif df1['available'][df1['product']==df2['Max4'][i]].values[0]>0:
        maxy.append(df2['Max4'][i])
        df1['available'][df1['product']==df2['Max4'][i]]=df1['available'][df1['product']==df2['Max4'][i]].values[0]-1
    else:
        print ("Check")

pd.DataFrame(maxy)
</code>```

Output:

```<code> product  available
0       A          3
1       B          2
2       C          3
3       D          2
  Max1 Max2 Max3 Max4
0    D    B    A    C
1    A    C    D    B
2    D    B    C    A
3    D    A    C    B
4    C    D    A    B
5    D    A    B    C
6    A    C    C    B
7    D    B    C    A
8    B    C    A    D
9    D    A    B    C

    0
0   D
1   A
2   D
3   A
4   C
5   A
6   C
7   B
8   B
9   C
</code>```

I was able to do that for any number of products through this

```<code>cols = list(df2)
maxy=[]

for i in range(len(df2)):
    for x in cols:
        if df1['available'][df1['product']==df2[x][i]].values[0]>0:
            maxy.append(df2[x][i])
            df1['available'][df1['product']==df2[x][i]]=df1['available'][df1['product']==df2[x][i]].values[0]-1
            break

final=pd.DataFrame(maxy)
print(final)
</code>```

Thanks

Body:
I have a table with scores for each product that needed to be sold for 10 days and availability of each product (totally number of products = 10)

A   B   C   D
20  56  12  65
80  13  76  51
24  81  56  90
67  12  65  87
45  23  67  50
62  32  23  75
76  34  67  67
23  45  32  98
24  67  34  12
56  53  32  78

Product availability

A   3
B   2
C   3
D   2

First I had to rank each product and prioritize what I need to sell for each day. I was able to do that by

import pandas as pd
df = pd.read_csv('test.csv')

new_df = pd.DataFrame()
num = len(list(df))
for i in range(1,num+1)  :
    new_df['Max'+str(i)] = df.T.apply(lambda x: x.nlargest(i).idxmin())

print(new_df)

That gives me

  Max1 Max2 Max3 Max4
0    D    B    A    C
1    A    C    D    B
2    D    B    C    A
3    D    A    C    B
4    C    D    A    B
5    D    A    B    C
6    A    C    C    B
7    D    B    C    A
8    B    C    A    D
9    D    A    B    C

now comes the hard part how do i create a table that contains the product to be sold for each day looking at the Max1 column but also keeping track of the availability. If the product is not available then chose the next maximum. The final df should look like this.

0   D
1   A
2   D
3   A
4   C
5   A
6   C
7   B
8   B
9   C

Breaking my head over this. Any help is appreciated. Thanks.

Body:
import pandas as pd
df1=pd.read_csv('file1',sep='\s+',header=None,names=['product','available'])
print df1
df2=pd.read_csv('file2',sep='\s+')
print df2

maxy=[]
for i in range(len(df2)):
    if df1['available'][df1['product']==df2['Max1'][i]].values[0]>0:
        maxy.append(df2['Max1'][i])
        df1['available'][df1['product']==df2['Max1'][i]]=df1['available'][df1['product']==df2['Max1'][i]].values[0]-1
    elif df1['available'][df1['product']==df2['Max2'][i]].values[0]>0:
        maxy.append(df2['Max2'][i])
        df1['available'][df1['product']==df2['Max2'][i]]=df1['available'][df1['product']==df2['Max2'][i]].values[0]-1
    elif df1['available'][df1['product']==df2['Max3'][i]].values[0]>0:
        maxy.append(df2['Max3'][i])
        df1['available'][df1['product']==df2['Max3'][i]]=df1['available'][df1['product']==df2['Max3'][i]].values[0]-1
    elif df1['available'][df1['product']==df2['Max4'][i]].values[0]>0:
        maxy.append(df2['Max4'][i])
        df1['available'][df1['product']==df2['Max4'][i]]=df1['available'][df1['product']==df2['Max4'][i]].values[0]-1
    else:
        print ("Check")

pd.DataFrame(maxy)

Output:

 product  available
0       A          3
1       B          2
2       C          3
3       D          2
  Max1 Max2 Max3 Max4
0    D    B    A    C
1    A    C    D    B
2    D    B    C    A
3    D    A    C    B
4    C    D    A    B
5    D    A    B    C
6    A    C    C    B
7    D    B    C    A
8    B    C    A    D
9    D    A    B    C

    0
0   D
1   A
2   D
3   A
4   C
5   A
6   C
7   B
8   B
9   C

I was able to do that for any number of products through this

cols = list(df2)
maxy=[]

for i in range(len(df2)):
    for x in cols:
        if df1['available'][df1['product']==df2[x][i]].values[0]>0:
            maxy.append(df2[x][i])
            df1['available'][df1['product']==df2[x][i]]=df1['available'][df1['product']==df2[x][i]].values[0]-1
            break

final=pd.DataFrame(maxy)
print(final)

Thanks


问:
Laravel Routing multiple Params
i recently started using the framework Laravel as backend for my new project. For the frontend I use Angular 8+. Both areas are still relatively new to me and I am currently working on API routing and need your advice.

I have a user table where I store several user settings. I would like to update them accordingly. They are mostly boolean values. I now have a UserController. With this I want to process the PUT requests.

Now to my question:
How should I set up the routing if I want to update the user settings at different actions.(e.g. Action1 update View1 + View2 or Action2 update View3)? Should I process all this in one function or in several functions within the controller? If there are several functions, how should the routing look like?

Multiple Routes and Function like this?

```<code>Route::middleware('api')->get('/user/{userid}', 'UserController@show');
Route::middleware('api')->put('/user/{userid}/updateViewAction1', 'UserController@updateViewAction1');
Route::middleware('api')->put('/user/{userid}/updateViewAction2', 'UserController@updateViewAction2');
</code>```

or

If Statements within my function but how to update only data from the request? Angular transmits true/false from  therefore I check with if for true and set the value to 1.

```<code>public function updateView($userId, Request $request)
{
   if($request->query('view1') == "true"){ $view1 = 1; } else {$view1 = 0;}
   if($request->query('view2 ') == "true"){ $view2 = 1; } else {$view2  = 0;}
   $query = \DB::table('users')
             ->where('userId', '=', $userId)
             ->update(
                  ['view1' => $view1,
                  'view2 ' => $view2 );
}
</code>```

It doesn't seem to be right, but I can't think of anything else. Authentication is not considered at this point. As there will be more than 20 settings in the future, I am looking for an efficient solution.

答:
In controller you include the Request $request as the first argument, not the second

public function updateView(Request $request, $userID)...
// Or
public function updateView(Request $request, User $userid)...
```

Your are not oblidged to use the ::put method, you can use ::post

Title: Laravel Routing multiple Params

Body:
i recently started using the framework Laravel as backend for my new project. For the frontend I use Angular 8+. Both areas are still relatively new to me and I am currently working on API routing and need your advice.

I have a user table where I store several user settings. I would like to update them accordingly. They are mostly boolean values. I now have a UserController. With this I want to process the PUT requests.

Now to my question:
How should I set up the routing if I want to update the user settings at different actions.(e.g. Action1 update View1 + View2 or Action2 update View3)? Should I process all this in one function or in several functions within the controller? If there are several functions, how should the routing look like?

Multiple Routes and Function like this?

Route::middleware('api')->get('/user/{userid}', 'UserController@show');
Route::middleware('api')->put('/user/{userid}/updateViewAction1', 'UserController@updateViewAction1');
Route::middleware('api')->put('/user/{userid}/updateViewAction2', 'UserController@updateViewAction2');

or

If Statements within my function but how to update only data from the request? Angular transmits true/false from  therefore I check with if for true and set the value to 1.

public function updateView($userId, Request $request)
{
   if($request->query('view1') == "true"){ $view1 = 1; } else {$view1 = 0;}
   if($request->query('view2 ') == "true"){ $view2 = 1; } else {$view2  = 0;}
   $query = \DB::table('users')
             ->where('userId', '=', $userId)
             ->update(
                  ['view1' => $view1,
                  'view2 ' => $view2 );
}

It doesn't seem to be right, but I can't think of anything else. Authentication is not considered at this point. As there will be more than 20 settings in the future, I am looking for an efficient solution.

Body:
In controller you include the Request $request as the first argument, not the second

public function updateView(Request $request, $userID)...
// Or
public function updateView(Request $request, User $userid)...

Your are not oblidged to use the ::put method, you can use ::post


问:
How to pass a Dictionary in a web service
I have created a simple service to provide configuration options as a Dictionary. I created a new SerializableDictionary class that implements IXmlSerializable as described on this board. When I add the service (via "Add Service Reference" in my consumer project), the method signature shows that it returns a DataSet. When I examine the DataSet at runtime it is empty.

Here is my service:

```<code>[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class AppSettingsService : System.Web.Services.WebService
{
        [WebMethod]
        public SerializableDictionary<string, string> ReadAppSettings()
        {
            return AppSettings.Settings; // Settings is a SerializableDictionary<string, string>
        }
}
</code>```

On the Client side I do this:

```<code>using Clients.AppSettingsServiceReference;

        static AppSettings()
        {
            AppSettingsServiceSoapClient client = new AppSettingsServiceSoapClient();
            var settings = client.ReadAppSettings();
            // ...
        }
</code>```

I expect settings to be a SerializableDictionary but it's an empty DataSet. I've tried sending it as a List of KeyValuePairs as suggested here and elsewhere but that also returns a DataSet. I'm using C#, ASP.Net 3.5, VS2008 Pro
I'm sure I'm overlooking something simple but I can't find it. Can someone show me how to do this?

答:
John Saunders is right: this isn't really possible. The "right" way to do what you're trying to do is to create a class that represents the key-value pairs you're really trying to return, and then return an IEnumerable of that class. For example:

```<code>public class AppSetting
{
    public string Name {get;set;}
    public string Value {get;set;}
}

    [WebMethod]
    public IEnumerable<AppSetting> ReadAppSettings()
    {
        return AppSettings.Settings.Select(
            kvp => new AppSetting{Name = kvp.Key, Value = kvp.Value});
    }
</code>```

This provides the data straight to the consumer: let them decide whether they want to represent this as a Dictionary/Hashtable, List, Array, Tree, or any other data structure they decide to make of it. All you care about from a data-integrity standpoint is making sure each key is tied to the right value.

Body:
I have created a simple service to provide configuration options as a Dictionary. I created a new SerializableDictionary class that implements IXmlSerializable as described on this board. When I add the service (via "Add Service Reference" in my consumer project), the method signature shows that it returns a DataSet. When I examine the DataSet at runtime it is empty.

Here is my service:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class AppSettingsService : System.Web.Services.WebService
{
        [WebMethod]
        public SerializableDictionary<string, string> ReadAppSettings()
        {
            return AppSettings.Settings; // Settings is a SerializableDictionary<string, string>
        }
}

On the Client side I do this:

using Clients.AppSettingsServiceReference;

        static AppSettings()
        {
            AppSettingsServiceSoapClient client = new AppSettingsServiceSoapClient();
            var settings = client.ReadAppSettings();
            // ...
        }

I expect settings to be a SerializableDictionary but it's an empty DataSet. I've tried sending it as a List of KeyValuePairs as suggested here and elsewhere but that also returns a DataSet. I'm using C#, ASP.Net 3.5, VS2008 Pro
I'm sure I'm overlooking something simple but I can't find it. Can someone show me how to do this?

Body:
John Saunders is right: this isn't really possible. The "right" way to do what you're trying to do is to create a class that represents the key-value pairs you're really trying to return, and then return an IEnumerable of that class. For example:

public class AppSetting
{
    public string Name {get;set;}
    public string Value {get;set;}
}

    [WebMethod]
    public IEnumerable<AppSetting> ReadAppSettings()
    {
        return AppSettings.Settings.Select(
            kvp => new AppSetting{Name = kvp.Key, Value = kvp.Value});
    }

This provides the data straight to the consumer: let them decide whether they want to represent this as a Dictionary/Hashtable, List, Array, Tree, or any other data structure they decide to make of it. All you care about from a data-integrity standpoint is making sure each key is tied to the right value.


问:
getElementById.value to json into PostgreSQL with node.js, won't pass value
Well, I need some help with my app.

I'm trying to pass a value which I get from an getElemenyById() on my HTML but when the code runs it won't go into my database.

When I show the value through an Alert() I see the json values correctly but they won't go to the database.

If I manually input the value instead of using the getElementById().value, the code works correctly.

I'll leave some key parts of my code, thanks in advance. Any help is appreciated!

```<code>        <script>
            const btnCreate = document.getElementById("btn");
            btnCreate.addEventListener("click", async e=> {
                const jsonRequest = {};

                jsonRequest.id = document.getElementById("status").value;
                jsonRequest.lead_id = document.getElementById("brandname").value;
                alert("id = "+jsonRequest.id+" && lead_d = "+jsonRequest.lead_id);

                const result = await fetch("http://localhost:8080/lds", {method: "POST",
                    headers: {"content-type": "application/json"}, body: JSON.stringify(jsonRequest) });
                const success = await result.json();
                alert("CREATED! ")

            })
        </script>
</code>```

```<code>app.post("/lds", async (req, res) => {
    let result = {}
    try{

        const reqJson = req.body;
        await createStatus(reqJson.id,reqJson.lead_id);
        result.success = true;
    }
    catch(e){
        result.success = false;
    }

    finally{
        res.setHeader("content-type", "application/json")
        res.send(JSON.stringify(result))
    }

})
</code>```

```<code>async function createStatus(id, lead_id) {

    try {
        await client.query("insert into lead_status (id, lead_id) values ($1, $2)", [id, lead_id]);
        return true
    } catch (e) {
        return false;
    }
}
</code>```

答:
Well that was quick,

I think I found an answer to my issue though I'm not sure if its correct. What I'm sure is that it works.

The problem was on the js on the html script. I just parsed the getElementById().valueas int.

Both fields in my db table are integers.

```<code>
parseInt(jsonRequest.id = document.getElementById("brandname").value);
parseInt(jsonRequest.lead_id = document.getElementById("status").value);

</code>```

Body:
Well, I need some help with my app.

I'm trying to pass a value which I get from an getElemenyById() on my HTML but when the code runs it won't go into my database.

When I show the value through an Alert() I see the json values correctly but they won't go to the database.

If I manually input the value instead of using the getElementById().value, the code works correctly.

I'll leave some key parts of my code, thanks in advance. Any help is appreciated!

app.post("/lds", async (req, res) => {
    let result = {}
    try{

        const reqJson = req.body;
        await createStatus(reqJson.id,reqJson.lead_id);
        result.success = true;
    }
    catch(e){
        result.success = false;
    }

    finally{
        res.setHeader("content-type", "application/json")
        res.send(JSON.stringify(result))
    }

})

async function createStatus(id, lead_id) {

    try {
        await client.query("insert into lead_status (id, lead_id) values ($1, $2)", [id, lead_id]);
        return true
    } catch (e) {
        return false;
    }
}

Body:
Well that was quick,

I think I found an answer to my issue though I'm not sure if its correct. What I'm sure is that it works.

The problem was on the js on the html script. I just parsed the getElementById().valueas int.

Both fields in my db table are integers.

parseInt(jsonRequest.id = document.getElementById("brandname").value);
parseInt(jsonRequest.lead_id = document.getElementById("status").value);


问:
Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?
I know I've done this before years ago, but I can't remember the syntax, and I can't find it anywhere due to pulling up tons of help docs and articles about "bulk imports".

Here's what I want to do, but the syntax is not exactly right... please, someone who has done this before, help me out :)

```<code>INSERT INTO dbo.MyTable (ID, Name)
VALUES (123, 'Timmy'),
    (124, 'Jonny'),
    (125, 'Sally')
</code>```

I know that this is close to the right syntax. I might need the word "BULK" in there, or something, I can't remember. Any idea?

I need this for a SQL Server 2005 database. I've tried this code, to no avail:

```<code>DECLARE @blah TABLE
(
    ID INT NOT NULL PRIMARY KEY,
    Name VARCHAR(100) NOT NULL
)

INSERT INTO @blah (ID, Name)
    VALUES (123, 'Timmy')
    VALUES (124, 'Jonny')
    VALUES (125, 'Sally')

SELECT * FROM @blah
</code>```

I'm getting Incorrect syntax near the keyword 'VALUES'.

答:
Others here have suggested a couple multi-record syntaxes. Expounding upon that, I suggest you insert into a temp table first, and insert your main table from there.

The reason for this is loading the data from a query can take longer, and you may end up locking the table or pages longer than is necessary, which slows down other queries running against that table.

```<code>-- Make a temp table with the needed columns
select top 0 *
into #temp
from MyTable (nolock)

-- load data into it at your leisure (nobody else is waiting for this table or these pages)
insert #temp (ID, Name)
values (123, 'Timmy'),
(124, 'Jonny'),
(125, 'Sally')

-- Now that all the data is in SQL, copy it over to the real table. This runs much faster in most cases.
insert MyTable (ID, Name)
select ID, Name
from #temp

-- cleanup
drop table #temp
</code>```

Also, your IDs should probably be identity(1,1) and you probably shouldn't be inserting them, in the vast majority of circumstances. Let SQL decide that stuff for you.

Body:
I know I've done this before years ago, but I can't remember the syntax, and I can't find it anywhere due to pulling up tons of help docs and articles about "bulk imports".

Here's what I want to do, but the syntax is not exactly right... please, someone who has done this before, help me out :)

INSERT INTO dbo.MyTable (ID, Name)
VALUES (123, 'Timmy'),
    (124, 'Jonny'),
    (125, 'Sally')

I know that this is close to the right syntax. I might need the word "BULK" in there, or something, I can't remember. Any idea?

I need this for a SQL Server 2005 database. I've tried this code, to no avail:

DECLARE @blah TABLE
(
    ID INT NOT NULL PRIMARY KEY,
    Name VARCHAR(100) NOT NULL
)

INSERT INTO @blah (ID, Name)
    VALUES (123, 'Timmy')
    VALUES (124, 'Jonny')
    VALUES (125, 'Sally')

SELECT * FROM @blah

I'm getting Incorrect syntax near the keyword 'VALUES'.

Body:
Others here have suggested a couple multi-record syntaxes. Expounding upon that, I suggest you insert into a temp table first, and insert your main table from there.

The reason for this is loading the data from a query can take longer, and you may end up locking the table or pages longer than is necessary, which slows down other queries running against that table.

-- Make a temp table with the needed columns
select top 0 *
into #temp
from MyTable (nolock)

-- load data into it at your leisure (nobody else is waiting for this table or these pages)
insert #temp (ID, Name)
values (123, 'Timmy'),
(124, 'Jonny'),
(125, 'Sally')

-- Now that all the data is in SQL, copy it over to the real table. This runs much faster in most cases.
insert MyTable (ID, Name)
select ID, Name
from #temp

-- cleanup
drop table #temp

Also, your IDs should probably be identity(1,1) and you probably shouldn't be inserting them, in the vast majority of circumstances. Let SQL decide that stuff for you.


问:
'int' object is not callable when called method of instance class
I don't know how to fix it but I think my code is clear. I am a beginner level python learner.

Here, I made a class Hero that has the method attack. However, when I called the method it says, there is an error 'int' object is not callable.

class Hero(object):
    def __init__(self, name, hp, att_pwr, def_pwr ):
      self.name = name
      self.health = hp
      self.attack = att_pwr
      self.defense = def_pwr

    def attack(self):
      print(self.name + ' is attacking')

Hero1 = Hero('Arif', 75, 50, 40)
Hero1.attack()
```

答:
Look closely, you have an attribute and a method named attack. The class is trying to call the attribute instead of the method. Here is the class that works!

class Hero:
    def __init__(self, name, hp, att_pwr, def_pwr):
        self.name = name
        self.hp = hp
        self.att_pwr = att_pwr
        self.def_pwr = def_pwr

    def attack(self):
        return self.name + " is attacking"

Hero1 = Hero("Arif", 75, 50, 40)
Hero1.attack()
```

<p>This prints out:</p>

```>> 'Arif is attacking'
```

Body:
Look closely, you have an attribute and a method named attack. The class is trying to call the attribute instead of the method. Here is the class that works!

class Hero:
    def __init__(self, name, hp, att_pwr, def_pwr):
        self.name = name
        self.hp = hp
        self.att_pwr = att_pwr
        self.def_pwr = def_pwr

    def attack(self):
        return self.name + " is attacking"

Hero1 = Hero("Arif", 75, 50, 40)
Hero1.attack()

This prints out:

>> 'Arif is attacking'


问:
A way to dynamically move userLocation while testing/showcasing iOS app?
I know of the GPX files, and I am using them, but i find them a hassle both to create and use, and I wanted to freely move the userLocation around a region and not just teleport it from place to place.

I was thinking of creating a function to move the userLocation by clicking the point you want in the map and teleporting there or moving X meters in the click's direction, the problem is that userLocation is get only.

I have to hand in this app and it must be functional with userLocation implemented, so I cannot go around by creating a different annotation and moving that around.

This feature would only be used to showcase the app without needing to actually walk around campus and while testing.

Does anyone have any workaround to move userLocation around without needing GPX files?

I have mapped all locations I want to "walk" to in GPX files, as seen in the image bellow, but I don't want to be "teleported" there as the debug menu does.

答: Within the simulator, you can test what the location changes.  From the menu, select Debug -> Location.  From there, you should have multiple options to choose from. "City Run," "City Bicycle Ride" or "Freeway Drive" are all options that will continue to update and move throughout the simulation.


问:
Read binary file: Matlab differs from R and python
I am trying to recreate a Matlab script that reads a binary file in either R or python. Here is a link to a the test.bin data: https://github.com/AndrewHFarkas/BinaryReadTest

Matlab

```<code>FilePath = 'test.bin'
fid=fopen(FilePath,'r','b');
VersionStr=fread(fid,7,'char')
Version=fread(fid,1,'int16')
SizeFormat='float32'
DataFormat='float32'
EegMegStatus=fread(fid,1,SizeFormat)
NChanExtra=fread(fid,1,SizeFormat)
TrigPoint=fread(fid,1,'float32')
DataTypeVal=fread(fid,1,'float32')
TmpSize=fread(fid,2,SizeFormat)
AvgMat=fread(fid,1,DataFormat)
</code>```

Matlab output:

```<code>VersionStr =
86
101
114
115
105
111
110
Version =
8
SizeFormat =
'float32'
DataFormat =
'float32'
EegMegStatus =
1
NChanExtra =
0
TrigPoint =
1
DataTypeVal =
0
TmpSize =
65
1076
AvgMat =
-12.9650
</code>```

This is my closest attempt with python (I found some of this code from a different stackoverflow answer:

```<code>import numpy as np
import array

def fread(fid, nelements, dtype):
     if dtype is np.str:
         dt = np.uint8  # WARNING: assuming 8-bit ASCII for np.str!
     else:
         dt = dtype

     data_array = np.fromfile(fid, dt, nelements)
     data_array.shape = (nelements, 1)

     return data_array

fid = open('test.bin', 'rb');
print(fread(fid, 7, np.str)) # so far so good!
[[ 86]
 [101]
 [114]
 [115]
 [105]
 [111]
 [110]]

#both of these options return 2048
print(fread(fid, 1, np.int16))
np.fromfile(fid, np.int16, 1)
</code>```

And no matter what else I've tried I can't get any of the same numbers past that point. I have tried using little and big endian settings, but maybe not correctly.

If it helps, here is my closest attempt in R:

```<code>newdata = file("test.bin", "rb")
version_char = readBin(newdata, "character", n=1)
version_char
[1] "Version" # this makes sense because the first 7 bytes to spell Version

version_num = readBin(newdata, "int", size = 1 , n = 1, endian = "little")
version_num
[1] 8 #correct number
</code>```

And nothing after that matches. This is were I get really confused because I was only able to get 8 with a (byte) size = 1 for the version_num, but an int16 should be two bytes as far as I understand. I have tried this code below to read in a float as suggested in another post:

```<code>readBin(newdata, "double", size = 4 , n = 1, endian = "little")
</code>```

Thank you all for your time

答:
struct is in general what you would use to unpack binary data

```<code>>>> keys = "VStr vNum EegMeg nChan trigPoint dType tmpSize[0] tmpSize[1] avgMat".split()
>>> dict(zip(keys,struct.unpack_from(">7sh7f",open("test.bin","rb").read())))
{'nChan': 0.0, 'EegMeg': 1.0, 'dType': 0.0, 'trigPoint': 1.0, 'VStr': 'Version', 'avgMat': -12.964995384216309, 'vNum': 8, 'tmpSize[0]': 65.0, 'tmpSize[1]': 1076.0}
</code>```

the unpack string says unpack a string of 7 characters, followed by a short int followed by 7 float32

Body:
I am trying to recreate a Matlab script that reads a binary file in either R or python. Here is a link to a the test.bin data: https://github.com/AndrewHFarkas/BinaryReadTest

Matlab

FilePath = 'test.bin'
fid=fopen(FilePath,'r','b');
VersionStr=fread(fid,7,'char')
Version=fread(fid,1,'int16')
SizeFormat='float32'
DataFormat='float32'
EegMegStatus=fread(fid,1,SizeFormat)
NChanExtra=fread(fid,1,SizeFormat)
TrigPoint=fread(fid,1,'float32')
DataTypeVal=fread(fid,1,'float32')
TmpSize=fread(fid,2,SizeFormat)
AvgMat=fread(fid,1,DataFormat)

Matlab output:

VersionStr =
86
101
114
115
105
111
110
Version =
8
SizeFormat =
'float32'
DataFormat =
'float32'
EegMegStatus =
1
NChanExtra =
0
TrigPoint =
1
DataTypeVal =
0
TmpSize =
65
1076
AvgMat =
-12.9650

This is my closest attempt with python (I found some of this code from a different stackoverflow answer:

import numpy as np
import array

def fread(fid, nelements, dtype):
     if dtype is np.str:
         dt = np.uint8  # WARNING: assuming 8-bit ASCII for np.str!
     else:
         dt = dtype

     data_array = np.fromfile(fid, dt, nelements)
     data_array.shape = (nelements, 1)

     return data_array

fid = open('test.bin', 'rb');
print(fread(fid, 7, np.str)) # so far so good!
[[ 86]
 [101]
 [114]
 [115]
 [105]
 [111]
 [110]]

#both of these options return 2048
print(fread(fid, 1, np.int16))
np.fromfile(fid, np.int16, 1)

And no matter what else I've tried I can't get any of the same numbers past that point. I have tried using little and big endian settings, but maybe not correctly.

If it helps, here is my closest attempt in R:

newdata = file("test.bin", "rb")
version_char = readBin(newdata, "character", n=1)
version_char
[1] "Version" # this makes sense because the first 7 bytes to spell Version

version_num = readBin(newdata, "int", size = 1 , n = 1, endian = "little")
version_num
[1] 8 #correct number

And nothing after that matches. This is were I get really confused because I was only able to get 8 with a (byte) size = 1 for the version_num, but an int16 should be two bytes as far as I understand. I have tried this code below to read in a float as suggested in another post:

readBin(newdata, "double", size = 4 , n = 1, endian = "little")

Thank you all for your time

Body:
struct is in general what you would use to unpack binary data

>>> keys = "VStr vNum EegMeg nChan trigPoint dType tmpSize[0] tmpSize[1] avgMat".split()
>>> dict(zip(keys,struct.unpack_from(">7sh7f",open("test.bin","rb").read())))
{'nChan': 0.0, 'EegMeg': 1.0, 'dType': 0.0, 'trigPoint': 1.0, 'VStr': 'Version', 'avgMat': -12.964995384216309, 'vNum': 8, 'tmpSize[0]': 65.0, 'tmpSize[1]': 1076.0}

the unpack string says unpack a string of 7 characters, followed by a short int followed by 7 float32


问:
What browser features/plugins for opera, IE, firefox, chrome, safari, etc. do you use for browser compatibility testing?
I use the Nightly Tester Tools for Firefox and Fiddler for IE. What do you use?</p>

答:
In Opera

View > Style

And all those various little selections (such as Outline, Class and Id, etc) have been great help in figuring out the floats and border constraints of DIVs and SPANs, the class and ID names of elements and makes switching back to tweak the code so much faster.

And that shortcut (CTRL+SHIFT+ALT+U in v9) to load the current page into the W3C validator is nifty too.

OwnerDisplayName: not-bob

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: moocha

OwnerDisplayName: Random Echo


问:
What does "var" mean in C#?
In C#, how does keyword var work?

答:
var is a "contextual keyword" in C# meaning you can only use it as a local variable implicitly in the context of the same class that you are using the variable. If you try to use it in a class that you call from "Main" or some other exterior class, or an interface for example you will get the error CS0825 < https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0825 >

See the remarks about when you can and can't use it in the documentation here: < https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables#remarks >

Basically, you should only use this when you are declaring a variable with an implicit value such as "var myValue = "This is the value"; This saves a little time in comparison to saying "string" for example but IMHO not much time is saved and places a constraint on the scalability of your project.

Title: What does "var" mean in C#?

Body: In C#, how does keyword var work?


问:
Deployment to Heroku Error: Cannot find module '/app/server.js'
I'm deploying an Angular 6 application created with the angular-cli to Heroku. The build completes successfully, however, when I go to the deployed application, I get a blank page.

After running the Heroku logs, it appears the error/crash happens upon starting up the node server instance. "Cannot find module '/app/server/js". The server.js file lives under the src directory so I don't know why this is happening.

from the logs:

Here is the package.json, I removed the node and npm engines to run the default versions from the heroku build:

```<code>{
  "name": "blog-app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "node server.js",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ng build --prod"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.0.0",
    "@angular/cdk": "^6.0.0",
    "@angular/cli": "~6.0.0",
    "@angular/common": "^6.0.0",
    "@angular/compiler": "^6.0.0",
    "@angular/compiler-cli": "^6.0.0",
    "@angular/core": "^6.0.0",
    "@angular/forms": "^6.0.0",
    "@angular/http": "^6.0.0",
    "@angular/material": "^6.0.1",
    "@angular/platform-browser": "^6.0.0",
    "@angular/platform-browser-dynamic": "^6.0.0",
    "@angular/router": "^6.0.0",
    "@ng-bootstrap/ng-bootstrap": "^2.0.0",
    "@ngrx/effects": "^5.2.0",
    "@ngrx/store": "^5.2.0",
    "angularfire2": "^5.0.0-rc.8.1-next",
    "bootstrap": "^3.3.7",
    "core-js": "^2.5.4",
    "express": "^4.16.3",
    "firebase": "^5.0.2",
    "ngx-quill": "^3.1.0",
    "rxjs": "^6.0.0",
    "rxjs-compat": "^6.1.0",
    "typescript": "~2.7.2",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.6.0",
    "@angular/language-service": "^6.0.0",
    "@types/jasmine": "~2.8.6",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.2.1",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~1.7.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~1.4.2",
    "karma-jasmine": "~1.1.1",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.3.0",
    "ts-node": "~5.0.1",
    "tslint": "~5.9.1"
  }
}
</code>```

And the server.js:

```<code>import express from "express";
const app = express();

app.use(static(__dirname + '/dist'));

app.all('*', (req, res) => {
  res.status(200).sendFile(__dirname + '/dist/index.html');
});

app.listen(process.env.PORT || 8080);
</code>```

File tree:

Any idea on what the problem could be?

EDIT: I added a Procfile at src/Procfile:

```<code>web: node src/server.js
</code>```

After adding this file, the app still crashes with the following output in the Heroku logs:

答:
Create Procfile in main folder and add:

```<code>web: node src/<you-app-name>.js
</code>```

Check the below image for where to put Procfile:

Body:
I'm deploying an Angular 6 application created with the angular-cli to Heroku. The build completes successfully, however, when I go to the deployed application, I get a blank page.

After running the Heroku logs, it appears the error/crash happens upon starting up the node server instance. "Cannot find module '/app/server/js". The server.js file lives under the src directory so I don't know why this is happening.

from the logs:

Here is the package.json, I removed the node and npm engines to run the default versions from the heroku build:

{
  "name": "blog-app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "node server.js",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ng build --prod"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.0.0",
    "@angular/cdk": "^6.0.0",
    "@angular/cli": "~6.0.0",
    "@angular/common": "^6.0.0",
    "@angular/compiler": "^6.0.0",
    "@angular/compiler-cli": "^6.0.0",
    "@angular/core": "^6.0.0",
    "@angular/forms": "^6.0.0",
    "@angular/http": "^6.0.0",
    "@angular/material": "^6.0.1",
    "@angular/platform-browser": "^6.0.0",
    "@angular/platform-browser-dynamic": "^6.0.0",
    "@angular/router": "^6.0.0",
    "@ng-bootstrap/ng-bootstrap": "^2.0.0",
    "@ngrx/effects": "^5.2.0",
    "@ngrx/store": "^5.2.0",
    "angularfire2": "^5.0.0-rc.8.1-next",
    "bootstrap": "^3.3.7",
    "core-js": "^2.5.4",
    "express": "^4.16.3",
    "firebase": "^5.0.2",
    "ngx-quill": "^3.1.0",
    "rxjs": "^6.0.0",
    "rxjs-compat": "^6.1.0",
    "typescript": "~2.7.2",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.6.0",
    "@angular/language-service": "^6.0.0",
    "@types/jasmine": "~2.8.6",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.2.1",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~1.7.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~1.4.2",
    "karma-jasmine": "~1.1.1",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.3.0",
    "ts-node": "~5.0.1",
    "tslint": "~5.9.1"
  }
}

And the server.js:

import express from "express";
const app = express();

app.use(static(__dirname + '/dist'));

app.all('*', (req, res) => {
  res.status(200).sendFile(__dirname + '/dist/index.html');
});

app.listen(process.env.PORT || 8080);

File tree:

Any idea on what the problem could be?

EDIT: I added a Procfile at src/Procfile:

web: node src/server.js

After adding this file, the app still crashes with the following output in the Heroku logs:

Body:
Create Procfile in main folder and add:

web: node src/<you-app-name>.js

Check the below image for where to put Procfile:


答:
This is because you have an attribute called attack as well as a method with the same name. Maybe you should rename the attack attribute to something else, for example attack_points.

```<code>class Hero(object):
    def __init__(self, name, hp, att_pwr, def_pwr ):
        self.name = name
        self.health = hp
        self.attack_points = att_pwr
        self.defense = def_pwr

    def attack(self):
        print(self.name + ' is attacking')

Hero1 = Hero('Arif', 75, 50, 40)
Hero1.attack()
</code>```

Title: 'int' object is not callable when called method of instance class

Body:
I don't know how to fix it but I think my code is clear. I am a beginner level python learner.

Here, I made a class Hero that has the method attack. However, when I called the method it says, there is an error 'int' object is not callable.

class Hero(object):
    def __init__(self, name, hp, att_pwr, def_pwr ):
      self.name = name
      self.health = hp
      self.attack = att_pwr
      self.defense = def_pwr

    def attack(self):
      print(self.name + ' is attacking')

Hero1 = Hero('Arif', 75, 50, 40)
Hero1.attack()

Body:
This is because you have an attribute called attack as well as a method with the same name. Maybe you should rename the attack attribute to something else, for example attack_points.

class Hero(object):
    def __init__(self, name, hp, att_pwr, def_pwr ):
        self.name = name
        self.health = hp
        self.attack_points = att_pwr
        self.defense = def_pwr

    def attack(self):
        print(self.name + ' is attacking')

Hero1 = Hero('Arif', 75, 50, 40)
Hero1.attack()


问:
data id iteration django
I really do not know how to iterate through my loop to display individual items. I have tried to
rearrange the loop but has worked. The data id id="portfolioModal" is what I want to also iterate for individual items.</p>

```<code>{% for subjects in object %}
    <div class="portfolio-modal modal fade" id="portfolioModal" tabindex="-1" role="dialog" aria-labelledby="portfolioModal1Label" aria-hidden="true">
      <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">
              <i class="fas fa-times"></i>
            </span>
          </button>
          <div class="modal-body text-center">
            <div class="container">
              <div class="row justify-content-center">

                <div class="col-lg-8">
                  <!-- Portfolio Modal - Title -->

                  <h2 class="portfolio-modal-title text-success text-uppercase mb-0">{{subjects.title}}</h2>
                  <!-- Icon Divider -->
                  <div class="divider-custom">
                    <div class="divider-custom-line"></div>
                    <div class="divider-custom-icon">
                      <i class="fas fa-star"></i>
                    </div>
                    <div class="divider-custom-line"></div>
                  </div>
                  <!-- Portfolio Modal - Image -->
                  <img class="img-fluid rounded-circle mb-5" src=" {{subjects.img.url}}" alt="">
                  <!-- Portfolio Modal - Text -->
                 <p>{{subjects.desc}}</p>
                  <button class="btn btn-danger" href="#" data-dismiss="modal">
                    <i class="fas fa-times fa-fw"></i>
                    Close Window
                  </button>

                </div>

              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
    {% endfor %}
</code>```

答:
If you want to iterate just numbers in the loop, you can use the {{ forloop.counter }}, like this:

```<code>{% for subjects in object %}
    <div class="portfolio-modal modal fade" id="portfolioModal-{{ forloop.counter }}" tabindex="-1" role="dialog" aria-labelledby="portfolioModal1Label" aria-hidden="true">

...

{% endfor %}
</code>```

In the for loop inside your template code, ever single object of your the context "object" variable is named "subjects", like you know. So, If you want iterate your div id using a object attribute (suppose object.id), just call it by {{ subjects.id }}:

```<code>{% for subjects in object %}
    <div class="portfolio-modal modal fade" id="portfolioModal-{{ subjects.id }}" tabindex="-1" role="dialog" aria-labelledby="portfolioModal1Label" aria-hidden="true">

...

{% endfor %}
</code>```

When this page is rendered,this will print a simple id=portfolioModal-1, id=portfolioModal-2, id=portfolioModal-3... where numbers are the objects ids

Title: data id iteration django

Body:
I really do not know how to iterate through my loop to display individual items. I have tried to
rearrange the loop but has worked. The data id id="portfolioModal" is what I want to also iterate for individual items.

{% for subjects in object %}

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">

          </button>

{{subjects.title}}

{{subjects.desc}}

                  <button class="btn btn-danger" href="#" data-dismiss="modal">

                    Close Window
                  </button>

    {% endfor %}

Body:
If you want to iterate just numbers in the loop, you can use the {{ forloop.counter }}, like this:

{% for subjects in object %}
    <div class="portfolio-modal modal fade" id="portfolioModal-{{ forloop.counter }}" tabindex="-1" role="dialog" aria-labelledby="portfolioModal1Label" aria-hidden="true">

...

{% endfor %}

In the for loop inside your template code, ever single object of your the context "object" variable is named "subjects", like you know. So, If you want iterate your div id using a object attribute (suppose object.id), just call it by {{ subjects.id }}:

{% for subjects in object %}
    <div class="portfolio-modal modal fade" id="portfolioModal-{{ subjects.id }}" tabindex="-1" role="dialog" aria-labelledby="portfolioModal1Label" aria-hidden="true">

...

{% endfor %}

When this page is rendered,this will print a simple id=portfolioModal-1, id=portfolioModal-2, id=portfolioModal-3... where numbers are the objects ids


问:
tslint to eslint converstion error using auto convert
Since tslint will be deprecated soon, I'm trying to convert tslint rules to eslint.

These are all my rules for tslint.

```<code>{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {
      "arrow-parens": false,
      "interface-name": false,
      "interface-over-type-literal": false,
      "max-classes-per-file": false,
      "max-line-length": false,
      "member-access": false,
      "member-ordering": false,
      "no-angle-bracket-type-assertion": false,
      "no-consecutive-blank-lines": [true, 2],
      "no-var-requires": false,
      "object-literal-shorthand": false,
      "object-literal-sort-keys": false,
      "quotemark": [true, "single", "avoid-template", "avoid-escape"],
      "trailing-comma": "never"
    },
    "rulesDirectory": []
}
</code>```

I've auto generated the tslint to eslint conversion by using npx tslint-to-eslint-config.
And this is auto converted eslint rules

```<code>{
    "env": {
        "browser": true,
        "es6": true,
        "node": true
    },
    "extends": [
        "plugin:@typescript-eslint/recommended",
        "plugin:@typescript-eslint/recommended-requiring-type-checking"
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "project": "tsconfig.json",
        "sourceType": "module"
    },
    "plugins": [
        "@typescript-eslint",
        "@typescript-eslint/tslint"
    ],
    "rules": {
        "@typescript-eslint/adjacent-overload-signatures": "error",
        "@typescript-eslint/array-type": "error",
        "@typescript-eslint/ban-types": "error",
        "@typescript-eslint/class-name-casing": "error",
        "@typescript-eslint/consistent-type-assertions": "off",
        "@typescript-eslint/consistent-type-definitions": "off",
        "@typescript-eslint/explicit-member-accessibility": [
            "off",
            {
                "accessibility": "explicit"
            }
        ],
        "@typescript-eslint/interface-name-prefix": "off",
        "@typescript-eslint/member-ordering": "off",
        "@typescript-eslint/no-empty-function": "error",
        "@typescript-eslint/no-empty-interface": "error",
        "@typescript-eslint/no-explicit-any": "off",
        "@typescript-eslint/no-misused-new": "error",
        "@typescript-eslint/no-namespace": "error",
        "@typescript-eslint/no-parameter-properties": "off",
        "@typescript-eslint/no-use-before-define": "off",
        "@typescript-eslint/no-var-requires": "off",
        "@typescript-eslint/prefer-for-of": "error",
        "@typescript-eslint/prefer-function-type": "error",
        "@typescript-eslint/prefer-namespace-keyword": "error",
        "@typescript-eslint/quotes": [
            "error",
            "single",
            {
                "avoidEscape": true
            }
        ],
        "@typescript-eslint/triple-slash-reference": "error",
        "@typescript-eslint/unified-signatures": "error",
        "arrow-parens": [
            "off",
            "as-needed"
        ],
        "camelcase": "error",
        "comma-dangle": "error",
        "complexity": "off",
        "constructor-super": "error",
        "dot-notation": "error",
        "eqeqeq": [
            "error",
            "smart"
        ],
        "guard-for-in": "error",
        "id-blacklist": [
            "error",
            "any",
            "Number",
            "number",
            "String",
            "string",
            "Boolean",
            "boolean",
            "Undefined",
            "undefined"
        ],
        "id-match": "error",
        "max-classes-per-file": "off",
        "max-len": "off",
        "new-parens": "error",
        "no-bitwise": "error",
        "no-caller": "error",
        "no-cond-assign": "error",
        "no-console": "error",
        "no-debugger": "error",
        "no-empty": "error",
        "no-eval": "error",
        "no-fallthrough": "off",
        "no-invalid-this": "off",
        "no-multiple-empty-lines": [
            "error",
            {
                "max": 2
            }
        ],
        "no-new-wrappers": "error",
        "no-shadow": [
            "error",
            {
                "hoist": "all"
            }
        ],
        "no-throw-literal": "error",
        "no-trailing-spaces": "error",
        "no-undef-init": "error",
        "no-underscore-dangle": "error",
        "no-unsafe-finally": "error",
        "no-unused-expressions": "error",
        "no-unused-labels": "error",
        "no-var": "error",
        "object-shorthand": "off",
        "one-var": [
            "error",
            "never"
        ],
        "prefer-arrow/prefer-arrow-functions": "error",
        "prefer-const": "error",
        "radix": "error",
        "spaced-comment": "error",
        "use-isnan": "error",
        "valid-typeof": "off",
        "@typescript-eslint/tslint/config": [
            "error",
            {
                "rules": {
                    "jsdoc-format": true,
                    "no-reference-import": true
                }
            }
        ]
    }
}
</code>```

When I ran npx eslint ., I get tons of error with @typescript-eslint/parser

```<code>0:0  error  Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser.
The file does not match your project config: dist/templates.js.
The file must be included in at least one of the projects provided
</code>```

I'm pretty new to using tslint or eslint, and I'm not sure how to exactly fix this issue.
Just wondering if I'm missing something crucial for this?

Thanks so much in advance!

答:
Here's what's happening:

typescript-eslint uses your tsconfig.json file to read in a collection of source files

ESLint rules use the TypeScript features provided by typescript-eslint

Those ESLint rules are being run on a file that's not included in your tsconfig.json

This causes a crash because TypeScript information is being requested about a file that TypeScript doesn't know about.

Make sure your ESLint file is set to only run on files included in your tsconfig.json, and this error should go away.

Body:
Since tslint will be deprecated soon, I'm trying to convert tslint rules to eslint.

These are all my rules for tslint.

{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {
      "arrow-parens": false,
      "interface-name": false,
      "interface-over-type-literal": false,
      "max-classes-per-file": false,
      "max-line-length": false,
      "member-access": false,
      "member-ordering": false,
      "no-angle-bracket-type-assertion": false,
      "no-consecutive-blank-lines": [true, 2],
      "no-var-requires": false,
      "object-literal-shorthand": false,
      "object-literal-sort-keys": false,
      "quotemark": [true, "single", "avoid-template", "avoid-escape"],
      "trailing-comma": "never"
    },
    "rulesDirectory": []
}

I've auto generated the tslint to eslint conversion by using npx tslint-to-eslint-config.
And this is auto converted eslint rules

{
    "env": {
        "browser": true,
        "es6": true,
        "node": true
    },
    "extends": [
        "plugin:@typescript-eslint/recommended",
        "plugin:@typescript-eslint/recommended-requiring-type-checking"
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "project": "tsconfig.json",
        "sourceType": "module"
    },
    "plugins": [
        "@typescript-eslint",
        "@typescript-eslint/tslint"
    ],
    "rules": {
        "@typescript-eslint/adjacent-overload-signatures": "error",
        "@typescript-eslint/array-type": "error",
        "@typescript-eslint/ban-types": "error",
        "@typescript-eslint/class-name-casing": "error",
        "@typescript-eslint/consistent-type-assertions": "off",
        "@typescript-eslint/consistent-type-definitions": "off",
        "@typescript-eslint/explicit-member-accessibility": [
            "off",
            {
                "accessibility": "explicit"
            }
        ],
        "@typescript-eslint/interface-name-prefix": "off",
        "@typescript-eslint/member-ordering": "off",
        "@typescript-eslint/no-empty-function": "error",
        "@typescript-eslint/no-empty-interface": "error",
        "@typescript-eslint/no-explicit-any": "off",
        "@typescript-eslint/no-misused-new": "error",
        "@typescript-eslint/no-namespace": "error",
        "@typescript-eslint/no-parameter-properties": "off",
        "@typescript-eslint/no-use-before-define": "off",
        "@typescript-eslint/no-var-requires": "off",
        "@typescript-eslint/prefer-for-of": "error",
        "@typescript-eslint/prefer-function-type": "error",
        "@typescript-eslint/prefer-namespace-keyword": "error",
        "@typescript-eslint/quotes": [
            "error",
            "single",
            {
                "avoidEscape": true
            }
        ],
        "@typescript-eslint/triple-slash-reference": "error",
        "@typescript-eslint/unified-signatures": "error",
        "arrow-parens": [
            "off",
            "as-needed"
        ],
        "camelcase": "error",
        "comma-dangle": "error",
        "complexity": "off",
        "constructor-super": "error",
        "dot-notation": "error",
        "eqeqeq": [
            "error",
            "smart"
        ],
        "guard-for-in": "error",
        "id-blacklist": [
            "error",
            "any",
            "Number",
            "number",
            "String",
            "string",
            "Boolean",
            "boolean",
            "Undefined",
            "undefined"
        ],
        "id-match": "error",
        "max-classes-per-file": "off",
        "max-len": "off",
        "new-parens": "error",
        "no-bitwise": "error",
        "no-caller": "error",
        "no-cond-assign": "error",
        "no-console": "error",
        "no-debugger": "error",
        "no-empty": "error",
        "no-eval": "error",
        "no-fallthrough": "off",
        "no-invalid-this": "off",
        "no-multiple-empty-lines": [
            "error",
            {
                "max": 2
            }
        ],
        "no-new-wrappers": "error",
        "no-shadow": [
            "error",
            {
                "hoist": "all"
            }
        ],
        "no-throw-literal": "error",
        "no-trailing-spaces": "error",
        "no-undef-init": "error",
        "no-underscore-dangle": "error",
        "no-unsafe-finally": "error",
        "no-unused-expressions": "error",
        "no-unused-labels": "error",
        "no-var": "error",
        "object-shorthand": "off",
        "one-var": [
            "error",
            "never"
        ],
        "prefer-arrow/prefer-arrow-functions": "error",
        "prefer-const": "error",
        "radix": "error",
        "spaced-comment": "error",
        "use-isnan": "error",
        "valid-typeof": "off",
        "@typescript-eslint/tslint/config": [
            "error",
            {
                "rules": {
                    "jsdoc-format": true,
                    "no-reference-import": true
                }
            }
        ]
    }
}

When I ran npx eslint ., I get tons of error with @typescript-eslint/parser

0:0  error  Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser.
The file does not match your project config: dist/templates.js.
The file must be included in at least one of the projects provided

I'm pretty new to using tslint or eslint, and I'm not sure how to exactly fix this issue.
Just wondering if I'm missing something crucial for this?

Thanks so much in advance!


问:
How to fix the error - Operand type clash: date is incompatible with int
```<code>INSERT INTO Buy
SELECT Title
    ,Type1
    ,Tedat
    ,DATEADD(DAY, - 2, DATEADD(YEAR, - 1, Tarikh))
    ,Descrip
FROM Buy
WHERE (
    Tarikh BETWEEN 2019-03-21
    AND 2020-03-19
)
</code>```

答:
You need to wrap your dates in quotes, as without them they are being evaluated as a series of integers, which isn't comparable with a date in your WHERE clause:

```<code>INSERT INTO Buy
SELECT      Title,
            Type1,
            Tedat,
            DATEADD(DAY,-2,DATEADD(YEAR,-1,Tarikh)),
            Descrip
FROM        Buy
WHERE       Tarikh BETWEEN '2019-03-21' AND '2020-03-19'
</code>```

Body:
You need to wrap your dates in quotes, as without them they are being evaluated as a series of integers, which isn't comparable with a date in your WHERE clause:

INSERT INTO Buy
SELECT      Title,
            Type1,
            Tedat,
            DATEADD(DAY,-2,DATEADD(YEAR,-1,Tarikh)),
            Descrip
FROM        Buy
WHERE       Tarikh BETWEEN '2019-03-21' AND '2020-03-19'


问:
What does this block of JS code mean?

Possible Duplicate:

  What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

I came across a JS file that can be summarized to the code below:

```<code>   (function(window){
              // some codes here
                    })(window);
</code>```

I wonder what this block of code means? Has the window special meanings, or it is just a parameter? What are the differences between the two "window" we see in the brackets?

Since this function does not have a name, I assume it is an anonymous function, so is it only invoked once? When is it invoked?

答:
It is an immediately invoked function expression. the grouping operator () around a function expression (essentially a function declaration without a name) means that the enclosed function is evaluated and a function object returned. A function followed by a formal parameter list (another set of ()) causes the function to be called, so:

```<code>(function() {
  alert('hey');
})();
</code>```

creates an anonymous function that is called immediately and run once. It doesn't create any global variables and leaves no trace of its existence.

Passing the indentifier window to the function means that it is passes whatever it references. The presumption here (I suppose) is that it will reference a global window object that, in browsers, is the global object. However, in an environment that doesn't have a global window object, it may well be undefined. It is a pointless exercise in my view.

If you are concerned about getting a refernce to the global object, then pass this from the global context:

```<code>(function(global) {
  // global refernces the global object
})(this);
</code>```

Title: What does this block of JS code mean?

Body:
Possible Duplicate:

  What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

I came across a JS file that can be summarized to the code below:

   (function(window){
              // some codes here
                    })(window);

I wonder what this block of code means? Has the window special meanings, or it is just a parameter? What are the differences between the two "window" we see in the brackets?

Since this function does not have a name, I assume it is an anonymous function, so is it only invoked once? When is it invoked?

Body:
It is an immediately invoked function expression. the grouping operator () around a function expression (essentially a function declaration without a name) means that the enclosed function is evaluated and a function object returned. A function followed by a formal parameter list (another set of ()) causes the function to be called, so:

(function() {
  alert('hey');
})();

creates an anonymous function that is called immediately and run once. It doesn't create any global variables and leaves no trace of its existence.

Passing the indentifier window to the function means that it is passes whatever it references. The presumption here (I suppose) is that it will reference a global window object that, in browsers, is the global object. However, in an environment that doesn't have a global window object, it may well be undefined. It is a pointless exercise in my view.

If you are concerned about getting a refernce to the global object, then pass this from the global context:

(function(global) {
  // global refernces the global object
})(this);


答:
You are missing quotes on the date</p>

```<code> INSERT INTO Buy SELECT  Title,Type1,Tedat,DATEADD(DAY,-2,DATEADD(YEAR,-1,Tarikh)),Descrip FROM Buy
                                WHERE(Tarikh BETWEEN '2019-03-21' AND '2020-03-19' )
</code>```

Title: How to fix the error - Operand type clash: date is incompatible with int

Body:
INSERT INTO Buy
SELECT Title
    ,Type1
    ,Tedat
    ,DATEADD(DAY, - 2, DATEADD(YEAR, - 1, Tarikh))
    ,Descrip
FROM Buy
WHERE (
    Tarikh BETWEEN 2019-03-21
    AND 2020-03-19
)

Body:
You are missing quotes on the date

 INSERT INTO Buy SELECT  Title,Type1,Tedat,DATEADD(DAY,-2,DATEADD(YEAR,-1,Tarikh)),Descrip FROM Buy
                                WHERE(Tarikh BETWEEN '2019-03-21' AND '2020-03-19' )