问:
Slow query operations on Azure database
I have 1.2 million rows in Azure data table. The following command:

```<code>DELETE FROM _PPL_DETAIL WHERE RunId <> 229
</code>```

is painfully slow.
There is an index on RunId.
I am deleting most of the data.
229 is a small number of records.
It has been running for an hour now
Should it take this long?
I am pretty sure it will finish.
Is there anything I can do to make operations like this faster?
The database does have a PK, although it is a dummy PK (not used).  I already saw that as an optimization need to help this problem, but it still takes way too long (SQL Server treats a table without a PK differently -- much less efficient).  It is still taking 1+ hour.

答:
Without knowing what database tier is using the database where that statment runs it is not easy to help you. However, let us tell you how the system works so that you can make this determination with a bit more investigation by yourself.

Currently the log commit rate is limited by the tier the database has. Deletes are fundamentally limited on the ability to write out log records (and replicate them to multiple machines in case your main machine dies). When you select records, you don't have to go over the network to N machines and you may not even need to go to the local disk if the records are preserved in memory, so selects are generally expected to be faster than inserts/updates/deletes because of the need to harden log for you. You can read about the specific limits for different reservation sizes are here: DTU Limits and vCore Limits.

One common problem is to do individual operations in a loop (like a cursor or driven from the client). This implies that each statement has a single row updated and thus has to harden each log record serially because the app has to wait for the statement to return before submitting the next statement. You are not hitting that since you are running a big delete as a single statement. That could be slow for other reasons such as:

Locking - if you have other users doing operations on the table, it could block the progress of the delete statement. You can potentially see this by looking at sys.dm_exec_requests to see if your statement is blocking on other locks.

Query Plan choice. If you have to scan a lot of rows to delete a small fraction, you could be blocked on the IO to find them. Looking at the query plan shape will help here, as will set statistics time on (We suggest you change the query to do TOP 100 or similar to get a sense of whether you are doing lots of logical read IOs vs. actual logical writes). This could imply that your on-disk layout is suboptimal for this problem. The general solutions would be to either pick a better indexing strategy or to use partitioning to help you quickly drop groups of rows instead of having to delete all the rows explicitly.

An additional strategy to have better performance with deletes is to perform batching.

Title: Slow query operations on Azure database

Body:
I have 1.2 million rows in Azure data table. The following command:

DELETE FROM _PPL_DETAIL WHERE RunId <> 229

is painfully slow.
There is an index on RunId.
I am deleting most of the data.
229 is a small number of records.
It has been running for an hour now
Should it take this long?
I am pretty sure it will finish.
Is there anything I can do to make operations like this faster?
The database does have a PK, although it is a dummy PK (not used).  I already saw that as an optimization need to help this problem, but it still takes way too long (SQL Server treats a table without a PK differently -- much less efficient).  It is still taking 1+ hour.


来源: stackexchange

问:
Pandas Python problema with match value excel
i have an excel with this values in te column A:

```<code>  A
</code>```

first column

0 3971118279

0 397111859

2 397111859

2 790ZR64-60-0

3 790ZR64-60-0

4 V4B7506333

5 V4B7506333

I read with pandas and merge with openpyxl the especific cell:

```<code>df1 = pd.read_excel(Cfijopath, index_col=None )
wb = load_workbook(Cfijopath)
ws = wb.active

for r in df1.index:
    il = df1.iloc[r,0]
    il = str(il)
    if il == 'nan':
        print('NAN')
    else:
        try:
            index = df1.index[df1['first column'] == il].tolist()
            fir = index[0]
            sec = index[-1]
            ws.merge_cells(f'A{fir}:A{sec}')
        except:
            print('error')
wb.save(Cfijopath)
</code>```

The code work, but when compare the first value (3971118279) doesnt match.
i tried with:

```<code>index = df1.index[df1['first column'] == '3971118279'].tolist()
</code>```

and not work.

This happens with values that have only numbers, how i can compare to get the index in this cases?

Thanks.

Update.
Finally tested only with openpyxl and happened the same.
In the code of below has the "solution":

```<code>wb = openpyxl.load_workbook(file, read_only=True)
ws = wb.active
for row in ws.iter_rows():
        for cell in row:
            val = str(cell.value)
            if val == "3971118279":
                print(ws.cell(row=cell.row, column=1).row)
                print(type(cell.value))
                print(type(val))
</code>```

Output:

```<code>2
<class 'int'>
<class 'str'>
3
<class 'int'>
<class 'str'>
</code>```

The problem happen because the cell value with only numbers is considered "int".
The solution is convert to "str" before the compare.

答:
```<code>wb = openpyxl.load_workbook(file, read_only=True)
ws = wb.active
for row in ws.iter_rows():
        for cell in row:
            val = str(cell.value)
            if val == "3971118279":
                print(ws.cell(row=cell.row, column=1).row)
                print(type(cell.value))
                print(type(val))

Output:

2
<class 'int'>
<class 'str'>
3
<class 'int'>
<class 'str'>
</code>```

The problem happen because the cell value with only numbers is considered "int". The solution is convert to "str" before the compare

ContentLicense: CC BY-SA 4.0

Body:
i have an excel with this values in te column A:

  A

first column

0 3971118279

0 397111859

2 397111859

2 790ZR64-60-0

3 790ZR64-60-0

4 V4B7506333

5 V4B7506333

I read with pandas and merge with openpyxl the especific cell:

df1 = pd.read_excel(Cfijopath, index_col=None )
wb = load_workbook(Cfijopath)
ws = wb.active

for r in df1.index:
    il = df1.iloc[r,0]
    il = str(il)
    if il == 'nan':
        print('NAN')
    else:
        try:
            index = df1.index[df1['first column'] == il].tolist()
            fir = index[0]
            sec = index[-1]
            ws.merge_cells(f'A{fir}:A{sec}')
        except:
            print('error')
wb.save(Cfijopath)

The code work, but when compare the first value (3971118279) doesnt match.
i tried with:

index = df1.index[df1['first column'] == '3971118279'].tolist()

and not work.

This happens with values that have only numbers, how i can compare to get the index in this cases?

Thanks.

Update.
Finally tested only with openpyxl and happened the same.
In the code of below has the "solution":

wb = openpyxl.load_workbook(file, read_only=True)
ws = wb.active
for row in ws.iter_rows():
        for cell in row:
            val = str(cell.value)
            if val == "3971118279":
                print(ws.cell(row=cell.row, column=1).row)
                print(type(cell.value))
                print(type(val))

Output:

2
<class 'int'>
<class 'str'>
3
<class 'int'>
<class 'str'>

The problem happen because the cell value with only numbers is considered "int".
The solution is convert to "str" before the compare.


问:
Problem with Recursively Packing Boxes into a Container
I am having problem with code I am writing which is supposed to take a list of boxes of varying size, and pack them into a single large container box.

The main method which is supposed to implement a solution is called fillContainerBox(). I have a basic nested if statement which will work for packing the first few boxes, but the code fails when it is necessary to unpack more than 1 box.

