问:
How to order by custom rule, e.g. how to order like 4,2,1,3
I am not sure that the title is saying it right, most probably it does not :)

So I have products table and I want to order them by the season they are made for.

If 'spring' is 1, 'summer' - 2 , 'autumn' - 3 and 'winter' - 4, how can I order them in such way so it shows the 'summer' first, then 'spring', then 'winter' and at the end 'autumn'. So like 2,1,4,3.

And to clarify it more, I want to be able to change the rule. It might be 2,1,4,3 or 4,2,1,3, etc. This is to show the season products on top.

Hope that explanation helps to get the problem. Any solutions are welcomed. Database is MySQL, language PHP.

答:
Create a string of "season" ids. Then do the order by field thing:

```<code>SELECT * FROM foo ORDER BY FIELD(season_id, 4, 2, 1, 3);
</code>```

Replace the 4, 2, 1, 3 part with interpolated php variable.

Body:
Create a string of "season" ids. Then do the order by field thing:

SELECT * FROM foo ORDER BY FIELD(season_id, 4, 2, 1, 3);

Replace the 4, 2, 1, 3 part with interpolated php variable.


来源: stackexchange

问:
Maximum dy value for XSSFClientAnchor
Using Apache-POI, I'm trying to insert an image in an Excel sheet with an upper-left corner halfway a row with a large font (Calibri-32).

Using the well-known formulas, I figured out that that the dy1 value within the XSSFClientAnchor should be something like 260,000.

However, when opening the Excel file, I get an error saying the contents is illeggible.

Accepting the warning, the image is shown correctly anyway.

After some tests, I figured out that the maximum value of the dy, without getting an error from Excel, appears to be 190,500.

The font I use, results in a row height of 55 pixels.

Halfway the row is therefore 0.5*55*Units.EMU_PER_PIXEL=261,938.

The same problem occurs when using a smaller font but making the image start near the end of the row.

In all cases, I get an error if the dy1 has a value greater than 190500.

Is there anyone who's got a clue?

UPDATE:

I extracted the xml from the xlsx file and I noticed a negative cy value somewhere. I'm not really familar with the xlsx contents but I hope it's useful for somebody:

```<code><xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
  <xdr:twoCellAnchor editAs="oneCell">
    <xdr:from>
      <xdr:col>2</xdr:col>
      <xdr:colOff>147637</xdr:colOff>
      <xdr:row>0</xdr:row>
      <xdr:rowOff>261937</xdr:rowOff>
    </xdr:from>
    <xdr:to>
      <xdr:col>5</xdr:col>
      <xdr:colOff>2309812</xdr:colOff>
      <xdr:row>13</xdr:row>
      <xdr:rowOff>14287</xdr:rowOff>
    </xdr:to>
    <xdr:pic>
      <xdr:nvPicPr>
        <xdr:cNvPr id="1" name="Picture 1" descr="Picture"/>
        <xdr:cNvPicPr>
          <a:picLocks noChangeAspect="true"/>
        </xdr:cNvPicPr>
      </xdr:nvPicPr>
      <xdr:blipFill>
        <a:blip r:embed="rId1"/>
        <a:stretch>
          <a:fillRect/>
        </a:stretch>
      </xdr:blipFill>
      <xdr:spPr>
        <a:xfrm>
          <a:off x="147637" y="261937"/>
          <a:ext cx="195263" cy="-71437"/>
        </a:xfrm>
        <a:prstGeom prst="rect">
          <a:avLst/>
        </a:prstGeom>
      </xdr:spPr>
    </xdr:pic>
    <xdr:clientData/>
  </xdr:twoCellAnchor>
</xdr:wsDr>
</code>```

UPDATE 2:

The following code shows the error. It occurs if dy1 is greater than 190500 AND row2 equals row1+1

```<code>/**********************************************************************************************************************
 * Package specification
 *********************************************************************************************************************/
package test;

/**********************************************************************************************************************
 * Import definitions
 *********************************************************************************************************************/
import java.awt.Desktop;
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.*;
import org.apache.poi.xssf.streaming.*;
import org.apache.poi.xssf.usermodel.*;

/**********************************************************************************************************************
 * This class implements a Minimal, Complete and Verifiable example for the problem of the maximum dy value for the
 * {@link XSSFClientAnchor}.
 *********************************************************************************************************************/
public class TestPictureOffset
{
  /********************************************************************************************************************
   * This constants represents the name of the file with the picture to import within the sheet.
   *******************************************************************************************************************/
  private static final String FILENAME_PICTURE = "./excel.png";

  /********************************************************************************************************************
   * These constants represents the width and height of the big cell within the sheet.
   *******************************************************************************************************************/
  private static final short BIG_CELL_COLUMN_WIDTH_IN_PIXELS = 317;
  private static final short BIG_CELL_ROW_HEIGHT_IN_PIXELS = 56;

  /********************************************************************************************************************
   * This constants represents the default height of a cell within the sheet.
   *******************************************************************************************************************/
  private static final short DEFAULT_ROW_HEIGHT_IN_PIXELS = 20;

  /********************************************************************************************************************
   * This method places the specified picture on the sheet.
   *******************************************************************************************************************/
  private static void setPicture(int        picture_index,
                                 SXSSFSheet sheet)
  {
    // -----------------
    // Initialize anchor
    // -----------------
    XSSFClientAnchor anchor;
    anchor = (XSSFClientAnchor)sheet.getWorkbook().getCreationHelper().createClientAnchor();
    anchor.setAnchorType(XSSFClientAnchor.AnchorType.MOVE_AND_RESIZE);

    // -----------------------------
    // Set position
    // THIS IS WHERE THE FUN HAPPENS
    // -----------------------------
    anchor.setCol1(1);
    anchor.setRow1(0);
    anchor.setDx1((int)(0.5 * BIG_CELL_COLUMN_WIDTH_IN_PIXELS * Units.EMU_PER_PIXEL));
    anchor.setDy1((int)(0.4 * BIG_CELL_ROW_HEIGHT_IN_PIXELS * Units.EMU_PER_PIXEL));
    anchor.setCol2(anchor.getCol1() + 1);
    anchor.setRow2(anchor.getRow1() + 1);   // Fails if dy1 > 190500
    //anchor.setRow2(anchor.getRow1() + 2); // OK independently from dy1
    anchor.setDx2(0);
    anchor.setDy2(0);

    // ----------------------
    // Show some measurements
    // ----------------------
    System.out.println("Got dy1: " + anchor.getDy1());
    System.out.println("Maximum dy in default cell: " + (DEFAULT_ROW_HEIGHT_IN_PIXELS * Units.EMU_PER_PIXEL));

    // ----------------
    // Draw the picture
    // ----------------
    sheet.createDrawingPatriarch().createPicture(anchor, picture_index);

  } // setPicture

  /********************************************************************************************************************
   * This method runs the application.
   *******************************************************************************************************************/
  private static void run()
    throws Exception
  {
    // ---------------
    // Create workbook
    // ---------------
    SXSSFWorkbook workbook;
    workbook = new SXSSFWorkbook();
    workbook.setCompressTempFiles(true);

    // ------------
    // Create sheet
    // ------------
    SXSSFSheet sheet;
    sheet = workbook.createSheet("TestSheet");
    sheet.trackAllColumnsForAutoSizing();

    // --------------------------
    // Create style with big font
    // --------------------------
    Font          font;
    XSSFCellStyle style;
    font = workbook.createFont();
    font.setFontHeightInPoints((short)32);
    style = (XSSFCellStyle)workbook.createCellStyle();
    style.setFont(font);

    // -------------------
    // Write something big
    // -------------------
    SXSSFRow  row;
    SXSSFCell cell;
    row = sheet.createRow(0);
    cell = row.createCell(1);
    cell.setCellStyle(style);
    cell.setCellValue("Hello everybody");

    // -----------------------
    // Auto resize this column
    // -----------------------
    sheet.autoSizeColumn(1);

    // ------------
    // Load picture
    // ------------
    InputStream input_stream;
    byte[]      bytes;
    input_stream = new FileInputStream(FILENAME_PICTURE);
    bytes = IOUtils.toByteArray(input_stream);
    input_stream.close();

    // ---------------
    // Add to workbook
    // ---------------
    int picture_index;
    picture_index = workbook.addPicture(bytes, SXSSFWorkbook.PICTURE_TYPE_PNG);

    // -------------------------
    // Position picture in sheet
    // -------------------------
    setPicture(picture_index, sheet);

    // -------------
    // Save workbook
    // -------------
    File             output_file;
    FileOutputStream output_stream;
    output_file = new File("testxls.xlsx");
    output_stream = new FileOutputStream(output_file);
    workbook.write(output_stream);
    output_stream.close();
    workbook.close();

    // -------
    // Open it
    // -------
    Desktop.getDesktop().open(output_file);

  } // run

  /********************************************************************************************************************
   *                                                M A I N
   *******************************************************************************************************************/
  public static void main(String[] args)
  {
    try
    {
      run();
    }
    catch (Exception exception)
    {
      exception.printStackTrace();
    }

  } // main

} // class TestPictureOffset
</code>```

答:
So we need determining where the negative cy may comes from.

At first: You should not using constants for BIG_CELL_COLUMN_WIDTH_IN_PIXELS and BIG_CELL_ROW_HEIGHT_IN_PIXELS. Instead do the same as apache poi does and use sheet.getColumnWidthInPixels and ImageUtils.getRowHeightInPixels to calculate width and height.

And you need set row height according to the fonts height. Else the row remains in default height until Excel is rendering  the sheet in view. And in default row height, the dy1 is outside the row if greater than 190500. So it would not be a valid dy1 for this row.

There is private CTTransform2D createXfrm(XSSFClientAnchor anchor) in XSSFDrawing.java which calculates the xfrm containing the cy. There you can see, that a negative cy only occurs if height + anchor.getDy2() is lower than anchor.getDy1().

Using XSSF this would be enough. But using SXSSF the calculation of the row height in private CTTransform2D createXfrm(XSSFClientAnchor anchor) using ImageUtils.getRowHeightInPixels(sheet, row) seems to be wrong. I suspect this is because row height is not known already in the sheet because of the streaming manner. So we need a workaround. Set default row height that big as needed for the big font, set the picture then and reset the default row height after that.

The following works for me:

