text:
Q: Issue related to Reading Excel using Apache POI in java I am trying to create an excel file of 2007.
Scenario for Creation of Excel from other file.
Input file       :- InputFile.xlsx with One Sheet
Calculation File :- Model.xlsx with four sheets
Description for Calculation file :- 1) First Sheet is input file
2) Second sheet is Output 3) Third and Fourth Sheet is calculation sheets.
in Java using Apache POI I am reading Excel file. in one function I am reading file,takes input files InputFiles.xlsx
in second function I am merging two sheets in model.xlsx file. i.e.in the first sheet of Model.xlsx merging first sheet of InputFile.xlsx
In third function I am reading output, that affect after writing in model.xlsx and reading it.
Merging function as follows
        public void writeXLSXFile(String modelid, String inputfile) throws SQLException, ClassNotFoundException
            {
                try
                {
                    String realPath = context.getRealPath("/");
                    String DestPath = "";
                    InputStream ExcelFileToRead = new FileInputStream(inputfile);

                    XSSFWorkbook wbip = new XSSFWorkbook(ExcelFileToRead);

                    DestPath = realPath + "WEB-INF/classes/uploadfiles/Model.xlsx";

                    NPOIFSFileSystem fs = new NPOIFSFileSystem(new File(DestPath));
                    EncryptionInfo info = new EncryptionInfo(fs);
                    Decryptor d = Decryptor.getInstance(info);
                    XSSFWorkbook wb = null;
                    try
                    {
                        if (d.verifyPassword("MUSDCM"))
                        {
                            wb = new XSSFWorkbook(d.getDataStream(fs));
                        } else
                        {
                            System.out.println("Wrong Password");
                        }
                    } catch (GeneralSecurityException ex)
                    {
                    }

                    XSSFSheet sheet = wb.getSheetAt(0);
                    wb.removeSheetAt(0);
                    wb.removeSheetAt(3);

                    wb.createSheet("2.2 Parameter Estimates");
                    wb.createSheet("Raw Macro Data");

                    wb.setSheetOrder("DCM_Implementation_v09.csv", 1);
                    wb.setSheetOrder("Excel Model_IG", 2);
                    wb.setSheetOrder("Excel Model_HY", 3);
                    wb.setSheetOrder("Raw Macro Data", 4);
                    wb.setSheetOrder("2.2 Parameter Estimates", 0);
                    sheet = wb.getSheetAt(0);

                    XSSFRow row = sheet.createRow(1);
                    XSSFCell cell = row.createCell(1);
                    cell.setCellValue("Investment Grade Bond Issuance Volume Model");
                    cell = row.createCell(4);
                    cell.setCellValue("High Yield Bond Issuance Volume Model");

                    row = sheet.createRow(3);
                    cell = row.createCell(1);
                    cell.setCellValue("Independent Variables");
                    cell = row.createCell(2);
                    cell.setCellValue("Coefficients");

                    cell = row.createCell(4);
                    cell.setCellValue("Independent Variables");
                    cell = row.createCell(5);
                    cell.setCellValue("Coefficients");

                    int rowNumber = 4;

                    Class.forName("com.mysql.jdbc.Driver");
                    Connection con = getConnection();
                    Statement st = con.createStatement();
                    ResultSet rs = st.executeQuery("SELECT s.volumename,s.id,s.parameter,s.value,m.model_name FROM singlevalue_table s inner join model_inventory m on s.modelid =m.modelid and s.modelid=" + modelid);
                    ArrayList InBond = new ArrayList();
                    ArrayList HnBond = new ArrayList();
                    while (rs.next())
                    {
                        if ("Investment Grade Bond Issuance Volume Model".equals(rs.getString("s.volumename")))
                        {
                            InBond.add(rs.getString("s.parameter"));
                            InBond.add(rs.getString("s.value"));
                        } else if ("High Yield Bond Issuance Volume Model".equals(rs.getString("s.volumename")))
                        {
                            HnBond.add(rs.getString("s.parameter"));
                            HnBond.add(rs.getString("s.value"));
                        }
                    }
                    int maxcount = ((InBond.size() >= HnBond.size()) ? InBond.size() : HnBond.size());
                    int count1 = 0;
                    int count2 = 0;
                    for (int j = 0; j < maxcount / 2; j++)
                    {
                        row = sheet.createRow(j + 4);
                        if (j < (InBond.size() / 2))
                        {
                            cell = row.createCell(1);
                            cell.setCellValue((String) InBond.get(count1));
                            cell = row.createCell(2);
                            cell.setCellValue((String) InBond.get(count1 + 1));
                            count1 += 2;
                        }
                        if (j < (HnBond.size() / 2))
                        {
                            cell = row.createCell(4);
                            cell.setCellValue((String) HnBond.get(count2));
                            cell = row.createCell(5);
                            cell.setCellValue((String) HnBond.get(count2 + 1));
                            count2 += 2;
                        }
                    }
                    wb = CopySheet(wbip, wb);
                    try
                    {
                        wb.setForceFormulaRecalculation(true);
                        FileOutputStream fileOut = new FileOutputStream(DestPath);
                        wb.write(fileOut);
                        wbip.close();
                        wb.close();
                        fs.close();
                        fileOut.close();
                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }

                    //Add password protection and encrypt the file
                    fs = null;
                    info = null;
                    fs = new NPOIFSFileSystem();
                    info = new EncryptionInfo(fs, EncryptionMode.binaryRC4);

                    Encryptor enc = info.getEncryptor();
                    enc.confirmPassword("MUSDCM");

                    OPCPackage opc = OPCPackage.open(new File(DestPath), PackageAccess.READ_WRITE);
                    OutputStream os = enc.getDataStream(fs);
                    opc.save(os);
                    opc.close();

                    FileOutputStream fos = new FileOutputStream(DestPath);
                    fs.writeFilesystem(fos);
                    fos.close();
                    fs.close();
                    ExcelFileToRead.close();
                    System.out.println("File created!!");
                } catch (Exception ex)
                {
                    Logger.getLogger(resource.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

Reading output from Model.xlsx function as follows
            public Response readXLSXFileWithSecondSheet(@QueryParam("modelid") String modelid) throws IOException, GeneralSecurityException
                {
                    try
                    {
                        String realPath = context.getRealPath("/");
                        String DestPath = realPath + "WEB-INF/classes/uploadfiles/DCM_Implementation_v10.xlsx";
                        NPOIFSFileSystem fs = new NPOIFSFileSystem(new File(DestPath));
                        EncryptionInfo info = new EncryptionInfo(fs);
                        Decryptor d = Decryptor.getInstance(info);
                        XSSFWorkbook wb = null;
                        if (d.verifyPassword("MUSDCM"))
                        {
                            wb = new XSSFWorkbook(d.getDataStream(fs));
                            wb.setForceFormulaRecalculation(true);
                        } else
                        {
                            System.out.println("Wrong Password");
                        }
                        XSSFSheet sheet = (XSSFSheet) wb.getSheetAt(1);
                        XSSFRow row;
                        XSSFCell cell;
                        ArrayList Heading = new ArrayList();
                        ArrayList<graphdata> Basemap = new ArrayList<graphdata>();
                        ArrayList<graphdata> Adversemap = new ArrayList<graphdata>();
                        ArrayList<graphdata> SeverelyAdversemap = new ArrayList<graphdata>();
                        ArrayList<graphdata> BHCBasemap = new ArrayList<graphdata>();
                        ArrayList<graphdata> BHCSeverelyAdversemap = new ArrayList<graphdata>();
                        String ModelName = "Investment Grade Bond Issuance Volume Model";
                        Iterator rows = sheet.rowIterator();
                        while (rows.hasNext())
                        {
                            row = (XSSFRow) rows.next();
                            Iterator cells = row.cellIterator();
                            //int columnNo = 1;
                            int CCARCount = 0;
                            graphdata g1 = new graphdata();
                            graphdata g2 = new graphdata();
                            graphdata g3 = new graphdata();
                            graphdata g4 = new graphdata();
                            graphdata g5 = new graphdata();
                            while (cells.hasNext())
                            {
                                cell = (XSSFCell) cells.next();
                                int ActulaColINdex = cell.getColumnIndex();

                                if (cell.getCellType() == XSSFCell.CELL_TYPE_BLANK)
                                {

                                    continue;
                                }

                                if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
                                {
                                    if (((String) cell.getRichStringCellValue().getString()).equals(ModelName) && cell.getColumnIndex() == 1)
                                    {
                                        ModelName = (String) cell.getRichStringCellValue().getString();
                                        continue;
                                    }
                                    if (((String) cell.getRichStringCellValue().getString()).equals("High Yield Bond Issuance Volume Model") && cell.getColumnIndex() == 1)
                                    {
                                        ModelName = (String) cell.getRichStringCellValue().getString();
                                        continue;
                                    }

                                    String FindCCAR = (String) cell.getRichStringCellValue().getString();
                                    if (FindCCAR.contains("CCAR"))
                                    {
                                        continue;
                                    }
                                    if (FindCCAR.contains("CCAR"))
                                    {
                                        switch (CCARCount)
                                        {
                                            case 0:
                                                Heading.add(FindCCAR);
                                                break;
                                            case 1:
                                                Heading.add(FindCCAR);
                                                break;
                                            case 2:
                                                Heading.add(FindCCAR);
                                                break;
                                            case 3:
                                                Heading.add(FindCCAR);
                                                break;
                                            case 4:
                                                Heading.add(FindCCAR);
                                                break;
                                        }
                                        CCARCount++;
                                    }
                                    if (FindCCAR.contains("Date") || FindCCAR.contains("Model") || FindCCAR.contains("Diff"))
                                    {
                                        continue;
                                    }

                                    if (ActulaColINdex <= 5 && ActulaColINdex >= 1) //Base
                                    {
                                        if (ActulaColINdex == 1)
                                        {
                                            g1.setVolumeName(ModelName);
                                            g1.setModelName("Base");
                                            g1.setYear(cell.getRichStringCellValue().toString());
                                        }
                                        //System.out.print(cell.getRichStringCellValue() + " ");

                                    }
                                    if (ActulaColINdex <= 11 && ActulaColINdex >= 7) //Adverse
                                    {
                                        if (ActulaColINdex == 7)
                                        {
                                            g2.setVolumeName(ModelName);
                                            g2.setModelName("Adverse");
                                            g2.setYear(cell.getRichStringCellValue().toString());
                                        }
                                        //System.out.print(cell.getRichStringCellValue() + " ");

                                    }
                                    if (ActulaColINdex <= 17 && ActulaColINdex >= 13) //Severly Adverse
                                    {
                                        if (ActulaColINdex == 13)
                                        {
                                            g3.setVolumeName(ModelName);
                                            g3.setModelName("Severely Adverse");
                                            g3.setYear(cell.getRichStringCellValue().toString());
                                        }
                                        //System.out.print(cell.getRichStringCellValue() + " ");

                                    }
                                    if (ActulaColINdex <= 23 && ActulaColINdex >= 19) //BHC Base
                                    {
                                        if (ActulaColINdex == 19)
                                        {
                                            g4.setVolumeName(ModelName);
                                            g4.setModelName("BHC Base");
                                            g4.setYear(cell.getRichStringCellValue().toString());
                                        }
                                        //System.out.print(cell.getRichStringCellValue() + " ");

                                    }
                                    if (ActulaColINdex <= 30 && ActulaColINdex >= 26) //BHC Severly Adverse
                                    {
                                        if (ActulaColINdex == 26)
                                        {
                                            g5.setVolumeName(ModelName);
                                            g5.setModelName("BHC Severely Adverse");
                                            g5.setYear(cell.getRichStringCellValue().toString());
                                        }
                                        //System.out.print(cell.getRichStringCellValue() + " ");

                                    }
                                } else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
                                {
                                    if (ActulaColINdex <= 5 && ActulaColINdex >= 1) //Base
                                    {
                                        if (ActulaColINdex == 2)
                                        {
                                            g1.setSasmodel(cell.getNumericCellValue());
                                        }

                                    }
                                    if (ActulaColINdex <= 11 && ActulaColINdex >= 7) //Adverse
                                    {
                                        if (ActulaColINdex == 8)
                                        {
                                            g2.setSasmodel(cell.getNumericCellValue());
                                        }

                                    }
                                    if (ActulaColINdex <= 17 && ActulaColINdex >= 13) //Severly Adverse
                                    {
                                        if (ActulaColINdex == 14)
                                        {
                                            g3.setSasmodel(cell.getNumericCellValue());
                                        }

                                    }
                                    if (ActulaColINdex <= 23 && ActulaColINdex >= 19) //BHC Base
                                    {
                                        if (ActulaColINdex == 20)
                                        {
                                            g4.setSasmodel(cell.getNumericCellValue());
                                        }

                                    }
                                    if (ActulaColINdex <= 30 && ActulaColINdex >= 26) //BHC Severly Advrse
                                    {
                                        if (ActulaColINdex == 27)
                                        {
                                            g5.setSasmodel(cell.getNumericCellValue());
                                        }

                                    }
                                } else if (cell.getCellType() == XSSFCell.CELL_TYPE_FORMULA)
                                {
                                    switch (cell.getCachedFormulaResultType())
                                    {
                                        case Cell.CELL_TYPE_NUMERIC:
                                        {
                                            if (ActulaColINdex <= 5 && ActulaColINdex >= 1) //Base
                                            {
                                                if (ActulaColINdex == 3)
                                                {
                                                    g1.setXxcelmodel(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 4)
                                                {
                                                    g1.setDiff(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 5)
                                                {
                                                    g1.setDiffper(cell.getNumericCellValue());
                                                    Basemap.add(g1);
                                                }

                                            }
                                            if (ActulaColINdex <= 11 && ActulaColINdex >= 7) //Adverse
                                            {
                                                if (ActulaColINdex == 9)
                                                {
                                                    g2.setXxcelmodel(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 10)
                                                {
                                                    g2.setDiff(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 11)
                                                {
                                                    g2.setDiffper(cell.getNumericCellValue());
                                                    Adversemap.add(g2);
                                                }

                                            }
                                            if (ActulaColINdex <= 17 && ActulaColINdex >= 13) //SeverlyAdverse
                                            {
                                                if (ActulaColINdex == 15)
                                                {
                                                    g3.setXxcelmodel(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 16)
                                                {
                                                    g3.setDiff(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 17)
                                                {
                                                    g3.setDiffper(cell.getNumericCellValue());
                                                    SeverelyAdversemap.add(g3);
                                                }

                                            }
                                            if (ActulaColINdex <= 23 && ActulaColINdex >= 19)//BHC Base
                                            {
                                                if (ActulaColINdex == 21)
                                                {
                                                    g4.setXxcelmodel(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 22)
                                                {
                                                    g4.setDiff(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 23)
                                                {
                                                    g4.setDiffper(cell.getNumericCellValue());
                                                    BHCBasemap.add(g4);
                                                }

                                            }
                                            if (ActulaColINdex <= 30 && ActulaColINdex >= 26)//BHC Severly Adverse
                                            {
                                                if (ActulaColINdex == 28)
                                                {
                                                    g5.setXxcelmodel(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 29)
                                                {
                                                    g5.setDiff(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 30)
                                                {
                                                    g5.setDiffper(cell.getNumericCellValue());
                                                    BHCSeverelyAdversemap.add(g5);
                                                }

                                            }

                                        }
                                        break;
                                        case Cell.CELL_TYPE_STRING:
                                        {
                                            if (ActulaColINdex <= 5 && ActulaColINdex >= 1)//Base
                                            {
                                                if (ActulaColINdex == 3)
                                                {
                                                    g1.setXxcelmodel(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 4)
                                                {
                                                    g1.setDiff(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 5)
                                                {
                                                    g1.setDiffper(cell.getNumericCellValue());
                                                    Basemap.add(g1);
                                                }

                                            }
                                            if (ActulaColINdex <= 11 && ActulaColINdex >= 7) //Adverse
                                            {
                                                if (ActulaColINdex == 9)
                                                {
                                                    g2.setXxcelmodel(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 10)
                                                {
                                                    g2.setDiff(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 11)
                                                {
                                                    g2.setDiffper(cell.getNumericCellValue());
                                                    Adversemap.add(g2);
                                                }

                                            }
                                            if (ActulaColINdex <= 17 && ActulaColINdex >= 13) //SeverlyAdverse
                                            {
                                                if (ActulaColINdex == 15)
                                                {
                                                    g3.setXxcelmodel(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 16)
                                                {
                                                    g3.setDiff(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 17)
                                                {
                                                    g3.setDiffper(cell.getNumericCellValue());
                                                    SeverelyAdversemap.add(g3);
                                                }
                                                ActulaColINdex++;
                                            }
                                            if (ActulaColINdex <= 23 && ActulaColINdex >= 19)//BHC Base
                                            {
                                                if (ActulaColINdex == 21)
                                                {
                                                    g4.setXxcelmodel(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 22)
                                                {
                                                    g4.setDiff(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 23)
                                                {
                                                    g4.setDiffper(cell.getNumericCellValue());
                                                    BHCBasemap.add(g4);
                                                }

                                            }
                                            if (ActulaColINdex <= 30 && ActulaColINdex >= 26)//BHC Severly Adverse
                                            {
                                                if (ActulaColINdex == 28)
                                                {
                                                    g5.setXxcelmodel(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 29)
                                                {
                                                    g5.setDiff(cell.getNumericCellValue());
                                                }
                                                if (ActulaColINdex == 30)
                                                {
                                                    g5.setDiffper(cell.getNumericCellValue());
                                                    BHCSeverelyAdversemap.add(g5);
                                                }

                                            }
                                        }
                                        break;
                                    }
                                } else
                                {
                                    //U Can Handel Boolean, Formula, Errors
                                }
                            }
                            System.out.println();
                        }
                        wb.close();
                        fs.close();
                        System.out.println("-----------------------Base----------------------");
                        Class.forName("com.mysql.jdbc.Driver");
                        Connection con;
                        con = getConnection();
                        Statement st = con.createStatement();
                        String sql1 = "delete from outputtable where modelid=" + modelid;
                        int flag1 = st.executeUpdate(sql1);

                        for (int i = 0; i < Basemap.size(); i++)
                        {
                            graphdata g = (graphdata) Basemap.get(i);
                            String sql = "INSERT INTO outputtable (VolumeName,ModelName,year,sasmodel,excelmodel,diff,diffper,modelid)"
                                    + " VALUES ('" + g.getVolumeName() + "','" + g.getModelName() + "','" + g.getYear() + "', " + g.getSasmodel() + ", " + g.getXxcelmodel() + ", " + g.getDiff() + ", " + g.getDiffper() + ", " + modelid + ")";
                            st.executeUpdate(sql);
                            System.out.println(g.getVolumeName() + "" + g.getYear() + "" + g.getModelName() + "" + g.getSasmodel() + "" + g.getXxcelmodel());
                        }
                        System.out.println("-----------------------Advrse----------------------");
                        for (int i = 0; i < Adversemap.size(); i++)
                        {
                            graphdata g = (graphdata) Adversemap.get(i);
                            String sql = "INSERT INTO outputtable (`outputtable`.`VolumeName`,`outputtable`.`ModelName`,`outputtable`.`year`,`outputtable`.`sasmodel`,`outputtable`.`excelmodel`,`outputtable`.`diff`,`outputtable`.`diffper`,`outputtable`.`modelid`)"
                                    + " VALUES ('" + g.getVolumeName() + "','" + g.getModelName() + "','" + g.getYear() + "', " + g.getSasmodel() + ", " + g.getXxcelmodel() + ", " + g.getDiff() + ", " + g.getDiffper() + ", " + modelid + ")";
                            st.executeUpdate(sql);
                            System.out.println(g.getVolumeName() + "" + g.getYear() + "" + g.getModelName() + "" + g.getSasmodel() + "" + g.getXxcelmodel());
                        }
                        System.out.println("-----------------------Severly Advers----------------------");
                        for (int i = 0; i < SeverelyAdversemap.size(); i++)
                        {
                            graphdata g = (graphdata) SeverelyAdversemap.get(i);
                            String sql = "INSERT INTO outputtable (`outputtable`.`VolumeName`,`outputtable`.`ModelName`,`outputtable`.`year`,`outputtable`.`sasmodel`,`outputtable`.`excelmodel`,`outputtable`.`diff`,`outputtable`.`diffper`,`outputtable`.`modelid`)"
                                    + " VALUES ('" + g.getVolumeName() + "','" + g.getModelName() + "','" + g.getYear() + "', " + g.getSasmodel() + ", " + g.getXxcelmodel() + ", " + g.getDiff() + ", " + g.getDiffper() + ", " + modelid + ")";
                            st.executeUpdate(sql);
                            System.out.println(g.getVolumeName() + "" + g.getYear() + "" + g.getModelName() + "" + g.getSasmodel() + "" + g.getXxcelmodel());
                        }
                        System.out.println("-----------------------BHC Base----------------------");
                        for (int i = 0; i < BHCBasemap.size(); i++)
                        {
                            graphdata g = (graphdata) BHCBasemap.get(i);
                            String sql = "INSERT INTO outputtable (`outputtable`.`VolumeName`,`outputtable`.`ModelName`,`outputtable`.`year`,`outputtable`.`sasmodel`,`outputtable`.`excelmodel`,`outputtable`.`diff`,`outputtable`.`diffper`,`outputtable`.`modelid`)"
                                    + " VALUES ('" + g.getVolumeName() + "','" + g.getModelName() + "','" + g.getYear() + "', " + g.getSasmodel() + ", " + g.getXxcelmodel() + ", " + g.getDiff() + ", " + g.getDiffper() + ", " + modelid + ")";
                            st.executeUpdate(sql);
                            System.out.println(g.getVolumeName() + "" + g.getYear() + "" + g.getModelName() + "" + g.getSasmodel() + "" + g.getXxcelmodel());
                        }
                        System.out.println("-----------------------BHC Severly Adve----------------------");
                        for (int i = 0; i < BHCSeverelyAdversemap.size(); i++)
                        {
                            graphdata g = (graphdata) BHCSeverelyAdversemap.get(i);
                            String sql = "INSERT INTO outputtable (`outputtable`.`VolumeName`,`outputtable`.`ModelName`,`outputtable`.`year`,`outputtable`.`sasmodel`,`outputtable`.`excelmodel`,`outputtable`.`diff`,`outputtable`.`diffper`,`outputtable`.`modelid`)"
                                    + " VALUES ('" + g.getVolumeName() + "','" + g.getModelName() + "','" + g.getYear() + "', " + g.getSasmodel() + ", " + g.getXxcelmodel() + ", " + g.getDiff() + ", " + g.getDiffper() + ", " + modelid + ")";
                            st.executeUpdate(sql);
                            System.out.println(g.getVolumeName() + "" + g.getYear() + "" + g.getModelName() + "" + g.getSasmodel() + "" + g.getXxcelmodel());
                        }
                    } catch (Exception e)
                    {
                        return Response.status(401)
                                .header("Access-Control-Allow-Origin", "*")
                                .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
                                .header("Access-Control-Allow-Credentials", "true")
                                .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
                                .header("Access-Control-Max-Age", "1209600")
                                .entity("[{\"Success\":\"Error\"}]")
                                .build();
                    }
                    return Response.status(200)
                            .header("Access-Control-Allow-Origin", "*")
                            .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
                            .header("Access-Control-Allow-Credentials", "true")
                            .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
                            .header("Access-Control-Max-Age", "1209600")
                            .entity("[{\"Success\":\"Yes\"}]")
                            .build();
                }

Problem is :- While reading second sheet using apache poi in java, it read previous data not the updated data after calculation.even if Model.xlsx contain updated data java reads only previous data.This is very strange find me any solution.
Kindly please assist me.
Thanks.

A: If you want to use Aspose.Cells for Java to implement your solution, then following articles will be helpful for you.

*

*http://www.aspose.com/docs/display/cellsjava/Copying+and+Moving+Worksheets

*http://www.aspose.com/docs/display/cellsjava/Combine+Multiple+Workbooks+into+a+Single+Workbook

*http://www.aspose.com/docs/display/cellsjava/Combine+Multiple+Worksheets+into+a+Single+Worksheet

*http://www.aspose.com/docs/display/cellsjava/Accessing+Cells+of+a+Worksheet

*http://www.aspose.com/docs/display/cellsjava/Adding+Data+to+Cells

*http://www.aspose.com/docs/display/cellsjava/Retrieving+Data+from+Cells

*http://www.aspose.com/docs/display/cellsjava/Importing+Data+to+Worksheets

*http://www.aspose.com/docs/display/cellsjava/Exporting+Data+from+Worksheets
Note: I am working as Developer Evangelist at Aspose


text:
Q: Reduce splash image time IOS Is it possible to reduce standard time (3 seconds) of the default.png image for splash image?
My intention is to set it to 1.5 seconds.

A: 1) Defer all processing until the first view has received viewDidAppear.
2) Reduce the number of libraries and frameworks you link to, since the loader takes time at launch.
3) Watch the WWDC 2012 session videos. This topic was covered in depth at one of the Instruments talks (I was in audience). If nothing else the session will show you how to accurately monitor what is going on during launch.

A: There is no "standard time". The time it is shown is the time until your applicationDidFinishLaunching completes.
If you want it to display for less, optimise or offset some loading of that method.

A: There's no standard time for displaying splash screen - it disappears as soon as your application finishes loading and is ready to present its first screen.
To reduce that time you need to optimize loading time of your application (e.g. move some heavy calculation/resource loading to background thread, use lazy-loading etc)

A: The splashscreen displays during applicationDidFinishLaunching is executed. Try to initialize your app in a background method called from applicationDidFinishLaunching, like :
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(initApplication:) userInfo:nil repeats:NO];
    return YES;
}

-(void)initApplication {
    ...
}

But you may have some black screen before the app graphic initialization!

A: Just to weigh in here, if you're initializing a bunch of view controllers for a UITabBarController, for example, it's advisable to defer any heavy initialization of these view controller to viewDidLoad: instead of their init: methods. This way, anything that needs to be allocated and initialized in memory isn't loaded until the view controller is needed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Project management: SharePoint vs activeCollab I'm trying to choose a project management and collaboration software for our next project and would like to know your opinion on "enterprisey" SharePoint vs. "lightweight" alternatives like BaseCamp or activeCollab (from the two, I would prefer the latter).
Features that are important to us:

*

*document sharing (specifications, manuals etc.)

*discussion forums (I hate when important information is lost in the inbox)

*issue tracking

*Subversion integration would be nice to have but probably neither SharePoint, nor activeCollab currently support it, do they?

Other things like time tracking are less important to us (although nice to have).
When I compare the two solutions, I see these strong points and drawbacks:

*

*Killer feature of SharePoint is Office integration. For instance, specification is much better authored in MS Word with styles, image drag&drop etc. compared to a plain HTML textarea and some plain text format. We also use Outlook quite extensively so it would be good if we could leverage this tool.

*activeCollab is web based and has a slick user interface which is important for adoption in our company (if our devs don't find the solution easy to work with, they will not use it). My boss also kind of likes easy solutions and activeCollab wins easily in this area.

Regarding price, activeCollab is something like few hundreds dollars (reasonable one time cost) but I'm not too sure about SharePoint. If I'm right, the basic "SharePoint Services" version would be enough for us (I don't think we need the full MS Office SharePoint Server) and in that case, we need only Windows Server licence (which we already) and a SQL Server licence (would SQL Server Express work? or do we need at least workgroup edition?). This means that even SharePoint doesn't need to be too expensive if we go for the lowest edition.
Is there anyone who did the same comparison and could possibly provide more insight?

A: SharePoint services can be used with SQL Express. For full text search support, do not forget to download SP2 with advanced features : http://msdn.microsoft.com/vstudio/express/sql/download/ .
So If you have a 2003 server licence, you're all set.
Currently, we manage a few projects using WSS V3. It's going quite well, we've implemented issue tracking with a custom list, and document sharing is very efficient (it's the base of WSS).

A: If you went with SharePoint, you would only need the base, Windows SharePoint Services, not Microsoft Office SharePoint Services. Between that, plus the fact that Microsoft Office SharePoint Designer is now free, you should do fine.
You will need to add an issue tracking system, though you could start with the built-in issue tracking list, and then customize it. In particular, it's fairly simple to add workflow to any list, and SharePoint workflows are based on Windows Workflow Foundation, meaning that you should be able to integrate with anything. You might do the same for your subversion integration.

A: Opengoo has all of the features you mention -except subverion integration, but including time tracking.
I see it as something in between basecamp and sharepoint. The only thing for which may be weaker is in office integration, thou I think fengoffice offers an office plugin.
Someone did a comparison of opengoo vs activecollab. I'll post it here when I find it.
edit:
Here is the link:
http://forums.opengoo.org/index.php?topic=617.0

A: ActiveCollab now has Subversion integration

A: i know this post is old, but i currently use both basecamp and activecollab. i handled the install of AC as well and it was about as painless as it gets.
managing it has been a breeze, and yes there is subversion integration.
as a temporary measure, i put fedora on n intel-based mac mini, and installed activeCollab and it runs great (yes, i do offsite database and file backups).

A: More people here are familiar with SharePoint, so let me provide answers from activeCollab perspective:
Document sharing and collaborative work on files is mainly on project level, done through Files section. There's also Global Documents section, but it's limited in functionality because it's made for sharing only and lacks collaborative features (no comments, revision tracking etc).
Files section features support for good old binary files (can't be edited in activeCollab itself, but you can download them, update them and upload new version), text documents (HTML documents that can be edited from within activeCollab's main interface), bookmarks and YouTube videos. New asset types can be added via third party modules.
Discussions: activeCollab is good at this because it's build to enable collaboration. Each project has a Discussions section (a mini forum), and most elements in the system (files, tasks etc) support comments which makes them discussion points as well.
Killer feature is activeCollab's email integration, that lets you  start discussions with email and reply to email notifications and have these replies imported in the system as comments. We found that this greatly increases adoption rate of the application because people can continue to use tools that they are familiar with (email) instead of the need to fully switch to something new.
More info about email integration can be found here: http://www.activecollab.com/features.html#email
Issue Tracking: You can use built in Tasks feature for this, but note that it's not built for issue tracking in particular - it's a general task management implementation. Dedicated issue tracking tools like FogBugz, Bugzilla etc offer more specialized features, but you may find activeCollab's implementation sufficient for your needs.
Version Control Integration: activeCollab 2 had SVN support, activeCollab 3 adds GIT and HG support as well.
Office Integration: We have something in works that will let you work in Office application, and have your changes automatically stored in activeCollab. Since this is work in progress, I can't share any details, but I'll update this comment as soon as that tool becomes available.
Disclaimer: I'm original author of activeCollab. This is reply to an unanswered activeCollab related question, not a sales pitch :)


text:
Q: Why does dispatch_queue_create give an EXC_BAD_ACCESS error in Swift? I am porting some code from C++ to Swift that used Grand Central Dispatch, and I am finding a curious error with dispatch_queue_create seemingly not working at all.
For instance, in my C++ base class header, I would declare
dispatch_queue_t m_WorkQ;

and in the initializer, put
m_ResultQ = dispatch_queue_create("com.myapp.mHitsUpdateQueue", 0);

... and everything was glorious.

I've tried this in Swift, in my class, declaring this at class level:
var resultQueue: dispatch_queue_t

... and in the initalizer, I have (among others) the line
resultQueue = dispatch_queue_create("com.myapp.mHitsUpdateQueue", 0)

... and it compiles and starts up fine, but gives me an immediate runtime error of EXC_BAD_ACCESS (code=1, address = 0x37) on the above line
To determine if it's anything else I've done, I created a command line tool application consisting only of the following code:
import Foundation

var thisQueue = dispatch_queue_create("com.myApp.mHitsUpdateQueue", 0)

println(thisQueue.description)

... and sure enough, I get the above error right on the "thisQueue" assignment line.  So I'm pretty sure there's something really obvious about Swift and GCD queue creation that I'm missing.
Can anyone please help me out here?

A: The second argument of dispatch_queue_create() has the type
dispatch_queue_attr_t, which is declared as
typealias dispatch_queue_attr_t = NSObject

You have to pass DISPATCH_QUEUE_SERIAL or nil for a serial queue
(or DISPATCH_QUEUE_CONCURRENT for a concurrent queue):
var thisQueue = dispatch_queue_create("com.myApp.mHitsUpdateQueue", DISPATCH_QUEUE_SERIAL)

In C(++), 0 can be passed instead of a NULL pointer.
The Swift compiler, however, wraps the integer 0 into an NSNumber object
so that it can be passed to the function expecting an NSObject
parameter. That causes the runtime exception because NSNumber is
not a valid attribute. So passing 0 or nil is
significantly different in Swift.


text:
Q: auto-Writing/auto-Inputting application for a lousy routine web-based submitions? I've started learning python for a week, as always love to learn as much languages as I can ; as python is one of the easiest languages, but still there's lots of things teachers won't tell.
Interacting with web pages is an obvious example; registration in forums and other websites gives a headache, so building a simple python application that just can READ LABELS, and input INFORMATION such as First Name, Last Name, Sex, and Address in their TEXT BOXES, then Submit the page at the end would be fantastic.
Another silly thing, but I MUST know, is how to contact a website first.
If you can provide me with any tips, or help, I appreciate your contribution.

A: For a simply contacting the website, consider the requests or twill libraries.  For screen-scraping, BeautifulSoup is your friend.
If third-party libraries really aren't an option, though, you'll need to delve into the htmllib, httplib, urllib, and urllib2 Python modules.


text:
Q: Rendering UIs / Generating GSPs directly from pencil or balsamiq wireframes Are there any existing tools/combination-of-tools I can use so that my wireframes built using pencil or balsamiq can be directly used by my application (grails) for rendering the UI? Or maybe a way to generate GSP's out of my wireframes (assuming there is a set style guide etc.)? I am essentially looking to do away with having to code the HTML/GSP for each and every page.

A: Napkee is a commercial solution. I don't know any completely free one, though


text:
Q: Xamarin Studio (on OSX) or Visual Studio ( on Windows)? I've a Mac ( with Windows in BootCamp ).
Now I am using Android Studio for Android dev. and XCode for iOS dev. both in OSX.
I'd like to get started with Xamarin development.
What are the most important differences between Xamarin Studio and Visual Studio?
How should I decide which IDE to choose?

A: Visual Studio is probably your best IDE for .Net development in general, plus you have the ability to install 3rd party extensions such as Resharper that can boost productivity and code quality in general.
Choosing Xamarin Studio on Mac would allow you to open your storyboard in Xcode  and edit it, run your app on iOS Simulators which you wouldn't be able to do on Windows. ( you could build your iOS app from Visual Studio using a remote mac: link)
Personally I prefer to develop on Mac with Xamarin Studio.

A: I'm not sure if your question isn't out of place on this site. At any rate, Visual Studio and Xamarin Studio can hardly be compared. The former one is a full-fledged, mature juggernaut of an IDE. Unsurprisingly, a bit of a resource hog along with it, still one of the best IDEs in the world.
I used Xamarin Studio on OSX for about a month (just last March). My experience was abysmal. I mean no disrespect for its creators, but I found it:

*

*extremely unstable (crashing a lot),

*with lots of irritating visual quirks (eg. the drop-down filenames list for file search popping up beyond the screen edge in full-screen mode, or the text cursor going missing),

*user-unfriendly (for instance the ridiculous exception details dialog, in which you need to click your way deep into the inheritance tree only to see the actual exception message)

*and far behind Visual Studio in terms of pretty much every functionality I could think of, starting with poor refactoring capabilities.
With latest acquisition, I'd expect things to turn around, but Xamarin Studio isn't there yet. I recommend Visual Studio.


text:
Q: Stopping the timeline sound on a loaded swf I'm working on a as3 player which loads swf like videos/chapters, inside them I have images and a level where a sound starts to play at frame 1.
I'm trying to stopping the sound of the loaded swf when I change it with a previous or later loaded file but nothing seem to work.
I've tried this:
loaded_swf.stop();
SoundMixer.stopAll();
media_container.removeChild(loaded_swf);

I've tried also this:
loaded_swf.stop();
var snd_transform:SoundTransform = SoundMixer.soundTransform;
snd_transform.volume = 0;
SoundMixer.soundTransform = snd_transform;
SoundMixer.stopAll();
media_container.removeChild(loaded_swf);

And this:
loaded_swf.stop();
var snd_transform:SoundTransform = loaded_swf.soundTransform;
snd_transform.volume = 0;
swf.soundTransform = snd_transform;
SoundMixer.stopAll();
media_container.removeChild(loaded_swf);

the timeline sound works without notice the SoundMixer method.
Does exists some way to fix this problem?

A: Here's a little recursive function that will silence all of the audio in a movieclip. If you're using timeline sounds, this should shut them up.
public function stopAllSounds(mc:MovieClip):void
{
    var mute:SoundTransform = new SoundTransform(0.0);
    mc.soundTransform = mute;

    for (var i:int = 0; i < mc.numChildren; ++i)
    {
        var m:DisplayObject = mc.getChildAt(i);
        if(m is MovieClip) stopAllSounds(m);
    }
}

A: Editing James' answer to make sure really everything is stopped (not just MovieClips):
public function stopAllSounds(sp:Sprite):void
{
    var mute:SoundTransform = new SoundTransform(0.0);
    sp.soundTransform = mute;

    var mc : MovieClip = sp as MovieClip;
    if(mc != null)
    {
        for (var i:int = 0; i < mc.numChildren; ++i)
        {
            var m:DisplayObject = mc.getChildAt(i);
            if(m != null) stopAllSounds(m);
        }
    }
}


text:
Q: Show delete button if expire date id greater than current date in laravel Yajra table I am using a Yajra table to retrieve data from a DB. At the moment I have a view button on the table to view data . On this I have to show a label to view records that are already expired.
This is my code
:
return DataTables::of($result)
      ->addIndexColumn()
      ->addColumn('action', function ($result) {
        return 'id . '" data-ref="' . $result->mbl_number . '" class="btn btn-xs btn-primary view_bl" data-toggle="tooltip" data-placement="bottom" title="View">';
      })
      ->addColumn('do-expire', function ($result) {
        if($result->do_expiry_date == "Expired"){
          return 'EXPIRED';
        }else{

        }
     })
      ->rawColumns(['action', 'do-expire'])
      ->make(true);

In this I should show EXPIRED label only if do_expiry_date > current_date. I am not sure if I'm doing this the right way since I'm new to Yajra table.
If anyone can help me to achieve this much appreciated.


text:
Q: Is Expandable ListView Expanded? What is the code for checking if the Expandable ListView is in the expanded state? Does any method exist that gives a true or false value depending upon the opened or closed state of an Expandable ListView.
This may seem like an easy question, but I've searched many places and could not find an answer.

A: On the android documentation it says isGroupExpanded(int groupPosition) http://developer.android.com/reference/android/widget/ExpandableListView.html
It looks as though each row can be expanded and these are know as groups. Therefore, can only find out if any one group is expanded. To know if all are you would need to loop through each and run this function.


text:
Q: How to create a phase plot for a 2D array of complex numbers with matplotlib? Is there any good way how to plot 2D array of complex numbers as image in mathplotlib ?
It makes very much sense to map magnitude of complex number as "brightness" or "saturation" and phase as "Hue" ( anyway Hue is nothing else than phase in RBG color space).
http://en.wikipedia.org/wiki/HSL_and_HSV
But as far as I know imshow does accept only scalar values which are then mapped using some colorscale. There is nothing like ploting real RGB pictures?
I thing it would be easy just implement a version which accepts 2D array of tuples (vectors) of 3 floating point numbers or ndarray of floats of shape [:,:,3]. I guess this would be generally usefful feature. It would be also usefull for plotting real RGB colord images, such as textures outputted from OpenCL

A: The library mpmath uses matplotlib to produce beautiful images of the complex plane. On the complex plane you usually care about the poles, so the argument of the function gives the color (hence poles will make a spiral). Regions of extremely large or small values are controlled by the saturation. From the docs:

By default, the complex argument (phase) is shown as color (hue) and
      the magnitude is show as brightness. You can also supply a
      custom color function (color). This function should take a
      complex number as input and return an RGB 3-tuple containing
      floats in the range 0.0-1.0.

Example:
import mpmath
mpmath.cplot(mpmath.gamma, points=100000)

Another example showing the zeta function, the trivial zeros and the critical strip:
import mpmath
mpmath.cplot(mpmath.zeta, [-45,5],[-25,25], points=100000)

A: You can use matplotlib.colors.hsv_to_rgb instead of colorsys.hls_to_rgb. The matplotlib function is about 10 times faster! See the results below:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import hsv_to_rgb
import time

def Complex2HSV(z, rmin, rmax, hue_start=90):
    # get amplidude of z and limit to [rmin, rmax]
    amp = np.abs(z)
    amp = np.where(amp < rmin, rmin, amp)
    amp = np.where(amp > rmax, rmax, amp)
    ph = np.angle(z, deg=1) + hue_start
    # HSV are values in range [0,1]
    h = (ph % 360) / 360
    s = 0.85 * np.ones_like(h)
    v = (amp -rmin) / (rmax - rmin)
    return hsv_to_rgb(np.dstack((h,s,v)))

here is the method of picked answer by @nadapez:
from colorsys import hls_to_rgb
def colorize(z):
    r = np.abs(z)
    arg = np.angle(z)

    h = (arg + np.pi)  / (2 * np.pi) + 0.5
    l = 1.0 - 1.0/(1.0 + r**0.3)
    s = 0.8

    c = np.vectorize(hls_to_rgb) (h,l,s) # --> tuple
    c = np.array(c)  # -->  array of (3,n,m) shape, but need (n,m,3)
    c = c.swapaxes(0,2)
    return c

Testing the results from the two method with 1024*1024 2darray:
N=1024
x, y = np.ogrid[-4:4:N*1j, -4:4:N*1j]
z = x + 1j*y

t0 = time.time()
img = Complex2HSV(z, 0, 4)
t1 = time.time()
print "Complex2HSV method: "+ str (t1 - t0) +" s"

t0 = time.time()
img = colorize(z)
t1 = time.time()
print "colorize method: "+ str (t1 - t0) +" s"

This result on my old laptop:
Complex2HSV method: 0.250999927521 s
colorize method: 2.03200006485 s

A: Adapting the plotting code from mpmath you can plot a numpy array even if you don't known the original function with numpy and matplotlib. If you do know the function, see my original answer using mpmath.cplot.
from colorsys import hls_to_rgb

def colorize(z):
    n,m = z.shape
    c = np.zeros((n,m,3))
    c[np.isinf(z)] = (1.0, 1.0, 1.0)
    c[np.isnan(z)] = (0.5, 0.5, 0.5)

    idx = ~(np.isinf(z) + np.isnan(z))
    A = (np.angle(z[idx]) + np.pi) / (2*np.pi)
    A = (A + 0.5) % 1.0
    B = 1.0 - 1.0/(1.0+abs(z[idx])**0.3)
    c[idx] = [hls_to_rgb(a, b, 0.8) for a,b in zip(A,B)]
    return c

From here, you can plot an arbitrary complex numpy array:
N = 1000
A = np.zeros((N,N),dtype='complex')
axis_x = np.linspace(-5,5,N)
axis_y = np.linspace(-5,5,N)
X,Y = np.meshgrid(axis_x,axis_y)
Z = X + Y*1j

A = 1/(Z+1j)**2 + 1/(Z-2)**2

# Plot the array "A" using colorize
import pylab as plt
plt.imshow(colorize(A), interpolation='none',extent=(-5,5,-5,5))
plt.show()

A: this does almost the same of @Hooked code but very much faster.
import numpy as np
from numpy import pi
import pylab as plt
from colorsys import hls_to_rgb

def colorize(z):
    r = np.abs(z)
    arg = np.angle(z)

    h = (arg + pi)  / (2 * pi) + 0.5
    l = 1.0 - 1.0/(1.0 + r**0.3)
    s = 0.8

    c = np.vectorize(hls_to_rgb) (h,l,s) # --> tuple
    c = np.array(c)  # -->  array of (3,n,m) shape, but need (n,m,3)
    c = c.swapaxes(0,2)
    return c

N=1000
x,y = np.ogrid[-5:5:N*1j, -5:5:N*1j]
z = x + 1j*y

w = 1/(z+1j)**2 + 1/(z-2)**2
img = colorize(w)
plt.imshow(img)
plt.show()

A: You can also use PIL.image to convert it
import PIL.Image

def colorize(z):
  z = Zxx
  n,m = z.shape

  A = (np.angle(z) + np.pi) / (2*np.pi)
  A = (A + 0.5) % 1.0 * 255
  B = 1.0 - 1.0/(1.0+abs(z)**0.3)
  B = abs(z)/ z.max() * 255
  H = np.ones_like(B)
  image = PIL.Image.fromarray(np.stack((A, B, np.full_like(A, 255)), axis=-1).astype(np.uint8), "HSV") # HSV has range 0..255 for all channels
  image = image.convert(mode="RGB")

  return np.array(image)


text:
Q: MetadataExtractor File format could not be determined I'm using metadataExtractor (v.2.7.1) in .Net Core (3.0.1) to get the date of the photos.
  var file = Request.Form.Files[0];
  try
  {
      IEnumerable<MetadataExtractor.Directory> directories = ImageMetadataReader.ReadMetadata(file.OpenReadStream());
  ....
  }

And I get sometimes this exception on this line "File format could not be determined"
Any idea what is wrong? This photo seems to be correct and having the exif metadata I need.
The code is working for other photos.
Thank you in advance

A: The problem was that this photo was larger than the other one and was uploaded in chunck. I was trying to get EXIF from each chunk, which is not possible...


text:
Q: Facing issue while redirecting to page in serveResource: liferay I am facing issue while redirecting to another page in serveResource method.
I got following exception
java.lang.IllegalStateException: Config is null, please ensure that your init(config) method calls super.init(config)

Following is my serveResource method
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws PortletException {

        System.out.println("Serve Resource Method Called");

        try {

            String url = getURL(Long.valueOf(resourceRequest.getParameter("key")));
            resourceRequest.setAttribute("url", conn.getURL().toString());
        include("/html/viewImage.jsp", resourceRequest, resourceResponse);
} catch (Exception e) {

            e.printStackTrace();
        }
    }

How to solve this problem?
Thanks

A: According to your comment you're calling serveResource from a different portlet. You're not supposed to do that.
If you share an implementation between different portlets, separate it out into a common component. You have no business in calling lifecycle methods yourself. Further, you probably are instantiating that portlet class yourself (otherwise there'd be no object to call serveResource on), which will probably not call init() at all - and here we are again: It's the portal's business to call lifecycle functions, not yours.

A: If we talk about jsp-servlet , we can switch from one jsp to another by two way only.
1) SendRedirect
2) Forward page
If we talk about pure servlet then for forwarding page would be like as below:
RequestDispatcher dispatcher = request.getRequestDispatcher("/template.jsp");
if (dispatcher != null) dispatcher.forward(request, response);

Now in order to answer of your question.
Portlet JSR 286 has created one interface for portlets on top of the RequestDisptcher, which will generate dispatcher reference.
below code has meaning as above describe.
PortletRequestDispatcher dispatcher = resourceRequest.getPortletSession().getPortletContext().getRequestDispatcher("/html/viewImage.jsp");
dispatcher.forward(resourceRequest, resourceResponse);

reference
HTH!
Thanks.


text:
Q: entt basic_registry::get<>() explanation Currently using g++11.3.0, C++20.
Could anyone explain how the basic_registry's get<>() template function is able to function such that when retrieving a single component through a call like auto& comp {registry.get<A>()};, the component itself can be directly assigned to and/or accessed like a normal reference, and when retrieving multiple components through a call like registry.get<A, B, C>(), it can be unpacked via a structured binding auto& [a, b, c].
Code (from https://skypjack.github.io/entt/registry_8hpp_source.html)
template<typename... Type>
[[nodiscard]] decltype(auto) get([[maybe_unused]] const entity_type entt) {
    if constexpr(sizeof...(Type) == 1u) {
        return (const_cast<Type &>(std::as_const(*this).template get<Type>(entt)), ...);
    } else {
        return std::forward_as_tuple(get<Type>(entt)...);
    }
}

A: The following function template returns a tuple:
template <typename ...T>
auto foo() {
    return std::make_tuple(T{}...);
}

You can call it via
auto [a, b, c] = foo<int,int,double>();

The following function template returns just a T:
template <typename T>
auto bar() { return T{};}

you can call it via
auto d{bar<int>()};

Functions can have only one return type. foo and bar are function templates. The functions foo<int,int,double> and bar<int> have one return type. They return one value.

The following function template selects between two function templates to be instantiated and called depending on the number of template arguments:
template <typename ...T>
auto moo() {
    if constexpr(sizeof...(T) == 1u) { return bar<T...>(); }
    else return foo<T...>();
}

You can call it via:
auto [x,y,z] = moo<int,int,double>();

Or
auto w{ moo<int>()};

Note that when T... is more than a single argument then bar<T...> would be a mismatch (because bar has only a single argument. However, with constexpr if in template context the not taken branch is discarded at compile time.

In the case of sizeof...(T) == 1u the parameter pack is expanded. However, the expansion is only a single type in this case (otherwise bar<T...> would not compile). It could have been written as
template <typename T,typename ...More>
auto moo() {
    if constexpr(sizeof...(More) == 0u) { return bar<T>(); }
    else return foo<T,More...>();
}

Live Demo


text:
Q: can Nativescript run at browser? I was working with Ionic but decided to move to Nativescript for not webView , but is there any way to work with browser as the ionic do (ionic serve ) for developing its much faster without running on android or emulator.Also, I heard some news that ionic tries to move that webView to phones engine as nativescript does, is that true ?

A: No, unfortunately there's no way right now to run Nativescript code at a browser. And Ionic doesn't generate native elements, if this is what you are asking!


text:
Q: How to change when packages are excecuted I have a package A in Go that looks like
package A

var Something int

func Do_something() {

    Something = 100

}

where do_something in package A is called in main.go
package main

import "example.com/this_project/A"

func main() {

    A.Do_something()

}

That works well, but now I add package B.
package B

import (
    "example.com/this_project/A"
    "fmt"
    "strconv"
)

_ = do_something_else()

func do_something_else() {

    fmt.Println("%s is the value of something", strconv.Itoa(A.Something))

}

func Some_other_function() {

    do_whatever()

}

Some_other_function will also get called in main.go
package main

import "example.com/this_project/A"
import "example.com/this_project/B"

func main() {

    A.Do_something()
    B.Some_other_function()

}

When I run this program, I expect it to output
100

But instead, it outputs
0

I think this means that package B is running before main.go, so I tried using time.sleep, but it just caused the entire project to stop. Any suggestions will be appreciated.

A: All global variables are initialized before main starts running. Because of that, this line:
_ = do_something_else()

will run before main starts, which will print the current value of the variable, which is 0 at that point.


text:
Q: How to run Ansible playbook with user input within Jenkins? I have a playbook with section "pause" and prompt. If I create job within Jenkins with Pipeline plugin and run this job I get
[WARNING]: Not waiting from prompt as stdin is not interactive

and job is failed. The question is how I can run job in interactive mode or how I can pause playbook within exact task and push combination Ctrl+c+c (because ansible module 'pause' is working only like that)? I have googled a few time and tried to do that with
def userInput = input(
    id: 'Password', message: 'input your input: ', ok: 'ok',
    parameters: [string(defaultValue: '', description: '.....', name: 'INPUT_TEST')])

But I can't push keys combination and can't understand how I can pause jenkins job on specific ansible task within playbook.
Pipeline example:
pipeline {
agent { label 'master' }
  environment {
  WORKDIR = '/home/jenkins/'
  }
  stages {

  stage('Checkout') {
    agent { label 'master' }
    steps {
      sh '''cd $WORKDIR
      ansible-playbook -vvvv manual_playbooks/test.yml'''
      }
    }

  stage ('Echo') {
     agent { label 'master' }
     steps {
        sh 'echo something'
     }
  }
  }
}

Playbook example:
---
- name: test
  hosts: localhost
  tasks:

    - name: Echo start
      shell: echo 'start playbook'

    - pause:
        prompt: "do you want to continue?"
        echo: yes
        private: no
      register: prompt_status

    - name: Continue tasks
      shell: echo 'Continue full flow'
      register: reset_account_response
      when: prompt_status.user_input is defined and
            prompt_status.user_input == "yes"

    - fail:
        msg: "Unexpected user input while prompting approval"
      when: prompt_status.user_input is defined and
            prompt_status.user_input != "yes"

Many thanks.

A: Why not put a when clause on your pause task to check for the existence of some other variable and then pass that in using Ansible's -e option when running the playbook through Jenkins.


text:
Q: Edit files in server using text editor I was wondering, is there a way I can edit files inside a live linux server using a text editor? I am able to edit using the nano command but that is not very friendly. Can I achieve the same using an editor.

A: vi is an editor. If you mean graphical editor, then it depends. At first glimpse, you have two options: A) Open the file using some file share (nfs, samba, ftp?) on your client computer using your favourite editor, or B) Use some ssh client which is capable of "tunneling" an X connection (putty?) and use an editor running on the server machine, displaying GUI on your client (which acts as an X host).

A: You can install a better editor, like vim or emacs on your Linux server.
You could also install X-client editors like gedit (and many others) and use ssh -X to access your server. You need some X11 server in front of you (on your laptop).


text:
Q: Change focus to parent element using NightwatchJS It is possible to move deeper into the DOM tree using the .frame JSON Wire Protocol call but I haven't been able to figure out a way to move upward through the DOM tree.
    module.exports = {
        "Enter and exit iframes in tree" : function(browser){
            browser
                //Currently focus is at top level.
                .frame('iframeOne')
                //Focus is now enters inner frame iframeTwo
                .frame('iframeTwo')

                //Attempt to move to frame directly
                .frame('iframeOne')
                //Selenium Error 'no such frame'

                //Attempt to move focus up to iframeOne by searching from root.
                .element('id', 'iframeOne', function(e){
                    browser.frame(e.value);
                }
                //Selenium Error 'no such element'

    }

There is a JSON Wire Protocol call frame/parent that is able to move up to the parent element but it is not currently supported by NightWatchJS. Any suggestions would be appreciated.

A: In current binary releases, you need to use the switchToDefaultContent command. In Java this manifests itself as driver.switchTo().defaultContent(). This will take you to the top of the frame hierarchy, and you can navigate back down the tree to the frame you need.
The "navigate to parent frame" wire protocol is brand new. On the order of days, at the time of this writing. No released server implementation at the time of this writing exists that understands that wire protocol endpoint. The Firefox driver has had it implemented only in the last day or so. Work hasn't started yet on the IE driver. It's not yet implemented in any language binding except Java, and that's only in the source tree; it hasn't been released in a binary form yet. If you're patient, it will be available to you in the future (no available timeline so don't ask), just not yet.

A: I was able to get around this problem by resetting the focus back up to the top level element and crawling down again.
    .frame(null)
    .frame('iframeOne')

It's a workable solution.


text:
Q: WCF Service and Interface - the result is object, even though ServiceKnownType was used I need to convert some objects that are not compatible with Silverlight to models to send over a WCF service. I've tried using the ServiceKnownType, but the result is still object. I am able to cast the object to the Model after I retreive the result, but I don't want to have to do that every time. Here is an example of what I have attempted.
Is this a good approach? Why doesn't WCF return a BikeModel as an object.
Interface
public interface IBike
{
  string BikeName { get; set;}
}

Model
[DataContract]
public class BikeModel : IBike
{
  [DataMember]
  public string BikeName { get; set; }
}

Other Object that can't be used in Silverlight because of MarshalObjectByRef etc in base class
public class Bike : IBike, UnusableBaseClass
{
....
}

IService1
[ServiceContract]
[ServiceKnownType(typeof(BikeModel))]
public interface IService1
{
    [OperationContract]
    IBike GetBike();
}

Service
 public class Service1 : IService1
 {
   public IBike GetBike()
   {
     Bike b = BikeManager.GetFirstBikeInTheDataBase();
     return b;
    }
 }

MainPage.xaml.cs -
public MainPage()
{
  InitializeComponent();
  this.Loaded += (s, a) =>
  {
     ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
     client.GetBikeCompleted += (sender, e) =>
     {
        var d = e.Result;
        // this cast works
        BikeModel model = (BikeModel)d;
      };
      client.GetBikeAsync();

    };
}

A: Is this just a typo, or is that really like this in your model?? The model class should be decorated with [DataContract] - not [DataMember]. It should be like this:
[DataContract]
public class BikeModel : IBike
{
  [DataMember]
  public string BikeName { get; set; }
}

UPDATE: okay, that was just a typo.
Can you try this? Turn your IBike interface into a BaseBike base class:
public class BaseBike
{
  string BikeName { get; set;}
}

and then return that base type from your call
[ServiceContract]
[ServiceKnownType(typeof(BikeModel))]
public interface IService1
{
    [OperationContract]
    BaseBike GetBike();
}

Does that change anything at all? I know WCF is a bit picky about what can be serialized around - since all that's serialized must be representable in XML schema, you cannot easily use interfaces and/or generics.
The other option you could try is to use the more focused [KnownType] attribute on the operation, instead of the [ServiceKnownType]. Again - not sure if it'll help, I'm fishing for ideas here.... (your stuff looks OK from a .NET standpoint - but WCF communication isn't always quite the same world....)


text:
Q: onYouTubeIframeAPIReady not firing on angular2 web app I'm building a web application using angular 2, typescript and YouTube API to add a player to the page after the user login.
So once logged in, the app loads the following component:
export class MyComponent implements OnInit {
  myService: MyService;

  constructor( private _myService: MyService ) {
    this.myService = _myService;
  }

  ngOnInit() {
   this._myService.loadAPI();
  }

}

The component html contains the following tag:
<iframe id="player" type="text/html" width="640" height="360"
      src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
      frameborder="0" allowfullscreen></iframe>

And finally, the service has the following:
  player: YT.Player;

  loadAPI(){
    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    console.log('API loaded'); // this is shown on the console.
  }

  onYouTubeIframeAPIReady(){
    this.player = new YT.Player('player', {
      events: {
        'onReady': this.onPlayerReady,
        'onStateChange': this.onPlayerStateChange
      }
    });
    console.log('youtube iframe api ready!'); // this is never triggered.
  }

  onPlayerReady(event){
    event.target.playVideo();
  }

  onPlayerStateChange(status){
    console.log(status.data);
  }

I've read that the function "onYouTubeIframeAPIReady" is automatically called by the API, so I wonder what should I do differently to have it working properly.

A: You need to define your function, onYouTubeIframeAPIReady, on the global object. This works exactly the same way as in the linked answer for JavaScript.
What follows is all 100% JavaScript stuff here, applicable to TypeScript by way of its superset of JavaScript nature.
If you are using modules, as is generally the case with an Angular 2 application, then your code is isolated and does not execute in the global scope by default. This means that in order to define a global, we need to obtain a reference to the Global Object. In a browser this is very simple as window refers to the global (unless it is shadowed).
What you need to write is quite straightforward. It is essentially
window.onYouTubeIframeAPIReady = function () { ... };

That means taking your current code, which looks like this
export default class YouTubeService {
  ...
  loadAPI() {
    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    console.log('API loaded'); // this is shown on the console.
  }

  onYouTubeIframeAPIReady() { }
}

And changing it to this
export default class YouTubeService {
  ...
  loadAPI() {
    window.onYouTubeIframeAPIReady = function () { };

    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    console.log('API loaded'); // this is shown on the console.
  }
}

You will get a TypeScript error telling you that window has no definition for onYouTubeIframeAPIReady. This is easily resolved in numerous ways, but I just will illustrate two possibilities, either will do the job, and technically neither is necessary since TypeScript will still emit code in spite of the error.

*

*Specify a type assertion on window that suppresses the error
(window as any).onYouTubeIframeAPIReady = function () {}

*Declare the member on window so that you can assign to it without an error. Inside a module (recall we are not in the global scope) we can use the following form
declare global {
  interface Window {
    onYouTubeIframeAPIReady?: () => void;
  }
}

Remember all JavaScript is valid TypeScript and that TypeScript does not add behavior or functionality to JavaScript. It is a typed view, an interpretation if you will, of JavaScript that allows it to be statically verified and have excellent tooling, to catch errors, provide a productive editing experience, and allow expectations to be documented at code level.
This is just JavaScript. It is the very same solution as used in Youtube iframe api not triggering onYouTubeIframeAPIReady, I only posted it because there seemed to be a disconnect.

Addendum: It is worth noting that if you using a module loader such as SystemJS or RequireJS, you can abstract the manual script tag injection process via loader configuration. The benefit is cleaner, more declarative code and also increased testability as you can then stub the YouTube dependency, isolating your tests from the network.
For SystemJS, you would use the following configuration
SystemJS.config({
  map: {
    "youtube": "https://www.youtube.com/iframe_api"
  },
  meta: {
    "https://www.youtube.com/iframe_api": {
      "format": "global",
      "scriptLoad": true,
      "build": false
    }
  }
});

You can write
export default class YouTubeService {
  async loadAPI() {
    window.onYouTubeIframeAPIReady = function () {
      console.log('API loaded'); // this is shown on the console.
    };
    try {
      await import('youtube'); // automatically injects a script tag
    }
    catch (e) {
      console.error('The YouTube API failed to load');
    }
  }
}

declare global {
  interface Window {
    onYouTubeIframeAPIReady?: () => void;
  }
}

Now if you wanted to test this code, mocking the YouTube API, you could write
test/test-stubs/stub-youtube-api.ts
(function () {
  window.onYouTubeIframeAPIReady();
}());

test/services/youtube-service.spec.ts
import test from 'blue-tape';

import YouTubeService from 'src/services/youtube.service'

SystemJS.config({
  map: {
    "youtube": "test/test-stubs/stub-youtube-api.ts"
  }
});

if(typeof window === 'undefined') {
  global.window = {};
}

test('Service must define a callback for onYouTubeIframeAPIReady', async ({isNot}) => {
  const service = new YouTubeService();
  await service.loadAPI();
  t.isNot(undefined, window.onYouTubeIframeAPIReady);
});


text:
Q: ¿Como puedo capturar los datos de un formulario html, procesarlo con azure function y enviar un correo? Tengo un formulario simple hecho en html5 y css (los campos son "nombre" y "email"), creé una azure function en javascript que se debe encargar de tomar los datos del formulario, procesarlos y enviar un correo electrónico al mismo correo que el usuario ingrese utilizando sendgrid, alguna idea de como hacerlo?...este es el código de mi azure function.
module.exports = async function (context, input) {
context.log(input);

var message = {
    "personalizations": [ { "to": [ { "email": "test@gmail.com" } ] } ],
   from: { email: "testfrom@gmail.com" },
   subject: "Azure news",
   content: [{
       type: 'text/plain',
       value: input
   }]

};
context.done(null, message);
}
De antemano, muchas gracias.


text:
Q: Mocking Bigquery for integration tests While other interfaces are relatively easy to mock in my Java integration tests, I couldn't find a proper way of mocking Bigquery.
One possibility is to mock the layer I wrote on top of Bigquery itself, but I prefer mocking Bigquery in a more natural way. I'm looking for a limited, lightweight implementation, which allows defining the table contents, and supports queries using the standard API.
Is there such a library? If not, what alternative approaches are recommended?

A: In unit testing it is perfectly fine to mock all external dependencies, and as long you are using interfaces to abstract out access to BigQuery client, mocking should not be an issue.
With integration testing I would rather get all my 3rd parties dependencies tested
to the extend an application needs it.
For instance one case would be an ETL which streams data from external sources to BigQuery, in this case an integration test needs to verify that all data is in BigQuery as expected, which means that verification stage needs to take into account repeated, and nested messages as required.
Another case would an application that runs some business SQLs, in this case  you would have populate BigQuery with some test data before applicaiton run,
then the applicaiton needs to publishe the SQL output either as  view/new table/or stream out of data out of for verification.
There are already some libraries taking care of integration testing with datastores including BigQuery/NoSQL/SQL
They would provide an easy solution for the cases described above and full support for SQL, dynamic macro/predicate etc ....

*

*Dsunit  (go-lang)

*JDsunit (java)

*Endly(language agnostic)

See more how to use endly for ETL and BiqQuery testing
If datastore integration test library is not an option for you and you are looking for just testing BigQuery client, the good news is that the client uses REST, so using network sniffers you can easy record what is being send back and forth, then you can use it in replayer. In order to redirect BigQuery from
public BG endpoints to your replayer you would use http java proxy.


text:
Q: Does repeating Thread.Sleep(200) and Thread.Sleep(1) do the same thing? I am writing a .Net Micro Framework application that starts a timer and then does stuff each time the timer tick happens. Here's the code:
public void Run()
{
    var timer = new Timer(DoStuff, null, 120000, 120000);
    while (true)
    {
        Thread.Sleep(1);
    }
}

So every two minutes the method DoStuff gets called. I need the while loop to prevent the application exiting. What are the implications of the choice of milliseconds passed into Thread.Sleep? Does a small value (like 1) make the application react faster to the timer? Does a larger value consume less CPU power?
========== EDIT ==========
I just found the call I should (probably) use instead of the while loop in this cut-down example on the GHI page about .Net Micro Framework Timers:
Thread.Sleep(Timeout.Infinite);

I can add 'infinte' to my list of values to understand.

A: It's not obvious what you are trying to do here. Why not have your timer fire as often as needed and do your periodic work from the timer method?
As for Sleep, it has a certain granularity by default that follows the Windows timer tick, so you will not get a 1 millisecond resolution by default. Yes, calling Sleep 1000 times rather than once obviously costs more CPU power but the different probably isn't significant in most scenarios.


text:
Q: Cannot create an instance of class ViewModel in the new project I have two different projects. In the first one I use ViewModel with my activity and Room database. Everything works. Then I just created new project for different purposes and there I instantiate ViewModel absolutely the same way, but my app crashes with this error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.MainViewModel
    at android.app.ActivityThread.performLaunchActivity(Unknown Source:591)
    at android.app.ActivityThread.handleLaunchActivity(Unknown Source:36)
    at android.app.servertransaction.LaunchActivityItem.execute(Unknown Source:57)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(Unknown Source:99)
    at android.app.servertransaction.TransactionExecutor.execute(Unknown Source:34)
    at android.app.ActivityThread$H.handleMessage(Unknown Source:36)
    at android.os.Handler.dispatchMessage(Unknown Source:21)
    at android.os.Looper.loop(Unknown Source:207)
    at android.app.ActivityThread.main(Unknown Source:107)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(Unknown Source:11)
    at com.android.internal.os.ZygoteInit.main(Unknown Source:274)
 Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.MainViewModel
    at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
    at com.kazguiu.MainActivity.applyAdapterAndViewModel(MainActivity.kt:37)
    at com.kazguiu.MainActivity.onCreate(MainActivity.kt:25)
    at android.app.Activity.performCreate(Unknown Source:16)
    at android.app.Activity.performCreate(Unknown Source:1)
    at android.app.Instrumentation.callActivityOnCreate(Unknown Source:3)
    at android.app.ActivityThread.performLaunchActivity(Unknown Source:368)
    at android.app.ActivityThread.handleLaunchActivity(Unknown Source:36)
    at android.app.servertransaction.LaunchActivityItem.execute(Unknown Source:57)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(Unknown Source:99)
    at android.app.servertransaction.TransactionExecutor.execute(Unknown Source:34)
    at android.app.ActivityThread$H.handleMessage(Unknown Source:36)
    at android.os.Handler.dispatchMessage(Unknown Source:21)
    at android.os.Looper.loop(Unknown Source:207)
    at android.app.ActivityThread.main(Unknown Source:107)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(Unknown Source:11)
    at com.android.internal.os.ZygoteInit.main(Unknown Source:274)
 Caused by: java.lang.InstantiationException: java.lang.Class<com.example.MainViewModel> has no zero argument constructor
    at java.lang.Class.newInstance(Native Method)
    at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)

I instantiate ViewModel in activity like this:
private lateinit var mainViewModel: MainViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    applyAdapterAndViewModel()

}

private fun applyAdapterAndViewModel() {
    mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
}

My ViewModel:
class MainViewModel(application: Application) : AndroidViewModel(application) {

    private val exampleDao = Database.getDatabase(application).exampleDao()
    private val repository = Repository(exampleDao)

    fun getSubjects() = repository.getSubjects()

    fun addSubjects(subject: Subjects) = viewModelScope.launch(Dispatchers.IO) {
        repository.addSubject(subject)
    }

}

This way of using ViewModel is the same as my previous project. Only difference is that I have two additional dependencies in my current gradle:
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'

If I delete them, Android Studio doesn't recognize ViewModelProvider, but I don't have these dependencies in my previous projects at all and I use LiveData and ViewModel absolutely the same way(even the imports are the same) there. So, what am I supposed to do?

A: Your ViewModel requires an argument application: Application which can only be provided by using a ViewModelFactory like so:
ViewModelFactory
class MainViewModelFactory(
    private val application: Application
) : ViewModelProvider.Factory {
    @Suppress("unchecked_cast")
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
            return MainViewModel(application) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

MainActivity
private fun applyAdapterAndViewModel() {
// Not so kotlinic
mainViewModel = ViewModelProvider(this,MainViewModelFactory(application)).get(MainViewModel::class.java)
}

Also, in MainActivity, replace
private lateinit var mainViewModel: MainViewModel
with
private val viewModel by viewModels<MainViewModel> {
MainViewModelFactory(application) }


text:
Q: How to output a reverse expanded sum I want to output a reverse expanded sum, which should give me an output like this:

Reverse expanded sum:
  Output the expanded sum in reverse.
  For example, if the user entered 7, then your program should output:
7+6+5+4+3+2+1=28

The code below is giving me an non-stop output instead with +-12+-13 format:
 public static int printSum(int n, boolean reverse) {
    int sum = 0;
    String s = "";
    for(int i = 1; i < n+1; i--) {
        sum += i;//was =
        //System.out.print(i + "+");
    }
    for(int i = 1; i <n; i--) {
        s =String.valueOf(i);
        System.out.print(s + "+");
    }
    //System.out.print(i);

    System.out.print( n + "=" + sum);
    return sum;
}

I used case statements in the main method to call the printSum method:
//reverse expanded sum
case 2:
    System.out.print("Enter a positive integer.\n");
    number = console.nextInt();
    printSum(number, false);
    break;

A: Think this does what you linked in the image assuming it only takes positive integers given "Enter a positive integer.\n"
  public static int printSum(int n) {
        int sum = 0;
        for(int x = 0; x < n; x++){
            sum += n - x;
            if(x != n - 1){
                System.out.print((n - x) + "+");
            }
            else{
                System.out.print((n - x) + "=" + sum);
            }
        }
        return sum;
    }

A: I suppose your logic is correct to some extent. Try this.
public static int printSum(int n, boolean reverse){

  int sum = 0;
  for( int i = n ; i>0 ; i--){
     sum += i;
     if(i > 1){
       System.out.print(i + "+");
     }else{
      System.out.print(i);
     }
  }
  System.out.print( n + "=" + sum);
  return sum;
 }


text:
Q: How to wait on Async tasks static void Main(string[] args)
{
    Action myAction = async () =>
    {
        await Task.Delay(5);
        Console.WriteLine(Interlocked.Add(ref ExecutionCounter, 1));
    };

    var actions = new[] { myAction, myAction, myAction };

    Task.WaitAll(actions.Select(a => Execute(a)).ToArray());  //This blocks, right?

    Console.WriteLine("Done waiting on tasks.");
    Console.ReadLine();
}

static int ExecutionCounter = 0;

private static Task Execute(Action a)
{
    return Task.Factory.StartNew(async () =>
    {
        await Task.Delay(5);
        a();
    });
}

This seems simple enough, but naturally the output always looks like this (the order of the numbers change, of course):

Done waiting on tasks.
2
1
3

What am I missing here? Why doesn't Task.WaitAll block like I'm expecting it to?

A: So there are several separate bugs here.
First, for Execute, you're using StartNew with an async lambda.  Since StartNew doesn't have a Task<Task> returning overload, like Task.Run does, you've got a method that returns a Task indicating when the asynchronous operation has finished starting, not when the asynchronous operation has finished, which means that the Task returned by Execute will be completed basically right away, rather than after Delay finishes or the action you call finishes.  Additionally, there's simply no reason to use StartNew or Run at all when running asynchronous methods, you can just execute them normally and await them without pushing them to a thread pool thread.
Next, Execute accepts an Action, which implies that it's a synchronous method that doesn't compute any value.  What you're providing is an asynchronous method, but as the delegate doesn't return a Task, Execute can't await it.  If you want Execute to handle asynchronous methods, it needs to accept a delegate that returns a Task.
So given all of that Execute should look like this.
private static async Task Execute(Func<Task> action)
{
    await Task.Delay(TimeSpan.FromMilliseconds(5));
    await action();
}

Next onto the Main method.  As mentioned before Execute is accepting an Action when you're trying to provide an async method.  This means that when the action is run the code will continued executing before your actions have finished.  You need to adjust it to using a Task returning method.
After all of that, your code still has a race condition in it, at a conceptual level, that will prevent you from theoretically getting the results in the right order.  You're performing 3 different operations in parallel, and as a result of that, they can finish in any order.  While you are atomically incrementing the counter, it's possible for one thread to increment the counter, then another to run, increment the counter, print its value, then have the other thread run again and print out the value, given you a possible output of what you have, even after fixing all of the bugs mentioned above.  To ensure that the values are printed in order, you need to ensure that the increment and the console write are performed atomically.
Now you can write out your Main method like so:
int ExecutionCounter = 0;
object key = new object();
Func<Task> myAction = async () =>
{
    await Task.Delay(TimeSpan.FromMilliseconds(5));
    lock (key)
    {
        Console.WriteLine(++ExecutionCounter);
    }
};

var actions = new[] { myAction, myAction, myAction };

Task.WaitAll(actions.Select(a => Execute(a)).ToArray());  //This blocks, right?

And yes, as your comment mentions, calling WaitAll will block, rather than being asynchronous.


text:
Q: VT pin flashing LED on WT12D RF receiver module even with transmitter not enabled The VT pin on the decoder side (signifying a valid transmission) flashes intermittently (sort of imitating a square wave pulse)
This happens without me making any change in the circuit - no address change, or TE' (transmission enable, which I have permanently grounded).
I put together a circuit that follows the schematic:

(Source: https://electrosome.com/wp-content/uploads/2013/06/ASK-RF-Transmitter-600x823.jpg)
on the encoder side and

(Source: https://electrosome.com/wp-content/uploads/2013/06/ASK-RF-Receiver-600x557.jpg)
on the decoder side.
I'm using a Hi-Waote 6f22M battery power source, in case it is important.
Any reason you guys could suggest as to why it's not permanently high on the VT pin?

A: I don't know what exactly caused the flashing part, but I know what resolved it - replacing the battery by a DC adapter, which made it work seamlessly. Thinking that it might have been because the battery wasn't "keeping up" with the demand, I tried to check if the battery was near it's end, and it was. But if it was slowly fading away, the intensity should have gradually reduced, so that still remains an unsolved question.


text:
Q: Hindi Typing Tutor application I have been trying to learn hindi typing which uses Devanagari script.  Do we know if there are any typing tutor applications for Hindi language (देवनागरी लिपि)?  The standard official script adopted by Indian govt. for administrative purposes is "inscript".  There are different varients of Hindi keyboard layout, but I am specifically looking for the "inscript" layout.

A: I believe this is the link where we can download the typing tutor but so far I am unable to download it as it gets timed out.
http://pune.cdac.in/html/gist/down/key.asp

A: Here is another thing I discovered over a period of time.  We can download the hindi typing tutor from http://pune.cdac.in/html/gist/down/key.asp
CDAC have designed it to work in DOS.  In Ubuntu we have an application known as DOSBOX.  This is basically a windows DOS emulator.  After installing this application, we can practice hindi typing in Ubuntu.  All it requires is the learning of basics of DOSBOX to run the .exe files.

A: I know that Klavaro claims to be language- and layout-agnostic. It starts with teaching you the home row and branches out, teaching you groups of keys at a time. You can also supply texts to use as practice. I don't know how good it is with non-European languages in practice, but it's free and available in the Software Centre, so you could give it a go.