```<code>/**Container Box Class which sorts using recursion
 *
 * @author Richard McCormick
 */
  public class ContainerBoxClass extends java.lang.Object
  {
  private static int CLEAR_BOX = 102;
  private static int FILL_BOX = 101;
  private static final char DEFAULT_FIELD_CHAR = 45;
  private static final int MAX_NUM_BOXES = 26;
  private static final int NO_BOXES_AVAILABLE = -1;
  private BoxClass[] boxList = new BoxClass[MAX_NUM_BOXES];
  private char[][] containerBoxField;
  private int containerBoxHeight = 0;
  private int containerBoxWidth = 0;
  private int numBoxesAvailable = 0;

  //Shows what you are doing
  private boolean displayFlag = false;

  /**Default constructor class
   * @param initBoxHeight - Height of container
   * @param initBoxWidth  - Width of container
   */
  ContainerBoxClass(int initBoxHeight, int initBoxWidth)
  {
     containerBoxHeight = initBoxHeight;
     containerBoxWidth = initBoxWidth;
     containerBoxField = new char[containerBoxWidth][containerBoxHeight];

     //Populates field with empty values
     for (int y = 0; y < containerBoxHeight; y++)
        {
           for (int x = 0; x < containerBoxWidth; x++)
              {
                 containerBoxField[x][y] = DEFAULT_FIELD_CHAR;
              }
        }

     displayFlag = false;
  }

  /**Adds a new box to list of boxes
   * @param boxWidth
   * @param boxHeight
   * @return success
   */
  public boolean addBoxToList(int boxWidth, int boxHeight)
  {
     //Initialize return
     boolean success = false;

     //Checks that there is room
     if (numBoxesAvailable < MAX_NUM_BOXES)
        {
           //Creates a new box
           BoxClass tempBox = new BoxClass(boxWidth, boxHeight);
           tempBox.unsetUsedState();

           //Increments available boxes
           boxList[numBoxesAvailable] = tempBox;
           numBoxesAvailable++;

           //Success
           success = true;
        }

     return success;
  }

  /**Checks location to see if box will fit
   *
   * @param testLocation  - Point class
   * @param testBox       - Box class
   *
   * @return fits         - Boolean indicator
   */
  private boolean checkForFitInField(PointClass testLocation, BoxClass testBox)
  {
     boolean fits = false;

     //Dimensions of testBox
     int testWidth = testBox.getWidth();
     int testHeight = testBox.getHeight();

     //Position of test point
     int testLocX = testLocation.getXPos();
     int testLocY = testLocation.getYPos();

     System.out.println("Test location: " + testLocX + " " + testLocY);

     //Booleans to see if box is out of bounds or not
     boolean inBoundsX = ((testLocX + testWidth) < containerBoxWidth);
     boolean inBoundsY = ((testLocY + testHeight) < containerBoxHeight);

     //If size fits within the container at desired location
     if (inBoundsX && inBoundsY)
        {
           int numOccupied = 0;

           //Iterates through location to determine if empty
           for (int ycounter = testLocY; ycounter < (testLocY + testHeight); ycounter++)
              {
                 for (int xcounter = testLocX; xcounter < (testLocX + testWidth); xcounter++)
                    {
                       //If there is something in location bounds, location not empty
                       if (containerBoxField[xcounter][ycounter] != DEFAULT_FIELD_CHAR)
                          {
                             numOccupied++;
                          }
                    }
              }

           if (numOccupied == 0)
              {
                 fits = true;
              }
        }

     return fits;
  }

  /**Displays the items in box
   *
   */
  public void displayField()
  {
     String row;

     //Prints field from top down, to preserve order/location
     for (int height = containerBoxHeight - 1; height >= 0; height--)
        {
           //Clears row each iteration
           row = "";

           //Iterates through columns in row
           for (int width = 0; width < containerBoxWidth; width++)
              {
                 //Checks to see if location is empty or not
                 if (containerBoxField[width][height] != DEFAULT_FIELD_CHAR)
                    {
                       row += " X ";
                    }
                 else
                    {
                       row += " " + DEFAULT_FIELD_CHAR + " ";
                    }
              }
           System.out.println(row);
        }
     System.out.println("===================================");
  }

  /**Fills a location in container box with a given box
   *
   * @param boxLocation   - Location to pack box
   * @param fillBox       - Box to be packed
   * @param clearFlag     - Indicates if box is to be packed or removed
   */
  public void fillBoxLocation(PointClass boxLocation, BoxClass fillBox, int clearFlag)
  {
     //Sets the starting and end positions for X-Axis
     int xstart = boxLocation.getXPos();
     int xend = xstart + fillBox.getWidth();

     //Sets the starting and end positions for Y-Axis
     int ystart = boxLocation.getYPos();
     int yend = ystart + fillBox.getHeight();

     //Output for testing
     System.out.println("Attempting to fill box of size: " + fillBox.getWidth() + " " + fillBox.getHeight());
     System.out.println("At location: " + xstart + " " + ystart);

     //Iterates through each row
     for (int ycounter = ystart; ycounter < yend; ycounter++)
        {
           //Iterates through each column
           for (int xcounter = xstart; xcounter < xend; xcounter++)
              {
                 //If clearFlag is set to fill box
                 if (clearFlag == FILL_BOX)
                    {
                       //Fill box
                       containerBoxField[xcounter][ycounter] = (char)FILL_BOX;
                       fillBox.setUsedState();
                    }

                 //Otherwise, erase box
                 else if (clearFlag == CLEAR_BOX)
                    {
                       containerBoxField[xcounter][ycounter] = (char)DEFAULT_FIELD_CHAR;
                       fillBox.unsetUsedState();
                    }
              }
        }
  }

  /**Attempts to fill the container class with boxes
   *
   * @return success   - Boolean value indicating operation success
   */
  public boolean fillContainerBox()
  {
     boolean success = false;

     int currentBoxIndex = 0;
     int previousBoxIndex = -1;
     BoxClass currentBox;
     BoxClass previousBox = new BoxClass();
     PointClass currentLocation;
     PointClass previousLocation = new PointClass();

     while (findNextUnusedBoxIndex(0) != NO_BOXES_AVAILABLE)
        {
           currentBoxIndex = findNextUnusedBoxIndex(0);
           currentBox = boxList[currentBoxIndex];
           currentLocation = findNextOpenLocation();
           BoxClass nextBox = boxList[currentBoxIndex + 1];

           if (checkForFitInField(currentLocation, currentBox))
              {
                 fillBoxLocation(currentLocation, currentBox, FILL_BOX);
                 PointClass nextLoc = new PointClass();
                 nextLoc = findNextOpenLocation();
                 if (checkForFitInField(nextLoc, nextBox) != true)
                    {
                       fillBoxLocation(currentLocation, currentBox, CLEAR_BOX);
                       fillBoxLocation(currentLocation, nextBox, FILL_BOX);
                    }
              }

           previousLocation = currentLocation;
           previousBox = currentBox;

           if (displayFlag)
              {
                 displayField();
              }
        }

     return success;
  }

  /**Finds the next open location in the container box
   *
   * @return openLocation   - PointClass object containing first open location
   */
  private PointClass findNextOpenLocation()
  {
     //Instantiates return variable as empty PointClass
     PointClass openLocation = new PointClass();

     //Boolean value which indicates whether location has been found
     boolean hasLocation = false;

     //Iterates through each row
     for (int ycounter = 0; ycounter < containerBoxHeight; ycounter++)
        {
           //Iterates through each column
           for (int xcounter = 0; xcounter < containerBoxWidth; xcounter++)
              {
                 //If item at current location is empty, and no item has yet been found
                 if (containerBoxField[xcounter][ycounter] == DEFAULT_FIELD_CHAR && hasLocation == false)
                    {
                       //Set current location as first open location
                       openLocation.setXPos(xcounter);
                       openLocation.setYPos(ycounter);

                       //Indicate that location has been found
                       hasLocation = true;
                    }
              }
        }

     //Return the open location
     return openLocation;
  }

  /**Finds the next unused box in boxList, starting at provided index
   *
   * @param startAtIndex  - Index to begin searching at
   * @return indexFinal   - Index of first unused box
   */
  private int findNextUnusedBoxIndex(int startAtIndex)
  {
     //Sets up return and internal vars
     int indexFinal = NO_BOXES_AVAILABLE;
     int counter = startAtIndex;

     //Iterates through available boxes
     while (counter < numBoxesAvailable)
        {
           //If box has already been used, skip and increment
           if (boxList[counter].isUsed())
              {
                 counter++;
              }

           //Otherwise, return unused box index & terminate
           else
              {
                 indexFinal = counter;
                 counter = numBoxesAvailable;
              }
        }

     //Return unused box index
     return indexFinal;
  }

  /**Sets display flag
   *
   * @param setState   - Boolean value to set displayFlag to
   */
  public void setDisplayFlag(boolean setState)
  {
     //If display flag is not already equal to set state
     if (setState != displayFlag)
        {
           //Set new flag state
           displayFlag = setState;
        }
  }
}
</code>```

Please excuse my messy code. I have been trying to find a solution but have not found one.

答:
Consider using a greedy algorithm.