```<code>/**********************************************************************************************************************
 * Import definitions
 *********************************************************************************************************************/
import java.awt.Desktop;
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.*;
import org.apache.poi.xssf.streaming.*;
import org.apache.poi.xssf.usermodel.*;

import org.apache.poi.ss.util.ImageUtils;

/**********************************************************************************************************************
 * This class implements a Minimal, Complete and Verifiable example for the problem of the maximum dy value for the
 * {@link XSSFClientAnchor}.
 *********************************************************************************************************************/
public class TestPictureOffset
{
  /********************************************************************************************************************
   * This constants represents the name of the file with the picture to import within the sheet.
   *******************************************************************************************************************/
  private static final String FILENAME_PICTURE = "./excel.png";

  /********************************************************************************************************************
   * These constants represents the width and height of the big cell within the sheet.
   *******************************************************************************************************************/
  // Don't do that. Instead do the same as apache poi does and use
  // sheet.getColumnWidthInPixels and
  // ImageUtils.getRowHeightInPixels to calculate width and height

  private static final short BIG_CELL_COLUMN_WIDTH_IN_PIXELS = 317;
  private static final short BIG_CELL_ROW_HEIGHT_IN_PIXELS = 56;

  /********************************************************************************************************************
   * This constants represents the default height of a cell within the sheet.
   *******************************************************************************************************************/
  private static final short DEFAULT_ROW_HEIGHT_IN_PIXELS = 20;

  /********************************************************************************************************************
   * This method places the specified picture on the sheet.
   *******************************************************************************************************************/
  private static void setPicture(int        picture_index,
                                 Sheet sheet)
  {
    // -----------------
    // Initialize anchor
    // -----------------
    ClientAnchor anchor;
    anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor();
    anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);

    // -----------------------------
    // Set position
    // THIS IS WHERE THE FUN HAPPENS
    // -----------------------------
    anchor.setCol1(1);
    anchor.setRow1(0);
    //anchor.setDx1((int)(0.5 * BIG_CELL_COLUMN_WIDTH_IN_PIXELS * Units.EMU_PER_PIXEL));
    //anchor.setDy1((int)(0.4 * BIG_CELL_ROW_HEIGHT_IN_PIXELS * Units.EMU_PER_PIXEL));
    anchor.setDx1((int)(0.5 * sheet.getColumnWidthInPixels(1) * Units.EMU_PER_PIXEL));
    anchor.setDy1((int)(0.4 * ImageUtils.getRowHeightInPixels(sheet, 0) * Units.EMU_PER_PIXEL));
    anchor.setCol2(anchor.getCol1() + 1);
    anchor.setRow2(anchor.getRow1() + 1);   // Fails if dy1 > 190500
    //anchor.setRow2(anchor.getRow1() + 2); // OK independently from dy1
    anchor.setDx2(0);
    anchor.setDy2(0);

    // ----------------------
    // Show some measurements
    // ----------------------
    System.out.println("Got dy1: " + anchor.getDy1());
    System.out.println("Maximum dy in default cell: " + (DEFAULT_ROW_HEIGHT_IN_PIXELS * Units.EMU_PER_PIXEL));

    // ----------------
    // Draw the picture
    // ----------------
    sheet.createDrawingPatriarch().createPicture(anchor, picture_index);

  } // setPicture

  /********************************************************************************************************************
   * This method runs the application.
   *******************************************************************************************************************/
  private static void run()
    throws Exception
  {
    // ---------------
    // Create workbook
    // ---------------
    SXSSFWorkbook workbook;
    workbook = new SXSSFWorkbook();
    workbook.setCompressTempFiles(true);

    // ------------
    // Create sheet
    // ------------
    SXSSFSheet sheet;
    sheet = workbook.createSheet("TestSheet");
    sheet.trackAllColumnsForAutoSizing();

    // --------------------------
    // Create style with big font
    // --------------------------
    Font          font;
    CellStyle style;
    font = workbook.createFont();
    font.setFontHeightInPoints((short)32);
    style = workbook.createCellStyle();
    style.setFont(font);

    // -------------------
    // Write something big
    // -------------------
    SXSSFRow  row;
    SXSSFCell cell;
    row = sheet.createRow(0);
    cell = row.createCell(1);
    cell.setCellStyle(style);
    cell.setCellValue("Hello everybody");

    // -----------------------
    // Set row heigth according to the fonts height
    // -----------------------
    row.setHeightInPoints(workbook.getFontAt(style.getFontIndex()).getFontHeightInPoints()*1.275f);

    // -----------------------
    // Auto resize this column
    // -----------------------
    sheet.autoSizeColumn(1);

    // ------------
    // Load picture
    // ------------
    InputStream input_stream;
    byte[]      bytes;
    input_stream = new FileInputStream(FILENAME_PICTURE);
    bytes = IOUtils.toByteArray(input_stream);
    input_stream.close();

    // ---------------
    // Add to workbook
    // ---------------
    int picture_index;
    picture_index = workbook.addPicture(bytes, SXSSFWorkbook.PICTURE_TYPE_PNG);

    // -------------------------
    // Position picture in sheet
    // -------------------------
    // Workaround for SXSSFSheet which has not the correct row height in
    // private CTTransform2D createXfrm(XSSFClientAnchor anchor)
    // because of the streaming manner.
    // So set default row height that big:
    sheet.setDefaultRowHeight(sheet.getRow(0).getHeight());
    // set the picture then:
    setPicture(picture_index, sheet);
    // and reset the default row height after that:
    sheet.setDefaultRowHeight((short)(15*20));

    // -------------
    // Save workbook
    // -------------
    File             output_file;
    FileOutputStream output_stream;
    output_file = new File("testxls.xlsx");
    output_stream = new FileOutputStream(output_file);
    workbook.write(output_stream);
    output_stream.close();
    workbook.close();

    workbook.dispose();

    // -------
    // Open it
    // -------
    Desktop.getDesktop().open(output_file);

  } // run

  /********************************************************************************************************************
   *                                                M A I N
   *******************************************************************************************************************/
  public static void main(String[] args)
  {
    try
    {
      run();
    }
    catch (Exception exception)
    {
      exception.printStackTrace();
    }

  } // main

} // class TestPictureOffset
</code>```

ContentLicense: CC BY-SA 3.0

Title: Maximum dy value for XSSFClientAnchor

Body:
Using Apache-POI, I'm trying to insert an image in an Excel sheet with an upper-left corner halfway a row with a large font (Calibri-32).

Using the well-known formulas, I figured out that that the dy1 value within the XSSFClientAnchor should be something like 260,000.

However, when opening the Excel file, I get an error saying the contents is illeggible.

Accepting the warning, the image is shown correctly anyway.

After some tests, I figured out that the maximum value of the dy, without getting an error from Excel, appears to be 190,500.

The font I use, results in a row height of 55 pixels.

Halfway the row is therefore 0.5*55*Units.EMU_PER_PIXEL=261,938.

The same problem occurs when using a smaller font but making the image start near the end of the row.

In all cases, I get an error if the dy1 has a value greater than 190500.

Is there anyone who's got a clue?

UPDATE:

I extracted the xml from the xlsx file and I noticed a negative cy value somewhere. I'm not really familar with the xlsx contents but I hope it's useful for somebody:

<xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
  <xdr:twoCellAnchor editAs="oneCell">
    <xdr:from>
      <xdr:col>2</xdr:col>
      <xdr:colOff>147637</xdr:colOff>
      <xdr:row>0</xdr:row>
      <xdr:rowOff>261937</xdr:rowOff>
    </xdr:from>
    <xdr:to>
      <xdr:col>5</xdr:col>
      <xdr:colOff>2309812</xdr:colOff>
      <xdr:row>13</xdr:row>
      <xdr:rowOff>14287</xdr:rowOff>
    </xdr:to>
    <xdr:pic>
      <xdr:nvPicPr>
        <xdr:cNvPr id="1" name="Picture 1" descr="Picture"/>
        <xdr:cNvPicPr>

        </xdr:cNvPicPr>
      </xdr:nvPicPr>
      <xdr:blipFill>

      </xdr:blipFill>
      <xdr:spPr>

      </xdr:spPr>
    </xdr:pic>
    <xdr:clientData/>
  </xdr:twoCellAnchor>
</xdr:wsDr>

UPDATE 2:

The following code shows the error. It occurs if dy1 is greater than 190500 AND row2 equals row1+1

/**********************************************************************************************************************
 * Package specification
 *********************************************************************************************************************/
package test;

/**********************************************************************************************************************
 * Import definitions
 *********************************************************************************************************************/
import java.awt.Desktop;
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.*;
import org.apache.poi.xssf.streaming.*;
import org.apache.poi.xssf.usermodel.*;

/**********************************************************************************************************************
 * This class implements a Minimal, Complete and Verifiable example for the problem of the maximum dy value for the
 * {@link XSSFClientAnchor}.
 *********************************************************************************************************************/
public class TestPictureOffset
{
  /********************************************************************************************************************
   * This constants represents the name of the file with the picture to import within the sheet.
   *******************************************************************************************************************/
  private static final String FILENAME_PICTURE = "./excel.png";

  /********************************************************************************************************************
   * These constants represents the width and height of the big cell within the sheet.
   *******************************************************************************************************************/
  private static final short BIG_CELL_COLUMN_WIDTH_IN_PIXELS = 317;
  private static final short BIG_CELL_ROW_HEIGHT_IN_PIXELS = 56;

  /********************************************************************************************************************
   * This constants represents the default height of a cell within the sheet.
   *******************************************************************************************************************/
  private static final short DEFAULT_ROW_HEIGHT_IN_PIXELS = 20;

  /********************************************************************************************************************
   * This method places the specified picture on the sheet.
   *******************************************************************************************************************/
  private static void setPicture(int        picture_index,
                                 SXSSFSheet sheet)
  {
    // -----------------
    // Initialize anchor
    // -----------------
    XSSFClientAnchor anchor;
    anchor = (XSSFClientAnchor)sheet.getWorkbook().getCreationHelper().createClientAnchor();
    anchor.setAnchorType(XSSFClientAnchor.AnchorType.MOVE_AND_RESIZE);

    // -----------------------------
    // Set position
    // THIS IS WHERE THE FUN HAPPENS
    // -----------------------------
    anchor.setCol1(1);
    anchor.setRow1(0);
    anchor.setDx1((int)(0.5 * BIG_CELL_COLUMN_WIDTH_IN_PIXELS * Units.EMU_PER_PIXEL));
    anchor.setDy1((int)(0.4 * BIG_CELL_ROW_HEIGHT_IN_PIXELS * Units.EMU_PER_PIXEL));
    anchor.setCol2(anchor.getCol1() + 1);
    anchor.setRow2(anchor.getRow1() + 1);   // Fails if dy1 > 190500
    //anchor.setRow2(anchor.getRow1() + 2); // OK independently from dy1
    anchor.setDx2(0);
    anchor.setDy2(0);

    // ----------------------
    // Show some measurements
    // ----------------------
    System.out.println("Got dy1: " + anchor.getDy1());
    System.out.println("Maximum dy in default cell: " + (DEFAULT_ROW_HEIGHT_IN_PIXELS * Units.EMU_PER_PIXEL));

    // ----------------
    // Draw the picture
    // ----------------
    sheet.createDrawingPatriarch().createPicture(anchor, picture_index);

  } // setPicture

