问:
Reading excel file in c# using Microsoft DocumentFormat.OpenXml SDK
I am using Microsoft DocumentFormat.OpenXml SDK to read data from excel file.
While doing so I am taking into consideration if a cell has blank values(If Yes, read that too).

Now, facing issues with one of the excel sheets where the workSheet.SheetDimension is null hence the code is throwing an exception.

Code used :

class OpenXMLHelper
    {
        //  A helper function to open an Excel file using OpenXML, and return a DataTable containing all the data from one
        //  of the worksheets.
        //
        //  We've had lots of problems reading in Excel data using OLEDB (eg the ACE drivers no longer being present on new servers,
        //  OLEDB not working due to security issues, and blatantly ignoring blank rows at the top of worksheets), so this is a more
        //  stable method of reading in the data.
        //

```<code>    public static DataTable ExcelWorksheetToDataTable(string pathFilename)
    {
        try
        {
            DataTable dt = new DataTable();
            string dimensions = string.Empty;

            using (FileStream fs = new FileStream(pathFilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (SpreadsheetDocument document = SpreadsheetDocument.Open(fs, false))
                {
                    // Find the sheet with the supplied name, and then use that
                    // Sheet object to retrieve a reference to the first worksheet.
                    //Sheet theSheet = document.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == worksheetName).FirstOrDefault();
                    //--Sheet theSheet = document.WorkbookPart.Workbook.Descendants<Sheet>().FirstOrDefault();

                    //--if (theSheet == null)
                    //--    throw new Exception("Couldn't find the worksheet: "+ theSheet.Id);

                    // Retrieve a reference to the worksheet part.
                    //WorksheetPart wsPart = (WorksheetPart)(document.WorkbookPart.GetPartById(theSheet.Id));
                    //--WorksheetPart wsPart = (WorksheetPart)(document.WorkbookPart.GetPartById(theSheet.Id));

                    WorkbookPart workbookPart = document.WorkbookPart;
                    WorksheetPart wsPart = workbookPart.WorksheetParts.FirstOrDefault();
                    Worksheet workSheet = wsPart.Worksheet;

                    dimensions = workSheet.SheetDimension.Reference.InnerText;       //  Get the dimensions of this worksheet, eg "B2:F4"

                    int numOfColumns = 0;
                    int numOfRows = 0;
                    CalculateDataTableSize(dimensions, ref numOfColumns, ref numOfRows);
                    //System.Diagnostics.Trace.WriteLine(string.Format("The worksheet \"{0}\" has dimensions \"{1}\", so we need a DataTable of size {2}x{3}.", worksheetName, dimensions, numOfColumns, numOfRows));

                    SheetData sheetData = workSheet.GetFirstChild<SheetData>();
                    IEnumerable<Row> rows = sheetData.Descendants<Row>();

                    string[,] cellValues = new string[numOfColumns, numOfRows];

                    int colInx = 0;
                    int rowInx = 0;
                    string value = "";
                    SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;

                    //  Iterate through each row of OpenXML data, and store each cell's value in the appropriate slot in our [,] string array.
                    foreach (Row row in rows)
                    {
                        for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
                        {
                            //  *DON'T* assume there's going to be one XML element for each column in each row...
                            Cell cell = row.Descendants<Cell>().ElementAt(i);
                            if (cell.CellValue == null || cell.CellReference == null)
                                continue;                       //  eg when an Excel cell contains a blank string

                            //  Convert this Excel cell's CellAddress into a 0-based offset into our array (eg "G13" -> [6, 12])
                            colInx = GetColumnIndexByName(cell.CellReference);             //  eg "C" -> 2  (0-based)
                            rowInx = GetRowIndexFromCellAddress(cell.CellReference) - 1;     //  Needs to be 0-based

                            //  Fetch the value in this cell
                            value = cell.CellValue.InnerXml;
                            if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
                            {
                                value = stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
                            }

                            cellValues[colInx, rowInx] = value;
                        }
                    }

                    //  Copy the array of strings into a DataTable.
                    //  We don't (currently) make any attempt to work out which columns should be numeric, rather than string.
                    for (int col = 0; col < numOfColumns; col++)
                    {
                        //dt.Columns.Add("Column_" + col.ToString());
                        dt.Columns.Add(cellValues[col, 0]);
                    }

                    //foreach (Cell cell in rows.ElementAt(0))
                    //{
                    //    dt.Columns.Add(GetCellValue(doc, cell));
                    //}

                    for (int row = 0; row < numOfRows; row++)
                    {
                        DataRow dataRow = dt.NewRow();
                        for (int col = 0; col < numOfColumns; col++)
                        {
                            dataRow.SetField(col, cellValues[col, row]);
                        }
                        dt.Rows.Add(dataRow);
                    }

                    dt.Rows.RemoveAt(0);
                    //#if DEBUG
                    //                //  Write out the contents of our DataTable to the Output window (for debugging)
                    //                string str = "";
                    //                for (rowInx = 0; rowInx < maxNumOfRows; rowInx++)
                    //                {
                    //                    for (colInx = 0; colInx < maxNumOfColumns; colInx++)
                    //                    {
                    //                        object val = dt.Rows[rowInx].ItemArray[colInx];
                    //                        str += (val == null) ? "" : val.ToString();
                    //                        str += "\t";
                    //                    }
                    //                    str += "\n";
                    //                }
                    //                System.Diagnostics.Trace.WriteLine(str);
                    //#endif
                    return dt;
                }
            }
        }
        catch (Exception ex)
        {
            return null;
        }

    }

    public static void CalculateDataTableSize(string dimensions, ref int numOfColumns, ref int numOfRows)
    {
        //  How many columns & rows of data does this Worksheet contain ?
        //  We'll read in the Dimensions string from the Excel file, and calculate the size based on that.
        //      eg "B1:F4" -> we'll need 6 columns and 4 rows.
        //
        //  (We deliberately ignore the top-left cell address, and just use the bottom-right cell address.)
        try
        {
            string[] parts = dimensions.Split(':');     // eg "B1:F4"
            if (parts.Length != 2)
                throw new Exception("Couldn't find exactly *two* CellAddresses in the dimension");

            numOfColumns = 1 + GetColumnIndexByName(parts[1]);     //  A=1, B=2, C=3  (1-based value), so F4 would return 6 columns
            numOfRows = GetRowIndexFromCellAddress(parts[1]);
        }
        catch
        {
            throw new Exception("Could not calculate maximum DataTable size from the worksheet dimension: " + dimensions);
        }
    }

    public static int GetRowIndexFromCellAddress(string cellAddress)
    {
        //  Convert an Excel CellReference column into a 1-based row index
        //  eg "D42"  ->  42
        //     "F123" ->  123
        string rowNumber = System.Text.RegularExpressions.Regex.Replace(cellAddress, "[^0-9 _]", "");
        return int.Parse(rowNumber);
    }

    public static int GetColumnIndexByName(string cellAddress)
    {
        //  Convert an Excel CellReference column into a 0-based column index
        //  eg "D42" ->  3
        //     "F123" -> 5
        var columnName = System.Text.RegularExpressions.Regex.Replace(cellAddress, "[^A-Z_]", "");
        int number = 0, pow = 1;
        for (int i = columnName.Length - 1; i >= 0; i--)
        {
            number += (columnName[i] - 'A' + 1) * pow;
            pow *= 26;
        }
        return number - 1;
    }
}[enter image description here][1]
</code>```

答:
The SheetDimension part is optional (and therefor you cannot always rely on it being up to date). See the following part of the OpenXML specification:

18.3.1.35 dimension (Worksheet Dimensions)

This element specifies the used range of the worksheet. It specifies the row and column bounds of
  used cells in the worksheet. This is optional and is not required.
  Used cells include cells with formulas, text content, and cell
  formatting. When an entire column is formatted, only the first cell in
  that column is considered used.

So an Excel file without any SheetDimension part is perfectly valid, so you should not rely on it being present in an Excel file.

Therefor I'd suggest to simply parse all Row elements contained in the SheetData part, and "count" the number of rows (instead of reading the SheetDimensions part to get the number of rows / columns). This way you can also take into account that an Excel file may contain completely blank rows in-between the data.

Body:
I am using Microsoft DocumentFormat.OpenXml SDK to read data from excel file.
While doing so I am taking into consideration if a cell has blank values(If Yes, read that too).

Now, facing issues with one of the excel sheets where the workSheet.SheetDimension is null hence the code is throwing an exception.

Code used :

class OpenXMLHelper
    {
        //  A helper function to open an Excel file using OpenXML, and return a DataTable containing all the data from one
        //  of the worksheets.
        //
        //  We've had lots of problems reading in Excel data using OLEDB (eg the ACE drivers no longer being present on new servers,
        //  OLEDB not working due to security issues, and blatantly ignoring blank rows at the top of worksheets), so this is a more
        //  stable method of reading in the data.
        //

    public static DataTable ExcelWorksheetToDataTable(string pathFilename)
    {
        try
        {
            DataTable dt = new DataTable();
            string dimensions = string.Empty;

            using (FileStream fs = new FileStream(pathFilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (SpreadsheetDocument document = SpreadsheetDocument.Open(fs, false))
                {
                    // Find the sheet with the supplied name, and then use that
                    // Sheet object to retrieve a reference to the first worksheet.
                    //Sheet theSheet = document.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == worksheetName).FirstOrDefault();
                    //--Sheet theSheet = document.WorkbookPart.Workbook.Descendants<Sheet>().FirstOrDefault();

                    //--if (theSheet == null)
                    //--    throw new Exception("Couldn't find the worksheet: "+ theSheet.Id);

                    // Retrieve a reference to the worksheet part.
                    //WorksheetPart wsPart = (WorksheetPart)(document.WorkbookPart.GetPartById(theSheet.Id));
                    //--WorksheetPart wsPart = (WorksheetPart)(document.WorkbookPart.GetPartById(theSheet.Id));

                    WorkbookPart workbookPart = document.WorkbookPart;
                    WorksheetPart wsPart = workbookPart.WorksheetParts.FirstOrDefault();
                    Worksheet workSheet = wsPart.Worksheet;

                    dimensions = workSheet.SheetDimension.Reference.InnerText;       //  Get the dimensions of this worksheet, eg "B2:F4"

                    int numOfColumns = 0;
                    int numOfRows = 0;
                    CalculateDataTableSize(dimensions, ref numOfColumns, ref numOfRows);
                    //System.Diagnostics.Trace.WriteLine(string.Format("The worksheet \"{0}\" has dimensions \"{1}\", so we need a DataTable of size {2}x{3}.", worksheetName, dimensions, numOfColumns, numOfRows));

                    SheetData sheetData = workSheet.GetFirstChild<SheetData>();
                    IEnumerable<Row> rows = sheetData.Descendants<Row>();

                    string[,] cellValues = new string[numOfColumns, numOfRows];

                    int colInx = 0;
                    int rowInx = 0;
                    string value = "";
                    SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;

                    //  Iterate through each row of OpenXML data, and store each cell's value in the appropriate slot in our [,] string array.
                    foreach (Row row in rows)
                    {
                        for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
                        {
                            //  *DON'T* assume there's going to be one XML element for each column in each row...
                            Cell cell = row.Descendants<Cell>().ElementAt(i);
                            if (cell.CellValue == null || cell.CellReference == null)
                                continue;                       //  eg when an Excel cell contains a blank string

                            //  Convert this Excel cell's CellAddress into a 0-based offset into our array (eg "G13" -> [6, 12])
                            colInx = GetColumnIndexByName(cell.CellReference);             //  eg "C" -> 2  (0-based)
                            rowInx = GetRowIndexFromCellAddress(cell.CellReference) - 1;     //  Needs to be 0-based

                            //  Fetch the value in this cell
                            value = cell.CellValue.InnerXml;
                            if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
                            {
                                value = stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
                            }

                            cellValues[colInx, rowInx] = value;
                        }
                    }

                    //  Copy the array of strings into a DataTable.
                    //  We don't (currently) make any attempt to work out which columns should be numeric, rather than string.
                    for (int col = 0; col < numOfColumns; col++)
                    {
                        //dt.Columns.Add("Column_" + col.ToString());
                        dt.Columns.Add(cellValues[col, 0]);
                    }

                    //foreach (Cell cell in rows.ElementAt(0))
                    //{
                    //    dt.Columns.Add(GetCellValue(doc, cell));
                    //}

                    for (int row = 0; row < numOfRows; row++)
                    {
                        DataRow dataRow = dt.NewRow();
                        for (int col = 0; col < numOfColumns; col++)
                        {
                            dataRow.SetField(col, cellValues[col, row]);
                        }
                        dt.Rows.Add(dataRow);
                    }

                    dt.Rows.RemoveAt(0);
                    //#if DEBUG
                    //                //  Write out the contents of our DataTable to the Output window (for debugging)
                    //                string str = "";
                    //                for (rowInx = 0; rowInx < maxNumOfRows; rowInx++)
                    //                {
                    //                    for (colInx = 0; colInx < maxNumOfColumns; colInx++)
                    //                    {
                    //                        object val = dt.Rows[rowInx].ItemArray[colInx];
                    //                        str += (val == null) ? "" : val.ToString();
                    //                        str += "\t";
                    //                    }
                    //                    str += "\n";
                    //                }
                    //                System.Diagnostics.Trace.WriteLine(str);
                    //#endif
                    return dt;
                }
            }
        }
        catch (Exception ex)
        {
            return null;
        }

    }

    public static void CalculateDataTableSize(string dimensions, ref int numOfColumns, ref int numOfRows)
    {
        //  How many columns & rows of data does this Worksheet contain ?
        //  We'll read in the Dimensions string from the Excel file, and calculate the size based on that.
        //      eg "B1:F4" -> we'll need 6 columns and 4 rows.
        //
        //  (We deliberately ignore the top-left cell address, and just use the bottom-right cell address.)
        try
        {
            string[] parts = dimensions.Split(':');     // eg "B1:F4"
            if (parts.Length != 2)
                throw new Exception("Couldn't find exactly *two* CellAddresses in the dimension");

            numOfColumns = 1 + GetColumnIndexByName(parts[1]);     //  A=1, B=2, C=3  (1-based value), so F4 would return 6 columns
            numOfRows = GetRowIndexFromCellAddress(parts[1]);
        }
        catch
        {
            throw new Exception("Could not calculate maximum DataTable size from the worksheet dimension: " + dimensions);
        }
    }

    public static int GetRowIndexFromCellAddress(string cellAddress)
    {
        //  Convert an Excel CellReference column into a 1-based row index
        //  eg "D42"  ->  42
        //     "F123" ->  123
        string rowNumber = System.Text.RegularExpressions.Regex.Replace(cellAddress, "[^0-9 _]", "");
        return int.Parse(rowNumber);
    }

    public static int GetColumnIndexByName(string cellAddress)
    {
        //  Convert an Excel CellReference column into a 0-based column index
        //  eg "D42" ->  3
        //     "F123" -> 5
        var columnName = System.Text.RegularExpressions.Regex.Replace(cellAddress, "[^A-Z_]", "");
        int number = 0, pow = 1;
        for (int i = columnName.Length - 1; i >= 0; i--)
        {
            number += (columnName[i] - 'A' + 1) * pow;
            pow *= 26;
        }
        return number - 1;
    }
}[enter image description here][1]


来源: stackexchange

问:
git-lfs i/o timeout while pushing code to bitbucket
I use git-lfs for big sized files in git repo. When im trying to push the binaries to repo, git-lfs is going in an infinite loop and tries to upload the files again and again.
Then I enabled trace logs and I see that git-lfs is failing due to i/o timeout error.

Git LFS: (0 of 8 files) 395.68 MB / 748.90 MB

  trace git-lfs: tq: retrying object
  25c358603c20dbd5af29ba6429bd4a1e43df7ac908b32: LFS: Put
  https://media-api.atlassian.io/upload/fe3853ab-61e8-9e38-a7ac90377129/binary?hashAlgorithm=sha256:
  read tcp xxx.rr.33.14:61709->xxx.rrr.dd.34:9480: i/o timeout trace
  git-lfs: tq: enqueue retry #1 for
  "25c3ac077a0dbd5af29ba6429bd4a1e43df7ac908b32" (size: 121194578) trace
  git-lfs: HTTP: PUT
  https://media-api.atlassian.io/upload/0e7801a5-e481-4ad7-b11a-067640/binary
  Git LFS: (0 of 8 files) 365.18 MB / 748.90 MB

Commands im running -

```<code>$ git add binaries/
$ git commit -m 'my msg'
$ git push
</code>```

答:
If you look here there are some timeout settings you can try to set.

Git LFS timeout settings

this is a common problem and you can try to adjust that parameters.

ContentLicense: CC BY-SA 3.0

Body:
I use git-lfs for big sized files in git repo. When im trying to push the binaries to repo, git-lfs is going in an infinite loop and tries to upload the files again and again.
Then I enabled trace logs and I see that git-lfs is failing due to i/o timeout error.

Git LFS: (0 of 8 files) 395.68 MB / 748.90 MB

  trace git-lfs: tq: retrying object
  25c358603c20dbd5af29ba6429bd4a1e43df7ac908b32: LFS: Put
  https://media-api.atlassian.io/upload/fe3853ab-61e8-9e38-a7ac90377129/binary?hashAlgorithm=sha256:
  read tcp xxx.rr.33.14:61709->xxx.rrr.dd.34:9480: i/o timeout trace
  git-lfs: tq: enqueue retry #1 for
  "25c3ac077a0dbd5af29ba6429bd4a1e43df7ac908b32" (size: 121194578) trace
  git-lfs: HTTP: PUT
  https://media-api.atlassian.io/upload/0e7801a5-e481-4ad7-b11a-067640/binary
  Git LFS: (0 of 8 files) 365.18 MB / 748.90 MB

Commands im running -

$ git add binaries/
$ git commit -m 'my msg'
$ git push

ContentLicense: CC BY-SA 4.0


问:
@ExceptionHandler doesn't catch HttpMessageNotReadableException
I have the following exception handler:

```<code>@ControllerAdvice
public class MyExceptionHandler {
  private static final Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);
    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void handle(HttpMessageNotReadableException e) {
        logger.warn("HttpMessageNotReadableException occurred.", e);
        throw e;
    }
</code>```

But it doesn't catch HttpMessageNotReadableException?! In my logs I see (it prints spring itself):

```<code>2017-07-04 13:26:38,699 DEBUG org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.getMethodArgumentValues:164 - Failed to resolve argument 0 of type 'com.finvale.model.Client'
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize value of type java.time.LocalDate from String "Invalid date": Text 'Invalid date' could not be parsed at index 0
 at [Source: java.io.PushbackInputStream@4f30395; line: 1, column: 103] (through reference chain: com.finvale.model.Client["birthDay"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.time.LocalDate from String "Invalid date": Text 'Invalid date' could not be parsed at index 0
 at [Source: java.io.PushbackInputStream@4f30395; line: 1, column: 103] (through reference chain: com.finvale.model.Client["birthDay"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:240)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:225)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:201)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:150)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:128)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:108)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
</code>```

Is it possible to catch this exception in my ExceptionHandler ?

P.S.

I agree that my code contains mistake. I neeed to specify type in annotation.
I changed it like this:

```<code> @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void handle(HttpMessageNotReadableException e) {
</code>```

but I still see same behaviour.

handle method doesn't invoke

答:
You have to specify the class that the handler needs to handle. Like:

```<code>@ExceptionHandler(HttpMessageNotReadableException.class)
</code>```

See here for further reading for example. Or there for a "complete" discussion regarding spring and exception handling.

Body:
I have the following exception handler:

@ControllerAdvice
public class MyExceptionHandler {
  private static final Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);
    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void handle(HttpMessageNotReadableException e) {
        logger.warn("HttpMessageNotReadableException occurred.", e);
        throw e;
    }

But it doesn't catch HttpMessageNotReadableException?! In my logs I see (it prints spring itself):

2017-07-04 13:26:38,699 DEBUG org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.getMethodArgumentValues:164 - Failed to resolve argument 0 of type 'com.finvale.model.Client'
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize value of type java.time.LocalDate from String "Invalid date": Text 'Invalid date' could not be parsed at index 0
 at [Source: java.io.PushbackInputStream@4f30395; line: 1, column: 103] (through reference chain: com.finvale.model.Client["birthDay"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.time.LocalDate from String "Invalid date": Text 'Invalid date' could not be parsed at index 0
 at [Source: java.io.PushbackInputStream@4f30395; line: 1, column: 103] (through reference chain: com.finvale.model.Client["birthDay"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:240)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:225)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:201)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:150)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:128)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:108)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