You start with a box (let's call it the package) that's going to contain the other boxes. Of the boxes you need to put into the package, put the largest box in first (You could acheive this by sorting your list of boxes by volume in descending order, E.G. [largest box, 2nd largest, ..., smallest box]) . Depending on the size of this box, the package might have some volume left over we can fill with other boxes. Now, in the remaining volumes we can try placing the second largest box following the same method used to fill the package. All we would have to do is partition the remaining space of the package and treat those partitions as smaller versions of the whole problem.

Body:
I am having problem with code I am writing which is supposed to take a list of boxes of varying size, and pack them into a single large container box.

The main method which is supposed to implement a solution is called fillContainerBox(). I have a basic nested if statement which will work for packing the first few boxes, but the code fails when it is necessary to unpack more than 1 box.

/**Container Box Class which sorts using recursion
 *
 * @author Richard McCormick
 */
  public class ContainerBoxClass extends java.lang.Object
  {
  private static int CLEAR_BOX = 102;
  private static int FILL_BOX = 101;
  private static final char DEFAULT_FIELD_CHAR = 45;
  private static final int MAX_NUM_BOXES = 26;
  private static final int NO_BOXES_AVAILABLE = -1;
  private BoxClass[] boxList = new BoxClass[MAX_NUM_BOXES];
  private char[][] containerBoxField;
  private int containerBoxHeight = 0;
  private int containerBoxWidth = 0;
  private int numBoxesAvailable = 0;

  //Shows what you are doing
  private boolean displayFlag = false;

  /**Default constructor class
   * @param initBoxHeight - Height of container
   * @param initBoxWidth  - Width of container
   */
  ContainerBoxClass(int initBoxHeight, int initBoxWidth)
  {
     containerBoxHeight = initBoxHeight;
     containerBoxWidth = initBoxWidth;
     containerBoxField = new char[containerBoxWidth][containerBoxHeight];

     //Populates field with empty values
     for (int y = 0; y < containerBoxHeight; y++)
        {
           for (int x = 0; x < containerBoxWidth; x++)
              {
                 containerBoxField[x][y] = DEFAULT_FIELD_CHAR;
              }
        }

     displayFlag = false;
  }

  /**Adds a new box to list of boxes
   * @param boxWidth
   * @param boxHeight
   * @return success
   */
  public boolean addBoxToList(int boxWidth, int boxHeight)
  {
     //Initialize return
     boolean success = false;

     //Checks that there is room
     if (numBoxesAvailable < MAX_NUM_BOXES)
        {
           //Creates a new box
           BoxClass tempBox = new BoxClass(boxWidth, boxHeight);
           tempBox.unsetUsedState();

           //Increments available boxes
           boxList[numBoxesAvailable] = tempBox;
           numBoxesAvailable++;

           //Success
           success = true;
        }

     return success;
  }

  /**Checks location to see if box will fit
   *
   * @param testLocation  - Point class
   * @param testBox       - Box class
   *
   * @return fits         - Boolean indicator
   */
  private boolean checkForFitInField(PointClass testLocation, BoxClass testBox)
  {
     boolean fits = false;

     //Dimensions of testBox
     int testWidth = testBox.getWidth();
     int testHeight = testBox.getHeight();

     //Position of test point
     int testLocX = testLocation.getXPos();
     int testLocY = testLocation.getYPos();

     System.out.println("Test location: " + testLocX + " " + testLocY);

     //Booleans to see if box is out of bounds or not
     boolean inBoundsX = ((testLocX + testWidth) < containerBoxWidth);
     boolean inBoundsY = ((testLocY + testHeight) < containerBoxHeight);

     //If size fits within the container at desired location
     if (inBoundsX && inBoundsY)
        {
           int numOccupied = 0;

           //Iterates through location to determine if empty
           for (int ycounter = testLocY; ycounter < (testLocY + testHeight); ycounter++)
              {
                 for (int xcounter = testLocX; xcounter < (testLocX + testWidth); xcounter++)
                    {
                       //If there is something in location bounds, location not empty
                       if (containerBoxField[xcounter][ycounter] != DEFAULT_FIELD_CHAR)
                          {
                             numOccupied++;
                          }
                    }
              }

           if (numOccupied == 0)
              {
                 fits = true;
              }
        }

     return fits;
  }

  /**Displays the items in box
   *
   */
  public void displayField()
  {
     String row;

     //Prints field from top down, to preserve order/location
     for (int height = containerBoxHeight - 1; height >= 0; height--)
        {
           //Clears row each iteration
           row = "";

           //Iterates through columns in row
           for (int width = 0; width < containerBoxWidth; width++)
              {
                 //Checks to see if location is empty or not
                 if (containerBoxField[width][height] != DEFAULT_FIELD_CHAR)
                    {
                       row += " X ";
                    }
                 else
                    {
                       row += " " + DEFAULT_FIELD_CHAR + " ";
                    }
              }
           System.out.println(row);
        }
     System.out.println("===================================");
  }

  /**Fills a location in container box with a given box
   *
   * @param boxLocation   - Location to pack box
   * @param fillBox       - Box to be packed
   * @param clearFlag     - Indicates if box is to be packed or removed
   */
  public void fillBoxLocation(PointClass boxLocation, BoxClass fillBox, int clearFlag)
  {
     //Sets the starting and end positions for X-Axis
     int xstart = boxLocation.getXPos();
     int xend = xstart + fillBox.getWidth();

     //Sets the starting and end positions for Y-Axis
     int ystart = boxLocation.getYPos();
     int yend = ystart + fillBox.getHeight();

     //Output for testing
     System.out.println("Attempting to fill box of size: " + fillBox.getWidth() + " " + fillBox.getHeight());
     System.out.println("At location: " + xstart + " " + ystart);

     //Iterates through each row
     for (int ycounter = ystart; ycounter < yend; ycounter++)
        {
           //Iterates through each column
           for (int xcounter = xstart; xcounter < xend; xcounter++)
              {
                 //If clearFlag is set to fill box
                 if (clearFlag == FILL_BOX)
                    {
                       //Fill box
                       containerBoxField[xcounter][ycounter] = (char)FILL_BOX;
                       fillBox.setUsedState();
                    }

                 //Otherwise, erase box
                 else if (clearFlag == CLEAR_BOX)
                    {
                       containerBoxField[xcounter][ycounter] = (char)DEFAULT_FIELD_CHAR;
                       fillBox.unsetUsedState();
                    }
              }
        }
  }

  /**Attempts to fill the container class with boxes
   *
   * @return success   - Boolean value indicating operation success
   */
  public boolean fillContainerBox()
  {
     boolean success = false;

     int currentBoxIndex = 0;
     int previousBoxIndex = -1;
     BoxClass currentBox;
     BoxClass previousBox = new BoxClass();
     PointClass currentLocation;
     PointClass previousLocation = new PointClass();

     while (findNextUnusedBoxIndex(0) != NO_BOXES_AVAILABLE)
        {
           currentBoxIndex = findNextUnusedBoxIndex(0);
           currentBox = boxList[currentBoxIndex];
           currentLocation = findNextOpenLocation();
           BoxClass nextBox = boxList[currentBoxIndex + 1];

           if (checkForFitInField(currentLocation, currentBox))
              {
                 fillBoxLocation(currentLocation, currentBox, FILL_BOX);
                 PointClass nextLoc = new PointClass();
                 nextLoc = findNextOpenLocation();
                 if (checkForFitInField(nextLoc, nextBox) != true)
                    {
                       fillBoxLocation(currentLocation, currentBox, CLEAR_BOX);
                       fillBoxLocation(currentLocation, nextBox, FILL_BOX);
                    }
              }

           previousLocation = currentLocation;
           previousBox = currentBox;

           if (displayFlag)
              {
                 displayField();
              }
        }

     return success;
  }

  /**Finds the next open location in the container box
   *
   * @return openLocation   - PointClass object containing first open location
   */
  private PointClass findNextOpenLocation()
  {
     //Instantiates return variable as empty PointClass
     PointClass openLocation = new PointClass();

     //Boolean value which indicates whether location has been found
     boolean hasLocation = false;

     //Iterates through each row
     for (int ycounter = 0; ycounter < containerBoxHeight; ycounter++)
        {
           //Iterates through each column
           for (int xcounter = 0; xcounter < containerBoxWidth; xcounter++)
              {
                 //If item at current location is empty, and no item has yet been found
                 if (containerBoxField[xcounter][ycounter] == DEFAULT_FIELD_CHAR && hasLocation == false)
                    {
                       //Set current location as first open location
                       openLocation.setXPos(xcounter);
                       openLocation.setYPos(ycounter);

                       //Indicate that location has been found
                       hasLocation = true;
                    }
              }
        }

     //Return the open location
     return openLocation;
  }

  /**Finds the next unused box in boxList, starting at provided index
   *
   * @param startAtIndex  - Index to begin searching at
   * @return indexFinal   - Index of first unused box
   */
  private int findNextUnusedBoxIndex(int startAtIndex)
  {
     //Sets up return and internal vars
     int indexFinal = NO_BOXES_AVAILABLE;
     int counter = startAtIndex;

     //Iterates through available boxes
     while (counter < numBoxesAvailable)
        {
           //If box has already been used, skip and increment
           if (boxList[counter].isUsed())
              {
                 counter++;
              }

           //Otherwise, return unused box index & terminate
           else
              {
                 indexFinal = counter;
                 counter = numBoxesAvailable;
              }
        }

     //Return unused box index
     return indexFinal;
  }

  /**Sets display flag
   *
   * @param setState   - Boolean value to set displayFlag to
   */
  public void setDisplayFlag(boolean setState)
  {
     //If display flag is not already equal to set state
     if (setState != displayFlag)
        {
           //Set new flag state
           displayFlag = setState;
        }
  }
}

Please excuse my messy code. I have been trying to find a solution but have not found one.


问:
How do I get the next day's date in JS in YYYY-MM-DD format?
Seems like a simple question, but all the timezone ins and outs in JS are causing me a bunch of headaches.

Basically, if I have a date like the following:

```<code>2018-04-06
</code>```

I want to be able to get the next day's date as such:

```<code>2018-04-07
</code>```

I found the following snippet on SO for doing this (kind of):

```<code>var date = new Date('2018-04-06');
date.setDate(date + 1);
</code>```

The problem is that I'm getting the date back with the adjusted timezone, and because I'm in the US ET timezone, it's giving me that date minus five hours, which is actually the same day as where I started.

I've been through countless SO posts trying to find an answer to this seemingly simple question, but for any given date, regardless of the timezone the user is in, how do I get the next day's date in YYYY-MM-DD format? Thank you.

答:
The logic would be to add 24 hours in milliseconds to the current time. As an example:

```<code>var myDate = new Date();
var oneMoreDay = new Date();
oneMoreDay.setTime(myDate.getTime() + 86400000);
console.log(myDate.getDate());
console.log(oneMoreDay.getDate());
</code>```

An additional day has been added to the oneMoreDay variable. In your specific example you just wanted to add one more day to the ORIGINAL variable, so i'd do something such as:

```<code>date.setTime(date.getTime() + 86400000);
</code>```

Body:
Seems like a simple question, but all the timezone ins and outs in JS are causing me a bunch of headaches.

Basically, if I have a date like the following:

2018-04-06

I want to be able to get the next day's date as such:

2018-04-07

I found the following snippet on SO for doing this (kind of):

var date = new Date('2018-04-06');
date.setDate(date + 1);

The problem is that I'm getting the date back with the adjusted timezone, and because I'm in the US ET timezone, it's giving me that date minus five hours, which is actually the same day as where I started.

I've been through countless SO posts trying to find an answer to this seemingly simple question, but for any given date, regardless of the timezone the user is in, how do I get the next day's date in YYYY-MM-DD format? Thank you.

Body:
The logic would be to add 24 hours in milliseconds to the current time. As an example:

var myDate = new Date();
var oneMoreDay = new Date();
oneMoreDay.setTime(myDate.getTime() + 86400000);
console.log(myDate.getDate());
console.log(oneMoreDay.getDate());

An additional day has been added to the oneMoreDay variable. In your specific example you just wanted to add one more day to the ORIGINAL variable, so i'd do something such as:

date.setTime(date.getTime() + 86400000);


问:
How does PyOpenGL pick the colors to draw each shape?
I am in the middle of a PyQt5 PyOpenGL project. I am trying to draw a white wireframe cube with a bunch of colored solid cubes. Wireframe cubes are drawn from a list of tuple points, and a list of tuple references to those points. Solid cubes are drawn from a list of tuple references to the points. Here is the cube code:

class cube():
    render = True
    solid = False
    color = (1, 1, 1)

    def config(self, x, y, z, size = 0.1, solid = False, color = (1, 1, 1)):
        self.solid = solid
        self.color = color
        self.size = size / 2
        s = self.size
        self.vertices = [
                         (-s + x, s + y, -s + z),
                         (s + x, s + y, -s + z),
                         (s + x, -s + y, -s + z),
                         (-s + x, -s + y, -s + z),
                         (-s + x, s + y, s + z),
                         (s + x, s + y, s + z),
                         (s + x, -s + y, s + z),
                         (-s + x, -s + y, s + z)
                       ]
        self.edges = [
                      (0,1), (0,3), (0,4), (2,1),
                      (2,3), (2,6), (7,3), (7,4),
                      (7,6), (5,1), (5,4), (5,6)
                     ]
        self.facets = [
                       (0, 1, 2, 3), (0, 1, 6, 5),
                       (0, 3, 7, 4), (6, 5, 1, 2),
                       (6, 7, 4, 5), (6, 7, 3, 2)
                      ]
    def show(self):
        self.render = True
    def hide(self):
        self.render = False
```

<p>To render a cube, I get the size of a list held in my <code>mainWindow</code> class, then append an instance of the cube class to that list. I can then reference that instance by using the size before appending. Here is the code for the render function:</p>

<pre class="lang-py prettyprint-override"><code>def paintGL(self):
    glLoadIdentity()
    gluPerspective(45, self.width / self.height, 0.1, 110.0)    #set perspective?
    glTranslatef(0, 0, self.zoomLevel)    #I used -10 instead of -2 in the PyGame version.
    glRotatef(self.rotateDegreeV, 1, 0, 0)    #I used 2 instead of 1 in the PyGame version.
    glRotatef(self.rotateDegreeH, 0, 0, 1)
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

    if len(self.shapes) != 0:
        glBegin(GL_LINES)
        for s in self.shapes:
            if s.render and not s.solid:
                for e in s.edges:
                    for v in e:
                        glVertex3fv(s.vertices[v])
        glEnd()

        glBegin(GL_QUADS)
        for s in self.shapes:
            if s.render and s.solid:
                for f in s.facets:
                    for v in f:
                        glColor3fv(s.color)
                        glVertex3fv(s.vertices[v])
        glEnd()
</code>```

If I render just one cube in wireframe, it renders white. If I add a red solid cube and a blue solid cube after it, the wireframe cube is colored in the last color used, whatever it may be. For example:

    self.shapes.append(self.cube())
    self.shapes.append(self.cube())
    self.shapes.append(self.cube())
    self.shapes[0].config(-1, 0, 0, size = 0.5, solid = False)
    self.shapes[1].config(0, 0, 0, size = 0.5, solid = True, color = (1, 0, 0))
    self.shapes[2].config(1, 0, 0, size = 0.5, solid = True, color = (0, 0, 1))
```

<p>Result:</p>

<p><img src="https://i.stack.imgur.com/6dTSM.png" alt="cubes"></p>

<p>How can I make my wireframes render in the default white or a different color? I would expect <code>glClear()</code> would reset it and draw the wireframe in white, given that it is the first one.</p>

<p>Here is the full code:</p>

<pre class="lang-py prettyprint-override"><code>import sys
from PyQt5.QtWidgets import (
                             QApplication, QMainWindow, QSlider,
                             QOpenGLWidget, QLabel, QPushButton
                            )
from PyQt5.QtCore import Qt
from OpenGL.GL import (
                       glLoadIdentity, glTranslatef, glRotatef,
                       glClear, glBegin, glEnd,
                       glColor3fv, glVertex3fv,
                       GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT,
                       GL_QUADS, GL_LINES
                      )
from OpenGL.GLU import gluPerspective

class mainWindow(QMainWindow):    #Main class.
    shapes = []    #this will hold instances of the following classes:
    zoomLevel = -10
    rotateDegreeV = -90
    rotateDegreeH = 0

    class cube():
        render = True
        solid = False
        color = (1, 1, 1)

        def config(self, x, y, z, size = 0.1, solid = False, color = (1, 1, 1)):
            self.solid = solid
            self.color = color
            self.size = size
            s = self.size / 2
            self.vertices = [
                             (-s + x, s + y, -s + z),
                             (s + x, s + y, -s + z),
                             (s + x, -s + y, -s + z),
                             (-s + x, -s + y, -s + z),
                             (-s + x, s + y, s + z),
                             (s + x, s + y, s + z),
                             (s + x, -s + y, s + z),
                             (-s + x, -s + y, s + z)
                            ]
            self.edges = [
                          (0,1), (0,3), (0,4), (2,1),
                          (2,3), (2,6), (7,3), (7,4),
                          (7,6), (5,1), (5,4), (5,6)
                         ]
            self.facets = [
                           (0, 1, 2, 3), (0, 1, 6, 5),
                           (0, 3, 7, 4), (6, 5, 1, 2),
                           (6, 7, 4, 5), (6, 7, 3, 2)
                          ]
        def show(self):
            self.render = True
        def hide(self):
            self.render = False

    def keyPressEvent(self, event):    #This is the keypress detector. I use this to determine input to edit grids.
        try:
            key = event.key()
            if key == 87:
                self.rotateV(5)
            elif key == 65:
                self.rotateH(5)
            elif key == 83:
                self.rotateV(-5)
            elif key == 68:
                self.rotateH(-5)
            elif key == 67:
                self.zoom(1)
            elif key == 88:
                self.zoom(-1)
        except:
            pass

    def __init__(self):
        super(mainWindow, self).__init__()
        self.width = 700    #Variables used for the setting of the size of everything
        self.height = 600
        self.setGeometry(0, 0, self.width, self.height)    #Set the window size
        self.shapes.append(self.cube())
        self.shapes.append(self.cube())
        self.shapes.append(self.cube())
        self.shapes[0].config(-1, 0, 0, size = 0.5, solid = False)
        self.shapes[1].config(0, 0, 0, size = 0.5, solid = True, color = (1, 0, 0))
        self.shapes[2].config(1, 0, 0, size = 0.5, solid = True, color = (0, 0, 1))

    def setupUI(self):
        self.openGLWidget = QOpenGLWidget(self)    #Create the GLWidget
        self.openGLWidget.setGeometry(0, 0, self.width, self.height)    #Size it the same as the window.
        self.openGLWidget.initializeGL()
        self.openGLWidget.resizeGL(self.width, self.height)    #Resize GL's knowledge of the window to match the physical size?
        self.openGLWidget.paintGL = self.paintGL    #override the default function with my own?

    def zoom(self, value):
        self.zoomLevel += value
        self.openGLWidget.update()

    def rotateV(self, value):
        self.rotateDegreeV += value
        self.openGLWidget.update()

    def rotateH(self, value):
        self.rotateDegreeH += value
        self.openGLWidget.update()

    def paintGL(self):
        glLoadIdentity()
        gluPerspective(45, self.width / self.height, 0.1, 110.0)    #set perspective?
        glTranslatef(0, 0, self.zoomLevel)    #I used -10 instead of -2 in the PyGame version.
        glRotatef(self.rotateDegreeV, 1, 0, 0)    #I used 2 instead of 1 in the PyGame version.
        glRotatef(self.rotateDegreeH, 0, 0, 1)
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        if len(self.shapes) != 0:
            glBegin(GL_LINES)
            for s in self.shapes:
                if s.render and not s.solid:
                    for e in s.edges:
                        for v in e:
                            glVertex3fv(s.vertices[v])
            glEnd()

            glBegin(GL_QUADS)
            for s in self.shapes:
                if s.render and s.solid:
                    for f in s.facets:
                        for v in f:
                            glColor3fv(s.color)
                            glVertex3fv(s.vertices[v])
            glEnd()

app = QApplication([])
window = mainWindow()
window.setupUI()
window.show()
sys.exit(app.exec_())
</code>```

答:
OpenGL is a state engine. Once a state is set, it is kept until it is changed again, even beyond frames. The current color is a global state. When glColor*  is called, then the current color is set.

When glVertex*  is called, then the current color, normal and texture coordinates are associated with the vertex.

That means, the proper color has to be set before the vertices are specified. You missed to set the color attribute, before you draw the wireframe cube:

class mainWindow(QMainWindow):    #Main class.
    # [...]

    def paintGL(self):
        # [...]

        if len(self.shapes) != 0:
            glBegin(GL_LINES)
            for s in self.shapes:
                glColor3fv(s.color)  # <------------------------
                if s.render and not s.solid:
                    for e in s.edges:
                        for v in e:
                            glVertex3fv(s.vertices[v])
            glEnd()

            glBegin(GL_QUADS)
            for s in self.shapes:
                glColor3fv(s.color)
                if s.render and s.solid:
                    for f in s.facets:
                        for v in f:
                            glVertex3fv(s.vertices[v])
            glEnd()
```

Note, it is not necessary to set the current color before each call to glVertex3fv. It is sufficient to set the current color once, when it is changed. The new color is associated to all the following vertices.

Body:
I am in the middle of a PyQt5 PyOpenGL project. I am trying to draw a white wireframe cube with a bunch of colored solid cubes. Wireframe cubes are drawn from a list of tuple points, and a list of tuple references to those points. Solid cubes are drawn from a list of tuple references to the points. Here is the cube code:

class cube():
    render = True
    solid = False
    color = (1, 1, 1)

    def config(self, x, y, z, size = 0.1, solid = False, color = (1, 1, 1)):
        self.solid = solid
        self.color = color
        self.size = size / 2
        s = self.size
        self.vertices = [
                         (-s + x, s + y, -s + z),
                         (s + x, s + y, -s + z),
                         (s + x, -s + y, -s + z),
                         (-s + x, -s + y, -s + z),
                         (-s + x, s + y, s + z),
                         (s + x, s + y, s + z),
                         (s + x, -s + y, s + z),
                         (-s + x, -s + y, s + z)
                       ]
        self.edges = [
                      (0,1), (0,3), (0,4), (2,1),
                      (2,3), (2,6), (7,3), (7,4),
                      (7,6), (5,1), (5,4), (5,6)
                     ]
        self.facets = [
                       (0, 1, 2, 3), (0, 1, 6, 5),
                       (0, 3, 7, 4), (6, 5, 1, 2),
                       (6, 7, 4, 5), (6, 7, 3, 2)
                      ]
    def show(self):
        self.render = True
    def hide(self):
        self.render = False

To render a cube, I get the size of a list held in my mainWindow class, then append an instance of the cube class to that list. I can then reference that instance by using the size before appending. Here is the code for the render function:

def paintGL(self):
    glLoadIdentity()
    gluPerspective(45, self.width / self.height, 0.1, 110.0)    #set perspective?
    glTranslatef(0, 0, self.zoomLevel)    #I used -10 instead of -2 in the PyGame version.
    glRotatef(self.rotateDegreeV, 1, 0, 0)    #I used 2 instead of 1 in the PyGame version.
    glRotatef(self.rotateDegreeH, 0, 0, 1)
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

    if len(self.shapes) != 0:
        glBegin(GL_LINES)
        for s in self.shapes:
            if s.render and not s.solid:
                for e in s.edges:
                    for v in e:
                        glVertex3fv(s.vertices[v])
        glEnd()

        glBegin(GL_QUADS)
        for s in self.shapes:
            if s.render and s.solid:
                for f in s.facets:
                    for v in f:
                        glColor3fv(s.color)
                        glVertex3fv(s.vertices[v])
        glEnd()

If I render just one cube in wireframe, it renders white. If I add a red solid cube and a blue solid cube after it, the wireframe cube is colored in the last color used, whatever it may be. For example:

    self.shapes.append(self.cube())
    self.shapes.append(self.cube())
    self.shapes.append(self.cube())
    self.shapes[0].config(-1, 0, 0, size = 0.5, solid = False)
    self.shapes[1].config(0, 0, 0, size = 0.5, solid = True, color = (1, 0, 0))
    self.shapes[2].config(1, 0, 0, size = 0.5, solid = True, color = (0, 0, 1))

Result:

How can I make my wireframes render in the default white or a different color? I would expect glClear() would reset it and draw the wireframe in white, given that it is the first one.

Here is the full code:

import sys
from PyQt5.QtWidgets import (
                             QApplication, QMainWindow, QSlider,
                             QOpenGLWidget, QLabel, QPushButton
                            )
from PyQt5.QtCore import Qt
from OpenGL.GL import (
                       glLoadIdentity, glTranslatef, glRotatef,
                       glClear, glBegin, glEnd,
                       glColor3fv, glVertex3fv,
                       GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT,
                       GL_QUADS, GL_LINES
                      )
from OpenGL.GLU import gluPerspective

class mainWindow(QMainWindow):    #Main class.
    shapes = []    #this will hold instances of the following classes:
    zoomLevel = -10
    rotateDegreeV = -90
    rotateDegreeH = 0

    class cube():
        render = True
        solid = False
        color = (1, 1, 1)

        def config(self, x, y, z, size = 0.1, solid = False, color = (1, 1, 1)):
            self.solid = solid
            self.color = color
            self.size = size
            s = self.size / 2
            self.vertices = [
                             (-s + x, s + y, -s + z),
                             (s + x, s + y, -s + z),
                             (s + x, -s + y, -s + z),
                             (-s + x, -s + y, -s + z),
                             (-s + x, s + y, s + z),
                             (s + x, s + y, s + z),
                             (s + x, -s + y, s + z),
                             (-s + x, -s + y, s + z)
                            ]
            self.edges = [
                          (0,1), (0,3), (0,4), (2,1),
                          (2,3), (2,6), (7,3), (7,4),
                          (7,6), (5,1), (5,4), (5,6)
                         ]
            self.facets = [
                           (0, 1, 2, 3), (0, 1, 6, 5),
                           (0, 3, 7, 4), (6, 5, 1, 2),
                           (6, 7, 4, 5), (6, 7, 3, 2)
                          ]
        def show(self):
            self.render = True
        def hide(self):
            self.render = False

    def keyPressEvent(self, event):    #This is the keypress detector. I use this to determine input to edit grids.
        try:
            key = event.key()
            if key == 87:
                self.rotateV(5)
            elif key == 65:
                self.rotateH(5)
            elif key == 83:
                self.rotateV(-5)
            elif key == 68:
                self.rotateH(-5)
            elif key == 67:
                self.zoom(1)
            elif key == 88:
                self.zoom(-1)
        except:
            pass

    def __init__(self):
        super(mainWindow, self).__init__()
        self.width = 700    #Variables used for the setting of the size of everything
        self.height = 600
        self.setGeometry(0, 0, self.width, self.height)    #Set the window size
        self.shapes.append(self.cube())
        self.shapes.append(self.cube())
        self.shapes.append(self.cube())
        self.shapes[0].config(-1, 0, 0, size = 0.5, solid = False)
        self.shapes[1].config(0, 0, 0, size = 0.5, solid = True, color = (1, 0, 0))
        self.shapes[2].config(1, 0, 0, size = 0.5, solid = True, color = (0, 0, 1))

    def setupUI(self):
        self.openGLWidget = QOpenGLWidget(self)    #Create the GLWidget
        self.openGLWidget.setGeometry(0, 0, self.width, self.height)    #Size it the same as the window.
        self.openGLWidget.initializeGL()
        self.openGLWidget.resizeGL(self.width, self.height)    #Resize GL's knowledge of the window to match the physical size?
        self.openGLWidget.paintGL = self.paintGL    #override the default function with my own?

    def zoom(self, value):
        self.zoomLevel += value
        self.openGLWidget.update()

    def rotateV(self, value):
        self.rotateDegreeV += value
        self.openGLWidget.update()

    def rotateH(self, value):
        self.rotateDegreeH += value
        self.openGLWidget.update()

    def paintGL(self):
        glLoadIdentity()
        gluPerspective(45, self.width / self.height, 0.1, 110.0)    #set perspective?
        glTranslatef(0, 0, self.zoomLevel)    #I used -10 instead of -2 in the PyGame version.
        glRotatef(self.rotateDegreeV, 1, 0, 0)    #I used 2 instead of 1 in the PyGame version.
        glRotatef(self.rotateDegreeH, 0, 0, 1)
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        if len(self.shapes) != 0:
            glBegin(GL_LINES)
            for s in self.shapes:
                if s.render and not s.solid:
                    for e in s.edges:
                        for v in e:
                            glVertex3fv(s.vertices[v])
            glEnd()

            glBegin(GL_QUADS)
            for s in self.shapes:
                if s.render and s.solid:
                    for f in s.facets:
                        for v in f:
                            glColor3fv(s.color)
                            glVertex3fv(s.vertices[v])
            glEnd()

app = QApplication([])
window = mainWindow()
window.setupUI()
window.show()
sys.exit(app.exec_())

Body:
OpenGL is a state engine. Once a state is set, it is kept until it is changed again, even beyond frames. The current color is a global state. When glColor*  is called, then the current color is set.

When glVertex*  is called, then the current color, normal and texture coordinates are associated with the vertex.

That means, the proper color has to be set before the vertices are specified. You missed to set the color attribute, before you draw the wireframe cube:

class mainWindow(QMainWindow):    #Main class.
    # [...]

    def paintGL(self):
        # [...]

        if len(self.shapes) != 0:
            glBegin(GL_LINES)
            for s in self.shapes:
                glColor3fv(s.color)  # <------------------------
                if s.render and not s.solid:
                    for e in s.edges:
                        for v in e:
                            glVertex3fv(s.vertices[v])
            glEnd()

            glBegin(GL_QUADS)
            for s in self.shapes:
                glColor3fv(s.color)
                if s.render and s.solid:
                    for f in s.facets:
                        for v in f:
                            glVertex3fv(s.vertices[v])
            glEnd()

Note, it is not necessary to set the current color before each call to glVertex3fv. It is sufficient to set the current color once, when it is changed. The new color is associated to all the following vertices.


问:
generating rdf from sparql endpoint using ARC2 in php
i am having sparql store and I would like to know how to generate rdf file from sparql store using ARC2 in php.

I tried with sparql store dump(), but it returns back as xml. Any parser which I can use to convert this xml to rdf will help.

答:
Ok, so the output you are getting is a SPARQL XML Results which is a SPOG dump (i.e. Quads based) of the Store.

You should be able to convert this into Triples and then serialize these as RDF yourself but it will require a bit of coding.

I don't know PHP or ARC2 well so I would suggest looking through the documentation at https://github.com/semsol/arc2/wiki or asking on their mailing list at http://groups.google.com/group/arc-dev

ContentLicense: CC BY-SA 3.0


问:
Is there a way to force all referenced assemblies to be loaded into the app domain?
My projects are set up like this:

Project "Definition"

Project "Implementation"

Project "Consumer"

Project "Consumer" references both "Definition" and "Implementation", but does not statically reference any types in "Implementation".

When the application starts, Project "Consumer" calls a static method in "Definition", which needs to find types in "Implementation"

Is there a way I can force any referenced assembly to be loaded into the App Domain without knowing the path or name, and preferably without having to use a full-fledged IOC framework?

答: If you have assemblies where no code is referenced at compile time, those assemblies will not be included as a reference to your other assembly, even if you have added the project or nuget package as a reference. This is regardless of Debug or Release build settings, code optimization, etc. In these cases, you must explicitly call Assembly.LoadFrom(dllFileName) to get the assembly loaded.


问:
Index for join within a SQL ETL batch process
Suppose I have a CTAS in a batch ETL process, with a join like this:

```<code>-- SQL Server syntax
SELECT *
INTO output
FROM input1 JOIN input2 on (input1.join_column = input2.join_column)

-- Everyone else
CREATE TABLE output AS
SELECT *
FROM input1 JOIN input2 on (input1.join_column = input2.join_column)

</code>```

Is there any benefit to having an index (clustered or otherwise) on either input1.join_column or input2.join_column if I expect to hit every row in both tables?

My impression was indexes were mostly helpful with a selective predicate -- i.e., to help you get to a small subset set of rows quickly.  But I'm wondering if there is any fringe benefit of having joins when you're doing an ETL-like operation.

My question is primarily for SQL Server, but I would be interested in knowing the answer for PostgreSQL as well.

答:
An index will probably help, but it depends.

Databases have a bunch of different ways to handle joins:

Nested loops (looping through one table then through the other).

Nest loops with index (looping through one table and looking up the values in the other).

Sorting the tables and merging.

Using an index to sort the tables and merge.

Hashing.

(And variations on these an more!)

What the optimizer chooses depends on the capabilities of the database, the hardware, the data, and the statistics.

That said, for this type of join, the second method is quite common and has good performance if both tables fit in memory.  The processing is basically looping through one table and looking up the appropriate values in the other, using an index.

Hashing and merging (without an index) both require reading and writing the data for intermediate data structures.  That can slow down the algorithms in practice -- even if the theoretical performance is better.

So, yes, an index can be quite useful for these types of queries.

Body:
Suppose I have a CTAS in a batch ETL process, with a join like this:

-- SQL Server syntax
SELECT *
INTO output
FROM input1 JOIN input2 on (input1.join_column = input2.join_column)

-- Everyone else
CREATE TABLE output AS
SELECT *
FROM input1 JOIN input2 on (input1.join_column = input2.join_column)

Is there any benefit to having an index (clustered or otherwise) on either input1.join_column or input2.join_column if I expect to hit every row in both tables?

My impression was indexes were mostly helpful with a selective predicate -- i.e., to help you get to a small subset set of rows quickly.  But I'm wondering if there is any fringe benefit of having joins when you're doing an ETL-like operation.

My question is primarily for SQL Server, but I would be interested in knowing the answer for PostgreSQL as well.


问:
Possible to use BrowserRouter with React to handle URLs non-pretty URLs?
I am attempting to bootstrap my React app inside a Wordpress plugin. When the plugin loads, the URL is /wp-admin/admin.php?page=my-plugin-name, and this cannot be changed. I've tried to do URL rewrites and use /wp-admin/my-plugin-name/, but it's been a no-go, so unfortunately I have to find another option.

Here is my router:

```<code><Router basename="/wp-admin/admin.php">
  <Switch>
    <Route exact path="/">
      <DashboardPage />
    </Route>
    <Route exact path="/account">
      <AccountPage />
    </Route>
    <Route exact path="/products">
      <ProductsPage />
    </Route>
  </Switch>
</Router>
</code>```

Currently the Dashboard (default) loads when I visit /wp-admin/admin.php?page=my-plugin-name in my browser. But if I visit any other page, such as /wp-admin/admin.php?page=my-plugin-name%2Fproducts (note that Wordpress automatically changes my-plugin-name/products to my-plugin-name%2Fproducts), the Dashboard page still shows.

I've also tried using /wp-admin/admin.php?page=my-plugin-name for basename with the same result.

How can I make the other pages loadable? I am able to make this work using HashRouter, but I'd like to use BrowserRouter.

答:
place </p>

```<code> <Route exact path="/">
      <DashboardPage />
    </Route>
</code>```

<p>as your last route in the list </p>

Body:
I am attempting to bootstrap my React app inside a Wordpress plugin. When the plugin loads, the URL is /wp-admin/admin.php?page=my-plugin-name, and this cannot be changed. I've tried to do URL rewrites and use /wp-admin/my-plugin-name/, but it's been a no-go, so unfortunately I have to find another option.

Here is my router:

<Router basename="/wp-admin/admin.php">
  <Switch>
    <Route exact path="/">
      <DashboardPage />
    </Route>
    <Route exact path="/account">
      <AccountPage />
    </Route>
    <Route exact path="/products">
      <ProductsPage />
    </Route>
  </Switch>
</Router>

Currently the Dashboard (default) loads when I visit /wp-admin/admin.php?page=my-plugin-name in my browser. But if I visit any other page, such as /wp-admin/admin.php?page=my-plugin-name%2Fproducts (note that Wordpress automatically changes my-plugin-name/products to my-plugin-name%2Fproducts), the Dashboard page still shows.

I've also tried using /wp-admin/admin.php?page=my-plugin-name for basename with the same result.

How can I make the other pages loadable? I am able to make this work using HashRouter, but I'd like to use BrowserRouter.

Body:
place

 <Route exact path="/">
      <DashboardPage />
    </Route>

as your last route in the list


问:
INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE
I am using Google notifications in my app, and until now I have done below in the manifest:

```<code><!-- GCM -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" /> <!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.WAKE_LOCK" /> <!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <!-- This app has permission to register and receive data message. -->

<!-- Creates a custom permission so only this app can receive its messages. NOTE: APP_PACKAGE.permission.C2D_MESSAGE -->
<permission android:name="com.myapp.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.myapp.permission.C2D_MESSAGE" />
<!-- END GCM -->
</code>```

It worked perfectly until I updated my Nexus 7 to Android 5.0.

Now when I try to install the app in this device with Eclipse, I get this error:

INSTALL_FAILED_DUPLICATE_PERMISSION perm=com.myapp.permission.C2D_MESSAGE pkg=com.myapp

I don't understand what is wrong? It was working perfectly until Android 5.0.

I know that I am using C2D_MESSAGE in two lines, permission and uses-permission but I have copied that code from the original Google GCM guide, so it must be fine.

答:
In my case, I had several applications installed having the same domain name in the package name as follows.

```<code>com.mypackage.app1
com.mypackage.app2
com.mypackage.app3
...
</code>```

I had to uninstall all the apps having similar package names and reinstall them again in order to get rid of the problem.

To find all package names from the device I used the following.

```<code>adb shell pm list packages
</code>```

Then I grabbed the packages that match my package name that I am looking for.

```<code>dumpsys | grep -A18 "Package \[com.mypackage\]"
</code>```

Then uninstalled all the apps having that domain.

```<code>uninstall com.mypackage.app1
uninstall com.mypackage.app2
uninstall com.mypackage.app3
...
</code>```

You can also uninstall the applications using the Settings app. Go to the Settings -> Apps -> Find the app -> Uninstall

Hope that helps someone having the same problem as me.

Body:
I am using Google notifications in my app, and until now I have done below in the manifest:

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<permission android:name="com.myapp.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.myapp.permission.C2D_MESSAGE" />

It worked perfectly until I updated my Nexus 7 to Android 5.0.

Now when I try to install the app in this device with Eclipse, I get this error:

INSTALL_FAILED_DUPLICATE_PERMISSION perm=com.myapp.permission.C2D_MESSAGE pkg=com.myapp

I don't understand what is wrong? It was working perfectly until Android 5.0.

I know that I am using C2D_MESSAGE in two lines, permission and uses-permission but I have copied that code from the original Google GCM guide, so it must be fine.

Body:
In my case, I had several applications installed having the same domain name in the package name as follows.

com.mypackage.app1
com.mypackage.app2
com.mypackage.app3
...

I had to uninstall all the apps having similar package names and reinstall them again in order to get rid of the problem.

To find all package names from the device I used the following.

adb shell pm list packages

Then I grabbed the packages that match my package name that I am looking for.

dumpsys | grep -A18 "Package \[com.mypackage\]"

Then uninstalled all the apps having that domain.

uninstall com.mypackage.app1
uninstall com.mypackage.app2
uninstall com.mypackage.app3
...

You can also uninstall the applications using the Settings app. Go to the Settings -> Apps -> Find the app -> Uninstall

Hope that helps someone having the same problem as me.


问:
inject variables into the scope of a function
the following function takes an object and returns a function. the function it returns is a higher order function that takes a callback function.

const deconstruct = function (object) {
    const declarations = Object.entries(object).reduce(function (string, entry) {
        const key = entry[0];
        const value = entry[1];
        const declaration = "const " + key + " = " + value + ";";
        return string + declaration;
    }, "");
    const execute = function (callback) {
        return Function(
            declarations
            + "return "
            + callback.toString()
            + "();"
        )();
    };
    return execute;
};
```

<p><code>execute</code> augments <code>callback</code> by making it part of a new function. the new function declares constants, runs <code>callback</code> and returns the result. because in the new function the constants declared and <code>callback</code> are in the same scope, <code>callback</code> can access those constants, thus effectively injecting those constants into the scope of <code>callback</code>. here’s an example of an invocation of <code>deconstruct</code>.</p>

<pre class="lang-js prettyprint-override"><code>deconstruct({
    a: 0,
    b: 1,
    c: 2
})(function () {
    console.log(a, b, c); // 0 1 2
});
</code>```

but is there a different way to inject variables into the scope of a function without using intermediary strings like my code does?

答:
Based on your revised information in the question, I see now that the purpose was to keep it DRY (Don't Repeat Yourself).  The goal was to avoid repeating (a,b,c) unnecessarily, imagining that there may be hundreds of properties.

Here's one strategy.  You could make use of the with statement to bring this into scope and bind the object to the function.

values = { a: 0, b: 1, c: 2 };

function foo() {
  with(this) {
    console.log(a,b,c);
  }
}

foo.apply(values);

// or

let bar = foo.bind(values);
bar();```
</div>
</div>
</p>

<p>Or for a one-time use, you can just define the function with the values in scope:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>values = { a: 0, b: 1, c: 2 };

with (values) foo = () => {
  console.log(a, b, c);
}

foo();</code>```

Body:
the following function takes an object and returns a function. the function it returns is a higher order function that takes a callback function.

const deconstruct = function (object) {
    const declarations = Object.entries(object).reduce(function (string, entry) {
        const key = entry[0];
        const value = entry[1];
        const declaration = "const " + key + " = " + value + ";";
        return string + declaration;
    }, "");
    const execute = function (callback) {
        return Function(
            declarations
            + "return "
            + callback.toString()
            + "();"
        )();
    };
    return execute;
};

execute augments callback by making it part of a new function. the new function declares constants, runs callback and returns the result. because in the new function the constants declared and callback are in the same scope, callback can access those constants, thus effectively injecting those constants into the scope of callback. here’s an example of an invocation of deconstruct.

deconstruct({
    a: 0,
    b: 1,
    c: 2
})(function () {
    console.log(a, b, c); // 0 1 2
});

but is there a different way to inject variables into the scope of a function without using intermediary strings like my code does?

Body:
Based on your revised information in the question, I see now that the purpose was to keep it DRY (Don't Repeat Yourself).  The goal was to avoid repeating (a,b,c) unnecessarily, imagining that there may be hundreds of properties.

Here's one strategy.  You could make use of the with statement to bring this into scope and bind the object to the function.

values = { a: 0, b: 1, c: 2 };

function foo() {
  with(this) {
    console.log(a,b,c);
  }
}

foo.apply(values);

// or

let bar = foo.bind(values);
bar();

Or for a one-time use, you can just define the function with the values in scope:

values = { a: 0, b: 1, c: 2 };

with (values) foo = () => {
  console.log(a, b, c);
}

foo();


问:
PHP performance and redundancy
I have a section in my site where I do need to count the number of comments for a specific post.I actually already built a function for retrieving all the data in the comments DB table (function getComments).

the comments DB table structure is : id(PK) | authorId | datetime | postId | text

Now, since I just need to count them (the comments),I was wondering if,in term of server resources/redundancy is better to use :

```<code>$comments=new Comment();
$comments->getComments();
echo count($comments);
</code>```

Or I'm better build another function (apart from 'getComments')like :

```<code>function countComments($postid)
{
  //count comments per post
}
</code>```

thanks

Luca

答:
Counting your comments in the database is more efficient, because

Only the count is transferred, so you save bandwidth between your database and the php
process.

You save IO because the result isn't generated and the data isn't read from disk

A RDBMS is optimized for such functions.

Assuming, that you use Zend_Db something like this should work:

```<code>$query = $db->select()->from('comments', 'count(*)');
$count = $db->fetchOne($query);
</code>```

Code redundancy isn't a problem IMHO here, it's just one or two lines.

Title: PHP performance and redundancy

Body:
I have a section in my site where I do need to count the number of comments for a specific post.I actually already built a function for retrieving all the data in the comments DB table (function getComments).

the comments DB table structure is : id(PK) | authorId | datetime | postId | text

Now, since I just need to count them (the comments),I was wondering if,in term of server resources/redundancy is better to use :

$comments=new Comment();
$comments->getComments();
echo count($comments);

Or I'm better build another function (apart from 'getComments')like :

function countComments($postid)
{
  //count comments per post
}

thanks

Luca

Body:
Counting your comments in the database is more efficient, because

Only the count is transferred, so you save bandwidth between your database and the php
process.

You save IO because the result isn't generated and the data isn't read from disk

A RDBMS is optimized for such functions.

Assuming, that you use Zend_Db something like this should work:

$query = $db->select()->from('comments', 'count(*)');
$count = $db->fetchOne($query);

Code redundancy isn't a problem IMHO here, it's just one or two lines.


问:
How to return a struct from a function in C++?
I've tried on a few different forums and can't seem to get a straight answer, how can I make this function return the struct? If I try 'return newStudent;' I get the error 'No suitable user-defined conversion from studentType to studentType exists.'</p>

```<code>// Input function
studentType newStudent()
{
    struct studentType
    {
        string studentID;
        string firstName;
        string lastName;
        string subjectName;
        string courseGrade;

        int arrayMarks[4];

        double avgMarks;

    } newStudent;

    cout << "\nPlease enter student information:\n";

    cout << "\nFirst Name: ";
    cin >> newStudent.firstName;

    cout << "\nLast Name: ";
    cin >> newStudent.lastName;

    cout << "\nStudent ID: ";
    cin >> newStudent.studentID;

    cout << "\nSubject Name: ";
    cin >> newStudent.subjectName;

    for (int i = 0; i < NO_OF_TEST; i++)
    {   cout << "\nTest " << i+1 << " mark: ";
        cin >> newStudent.arrayMarks[i];
    }

    newStudent.avgMarks = calculate_avg(newStudent.arrayMarks,NO_OF_TEST );
    newStudent.courseGrade = calculate_grade (newStudent.avgMarks);

}
</code>```

答:
You can now (C++14) return a locally-defined (i.e. defined inside the function) struct as follows:</p>
```<code>auto f()
{
    struct S
    {
      int a;
      double b;
    } s;
    s.a = 42;
    s.b = 42.0;
    return s;
}

auto x = f();
a = x.a;
b = x.b;
</code>```

Body:
I've tried on a few different forums and can't seem to get a straight answer, how can I make this function return the struct? If I try 'return newStudent;' I get the error 'No suitable user-defined conversion from studentType to studentType exists.'

// Input function
studentType newStudent()
{
    struct studentType
    {
        string studentID;
        string firstName;
        string lastName;
        string subjectName;
        string courseGrade;

        int arrayMarks[4];

        double avgMarks;

    } newStudent;

    cout << "\nPlease enter student information:\n";

    cout << "\nFirst Name: ";
    cin >> newStudent.firstName;

    cout << "\nLast Name: ";
    cin >> newStudent.lastName;

    cout << "\nStudent ID: ";
    cin >> newStudent.studentID;

    cout << "\nSubject Name: ";
    cin >> newStudent.subjectName;

    for (int i = 0; i < NO_OF_TEST; i++)
    {   cout << "\nTest " << i+1 << " mark: ";
        cin >> newStudent.arrayMarks[i];
    }

    newStudent.avgMarks = calculate_avg(newStudent.arrayMarks,NO_OF_TEST );
    newStudent.courseGrade = calculate_grade (newStudent.avgMarks);

}

Body:
You can now (C++14) return a locally-defined (i.e. defined inside the function) struct as follows:

auto f()
{
    struct S
    {
      int a;
      double b;
    } s;
    s.a = 42;
    s.b = 42.0;
    return s;
}

auto x = f();
a = x.a;
b = x.b;


问:
Confusing VBA comment insertion behavior in Excel
I'm going to rewrite this request. I see that I could be clearer.

From within the spreadsheet I highlight a cell where I want a standardized comment inserted. I use a keyboard shortcut to activate AddServiceNote and the code inserts a comment with standardized formatting and text.

Everything works, but it is not repeatable. I can't select another cell and add another comment using the same keyboard shortcut.

I can use another keyboard shortcut to activate FormatNotes where all the comments are formatted. Mysteriously, that reactivates my ability to insert another single standardized comment with AddServiceNote.

Am I missing something obvious? Why can't I insert comments over and over? Does this have to do with Set Note = ActiveCell.Comment?

```<code>Public Note As Comment

Public Sub AddServiceNote()
    If Note Is Nothing Then
        ActiveCell.AddComment
        Set Note = ActiveCell.Comment
        Note.Text "Function: "
        OrganizeElements
    End If
End Sub

Public Sub FormatNotes()
    For Each Note In ActiveSheet.Comments
        OrganizeElements
    Next
End Sub

Public Sub OrganizeElements()
     Note.Shape.TextFrame.AutoSize = True
     'and a long list of other attributes
End Sub
</code>```

答:
Properly indenting the code makes it more obvious that the entirety of it in Sub CommentAddLabor only runs if there is no comment in the selected cell.

You want:

```<code>Public Sub CommentAddLabor()
    If Ct Is Nothing Then
        ActiveCell.AddComment
    End If
    Set Ct = ActiveCell.Comment
    CommentFormat 'calls the sub above
    Ct.Text "Function: " & Chr(10) & "Envision: " & Chr(10) & "Activity: " & Chr(10) & "Material: " & Chr(10) & "Duration: " & Chr(10) & "Consider: "
End Sub
</code>```

Body:
I'm going to rewrite this request. I see that I could be clearer.

From within the spreadsheet I highlight a cell where I want a standardized comment inserted. I use a keyboard shortcut to activate AddServiceNote and the code inserts a comment with standardized formatting and text.

Everything works, but it is not repeatable. I can't select another cell and add another comment using the same keyboard shortcut.

I can use another keyboard shortcut to activate FormatNotes where all the comments are formatted. Mysteriously, that reactivates my ability to insert another single standardized comment with AddServiceNote.

Am I missing something obvious? Why can't I insert comments over and over? Does this have to do with Set Note = ActiveCell.Comment?

Public Note As Comment

Public Sub AddServiceNote()
    If Note Is Nothing Then
        ActiveCell.AddComment
        Set Note = ActiveCell.Comment
        Note.Text "Function: "
        OrganizeElements
    End If
End Sub

Public Sub FormatNotes()
    For Each Note In ActiveSheet.Comments
        OrganizeElements
    Next
End Sub

Public Sub OrganizeElements()
     Note.Shape.TextFrame.AutoSize = True
     'and a long list of other attributes
End Sub

Body:
Properly indenting the code makes it more obvious that the entirety of it in Sub CommentAddLabor only runs if there is no comment in the selected cell.

You want:

Public Sub CommentAddLabor()
    If Ct Is Nothing Then
        ActiveCell.AddComment
    End If
    Set Ct = ActiveCell.Comment
    CommentFormat 'calls the sub above
    Ct.Text "Function: " & Chr(10) & "Envision: " & Chr(10) & "Activity: " & Chr(10) & "Material: " & Chr(10) & "Duration: " & Chr(10) & "Consider: "
End Sub


问:
Bot Service Web App not supported in Resource Group with existing Linux ASP
When attempting to create a Bot Service hosted on a Web App I am encountering an error when attempt to deploy to a Resource Group where an existing Linux App Service Plan exists. I am not trying to host my Bot Service on that ASP just simply trying to deplpoy a new ASP for Bot Service and am getting the following error:

In consideration of Resource Group design if I want any Bot Service Web Apps is it true that I cannot deploy them in a Resource Group with a Linux ASP?

答: The GitHub issue that Bill Overton linked to describes a problem where people were getting an error message about not being able to create a Windows ASP in a resource group with a Linux ASP even though the resource group had no Linux ASP. That is the problem that was supposedly fixed. The limitation remains of not being able to have a Windows ASP and a Linux ASP in the same resource group, and if you want that to change there is an existing post in the feedback forum where you can voice your opinion.</p>


问:
Javascript promise to iterate/include dynamic number of Arguments
I'm using the mssql npm module (with Tedious driver) to read/write to Azure Sql database from my node Server.  https://www.npmjs.com/package/mssql

All the examples I've found provide an hardcoded example of the query whether to read or write records, like this:

```<code>var insertRecordIntoTable = function (callback) {

  sql.connect(dbConfig).then(pool => {

     return pool.request()
        .input('ID', sql.Int, 210)
        .input('Name', sql.NVarChar, "John Doe")
        .input('EmailAddress', sql.NVarChar, "test@test.com")
        .query("INSERT INTO Accounts (ID, Name, EmailAddress) VALUES (@ID, @Name, @EmailAddress)")
  }).then(result => {
     console.dir(result)
     callback(result);
  }).catch(err => {
     // ... error checks
     console.log("Error occured: " + err);
     callback(err);
  });

}
</code>```

Obviously, I'd like to write one standard method to write records to any table in the database.

Now I can fetch structure of each table and use that to find how what datatype each field should be from the key in jsonRecord and write something like this:

```<code>var insertRecordIntoTable = function (jsonRecord, tableName, callback) {

  let arrKeys = jsonRecord.allKeys();
  let columnNames = getCommaSeparatedColumnNames(arrKeys);
  let valuePlaceholders = getValuePlaceholdersForSql(arrKeys);

  sql.connect(dbConfig).then(pool => {

     return pool.request()

        // how do I write something like this so that dynamic number of fields and values get populated in the query inside this promise.
        // I'm open to methods without promise as well.

        for(let x=0; x < arrKeys.length; x++){

           let key = arrKeys[x];

           // .input('ID', sql.Int, 210)
           .input(key, getTypeForKey(key, tableName), jsonRecord[ key ] )

        }

        .query("INSERT INTO " + tableName + " (" + columnNames + ") VALUES (" + valuePlaceholders + ")")
  }).then(result => {
     console.dir(result)
     callback(result);
  }).catch(err => {
     // ... error checks
     console.log("Error occured: " + err);
     callback(err);
  });

}

function getTypeForKey(key){. // looks up table schema and returns keyType }

function getCommaSeparatedColumnNames(arrKeys){  return arrKeys.join(", "); }

function getValuePlaceholdersForSql(arrKeys){   // write code to append '@' before every key and then join using comma's and return that string }
</code>```

I'm sure node.js writing to SQL is a fairly common functionality and there may be better ways to achieve what I'm trying to do here. Please feel free to go a different route.

P.S. - Although I should say that I prefer mssql over Tedious package. It just seems better in functionality after going through the documentation in the last several hours.

答:
If you want to interact with your database without creating all the queries by yourself, you can use a query builder like knex to manage the data as objects:

```<code>knex('Accounts').insert({ID: 210, Name: "John Doe", EmailAddress: "test@test.com"})
</code>```

Would be similar to:

```<code>insert into `Accounts` (`EmailAddress`, `ID`, `Name`) values ('test@test.com', 210, 'John Doe')
</code>```

Also I see you are checking types. If you need validation, maybe a complete ORM (I like Objection.js) would be a good choice.

Body:
I'm using the mssql npm module (with Tedious driver) to read/write to Azure Sql database from my node Server.  https://www.npmjs.com/package/mssql

All the examples I've found provide an hardcoded example of the query whether to read or write records, like this:

var insertRecordIntoTable = function (callback) {

  sql.connect(dbConfig).then(pool => {

     return pool.request()
        .input('ID', sql.Int, 210)
        .input('Name', sql.NVarChar, "John Doe")
        .input('EmailAddress', sql.NVarChar, "test@test.com")
        .query("INSERT INTO Accounts (ID, Name, EmailAddress) VALUES (@ID, @Name, @EmailAddress)")
  }).then(result => {
     console.dir(result)
     callback(result);
  }).catch(err => {
     // ... error checks
     console.log("Error occured: " + err);
     callback(err);
  });

}

Obviously, I'd like to write one standard method to write records to any table in the database.

Now I can fetch structure of each table and use that to find how what datatype each field should be from the key in jsonRecord and write something like this:

var insertRecordIntoTable = function (jsonRecord, tableName, callback) {

  let arrKeys = jsonRecord.allKeys();
  let columnNames = getCommaSeparatedColumnNames(arrKeys);
  let valuePlaceholders = getValuePlaceholdersForSql(arrKeys);

  sql.connect(dbConfig).then(pool => {

     return pool.request()

        // how do I write something like this so that dynamic number of fields and values get populated in the query inside this promise.
        // I'm open to methods without promise as well.

        for(let x=0; x < arrKeys.length; x++){

           let key = arrKeys[x];

           // .input('ID', sql.Int, 210)
           .input(key, getTypeForKey(key, tableName), jsonRecord[ key ] )

        }

        .query("INSERT INTO " + tableName + " (" + columnNames + ") VALUES (" + valuePlaceholders + ")")
  }).then(result => {
     console.dir(result)
     callback(result);
  }).catch(err => {
     // ... error checks
     console.log("Error occured: " + err);
     callback(err);
  });

}

function getTypeForKey(key){. // looks up table schema and returns keyType }

function getCommaSeparatedColumnNames(arrKeys){  return arrKeys.join(", "); }

function getValuePlaceholdersForSql(arrKeys){   // write code to append '@' before every key and then join using comma's and return that string }

I'm sure node.js writing to SQL is a fairly common functionality and there may be better ways to achieve what I'm trying to do here. Please feel free to go a different route.

P.S. - Although I should say that I prefer mssql over Tedious package. It just seems better in functionality after going through the documentation in the last several hours.

Body:
If you want to interact with your database without creating all the queries by yourself, you can use a query builder like knex to manage the data as objects:

knex('Accounts').insert({ID: 210, Name: "John Doe", EmailAddress: "test@test.com"})

Would be similar to:

insert into `Accounts` (`EmailAddress`, `ID`, `Name`) values ('test@test.com', 210, 'John Doe')

Also I see you are checking types. If you need validation, maybe a complete ORM (I like Objection.js) would be a good choice.


问:
My mercurial repository is too large, I need to delete old commits. Is it possible?
I have a big Mercurial Repository on Google Code Hosting, how can I delete the old commits/revisions? I don't need that old revisions anymore because I have forked it to other repositories.</p>

答:
I would say that deleting revisions is anathema to version control :-)

Nevertheless, you might use the hg convert options to convert to a new repo with changed revisions. AFAIK using splicemap, you could remove revisions.

But it won't help with the Google repository, because it stays as it is. You will have to delete it (reset as described by Klaim) and push the converted repository.

You can also push the converted repository to another place (other then default repo) because you may have up to 7 repositories on Google Code in one project.

ContentLicense: CC BY-SA 2.5


问:
Remove files/folders from S3 that are x days old
I am trying to delete files/folders from S3 bucket using Azure pipelines with task "AWS Tools for Windows PowerShell Script". Below is the powershell script that I am using:

```<code>Get-S3Object -BucketName "tfsonline-fullbuild-drop" | Where {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} | Remove-S3Object -Force
</code>```

This unfortunately is deleting every single file and folder from the bucket. It does not seem to be taking the Where command into consideration at all. Can you please let me know what I am doing wrong.

Thanks!

答:
The documentation on Amazon's site here states that the Get-S3object cmdlet returns objects of type Amazon.S3.Model.S3Object or Amazon.S3.Model.ListObjectsResponse.  Neither of those object types have a LastWriteTime property.  In order to be sure you are testing the correct property, you need to determine exactly which properties the return object(s) has/have.  Reading the documentation will help, but another option is the get-member command.

If you were to take one of the returned objects and pipe it to get-member you can see all of the properties in the object being returned, and you can then make a good choice about how to do your test.  Something like this may help:

```<code>(Get-S3Object -BucketName "tfsonline-fullbuild-drop")[0] | gm
</code>```

Good luck.

Body:
I am trying to delete files/folders from S3 bucket using Azure pipelines with task "AWS Tools for Windows PowerShell Script". Below is the powershell script that I am using:

Get-S3Object -BucketName "tfsonline-fullbuild-drop" | Where {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} | Remove-S3Object -Force

This unfortunately is deleting every single file and folder from the bucket. It does not seem to be taking the Where command into consideration at all. Can you please let me know what I am doing wrong.

Thanks!

Body:
The documentation on Amazon's site here states that the Get-S3object cmdlet returns objects of type Amazon.S3.Model.S3Object or Amazon.S3.Model.ListObjectsResponse.  Neither of those object types have a LastWriteTime property.  In order to be sure you are testing the correct property, you need to determine exactly which properties the return object(s) has/have.  Reading the documentation will help, but another option is the get-member command.

If you were to take one of the returned objects and pipe it to get-member you can see all of the properties in the object being returned, and you can then make a good choice about how to do your test.  Something like this may help:

(Get-S3Object -BucketName "tfsonline-fullbuild-drop")[0] | gm

Good luck.


问:
I can't get past a few do-while loops even though their conditions have not been met
I'm just doing an exercise where I'm supposed to be finding all even numbers between two certain integers. However, each time I enter any numbers I get held up on one of the first two do-while loops. I assume I'm making a simple error. Does anybody see what I'm doing wrong?
Thank you!

The input should be x and y, the output should be b. x must be smaller than y, and they both must be between 1-99 (I'll fix that, it should be 0-100.)

```<code>#include <iostream>

int main()
{
    int x, y, b;

    std::cout << "This program will show all even numbers between a certain range.\n\nEnter two integers >0 and <100. The first integer must be smaller than the second integer.\n ";
    std::cin >> x >> y;

    do
    {
        std::cout << "The first integer must be smaller than the second integer. Please enter two integers.\n ";
        std::cin >> x >> y;

    } while (x > y);

    do
    {
        std::cout << "The first smaller integer must be greater than 0, the second larger integer must be less than 100.\n ";
        std::cin >> x >> y;

    } while (((x < 0 || y > 100 || x > y)));

    b = x;

    if ((b % 2) == 0)
    {
        do
        {
            std::cout << b;
            b++;
        } while (b < y);
    }
}
</code>```

答:
Well, since it is homework we could just post the code and move on, but I will try to explain what is going on:

```<code>#include <iostream>

int main() {
    int x,y;

    std::cout << "This program will show all even numbers between a certain "
    "range.\n\nEnter two integers >0 and <100. The first integer must be smaller "
    "than the second integer.\n";

    do {
        std::cin>>x>>y;
    } while(x >= y || x <= 0 || y >= 100);

    x+=1; // we update the value with 1, to make sure we don't print the start value, and we start with the first even value

    do {
        if(x % 2 == 0) {
            std::cout << x << std::endl;
        }
        x++;
    } while(x < y);

}
</code>```

What was going wrong in your code?
The first thing which was going wrong it that you were multiple times asking for input for different conditions. We only need to ask the user 1 time for input, and we will check if that input matches our conditions, if it doesn't we will ask the user again for new input.

Furthermore also this part was wrong:

```<code>if ((b % 2) == 0)
{
    do
    {
        std::cout << b;
        b++;
    } while (b < y);
}
</code>```

Why?

Well because in this case you only start the do-while loop if the the input number is even. So for example with a input of 40 it would start the do-while loop, but with 41 it wouldn't.

Also in the do-while loop you keep printing all numbers even if they are not even. That is because the if statement is not checked in the do-while loop

Body:
I'm just doing an exercise where I'm supposed to be finding all even numbers between two certain integers. However, each time I enter any numbers I get held up on one of the first two do-while loops. I assume I'm making a simple error. Does anybody see what I'm doing wrong?
Thank you!

The input should be x and y, the output should be b. x must be smaller than y, and they both must be between 1-99 (I'll fix that, it should be 0-100.)

#include <iostream>

int main()
{
    int x, y, b;

    std::cout << "This program will show all even numbers between a certain range.\n\nEnter two integers >0 and <100. The first integer must be smaller than the second integer.\n ";
    std::cin >> x >> y;

    do
    {
        std::cout << "The first integer must be smaller than the second integer. Please enter two integers.\n ";
        std::cin >> x >> y;

    } while (x > y);

    do
    {
        std::cout << "The first smaller integer must be greater than 0, the second larger integer must be less than 100.\n ";
        std::cin >> x >> y;

    } while (((x < 0 || y > 100 || x > y)));

    b = x;

    if ((b % 2) == 0)
    {
        do
        {
            std::cout << b;
            b++;
        } while (b < y);
    }
}

Body:
Well, since it is homework we could just post the code and move on, but I will try to explain what is going on:

#include <iostream>

int main() {
    int x,y;

    std::cout << "This program will show all even numbers between a certain "
    "range.\n\nEnter two integers >0 and <100. The first integer must be smaller "
    "than the second integer.\n";

    do {
        std::cin>>x>>y;
    } while(x >= y || x <= 0 || y >= 100);

    x+=1; // we update the value with 1, to make sure we don't print the start value, and we start with the first even value

    do {
        if(x % 2 == 0) {
            std::cout << x << std::endl;
        }
        x++;
    } while(x < y);

}

What was going wrong in your code?
The first thing which was going wrong it that you were multiple times asking for input for different conditions. We only need to ask the user 1 time for input, and we will check if that input matches our conditions, if it doesn't we will ask the user again for new input.

Furthermore also this part was wrong:

if ((b % 2) == 0)
{
    do
    {
        std::cout << b;
        b++;
    } while (b < y);
}

Why?

Well because in this case you only start the do-while loop if the the input number is even. So for example with a input of 40 it would start the do-while loop, but with 41 it wouldn't.

Also in the do-while loop you keep printing all numbers even if they are not even. That is because the if statement is not checked in the do-while loop


问:
Django: call method after clicking button
I was searching for this answer but none met my expectation. So, In my template I have some content and wanted to add button (which later will add to favorites). After clicking I want to call method from my views.py and redirect to other view.

my views.py

```<code>def home(request):
    //logic here
    request.session['url'] = url
    return render(request,'file.html')

def function_to_call(request):
    ///logic here
    url = request.session.get('url')
    return render(request,'second_file.html',url=url)
</code>```

file.html

```<code><form action="{% url 'function_to_call' %}">
    <button id="submit" type="button" value="Click" />
</form>
</code>```

and in my urls.py

```<code>url(r'^function_to_call/',views.function_to_call,name='function_to_call'),
</code>```

Unfortunately, after clicking on button, nothing happens

答:
unless you are submitting a form, you should use</p>

```<code> <a href="{% url 'function_to_call' %}">Click</a>
</code>```

Body:
I was searching for this answer but none met my expectation. So, In my template I have some content and wanted to add button (which later will add to favorites). After clicking I want to call method from my views.py and redirect to other view.

my views.py

def home(request):
    //logic here
    request.session['url'] = url
    return render(request,'file.html')

def function_to_call(request):
    ///logic here
    url = request.session.get('url')
    return render(request,'second_file.html',url=url)

file.html

<form action="{% url 'function_to_call' %}">
    <button id="submit" type="button" value="Click" />
</form>

and in my urls.py

url(r'^function_to_call/',views.function_to_call,name='function_to_call'),

Unfortunately, after clicking on button, nothing happens

Body:
unless you are submitting a form, you should use

 <a href="{% url 'function_to_call' %}">Click</a>


问:
Emulator SD card Partition
Is it possible to create partitions on SD card from the emulator.</p>

答:
I finally find a way to do it. What you need first is a sd card or usb drive then plug it in your computer. I use Linux so let's say after that there is a new device in /dev named /dev/sdb.
Use a partition tool (eg fdisk for linux) to create the partitions. When you're done, make a copy of /dev/sdb with dd (dd if=/dev/sdb of=sdcard.img).

That's all. You can now launch your emulator with your new sdcard.

Title: Emulator SD card Partition