  /********************************************************************************************************************
   * This method runs the application.
   *******************************************************************************************************************/
  private static void run()
    throws Exception
  {
    // ---------------
    // Create workbook
    // ---------------
    SXSSFWorkbook workbook;
    workbook = new SXSSFWorkbook();
    workbook.setCompressTempFiles(true);

    // ------------
    // Create sheet
    // ------------
    SXSSFSheet sheet;
    sheet = workbook.createSheet("TestSheet");
    sheet.trackAllColumnsForAutoSizing();

    // --------------------------
    // Create style with big font
    // --------------------------
    Font          font;
    XSSFCellStyle style;
    font = workbook.createFont();
    font.setFontHeightInPoints((short)32);
    style = (XSSFCellStyle)workbook.createCellStyle();
    style.setFont(font);

    // -------------------
    // Write something big
    // -------------------
    SXSSFRow  row;
    SXSSFCell cell;
    row = sheet.createRow(0);
    cell = row.createCell(1);
    cell.setCellStyle(style);
    cell.setCellValue("Hello everybody");

    // -----------------------
    // Auto resize this column
    // -----------------------
    sheet.autoSizeColumn(1);

    // ------------
    // Load picture
    // ------------
    InputStream input_stream;
    byte[]      bytes;
    input_stream = new FileInputStream(FILENAME_PICTURE);
    bytes = IOUtils.toByteArray(input_stream);
    input_stream.close();

    // ---------------
    // Add to workbook
    // ---------------
    int picture_index;
    picture_index = workbook.addPicture(bytes, SXSSFWorkbook.PICTURE_TYPE_PNG);

    // -------------------------
    // Position picture in sheet
    // -------------------------
    setPicture(picture_index, sheet);

    // -------------
    // Save workbook
    // -------------
    File             output_file;
    FileOutputStream output_stream;
    output_file = new File("testxls.xlsx");
    output_stream = new FileOutputStream(output_file);
    workbook.write(output_stream);
    output_stream.close();
    workbook.close();

    // -------
    // Open it
    // -------
    Desktop.getDesktop().open(output_file);

  } // run

  /********************************************************************************************************************
   *                                                M A I N
   *******************************************************************************************************************/
  public static void main(String[] args)
  {
    try
    {
      run();
    }
    catch (Exception exception)
    {
      exception.printStackTrace();
    }

  } // main

} // class TestPictureOffset

Body:
So we need determining where the negative cy may comes from.

At first: You should not using constants for BIG_CELL_COLUMN_WIDTH_IN_PIXELS and BIG_CELL_ROW_HEIGHT_IN_PIXELS. Instead do the same as apache poi does and use sheet.getColumnWidthInPixels and ImageUtils.getRowHeightInPixels to calculate width and height.

And you need set row height according to the fonts height. Else the row remains in default height until Excel is rendering  the sheet in view. And in default row height, the dy1 is outside the row if greater than 190500. So it would not be a valid dy1 for this row.

There is private CTTransform2D createXfrm(XSSFClientAnchor anchor) in XSSFDrawing.java which calculates the xfrm containing the cy. There you can see, that a negative cy only occurs if height + anchor.getDy2() is lower than anchor.getDy1().

Using XSSF this would be enough. But using SXSSF the calculation of the row height in private CTTransform2D createXfrm(XSSFClientAnchor anchor) using ImageUtils.getRowHeightInPixels(sheet, row) seems to be wrong. I suspect this is because row height is not known already in the sheet because of the streaming manner. So we need a workaround. Set default row height that big as needed for the big font, set the picture then and reset the default row height after that.

The following works for me:

/**********************************************************************************************************************
 * Import definitions
 *********************************************************************************************************************/
import java.awt.Desktop;
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.*;
import org.apache.poi.xssf.streaming.*;
import org.apache.poi.xssf.usermodel.*;

import org.apache.poi.ss.util.ImageUtils;

/**********************************************************************************************************************
 * This class implements a Minimal, Complete and Verifiable example for the problem of the maximum dy value for the
 * {@link XSSFClientAnchor}.
 *********************************************************************************************************************/
public class TestPictureOffset
{
  /********************************************************************************************************************
   * This constants represents the name of the file with the picture to import within the sheet.
   *******************************************************************************************************************/
  private static final String FILENAME_PICTURE = "./excel.png";

  /********************************************************************************************************************
   * These constants represents the width and height of the big cell within the sheet.
   *******************************************************************************************************************/
  // Don't do that. Instead do the same as apache poi does and use
  // sheet.getColumnWidthInPixels and
  // ImageUtils.getRowHeightInPixels to calculate width and height

  private static final short BIG_CELL_COLUMN_WIDTH_IN_PIXELS = 317;
  private static final short BIG_CELL_ROW_HEIGHT_IN_PIXELS = 56;

  /********************************************************************************************************************
   * This constants represents the default height of a cell within the sheet.
   *******************************************************************************************************************/
  private static final short DEFAULT_ROW_HEIGHT_IN_PIXELS = 20;

  /********************************************************************************************************************
   * This method places the specified picture on the sheet.
   *******************************************************************************************************************/
  private static void setPicture(int        picture_index,
                                 Sheet sheet)
  {
    // -----------------
    // Initialize anchor
    // -----------------
    ClientAnchor anchor;
    anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor();
    anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);

    // -----------------------------
    // Set position
    // THIS IS WHERE THE FUN HAPPENS
    // -----------------------------
    anchor.setCol1(1);
    anchor.setRow1(0);
    //anchor.setDx1((int)(0.5 * BIG_CELL_COLUMN_WIDTH_IN_PIXELS * Units.EMU_PER_PIXEL));
    //anchor.setDy1((int)(0.4 * BIG_CELL_ROW_HEIGHT_IN_PIXELS * Units.EMU_PER_PIXEL));
    anchor.setDx1((int)(0.5 * sheet.getColumnWidthInPixels(1) * Units.EMU_PER_PIXEL));
    anchor.setDy1((int)(0.4 * ImageUtils.getRowHeightInPixels(sheet, 0) * Units.EMU_PER_PIXEL));
    anchor.setCol2(anchor.getCol1() + 1);
    anchor.setRow2(anchor.getRow1() + 1);   // Fails if dy1 > 190500
    //anchor.setRow2(anchor.getRow1() + 2); // OK independently from dy1
    anchor.setDx2(0);
    anchor.setDy2(0);

    // ----------------------
    // Show some measurements
    // ----------------------
    System.out.println("Got dy1: " + anchor.getDy1());
    System.out.println("Maximum dy in default cell: " + (DEFAULT_ROW_HEIGHT_IN_PIXELS * Units.EMU_PER_PIXEL));

    // ----------------
    // Draw the picture
    // ----------------
    sheet.createDrawingPatriarch().createPicture(anchor, picture_index);

  } // setPicture

  /********************************************************************************************************************
   * This method runs the application.
   *******************************************************************************************************************/
  private static void run()
    throws Exception
  {
    // ---------------
    // Create workbook
    // ---------------
    SXSSFWorkbook workbook;
    workbook = new SXSSFWorkbook();
    workbook.setCompressTempFiles(true);

    // ------------
    // Create sheet
    // ------------
    SXSSFSheet sheet;
    sheet = workbook.createSheet("TestSheet");
    sheet.trackAllColumnsForAutoSizing();

    // --------------------------
    // Create style with big font
    // --------------------------
    Font          font;
    CellStyle style;
    font = workbook.createFont();
    font.setFontHeightInPoints((short)32);
    style = workbook.createCellStyle();
    style.setFont(font);

    // -------------------
    // Write something big
    // -------------------
    SXSSFRow  row;
    SXSSFCell cell;
    row = sheet.createRow(0);
    cell = row.createCell(1);
    cell.setCellStyle(style);
    cell.setCellValue("Hello everybody");

    // -----------------------
    // Set row heigth according to the fonts height
    // -----------------------
    row.setHeightInPoints(workbook.getFontAt(style.getFontIndex()).getFontHeightInPoints()*1.275f);

    // -----------------------
    // Auto resize this column
    // -----------------------
    sheet.autoSizeColumn(1);

    // ------------
    // Load picture
    // ------------
    InputStream input_stream;
    byte[]      bytes;
    input_stream = new FileInputStream(FILENAME_PICTURE);
    bytes = IOUtils.toByteArray(input_stream);
    input_stream.close();

    // ---------------
    // Add to workbook
    // ---------------
    int picture_index;
    picture_index = workbook.addPicture(bytes, SXSSFWorkbook.PICTURE_TYPE_PNG);

    // -------------------------
    // Position picture in sheet
    // -------------------------
    // Workaround for SXSSFSheet which has not the correct row height in
    // private CTTransform2D createXfrm(XSSFClientAnchor anchor)
    // because of the streaming manner.
    // So set default row height that big:
    sheet.setDefaultRowHeight(sheet.getRow(0).getHeight());
    // set the picture then:
    setPicture(picture_index, sheet);
    // and reset the default row height after that:
    sheet.setDefaultRowHeight((short)(15*20));

    // -------------
    // Save workbook
    // -------------
    File             output_file;
    FileOutputStream output_stream;
    output_file = new File("testxls.xlsx");
    output_stream = new FileOutputStream(output_file);
    workbook.write(output_stream);
    output_stream.close();
    workbook.close();

    workbook.dispose();

    // -------
    // Open it
    // -------
    Desktop.getDesktop().open(output_file);

  } // run

  /********************************************************************************************************************
   *                                                M A I N
   *******************************************************************************************************************/
  public static void main(String[] args)
  {
    try
    {
      run();
    }
    catch (Exception exception)
    {
      exception.printStackTrace();
    }

  } // main

} // class TestPictureOffset


问:
Best way to import a large dataset into Oracle sql database?
I'm new to oracle Database and I'm making a very simple bilingual dictionary ( 2 tables - English and French).

A dictionary often contains thousands of words. My question is that instead of writing thousand of [INSERT INTO ... VALUES] commands, is there any better way to somehow automate the process, like making a import form? Since the book my school provides only mentions about the INSERT command.

答:
You can use a combination of a spreadsheet and an INSERT ALL command to quickly generate an SQL INSERT command to insert your data.

If you have your data in a spreadsheet format, you can use formulas to construct an INSERT statement for each row.

However, you could use the INSERT ALL syntax instead of the INSERT (single row) syntax.

To do this:

Add a column into your spreadsheet with the formula that looks like this: "INTO table (col1, col2, col3) VALUES ('val1', 'val2', 'val3')". You would need to use concatenation to add the values into this formula.