Is it possible to catch this exception in my ExceptionHandler ?

P.S.

I agree that my code contains mistake. I neeed to specify type in annotation.
I changed it like this:

 @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void handle(HttpMessageNotReadableException e) {

but I still see same behaviour.

handle method doesn't invoke

Body:
You have to specify the class that the handler needs to handle. Like:

@ExceptionHandler(HttpMessageNotReadableException.class)

See here for further reading for example. Or there for a "complete" discussion regarding spring and exception handling.


问:
How to display [please select] on select box, instead of first item on selectbox in php?
i have developed select box using php all work fine. but i want to display default word like SELECT instead of first item in selectbox, how can i do it. </p>

```<code>                <?php
                    if(!isset($_POST['floor_id']))
                    {
                        $fl = 'floor_id';
                        $_POST['floor_id'] = $fl;
                    }

                    $query = "SELECT id,floor from sdh_extension.tb_floor";

                    $selectbox='<select name="floor_id" class="form-control"
                    onchange="this.form.submit()">';
                    foreach ($db->query($query) as $row)
                    {
                        $id=$row['id'];
                        $name=$row['floor'];

                        if($row['id'] == $_POST['floor_id'])
                        {

                             $isSelected = ' selected="selected"';
                        }
                        else {
                                $isSelected = '';
                                }
                        $selectbox.= "
                       <optionvalue=".$id.$isSelected.">".$name."</option>";
                    }
                        $selectbox.='</select>';
                        echo $selectbox;
                ?>
</code>```

答:
Hope this will help.

Use the below code to:

```<code><?php
                if(!isset($_POST['floor_id']))
                {
                    $fl = 'floor_id';
                    $_POST['floor_id'] = $fl;
                }

                $query = "SELECT id,floor from sdh_extension.tb_floor";

                $selectbox='<select name="floor_id" class="form-control"
                onchange="this.form.submit()">';
                $selectbox.= "
                   <option value="">Please select one option</option>";
                foreach ($db->query($query) as $row)
                {
                    $id=$row['id'];
                    $name=$row['floor'];

                    if($row['id'] == $_POST['floor_id'])
                    {

                         $isSelected = ' selected="selected"';
                    }
                    else {
                            $isSelected = '';
                            }
                    $selectbox.= "
                   <option value=".$id.$isSelected.">".$name."</option>";
                }
                    $selectbox.='</select>';
                    echo $selectbox;
            ?>
</code>```

Body:
i have developed select box using php all work fine. but i want to display default word like SELECT instead of first item in selectbox, how can i do it.

                <?php
                    if(!isset($_POST['floor_id']))
                    {
                        $fl = 'floor_id';
                        $_POST['floor_id'] = $fl;
                    }

                    $query = "SELECT id,floor from sdh_extension.tb_floor";

                    $selectbox='<select name="floor_id" class="form-control"
                    onchange="this.form.submit()">';
                    foreach ($db->query($query) as $row)
                    {
                        $id=$row['id'];
                        $name=$row['floor'];

                        if($row['id'] == $_POST['floor_id'])
                        {

                             $isSelected = ' selected="selected"';
                        }
                        else {
                                $isSelected = '';
                                }
                        $selectbox.= "
                       <optionvalue=".$id.$isSelected.">".$name."</option>";
                    }
                        $selectbox.='</select>';
                        echo $selectbox;
                ?>

Body:
Hope this will help.

Use the below code to:

<?php
                if(!isset($_POST['floor_id']))
                {
                    $fl = 'floor_id';
                    $_POST['floor_id'] = $fl;
                }

                $query = "SELECT id,floor from sdh_extension.tb_floor";

                $selectbox='<select name="floor_id" class="form-control"
                onchange="this.form.submit()">';
                $selectbox.= "
                   <option value="">Please select one option</option>";
                foreach ($db->query($query) as $row)
                {
                    $id=$row['id'];
                    $name=$row['floor'];

                    if($row['id'] == $_POST['floor_id'])
                    {

                         $isSelected = ' selected="selected"';
                    }
                    else {
                            $isSelected = '';
                            }
                    $selectbox.= "
                   <option value=".$id.$isSelected.">".$name."</option>";
                }
                    $selectbox.='</select>';
                    echo $selectbox;
            ?>


问:
Serverside Datatables Search box styling
I have noticed that the search and show inputs for the datatables are stuck inside  tags. When I try to remove the label tags from the source JavaScript, the input disappears. I may be doing it wrong but is there a way to remove it so that I can adjust its width and make it adhere to my dynamic column sizing?

This is the part I'm talking about (from the source JavaScript file)

```<code>function pb(a) {
        var b = a.oClasses,
            c = a.sTableId,
            d = a.oLanguage,
            e = a.oPreviousSearch,
            f = a.aanFeatures,
            g = '<input type="search" class="' + b.sFilterInput + '"/>',
            j = d.sSearch,
            j = j.match(/_INPUT_/) ? j.replace("_INPUT_", g) : j + g,
            b = h("<div/>", {
                id: !f.f ? c + "_filter" : null,
                "class": b.sFilter
            }).append(h("<label/>").append(j)),
            f = function() {
                var b = !this.value ?
                    "" : this.value;
                b != e.sSearch && (fa(a, {
                    sSearch: b,
                    bRegex: e.bRegex,
                    bSmart: e.bSmart,
                    bCaseInsensitive: e.bCaseInsensitive
                }), a._iDisplayStart = 0, O(a))
            },
            g = null !== a.searchDelay ? a.searchDelay : "ssp" === y(a) ? 400 : 0,
            i = h("input", b).val(e.sSearch).attr("placeholder", d.sSearchPlaceholder).bind("keyup.DT search.DT input.DT paste.DT cut.DT", g ? Oa(f, g) : f).bind("keypress.DT", function(a) {
                if (13 == a.keyCode) return !1
            }).attr("aria-controls", c);
        h(a.nTable).on("search.dt.DT", function(b, c) {
            if (a === c) try {
                i[0] !== I.activeElement && i.val(e.sSearch)
            } catch (d) {}
        });
        return b[0]
    }
</code>```

The code when the page is loaded

```<code><div class="row">
    <div class="col-sm-12">
        <div id="table_filter" class="dataTables_filter pull-left">
            <label>
                <input type="search" class="form-control input-sm" placeholder="Search" aria-controls="table">
            </label>
        </div>
    </div>
</div>
</code>```

See how the search input is under the label? I was wondering how I can remove it so that it adheres to my column sizing.

答:
Use the code below to remove label node from the search box.

```<code>var table = $('#example').DataTable({
   initComplete: function(){
      $('.dataTables_filter label').children().unwrap('<label/>');
   }
});
</code>```

See this example for code and demonstration.

Body:
I have noticed that the search and show inputs for the datatables are stuck inside  tags. When I try to remove the label tags from the source JavaScript, the input disappears. I may be doing it wrong but is there a way to remove it so that I can adjust its width and make it adhere to my dynamic column sizing?

This is the part I'm talking about (from the source JavaScript file)

function pb(a) {
        var b = a.oClasses,
            c = a.sTableId,
            d = a.oLanguage,
            e = a.oPreviousSearch,
            f = a.aanFeatures,
            g = '<input type="search" class="' + b.sFilterInput + '"/>',
            j = d.sSearch,
            j = j.match(/_INPUT_/) ? j.replace("_INPUT_", g) : j + g,
            b = h("
", {
                id: !f.f ? c + "_filter" : null,
                "class": b.sFilter
            }).append(h("").append(j)),
            f = function() {
                var b = !this.value ?
                    "" : this.value;
                b != e.sSearch && (fa(a, {
                    sSearch: b,
                    bRegex: e.bRegex,
                    bSmart: e.bSmart,
                    bCaseInsensitive: e.bCaseInsensitive
                }), a._iDisplayStart = 0, O(a))
            },
            g = null !== a.searchDelay ? a.searchDelay : "ssp" === y(a) ? 400 : 0,
            i = h("input", b).val(e.sSearch).attr("placeholder", d.sSearchPlaceholder).bind("keyup.DT search.DT input.DT paste.DT cut.DT", g ? Oa(f, g) : f).bind("keypress.DT", function(a) {
                if (13 == a.keyCode) return !1
            }).attr("aria-controls", c);
        h(a.nTable).on("search.dt.DT", function(b, c) {
            if (a === c) try {
                i[0] !== I.activeElement && i.val(e.sSearch)
            } catch (d) {}
        });
        return b[0]
    }

