问:
ElasticSearch-Kibana : filter array by key
I have data with one parameter which is an array. I know that objects in array are not well supported in Kibana, however I would like to know if there is a way to filter that array with only one value for the key. I mean :

This is a json for exemple :

```<code>{
  "_index": "index",
  "_type": "data",
  "_id": "8",
  "_version": 2,
  "_score": 1,
  "_source": {
    "envelope": {
      "version": "0.0.1",
      "submitter": "VF12RBU1D53087510",
      "MetaData": {
        "SpecificMetaData": [
          {
            "key": "key1",
            "value": "94"
          },
          {
            "key": "key2",
            "value": "0"
          }
        ]
      }
    }
  }
}
</code>```

And I would like to only have the data which contains key1 in my SpecificMetaData array in order to plot them. For now, when I plot SpecificMetaData.value it takes all the values of the array (value of key1 and key2) and doesn't propose SpecificMetaData.value1 and  SpecificMetaData.value2.

If you need more information, tell me. Thank you.

答:
you may need to map your data to mappings so as SpecificMetaData should act as nested_type and inner_hits of nested filter can supply you with objects which have key1.</p>

```<code>PUT envelope_index
{
    "mappings": {
        "document_type": {
            "properties": {
                "envelope": {
                    "type": "object",
                    "properties": {
                        "version": {
                            "type": "text"
                        },
                        "submitter": {
                            "type": "text"
                        },
                        "MetaData": {
                            "type": "object",
                            "properties": {
                                "SpecificMetaData": {
                                    "type": "nested"
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

POST envelope_index/document_type
{
    "envelope": {
        "version": "0.0.1",
        "submitter": "VF12RBU1D53087510",
        "MetaData": {
            "SpecificMetaData": [{
                    "key": "key1",
                    "value": "94"
                },
                {
                    "key": "key2",
                    "value": "0"
                }
            ]
        }
    }
 }

POST envelope_index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "inner_hits": {},
            "path": "envelope.MetaData.SpecificMetaData",
            "query": {
              "bool": {
                "must": [
                  {
                    "term": {
                      "envelope.MetaData.SpecificMetaData.key": {
                        "value": "key1"
                      }
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}
</code>```

Body:
I have data with one parameter which is an array. I know that objects in array are not well supported in Kibana, however I would like to know if there is a way to filter that array with only one value for the key. I mean :

This is a json for exemple :

{
  "_index": "index",
  "_type": "data",
  "_id": "8",
  "_version": 2,
  "_score": 1,
  "_source": {
    "envelope": {
      "version": "0.0.1",
      "submitter": "VF12RBU1D53087510",
      "MetaData": {
        "SpecificMetaData": [
          {
            "key": "key1",
            "value": "94"
          },
          {
            "key": "key2",
            "value": "0"
          }
        ]
      }
    }
  }
}

And I would like to only have the data which contains key1 in my SpecificMetaData array in order to plot them. For now, when I plot SpecificMetaData.value it takes all the values of the array (value of key1 and key2) and doesn't propose SpecificMetaData.value1 and  SpecificMetaData.value2.

If you need more information, tell me. Thank you.

Body:
you may need to map your data to mappings so as SpecificMetaData should act as nested_type and inner_hits of nested filter can supply you with objects which have key1.