So your formula may look like this (assuming columns of A, B, and C):

="INTO table (col1, col2, col3) VALUES ('"&A2&"', '"&B2&"', '"&C2&"')"

Copy the formula to each row.

Copy and paste all of these formulas to a query window inside your IDE.

Add the words INSERT ALL at the start of your command

Add the words SELECT * FROM dual; at the end of your command

Your command would then look like this:

```<code>INSERT ALL
INTO table (col1, col2, col3) VALUES ('val1', 'val2', 'val3')
INTO table (col1, col2, col3) VALUES ('val1a', 'val2a', 'val3a')
INTO table (col1, col2, col3) VALUES ('val1b', 'val2b', 'val3b')
SELECT * FROM dual;
</code>```

This will insert all records in a single statement and is likely to be much faster than hundreds or thousands of INSERT statements.

Alternatively, you could use a tool like Data Pump Import and Export, but I have limited experience with that so perhaps another user could elaborate on that.

Body:
You can use a combination of a spreadsheet and an INSERT ALL command to quickly generate an SQL INSERT command to insert your data.

If you have your data in a spreadsheet format, you can use formulas to construct an INSERT statement for each row.

However, you could use the INSERT ALL syntax instead of the INSERT (single row) syntax.

To do this:

Add a column into your spreadsheet with the formula that looks like this: "INTO table (col1, col2, col3) VALUES ('val1', 'val2', 'val3')". You would need to use concatenation to add the values into this formula.

So your formula may look like this (assuming columns of A, B, and C):

="INTO table (col1, col2, col3) VALUES ('"&A2&"', '"&B2&"', '"&C2&"')"

Copy the formula to each row.

Copy and paste all of these formulas to a query window inside your IDE.

Add the words INSERT ALL at the start of your command

Add the words SELECT * FROM dual; at the end of your command

Your command would then look like this:

INSERT ALL
INTO table (col1, col2, col3) VALUES ('val1', 'val2', 'val3')
INTO table (col1, col2, col3) VALUES ('val1a', 'val2a', 'val3a')
INTO table (col1, col2, col3) VALUES ('val1b', 'val2b', 'val3b')
SELECT * FROM dual;

This will insert all records in a single statement and is likely to be much faster than hundreds or thousands of INSERT statements.

Alternatively, you could use a tool like Data Pump Import and Export, but I have limited experience with that so perhaps another user could elaborate on that.


问:
What are the drawbacks of using Hardware Accelerated and Large Heap in an app?
I want to use these features because my list views are big with images and other things. Hardware acceleration does seem to improve it a bit but I am wondering if there is any downsides</p>

```<code>android:hardwareAccelerated="true"
android:largeHeap="true"
</code>```

答: Hardware acceleration is enabled by default for API 14+ and is usually a good thing to enable, but depending on what you do with custom views it may not always work. There are a few limitations on what drawing operations are supported by Hardware acceleration. For details I suggest looking at https://developer.android.com/guide/topics/graphics/hardware-accel.html . If your application is affected by any of these missing features or limitations, you can turn off hardware acceleration for just the affected portion of your application by calling setLayerType(View.LAYER_TYPE_SOFTWARE, null).

Body:
I want to use these features because my list views are big with images and other things. Hardware acceleration does seem to improve it a bit but I am wondering if there is any downsides

android:hardwareAccelerated="true"
android:largeHeap="true"


问:
Show Date-Values on X-Axis in locale depending format ngx-charts / d3
I have a Webapp using Angular v4.0.1 and ngx-charts (uses d3) v5.1.2 creating a line-chart where the x-axis has date-values.

My Problem is that the x-axis does not show the german time-format. So I found out how I can set locale formatting for d3:

```<code>import * as d3 from "d3";

import * as formatDE from "d3-format/locale/de-DE.json";
import * as timeFormatDE from "d3-time-format/locale/de-DE.json";

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor() {
    var formatBefore = d3.timeFormat("%A");
    console.log('Before: '+formatBefore(new Date));
    // output: Thursday -> OK

    d3.formatDefaultLocale(formatDE);
    d3.timeFormatDefaultLocale(timeFormatDE);

    var formatAfter = d3.timeFormat("%A");
    console.log('After: '+formatAfter(new Date));
    // output: Donnerstag -> YES, nice
  }
}
</code>```

But this has now effect for the x-axis! The date and time-value are still in english format.

答:
Although ngx-charts wraps d3 not all d3 tricks work with it. Most ngx-charts components have an xAxisTickFormatting input that you connect to your own formatting function, e.g.:

<ngx-charts-line-chart ... [xAxisTickFormatting]="dateTickFormatting" ...>
</ngx-charts-line-chart>
```

<pre class="lang-ts prettyprint-override"><code>// some-component.ts
function dateTickFormatting(val: any): string {
  if (val instanceof Date) {
    return (<Date>val).toLocaleString('de-DE');
  }
}
</code>```

[Updated 2018-11-03 with a more detailed example]

Pay attention to the Date.toLocaleString() reference:

the first parameter is a locale string representing the culture you wish to format for (e.g.: 'en-US', 'de-DE', 'fr-FR')

the second parameter is an options object that allows you to change the format of different date/time parts.

Starting a new Angular project from scratch to demo this fully...

```<code>$ npm -g install generator-ngx-rocket@1.3.3

$ mkdir charts-demo; cd charts-demo; ngx new charts-demo
> Web app
> Progressive: Yes
> Bootstrap
> Authentication: No
> Lazy loading: No
> Analytics: No
> Prettier: Yes

$ npm i @swimlane/ngx-charts@10.0.0
</code>```

In app.module.ts:

import {NgxChartsModule} from '@swimlane/ngx-charts'; //<<-- Add this
@NgModule({
  imports: [
    ...
    NgbModule,
    NgxChartsModule, //<<-- Add this
    CoreModule,
    ...
  ],
  declarations: [AppComponent],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
```

<p>In app.component.html:</p>

<pre class="lang-html prettyprint-override"><code><router-outlet>
</router-outlet>
<!-- Add this... -->
<ngx-charts-line-chart
    [legend]="true"
    [results]="chartData"
    [view]="[1100,320]"
    [xAxis]="true"
    [xAxisTickFormatting]="this.dateTickFormatting">
</ngx-charts-line-chart>
</code>```

Finally, in app.component.ts:

// ...
export class AppComponent implements OnInit {
  // Add this...
  // Note the Date objects for the names (X Axis values)...
  chartData: any[] = [
    {
      name: 'Series 1',
      series: [
        { name: new Date("2017-12-01"), value: 0 },
        { name: new Date("2018-01-01"), value: 1 },
        { name: new Date("2018-02-01"), value: 1 },
        { name: new Date("2018-03-01"), value: 2 },
        { name: new Date("2018-04-01"), value: 3 },
        { name: new Date("2018-05-01"), value: 5 },
        { name: new Date("2018-06-01"), value: 8 },
        { name: new Date("2018-07-01"), value: 13 },
        { name: new Date("2018-08-01"), value: 21 },
        { name: new Date("2018-09-01"), value: 34 },
        { name: new Date("2018-10-01"), value: 55 },
        { name: new Date("2018-11-01"), value: 89 },
        { name: new Date("2018-12-01"), value: 144 }
      ]
    }
  ];
  constructor(
  // ...
  // in ngOnInit()...
      .subscribe(event => {
        const title = event['title'];
        if (title) {

this.titleService.setTitle(this.translateService.instant(title));
        }
        //Add this: Record the new language...
        environment.defaultLanguage = this.translateService.currentLang;
        //Add this: Refresh the ngx-chart...
        this.chartData = [... this.chartData];
      });
  // ...
  // new method, dateTickFormatting...
  dateTickFormatting(val: any): String {
    if (val instanceof Date) {
      var options = { month: 'long' };
      //return (<Date>val).toLocaleString('de-DE', options);
      return (<Date>val).toLocaleString(environment.defaultLanguage, options);
    }
  }
}
```

What we've done so far enables you to switch between the out-of-the-box languages for an ngx-rocket application, en-US and fr-FR:

.

.

You can add some basic plumbing and translations to enable switching to de-DE as well:

.

Hope this helps!

Body:
I have a Webapp using Angular v4.0.1 and ngx-charts (uses d3) v5.1.2 creating a line-chart where the x-axis has date-values.

My Problem is that the x-axis does not show the german time-format. So I found out how I can set locale formatting for d3:

import * as d3 from "d3";

import * as formatDE from "d3-format/locale/de-DE.json";
import * as timeFormatDE from "d3-time-format/locale/de-DE.json";

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor() {
    var formatBefore = d3.timeFormat("%A");
    console.log('Before: '+formatBefore(new Date));
    // output: Thursday -> OK

    d3.formatDefaultLocale(formatDE);
    d3.timeFormatDefaultLocale(timeFormatDE);

    var formatAfter = d3.timeFormat("%A");
    console.log('After: '+formatAfter(new Date));
    // output: Donnerstag -> YES, nice
  }
}

But this has now effect for the x-axis! The date and time-value are still in english format.

Body:
Although ngx-charts wraps d3 not all d3 tricks work with it. Most ngx-charts components have an xAxisTickFormatting input that you connect to your own formatting function, e.g.:

<!-- some-component.html -->
<ngx-charts-line-chart ... [xAxisTickFormatting]="dateTickFormatting" ...>
</ngx-charts-line-chart>

// some-component.ts
function dateTickFormatting(val: any): string {
  if (val instanceof Date) {
    return (<Date>val).toLocaleString('de-DE');
  }
}

[Updated 2018-11-03 with a more detailed example]

Pay attention to the Date.toLocaleString() reference:

the first parameter is a locale string representing the culture you wish to format for (e.g.: 'en-US', 'de-DE', 'fr-FR')

the second parameter is an options object that allows you to change the format of different date/time parts.

Starting a new Angular project from scratch to demo this fully...

$ npm -g install generator-ngx-rocket@1.3.3

$ mkdir charts-demo; cd charts-demo; ngx new charts-demo
> Web app
> Progressive: Yes
> Bootstrap
> Authentication: No
> Lazy loading: No
> Analytics: No
> Prettier: Yes

$ npm i @swimlane/ngx-charts@10.0.0

In app.module.ts:

import {NgxChartsModule} from '@swimlane/ngx-charts'; //<<-- Add this
@NgModule({
  imports: [
    ...
    NgbModule,
    NgxChartsModule, //<<-- Add this
    CoreModule,
    ...
  ],
  declarations: [AppComponent],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

In app.component.html:

<router-outlet>
</router-outlet>
<!-- Add this... -->
<ngx-charts-line-chart
    [legend]="true"
    [results]="chartData"
    [view]="[1100,320]"
    [xAxis]="true"
    [xAxisTickFormatting]="this.dateTickFormatting">
</ngx-charts-line-chart>

Finally, in app.component.ts:

// ...
export class AppComponent implements OnInit {
  // Add this...
  // Note the Date objects for the names (X Axis values)...
  chartData: any[] = [
    {
      name: 'Series 1',
      series: [
        { name: new Date("2017-12-01"), value: 0 },
        { name: new Date("2018-01-01"), value: 1 },
        { name: new Date("2018-02-01"), value: 1 },
        { name: new Date("2018-03-01"), value: 2 },
        { name: new Date("2018-04-01"), value: 3 },
        { name: new Date("2018-05-01"), value: 5 },
        { name: new Date("2018-06-01"), value: 8 },
        { name: new Date("2018-07-01"), value: 13 },
        { name: new Date("2018-08-01"), value: 21 },
        { name: new Date("2018-09-01"), value: 34 },
        { name: new Date("2018-10-01"), value: 55 },
        { name: new Date("2018-11-01"), value: 89 },
        { name: new Date("2018-12-01"), value: 144 }
      ]
    }
  ];
  constructor(
  // ...
  // in ngOnInit()...
      .subscribe(event => {
        const title = event['title'];
        if (title) {

this.titleService.setTitle(this.translateService.instant(title));
        }
        //Add this: Record the new language...
        environment.defaultLanguage = this.translateService.currentLang;
        //Add this: Refresh the ngx-chart...
        this.chartData = [... this.chartData];
      });
  // ...
  // new method, dateTickFormatting...
  dateTickFormatting(val: any): String {
    if (val instanceof Date) {
      var options = { month: 'long' };
      //return (<Date>val).toLocaleString('de-DE', options);
      return (<Date>val).toLocaleString(environment.defaultLanguage, options);
    }
  }
}

What we've done so far enables you to switch between the out-of-the-box languages for an ngx-rocket application, en-US and fr-FR:

.

.

You can add some basic plumbing and translations to enable switching to de-DE as well:

.

Hope this helps!

ContentLicense: CC BY-SA 4.0


问:
Get user_metadata Roles in Auth0
I am trying to get user Roles when after logged in in Auth0, as per documentation, I created a rule

```<code>function (user, context, callback) {
    var namespace = 'https://myayth0.com/';
    context.idToken[namespace + 'app_metadata'] = user.app_metadata;
    context.idToken[namespace + 'user_metadata'] = user.user_metadata;
    context.idToken[namespace + 'roles'] = user.user_metadata.roles;
    context.accessToken[namespace + 'app_metadata'] = user.app_metadata;
    context.accessToken[namespace + 'user_metadata'] = user.user_metadata;
    context.accessToken[namespace + 'roles'] = user.user_metadata.roles;
    callback(null, user, context);
 }
</code>```

Now I have this data return

```<code>(...)
 email_verified
:
(...)
 https://ian:auth0:com/app_metadata
 :
(...)
https://ian:auth0:com/roles
:
https://ian:auth0:com/user_metadata
(...)
:
(...)
picture
:
(...)
sub
:
(...)
updated_at
:
(...)
</code>```

Now accessing picture or email  is easy

```<code>     this.user.email, this.user.picture
</code>```

But how about the role?

```<code>   https://ian:auth0:com/roles
     : Array(1)
     0: "admin"
   ..................
</code>```

答:
```<code>const roles = this.user['https://ian:auth0:com/roles']
              this.roles = roles[0]
</code>```

Title: Get user_metadata Roles in Auth0

Body:
I am trying to get user Roles when after logged in in Auth0, as per documentation, I created a rule

function (user, context, callback) {
    var namespace = 'https://myayth0.com/';
    context.idToken[namespace + 'app_metadata'] = user.app_metadata;
    context.idToken[namespace + 'user_metadata'] = user.user_metadata;
    context.idToken[namespace + 'roles'] = user.user_metadata.roles;
    context.accessToken[namespace + 'app_metadata'] = user.app_metadata;
    context.accessToken[namespace + 'user_metadata'] = user.user_metadata;
    context.accessToken[namespace + 'roles'] = user.user_metadata.roles;
    callback(null, user, context);
 }

Now I have this data return

(...)
 email_verified
:
(...)
 https://ian:auth0:com/app_metadata
 :
(...)
https://ian:auth0:com/roles
:
https://ian:auth0:com/user_metadata
(...)
:
(...)
picture
:
(...)
sub
:
(...)
updated_at
:
(...)

Now accessing picture or email  is easy

     this.user.email, this.user.picture

But how about the role?

   https://ian:auth0:com/roles
     : Array(1)
     0: "admin"
   ..................


问:
C struct and malloc problem (C)
It's amazing how even the littlest program can cause so much trouble in C.

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}
</code>```

The compiler says:

```<code>main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token
</code>```

Can you please help?

答:
Don't use typedef'ed names as variable names, and there is not need to cast malloc(); in C.

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree->nodes[0] = malloc(sizeof(node));
    return malloc(sizeof(tree));
}

int main() {
    return 0;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: C struct and malloc problem (C)

Body:
It's amazing how even the littlest program can cause so much trouble in C.

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}

The compiler says:

main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token

Can you please help?

Body:
Don't use typedef'ed names as variable names, and there is not need to cast malloc(); in C.

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree->nodes[0] = malloc(sizeof(node));
    return malloc(sizeof(tree));
}

int main() {
    return 0;
}


问:
(Java) Trying to format the layout of multiple JTables with other elements in a JPanel
I've been working on a Pokemon-themed quiz game in Java (modeled after Sporcle, if you're familiar). Pretty much everything works how I want it to, except for the layout of the different components of the program.

I've never been very good with the different layout managers, and I don't know how to get them to do what I need.

Here's what the window looks like right now:

Now, I'll play around with font sizes later, but the tables themselves look exactly how I want them to. The problem is, I want them to be under the text fields and buttons and stuff. Here's the portion of the code where I add all the components to my JPanel:

```<code>    panel.add(label,FlowLayout.LEFT); //adding the "big question text"
    panel.add(answerfield); //adding the JTextField
    panel.add(correctAnswerTracker); //adding the "x / 151" text
    for(int x = sPanes.length-1; x >=0; x--) //as you keep adding to left, it gets pushed over, so doing it backwards results in the correct order
    panel.add(sPanes[x],FlowLayout.LEFT);
    //each table is in a scrollPane, and all my scrollPanes are in the array sPanes, so I'm looping through that to add the tables
    panel.add(startStopButton); //button that says "Start"
    panel.add(exit); //button that says "Exit
    panel.add(timer); //the timer
</code>```

As you can see, the statements to add the text field, and correct answer tracker are all written before the add statement for the tables, and yet the tables are at the top. Additionally, there's the issue of my tables in that loop being added in the backwards order, so I had to reverse the direction of the loop iterations to get the tables to appear in the correct order. I've tried using stuff like setLocation and setBounds to get my components more where I want them, but nothing happened. Also, everything just appears in a row below the tables (and I know that's what FlowLayout does), but how would I go about customizing exactly where things appear?

答: Either use a LayoutManager or setLayout(null). In the latter case, you can move your components around by calling setBounds on them. I've been doing that lately too (not using a LayoutManager), it's quite liberating.

Body:
I've been working on a Pokemon-themed quiz game in Java (modeled after Sporcle, if you're familiar). Pretty much everything works how I want it to, except for the layout of the different components of the program.

I've never been very good with the different layout managers, and I don't know how to get them to do what I need.

Here's what the window looks like right now:

Now, I'll play around with font sizes later, but the tables themselves look exactly how I want them to. The problem is, I want them to be under the text fields and buttons and stuff. Here's the portion of the code where I add all the components to my JPanel:

    panel.add(label,FlowLayout.LEFT); //adding the "big question text"
    panel.add(answerfield); //adding the JTextField
    panel.add(correctAnswerTracker); //adding the "x / 151" text
    for(int x = sPanes.length-1; x >=0; x--) //as you keep adding to left, it gets pushed over, so doing it backwards results in the correct order
    panel.add(sPanes[x],FlowLayout.LEFT);
    //each table is in a scrollPane, and all my scrollPanes are in the array sPanes, so I'm looping through that to add the tables
    panel.add(startStopButton); //button that says "Start"
    panel.add(exit); //button that says "Exit
    panel.add(timer); //the timer