The code when the page is loaded

                <input type="search" class="form-control input-sm" placeholder="Search" aria-controls="table">

See how the search input is under the label? I was wondering how I can remove it so that it adheres to my column sizing.

Body:
Use the code below to remove label node from the search box.

var table = $('#example').DataTable({
   initComplete: function(){
      $('.dataTables_filter label').children().unwrap('<label/>');
   }
});

See this example for code and demonstration.


问:
Render view Express after processing /POST
I'am trying to render a view after processing the file uploaded with Multer.
I got a error

Unhandled promise rejection (rejection id: 1): TypeError: res.redirect is not a function

What do i understand wrong ?
Also the application never do the rendering on botom to 'step2.ejs'

```<code>app.post('/vision/upload', upload.single("upl"), function(req, res) {
var file = req.file;
filePath = req.file.path;
const req2 = new vision.Request({
    image: new vision.Image(file),
    features: [
        new vision.Feature('DOCUMENT_TEXT_DETECTION', 10),
    ]
});
vision.annotate(req2).then((res) => {
    p1 = JSON.stringify(res.responses);
p1up = p1.toUpperCase();
occurrencesText = new Occurrences(p1up);
console.log(occurrencesText);
connection.query(queryString, function(err, rows, fields) {
    if (err) throw err;
    for (var i in rows) {
        var occurence = stringOccurrence(p1up, rows[i].name);
        var fuzzy = fuzzysearch(rows[i].name, p1up);
        if(fuzzy = true){
            arrayResults.push([rows[i].name, occurence]);
        }
       //
    }
});
res.render('step2.ejs', {
    results: arrayResults,
    "filePath": filePath
});
</code>```

})
});