PUT envelope_index
{
    "mappings": {
        "document_type": {
            "properties": {
                "envelope": {
                    "type": "object",
                    "properties": {
                        "version": {
                            "type": "text"
                        },
                        "submitter": {
                            "type": "text"
                        },
                        "MetaData": {
                            "type": "object",
                            "properties": {
                                "SpecificMetaData": {
                                    "type": "nested"
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

POST envelope_index/document_type
{
    "envelope": {
        "version": "0.0.1",
        "submitter": "VF12RBU1D53087510",
        "MetaData": {
            "SpecificMetaData": [{
                    "key": "key1",
                    "value": "94"
                },
                {
                    "key": "key2",
                    "value": "0"
                }
            ]
        }
    }
 }

POST envelope_index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "inner_hits": {},
            "path": "envelope.MetaData.SpecificMetaData",
            "query": {
              "bool": {
                "must": [
                  {
                    "term": {
                      "envelope.MetaData.SpecificMetaData.key": {
                        "value": "key1"
                      }
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}


来源: stackexchange

问:
convert an int to QByteArray in Qt
I'm trying to convert an int to QByteArray. I'm using this method QByteArray::number(m_vman); is it correct?

I'm trying to use the number() for getting an int to QByteArray.

I'm trying the following code but the bytearray is zero

```<code>    QByteArray vmanByteArray, vheaterByteArray;
    QDataStream streamVMan(&vmanByteArray, QIODevice::WriteOnly);
    QDataStream streamVHeater(&vheaterByteArray, QIODevice::WriteOnly);

    streamVMan << m_vman;
    streamVHeater << m_vheater;

QByteArray arr = m_htman ? vmanByteArray : vheaterByteArray;
</code>```

答:
you can simply do like this.</p>

```<code>int myInt = 123;
QByteArray q_b;
q_b.setNum(myInt);
</code>```

ContentLicense: CC BY-SA 4.0

Title: convert an int to QByteArray in Qt

Body:
I'm trying to convert an int to QByteArray. I'm using this method QByteArray::number(m_vman); is it correct?

I'm trying to use the number() for getting an int to QByteArray.

I'm trying the following code but the bytearray is zero

    QByteArray vmanByteArray, vheaterByteArray;
    QDataStream streamVMan(&vmanByteArray, QIODevice::WriteOnly);
    QDataStream streamVHeater(&vheaterByteArray, QIODevice::WriteOnly);

    streamVMan << m_vman;
    streamVHeater << m_vheater;

QByteArray arr = m_htman ? vmanByteArray : vheaterByteArray;

Body:
you can simply do like this.

int myInt = 123;
QByteArray q_b;
q_b.setNum(myInt);

ContentLicense: CC BY-SA 3.0


问:
Mobile Apps remember login without saving password
What strategy should I follow if I need to remember login in a mobile client if the company policy restricts me from storing password in the mobile client.</p>

答: You can save auth token when user log into app. Then use this token with your requests to backend, if you get 401 http error (not authorized) this means your token is invalid or expired and you should logout user.</p>


问:
top two elements of an associative array in php
I've accomplished the end goal for this already, but maybe there is a more elegant way of accomplishing this.

If I have an array like such:

```<code>$data = array(
    'wood' => 2,
    'metal' => 5,
    'plastic' => 3,
);
</code>```

I want to get the top 2 key/value pairs from $data (ie metal:5 & plastic:3). Here's what I came up with:

```<code>arsort($data);       //put values in order
reset($data);           //set pointer to first element
$first = each($data);    //assign first element to $first
array_shift($data); //remove first element from array
reset($data);           //set pointer to the new first element
$second = each($data); //assign the new first element to $second
</code>```

答:
For getting both key and value I would go this way:</p>

```<code>arsort($data);
$result = array_slice($data,0,2);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've accomplished the end goal for this already, but maybe there is a more elegant way of accomplishing this.

If I have an array like such:

$data = array(
    'wood' => 2,
    'metal' => 5,
    'plastic' => 3,
);

I want to get the top 2 key/value pairs from $data (ie metal:5 & plastic:3). Here's what I came up with:

arsort($data);       //put values in order
reset($data);           //set pointer to first element
$first = each($data);    //assign first element to $first
array_shift($data); //remove first element from array
reset($data);           //set pointer to the new first element
$second = each($data); //assign the new first element to $second

Body:
For getting both key and value I would go this way:

arsort($data);
$result = array_slice($data,0,2);


问:
Ellipsize - start not working in TextView
I have a textView as follows:

```<code><TextView
    android:id="@+id/pointsTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/pointTextView"
    android:ellipsize="start"
    android:lines="2"
    android:paddingEnd="5dp"
    android:paddingStart="5dp"
    android:text="this is a very very very very very very very very very very very very very very very very very very very very very long sentence." />
</code>```

Here ellipsize="end" is working perfectly, but ellipsize="start" is not wroking when no of lines is not 1.

How can I make this work in such TextView with 2 or more no of lines?

答:
If you want to use android:ellipsize="start" with android:maxLines="2" (more than one), then it's not possible in android (since API level 1).

If setMaxLines(int) has been used to set two or more lines, only END and MARQUEE are supported (other ellipsizing types will not do anything).

See the documentation here

Body:
I have a textView as follows:

<TextView
    android:id="@+id/pointsTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/pointTextView"
    android:ellipsize="start"
    android:lines="2"
    android:paddingEnd="5dp"
    android:paddingStart="5dp"
    android:text="this is a very very very very very very very very very very very very very very very very very very very very very long sentence." />

Here ellipsize="end" is working perfectly, but ellipsize="start" is not wroking when no of lines is not 1.

How can I make this work in such TextView with 2 or more no of lines?


问:
searching keys in dictionary swift
I want to search for the key id in the dictionary. I have a dictionary like this:

```<code>var tableData:[String:Any] = ["id":["path":"","type":"","parameters":[]]]
</code>```

Table data has 307 items, and all id's unique. I want to search in dictionary key id, like when I write "get" , it need the show all the search results with "get" in table view.

```<code>func updateSearchResults(for searchController: UISearchController) {
    let searchString = searchController.searchBar.text

    if let entry = tableData.keys.first(where: { $0.lowercased().contains(searchString) }) {
        print(entry)
    } else {
        print("no match")
    }
    tableView.reloadData()
}

func didChangeSearchText(searchText: String) {

    if let entry = tableData.keys.first(where: { $0.lowercased().contains(searchText) }) {
        print(entry)
    } else {
        print("no match")
    }
    // Reload the tableview.
    tableView.reloadData()
}
</code>```

When I try to search a word it prints "no match", in the debug, unable to read data writes for the value of the entry. Thank you in advance!

答:
To access an element in a Dictionary with a key, use the following code.

```<code>if let entry = tableData[searchText] {
   print(entry)
}
</code>```

For further information, have a look at:

how can i get key's value from dictionary in Swift?

Title: searching keys in dictionary swift

Body:
I want to search for the key id in the dictionary. I have a dictionary like this:

var tableData:[String:Any] = ["id":["path":"","type":"","parameters":[]]]

Table data has 307 items, and all id's unique. I want to search in dictionary key id, like when I write "get" , it need the show all the search results with "get" in table view.

func updateSearchResults(for searchController: UISearchController) {
    let searchString = searchController.searchBar.text

    if let entry = tableData.keys.first(where: { $0.lowercased().contains(searchString) }) {
        print(entry)
    } else {
        print("no match")
    }
    tableView.reloadData()
}

func didChangeSearchText(searchText: String) {

    if let entry = tableData.keys.first(where: { $0.lowercased().contains(searchText) }) {
        print(entry)
    } else {
        print("no match")
    }
    // Reload the tableview.
    tableView.reloadData()
}

When I try to search a word it prints "no match", in the debug, unable to read data writes for the value of the entry. Thank you in advance!

Body:
To access an element in a Dictionary with a key, use the following code.

if let entry = tableData[searchText] {
   print(entry)
}

For further information, have a look at:

how can i get key's value from dictionary in Swift?


问:
Could not load file or assembly 'PDFNet' or one of its dependencies. An attempt was made to load a program with an incorrect format
I'm trying to build a sample web application from a blank web form template in VS2012, and add the PDFNet dll to it. If I run the project in .NET 3.5 no problem. If I run it in .NET >= 4 I get this error:

Could not load file or assembly 'PDFNet64' or one of its dependencies. An attempt was made to load a program with an incorrect format.

this is the stack trace:

```<code>Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable  C:\Program Files (x86)\IIS Express\iisexpress.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: User = COLLAB\mirko.lugano
LOG: DisplayName = PDFNet64
 (Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: PDFNet64 | Domain ID: 2
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///c:/users/mirko.lugano/documents/visual studio 2012/Projects/WebApplication3/WebApplication3/
LOG: Initial PrivatePath = c:\users\mirko.lugano\documents\visual studio 2012\Projects\WebApplication3\WebApplication3\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: c:\users\mirko.lugano\documents\visual studio 2012\Projects\WebApplication3\WebApplication3\web.config
LOG: Using host configuration file: C:\Users\mirko.lugano\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/root/ccfa215a/dc93c54d/PDFNet64.DLL.
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/root/ccfa215a/dc93c54d/PDFNet64/PDFNet64.DLL.
LOG: Attempting download of new URL file:///c:/users/mirko.lugano/documents/visual studio 2012/Projects/WebApplication3/WebApplication3/bin/PDFNet64.DLL.
ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.

Stack Trace:

[BadImageFormatException: Could not load file or assembly 'PDFNet64' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +34
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +16
   System.Reflection.Assembly.Load(String assemblyString) +28
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Could not load file or assembly 'PDFNet64' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +752
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +218
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
   System.Web.Compilation.WebDirectoryBatchCompiler..ctor(VirtualDirectory vdir) +124
   System.Web.Compilation.BuildManager.BatchCompileWebDirectoryInternal(VirtualDirectory vdir, Boolean ignoreErrors) +44
   System.Web.Compilation.BuildManager.BatchCompileWebDirectory(VirtualDirectory vdir, VirtualPath virtualDir, Boolean ignoreErrors) +187
   System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath) +74
   System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate) +299
   System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate) +103
   System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean throwIfNotFound) +165
   System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp) +43
   System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +31
   System.Web.UI.PageHandlerFactory.GetHandler(HttpContext context, String requestType, String virtualPath, String path) +37
   System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +346
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18033
</code>```

I have already searched a lot in the web and in google groups, and I have already tried these solutions (among the others), THIS and for instance THIS

I'm running a Windows 8 x64 PC, and I DO have the Visual c++ 2010 x64 redistributable installed on my machine. I have also tried the console applications provided by the samples downloaded from pdftron.com, and those work ok in all versions of .NET. I have tried creating a console app of  my own and that too works on all versions of .NET. I had then thought it was maybe the fault of VS2012 development server which runs in x86 mode, so I set up a IIS website and run it from there, but still the same problem.
I am a bit bereft, does anybody have any ideas? Thanx.

答:
By making the DLL's "Copy Local" set to True solved my case.
IIS Application pool also needs 32bit support Off.

Body:
I'm trying to build a sample web application from a blank web form template in VS2012, and add the PDFNet dll to it. If I run the project in .NET 3.5 no problem. If I run it in .NET >= 4 I get this error:

Could not load file or assembly 'PDFNet64' or one of its dependencies. An attempt was made to load a program with an incorrect format.

this is the stack trace:

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable  C:\Program Files (x86)\IIS Express\iisexpress.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: User = COLLAB\mirko.lugano
LOG: DisplayName = PDFNet64
 (Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: PDFNet64 | Domain ID: 2
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///c:/users/mirko.lugano/documents/visual studio 2012/Projects/WebApplication3/WebApplication3/
LOG: Initial PrivatePath = c:\users\mirko.lugano\documents\visual studio 2012\Projects\WebApplication3\WebApplication3\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: c:\users\mirko.lugano\documents\visual studio 2012\Projects\WebApplication3\WebApplication3\web.config
LOG: Using host configuration file: C:\Users\mirko.lugano\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/root/ccfa215a/dc93c54d/PDFNet64.DLL.
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/root/ccfa215a/dc93c54d/PDFNet64/PDFNet64.DLL.
LOG: Attempting download of new URL file:///c:/users/mirko.lugano/documents/visual studio 2012/Projects/WebApplication3/WebApplication3/bin/PDFNet64.DLL.
ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.

Stack Trace:

[BadImageFormatException: Could not load file or assembly 'PDFNet64' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +34
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +16
   System.Reflection.Assembly.Load(String assemblyString) +28
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Could not load file or assembly 'PDFNet64' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +752
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +218
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
   System.Web.Compilation.WebDirectoryBatchCompiler..ctor(VirtualDirectory vdir) +124
   System.Web.Compilation.BuildManager.BatchCompileWebDirectoryInternal(VirtualDirectory vdir, Boolean ignoreErrors) +44
   System.Web.Compilation.BuildManager.BatchCompileWebDirectory(VirtualDirectory vdir, VirtualPath virtualDir, Boolean ignoreErrors) +187
   System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath) +74
   System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate) +299
   System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate) +103
   System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean throwIfNotFound) +165
   System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp) +43
   System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +31
   System.Web.UI.PageHandlerFactory.GetHandler(HttpContext context, String requestType, String virtualPath, String path) +37
   System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +346
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18033

I have already searched a lot in the web and in google groups, and I have already tried these solutions (among the others), THIS and for instance THIS

I'm running a Windows 8 x64 PC, and I DO have the Visual c++ 2010 x64 redistributable installed on my machine. I have also tried the console applications provided by the samples downloaded from pdftron.com, and those work ok in all versions of .NET. I have tried creating a console app of  my own and that too works on all versions of .NET. I had then thought it was maybe the fault of VS2012 development server which runs in x86 mode, so I set up a IIS website and run it from there, but still the same problem.
I am a bit bereft, does anybody have any ideas? Thanx.


问:
How to make the ajax 'data' that come with 2 values to get each value separately?
```<code><?
 function phpfunction(){

 //insert data to database //some codes work inside this.

$return_arr[] = array($arrResult,         // include only one value
                      $response_array['status'] );//success or not success value

return $return_arr;
}
?>
</code>```

This $return_arr[] value return to the javascript ajax file >>

```<code>                    $.ajax({
                            url: 'PHPMethodCalls_AL.php',
                            type: 'post',
                            data: {... post many values to php function..   },
                            success: function(data) {
                            alert(data);
</code>```

//data is successfully come as this format >> [[["Testing123"],"success"]]

```<code>                            var results = JSON.parse(data);
                            alert(results);
</code>```

// this alert got >> Testing123,success

```<code>                        },
</code>```

//this one is post value to function

```<code>$newCIarrayList = array();
$newCIarrayList = phpfunction(..data include );
echo json_encode($newCIarrayList);
</code>```

What should I do to get each value as "Testing123" and "success" value separately? I tried with split(",") function but it didn't work.

答:
What you get back in success: function(data) is a stringified json of a nested array: [[["Testing123"],"success"]].

To get your status and payload out of this structure, you can use the following snippet.

var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
console.log(parsedData); // quite nested

var status = parsedData[0][1];
console.log(status);

var payload = parsedData[0][0][0];
console.log(payload);```
</div>
</div>
</p>

<p>Or using ES6 destructuring:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
[[[payload], status]] = parsedData;
console.log(status);
console.log(payload);</code>```

I would however suggest that you revise your php-side code, and make it so that it forms a simpler structure, ideally:

```<code>{"status": "success", "payload": "Testing123"}
</code>```

Body:
<?
 function phpfunction(){

 //insert data to database //some codes work inside this.

$return_arr[] = array($arrResult,         // include only one value
                      $response_array['status'] );//success or not success value

return $return_arr;
}
?>

This $return_arr[] value return to the javascript ajax file >>

                    $.ajax({
                            url: 'PHPMethodCalls_AL.php',
                            type: 'post',
                            data: {... post many values to php function..   },
                            success: function(data) {
                            alert(data);

//data is successfully come as this format >> [[["Testing123"],"success"]]

                            var results = JSON.parse(data);
                            alert(results);

// this alert got >> Testing123,success

                        },

//this one is post value to function

$newCIarrayList = array();
$newCIarrayList = phpfunction(..data include );
echo json_encode($newCIarrayList);

What should I do to get each value as "Testing123" and "success" value separately? I tried with split(",") function but it didn't work.

Body:
What you get back in success: function(data) is a stringified json of a nested array: [[["Testing123"],"success"]].

To get your status and payload out of this structure, you can use the following snippet.

var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
console.log(parsedData); // quite nested

var status = parsedData[0][1];
console.log(status);

var payload = parsedData[0][0][0];
console.log(payload);

Or using ES6 destructuring:

var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
[[[payload], status]] = parsedData;
console.log(status);
console.log(payload);

I would however suggest that you revise your php-side code, and make it so that it forms a simpler structure, ideally:

{"status": "success", "payload": "Testing123"}


问:
In Spring-Roo 2.0, the JSON I get does not show relationship between objects.
This is a simplified example of the problem I'm having with Spring-Roo 2.0 returning JSON from the RESTful web-service call. Below are the Roo script for 2 classes (company, and user), the database content showing that the user is related to company_id=1, and the JSON I get back for the GET on the user. Note that company=null. That's the problem. Am I doing something wrong?

Roo Script

```<code>jpa setup --provider HIBERNATE --database MYSQL
--userName pivot --password pivot  --databaseName testdb

entity jpa --class ~.model.MyUser
field string --fieldName firstName --notNull
field string --fieldName lastName --notNull

entity jpa --class ~.model.Company
field string --fieldName name –notNull

field set --fieldName users --type ~.model.MyUser --cardinality ONE_TO_MANY
      --mappedBy company --comment "Users" --notNull false

repository jpa --all --package ~.repository
service --all --apiPackage ~.service.api --implPackage ~.service.impl
web mvc setup

/* ThymeLeaf view layer */
web mvc view setup --type THYMELEAF
web mvc templates setup --type THYMELEAF
web mvc controller --all --package ~.web --responseType THYMELEAF

/* JSON Rest controllers */
web mvc controller --all --responseType JSON --pathPrefix /json

web mvc finder --all --responseType THYMELEAF
web mvc finder --all --responseType JSON
</code>```

Database

```<code>mysql> select * from my_user;
+----+------------+-----------+---------+------------+
| id | first_name | last_name | version | company_id |
+----+------------+-----------+---------+------------+
|  1 | First      | Last      |       0 |          1 |
+----+------------+-----------+---------+------------+
1 row in set (0.00 sec)
</code>```

JSON

```<code>{
    "content": [
        {
            "id": 1,
            "version": 0,
            "firstName": "First",
            "lastName": "Last",
            "company": null
        }
    ],
    "last": true,
    "totalPages": 1,
    "totalElements": 1,
    "size": 20,
    "number": 0,
    "first": true,
    "numberOfElements": 1,
    "sort": null
}
</code>```

答:
The relationships generated by Spring Roo 2.0 are setted as Lazy by default to prevent data overload. Remember that Spring Roo tries to apply the best practises as possible. You could see this in your MyUser.java entity:

```<code>@ManyToOne(fetch = FetchType.LAZY)
@EntityFormat
private Company company;
</code>```

So, when you are obtaining all the records of MyUser entity, the relationships with Comapny are not loaded by default.

However, If you know that you want to obtain this information, you should customize the generated code by Spring Roo. Follow these steps:

Make push-in of the method findAll declared in theMyUserRepositoryImpl class. To do it, execute the following command:

```<code>push-in --class ~.repository.MyUserRepositoryImpl --method findAll(GlobalSearch,Pageable)
</code>```

After that, open the MyUserRepositoryImpl.java class and change the default query to execute a left join with Company. To do that, change this generated code:

```<code>JPQLQuery<MyUser> query = from(myUser);
</code>```

to this one:

```<code>JPQLQuery<MyUser> query = from(myUser).leftJoin(myUser.company).fetchJoin();
</code>```

Repeat the process with the findOne method that is used when you try to obtain an individual item instead of a list. In this case, you should define the findOne method in the MyUserRepositoryCustom interface and after that, implement it using QueryDSL in MyUserRepositoryImpl.

With the changes above, you should be able to obtain the following JSON when you acces to the url http://localhost:8080/json/myusers/ using GET operation:

```<code>{
  "content": [
    {
      "id": 1,
      "version": 0,
      "firstName": "test",
      "lastName": "test",
      "company": {
        "id": 1,
        "version": 0,
        "name": "aaa"
      }
    }
  ],
  "last": true,
  "totalPages": 1,
  "totalElements": 1,
  "sort": null,
  "numberOfElements": 1,
  "first": true,
  "size": 20,
  "number": 0
}
</code>```

As an advice, I have to say that you should be careful when you use entities with relationships in JSON responses. Maybe you could get a cyclic relationship if some entity is related with other entity that is related with the first one. Instead of return the complete entity in your JSON responses, you should return an entity projection that only shows the identifier of the related element instead of the entire related entity.

Hope it helps,

Body:
This is a simplified example of the problem I'm having with Spring-Roo 2.0 returning JSON from the RESTful web-service call. Below are the Roo script for 2 classes (company, and user), the database content showing that the user is related to company_id=1, and the JSON I get back for the GET on the user. Note that company=null. That's the problem. Am I doing something wrong?

Roo Script

jpa setup --provider HIBERNATE --database MYSQL
--userName pivot --password pivot  --databaseName testdb

entity jpa --class ~.model.MyUser
field string --fieldName firstName --notNull
field string --fieldName lastName --notNull

entity jpa --class ~.model.Company
field string --fieldName name –notNull

field set --fieldName users --type ~.model.MyUser --cardinality ONE_TO_MANY
      --mappedBy company --comment "Users" --notNull false

repository jpa --all --package ~.repository
service --all --apiPackage ~.service.api --implPackage ~.service.impl
web mvc setup

/* ThymeLeaf view layer */
web mvc view setup --type THYMELEAF
web mvc templates setup --type THYMELEAF
web mvc controller --all --package ~.web --responseType THYMELEAF

/* JSON Rest controllers */
web mvc controller --all --responseType JSON --pathPrefix /json

web mvc finder --all --responseType THYMELEAF
web mvc finder --all --responseType JSON

Database

mysql> select * from my_user;
+----+------------+-----------+---------+------------+
| id | first_name | last_name | version | company_id |
+----+------------+-----------+---------+------------+
|  1 | First      | Last      |       0 |          1 |
+----+------------+-----------+---------+------------+
1 row in set (0.00 sec)

JSON

{
    "content": [
        {
            "id": 1,
            "version": 0,
            "firstName": "First",
            "lastName": "Last",
            "company": null
        }
    ],
    "last": true,
    "totalPages": 1,
    "totalElements": 1,
    "size": 20,
    "number": 0,
    "first": true,
    "numberOfElements": 1,
    "sort": null
}

Body:
The relationships generated by Spring Roo 2.0 are setted as Lazy by default to prevent data overload. Remember that Spring Roo tries to apply the best practises as possible. You could see this in your MyUser.java entity:

@ManyToOne(fetch = FetchType.LAZY)
@EntityFormat
private Company company;

So, when you are obtaining all the records of MyUser entity, the relationships with Comapny are not loaded by default.

However, If you know that you want to obtain this information, you should customize the generated code by Spring Roo. Follow these steps:

Make push-in of the method findAll declared in theMyUserRepositoryImpl class. To do it, execute the following command:

push-in --class ~.repository.MyUserRepositoryImpl --method findAll(GlobalSearch,Pageable)

After that, open the MyUserRepositoryImpl.java class and change the default query to execute a left join with Company. To do that, change this generated code:

JPQLQuery<MyUser> query = from(myUser);

to this one:

JPQLQuery<MyUser> query = from(myUser).leftJoin(myUser.company).fetchJoin();

Repeat the process with the findOne method that is used when you try to obtain an individual item instead of a list. In this case, you should define the findOne method in the MyUserRepositoryCustom interface and after that, implement it using QueryDSL in MyUserRepositoryImpl.

With the changes above, you should be able to obtain the following JSON when you acces to the url http://localhost:8080/json/myusers/ using GET operation:

{
  "content": [
    {
      "id": 1,
      "version": 0,
      "firstName": "test",
      "lastName": "test",
      "company": {
        "id": 1,
        "version": 0,
        "name": "aaa"
      }
    }
  ],
  "last": true,
  "totalPages": 1,
  "totalElements": 1,
  "sort": null,
  "numberOfElements": 1,
  "first": true,
  "size": 20,
  "number": 0
}

As an advice, I have to say that you should be careful when you use entities with relationships in JSON responses. Maybe you could get a cyclic relationship if some entity is related with other entity that is related with the first one. Instead of return the complete entity in your JSON responses, you should return an entity projection that only shows the identifier of the related element instead of the entire related entity.

Hope it helps,


问:
User input and do while loop with negation
I was trying to make an user input in an do while loop. The loop should continue if the user input is not yes OR not.
    When I write:

```<code>BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    String userInput = "";
    String yes = "yes";
    String no = "no";

    do {
        System.out.print("Type yes or no: ");
        userInput = input.readLine();
    } while (userInput.equals(yes) || userInput.equals(no));
</code>```

If the user type "yes" OR "no" the loop will continue, all other inputs will result the end of the loop.

When I write:

```<code>while (!userInput.equals(yes) || !userInput.equals(no));
</code>```

The loop continues everytime, no matter what the user enters.

Only when I use the AND operator it works.

```<code>while (!userInput.equals(yes) && !userInput.equals(no));
</code>```

Why is that so?
Should it not be the OR operator because I want to say, if the user enters yes OR no stop the loop.

答:
```<code>!userInput.equals(yes) || !userInput.equals(no)
</code>```

Let's say the user enters "hello". You ths have

```<code>!false || !false
</code>```

which is

```<code>true || true
</code>```

which is

```<code>true
</code>```

Let's say the user enters "yes".

You thus have

```<code>!true || !false
</code>```

which is

```<code>false || true
</code>```

which is

```<code>true
</code>```

Let's say the user enters "no".

You thus have

```<code>!false || !true
</code>```

which is

```<code>true || false
</code>```

which is

```<code>true
</code>```

So you see that, whetever the user enters, the condition is always true, and thus the loop continues forever.

Body:
I was trying to make an user input in an do while loop. The loop should continue if the user input is not yes OR not.
    When I write:

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    String userInput = "";
    String yes = "yes";
    String no = "no";

    do {
        System.out.print("Type yes or no: ");
        userInput = input.readLine();
    } while (userInput.equals(yes) || userInput.equals(no));

If the user type "yes" OR "no" the loop will continue, all other inputs will result the end of the loop.

When I write:

while (!userInput.equals(yes) || !userInput.equals(no));

The loop continues everytime, no matter what the user enters.

Only when I use the AND operator it works.

while (!userInput.equals(yes) && !userInput.equals(no));

Why is that so?
Should it not be the OR operator because I want to say, if the user enters yes OR no stop the loop.

Body:
!userInput.equals(yes) || !userInput.equals(no)

Let's say the user enters "hello". You ths have

!false || !false

which is

true || true

which is

true

Let's say the user enters "yes".

You thus have

!true || !false

which is

false || true

which is

true

Let's say the user enters "no".

You thus have

!false || !true

which is

true || false

which is

true

So you see that, whetever the user enters, the condition is always true, and thus the loop continues forever.


问:
Rdlc reporting returns null on renderReport
I am using c# rdlc reporting I am getting error when it reaches a line on code to generate bytes mimetype is empty  which results in  null exception
can anyone help with this I don't know what I am missing.</p>

```<code>        string mimeType ="";
        long? plantId = 0;
        LocalReportModel reportModel = new LocalReportModel()
        {
            ExportFileName = "ChangeRequestReportDoc",
            Format = (reportAction == ReportActionType.ExportPDF ? LocalReportFormat.PDF : (reportAction == ReportActionType.ExportExcel ? LocalReportFormat.Excel : LocalReportFormat.Word)),
            Name = "ChangeRequestReportDoc",
            ReportEmbeddedResource = "A.HQM.Reports.ChangeRequestDocument.rdlc"
        };

        if (Cache.LoggedInUserModel() != null)
        {
            var loggedInUser = Cache.LoggedInUserModel();
            plantId = loggedInUser.SelectedPlant;
        }

        TrainingReportFilterModel model = new TrainingReportFilterModel()
        {
            FromDate = fromDate,
            ToDate = toDate,
            PlantId = plantId
        };

        List<A.HQM.BL.Entities.ChangeRequestData.ChangeRequest> reportData = ChangeRequestProvider.ChangeReport(model.FromDate, model.ToDate, plantId
                                                    ).ToList();

        DataSet dataset = new A.HQM.Reports.ChangeRequest.ChangeRequestData();
        DataTable tableToAdd = dataset.Tables["ChangeRequestReport"];

        foreach (A.HQM.BL.Entities.ChangeRequestData.ChangeRequest found in reportData)
        {
            DataRow dataRow = tableToAdd.NewRow();
            dataRow.SetField("Comments", found.Comments);
            dataRow.SetField("CRSummary",found.CRSummary);
            dataRow.SetField("Status",found.Status);
            dataRow.SetField("ChangeRequestDate", found.ChangeRequestDate);
            tableToAdd.Rows.Add(dataRow);
        }

        reportModel.DataSets.Add(new LocalReportDataSet() { DataSetData = tableToAdd, DatasetName = "ChangeRequestData" });

        byte[] renderedBytes = reportModel.RenderReport(out mimeType);
        return File(renderedBytes, System.Net.Mime.MediaTypeNames.Application.Octet, reportModel.FileName);
</code>```

答:
Maybe your not passing all required parameters to the RenderReport method?

```<code>Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;

byte[] renderedBytes = reportModel.RenderReport(
    "PDF", null, out mimeType, out encoding, out filenameExtension,
    out streamids, out warnings);
</code>```

Body:
I am using c# rdlc reporting I am getting error when it reaches a line on code to generate bytes mimetype is empty  which results in  null exception
can anyone help with this I don't know what I am missing.

        string mimeType ="";
        long? plantId = 0;
        LocalReportModel reportModel = new LocalReportModel()
        {
            ExportFileName = "ChangeRequestReportDoc",
            Format = (reportAction == ReportActionType.ExportPDF ? LocalReportFormat.PDF : (reportAction == ReportActionType.ExportExcel ? LocalReportFormat.Excel : LocalReportFormat.Word)),
            Name = "ChangeRequestReportDoc",
            ReportEmbeddedResource = "A.HQM.Reports.ChangeRequestDocument.rdlc"
        };

        if (Cache.LoggedInUserModel() != null)
        {
            var loggedInUser = Cache.LoggedInUserModel();
            plantId = loggedInUser.SelectedPlant;
        }

        TrainingReportFilterModel model = new TrainingReportFilterModel()
        {
            FromDate = fromDate,
            ToDate = toDate,
            PlantId = plantId
        };

        List reportData = ChangeRequestProvider.ChangeReport(model.FromDate, model.ToDate, plantId
                                                    ).ToList();

        DataSet dataset = new A.HQM.Reports.ChangeRequest.ChangeRequestData();
        DataTable tableToAdd = dataset.Tables["ChangeRequestReport"];

        foreach (A.HQM.BL.Entities.ChangeRequestData.ChangeRequest found in reportData)
        {
            DataRow dataRow = tableToAdd.NewRow();
            dataRow.SetField("Comments", found.Comments);
            dataRow.SetField("CRSummary",found.CRSummary);
            dataRow.SetField("Status",found.Status);
            dataRow.SetField("ChangeRequestDate", found.ChangeRequestDate);
            tableToAdd.Rows.Add(dataRow);
        }

        reportModel.DataSets.Add(new LocalReportDataSet() { DataSetData = tableToAdd, DatasetName = "ChangeRequestData" });

        byte[] renderedBytes = reportModel.RenderReport(out mimeType);
        return File(renderedBytes, System.Net.Mime.MediaTypeNames.Application.Octet, reportModel.FileName);

Body:
Maybe your not passing all required parameters to the RenderReport method?

Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;

byte[] renderedBytes = reportModel.RenderReport(
    "PDF", null, out mimeType, out encoding, out filenameExtension,
    out streamids, out warnings);


问:
CSS - Line height property, how it works (simple)
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

```<code>line-height:100px;
</code>```

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!

答: Using the line-height property to 100px means that the text is going to be vertically centered in the middle of a line with a 100px height. Meaning it will be placed around 50px. Setting the margins to 50px will give you a similar result but you might notice its not exactly centered.</p>

Body:
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

line-height:100px;

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!


答: Think about the Boolean expressions you are writing. When the users enters 'yes', it evaluates as !true || !false which is equivalent to false||true which is true. Since the condition is satisfied, the loop continues.

Title: User input and do while loop with negation


问:
md-select same object in ng-option and ng-model
Is it possible to use same json object in ng-option and ng-model of md-select?

Here I'm using Angular Material md-select instead of HTML Select

Controller:

```<code>$scope.languages = [
     { name: 'English', value: true },
     { name: 'English', value: false }
];
</code>```

View:

```<code><md-select ng-model="languages"
             placeholder="Select"
             class="select-dropdown md-no-underline"
             multiple>
    <md-option ng-value="language.value" ng-repeat="language in languages">
      {{language.name}}
    </md-option>

</md-select>
</code>```

答: It is so because when you select or un-select the list items from your md-checkbox it alters the list from which ng-repeat is getting values. You need to maintain the selections in another variable.

Body:
Is it possible to use same json object in ng-option and ng-model of md-select?

Here I'm using Angular Material md-select instead of HTML Select

Controller:

$scope.languages = [
     { name: 'English', value: true },
     { name: 'English', value: false }
];

View:

<md-select ng-model="languages"
             placeholder="Select"
             class="select-dropdown md-no-underline"
             multiple>
    <md-option ng-value="language.value" ng-repeat="language in languages">
      {{language.name}}
    </md-option>

</md-select>


问:
getting warning Invalid argument for foreach in codeigniter
In foreach loop i am getting warning Invalid argument supplied for foreach() below is my loop code and modal code please let me know where i done wrong

Controller

```<code>$concond = array("con_id"=>1,"con_status"=>1);
$this->data['contact']=$this->Frontend_model->get_contact($concond);
$this->load->view('frontend/clienthome',$this->data);
</code>```

foreach Loop

```<code>if($contact)
{
  foreach($contact as $foot)
  {
     $footadr1 = $foot->con_addr_line_1;
     $footadr2 = $foot->con_addr_line_2;
     $footcity = $foot->con_city;
     $footstate = $foot->con_state;
     $footcountry = $foot->con_country;
     $footpin = $foot->con_pincode;
     $footp1 = $foot->con_phone_1;
     $footp2 = $foot->con_phone_2;
     $footp3 = $foot->con_phone_3;
     $footp4 = $foot->con_phone_4;
     $footemail = $foot->con_email_id;
  }
}
</code>```

modal

```<code>function get_contact($concond)
{
  $this->db->select('*');
  $this->db->from('is_addres_contact');
  $this->db->where($concond);
  $query = $this->db->get();
  return $query->result();
}
</code>```

答:
Try in model

```<code>function get_contact($con_id, $con_stat)
{
  $this->db->where('con_id', $con_id);
  $this->db->where('con_status', $con_stat);
  $query = $this->db->get('is_addres_contact');
  return $query->result();
}
</code>```

Controller

```<code>$con_id = '1';
$con_stat = '1';

$this->data['contact'] = $this->frontend_model->get_contact($con_id, $con_stat);

$this->load->view('frontend/clienthome',$this->data);
</code>```

Body:
In foreach loop i am getting warning Invalid argument supplied for foreach() below is my loop code and modal code please let me know where i done wrong

Controller

$concond = array("con_id"=>1,"con_status"=>1);
$this->data['contact']=$this->Frontend_model->get_contact($concond);
$this->load->view('frontend/clienthome',$this->data);

foreach Loop

if($contact)
{
  foreach($contact as $foot)
  {
     $footadr1 = $foot->con_addr_line_1;
     $footadr2 = $foot->con_addr_line_2;
     $footcity = $foot->con_city;
     $footstate = $foot->con_state;
     $footcountry = $foot->con_country;
     $footpin = $foot->con_pincode;
     $footp1 = $foot->con_phone_1;
     $footp2 = $foot->con_phone_2;
     $footp3 = $foot->con_phone_3;
     $footp4 = $foot->con_phone_4;
     $footemail = $foot->con_email_id;
  }
}

modal

function get_contact($concond)
{
  $this->db->select('*');
  $this->db->from('is_addres_contact');
  $this->db->where($concond);
  $query = $this->db->get();
  return $query->result();
}

Body:
Try in model

function get_contact($con_id, $con_stat)
{
  $this->db->where('con_id', $con_id);
  $this->db->where('con_status', $con_stat);
  $query = $this->db->get('is_addres_contact');
  return $query->result();
}

Controller

$con_id = '1';
$con_stat = '1';

$this->data['contact'] = $this->frontend_model->get_contact($con_id, $con_stat);

$this->load->view('frontend/clienthome',$this->data);


问:
Duplicate Record display in Table
I'm working on software everything work perfectly, but when I print its record from multiple table is show duplicate entry for each row

I have no idea why this thing happened.

Here is my Query which gets data from table and display using PHP

```<code>Select item_id,item_name,rci.item_shape,
remaing_quantity,rci.child_date from rads_childrenitem rci ,
add_itemchildren aic where aic.id = rci.item_id group by
rci.id,item_name,rci.item_shape, remaing_quantity order by rci.id desc
</code>```

Image attached for better understanding.

答:
You can update your SQL to using JOIN rather than using multiple tables in the FROM clause.  Also the group by MAY be wrong (can't test it without using your data), but in any case, try this...

```<code>Select item_id,item_name,rci.item_shape,
        remaing_quantity,rci.child_date
    from rads_childrenitem rci
    join add_itemchildren aic on aic.id = rci.item_id
    group by item_id, item_name,rci.item_shape, remaing_quantity
    order by rci.id desc
</code>```

Note that I've changed the group from rci.id to item_id.

Also the field child_date should either be in your group by or something like MAX() or MIN().  You may also want to change the order by to item_id.

Title: Duplicate Record display in Table

Body:
I'm working on software everything work perfectly, but when I print its record from multiple table is show duplicate entry for each row

I have no idea why this thing happened.

Here is my Query which gets data from table and display using PHP

Select item_id,item_name,rci.item_shape,
remaing_quantity,rci.child_date from rads_childrenitem rci ,
add_itemchildren aic where aic.id = rci.item_id group by
rci.id,item_name,rci.item_shape, remaing_quantity order by rci.id desc

Image attached for better understanding.

Body:
You can update your SQL to using JOIN rather than using multiple tables in the FROM clause.  Also the group by MAY be wrong (can't test it without using your data), but in any case, try this...

Select item_id,item_name,rci.item_shape,
        remaing_quantity,rci.child_date
    from rads_childrenitem rci
    join add_itemchildren aic on aic.id = rci.item_id
    group by item_id, item_name,rci.item_shape, remaing_quantity
    order by rci.id desc

Note that I've changed the group from rci.id to item_id.

Also the field child_date should either be in your group by or something like MAX() or MIN().  You may also want to change the order by to item_id.


问:
How to add title to the custom Dialog?
How can i add title to this custom dialog??

I have tried like this

```<code>public void customDialog()
 {
  Dialog dialog=new Dialog(this);
  dialog.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
  dialog.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.string.app_name );
  dialog.setContentView(R.layout.dialog_submit);
  TextView edit_model=(TextView) dialog.findViewById(R.id.edit_model);
  edit_model.setText(android.os.Build.DEVICE);
  dialog.show();
 }//end of custom dialog function
</code>```

I have tried to set title like this too..dialog.setTitle("Enter Details"); but this too didn't yielded any result. So how can i set title to this custom dialog??

This is my dialog_submit.xml file used for the custom dialog.

```<code> <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/layout_root"
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:padding="10dp"
          >
  <TextView android:id="@+id/txt_name"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textColor="#FFF"
          android:text="Name"
          android:textStyle="bold"
          />
  <EditText android:id="@+id/edit_name"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_below="@+id/txt_name"
          />
<TextView android:id="@+id/txt_model"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textColor="#FFF"
          android:layout_below="@+id/edit_name"
          android:text="Phone Model"
          />
<TextView android:id="@+id/edit_model"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_below="@+id/txt_model"
          />

<Button android:id="@+id/but_cancel"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_below="@+id/edit_model"
          android:text="Cancel"
          />
<Button android:id="@+id/but_submit"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_below="@+id/edit_model"
          android:layout_toRightOf="@+id/but_cancel"
          android:text="Submit"
          />
</RelativeLayout>
</code>```

答:
Please use this line in to hide built-in title from dialog

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

and add textView in your layout file.

Title: How to add title to the custom Dialog?

Body:
How can i add title to this custom dialog??

I have tried like this

public void customDialog()
 {
  Dialog dialog=new Dialog(this);
  dialog.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
  dialog.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.string.app_name );
  dialog.setContentView(R.layout.dialog_submit);
  TextView edit_model=(TextView) dialog.findViewById(R.id.edit_model);
  edit_model.setText(android.os.Build.DEVICE);
  dialog.show();
 }//end of custom dialog function

I have tried to set title like this too..dialog.setTitle("Enter Details"); but this too didn't yielded any result. So how can i set title to this custom dialog??

This is my dialog_submit.xml file used for the custom dialog.

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/layout_root"
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:padding="10dp"
          >
  <TextView android:id="@+id/txt_name"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textColor="#FFF"
          android:text="Name"
          android:textStyle="bold"
          />
  <EditText android:id="@+id/edit_name"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_below="@+id/txt_name"
          />
<TextView android:id="@+id/txt_model"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textColor="#FFF"
          android:layout_below="@+id/edit_name"
          android:text="Phone Model"
          />
<TextView android:id="@+id/edit_model"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_below="@+id/txt_model"
          />

<Button android:id="@+id/but_cancel"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_below="@+id/edit_model"
          android:text="Cancel"
          />
<Button android:id="@+id/but_submit"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_below="@+id/edit_model"
          android:layout_toRightOf="@+id/but_cancel"
          android:text="Submit"
          />
</RelativeLayout>


问:
Registering event, why the code can compile without error?
I believe there should be many questions on SO related to this but I can't think of the proper keywords to search for them.

The code

```<code>class Subscriber
{
    public Subscriber(Notifier n)
    {
        n.OnSomeEvent += (object sender, EventArgs e) => { }; //This does not compile
        n.OnSomeEvent += ReactOnEvent; //This compile successfully!
    }

    private void ReactOnEvent(object sender, EventArgs e)
    {

    }
}

class Notifier
{
    public event EventHandler<MyEventArgs> OnSomeEvent;
    public void Trigger()
    {
        OnSomeEvent?.Invoke(this, new MyEventArgs());
    }
}

class MyEventArgs : EventArgs
{

}
</code>```

The compile errors for registering the lambda expression are making sense.

Error  CS1661  Cannot convert lambda expression to delegate type 'EventHandler<MyEventArgs>' because the parameter types do not match the delegate parameter types

Error  CS1678  Parameter 2 is declared as type 'System.EventArgs' but should be 'ConsoleApplication1.MyEventArgs'

But why compiler doesn't give me the same errors for this? Is my understanding of event handling fundamentally wrong? I think the compiler requires that the signature of the event and its handlers are matching.

```<code>n.OnSomeEvent += ReactOnEvent;
</code>```

Edit: The answer for this question

As Peter pointed out in his comments, and quoted from ms docs,

(starting with .NET 3.5)...you can assign to delegates not only methods that have matching signatures, but also methods that return more derived types (covariance) or that accept parameters that have less derived types (contravariance) than that specified by the delegate type.

答:
when using a lambda expression the input parameters are inferred by the compiler.

n.OnSomeEvent += (sender, e) => { };

mouse over the sender and e, and you should notice that they have the correct types that are required for OnSomeEvent

A quick example about using lambda expressions to subscribe to events can be found here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-use-lambda-expressions-outside-linq

Body:
I believe there should be many questions on SO related to this but I can't think of the proper keywords to search for them.

The code

class Subscriber
{
    public Subscriber(Notifier n)
    {
        n.OnSomeEvent += (object sender, EventArgs e) => { }; //This does not compile
        n.OnSomeEvent += ReactOnEvent; //This compile successfully!
    }

    private void ReactOnEvent(object sender, EventArgs e)
    {

    }
}

class Notifier
{
    public event EventHandler<MyEventArgs> OnSomeEvent;
    public void Trigger()
    {
        OnSomeEvent?.Invoke(this, new MyEventArgs());
    }
}

class MyEventArgs : EventArgs
{

}

The compile errors for registering the lambda expression are making sense.

Error  CS1661  Cannot convert lambda expression to delegate type 'EventHandler<MyEventArgs>' because the parameter types do not match the delegate parameter types

Error  CS1678  Parameter 2 is declared as type 'System.EventArgs' but should be 'ConsoleApplication1.MyEventArgs'

But why compiler doesn't give me the same errors for this? Is my understanding of event handling fundamentally wrong? I think the compiler requires that the signature of the event and its handlers are matching.

n.OnSomeEvent += ReactOnEvent;

Edit: The answer for this question

As Peter pointed out in his comments, and quoted from ms docs,

(starting with .NET 3.5)...you can assign to delegates not only methods that have matching signatures, but also methods that return more derived types (covariance) or that accept parameters that have less derived types (contravariance) than that specified by the delegate type.


问:
Finding reachable vertices of a vertice in a graph
I am having problem in my code to calculate the reachable vertices in a graph.

I have the following code for the graph

```<code>class Vertices():
    number = 0
    def __init__(self):
        Vertices.number += 1
        self.number = Vertices.number
        self.Reachable= []
</code>```

I create the graph in the following way

```<code>a = Vertices()
a.Reachable = [1,2]
b = Vertices()
b.Reachable = [3]
c = Vertices()
c.Reachable= [3]
List = []
List.append(a)
List.append(b)
List.append(c)
</code>```

Thus vertice 1 that is a has an edge to itself and b . Similarly for b and for c.

We can move around the graph using List ie for vertex a it is reachable to List[trans-1] where trans refers to the Reachable list of a (List[0] and List[1])

Now in this graph I have to calculate the reachability for each vertice ie for each vertice calculate the vertices that it can reach.For eg a can reach a,b and c

I have read that I can use sets to do depth first search in all the list. Can you provide me a solution as to how to proceed.

Can anyone tell me how to use sets as I think that it is quite ideal for this problem seeing that it has union and difference functions associated with it....
PS : This is'nt a school based assignment.....

答:
How about using well-known solution to your problem?

First, you need a data structure for a graph. You can do it as dictionary of lists where each vertex is represented as the key and reachable vertices are the list values.

```<code>graph = {'A': ['B', 'C'],
         'B': ['C', 'D'],
         'C': ['D'],
         'D': ['C'],
         'E': ['F'],
         'F': ['C']}
</code>```

If you represent your graph as shown above, finding the neighbouring vertices of B would be just

```<code>neighbours_of_B = graph['B']
</code>```

and (from the same site)
finding all paths without cycles would be:

```<code>def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return [path]
    if not graph.has_key(start):
        return []
    paths = []
    for node in graph[start]:
        if node not in path:
            newpaths = find_all_paths(graph, node, end, path)
            for newpath in newpaths:
                paths.append(newpath)
    return paths
</code>```

and run it as:

```<code>find_all_paths(graph, 'A', 'D')
</code>```

hope that helps.
Read more about it at the above link.

Body:
I am having problem in my code to calculate the reachable vertices in a graph.

I have the following code for the graph

class Vertices():
    number = 0
    def __init__(self):
        Vertices.number += 1
        self.number = Vertices.number
        self.Reachable= []

I create the graph in the following way

a = Vertices()
a.Reachable = [1,2]
b = Vertices()
b.Reachable = [3]
c = Vertices()
c.Reachable= [3]
List = []
List.append(a)
List.append(b)
List.append(c)

Thus vertice 1 that is a has an edge to itself and b . Similarly for b and for c.

We can move around the graph using List ie for vertex a it is reachable to List[trans-1] where trans refers to the Reachable list of a (List[0] and List[1])

Now in this graph I have to calculate the reachability for each vertice ie for each vertice calculate the vertices that it can reach.For eg a can reach a,b and c

I have read that I can use sets to do depth first search in all the list. Can you provide me a solution as to how to proceed.

Can anyone tell me how to use sets as I think that it is quite ideal for this problem seeing that it has union and difference functions associated with it....
PS : This is'nt a school based assignment.....

Body:
How about using well-known solution to your problem?

First, you need a data structure for a graph. You can do it as dictionary of lists where each vertex is represented as the key and reachable vertices are the list values.

graph = {'A': ['B', 'C'],
         'B': ['C', 'D'],
         'C': ['D'],
         'D': ['C'],
         'E': ['F'],
         'F': ['C']}

If you represent your graph as shown above, finding the neighbouring vertices of B would be just

neighbours_of_B = graph['B']

and (from the same site)
finding all paths without cycles would be:

def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return [path]
    if not graph.has_key(start):
        return []
    paths = []
    for node in graph[start]:
        if node not in path:
            newpaths = find_all_paths(graph, node, end, path)
            for newpath in newpaths:
                paths.append(newpath)
    return paths

and run it as:

find_all_paths(graph, 'A', 'D')

hope that helps.
Read more about it at the above link.


问:
How convert a JSON format to another using Javascript?
Iam implementing datepicker using Oracle JET.The JET cookbook provides me sample Datapicker that has JSON file as below.

```<code> "Holidays": {
  "*": {
     "1": {
        "14": {
           "className": "holiday"

        },
        "26": {
           "className": "holiday"

        }
     }
   }
</code>```

And Json file I get from my rest services is as below

```<code> [
 {
     "YEAR":"2017",
     "MONTH":"1",
     "DAY":[
     {
         "N_DAYS":"25",
         "className":"holiday"
     },
     {
         "N_DAYS":"25",
         "className":"holiday"
     }
 ]

      },
  ];
</code>```

How I can convert JSON file I get from the rest services like above one provided in JET cookbook

答:
And Here is the fiddle link
https://fiddle.jshell.net/q80212b7/1/

   var myStuff= [ {
    "YYYY_YEAR" : "2013",
    "MMM_MONTH" : "06",
    "DAY_OUT" : {
      "DAY_OUT_ITEM" : {
        "N_DAYS" : "06",
        "CLASSNAME" : "Holiday",
        "TOOLTIP" : "Lalat Al Miraj"
      }
    }
  }, {
    "YYYY_YEAR" : "2017",
    "MMM_MONTH" : "06",
    "DAY_OUT" : {
      "DAY_OUT_ITEM" : [ {
        "N_DAYS" : "06",
        "CLASSNAME" : "Holiday",
        "TOOLTIP" : "Lalat Al Miraj"
      } ]
    }
  }, {
    "YYYY_YEAR" : "2013",
    "MMM_MONTH" : "01",
    "DAY_OUT" : {
      "DAY_OUT_ITEM" : [ {
        "N_DAYS" : "01",
        "CLASSNAME" : "Holiday",
        "TOOLTIP" : "New Year's Day"
      }, {
        "N_DAYS" : "24",
        "CLASSNAME" : "Holiday",
        "TOOLTIP" : "Milad Un Nabi"
      } ]
    }
  }, {
    "YYYY_YEAR" : "2017",
    "MMM_MONTH" : "01",
    "DAY_OUT" : {
      "DAY_OUT_ITEM" : [ {
        "N_DAYS" : "01",
        "CLASSNAME" : "Holiday",
        "TOOLTIP" : "New Year's Day"
      }, {
        "N_DAYS" : "24",
        "CLASSNAME" : "Holiday",
        "TOOLTIP" : "Milad Un Nabi"
      } ]
    }
  }];

Holidays = {
   'value': { }
}

 for (var i = 0; i < myStuff.length; i++) {
  var year = parseInt(myStuff[i].YYYY_YEAR,10);

 var month = parseInt(myStuff[i].MMM_MONTH,10);

 if (typeof Holidays['value'][myStuff[i].YYYY_YEAR] == 'undefined') {
  Holidays['value'][year] = {};
}
  if (typeof Holidays['value'][year][myStuff[i].MMM_MONTH] == 'undefined') {
  Holidays['value'][year][month] = {};

}
 if(myStuff[i].DAY_OUT.DAY_OUT_ITEM instanceof Array) {

 for (var j = 0; j < myStuff[i].DAY_OUT.DAY_OUT_ITEM.length; j++) {

  var day=parseInt(myStuff[i].DAY_OUT.DAY_OUT_ITEM[j].N_DAYS,10);
 Holidays['value'][year][month][day] = {
  className: myStuff[i].DAY_OUT.DAY_OUT_ITEM[j].CLASSNAME,
   tooltip: myStuff[i].DAY_OUT.DAY_OUT_ITEM[j].TOOLTIP
  };
  }
  }
  else
   {

  var day=parseInt(myStuff[i].DAY_OUT.DAY_OUT_ITEM.N_DAYS,10);
 Holidays['value'][year][month][day] = {
  className: myStuff[i].DAY_OUT.DAY_OUT_ITEM.CLASSNAME,
   tooltip: myStuff[i].DAY_OUT.DAY_OUT_ITEM.TOOLTIP
   };

  }
}

 Holidays = { Holidays: Holidays }
 console.log(JSON.stringify(Holidays.Holidays));```

Body:
Iam implementing datepicker using Oracle JET.The JET cookbook provides me sample Datapicker that has JSON file as below.

 "Holidays": {
  "*": {
     "1": {
        "14": {
           "className": "holiday"

        },
        "26": {
           "className": "holiday"

        }
     }
   }

And Json file I get from my rest services is as below

 [
 {
     "YEAR":"2017",
     "MONTH":"1",
     "DAY":[
     {
         "N_DAYS":"25",
         "className":"holiday"
     },
     {
         "N_DAYS":"25",
         "className":"holiday"
     }
 ]

      },
  ];

How I can convert JSON file I get from the rest services like above one provided in JET cookbook


问:
the efficient way to get the high 32 bits of the product of two unsigned integers c++
```<code>unsigned int a = 4294967295;  // (2^32)-1
unsigned int b = 2;
</code>```

I am trying to figure out the most efficient way to get the high 32 bits of the product of two unsigned integers.
For example, using CUDA programming I can just unsigned int first32bits = __umulhi(a,b) and get the high 32 bits.

Are there ways to do such thing in C++?

Here's my approach:

```<code>unsigned long c = ( ((unsigned long)a * (unsigned long)b ) >> 32) & 0x00000000FFFFFFFF;
</code>```

Are there any ways to make my approach faster?

答:
Unless there is some architecture dependent circuitry that maps imulh32 to a native instruction then I think that that is sort of the best you can do.

Looking at the assembly generated by g++ 6.3 for your function, it is clear than it costs just 1 assembly operation more than a function which only does multiplication because of the shr $0x20.

```<code> unsigned long umulhi32( unsigned int x,  unsigned int y)
{
  return ( ((unsigned long)a * (unsigned long)b ) >> 32);
}
0000000000000960 <_Z8umulhi32jy>:
 960:   89 f8                   mov    %edi,%eax
 962:   89 f7                   mov    %esi,%edi
 964:   48 0f af c7             imul   %rdi,%rax
 968:   48 c1 e8 20             shr    $0x20,%rax
 96c:   c3                      retq
 96d:   0f 1f 00                nopl   (%rax)
</code>```

It would be interesting to have the assembly of the cuda umulhi in order to see if it maps to some dedicated PTX instruction which I think is very likely to be so since the PTX assembly used by cuda exposes, for instance, the mul24 which (quoting)

mul24.hi performs a 24x24-bit multiply and returns the high 32 bits of
  the 48-bit result

As far as I know, there are not such instructions in x86 assembly.

Hope this helps.

Body:
unsigned int a = 4294967295;  // (2^32)-1
unsigned int b = 2;

I am trying to figure out the most efficient way to get the high 32 bits of the product of two unsigned integers.
For example, using CUDA programming I can just unsigned int first32bits = __umulhi(a,b) and get the high 32 bits.

Are there ways to do such thing in C++?

Here's my approach:

unsigned long c = ( ((unsigned long)a * (unsigned long)b ) >> 32) & 0x00000000FFFFFFFF;

Are there any ways to make my approach faster?

Body:
Unless there is some architecture dependent circuitry that maps imulh32 to a native instruction then I think that that is sort of the best you can do.

Looking at the assembly generated by g++ 6.3 for your function, it is clear than it costs just 1 assembly operation more than a function which only does multiplication because of the shr $0x20.

 unsigned long umulhi32( unsigned int x,  unsigned int y)
{
  return ( ((unsigned long)a * (unsigned long)b ) >> 32);
}
0000000000000960 <_Z8umulhi32jy>:
 960:   89 f8                   mov    %edi,%eax
 962:   89 f7                   mov    %esi,%edi
 964:   48 0f af c7             imul   %rdi,%rax
 968:   48 c1 e8 20             shr    $0x20,%rax
 96c:   c3                      retq
 96d:   0f 1f 00                nopl   (%rax)

It would be interesting to have the assembly of the cuda umulhi in order to see if it maps to some dedicated PTX instruction which I think is very likely to be so since the PTX assembly used by cuda exposes, for instance, the mul24 which (quoting)

mul24.hi performs a 24x24-bit multiply and returns the high 32 bits of
  the 48-bit result

As far as I know, there are not such instructions in x86 assembly.

Hope this helps.


问:
Mobile Apps remember login without saving password
What strategy should I follow if I need to remember login in a mobile client if the company policy restricts me from storing password in the mobile client.</p>

答:
Time limited token.
You have multiple options:
1. After successful login create time limited token on server and send it to client. Don't forget to generate new token often enough, to prevent it's expiration (ideally on every request)
2. After successful login share secret key, used to generate token between client and server (ideally newly generated secret). Then you can use this secret on client to generate token when needed.

In any case, every client request should contain token + some signature for ensuring that request hasn't change by third party.


问:
Inserting data from Coinbase API V2 into a MySQL Database using php
I'm a bit stuck here. I'm building an app based on the Coinbase PHP API V2.

This is what I'm trying to achieve. I would like to place the currency code (for e.g. EUR or USD) and the corresponding sell price at the moment of calling in my local MySQL database (ideal also including a timestamp).

I'm getting this info by using the method: getSellPrice(). This method returns this info:

```<code>Coinbase\Wallet\Value\Money Object ( [amount:Coinbase\Wallet\Value\Money:private] => 2250.47 [currency:Coinbase\Wallet\Value\Money:private] => USD )
</code>```

So far so good. But how do I get these values saved in my database? Breaking it down I have the following sub-questions:

How do extract the values "amount=>2250.47" and "currency=>USD"?

How do I save these 2 values in the corresponding columns "amount" and "currency" in my database?

What exact script do I need /steps to follow?

Just some general info. I'm using XAMPP as local server.

This is the code which I have so far:

`

```<code><?php

require_once __DIR__ . '/vendor/autoload.php';
use Coinbase\Wallet\Client;
use Coinbase\Wallet\Configuration;

//Connect with credentials.
$apiKey = 'xxx';
$apiSecret = 'xxx';

$configuration = Configuration::apiKey($apiKey, $apiSecret);

$client = Client::create($configuration);

$sellPrice = $client->getSellPrice('BTC-USD');
print_r ($sellPrice);

//So far it works fine.

?>
</code>```

`

I have set up a table by using this query:

```<code>`CREATE TABLE `data` (
`id` BIGINT UNSIGNED NOT NULL ,
`time_stamp` BIGINT UNSIGNED NOT NULL ,
`currency` VARCHAR( 255 ) NOT NULL ,
`amount` BIGINT UNSIGNED NOT NULL ,
PRIMARY KEY ( `id` )
);
</code>```

`

Every help is welcome or pointing me in the right direction. And is much appreciated!

Cheers

答:
TRY This code to get amount and currency

```<code>$sellPrice = $client->getSellPrice('BTC-USD');
$amount=$sellPrice->getAmount();
$currency=$sellPrice->getCurrency();
</code>```

Hope it will work

Body:
I'm a bit stuck here. I'm building an app based on the Coinbase PHP API V2.

This is what I'm trying to achieve. I would like to place the currency code (for e.g. EUR or USD) and the corresponding sell price at the moment of calling in my local MySQL database (ideal also including a timestamp).

I'm getting this info by using the method: getSellPrice(). This method returns this info:

Coinbase\Wallet\Value\Money Object ( [amount:Coinbase\Wallet\Value\Money:private] => 2250.47 [currency:Coinbase\Wallet\Value\Money:private] => USD )

So far so good. But how do I get these values saved in my database? Breaking it down I have the following sub-questions:

How do extract the values "amount=>2250.47" and "currency=>USD"?

How do I save these 2 values in the corresponding columns "amount" and "currency" in my database?

What exact script do I need /steps to follow?

Just some general info. I'm using XAMPP as local server.

This is the code which I have so far:

`

<?php

require_once __DIR__ . '/vendor/autoload.php';
use Coinbase\Wallet\Client;
use Coinbase\Wallet\Configuration;

//Connect with credentials.
$apiKey = 'xxx';
$apiSecret = 'xxx';

$configuration = Configuration::apiKey($apiKey, $apiSecret);

$client = Client::create($configuration);

$sellPrice = $client->getSellPrice('BTC-USD');
print_r ($sellPrice);

//So far it works fine.

?>

`

I have set up a table by using this query:

`CREATE TABLE `data` (
`id` BIGINT UNSIGNED NOT NULL ,
`time_stamp` BIGINT UNSIGNED NOT NULL ,
`currency` VARCHAR( 255 ) NOT NULL ,
`amount` BIGINT UNSIGNED NOT NULL ,
PRIMARY KEY ( `id` )
);

`

Every help is welcome or pointing me in the right direction. And is much appreciated!

Cheers

Body:
TRY This code to get amount and currency

$sellPrice = $client->getSellPrice('BTC-USD');
$amount=$sellPrice->getAmount();
$currency=$sellPrice->getCurrency();

Hope it will work


问:
Polymer Javascript Dom-Repeat Button Group Issue
I'm relatively new to Polymer and I am trying to create a button group with a button corresponding to each entry in a property array. Here is the code that I have so far:

           <template is="dom-repeat" items="{{floorCount}}">
             <input id="button-[[index]]" name="btn-group" type="radio">
             [[item]]
           </template>
           <input id="idAll" name="btn-group"  type="radio">
           All

         ```
</div>
</div>
</p>

<p>The floor count property has been included below.</p>

```floorCount:{
      type: Array,
      value: function(){
        return ["1"];
      }
    }
```

The issue is that it correctly creates each of the buttons, but for some reason, you can only click on the "idAll" button in the group. This dom-repeat and binding is somehow breaking the functionality of the group. Any help would be appreciated, thanks!

答: Polymer does not like to concat Strings in properties on the fly id$="[[_getId(index)]]" also when writing into a html default property add an $, same for the style property.

Body:
I'm relatively new to Polymer and I am trying to create a button group with a button corresponding to each entry in a property array. Here is the code that I have so far:

           <template is="dom-repeat" items="{{floorCount}}">
             <input id="button-[[index]]" name="btn-group" type="radio">
             [[item]]
           </template>
           <input id="idAll" name="btn-group"  type="radio">
           All

The floor count property has been included below.

floorCount:{
      type: Array,
      value: function(){
        return ["1"];
      }
    }

The issue is that it correctly creates each of the buttons, but for some reason, you can only click on the "idAll" button in the group. This dom-repeat and binding is somehow breaking the functionality of the group. Any help would be appreciated, thanks!


问:
Getting two different result for pow() function on two different Linux OS
Here is my code

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

void main(void)
{
    printf("pow as double: %lf\n\r", pow(2,32));
    printf("pow as long int: %ld\n\r", ((long int)pow(2,32)));
}
</code>```

I compiled the code on 2 different Linux OS. (gcc powfn.c -o powfn)

On VirtualBox Ubuntu, I got the following result

```<code>pow as double: 4294967296.000000
pow as long int: 4294967296
</code>```

On Debian GNU/Linux 8 OS running on a Znyq ARM Cortex A9 processor, I got the following result

```<code>pow as double: 4294967296.000000
pow as long int: 2147483647
</code>```

What is going on? Why the two different results?

答:
It's highly likely the two processors have different sizes for the same data types. You can test it by compiling and running this code on both machines:

#include <stdio.h>
int main()
{
    int integerType;
    long int longIntType;
    float floatType;
    double doubleType;
    char charType;

    // Sizeof operator is used to evaluate the size of a variable
    printf("Size of int: %ld bytes\n",sizeof(integerType));
    printf("Size of long int: %ld bytes\n",sizeof(longIntType));
    printf("Size of float: %ld bytes\n",sizeof(floatType));
    printf("Size of double: %ld bytes\n",sizeof(doubleType));
    printf("Size of char: %ld byte\n",sizeof(charType));

    return 0;
}
```

<p>Here is the result of running the program on a Wandboard with Cortex-A9 and Ubuntu 15.10:</p>

```wandboard:~$ ./test.exe
Size of int: 4 bytes
Size of long int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of char: 1 byte
```

Body:
Here is my code

#include<stdio.h>
#include<math.h>

void main(void)
{
    printf("pow as double: %lf\n\r", pow(2,32));
    printf("pow as long int: %ld\n\r", ((long int)pow(2,32)));
}

I compiled the code on 2 different Linux OS. (gcc powfn.c -o powfn)

On VirtualBox Ubuntu, I got the following result

pow as double: 4294967296.000000
pow as long int: 4294967296

On Debian GNU/Linux 8 OS running on a Znyq ARM Cortex A9 processor, I got the following result

pow as double: 4294967296.000000
pow as long int: 2147483647

What is going on? Why the two different results?

Body:
It's highly likely the two processors have different sizes for the same data types. You can test it by compiling and running this code on both machines:

#include <stdio.h>
int main()
{
    int integerType;
    long int longIntType;
    float floatType;
    double doubleType;
    char charType;

    // Sizeof operator is used to evaluate the size of a variable
    printf("Size of int: %ld bytes\n",sizeof(integerType));
    printf("Size of long int: %ld bytes\n",sizeof(longIntType));
    printf("Size of float: %ld bytes\n",sizeof(floatType));
    printf("Size of double: %ld bytes\n",sizeof(doubleType));
    printf("Size of char: %ld byte\n",sizeof(charType));

    return 0;
}

Here is the result of running the program on a Wandboard with Cortex-A9 and Ubuntu 15.10:

wandboard:~$ ./test.exe
Size of int: 4 bytes
Size of long int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of char: 1 byte


问:
iPhone memory leak
I know that there are memory leaks that are no big deal or are out of the individual developer's control as they are in the sdk itself, but the one I'm seeing is 32KB on the iPhone 4 build against iOS SDK 4.2.  I have not been able to trigger this on a 3GS.  It happens in response to user interaction (in response to opening the photo library, and the leak seems to happen while I'm in the photo library), so it could build up quickly.

Here's the stack trace I'm seeing on the iPhone 4:

```<code>   0 libSystem.B.dylib calloc
   1  0x317e8363
   2  0x317e9c41
   3  0x318273ff
   4  0x31827ea5
   5  0x302ea49d
   6  0x302ebe07
   7  0x302eb7c3
   8  0x302ebcab
   9  0x303304cd
  10 UIKit -[UINavigationController _startTransition:fromViewController:toViewController:]
  11 UIKit -[UINavigationController _startDeferredTransitionIfNeeded]
  12 UIKit -[UINavigationController viewWillLayoutSubviews]
  13 UIKit -[UILayoutContainerView layoutSubviews]
  14 UIKit -[UIView(CALayerDelegate) layoutSublayersOfLayer:]
  15 CoreFoundation -[NSObject(NSObject) performSelector:withObject:]
  16 QuartzCore -[CALayer layoutSublayers]
  17 QuartzCore CALayerLayoutIfNeeded
  18 QuartzCore CA::Context::commit_transaction(CA::Transaction*)
  19 QuartzCore CA::Transaction::commit()
  20 QuartzCore CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*)
  21 CoreFoundation __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__
  22 CoreFoundation __CFRunLoopDoObservers
  23 CoreFoundation __CFRunLoopRun
  24 CoreFoundation CFRunLoopRunSpecific
  25 CoreFoundation CFRunLoopRunInMode
  26 GraphicsServices GSEventRunModal
  27 GraphicsServices GSEventRun
  28 UIKit -[UIApplication _run]
  29 UIKit UIApplicationMain
  30 MyApp main /Users/david/src/MyApp/main.m:14
  31 MyApp start
</code>```

I don't see my code anywhere here and I'm not sure what to do to inspect the symbols with addresses.  Any ideas?  Could this have something to do with the sublayers I'm adding?  (That's the only thing I see here that I might have control over.)

Thanks for any help.

Edit:  As GojaN's question points out (Thanks, GojaN), I completely forgot to mention that this is showing up in instruments as:

```<code>Leaked Object # Address Size Responsible Library Responsible Frame
GeneralBlock-36864   0x4ff3000 36864 UIKit -[UINavigationController _startTransition:fromViewController:toViewController:]
</code>```

答:
Do you know it's a leak? It's quite possible it's a cache. (Semi-related: I saw memory keep growing in my PDF viewing app, which looked like a leak. But it was apparently caching each page, and they all went away when I closed the PDF doc.)

Leaks usually happen in Simulator as well as device, does it happen there?

This is code running in the run loop but likely initiated by your code. So does this block get leaked every time you run your code?

Title: iPhone memory leak

Body:
I know that there are memory leaks that are no big deal or are out of the individual developer's control as they are in the sdk itself, but the one I'm seeing is 32KB on the iPhone 4 build against iOS SDK 4.2.  I have not been able to trigger this on a 3GS.  It happens in response to user interaction (in response to opening the photo library, and the leak seems to happen while I'm in the photo library), so it could build up quickly.

Here's the stack trace I'm seeing on the iPhone 4:

   0 libSystem.B.dylib calloc
   1  0x317e8363
   2  0x317e9c41
   3  0x318273ff
   4  0x31827ea5
   5  0x302ea49d
   6  0x302ebe07
   7  0x302eb7c3
   8  0x302ebcab
   9  0x303304cd
  10 UIKit -[UINavigationController _startTransition:fromViewController:toViewController:]
  11 UIKit -[UINavigationController _startDeferredTransitionIfNeeded]
  12 UIKit -[UINavigationController viewWillLayoutSubviews]
  13 UIKit -[UILayoutContainerView layoutSubviews]
  14 UIKit -[UIView(CALayerDelegate) layoutSublayersOfLayer:]
  15 CoreFoundation -[NSObject(NSObject) performSelector:withObject:]
  16 QuartzCore -[CALayer layoutSublayers]
  17 QuartzCore CALayerLayoutIfNeeded
  18 QuartzCore CA::Context::commit_transaction(CA::Transaction*)
  19 QuartzCore CA::Transaction::commit()
  20 QuartzCore CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*)
  21 CoreFoundation __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__
  22 CoreFoundation __CFRunLoopDoObservers
  23 CoreFoundation __CFRunLoopRun
  24 CoreFoundation CFRunLoopRunSpecific
  25 CoreFoundation CFRunLoopRunInMode
  26 GraphicsServices GSEventRunModal
  27 GraphicsServices GSEventRun
  28 UIKit -[UIApplication _run]
  29 UIKit UIApplicationMain
  30 MyApp main /Users/david/src/MyApp/main.m:14
  31 MyApp start

I don't see my code anywhere here and I'm not sure what to do to inspect the symbols with addresses.  Any ideas?  Could this have something to do with the sublayers I'm adding?  (That's the only thing I see here that I might have control over.)

Thanks for any help.

Edit:  As GojaN's question points out (Thanks, GojaN), I completely forgot to mention that this is showing up in instruments as:

Leaked Object # Address Size Responsible Library Responsible Frame
GeneralBlock-36864   0x4ff3000 36864 UIKit -[UINavigationController _startTransition:fromViewController:toViewController:]


问:
Atomic read and delete in mongo
I am fairly new to mongo, so what I'm trying to achieve here might not be possible. My research so far is inconclusive...

My scenario is the following: I have an application which may have multiple instances running. These instances are processing some data, and when that processing fails, they write the ID of the failed item in a mongo collection ("error").

From time to time I want to retry processing those items. So, at fixed intervals, the application reads all the IDs from the collection, after which it deletes all the records. Now, this is an obvious race condition. Two instances may read the very same data, which would double the work to be done. Some IDs may also be missed like this.

My question would be the following: is there any way I can read and delete those records, in a distributed-atomic way? I was thinking about locking the collection, but for this I found no support so far in the java driver's documentation. I also tried to look for a findAndDrop() like method, but no luck so far.

I am aware of techniques like leader election, which most probably would solve this problem, but I wanted to see if it can be done in an easier way.

答: You can use BlockingQueue with multiple producer-single consumer approach, as you have multiple producer to produce ids and delete them with single consumer.

Title: Atomic read and delete in mongo


问:
Magento - get the custom attribute value for products in an external PHP script
does anyone know how I can get the custom attribute value for products in an PHP script (that we have in he root of the server which is used to generate XML an feed) ?

The custom attribute is property_type. Others work but not that one. Here is the code:

```<code>foreach ($arrayObj  as $row ) {
//get data
$pro_item = getPropertyItem($row['entity_id'],$pdo);
$images = getImages($row['entity_id'],$pdo);
$term = getTerm($row['entity_id'],$pdo);
$local=getLocation($row['entity_id'],$pdo);
// create tags and data
$item = $xml->createElement('item');
$i_status = $xml->createElement('status',getStatus($row['entity_id'],$pdo));
$i_propertyType = $xml->createElement('propertyType',$row['property_type']);
$i_title = $xml->createElement('title',htmlentities(removeAt($pro_item['title'])));

$i_projectName = $xml->createElement('projectName',getBuilding($local,$pro_item['title']));

$i_description = $xml->createElement('description',htmlentities(removeAt($pro_item['description'])));
</code>```

答:
Need to add the below line in header part of script.

Mage::app('admin');

Set Used in Product Listing option to YES in admin panel attribute edit section.

Body:
does anyone know how I can get the custom attribute value for products in an PHP script (that we have in he root of the server which is used to generate XML an feed) ?

The custom attribute is property_type. Others work but not that one. Here is the code:

foreach ($arrayObj  as $row ) {
//get data
$pro_item = getPropertyItem($row['entity_id'],$pdo);
$images = getImages($row['entity_id'],$pdo);
$term = getTerm($row['entity_id'],$pdo);
$local=getLocation($row['entity_id'],$pdo);
// create tags and data
$item = $xml->createElement('item');
$i_status = $xml->createElement('status',getStatus($row['entity_id'],$pdo));
$i_propertyType = $xml->createElement('propertyType',$row['property_type']);
$i_title = $xml->createElement('title',htmlentities(removeAt($pro_item['title'])));

$i_projectName = $xml->createElement('projectName',getBuilding($local,$pro_item['title']));

$i_description = $xml->createElement('description',htmlentities(removeAt($pro_item['description'])));