As you can see, the statements to add the text field, and correct answer tracker are all written before the add statement for the tables, and yet the tables are at the top. Additionally, there's the issue of my tables in that loop being added in the backwards order, so I had to reverse the direction of the loop iterations to get the tables to appear in the correct order. I've tried using stuff like setLocation and setBounds to get my components more where I want them, but nothing happened. Also, everything just appears in a row below the tables (and I know that's what FlowLayout does), but how would I go about customizing exactly where things appear?


答:
You defined users variable as a list (then Ansible internally passes this value as a JSON representation to the useradd executable which fails).

You should define the value as a string:

```<code>users: jjohnson
</code>```

But if you wanted to add multiple users (as the plural name users suggests), you should use loops.  There is an example right for you at the top of the documentation.

Title: "useradd: invalid user name" in Ansible user module

Body:
My Ansible playbook:

- hosts: docker
  remote_user: root

  tasks:
  - include_vars: users.yml
  - name: Add users to local docker groups
    user: name='{{users}}' groups='{{group_name}}' append=yes

users.yml file:

users:
    - jjohnson

group_name: docker

ansible-playbook docker-groups.yml:

PLAY [docker] **********************************************************************************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************************************************************************************
ok: [server]

TASK [include_vars] ****************************************************************************************************************************************************************************************
ok: [server]

TASK [Add users to local docker groups] ********************************************************************************************************************************************************************
fatal: [server]: FAILED! => {"changed": false, "failed": true, "msg": "useradd: invalid user name '['jjohnson']'\n", "name": "['jjohnson']", "rc": 3}

Why is it falling?

Body:
You defined users variable as a list (then Ansible internally passes this value as a JSON representation to the useradd executable which fails).

You should define the value as a string:

users: jjohnson

But if you wanted to add multiple users (as the plural name users suggests), you should use loops.  There is an example right for you at the top of the documentation.


问:
Returning a resolved value from 'fetch'
I'm trying to use fetch to get a JSON object from an API, I want to return the final resolved value of the object so that any one who uses the function can directly get the value without any need to resolve the promise it returns.

function f() {
    let result = fetch(url, {
        method: 'GET'
    })
    .then(response => response.json())
    .then(json => {
        return json
    }).catch(err => {
        // Error
    });

    return result;
}```

I don't really know if this is possible or not, but I'll be thankful for help, Thanks in advance.

答:
You can use await and async, which automatically resolves the Promise and avoids using .then() over and over.

```<code>async function f() {
    let result = (await fetch(url, {
        method: 'GET'
    })).json();

    return result;
}
</code>```

Title: Returning a resolved value from 'fetch'

Body:
I'm trying to use fetch to get a JSON object from an API, I want to return the final resolved value of the object so that any one who uses the function can directly get the value without any need to resolve the promise it returns.

function f() {
    let result = fetch(url, {
        method: 'GET'
    })
    .then(response => response.json())
    .then(json => {
        return json
    }).catch(err => {
        // Error
    });

    return result;
}

I don't really know if this is possible or not, but I'll be thankful for help, Thanks in advance.

Body:
You can use await and async, which automatically resolves the Promise and avoids using .then() over and over.

async function f() {
    let result = (await fetch(url, {
        method: 'GET'
    })).json();

    return result;
}


问:
Javascript, inner classes, and how to access parent scope efficiently
In Javascript, I would like to define a class with an inner (or nested) class.  Within the inner class I'd like to be able to get access to the parent instance. How can I do this efficiently?

Some code will show what I mean. Suppose I define a class, MyType1, which exposes several properties and one function, SayHello:

```<code>(function(){
    MyType1 = function(name){
        this.TypeName = "MyType1";
        this.Name = name;
    };

    MyType1.prototype.SayHello = function() {
        say(this.Name + " says hello...");
    };
})();
</code>```

Ok, now, starting from there, I want to add an "inner class" to MyType1, so I add some new code so that it looks like this:

```<code>(function(){
    MyType1 = function(name){
        this.TypeName = "MyType1";
        this.Name = name;
        var parentName = name;
        this.Child = function(name) {
            this.Description = parentName + "'s child, " + name;
        };

        this.Child.prototype.Introduce = function() {
            say(this.Description + ", greets you...");
        };
    };

    MyType1.prototype.SayHello = function() {
        say(this.Name + " says hello...");
    };
})();
</code>```

Now I can use these classes like this:

```<code>var x = new MyType1("Victor");
x.SayHello();

var c = new x.Child("Elizabeth");
c.Introduce();
</code>```

that all works.  But it defines a new Child function (or type, if you like) for every instance of MyType1.  What I'd like to do is get access to the parent class scope, without resorting to that inefficiency.
Something like this:

```<code>(function(){
    MyType2 = function(name){
        this.TypeName = "MyType2";
        this.Name = name;
        this.Prop1 = 1872;
        var parentName = name;
    };

    MyType2.prototype.SayHello = function() {
        say(this.Name + " says hello...");
    };

    var c1 = function(name) {
        this.Description = parentName + "'s child, " + name;
        //                ^^ no go! ^^
    };

    c1.prototype.Introduce = function() {
        say(this.Description + ", greets you...");
    };

    MyType2.prototype.Child = c1;

})();
</code>```

But, this doesn't work.  The parentName var is out of scope, of course.

Is there an efficient way for the Child instance (in the constructor, or in any class function) to gain access to the parent (MyType2) instance?

I know that I could define the Child class to be an independent, non-nested class, then in the ctor for that, just pass the Parent instance. But this creates N references to the parent instance, one for every Child instance. That seems like an inefficiency I'd like to avoid.

thanks for any tips.

EDIT - the reason I want the Child to have access to the parent instance, is that the parent holds an object that is fairly expensive to create - something like a db connection - and I'd like the child to be able to utilize that thing.

答:
The only way I can think of is to pass in the parent object to the Child constructor:

```<code>MyType2.Child = function (parent, name) {
    this.parent = parent;
    this.name = name;
    this.Description = this.parent.name + "'s child, " + name;
};
</code>```

And instantiate it with:

```<code>var x = new MyType2("Victor");

var c = new MyType2.Child(x, "Elizabeth");
</code>```

My justification is that it makes more sense that the Child constructor is a "static" property of MyType2, instead of the instantiated object x in your example, since we are talking about types here, which are the same across all instances of MyType2.

Body:
In Javascript, I would like to define a class with an inner (or nested) class.  Within the inner class I'd like to be able to get access to the parent instance. How can I do this efficiently?

Some code will show what I mean. Suppose I define a class, MyType1, which exposes several properties and one function, SayHello:

(function(){
    MyType1 = function(name){
        this.TypeName = "MyType1";
        this.Name = name;
    };

    MyType1.prototype.SayHello = function() {
        say(this.Name + " says hello...");
    };
})();

Ok, now, starting from there, I want to add an "inner class" to MyType1, so I add some new code so that it looks like this:

(function(){
    MyType1 = function(name){
        this.TypeName = "MyType1";
        this.Name = name;
        var parentName = name;
        this.Child = function(name) {
            this.Description = parentName + "'s child, " + name;
        };

        this.Child.prototype.Introduce = function() {
            say(this.Description + ", greets you...");
        };
    };

    MyType1.prototype.SayHello = function() {
        say(this.Name + " says hello...");
    };
})();

Now I can use these classes like this:

var x = new MyType1("Victor");
x.SayHello();

var c = new x.Child("Elizabeth");
c.Introduce();

that all works.  But it defines a new Child function (or type, if you like) for every instance of MyType1.  What I'd like to do is get access to the parent class scope, without resorting to that inefficiency.
Something like this:

(function(){
    MyType2 = function(name){
        this.TypeName = "MyType2";
        this.Name = name;
        this.Prop1 = 1872;
        var parentName = name;
    };

    MyType2.prototype.SayHello = function() {
        say(this.Name + " says hello...");
    };

    var c1 = function(name) {
        this.Description = parentName + "'s child, " + name;
        //                ^^ no go! ^^
    };

    c1.prototype.Introduce = function() {
        say(this.Description + ", greets you...");
    };

    MyType2.prototype.Child = c1;

})();

But, this doesn't work.  The parentName var is out of scope, of course.

Is there an efficient way for the Child instance (in the constructor, or in any class function) to gain access to the parent (MyType2) instance?

I know that I could define the Child class to be an independent, non-nested class, then in the ctor for that, just pass the Parent instance. But this creates N references to the parent instance, one for every Child instance. That seems like an inefficiency I'd like to avoid.

thanks for any tips.

EDIT - the reason I want the Child to have access to the parent instance, is that the parent holds an object that is fairly expensive to create - something like a db connection - and I'd like the child to be able to utilize that thing.

Body:
The only way I can think of is to pass in the parent object to the Child constructor:

MyType2.Child = function (parent, name) {
    this.parent = parent;
    this.name = name;
    this.Description = this.parent.name + "'s child, " + name;
};

And instantiate it with:

var x = new MyType2("Victor");

var c = new MyType2.Child(x, "Elizabeth");

My justification is that it makes more sense that the Child constructor is a "static" property of MyType2, instead of the instantiated object x in your example, since we are talking about types here, which are the same across all instances of MyType2.


问:
JSX or HTML autocompletion in Visual Studio Code
Is there any way to use components or HTML completion in Visual Studio Code? Because typing each letter manually is not good idea when we have classes like Bootstrap etc. For example completion as in Emmet: ul>li*2>a

```<code>var React = require('react');

var Header = React.createClass({
    render: function () {
        return (

            <nav className="navbar navbar-defaullt">
                <div className="container-fluid">
                    <a href="/" className="navbar-brand">
                        <img width="50" height="50" src="images/logo.png" alt="logo" />
                    </a>
                    <ul className="nav navbar-nav">
                        <li><a href="/">Home</a></li>
                        <li><a href="/#about">About</a></li>
                    </ul>
                </div>
            </nav>

                );
                }
                });
module.exports  = Header;
</code>```

答:
2023: Straightforward way to add JSX/HTML autocomplete for .js files in React projects...

First, open VSCode's Settings by pressing Ctrl + , (or Cmd+, on Mac). Then...

Set with JSON:

From Settings, to open settings.json, click the Open JSON button shown below. Optionally, if you don't want to set this globally, you can create a .vscode/settings.json file at the project root.

Add these JSON values in the settings.json:

```<code> "emmet.includeLanguages": {
     "javascript": "javascriptreact"
 },
 "emmet.syntaxProfiles": {
     "javascript": "jsx"
 }
</code>```

Set with Settings UI:

Note that Emmet: Syntax Profiles still requires opening settings.json (shown above), but for anyone seeking this info, here it is...

From Settings, use the search bar to find Emmet: Include Languages

Click "Add item" then add a mapping for javascript to javascriptreact.

Body:
Is there any way to use components or HTML completion in Visual Studio Code? Because typing each letter manually is not good idea when we have classes like Bootstrap etc. For example completion as in Emmet: ul>li*2>a

var React = require('react');

var Header = React.createClass({
    render: function () {
        return (

Home

About

                );
                }
                });
module.exports  = Header;

Body:
2023: Straightforward way to add JSX/HTML autocomplete for .js files in React projects...

First, open VSCode's Settings by pressing Ctrl + , (or Cmd+, on Mac). Then...

Set with JSON:

From Settings, to open settings.json, click the Open JSON button shown below. Optionally, if you don't want to set this globally, you can create a .vscode/settings.json file at the project root.

Add these JSON values in the settings.json:

 "emmet.includeLanguages": {
     "javascript": "javascriptreact"
 },
 "emmet.syntaxProfiles": {
     "javascript": "jsx"
 }

Set with Settings UI:

Note that Emmet: Syntax Profiles still requires opening settings.json (shown above), but for anyone seeking this info, here it is...

From Settings, use the search bar to find Emmet: Include Languages

Click "Add item" then add a mapping for javascript to javascriptreact.


问:
How to Fix Permissions on Home-brew on MacOS High Sierra
When I tried to install python onto homebrew it downloaded it and then an error message popped up at the end that stopped it from completing. When I try to do it again it asks me to do:

```<code>$ brew link python
</code>```

After entering that the same error message appears:

```permission denied @ dir_s_mkdir - /usr/local/lib```

I have tried to do:

```<code>$ sudo chown -R $(whoami) /usr/local
</code>```

And I get an error message that reads:

chown: /usr/local: Operation not permitted

答:
As mentioned, by henrikstroem, backticks can be helpful, and as mentioned by bnaecker special attributes might also hinder the process.

You might also try to run the command directly as root to see if better results, by doing sudo su - and then chown -R username /usr/local

But are you sure that is really what you want?
It might be more interesting to create a group that has an access on it (like chown -R originaluser:group /usr/local, set the rights you want, and/or to make your user part of that group.

Body:
When I tried to install python onto homebrew it downloaded it and then an error message popped up at the end that stopped it from completing. When I try to do it again it asks me to do:

$ brew link python

After entering that the same error message appears:

permission denied @ dir_s_mkdir - /usr/local/lib

I have tried to do:

$ sudo chown -R $(whoami) /usr/local

And I get an error message that reads:

chown: /usr/local: Operation not permitted


问:
Trying to count words in different lists
I'm trying for sentiment analysis to score many comments in a data frame. I have a negative word corpora, and a positive one. I want to add 1 for every positive word, and remove 1 for every negative word in the comment. My code:

```<code>     text['counts'] = 0
     for i in text.Reviews:
         if i in p:
             text['counts'] += 1
         elif i in n:
             text['counts'] +=-1
</code>```

I want the new column, text.counts to give the comment's score for every comment, but so far I've only managed to get the total count appear on every row (as if my dataframe was one big comment.)

Thank you!

答:
TL;DR

```<code>from collections import Counter

import pandas as pd
from nltk import word_tokenize

positive_words = set(['good', 'awesome', 'excellent'])
negative_words = set(['bad', 'terrible'])

df = pd.DataFrame( ['good and not bad', 'it is a terrible bad product', 'excellent product'], columns = ['Reviews'])

df['Tokenized'] = df['Reviews'].apply(str.lower).apply(word_tokenize)
df['WordCount'] = df['Tokenized'].apply(lambda x: Counter(x))

df['Positive'] = df['WordCount'].apply(lambda x: sum(v for k,v in x.items() if k in positive_words))
df['Negative'] = df['WordCount'].apply(lambda x: sum(v for k,v in x.items() if k in negative_words))
</code>```

Then:

```<code>>>> df['Sentiment'] = df['Positive'] - df['Negative']
>>> df[['Reviews', 'Sentiment']]
                        Reviews  Sentiment
0              good and not bad          0
1  it is a terrible bad product         -2
2             excellent product          1
</code>```

Above answer loops twice, here's another alternative:

```<code>from collections import Counter

import pandas as pd
from nltk import word_tokenize

positive_words = set(['good', 'awesome', 'excellent'])
negative_words = set(['bad', 'terrible'])

df = pd.DataFrame( ['good and not bad', 'it is a terrible bad product', 'excellent product'], columns = ['Reviews'])

df['Tokenized'] = df['Reviews'].apply(str.lower).apply(word_tokenize)
df['WordCount'] = df['Tokenized'].apply(lambda x: Counter(x))

df['Sentiment'] = df['WordCount'].apply(lambda x: sum(v if k in positive_words else -v if k in negative_words else 0 for k,v in x.items()))
</code>```

Body:
I'm trying for sentiment analysis to score many comments in a data frame. I have a negative word corpora, and a positive one. I want to add 1 for every positive word, and remove 1 for every negative word in the comment. My code:

     text['counts'] = 0
     for i in text.Reviews:
         if i in p:
             text['counts'] += 1
         elif i in n:
             text['counts'] +=-1

I want the new column, text.counts to give the comment's score for every comment, but so far I've only managed to get the total count appear on every row (as if my dataframe was one big comment.)

Thank you!

Body:
TL;DR

from collections import Counter

import pandas as pd
from nltk import word_tokenize

positive_words = set(['good', 'awesome', 'excellent'])
negative_words = set(['bad', 'terrible'])

df = pd.DataFrame( ['good and not bad', 'it is a terrible bad product', 'excellent product'], columns = ['Reviews'])

df['Tokenized'] = df['Reviews'].apply(str.lower).apply(word_tokenize)
df['WordCount'] = df['Tokenized'].apply(lambda x: Counter(x))

df['Positive'] = df['WordCount'].apply(lambda x: sum(v for k,v in x.items() if k in positive_words))
df['Negative'] = df['WordCount'].apply(lambda x: sum(v for k,v in x.items() if k in negative_words))

Then:

>>> df['Sentiment'] = df['Positive'] - df['Negative']
>>> df[['Reviews', 'Sentiment']]
                        Reviews  Sentiment
0              good and not bad          0
1  it is a terrible bad product         -2
2             excellent product          1

Above answer loops twice, here's another alternative:

from collections import Counter

import pandas as pd
from nltk import word_tokenize

positive_words = set(['good', 'awesome', 'excellent'])
negative_words = set(['bad', 'terrible'])

df = pd.DataFrame( ['good and not bad', 'it is a terrible bad product', 'excellent product'], columns = ['Reviews'])

df['Tokenized'] = df['Reviews'].apply(str.lower).apply(word_tokenize)
df['WordCount'] = df['Tokenized'].apply(lambda x: Counter(x))

df['Sentiment'] = df['WordCount'].apply(lambda x: sum(v if k in positive_words else -v if k in negative_words else 0 for k,v in x.items()))


问:
Unwrapping Optional JSON Element Crashes App
I have a problem unwrapping an optional element in my JSON nested array. The elements in question are labeled as "solo_competitive_rank" and "score". For reference, when a tableview cell in one controller is clicked, these elements should be displayed in a new view controller. While this works sometimes, when a cell that is selected does not have these values, the app crashes. Could someone please assist me in properly unwrapping these elements?

JSON Struct

```<code>struct PlayerStatsParent:Decodable{
let rankings: [PlayerStats]
}

struct PlayerStats:Decodable {
let personaname: String?
let score: Double?
let solo_competitive_rank: Int?
let avatar: String?
}
</code>```

Display View

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    rankLabel.text = "\((playerRank?.solo_competitive_rank)!)"
    scoreLabel.text = "\((playerRank?.score)!)"
}
</code>```

答:
I'd recommend wrapping each label in an if statement. Like so:</p>

```<code>if let soloRank = playerRank?.solo_competitive_rank as? Int {
   rankLabel.text = String(soloRank)
}

if let score = playerRank?.score as? Double {
   scoreLabel.text = String(score)
}
</code>```

Body:
I have a problem unwrapping an optional element in my JSON nested array. The elements in question are labeled as "solo_competitive_rank" and "score". For reference, when a tableview cell in one controller is clicked, these elements should be displayed in a new view controller. While this works sometimes, when a cell that is selected does not have these values, the app crashes. Could someone please assist me in properly unwrapping these elements?

JSON Struct

struct PlayerStatsParent:Decodable{
let rankings: [PlayerStats]
}

struct PlayerStats:Decodable {
let personaname: String?
let score: Double?
let solo_competitive_rank: Int?
let avatar: String?
}

Display View

override func viewDidLoad() {
    super.viewDidLoad()
    rankLabel.text = "\((playerRank?.solo_competitive_rank)!)"
    scoreLabel.text = "\((playerRank?.score)!)"
}

Body:
I'd recommend wrapping each label in an if statement. Like so:

if let soloRank = playerRank?.solo_competitive_rank as? Int {
   rankLabel.text = String(soloRank)
}

if let score = playerRank?.score as? Double {
   scoreLabel.text = String(score)
}


问:
Setting the application icon for OSX in Qt Creator
Followed the directions here for OSX: http://doc.qt.io/qt-5/appicon.html
stating that all I need to do is add ICON = myapp.icns to my project file.
I used one of the ICNS files I stole from Qt itself (in other words, it should work, its not a conversion problem) and when build after running qmake I get the error

```<code>make: *** No rule to make target '1.22/MyProject.icns', needed by 'myapp.app/Contents/Resources/MyProject.icns'
</code>```

I regularly use make but have little experience with Qt so I have no idea what it's trying to tell me here (I don't even know where these file paths are coming from).
The .icns file has been added to the resources .qrc and is in the base directory of the project.