答: Rename res in vision.annotate(req2).then((res) => {})) as it is overriding the actual res object of the request.

Body:
I'am trying to render a view after processing the file uploaded with Multer.
I got a error

Unhandled promise rejection (rejection id: 1): TypeError: res.redirect is not a function

What do i understand wrong ?
Also the application never do the rendering on botom to 'step2.ejs'

app.post('/vision/upload', upload.single("upl"), function(req, res) {
var file = req.file;
filePath = req.file.path;
const req2 = new vision.Request({
    image: new vision.Image(file),
    features: [
        new vision.Feature('DOCUMENT_TEXT_DETECTION', 10),
    ]
});
vision.annotate(req2).then((res) => {
    p1 = JSON.stringify(res.responses);
p1up = p1.toUpperCase();
occurrencesText = new Occurrences(p1up);
console.log(occurrencesText);
connection.query(queryString, function(err, rows, fields) {
    if (err) throw err;
    for (var i in rows) {
        var occurence = stringOccurrence(p1up, rows[i].name);
        var fuzzy = fuzzysearch(rows[i].name, p1up);
        if(fuzzy = true){
            arrayResults.push([rows[i].name, occurence]);
        }
       //
    }
});
res.render('step2.ejs', {
    results: arrayResults,
    "filePath": filePath
});

})
});


问:
What properties can I use with event.target?
I need to identify elements from which events are fired.

Using event.target gets the respective element.

What properties can I use from there?

href

id

nodeName

I cannot find a whole lot of info on it, even on the jQuery pages, so here is to hoping someone can complete the above list.

EDIT:

These may be helpful: selfHTML node properties and selfHTML HTML properties

答:
```<code>window.onclick = e => {
    console.dir(e.target);  // use this in chrome
    console.log(e.target);  // use this in firefox - click on tag name to view
}
</code>```

take advantage of using filter propeties

```<code>e.target.tagName
e.target.className
e.target.style.height  // its not the value applied from the css style sheet, to get that values use `getComputedStyle()`
</code>```

Body:
window.onclick = e => {
    console.dir(e.target);  // use this in chrome
    console.log(e.target);  // use this in firefox - click on tag name to view
}

take advantage of using filter propeties

e.target.tagName
e.target.className
e.target.style.height  // its not the value applied from the css style sheet, to get that values use `getComputedStyle()`


问:
Issue with updating field with embedded map in orientdb
I have a javascript function in orientdb studio(2.1.12) where I am trying to update field called "node" with json whose property is of type embeddedMap in uiJson Document/Class.Find the code below:

```<code> var dt = db.query("SELECT * from uijson");
    childUijson = dt[0].getRecord();
     node = childUijson.field('node');
     print(node )
    db.command('update uiJson set node=' + node + 'where @rid=18:1');
    return node;
       /*Print in oriendb console{0=inputs[{s_type=URL,source=,v_type=java.l,value=http://www.gmail.com}], next={0=1}, label=Open Url, type=OPEN_URL, component=FireFox, screenshot=false,chained=false,flowchartElement=startElement_1,left=0.12737921}}
*/
/*Return statement {
        "0": {
            "inputs": [
                {
                    "s_type": "URL",
                    "source": "",
                    "v_type": "java.lang.String",
                    "value": "http://localhost:8090/Automaton/"
                }
            ],
            "next": {
                "0": "1"
            },
            "label": "Open Url",
            "type": "OPEN_URL",
            "component": "FireFox",
            "screenshot": false,
            "chained": false,
            "flowchartElement": "startElement_1",
            "top": 0.4410876,
            "left": 0.12737921
        }
        "@type": "d",
        "@version": 0
    }*/
</code>```

Print and return uses the same variable node .While printing in the console it prints using java object tostring() while returning it gives as Json.Please help me in updating a field with Json of type embedded map.

```<code>Error message {
    "errors": [
        {
            "code": 500,
            "reason": 500,
            "content": "com.orientechnologies.orient.core.sql.OCommandSQLParsingException: Error on parsing command at position #0: Error parsing query: \nupdate uiJson set node={0={inputs=[{s_type=URL, source=, v_type=java.lang.String, value=http://www.gmail.com/}], next={0=1}, label=Open Url, type=OPEN_URL, component=FireFox, screenshot=false, chained=false, flowchartElement=startElement_1, top=0.4410876, left=0.12737921}}where @rid=18:1\nEncountered \" <INTEGER_LITERAL> \"0 \"\" at line 1, column 25.\r\nWas expecting one of:\r\n    <TO> ...\r\n    <VALUES> ...\r\n    <SET> ...\r\n    <ADD> ...\r\n    <PUT> ...\r\n    <MERGE> ...\r\n    <CONTENT> ...\r\n    <REMOVE> ...\r\n    <ORDER> ...\r\n    <GROUP> ...\r\n    <OFFSET> ...\r\n    <RECORD> ...\r\n    <LUCENE> ...\r\n    <NEAR> ...\r\n    <WITHIN> ...\r\n    <EXCEPTION> ...\r\n    <FIND> ...\r\n    <REFERENCES> ...\r\n    <RECORD_ATTRIBUTE> ...\r\n    <CHARACTER_LITERAL> ...\r\n    <STRING_LITERAL> ...\r\n    \"}\" ...\r\n    <IN> ...\r\n    <KEY> ...\r\n    <IDENTIFIER> ...\r\n    <QUOTED_IDENTIFIER> ...\r\n    "
        }
    ]
}
</code>```

答:
```<code>childUijson.field("node",node);
db.save();
db.commit();
</code>```

Solved my problem

Body:
I have a javascript function in orientdb studio(2.1.12) where I am trying to update field called "node" with json whose property is of type embeddedMap in uiJson Document/Class.Find the code below:

 var dt = db.query("SELECT * from uijson");
    childUijson = dt[0].getRecord();
     node = childUijson.field('node');
     print(node )
    db.command('update uiJson set node=' + node + 'where @rid=18:1');
    return node;
       /*Print in oriendb console{0=inputs[{s_type=URL,source=,v_type=java.l,value=http://www.gmail.com}], next={0=1}, label=Open Url, type=OPEN_URL, component=FireFox, screenshot=false,chained=false,flowchartElement=startElement_1,left=0.12737921}}
*/
/*Return statement {
        "0": {
            "inputs": [
                {
                    "s_type": "URL",
                    "source": "",
                    "v_type": "java.lang.String",
                    "value": "http://localhost:8090/Automaton/"
                }
            ],
            "next": {
                "0": "1"
            },
            "label": "Open Url",
            "type": "OPEN_URL",
            "component": "FireFox",
            "screenshot": false,
            "chained": false,
            "flowchartElement": "startElement_1",
            "top": 0.4410876,
            "left": 0.12737921
        }
        "@type": "d",
        "@version": 0
    }*/

Print and return uses the same variable node .While printing in the console it prints using java object tostring() while returning it gives as Json.Please help me in updating a field with Json of type embedded map.

Error message {
    "errors": [
        {
            "code": 500,
            "reason": 500,
            "content": "com.orientechnologies.orient.core.sql.OCommandSQLParsingException: Error on parsing command at position #0: Error parsing query: \nupdate uiJson set node={0={inputs=[{s_type=URL, source=, v_type=java.lang.String, value=http://www.gmail.com/}], next={0=1}, label=Open Url, type=OPEN_URL, component=FireFox, screenshot=false, chained=false, flowchartElement=startElement_1, top=0.4410876, left=0.12737921}}where @rid=18:1\nEncountered \" <INTEGER_LITERAL> \"0 \"\" at line 1, column 25.\r\nWas expecting one of:\r\n    <TO> ...\r\n    <VALUES> ...\r\n    <SET> ...\r\n    <ADD> ...\r\n    <PUT> ...\r\n    <MERGE> ...\r\n    <CONTENT> ...\r\n    <REMOVE> ...\r\n    <ORDER> ...\r\n    <GROUP> ...\r\n    <OFFSET> ...\r\n    <RECORD> ...\r\n    <LUCENE> ...\r\n    <NEAR> ...\r\n    <WITHIN> ...\r\n    <EXCEPTION> ...\r\n    <FIND> ...\r\n    <REFERENCES> ...\r\n    <RECORD_ATTRIBUTE> ...\r\n    <CHARACTER_LITERAL> ...\r\n    <STRING_LITERAL> ...\r\n    \"}\" ...\r\n    <IN> ...\r\n    <KEY> ...\r\n    <IDENTIFIER> ...\r\n    <QUOTED_IDENTIFIER> ...\r\n    "
        }
    ]
}