Any help is much appreciated.  Thanks!

EDIT:
Ok, the space in the file path was preventing the build.  It now compiles and runs but still does not have a dock icon.

Here is the output of the grep command, as requested by Simon Warta:

```<code>_Qt_5_1_1_clang_64bit-Debug/Makefile | grep -C 3 icns
443
444 :
445     @$(DEL_FILE)
446     @sed -e "s,@SHORT_VERSION@,1.22,g" -e "s,@TYPEINFO@,????,g" -e "s,@ICON@,myapp.icns,g" -e "s,@EXECUTABLE@,myapp,g" -e "s,@TYPEINFO@,????,g" ../myapp1.22/myapp.plist >
447 myapp.app/Contents/Resources/myapp.icns: ../myapp1.22/myapp.icns
448     @test -d myapp.app/Contents/Resources/ || mkdir -p myapp.app/Contents/Resources/
--
448     @test -d myapp.app/Contents/Resources/ || mkdir -p myapp.app/Contents/Resources/
449     @$(DEL_FILE) myapp.app/Contents/Resources/myapp.icns
450     @$(COPY_FILE) ../myapp1.22/myapp.icns myapp.app/Contents/Resources/myapp.icns
451 dist:
452     @test -d .tmp/myapp1.22 || mkdir -p .tmp/myapp1.22

[[All my source files]]

477 compiler_rcc_clean:
478     -$(DEL_FILE) qrc_myapp.cpp
479 qrc_myapp.cpp: ../myapp1.22/myapp.qrc \
480         ../myapp1.22/myapp.icns \
481         ../myapp1.22/images/splashmyapp2.png \
482         ../myapp1.22/images/splashmyapp1.png \
483         ../myapp1.22/images/About.png \
--
--
481         ../myapp1.22/images/splashmyapp2.png \
482         ../myapp1.22/images/splashmyapp1.png \
483         ../myapp1.22/images/About.png
486     /Users/EngMac/Qt5.1.1/5.1.1/clang_64/bin/rcc -name myapp ../myapp1.22/myapp.qrc -o qrc_myapp.cpp
</code>```

From myapp.pro:

```<code>ICON = myapp.icns
QMAKE_INFO_PLIST = myapp.plist
</code>```

答:
I had to add to Project.pro:

```<code>ICON = Project.icns
QMAKE_INFO_PLIST = Info.plist

# Qt doesn't copy over the .icns file ?!
RESOURCE_FILES.files = $$ICON
RESOURCE_FILES.path = Contents/Resources
QMAKE_BUNDLE_DATA += RESOURCE_FILES
</code>```

and in Info.plist:

```<code><key>CFBundleIconFile</key>
<string>ContentCanvas</string>
</code>```

It seems that Qt doesn't set the project up to copy the .icns file into the bundle (at least with Qt 5.9), so having it in the .plist file is useless.  The last three lines in the .pro file copy it manually.

Body:
Followed the directions here for OSX: http://doc.qt.io/qt-5/appicon.html
stating that all I need to do is add ICON = myapp.icns to my project file.
I used one of the ICNS files I stole from Qt itself (in other words, it should work, its not a conversion problem) and when build after running qmake I get the error

make: *** No rule to make target '1.22/MyProject.icns', needed by 'myapp.app/Contents/Resources/MyProject.icns'