Body:
childUijson.field("node",node);
db.save();
db.commit();

Solved my problem


问:
How to align html elements on the same row
If you see the attachment below, three share buttons are not equally margined from the top. Tweet button didn't maintain the consistency, it is little bit up than the other two. How do I make all of them equally distanced from the top?

The code I am working on:

```<code>                            <h2 class="title">Share this blog</h2>

                            <div class="fb-share-button" data-href="http://alfa-blog.com/"
                                 data-layout="button_count" data-size="large" data-mobile-iframe="true">
                                <a class="fb-xfbml-parse-ignore" target="_blank"
                                   href="https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Falfa-blog.com%2Findex.html&src=sdkpreparse">Share</a>
                            </div>

                            <a href="https://twitter.com/share"
                               data-size="large"
                               class="twitter-share-button" data-show-count="false">Tweet</a>

                            <div class="g-plus" data-action="share" data-height="24" data-href="http://alfa-blog.com/"></div>
</code>```

答:
Since your css is missing I will assume that you use display:inline-block;, you probably forgot to include :

```<code>.your_icons {
    vertical-align:top;
}
</code>```

Body:
If you see the attachment below, three share buttons are not equally margined from the top. Tweet button didn't maintain the consistency, it is little bit up than the other two. How do I make all of them equally distanced from the top?

The code I am working on:

Share this blog

                                Share

                            Tweet

Body:
Since your css is missing I will assume that you use display:inline-block;, you probably forgot to include :

.your_icons {
    vertical-align:top;
}


问:
Difference between background-attachment:fixed and position : fixed
im a beginner in CSS , and i am confused with this 2 ... Who can explain me what is the difference between  background-attachment:fixed and position : fixed ??? </p>

答:
<!DOCTYPE html>

The background-image is fixed. Try to scroll down the page.

The background-image is fixed. Try to scroll down the page.

The background-image is fixed. Try to scroll down the page.

The background-image is fixed. Try to scroll down the page.

The background-image is fixed. Try to scroll down the page.

The background-image is fixed. Try to scroll down the page.

The background-image is fixed. Try to scroll down the page.

The background-image is fixed. Try to scroll down the page.

The background-image is fixed. Try to scroll down the page.

The background-image is fixed. Try to scroll down the page.

The background-image is fixed. Try to scroll down the page.

The background-image is fixed. Try to scroll down the page.

The background-image is fixed. Try to scroll down the page.

The background-image is fixed. Try to scroll down the page.

The background-image is fixed. Try to scroll down the page.

If you do not see any scrollbars, try to resize the browser window.

```

Background-attachment:fixed is for positioning an Image where as , position :fixed; is for elements like p ,span ,div.

Body:
<!DOCTYPE html>
<html>
<head>
<style>
body  {
    background-image: url('w3css.gif');
    background-repeat: no-repeat;
    background-attachment: fixed;
}
p{
position: fixed;
color:Red;
}
</style>
</head>
<body>

<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>

<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>If you do not see any scrollbars, try to resize the browser window.</p>

</body>
</html>

Background-attachment:fixed is for positioning an Image where as , position :fixed; is for elements like p ,span ,div.


答:
Use a disable option 'SELECT' on the select option
Try this

```<code><?php
if(!isset($_POST['floor_id']))
{
    $fl = 'floor_id';
    $_POST['floor_id'] = $fl;
}

$query = "SELECT id,floor from sdh_extension.tb_floor";

$selectbox='<select name="floor_id" class="form-control"
onchange="this.form.submit()"> <option value=""  disabled>SELECT</option>"';
foreach ($db->query($query) as $row)
{
    $id=$row['id'];
    $name=$row['floor'];

    if($row['id'] == $_POST['floor_id'])
    {

        $isSelected = ' selected="selected"';
    }
    else {
        $isSelected = '';
    }
    $selectbox.= "
   <optionvalue=".$id.$isSelected.">".$name."</option>";
}
    $selectbox.='</select>';
    echo $selectbox;
?>
</code>```

Title: How to display [please select] on select box, instead of first item on selectbox in php?

Body:
Use a disable option 'SELECT' on the select option
Try this

<?php
if(!isset($_POST['floor_id']))
{
    $fl = 'floor_id';
    $_POST['floor_id'] = $fl;
}

$query = "SELECT id,floor from sdh_extension.tb_floor";

$selectbox='<select name="floor_id" class="form-control"
onchange="this.form.submit()"> <option value=""  disabled>SELECT</option>"';
foreach ($db->query($query) as $row)
{
    $id=$row['id'];
    $name=$row['floor'];

    if($row['id'] == $_POST['floor_id'])
    {

        $isSelected = ' selected="selected"';
    }
    else {
        $isSelected = '';
    }
    $selectbox.= "
   <optionvalue=".$id.$isSelected.">".$name."</option>";
}
    $selectbox.='</select>';
    echo $selectbox;
?>


问:
JavaScript - Find an object among an array of objects, inside an array of objects
I'm using Vue, lodash, etc.

```<code>{
  "street": {
    "id": "1",
    "streetName": "test",
    "buildings": [
      {
        "id": "1",
        "buildingName": "test"
      }
    ]
  }
}
</code>```

I have a setup similar to this. This is a singular object, I basically have an array of these.

All I get is a building.id value.

From it, I need to be able to find the building it belongs to, and there isn't any direct list of buildings for me to access.

Currently

I'm using a nested loop to loop through each site until I find the one that has a building with that id. I don't know if I'm doing it correctly, it doesn't feel correct.

```<code>for(var i = 0; i < streets.length; i++){
    for(var x = 0; x < streets[i].buildings.length;x++){
        if(streets[i].buildings[x].id == '2aec6bed-8cdd-4043-9041-3db4681c6d08'){

        }
    }
}
</code>```

Any tips? Thanks.

答:
If you're trying to get all the buildings in all streets by a buildingId, this solves the problem:

```<code>streetsList.map(streetItem => streetItem.street.buildings.find(building => building.id === searchedBuildingId)).filter(v => v);
</code>```

.filter(v => v) is for filtering out falsy values since we want a clean result here.

If there can be more than a single building in a street with the same id, then use .some instead of .find in the example.

Body:
I'm using Vue, lodash, etc.

{
  "street": {
    "id": "1",
    "streetName": "test",
    "buildings": [
      {
        "id": "1",
        "buildingName": "test"
      }
    ]
  }
}

I have a setup similar to this. This is a singular object, I basically have an array of these.

All I get is a building.id value.

From it, I need to be able to find the building it belongs to, and there isn't any direct list of buildings for me to access.

Currently

I'm using a nested loop to loop through each site until I find the one that has a building with that id. I don't know if I'm doing it correctly, it doesn't feel correct.

for(var i = 0; i < streets.length; i++){
    for(var x = 0; x < streets[i].buildings.length;x++){
        if(streets[i].buildings[x].id == '2aec6bed-8cdd-4043-9041-3db4681c6d08'){

        }
    }
}

Any tips? Thanks.

Body:
If you're trying to get all the buildings in all streets by a buildingId, this solves the problem:

streetsList.map(streetItem => streetItem.street.buildings.find(building => building.id === searchedBuildingId)).filter(v => v);

.filter(v => v) is for filtering out falsy values since we want a clean result here.

If there can be more than a single building in a street with the same id, then use .some instead of .find in the example.


问:
how to create two rounded bordered uiimage in swift
Could anyone suggest me how could I create two rounded border uiimage like shown in this picture.

Is there any available library that I could use?

答:
you can use below func

```<code>    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.viewPicture.layer.cornerRadius = self.viewPicture.frame.size.height/2
    self.ivPicture.layer.cornerRadius = self.ivPicture.frame.size.height/2

}

override func viewWillAppear(_ animated: Bool) {
    self.addviewBGBezier(self.viewBG)
    self.addviewPicBezier(self.viewPicture)
}

func addviewBGBezier(_ viewMy : UIView)  {
    let layer = CAShapeLayer()
    let path = UIBezierPath()

    path.move(to: CGPoint(x: 0, y: viewMy.frame.size.height))
    path.addLine(to: CGPoint(x: viewMy.frame.size.width, y: 140))
    path.addLine(to: CGPoint(x: viewMy.frame.size.width, y: viewMy.frame.size.height))
    path.close()
    layer.path = path.cgPath
    layer.fillColor = UIColor.white.cgColor

    viewMy.layer.addSublayer(layer)
}

func addviewPicBezier(_ viewMy : UIView)  {
    let layerLower = CAShapeLayer()

    let center = CGPoint(x: viewMy.frame.size.width/2, y: viewMy.frame.size.height/2)
    print("cal center : \(center)")

    let path = UIBezierPath(arcCenter: center,
                            radius: viewMy.frame.size.width/2,
                            startAngle: CGFloat(-Double.pi/10.35), endAngle: CGFloat(Double.pi), clockwise: true)

    layerLower.path = path.cgPath
    layerLower.fillColor = UIColor.clear.cgColor
    layerLower.strokeColor = UIColor.cyan.cgColor
    layerLower.lineWidth = 20
    viewMy.layer.addSublayer(layerLower)

    let layerUpper = CAShapeLayer()

    let pathUpper = UIBezierPath(arcCenter: center,
                            radius: viewMy.frame.size.width/2,
                            startAngle: CGFloat(-Double.pi/10.35), endAngle: CGFloat(Double.pi), clockwise: false)

    layerUpper.path = pathUpper.cgPath
    layerUpper.fillColor = UIColor.clear.cgColor
    layerUpper.strokeColor = UIColor.cyan.cgColor
    layerUpper.lineWidth = 20
    viewMy.layer.addSublayer(layerUpper)

}
</code>```

Output

After chnging the below line

```<code>layerLower.strokeColor = UIColor.white.cgColor
</code>```

Output is:

Body:
you can use below func

    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.viewPicture.layer.cornerRadius = self.viewPicture.frame.size.height/2
    self.ivPicture.layer.cornerRadius = self.ivPicture.frame.size.height/2

}

override func viewWillAppear(_ animated: Bool) {
    self.addviewBGBezier(self.viewBG)
    self.addviewPicBezier(self.viewPicture)
}

func addviewBGBezier(_ viewMy : UIView)  {
    let layer = CAShapeLayer()
    let path = UIBezierPath()

    path.move(to: CGPoint(x: 0, y: viewMy.frame.size.height))
    path.addLine(to: CGPoint(x: viewMy.frame.size.width, y: 140))
    path.addLine(to: CGPoint(x: viewMy.frame.size.width, y: viewMy.frame.size.height))
    path.close()
    layer.path = path.cgPath
    layer.fillColor = UIColor.white.cgColor

    viewMy.layer.addSublayer(layer)
}

func addviewPicBezier(_ viewMy : UIView)  {
    let layerLower = CAShapeLayer()

    let center = CGPoint(x: viewMy.frame.size.width/2, y: viewMy.frame.size.height/2)
    print("cal center : \(center)")

    let path = UIBezierPath(arcCenter: center,
                            radius: viewMy.frame.size.width/2,
                            startAngle: CGFloat(-Double.pi/10.35), endAngle: CGFloat(Double.pi), clockwise: true)

    layerLower.path = path.cgPath
    layerLower.fillColor = UIColor.clear.cgColor
    layerLower.strokeColor = UIColor.cyan.cgColor
    layerLower.lineWidth = 20
    viewMy.layer.addSublayer(layerLower)

    let layerUpper = CAShapeLayer()

    let pathUpper = UIBezierPath(arcCenter: center,
                            radius: viewMy.frame.size.width/2,
                            startAngle: CGFloat(-Double.pi/10.35), endAngle: CGFloat(Double.pi), clockwise: false)

    layerUpper.path = pathUpper.cgPath
    layerUpper.fillColor = UIColor.clear.cgColor
    layerUpper.strokeColor = UIColor.cyan.cgColor
    layerUpper.lineWidth = 20
    viewMy.layer.addSublayer(layerUpper)

}

Output

After chnging the below line

layerLower.strokeColor = UIColor.white.cgColor

Output is:


答:
You can use a combination of filter and some methods, like this:

```<code>var result = streets.filter(function(s) {
  return s.street.buildings.some(function(b) {
    return b.id === searchedId;
  });
});
</code>```

Using .some() method will return true if any building of the iterated buildings has the searchedId.

Using .filter() will filter the streets array to return only street object where the call of some() method on its buildings will return true, in other words which meets the condition of having an idequal to searchedId.

Demo:

var streets = [{
  "street": {
    "id": "1",
    "streetName": "test",
    "buildings": [{
      "id": "1",
      "buildingName": "test"
    }]
  }
}, {
  "street": {
    "id": "1",
    "streetName": "test",
    "buildings": [{
      "id": '2aec6bed-8cdd-4043-9041-3db4681c6d08',
      "buildingName": "test"
    }]
  }
}];
var searchedId = '2aec6bed-8cdd-4043-9041-3db4681c6d08';

var result = streets.filter(function(s) {
  return s.street.buildings.some(function(b) {
    return b.id === searchedId;
  });
});
console.log(result);```

Title: JavaScript - Find an object among an array of objects, inside an array of objects

Body:
You can use a combination of filter and some methods, like this:

var result = streets.filter(function(s) {
  return s.street.buildings.some(function(b) {
    return b.id === searchedId;
  });
});

Using .some() method will return true if any building of the iterated buildings has the searchedId.

Using .filter() will filter the streets array to return only street object where the call of some() method on its buildings will return true, in other words which meets the condition of having an idequal to searchedId.

Demo:

var streets = [{
  "street": {
    "id": "1",
    "streetName": "test",
    "buildings": [{
      "id": "1",
      "buildingName": "test"
    }]
  }
}, {
  "street": {
    "id": "1",
    "streetName": "test",
    "buildings": [{
      "id": '2aec6bed-8cdd-4043-9041-3db4681c6d08',
      "buildingName": "test"
    }]
  }
}];
var searchedId = '2aec6bed-8cdd-4043-9041-3db4681c6d08';

var result = streets.filter(function(s) {
  return s.street.buildings.some(function(b) {
    return b.id === searchedId;
  });
});
console.log(result);


问:
Xamarin Android deployment not using the latest code?
I'm creating an Android app in Visual Studio. When I create the aligned APK to side load on my device (from the Tools -> Android -> Publish Android App), it installs and runs, but doesn't seem to have the very latest changes. The series of events I've experienced is as follows:

Installed a version of the app on my device

Updated a color on the login page and set the application theme (among other things)

Re-installed the app

Saw the new theme but not the new color on the login page

Made a random text change on the login page as a test

Re-installed the app

Saw the color change but not the random text change?!

Any suggestions on what I might be doing wrong?

答:
In my case, I had a similar problem with connected device, and no one proposed solution like Clean\Rebuild\Restart\Reinstall\etc could help me.
At the same time on the AVD everything worked perfectly, latest code deployed ok.

I found that asked issue depended on selected settings in the [USB Developer] section on the connected device (mine was Xiaomi smartphone). Because some vendors provide us with too many security settings...