I regularly use make but have little experience with Qt so I have no idea what it's trying to tell me here (I don't even know where these file paths are coming from).
The .icns file has been added to the resources .qrc and is in the base directory of the project.

Any help is much appreciated.  Thanks!

EDIT:
Ok, the space in the file path was preventing the build.  It now compiles and runs but still does not have a dock icon.

Here is the output of the grep command, as requested by Simon Warta:

_Qt_5_1_1_clang_64bit-Debug/Makefile | grep -C 3 icns
443
444 :
445     @$(DEL_FILE)
446     @sed -e "s,@SHORT_VERSION@,1.22,g" -e "s,@TYPEINFO@,????,g" -e "s,@ICON@,myapp.icns,g" -e "s,@EXECUTABLE@,myapp,g" -e "s,@TYPEINFO@,????,g" ../myapp1.22/myapp.plist >
447 myapp.app/Contents/Resources/myapp.icns: ../myapp1.22/myapp.icns
448     @test -d myapp.app/Contents/Resources/ || mkdir -p myapp.app/Contents/Resources/
--
448     @test -d myapp.app/Contents/Resources/ || mkdir -p myapp.app/Contents/Resources/
449     @$(DEL_FILE) myapp.app/Contents/Resources/myapp.icns
450     @$(COPY_FILE) ../myapp1.22/myapp.icns myapp.app/Contents/Resources/myapp.icns
451 dist:
452     @test -d .tmp/myapp1.22 || mkdir -p .tmp/myapp1.22

[[All my source files]]

477 compiler_rcc_clean:
478     -$(DEL_FILE) qrc_myapp.cpp
479 qrc_myapp.cpp: ../myapp1.22/myapp.qrc \
480         ../myapp1.22/myapp.icns \
481         ../myapp1.22/images/splashmyapp2.png \
482         ../myapp1.22/images/splashmyapp1.png \
483         ../myapp1.22/images/About.png \
--
--
481         ../myapp1.22/images/splashmyapp2.png \
482         ../myapp1.22/images/splashmyapp1.png \
483         ../myapp1.22/images/About.png
486     /Users/EngMac/Qt5.1.1/5.1.1/clang_64/bin/rcc -name myapp ../myapp1.22/myapp.qrc -o qrc_myapp.cpp

From myapp.pro:

ICON = myapp.icns
QMAKE_INFO_PLIST = myapp.plist

Body:
I had to add to Project.pro:

ICON = Project.icns
QMAKE_INFO_PLIST = Info.plist

# Qt doesn't copy over the .icns file ?!
RESOURCE_FILES.files = $$ICON
RESOURCE_FILES.path = Contents/Resources
QMAKE_BUNDLE_DATA += RESOURCE_FILES

and in Info.plist:

<key>CFBundleIconFile</key>
<string>ContentCanvas</string>

It seems that Qt doesn't set the project up to copy the .icns file into the bundle (at least with Qt 5.9), so having it in the .plist file is useless.  The last three lines in the .pro file copy it manually.


问:
Bootstrap 4: Uncaught ReferenceError: Popper is not defined
I've installed Bootstrap 4 using Node and Gulp and when running the application I get the following error

Uncaught ReferenceError: Popper is not defined

I've only been using the Bootstrap grid system so far and I haven't used anything that would require the Bootstrap JS. Looks to me like Bootstrap is missing something or I haven't installed it correctly (to be honest it's probably me) - has anyone else come across the same issue or know a fix at all?

答:
I had the same issue and have been playing around with it for half a day over a simple carousel.  Safari on Mac didn't give feedback properly in that there is a priority on libraries:

```<code>    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
</code>```

Reviewing the error I ran across "You need JQ before BS for this to work", so I tried it, also putting Popper before BS.

So I have all of these in my  and boom it worked.

Body:
I had the same issue and have been playing around with it for half a day over a simple carousel.  Safari on Mac didn't give feedback properly in that there is a priority on libraries:

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>

Reviewing the error I ran across "You need JQ before BS for this to work", so I tried it, also putting Popper before BS.

So I have all of these in my <head> and boom it worked.


问:
Fast element access for multi-dimensional representation of contiguous array
I have a multi-dimensional array represented contiguously in memory. I want to keep this representation hidden and just let the user access the array elements as if it were a multi-dimensional one: e.g. my_array[0][3][5] or my_array(0,3,5) or something similar. The dimensions of the object are not determined until runtime, but the object is created with a type that specifies how many dimensions it has. This element look-up will need to be called billions of times, and so should hopefully involve minimal overhead for each call.

I have looked at similar questions but not really found a good solution. Using the [] operator requires the creation of N-1 dimensional objects, which is fine for multi-dimensional structures like vectors-of-vectors because the object already exists, but for a contiguous array it seems like it would get convoluted very quickly and require some kind of slicing through the original array.

I have also looked at overloading (), which seems more promising, but requires specifying the number of arguments, which will vary depending upon the number of dimensions of the array. I have thought about using list initialization or vectors, but wanted to avoid instantiating objects.

I am only a little familiar with templates and figure that there should be some way with C++'s majestic template powers to specify a unique overloading of () for arrays with different types (e.g. different numbers of dimensions). But I have only used templates in really basic generic cases like making a function use both float and double.

I am imagining something like this:

```<code>template<typename TDim>
class MultiArray {
public:
  MultiArray() {} //build some things
  ~MultiArray() {} //destroy some things

  // The number of arguments would be == to TDim for the instantiated class
  float& operator() (int dim1, int dim2, ...) {
    //convert to contiguous index and return ref to element
    // I believe the conversion equation is something like:
    // dim1 + Maxdim1 * ( dim2 + MaxDim2 * ( dim3 + MaxDim3 * (...)))
  }

private:
  vector<float> internal_array;
  vector<int> MaxDimX; // Each element says how large each corresponding dim is.
};
</code>```

So if I initialize this class and attempted to access an element, it would look something like this:

```<code>my_array = MultiArray<4>();
element = my_array(2,5,4,1);
</code>```

How might I go about doing this using templates? Is this even possible?

答:
```<code>template<class T>
struct slice {
    T* data = 0;
    std::size_t const* stride = 0;
    slice operator[](std::size_t I)const {
        return{ data + I* *stride, stride + 1 };
    }
    operator T&()const {
      return *data;
    }
    T& operator=(typename std::remove_const<T>::type in)const {
      *data = std::move(in); return *data;
    }
};
</code>```

store a vector<T> of data, and an std::vector<std::size_t> stride of strides, where stride[0] is the element-stride that the first index wants.

```<code>template<class T>
struct buffer {
  std::vector<T> data;
  std::vector<std::size_t> strides;

  buffer( std::vector<std::size_t> sizes, std::vector<T> d ):
    data(std::move(d)),
    strides(sizes)
  {
    std::size_t scale = 1;
    for (std::size_t i = 0; i<sizes.size(); ++i){
      auto next = scale*strides[sizes.size()-1-i];
      strides[sizes.size()-1-i] = scale;
      scale=next;
    }
  }
  slice<T> get(){ return {data.data(), strides.data()}; }
  slice<T const> get()const{ return {data.data(), strides.data()}; }
};
</code>```

c++14.  Live example.

If you use not enough []s it refers to the first element of the subarray in question.  If you use too many it does UB.  It does zero dimension checking, both in count of dimensions and in size.

Both can be added, but would cost performance.

The number of dimensions is dynamic.  You can split buffer into two types, one that owns the buffer and the other that provides the dimensioned view of it.

Body:
I have a multi-dimensional array represented contiguously in memory. I want to keep this representation hidden and just let the user access the array elements as if it were a multi-dimensional one: e.g. my_array[0][3][5] or my_array(0,3,5) or something similar. The dimensions of the object are not determined until runtime, but the object is created with a type that specifies how many dimensions it has. This element look-up will need to be called billions of times, and so should hopefully involve minimal overhead for each call.

I have looked at similar questions but not really found a good solution. Using the [] operator requires the creation of N-1 dimensional objects, which is fine for multi-dimensional structures like vectors-of-vectors because the object already exists, but for a contiguous array it seems like it would get convoluted very quickly and require some kind of slicing through the original array.

I have also looked at overloading (), which seems more promising, but requires specifying the number of arguments, which will vary depending upon the number of dimensions of the array. I have thought about using list initialization or vectors, but wanted to avoid instantiating objects.

I am only a little familiar with templates and figure that there should be some way with C++'s majestic template powers to specify a unique overloading of () for arrays with different types (e.g. different numbers of dimensions). But I have only used templates in really basic generic cases like making a function use both float and double.

I am imagining something like this:

template<typename TDim>
class MultiArray {
public:
  MultiArray() {} //build some things
  ~MultiArray() {} //destroy some things

  // The number of arguments would be == to TDim for the instantiated class
  float& operator() (int dim1, int dim2, ...) {
    //convert to contiguous index and return ref to element
    // I believe the conversion equation is something like:
    // dim1 + Maxdim1 * ( dim2 + MaxDim2 * ( dim3 + MaxDim3 * (...)))
  }

private:
  vector<float> internal_array;
  vector<int> MaxDimX; // Each element says how large each corresponding dim is.
};

So if I initialize this class and attempted to access an element, it would look something like this:

my_array = MultiArray<4>();
element = my_array(2,5,4,1);

How might I go about doing this using templates? Is this even possible?

Body:
template<class T>
struct slice {
    T* data = 0;
    std::size_t const* stride = 0;
    slice operator[](std::size_t I)const {
        return{ data + I* *stride, stride + 1 };
    }
    operator T&()const {
      return *data;
    }
    T& operator=(typename std::remove_const<T>::type in)const {
      *data = std::move(in); return *data;
    }
};

store a vector<T> of data, and an std::vector<std::size_t> stride of strides, where stride[0] is the element-stride that the first index wants.

template<class T>
struct buffer {
  std::vector<T> data;
  std::vector<std::size_t> strides;

  buffer( std::vector<std::size_t> sizes, std::vector<T> d ):
    data(std::move(d)),
    strides(sizes)
  {
    std::size_t scale = 1;
    for (std::size_t i = 0; i<sizes.size(); ++i){
      auto next = scale*strides[sizes.size()-1-i];
      strides[sizes.size()-1-i] = scale;
      scale=next;
    }
  }
  slice<T> get(){ return {data.data(), strides.data()}; }
  slice<T const> get()const{ return {data.data(), strides.data()}; }
};

c++14.  Live example.

If you use not enough []s it refers to the first element of the subarray in question.  If you use too many it does UB.  It does zero dimension checking, both in count of dimensions and in size.

Both can be added, but would cost performance.

The number of dimensions is dynamic.  You can split buffer into two types, one that owns the buffer and the other that provides the dimensioned view of it.