What I found, you have to turn on both USB Debugging & USB debugging (Security settings), and turn off MIUI Optimization (it's true for Xiaomi vendor, but you can check your device for similar options). Hope this helps.


问:
Problems displaying code with js and underscore.js
I have this code below and I want to use undercorejs in order to display the text from the json file.  I need to modify the section, as it seen below the comment, to be like that:

I have tried to duplicate it but it causes errors and does not display anything. Any suggestions? Sorry, if that's a silly question but im new to programming.

hold.options (tooltips object) = {
       (property based on the section generated automatically): {
        (properly based on the itemName generated automatically): {
             t: item.Texts,

          }
        }

```<code>var log = function(contents) {
  if (_.isArray(contents)) {
    _.each(contents, function(e, i, l) {
      log(e);
      $('#result');
      $('#result').append('</br></br>');
    });
  } else {
    $('#result').append(contents);
  }
};

var ty = [{
  "Language": "en-GB",
  "Section": "Sales&Marketing",
  "ItemName": "CalculationType",
  "Texts": "Having selected the account heading select the calculation ..."
}, {
  "Language": "en-GB",
  "Section": "Taxes",
  "ItemName": "Save",
  "Texts": "The Master Tax Table has been pre populated with the current UK, ..."
}];
var out = [];
_.each(ty, function(item, key) {
  var hold = {};

//Part that needs to change
  hold.options = {
    Taxes: {
      Save: {
        t: item.Texts,
      }
    }
  };
  out.push(hold)
});
_.each(out, function(item) {
  log(item.options.Taxes.Save.t + '<br>');
})
</code>```

答:
This seems to work:

Fiddle

```<code>//Part that needs to change
  hold.options = {};
  hold.options[item.Section] = {};
  hold.options[item.Section][item.ItemName] = {t: item.Texts};
  out.push(hold)
});
_.each(out, function(item) {
  if(item.options.Sales !== undefined && item.options.Sales.Type !== undefined){
    log(item.options.Sales.Type.t);
  }
  else if(item.options.Taxes !== undefined && item.options.Taxes.Save !== undefined){
    log(item.options.Taxes.Save.t);
  }
</code>```

Body:
I have this code below and I want to use undercorejs in order to display the text from the json file.  I need to modify the section, as it seen below the comment, to be like that:

I have tried to duplicate it but it causes errors and does not display anything. Any suggestions? Sorry, if that's a silly question but im new to programming.

hold.options (tooltips object) = {
       (property based on the section generated automatically): {
        (properly based on the itemName generated automatically): {
             t: item.Texts,

          }
        }

var log = function(contents) {
  if (_.isArray(contents)) {
    _.each(contents, function(e, i, l) {
      log(e);
      $('#result');
      $('#result').append('

');
    });
  } else {
    $('#result').append(contents);
  }
};

var ty = [{
  "Language": "en-GB",
  "Section": "Sales&Marketing",
  "ItemName": "CalculationType",
  "Texts": "Having selected the account heading select the calculation ..."
}, {
  "Language": "en-GB",
  "Section": "Taxes",
  "ItemName": "Save",
  "Texts": "The Master Tax Table has been pre populated with the current UK, ..."
}];
var out = [];
_.each(ty, function(item, key) {
  var hold = {};

//Part that needs to change
  hold.options = {
    Taxes: {
      Save: {
        t: item.Texts,
      }
    }
  };
  out.push(hold)
});
_.each(out, function(item) {
  log(item.options.Taxes.Save.t + '
');
})

Body:
This seems to work:

Fiddle

//Part that needs to change
  hold.options = {};
  hold.options[item.Section] = {};
  hold.options[item.Section][item.ItemName] = {t: item.Texts};
  out.push(hold)
});
_.each(out, function(item) {
  if(item.options.Sales !== undefined && item.options.Sales.Type !== undefined){
    log(item.options.Sales.Type.t);
  }
  else if(item.options.Taxes !== undefined && item.options.Taxes.Save !== undefined){
    log(item.options.Taxes.Save.t);
  }


问:
CELERYD_CONCURRENCY, --concurrency and autoscale
I have a few questions regarding task routing, concurrency and performance.
Here is my use case :

I've got one dedicated server to run celery tasks, so I can use all the CPUs to run celery workers on this server.

I have a lot of different python tasks, which I route using : CELERY_ROUTES and because the tasks perform really different types of python code, I created 5 different workers.
These worker are created when I deploy my project using ansible, here is an example:

```<code>[program:default_queue-celery]
command={{ venv_dir }}/bin/celery worker --app=django_coreapp --loglevel=INFO --concurrency=1 --autoscale=15,10 --queues=default_queue
environment =
    SERVER_TYPE="{{ SERVER_TYPE }}",
    DB_SCHEMA="{{ DB_SCHEMA }}",
    DB_USER="{{ DB_USER }}",
    DB_PASS="{{ DB_PASS }}",
    DB_HOST="{{ DB_HOST }}"
directory={{ git_dir }}
user={{ user }}
group={{ group }}
stdout_logfile={{ log_dir }}/default_queue.log
stdout_logfile_maxbytes=50MB
stdout_logfile_backups=5
redirect_stderr=true
autostart=true
autorestart=true
startsecs=10
killasgroup=true
</code>```

I have also a CELERY_QUEUES in settings.py to make the bridge between CELERY_ROUTES and my celery programs (Queues)

```<code>CELERY_DEFAULT_QUEUE = 'default_queue'
</code>```

And if it happens that I don't route a task it will go to my 'default_queue'

To give space to all of my queues, I set --concurrency to 1 for default_queue, and more for my most important queue.

But I am wondering, does AutoScale have impact on the same value as concurrency ? Meaning, if I set concurrency to 1 and --autoscale to 15,10 (example above)

Will my worker 'work' on CPU and process a maximum of 15 tasks on this CPU ?
Or does this mean something completely different ?

答:
It makes no sense setting both concurrency and autoscale since both are means to control the number of worker subprocesses for a given worker instance, as explained here.

--concurrency N means you will have exactly N worker subprocesses for your worker instance (meaning the worker instance can handle N conccurent tasks).

--autoscale max, min means you will have at least min and at most  max concurrent worker subprocesses for a given worker instance.

On which CPU each process (the main worker process or any of it's child subprocesses) will run is not predictable, it's an OS thing, but do not assume subprocesses will all run on the same CPU (chances are they won't - that's part of the point of having concurrent subprocesses actually).

Body:
I have a few questions regarding task routing, concurrency and performance.
Here is my use case :

I've got one dedicated server to run celery tasks, so I can use all the CPUs to run celery workers on this server.

I have a lot of different python tasks, which I route using : CELERY_ROUTES and because the tasks perform really different types of python code, I created 5 different workers.
These worker are created when I deploy my project using ansible, here is an example:

[program:default_queue-celery]
command={{ venv_dir }}/bin/celery worker --app=django_coreapp --loglevel=INFO --concurrency=1 --autoscale=15,10 --queues=default_queue
environment =
    SERVER_TYPE="{{ SERVER_TYPE }}",
    DB_SCHEMA="{{ DB_SCHEMA }}",
    DB_USER="{{ DB_USER }}",
    DB_PASS="{{ DB_PASS }}",
    DB_HOST="{{ DB_HOST }}"
directory={{ git_dir }}
user={{ user }}
group={{ group }}
stdout_logfile={{ log_dir }}/default_queue.log
stdout_logfile_maxbytes=50MB
stdout_logfile_backups=5
redirect_stderr=true
autostart=true
autorestart=true
startsecs=10
killasgroup=true

I have also a CELERY_QUEUES in settings.py to make the bridge between CELERY_ROUTES and my celery programs (Queues)

CELERY_DEFAULT_QUEUE = 'default_queue'

And if it happens that I don't route a task it will go to my 'default_queue'

To give space to all of my queues, I set --concurrency to 1 for default_queue, and more for my most important queue.

But I am wondering, does AutoScale have impact on the same value as concurrency ? Meaning, if I set concurrency to 1 and --autoscale to 15,10 (example above)

Will my worker 'work' on CPU and process a maximum of 15 tasks on this CPU ?
Or does this mean something completely different ?


问:
Matching TV and Movie File names with NLP/Machine Learning?
So i've wondered if there would be a way to tokenize/tag TV or Movie Files using NLP/Machine Learing.

I know there are a lot of regexp approaches out there which do this already but shouldn't it be possible to get this done with NLP/Machine Learning as well?

Example:
The.Heart.Guy.S01E07.Die.Belastungsprobe.German.DL.720p.HDTV.x264-GDR

Should be something like:

The Heart Guy SHOW-NAME
1 SEASON
7 EPISODE
Die Belastungsprobe EP-NAME
German DL LANGUAGE
720p RESOLUTION
HDTV SOURCE
x264 CODEC
GDR GROUP

Anyone ever tried something like this? Or any hints where one should start or if it's even possible to get something like this working.

答: Machine learning approaches would cost more than rule-based approaches. But if you want to try a machine learning solution the best solution that comes to my mind is to use markov models as the problem has sequential observations and you can handle it with finite state automatas. You can use this paper as a reference.</p>


问:
What does graph argument in tf.Session() do?
I am having trouble understanding the graph argument in the tf.Session(). I tried looking up at the TensorFlow website :link but couldn't understand much.

I am trying to find out the different between tf.Session() and tf.Session(graph=some_graph_inserted_here).

Question Context

Code A (Not Working):

```<code>def predict():
    with tf.name_scope("predict"):
        with tf.Session() as sess:
            saver = tf.train.import_meta_graph("saved_models/testing.meta")
            saver.restore(sess, "saved_models/testing")
            loaded_graph = tf.get_default_graph()
            output_ = loaded_graph.get_tensor_by_name('loss/network/output_layer/BiasAdd:0')
            _x = loaded_graph.get_tensor_by_name('x:0')
            print sess.run(output_, feed_dict={_x: np.array([12003]).reshape([-1, 1])})
</code>```

This code gives the following error: ValueError: cannot add op with name hidden_layer1/kernel/Adam as that name is already used when trying to load the graph at saver = tf.train.import_meta_graph("saved_models/testing.meta")

Code B (Working):

```<code>def predict():
    with tf.name_scope("predict"):
        loaded_graph = tf.Graph()
        with tf.Session(graph=loaded_graph) as sess:
            saver = tf.train.import_meta_graph("saved_models/testing.meta")
            saver.restore(sess, "saved_models/testing")
            output_ = loaded_graph.get_tensor_by_name('loss/network/output_layer/BiasAdd:0')
            _x = loaded_graph.get_tensor_by_name('x:0')
            print sess.run(output_, feed_dict={_x: np.array([12003]).reshape([-1, 1])})
</code>```

The codes does not work if I replace loaded_graph = tf.Graph() with loaded_graph = tf.get_default_graph(). Why?

Full Code if it helps:
 (https://gist.github.com/duemaster/f8cf05c0923ebabae476b83e895619ab)

答:
The TensorFlow Graph is an object which contains your various tf.Tensor and tf.Operation.

When you create these tensors (e.g. using tf.Variable or tf.constant) or operations (e.g. tf.matmul), they will be added to the default graph (look at the graph member of these object to get the graph they belong to).  If you haven't specified anything, it will be the graph you get when calling the tf.get_default_graph method.

But you could also work with multiple graphes using a context manager:

```<code>g = tf.Graph()
with g.as_default():
    [your code]
</code>```

Suppose you created several graphes in your code, you then need to put the graph you and to run as an argument of the tf.Session method to specify TensorFlow which one to run.

In Code A, you

work with the default graph,

try to import the meta graph into it (which fails because it already contains some of the nodes) and,

would restore the model into it,

while in Code B, you

create a fresh new graph,

import the meta graph into it (which succeeds because it's an empty graph) and

restore it.

Useful link:

tf.Graph API

Edit:

This piece of code makes the Code A work (I reset the default graph to a fresh one, and I removed the predict name_scope).

```<code>def predict():
    tf.reset_default_graph()
    with tf.Session() as sess:
        saver = tf.train.import_meta_graph("saved_models/testing.meta")
        saver.restore(sess, "saved_models/testing")
        loaded_graph = tf.get_default_graph()
        output_ = loaded_graph.get_tensor_by_name('loss/network/output_layer/BiasAdd:0')
        _x = loaded_graph.get_tensor_by_name('x:0')
        print(sess.run(output_, feed_dict={_x: np.array([12003]).reshape([-1, 1])}))
</code>```

Body:
I am having trouble understanding the graph argument in the tf.Session(). I tried looking up at the TensorFlow website :link but couldn't understand much.

I am trying to find out the different between tf.Session() and tf.Session(graph=some_graph_inserted_here).

Question Context

Code A (Not Working):

def predict():
    with tf.name_scope("predict"):
        with tf.Session() as sess:
            saver = tf.train.import_meta_graph("saved_models/testing.meta")
            saver.restore(sess, "saved_models/testing")
            loaded_graph = tf.get_default_graph()
            output_ = loaded_graph.get_tensor_by_name('loss/network/output_layer/BiasAdd:0')
            _x = loaded_graph.get_tensor_by_name('x:0')
            print sess.run(output_, feed_dict={_x: np.array([12003]).reshape([-1, 1])})

This code gives the following error: ValueError: cannot add op with name hidden_layer1/kernel/Adam as that name is already used when trying to load the graph at saver = tf.train.import_meta_graph("saved_models/testing.meta")

Code B (Working):

def predict():
    with tf.name_scope("predict"):
        loaded_graph = tf.Graph()
        with tf.Session(graph=loaded_graph) as sess:
            saver = tf.train.import_meta_graph("saved_models/testing.meta")
            saver.restore(sess, "saved_models/testing")
            output_ = loaded_graph.get_tensor_by_name('loss/network/output_layer/BiasAdd:0')
            _x = loaded_graph.get_tensor_by_name('x:0')
            print sess.run(output_, feed_dict={_x: np.array([12003]).reshape([-1, 1])})

The codes does not work if I replace loaded_graph = tf.Graph() with loaded_graph = tf.get_default_graph(). Why?

Full Code if it helps:
 (https://gist.github.com/duemaster/f8cf05c0923ebabae476b83e895619ab)

Body:
The TensorFlow Graph is an object which contains your various tf.Tensor and tf.Operation.

When you create these tensors (e.g. using tf.Variable or tf.constant) or operations (e.g. tf.matmul), they will be added to the default graph (look at the graph member of these object to get the graph they belong to).  If you haven't specified anything, it will be the graph you get when calling the tf.get_default_graph method.

But you could also work with multiple graphes using a context manager:

g = tf.Graph()
with g.as_default():
    [your code]

Suppose you created several graphes in your code, you then need to put the graph you and to run as an argument of the tf.Session method to specify TensorFlow which one to run.

In Code A, you

work with the default graph,

try to import the meta graph into it (which fails because it already contains some of the nodes) and,

would restore the model into it,

while in Code B, you

create a fresh new graph,

import the meta graph into it (which succeeds because it's an empty graph) and

restore it.

Useful link:

tf.Graph API

Edit:

This piece of code makes the Code A work (I reset the default graph to a fresh one, and I removed the predict name_scope).

def predict():
    tf.reset_default_graph()
    with tf.Session() as sess:
        saver = tf.train.import_meta_graph("saved_models/testing.meta")
        saver.restore(sess, "saved_models/testing")
        loaded_graph = tf.get_default_graph()
        output_ = loaded_graph.get_tensor_by_name('loss/network/output_layer/BiasAdd:0')
        _x = loaded_graph.get_tensor_by_name('x:0')
        print(sess.run(output_, feed_dict={_x: np.array([12003]).reshape([-1, 1])}))


问:
Selecting a resource programatically in Eclipse does not expand tree
I have the following problem with my RCP Eclipse application: I am trying to set selection on an IResource within a Project Explorer tree.
Code I am using is:

```
final IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
final IViewPart viewPart = page.findView(IPageLayout.ID_PROJECT_EXPLORER);
final ISelectionProvider selProvider = viewPart.getSite().getSelectionProvider();
selProvider.setSelection(new StructuredSelection(mrcReportRuleOccurrence.getIResource()));
```

The code seems to work only if the leaf was already once expanded in the tree. If the tree is completely collapsed, the code does not make eclipse expand the containing folder and select the desired file in the project explorer. Does anyone know how to bring this about?

答:
You could try checking if the selection provider is a Viewer and using the setSelection(selection. reveal) method:

```<code>if (selProvider instanceof Viewer) {
  ((Viewer)selProvider).setSelection(selection, true);
}
</code>```

It may also be necessary to use a TreeSelection with a TreePath for the selection rather than just StructuredSelection.

```<code>TreePath path = new TreePath(.... array of objects ...);

TreeSelection selection = new TreeSelection(path);
</code>```

Where 'array of objects' is the path through the tree to the resource.

But selecting items in the tree of a different view is not what the ISelectionProvider interface is for. There is no guarantee that this can be done using this interface.

Body:
I have the following problem with my RCP Eclipse application: I am trying to set selection on an IResource within a Project Explorer tree.
Code I am using is:

final IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
final IViewPart viewPart = page.findView(IPageLayout.ID_PROJECT_EXPLORER);
final ISelectionProvider selProvider = viewPart.getSite().getSelectionProvider();
selProvider.setSelection(new StructuredSelection(mrcReportRuleOccurrence.getIResource()));

The code seems to work only if the leaf was already once expanded in the tree. If the tree is completely collapsed, the code does not make eclipse expand the containing folder and select the desired file in the project explorer. Does anyone know how to bring this about?

Body:
You could try checking if the selection provider is a Viewer and using the setSelection(selection. reveal) method:

if (selProvider instanceof Viewer) {
  ((Viewer)selProvider).setSelection(selection, true);
}

It may also be necessary to use a TreeSelection with a TreePath for the selection rather than just StructuredSelection.

TreePath path = new TreePath(.... array of objects ...);

TreeSelection selection = new TreeSelection(path);

Where 'array of objects' is the path through the tree to the resource.

But selecting items in the tree of a different view is not what the ISelectionProvider interface is for. There is no guarantee that this can be done using this interface.


答:
You can use

float:left; and individual margin and padding in css for each socio div

or absolute position for these elements

Title: How to align html elements on the same row


问:
Whatsapp sharing doesn't work on IOS
I'm developing an app across Gluon Mobile plugin on JavaFX and I integrated a whatsapp sharing, but when I try to use it on IOS doesn't work, on Android device the list of whatsapp contacts are displayed and the function works correctly.
To implement that, after some researches,I added on .plist file this key:

```<code><key>LSApplicationQueriesSchemes</key>
    <array>
          <string>whatsapp</string>
</code>```

and     I used this code to open whatsapp from browser:

```<code>String whatsappUrl = "whatsapp://send?text=\\"; service.launchExternalBrowser(whatsappUrl+ myUrl);
</code>```

where myUrl is the url that I want to join by whatsapp.

Can anyone helps to solve this problem on IOS?
Thank you in advance.

答: I solved, the error was in the prefix whatsapp://send?text=\ , I changed it in whatsapp://send?text= and it works.</p>

Title: Whatsapp sharing doesn't work on IOS

Body:
I'm developing an app across Gluon Mobile plugin on JavaFX and I integrated a whatsapp sharing, but when I try to use it on IOS doesn't work, on Android device the list of whatsapp contacts are displayed and the function works correctly.
To implement that, after some researches,I added on .plist file this key:

<key>LSApplicationQueriesSchemes</key>
    <array>
          <string>whatsapp</string>

and     I used this code to open whatsapp from browser:

String whatsappUrl = "whatsapp://send?text=\\"; service.launchExternalBrowser(whatsappUrl+ myUrl);

where myUrl is the url that I want to join by whatsapp.

Can anyone helps to solve this problem on IOS?
Thank you in advance.


答:
In Tensorflow, you are constructing graphs. By default, Tensorflow creates a default (sorry for tautology) graph (which you could access using tf.get_default_graph()). By default, any new Session object uses this default graph.

In your case, you already have a graph (which is a default one), and you also saved exactly this graph into meta file. Then, you are trying to recover this graph using tf.train.import_meta_graph(). However, since your session uses a default graph, and you are trying to recover an identical one, you are encountering an error since this operation is trying to duplicate the nodes, which is forbidden.

When you explicitly create a new graph object by calling tf.Graph() and create a Session object using this graph (but not the default one) everything is fine since the nodes are created in another graph.

Title: What does graph argument in tf.Session() do?


问:
Dynamic typecasting in asp.net mvc Edit action: how can I handle multiple datatypes without throwing an exception?
I'm making a generic MVC viewer/editor for data objects I've designed, modeled after ActiveRecord.

The data objects are completely generic, they can have primary keys that are strings, ints, int16s, whatever the database uses (the persistence layer at this organization uses all sorts of datatypes for primary keys and I want this MVC "browser/editor" to handle them all).

Creating the Edit links in the Index view is easy:

```<code>Response.Write("<td>" + Html.ActionLink("Edit", "Edit", new { id = pkValue }) + "</td>");
</code>```

The problem is on the other side, in the Edit action:

```<code>public ActionResult Edit(object id)
</code>```

Anything other than a string throws an exception when I try to use id as the sole element of an array of parameters to a static "select" method invoked via reflection to retrieve a hydrated data object to edit from the database:

```<code>object[] parameters = { id };
list = (List<T>)select.Invoke(null, parameters);
</code>```

I know the CLR type of the parameter, and I know the "real" type of object id. Am I supposed to use some kind of gnarly case statement to do the type conversion manually, or is there a trick I can use to do the type conversion using the type of the parameter?

Can/Should I overload the ActionResult Edit() to take int, int16, int32, etc?

What should I do here to ensure that no matter the "real" type of id, I can pass it into the database without an exception being thrown?

Here's what I've tried so far:

I made my generic controller take two type parameters, one for the data object and another for the primary key datatype:

```<code>public class CoreDataController<t,T> : Controller  where T:IDataObjectBase<T>
</code>```

Then I tried this move:

```<code>id = (t)id;
object[] parameters = { id};
</code>```

BZZZRT! "the specified cast is invalid". id is "2" and t is int?

答:
Can you supply more code details for the select method and the Stored Proc or Query that you are executing to the pull data.

I would currently suggest to pass the value of id parameter to select in the following manner.

```<code>if(id != null)
  Select(id.ToString());
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm making a generic MVC viewer/editor for data objects I've designed, modeled after ActiveRecord.

The data objects are completely generic, they can have primary keys that are strings, ints, int16s, whatever the database uses (the persistence layer at this organization uses all sorts of datatypes for primary keys and I want this MVC "browser/editor" to handle them all).

Creating the Edit links in the Index view is easy:

Response.Write("" + Html.ActionLink("Edit", "Edit", new { id = pkValue }) + "	");

The problem is on the other side, in the Edit action:

public ActionResult Edit(object id)

Anything other than a string throws an exception when I try to use id as the sole element of an array of parameters to a static "select" method invoked via reflection to retrieve a hydrated data object to edit from the database:

object[] parameters = { id };
list = (List<T>)select.Invoke(null, parameters);

I know the CLR type of the parameter, and I know the "real" type of object id. Am I supposed to use some kind of gnarly case statement to do the type conversion manually, or is there a trick I can use to do the type conversion using the type of the parameter?

Can/Should I overload the ActionResult Edit() to take int, int16, int32, etc?

What should I do here to ensure that no matter the "real" type of id, I can pass it into the database without an exception being thrown?

Here's what I've tried so far:

I made my generic controller take two type parameters, one for the data object and another for the primary key datatype:

public class CoreDataController<t,T> : Controller  where T:IDataObjectBase<T>

Then I tried this move:

id = (t)id;
object[] parameters = { id};

BZZZRT! "the specified cast is invalid". id is "2" and t is int?

Body:
Can you supply more code details for the select method and the Stored Proc or Query that you are executing to the pull data.

I would currently suggest to pass the value of id parameter to select in the following manner.

if(id != null)
  Select(id.ToString());