问:
SSMS can't connect to remote server, crashes
I installed Microsoft SQL Server Management Studio v17.3 on a Windows 10 box.  I created a Central Management Server instance and successfully connected to it.

I created a second Central Management Server instance to a different URL and the Test connection passed.  However, the second Central Management Server instance fails to appear in the Server name drop-down of Connect to Server.  Instead, an old instance that I first created and have since deleted appears.

When I click to Browse for Servers I get a long list under Database Engine but not the server that I want.

When I right-click on the Registered Server (the second one that I created and which doesn't appear in the drop-down) and select Object Explorer, SSMS stopped working message followed by SSMS is restarting.

Event Viewer reports two errors.  From top to bottom:

```<code>Event 1000, Application Error

Faulting application name: Ssms.exe, version: 2017.140.17199.0, time stamp:    0x59d44f4f
Faulting module name: KERNELBASE.dll, version: 10.0.15063.674, time stamp: 0x6d16dd24
Exception code: 0xe0434352
Fault offset: 0x000eb872
Faulting process id: 0x22c8
Faulting application start time: 0x01d35a6d01c23a7f
Faulting application path: C:\Program Files (x86)\Microsoft SQL    Server\140\Tools\Binn\ManagementStudio\Ssms.exe
Faulting module path: C:\WINDOWS\System32\KERNELBASE.dll
Report Id: 7597bf9e-4992-4f78-ac09-2bdb12a4ee2f
Faulting package full name:
Faulting package-relative application ID:
</code>```

The second error is:

```<code>Event 1026, .NET Runtime

Application: Ssms.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Data.SqlClient.SqlException
   at Microsoft.SqlServer.Management.Common.ConnectionManager.ExecuteTSql(ExecuteTSqlAction, System.Object, System.Data.DataSet, Boolean)
   at Microsoft.SqlServer.Management.Common.ServerConnection.GetExecuteReader(System.Data.SqlClient.SqlCommand)

Exception Info: Microsoft.SqlServer.Management.Common.ExecutionFailureException
   at Microsoft.SqlServer.Management.Common.ServerConnection.GetExecuteReader(System.Data.SqlClient.SqlCommand)
   at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteReader(System.String, System.Data.SqlClient.SqlCommand ByRef)
   at Microsoft.SqlServer.Management.Sdk.Sfc.ExecuteSql.GetDataReader(System.String, System.Data.SqlClient.SqlCommand ByRef)
   at Microsoft.SqlServer.Management.Sdk.Sfc.DataProvider.SetConnectionAndQuery(Microsoft.SqlServer.Management.Sdk.Sfc.ExecuteSql, System.String)
   at Microsoft.SqlServer.Management.Sdk.Sfc.ExecuteSql.GetDataProvider(System.Collections.Specialized.StringCollection, System.Object, Microsoft.SqlServer.Management.Sdk.Sfc.StatementBuilder, RetriveMode)
   at Microsoft.SqlServer.Management.Sdk.Sfc.SqlObjectBase.FillData(Microsoft.SqlServer.Management.Sdk.Sfc.ResultType, System.Collections.Specialized.StringCollection, System.Object, Microsoft.SqlServer.Management.Sdk.Sfc.StatementBuilder)
   at Microsoft.SqlServer.Management.Sdk.Sfc.SqlObjectBase.FillDataWithUseFailure(Microsoft.SqlServer.Management.Sdk.Sfc.SqlEnumResult, Microsoft.SqlServer.Management.Sdk.Sfc.ResultType)
   at Microsoft.SqlServer.Management.Sdk.Sfc.SqlObjectBase.BuildResult(Microsoft.SqlServer.Management.Sdk.Sfc.EnumResult)
   at Microsoft.SqlServer.Management.Sdk.Sfc.SqlObjectBase.GetData(Microsoft.SqlServer.Management.Sdk.Sfc.EnumResult)
   at Microsoft.SqlServer.Management.Sdk.Sfc.Environment.GetData()
   at Microsoft.SqlServer.Management.Sdk.Sfc.Environment.GetData(Microsoft.SqlServer.Management.Sdk.Sfc.Request, System.Object)
   at Microsoft.SqlServer.Management.Sdk.Sfc.Enumerator.GetData(System.Object, Microsoft.SqlServer.Management.Sdk.Sfc.Request)
   at Microsoft.SqlServer.Management.Sdk.Sfc.SfcInstance.GetInitDataReader(Microsoft.SqlServer.Management.Common.ISfcConnection, Microsoft.SqlServer.Management.Sdk.Sfc.Urn, System.String[], Microsoft.SqlServer.Management.Sdk.Sfc.OrderBy[])
   at Microsoft.SqlServer.Management.Sdk.Sfc.SfcInstance.Initialize()
   at Microsoft.SqlServer.Management.Sdk.Sfc.SfcCollection`3[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].CreateAndInitializeChildObject(System.__Canon)
   at Microsoft.SqlServer.Management.Sdk.Sfc.SfcCollatedDictionaryCollection`3[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].GetObjectByKey(System.__Canon)
   at Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore.get_DatabaseEngineServerGroup()
   at Microsoft.SqlServer.Management.RegisteredServers.SharedServer.GetServerGroupByType(Microsoft.SqlServer.Management.Common.ServerType)
   at Microsoft.SqlServer.Management.RegisteredServers.Utils.GetServerGroupFromNode(System.Windows.Forms.TreeNode, Microsoft.SqlServer.Management.Common.ServerType)
   at Microsoft.SqlServer.Management.RegisteredServers.RegisteredServerTree.get_SelectedNodeAsServerGroup()
   at Microsoft.SqlServer.Management.RegisteredServers.RegisteredServerTree.ConnectOeToCurrentNode(Boolean)
   at Microsoft.SqlServer.Management.RegisteredServers.RegisteredServerTree.OnConnectOeToCurrentNode(System.Object, System.EventArgs)
   at System.Windows.Forms.MenuItem.OnClick(System.EventArgs)
   at System.Windows.Forms.MenuItem+MenuItemData.Execute()
   at System.Windows.Forms.Command.Invoke()
   at System.Windows.Forms.Command.DispatchID(Int32)
   at System.Windows.Forms.Control.WmCommand(System.Windows.Forms.Message ByRef)
   at System.Windows.Forms.Control.WndProc(System.Windows.Forms.Message ByRef)
   at System.Windows.Forms.TreeView.WndProc(System.Windows.Forms.Message ByRef)
   at System.Windows.Forms.Control+ControlNativeWindow.OnMessage(System.Windows.Forms.Message ByRef)
   at System.Windows.Forms.Control+ControlNativeWindow.WndProc(System.Windows.Forms.Message ByRef)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr, Int32, IntPtr, IntPtr)
</code>```

I have tried uninstalling and reinstalling SSMS.  I installed the latest
Visual C++ 2013 Redistributable Package. Version 12.00.40660.

I also installed Visual Studio Express in the hope that it might fix any .NET problems.

The DBA can login to the remote server using my credentials so it is something on my machine. Any help would be greatly appreciated.

答:
I ran a repair on the SSMS installation.  After that, the error became clear; it was a permission's error. The DBA gave me access to one database but that database depended on a second database.  Once the DBA gave my userId permission to access that second database everything worked.

As to why a new install needed a repair; no idea. Repeated uninstall/reinstalls of SSMS didn't fix it.

Body:
I installed Microsoft SQL Server Management Studio v17.3 on a Windows 10 box.  I created a Central Management Server instance and successfully connected to it.

I created a second Central Management Server instance to a different URL and the Test connection passed.  However, the second Central Management Server instance fails to appear in the Server name drop-down of Connect to Server.  Instead, an old instance that I first created and have since deleted appears.

When I click to Browse for Servers I get a long list under Database Engine but not the server that I want.

When I right-click on the Registered Server (the second one that I created and which doesn't appear in the drop-down) and select Object Explorer, SSMS stopped working message followed by SSMS is restarting.

Event Viewer reports two errors.  From top to bottom:

Event 1000, Application Error

Faulting application name: Ssms.exe, version: 2017.140.17199.0, time stamp:    0x59d44f4f
Faulting module name: KERNELBASE.dll, version: 10.0.15063.674, time stamp: 0x6d16dd24
Exception code: 0xe0434352
Fault offset: 0x000eb872
Faulting process id: 0x22c8
Faulting application start time: 0x01d35a6d01c23a7f
Faulting application path: C:\Program Files (x86)\Microsoft SQL    Server\140\Tools\Binn\ManagementStudio\Ssms.exe
Faulting module path: C:\WINDOWS\System32\KERNELBASE.dll
Report Id: 7597bf9e-4992-4f78-ac09-2bdb12a4ee2f
Faulting package full name:
Faulting package-relative application ID:

The second error is:

Event 1026, .NET Runtime

Application: Ssms.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Data.SqlClient.SqlException
   at Microsoft.SqlServer.Management.Common.ConnectionManager.ExecuteTSql(ExecuteTSqlAction, System.Object, System.Data.DataSet, Boolean)
   at Microsoft.SqlServer.Management.Common.ServerConnection.GetExecuteReader(System.Data.SqlClient.SqlCommand)

Exception Info: Microsoft.SqlServer.Management.Common.ExecutionFailureException
   at Microsoft.SqlServer.Management.Common.ServerConnection.GetExecuteReader(System.Data.SqlClient.SqlCommand)
   at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteReader(System.String, System.Data.SqlClient.SqlCommand ByRef)
   at Microsoft.SqlServer.Management.Sdk.Sfc.ExecuteSql.GetDataReader(System.String, System.Data.SqlClient.SqlCommand ByRef)
   at Microsoft.SqlServer.Management.Sdk.Sfc.DataProvider.SetConnectionAndQuery(Microsoft.SqlServer.Management.Sdk.Sfc.ExecuteSql, System.String)
   at Microsoft.SqlServer.Management.Sdk.Sfc.ExecuteSql.GetDataProvider(System.Collections.Specialized.StringCollection, System.Object, Microsoft.SqlServer.Management.Sdk.Sfc.StatementBuilder, RetriveMode)
   at Microsoft.SqlServer.Management.Sdk.Sfc.SqlObjectBase.FillData(Microsoft.SqlServer.Management.Sdk.Sfc.ResultType, System.Collections.Specialized.StringCollection, System.Object, Microsoft.SqlServer.Management.Sdk.Sfc.StatementBuilder)
   at Microsoft.SqlServer.Management.Sdk.Sfc.SqlObjectBase.FillDataWithUseFailure(Microsoft.SqlServer.Management.Sdk.Sfc.SqlEnumResult, Microsoft.SqlServer.Management.Sdk.Sfc.ResultType)
   at Microsoft.SqlServer.Management.Sdk.Sfc.SqlObjectBase.BuildResult(Microsoft.SqlServer.Management.Sdk.Sfc.EnumResult)
   at Microsoft.SqlServer.Management.Sdk.Sfc.SqlObjectBase.GetData(Microsoft.SqlServer.Management.Sdk.Sfc.EnumResult)
   at Microsoft.SqlServer.Management.Sdk.Sfc.Environment.GetData()
   at Microsoft.SqlServer.Management.Sdk.Sfc.Environment.GetData(Microsoft.SqlServer.Management.Sdk.Sfc.Request, System.Object)
   at Microsoft.SqlServer.Management.Sdk.Sfc.Enumerator.GetData(System.Object, Microsoft.SqlServer.Management.Sdk.Sfc.Request)
   at Microsoft.SqlServer.Management.Sdk.Sfc.SfcInstance.GetInitDataReader(Microsoft.SqlServer.Management.Common.ISfcConnection, Microsoft.SqlServer.Management.Sdk.Sfc.Urn, System.String[], Microsoft.SqlServer.Management.Sdk.Sfc.OrderBy[])
   at Microsoft.SqlServer.Management.Sdk.Sfc.SfcInstance.Initialize()
   at Microsoft.SqlServer.Management.Sdk.Sfc.SfcCollection`3[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].CreateAndInitializeChildObject(System.__Canon)
   at Microsoft.SqlServer.Management.Sdk.Sfc.SfcCollatedDictionaryCollection`3[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].GetObjectByKey(System.__Canon)
   at Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore.get_DatabaseEngineServerGroup()
   at Microsoft.SqlServer.Management.RegisteredServers.SharedServer.GetServerGroupByType(Microsoft.SqlServer.Management.Common.ServerType)
   at Microsoft.SqlServer.Management.RegisteredServers.Utils.GetServerGroupFromNode(System.Windows.Forms.TreeNode, Microsoft.SqlServer.Management.Common.ServerType)
   at Microsoft.SqlServer.Management.RegisteredServers.RegisteredServerTree.get_SelectedNodeAsServerGroup()
   at Microsoft.SqlServer.Management.RegisteredServers.RegisteredServerTree.ConnectOeToCurrentNode(Boolean)
   at Microsoft.SqlServer.Management.RegisteredServers.RegisteredServerTree.OnConnectOeToCurrentNode(System.Object, System.EventArgs)
   at System.Windows.Forms.MenuItem.OnClick(System.EventArgs)
   at System.Windows.Forms.MenuItem+MenuItemData.Execute()
   at System.Windows.Forms.Command.Invoke()
   at System.Windows.Forms.Command.DispatchID(Int32)
   at System.Windows.Forms.Control.WmCommand(System.Windows.Forms.Message ByRef)
   at System.Windows.Forms.Control.WndProc(System.Windows.Forms.Message ByRef)
   at System.Windows.Forms.TreeView.WndProc(System.Windows.Forms.Message ByRef)
   at System.Windows.Forms.Control+ControlNativeWindow.OnMessage(System.Windows.Forms.Message ByRef)
   at System.Windows.Forms.Control+ControlNativeWindow.WndProc(System.Windows.Forms.Message ByRef)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr, Int32, IntPtr, IntPtr)

I have tried uninstalling and reinstalling SSMS.  I installed the latest
Visual C++ 2013 Redistributable Package. Version 12.00.40660.

I also installed Visual Studio Express in the hope that it might fix any .NET problems.

The DBA can login to the remote server using my credentials so it is something on my machine. Any help would be greatly appreciated.


来源: stackexchange

问:
wso2 api manager modify JSON payload sent to backend
I have REST API URL defined as

https://hostname/[version]/[service]/[operation]

and I would like to transform JSON payload in WSO2 API Manager in order to put version and operation inside.

So the WSO2 will send it to backend in the following form:

```<code>POST https://backend/[service]
{
    “version”: [version],
    “operation”: [operation]
}
</code>```

So I need to put version and operation from URL to JSON payload. How to do it?

答:
As I understand you want to create a new payload and POST with values from the resource URI definition (not API context).

Lets assume:

you don't want to change the method (the resource is having POST method).

the original request posted is JSON as well

You may want to create a (synapse) mediation flow as for ESB building such a message.

Plugging in the mediation is described in the documentation Adding Mediation Extensions. This mediation will be executed for every request of the API

Having resource https://hostname/[version]/[service]/[operation]

In the mediation, you may build the JSON payload

```<code><payloadFactory media-type="json">
  <format>{
      "version":"$1",
      "service": "$2",
      "some_original_data": "$3"
    }</format>
  <args>
    <arg  expression="get-property('uri.var.version')"/>
    <arg  expression="get-property('uri.var.service')"/>
    <arg  expression="$.person.name" evaluator="json" />
  </args>
</payloadFactory>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have REST API URL defined as

https://hostname/[version]/[service]/[operation]

and I would like to transform JSON payload in WSO2 API Manager in order to put version and operation inside.

So the WSO2 will send it to backend in the following form:

POST https://backend/[service]
{
    “version”: [version],
    “operation”: [operation]
}

So I need to put version and operation from URL to JSON payload. How to do it?

Body:
As I understand you want to create a new payload and POST with values from the resource URI definition (not API context).

Lets assume:

you don't want to change the method (the resource is having POST method).

the original request posted is JSON as well

You may want to create a (synapse) mediation flow as for ESB building such a message.

Plugging in the mediation is described in the documentation Adding Mediation Extensions. This mediation will be executed for every request of the API

Having resource https://hostname/[version]/[service]/[operation]

In the mediation, you may build the JSON payload

<payloadFactory media-type="json">
  <format>{
      "version":"$1",
      "service": "$2",
      "some_original_data": "$3"
    }</format>
  <args>
    <arg  expression="get-property('uri.var.version')"/>
    <arg  expression="get-property('uri.var.service')"/>
    <arg  expression="$.person.name" evaluator="json" />
  </args>
</payloadFactory>


问:
.htaccess Rewrite all
I have the following rules in .htaccess. Unfortunately, it does not work due to the last rule (everything else works fine). Why?

```<code>Options -Indexes
RewriteEngine On
RewriteRule ^(cdn) - [L]
RewriteRule ^admin/(.*)$ backend_0.0.1/index.php/$1 [QSA,L]
RewriteRule ^css/(.*)$ frontend_0.0.1/css.php/$1 [NC,QSA,E=no-gzip:1,L]
RewriteRule ^js/(.*)$ frontend_0.0.1/js.php/$1 [NC,QSA,E=no-gzip:1,L]
RewriteRule ^(.*)$ frontend_0.0.1/index.php/$1 [QSA,L]
</code>```

If I replace the last line by:

```<code>RewriteRule ^(.*)$ frontend_0.0.1/index.php?q=$1 [QSA,L]
</code>```

Then it suddenly starts to work but previous rules are skipped and only this last rule is applied. But I need rules to stop rewriting once the first one mathches.

答:
You need to exclude the destinations you are redirecting to:</p>

```<code>RewriteCond $1 !^(backend_0\.0\.1|frontend_0\.0\.1)/
RewriteRule ^(.*)$ frontend_0.0.1/index.php/$1 [QSA,L]
</code>```

ContentLicense: CC BY-SA 2.5

Title: .htaccess Rewrite all

Body:
I have the following rules in .htaccess. Unfortunately, it does not work due to the last rule (everything else works fine). Why?

Options -Indexes
RewriteEngine On
RewriteRule ^(cdn) - [L]
RewriteRule ^admin/(.*)$ backend_0.0.1/index.php/$1 [QSA,L]
RewriteRule ^css/(.*)$ frontend_0.0.1/css.php/$1 [NC,QSA,E=no-gzip:1,L]
RewriteRule ^js/(.*)$ frontend_0.0.1/js.php/$1 [NC,QSA,E=no-gzip:1,L]
RewriteRule ^(.*)$ frontend_0.0.1/index.php/$1 [QSA,L]

If I replace the last line by:

RewriteRule ^(.*)$ frontend_0.0.1/index.php?q=$1 [QSA,L]

Then it suddenly starts to work but previous rules are skipped and only this last rule is applied. But I need rules to stop rewriting once the first one mathches.

Body:
You need to exclude the destinations you are redirecting to:

RewriteCond $1 !^(backend_0\.0\.1|frontend_0\.0\.1)/
RewriteRule ^(.*)$ frontend_0.0.1/index.php/$1 [QSA,L]


问:
Preprocessor batch for all structure members
Is it possible to write a preprocessor macro that automatically iterates for all members of a structure?

I have such a structure (automatically generated from a Simulink model):

```<code>typedef struct {
  real_T driveStatusword;
  real_T posSensor[2];
  real_T softAbortDemand;
} ExtU_motionCtrlRTOS_T;
</code>```

And a similar one:

```<code>struct CoreInputOffsets
{
    uint32_t driveStatusword;
    uint32_t posSensor;
    uint32_t softAbortDemand;
};
</code>```

And I would like to do such an operation:

```<code>void getCoreInputOffsets(CoreInputOffsets* pCoreInputOffsets)
{
    pCoreInputOffsets->driveStatusword = offsetof(ExtU_motionCtrlRTOS_T, driveStatusword);
    pCoreInputOffsets->posSensor = offsetof(ExtU_motionCtrlRTOS_T, posSensor);
    pCoreInputOffsets->softAbortDemand = offsetof(ExtU_motionCtrlRTOS_T, softAbortDemand);
}
</code>```

But without having to edit this function each time the structure changes, by iterating for all members of CoreInputOffsets.

答:
from c++14, yes we do have compile time reflection of (almost all) aggregate types, see Antony Polukhin's magic get library (and this cppcon presentation to see how it works). I think you can also make it work in c++11 with some ABI support.

For example, to assign to an ExtU_motionCtrlRTOS_T x; you'd simply write

```<code>boost::pfr::flat_structure_tie(x) = boost::pfr::flat_structure_tie(some_unrelated_pod);
</code>```

where I assumed that members are assigned in order. Note that I used the flat tie version, to assign nested arrays element-wise.

Now, in light of the above, it would be wiser to avoid relying on offsetof() as you're doing now and just exploit all compile time info for related operations (this will also probably give you faster code).

Anyway, if you still want to get offsets, a verbatim transcription of your code may look like:

```<code>#include <boost/pfr/flat/core.hpp>

struct CoreInputOffsets
{
    uint32_t driveStatusword;
    uint32_t posSensor[2];
    uint32_t softAbortDemand;
};

template <typename T,std::size_t... Is>
void assignOffsets( CoreInputOffsets& offsets, std::index_sequence<Is...> )
{
  T t;
  (( boost::pfr::flat_get<Is>(offsets) = reinterpret_cast<char*>(&boost::pfr::flat_get<Is>(t)) - reinterpret_cast<char*>(&boost::pfr::flat_get<0>(t)) ), ...);
}

template <typename T>
void assignOffsets( CoreInputOffsets& offsets )
{
  assignOffsets<T>( offsets, std::make_index_sequence< boost::pfr::flat_tuple_size<T>::value >{} );
}

void getCoreInputOffsets(CoreInputOffsets* pCoreInputOffsets)
{
  assignOffsets<ExtU_motionCtrlRTOS_T>( *pCoreInputOffsets );
}
</code>```

with the caveats:

this is c++17 (you can make it c++14 compliant though)

the code taking the actual offsets needs a dummy ExtU_motionCtrlRTOS_T; this is not a big deal given that you'll assign it just once, I suppose

the code taking the actual offsets via pointer substraction gives undefined behavior standard-wise, you'll need to verify it's legal for your platform

CoreInputOffsets::posSensor shall be an array and will get two offsets now

Body:
Is it possible to write a preprocessor macro that automatically iterates for all members of a structure?

I have such a structure (automatically generated from a Simulink model):

typedef struct {
  real_T driveStatusword;
  real_T posSensor[2];
  real_T softAbortDemand;
} ExtU_motionCtrlRTOS_T;

And a similar one:

struct CoreInputOffsets
{
    uint32_t driveStatusword;
    uint32_t posSensor;
    uint32_t softAbortDemand;
};

And I would like to do such an operation:

void getCoreInputOffsets(CoreInputOffsets* pCoreInputOffsets)
{
    pCoreInputOffsets->driveStatusword = offsetof(ExtU_motionCtrlRTOS_T, driveStatusword);
    pCoreInputOffsets->posSensor = offsetof(ExtU_motionCtrlRTOS_T, posSensor);
    pCoreInputOffsets->softAbortDemand = offsetof(ExtU_motionCtrlRTOS_T, softAbortDemand);
}

But without having to edit this function each time the structure changes, by iterating for all members of CoreInputOffsets.

Body:
from c++14, yes we do have compile time reflection of (almost all) aggregate types, see Antony Polukhin's magic get library (and this cppcon presentation to see how it works). I think you can also make it work in c++11 with some ABI support.

For example, to assign to an ExtU_motionCtrlRTOS_T x; you'd simply write

boost::pfr::flat_structure_tie(x) = boost::pfr::flat_structure_tie(some_unrelated_pod);

where I assumed that members are assigned in order. Note that I used the flat tie version, to assign nested arrays element-wise.

Now, in light of the above, it would be wiser to avoid relying on offsetof() as you're doing now and just exploit all compile time info for related operations (this will also probably give you faster code).

Anyway, if you still want to get offsets, a verbatim transcription of your code may look like:

#include <boost/pfr/flat/core.hpp>

struct CoreInputOffsets
{
    uint32_t driveStatusword;
    uint32_t posSensor[2];
    uint32_t softAbortDemand;
};

template <typename T,std::size_t... Is>
void assignOffsets( CoreInputOffsets& offsets, std::index_sequence<Is...> )
{
  T t;
  (( boost::pfr::flat_get<Is>(offsets) = reinterpret_cast<char*>(&boost::pfr::flat_get<Is>(t)) - reinterpret_cast<char*>(&boost::pfr::flat_get<0>(t)) ), ...);
}

template <typename T>
void assignOffsets( CoreInputOffsets& offsets )
{
  assignOffsets<T>( offsets, std::make_index_sequence< boost::pfr::flat_tuple_size<T>::value >{} );
}

void getCoreInputOffsets(CoreInputOffsets* pCoreInputOffsets)
{
  assignOffsets<ExtU_motionCtrlRTOS_T>( *pCoreInputOffsets );
}

with the caveats:

this is c++17 (you can make it c++14 compliant though)

the code taking the actual offsets needs a dummy ExtU_motionCtrlRTOS_T; this is not a big deal given that you'll assign it just once, I suppose

the code taking the actual offsets via pointer substraction gives undefined behavior standard-wise, you'll need to verify it's legal for your platform

CoreInputOffsets::posSensor shall be an array and will get two offsets now


问:
One field assigned null when deserialising JSON with Jackson in Spring Boot project
I'm calling an external API using Spring restTemplate. The returned JSON has the following content.

```<code>{
  "message": null,
  "responseStatus": "0",
  "accessInfo": {
    "access": {
      "message": "success",
      "token": {
        "expires": "xxxxx",
        "id": null,
        "UDID": null,
        "permissions": {
          "orgGroups": [],
          "channelGroups": [
            "xxxxx"
          ]
        }
      }
    }
  },
  "profile": {
    "message": null,
    "responseStatus": null,
    "UDID": "xxxxx",
    "name": null,
    "age": null,
    "gender": null,
    "maritalStatus": null,
    "familySize": null,
    "lat": null,
    "lon": null,
    "birthDay": null,
    "imageURL": null,
    "sessionId": "xxxxx",
    "FBId": null,
    "expiry": null,
    "email": "xxxxx",
    "workLocationLat": null,
    "workLocationLong": null,
    "workLocationAddress": null,
    "homeLocationAddress": null,
    "homeLocationLat": null,
    "homeLocationLong": null,
    "id": 789,
    "isFBIdAlreadyExists": false,
    "tagList": []
  }
}
</code>```

All the values are really what is returned except for those xxxxx which I masked. As you can see, there are two UDID fields in the JSON. One is in the node accessInfo > access > token which is null and the other in the node profile. The value in the second node is the one I'm interested in which is not supposed to be null.

I have created 2 POJOs as given below. I'm only interested in UDID and sessionId under profile node.

Parent POJO:

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class AgtAuthentication {

    private Profile profile;

}
</code>```

Child POJO:

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class Profile {

    private String sessionId;
    private String UDID;

}
</code>```

I have removed the getters and setters and no args constructors for brevity.

When I call the Api I receive the response and the JSON mapping works fine except for the UDID attribute. When I do a System.out.println() for the response body, I get the below result:

```<code>Authentication [profile = Profile [sessionId = xxxxx, UDID = null]]
</code>```

sessionId is correct. However, UDID is always null. Not sure if this is because there's a duplicate UDID value in the JSON. Can anyone help? Thanks.

EDIT: The code that calls the actual Api (xxxxx being masked values) is below:

```<code>private void setUuidAndSessionId() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> requestBody= new LinkedMultiValueMap<String, String>();
        requestBody.add("clientId", "xxxxx");
        requestBody.add("clientPassword", "xxxxx");
        requestBody.add("UDID", "");
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(requestBody, headers);

        RestTemplate restTemplate = new RestTemplate();

        String agtAuthUrl = "http://xxxxx";

        ResponseEntity<AgtAuthentication> response = restTemplate.exchange(agtAuthUrl, HttpMethod.POST, request, AgtAuthentication.class);

        System.out.println(response.getBody().toString());

        sessionId = response.getBody().getProfile().getSessionId();
        String tempUuid = response.getBody().getProfile().getUDID();
    }
</code>```

答:
I am assuming Jackson expects a field in the JSON named uDID - because of getter/setter method naming convention converting the first letter of field to uppercase.

You can try to annotate the Profile.getUDID() getter with @JsonProperty("UDID")

Body:
I'm calling an external API using Spring restTemplate. The returned JSON has the following content.

{
  "message": null,
  "responseStatus": "0",
  "accessInfo": {
    "access": {
      "message": "success",
      "token": {
        "expires": "xxxxx",
        "id": null,
        "UDID": null,
        "permissions": {
          "orgGroups": [],
          "channelGroups": [
            "xxxxx"
          ]
        }
      }
    }
  },
  "profile": {
    "message": null,
    "responseStatus": null,
    "UDID": "xxxxx",
    "name": null,
    "age": null,
    "gender": null,
    "maritalStatus": null,
    "familySize": null,
    "lat": null,
    "lon": null,
    "birthDay": null,
    "imageURL": null,
    "sessionId": "xxxxx",
    "FBId": null,
    "expiry": null,
    "email": "xxxxx",
    "workLocationLat": null,
    "workLocationLong": null,
    "workLocationAddress": null,
    "homeLocationAddress": null,
    "homeLocationLat": null,
    "homeLocationLong": null,
    "id": 789,
    "isFBIdAlreadyExists": false,
    "tagList": []
  }
}

All the values are really what is returned except for those xxxxx which I masked. As you can see, there are two UDID fields in the JSON. One is in the node accessInfo > access > token which is null and the other in the node profile. The value in the second node is the one I'm interested in which is not supposed to be null.

I have created 2 POJOs as given below. I'm only interested in UDID and sessionId under profile node.

Parent POJO:

@JsonIgnoreProperties(ignoreUnknown = true)
public class AgtAuthentication {

    private Profile profile;

}

Child POJO:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Profile {

    private String sessionId;
    private String UDID;

}

I have removed the getters and setters and no args constructors for brevity.

When I call the Api I receive the response and the JSON mapping works fine except for the UDID attribute. When I do a System.out.println() for the response body, I get the below result:

Authentication [profile = Profile [sessionId = xxxxx, UDID = null]]

sessionId is correct. However, UDID is always null. Not sure if this is because there's a duplicate UDID value in the JSON. Can anyone help? Thanks.

EDIT: The code that calls the actual Api (xxxxx being masked values) is below:

private void setUuidAndSessionId() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> requestBody= new LinkedMultiValueMap<String, String>();
        requestBody.add("clientId", "xxxxx");
        requestBody.add("clientPassword", "xxxxx");
        requestBody.add("UDID", "");
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(requestBody, headers);

        RestTemplate restTemplate = new RestTemplate();

        String agtAuthUrl = "http://xxxxx";

        ResponseEntity<AgtAuthentication> response = restTemplate.exchange(agtAuthUrl, HttpMethod.POST, request, AgtAuthentication.class);

        System.out.println(response.getBody().toString());

        sessionId = response.getBody().getProfile().getSessionId();
        String tempUuid = response.getBody().getProfile().getUDID();
    }


问:
Can't get height-attribute in Bootstrap 4 alpha to work
I'm learning Bootstrap, and I can't get the height attribute in v4 (e.g.: "row h-25") to work.

I've tried to add another CSS which sets the height of "container-fluid" as well as html and body to 100%, which someone proposed as a solution in another answer. Still doesn't work, I'm afraid. I'm using Visual Studio, and when I open "NuGet - Solution", it says that the bootstrap version is 'v4.0.0-alpha'.

Any help would be greatly appreciated.

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/custom.css" rel="stylesheet" />
    <script src="scripts/angular.min.js"></script>
</head>
<body>
    <div class="container-fluid" style="background-color: #e7fdd6">
        <div class="row h-25" style="background-color: #eee">
            <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3"><p>Customer</p><!-- These are just rough drafts while I learn the grid system. --></div>
            <div class="col-md-3 col-lg-3 hidden-xs hidden-sm"><p>Power</p></div>
            <div class="col-md-3 col-lg-3 hidden-xs hidden-sm"><p>Panels</p></div>
            <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3"><p>Projects</p></div>
        </div>

        <div class="row h-25" style="background-color: #eee">
            <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3"><p>Customer-slider</p></div>
            <div class="col-md-3 col-lg-3 hidden-xs hidden-sm"><p>Power amount</p></div>
            <div class="col-md-3 col-lg-3 hidden-xs hidden-sm"><p>Panels</p></div>
            <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3"><p>Projects-slider</p></div>
        </div>

        <div class="row h-25">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"><img src="Content/picture.jpg" alt="Park" align="middle" /> <!-- Bilde --></div>
        </div>

        <div class="row h-25">
            <div class="col-lg-6 col-md-6-col-sm-12 col-xs-12"><!-- Graph 1 --></div>
            <div class="col-lg-6 col-md-6 hidden-sm hidden-xs"><!-- Graph 2 --></div>
        </div>

    </div>
</body>
</html>
</code>```

custom.css:

```<code>.container-fluid {
    height: 100%;
}

html, body {
    height: 100%;
}
</code>```

答:
Bootstrap 4 alpha works well with h-25 class.You have to set the height for the parent element i.e.,container-fluid in px,rem or em.Do not add parent height in percentage.

```<code>.container-fluid {
    min-height: 200px ;
}
</code>```

Best practise is to add styles to custom class in the parent element rather than applying the styles for bootstrap core classes.

Body:
I'm learning Bootstrap, and I can't get the height attribute in v4 (e.g.: "row h-25") to work.

I've tried to add another CSS which sets the height of "container-fluid" as well as html and body to 100%, which someone proposed as a solution in another answer. Still doesn't work, I'm afraid. I'm using Visual Studio, and when I open "NuGet - Solution", it says that the bootstrap version is 'v4.0.0-alpha'.

Any help would be greatly appreciated.

<!DOCTYPE html>

    <title></title>
    <meta charset="utf-8" />
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/custom.css" rel="stylesheet" />

Customer

Power

Panels

Projects

Customer-slider

Power amount

Panels

Projects-slider

custom.css:

.container-fluid {
    height: 100%;
}

html, body {
    height: 100%;
}

Body:
Bootstrap 4 alpha works well with h-25 class.You have to set the height for the parent element i.e.,container-fluid in px,rem or em.Do not add parent height in percentage.

.container-fluid {
    min-height: 200px ;
}

Best practise is to add styles to custom class in the parent element rather than applying the styles for bootstrap core classes.


问:
How to incorporate median value into regression as an independent variable?
I want to regress y on x1 and median value of x2.
I use below code with package plm:

```<code>Result <- plm(y ~ x1 + median(x2,na.rm=T),data = Panel[which(!is.na(Panel$Firms)),],
              model = "random",effect = "time",index = c("Firms", "Time"))
</code>```

But it does not work. It returns

Error in model.frame.default(terms(formula, lhs = lhs, rhs = rhs, data = data,  :

  variable lengths differ (found for 'median(MB)')

How can I incorporate median value into regression as an independent variable?

答:
Assuming you are interested in firm-specific medians, an example using the dplyr package would be:

```<code>library(dplyr)
panel <- panel %>%
group_by(Firms) %>%
mutate(median_x2 = median(x2))
</code>```

You should then be able to run your model using the newly generated variable.

Body:
I want to regress y on x1 and median value of x2.
I use below code with package plm:

Result <- plm(y ~ x1 + median(x2,na.rm=T),data = Panel[which(!is.na(Panel$Firms)),],
              model = "random",effect = "time",index = c("Firms", "Time"))

But it does not work. It returns

Error in model.frame.default(terms(formula, lhs = lhs, rhs = rhs, data = data,  :

  variable lengths differ (found for 'median(MB)')

How can I incorporate median value into regression as an independent variable?

Body:
Assuming you are interested in firm-specific medians, an example using the dplyr package would be:

library(dplyr)
panel <- panel %>%
group_by(Firms) %>%
mutate(median_x2 = median(x2))

You should then be able to run your model using the newly generated variable.


问:
Running Gunicorn on both http and https
When I start my Gunicorn service, I currently use this command to start it up:

```<code>gunicorn --certfile=/Projects/thebodyofchrist.us.crt --keyfile=/Projects/thebodyofchrist.us.key bodyofchrist.wsgi -b 0.0.0.0:443 -b 0.0.0.0:80 -w 10
</code>```

For binding gunicorn to both http and https -- or setup apache2 to listen to http and redirect requests to https with existing parameters.
I have hundreds of links to the http://example.com/sample/request
and need it to automatically go to https://example.com/sample/request

gunicorn is hosting django.

Thanks for any help!

答:
Gunicorn is a very solid project, I hope they build it out someday with multiple port binding and command line switch to indicate SSL precedence.

When you finally get in production, you'll want to use the superior load balancing of Apache or Nginx.

But nothing prevents you (during development) from running some workers bound to port 80 and some workers bound to port 443 with keyfile and certfile set. You could then write the login link as an "absolute" url e.g. href="https://yoursite/login" after the login, they'd be using https urls.

```<code>#!/bin/sh
# put 8 workers as Daemon listening for HTTPS on 443
gunicorn -D -w 8 --certfile=/Projects/thebodyofchrist.us.crt --keyfile=/Projects/thebodyofchrist.us.key bodyofchrist.wsgi -b 0.0.0.0:443

# put 2 workers as Daemon listening for HTTP on port 80
gunicorn -D -w 2 bodyofchrist.wsgi -b 0.0.0.0:80
</code>```

ContentLicense: CC BY-SA 4.0

Title: Running Gunicorn on both http and https

Body:
When I start my Gunicorn service, I currently use this command to start it up:

gunicorn --certfile=/Projects/thebodyofchrist.us.crt --keyfile=/Projects/thebodyofchrist.us.key bodyofchrist.wsgi -b 0.0.0.0:443 -b 0.0.0.0:80 -w 10

For binding gunicorn to both http and https -- or setup apache2 to listen to http and redirect requests to https with existing parameters.
I have hundreds of links to the http://example.com/sample/request
and need it to automatically go to https://example.com/sample/request

gunicorn is hosting django.

Thanks for any help!

Body:
Gunicorn is a very solid project, I hope they build it out someday with multiple port binding and command line switch to indicate SSL precedence.

When you finally get in production, you'll want to use the superior load balancing of Apache or Nginx.

But nothing prevents you (during development) from running some workers bound to port 80 and some workers bound to port 443 with keyfile and certfile set. You could then write the login link as an "absolute" url e.g. href="https://yoursite/login" after the login, they'd be using https urls.

#!/bin/sh
# put 8 workers as Daemon listening for HTTPS on 443
gunicorn -D -w 8 --certfile=/Projects/thebodyofchrist.us.crt --keyfile=/Projects/thebodyofchrist.us.key bodyofchrist.wsgi -b 0.0.0.0:443

# put 2 workers as Daemon listening for HTTP on port 80
gunicorn -D -w 2 bodyofchrist.wsgi -b 0.0.0.0:80


问:
MediaPlayer android, playing a file that's is inside the project
i'm a new android dev. Actually i'm moving from iPhone to Android :-)

well, i'm modifying the source of one of the examples (MediaPlayerDemo_Video.java) here: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/media/index.html

well, the point is that i want to play a video that is inside the project.

my questions:

where should i place the video file?, i guess inside the assets folder.

how do i get the correct video file path?

thanks in advance

答:
Pop the file in the res/raw folder. Then the next time you compile you'll get a new entry in the gen R.java file. This lovely file contains references to all your resources; strings, images, etc.

Then use the MediaPlayer class to play the file from the resource, using the resource ID that was generated for you. e.g.

```<code>MediaPlayer mp = MediaPlayer.create(context, R.raw.my_video_file);
</code>```

In your example you can probably replace 'context' with 'this'.

You don't ever need to know the actual file path, its probably not exposed to you anyway.

Have a look at these bits of documentation for more info:

http://developer.android.com/guide/topics/media/index.html

http://developer.android.com/guide/topics/resources/index.html

Body:
Pop the file in the res/raw folder. Then the next time you compile you'll get a new entry in the gen R.java file. This lovely file contains references to all your resources; strings, images, etc.

Then use the MediaPlayer class to play the file from the resource, using the resource ID that was generated for you. e.g.

MediaPlayer mp = MediaPlayer.create(context, R.raw.my_video_file);

In your example you can probably replace 'context' with 'this'.

You don't ever need to know the actual file path, its probably not exposed to you anyway.

Have a look at these bits of documentation for more info:

http://developer.android.com/guide/topics/media/index.html

http://developer.android.com/guide/topics/resources/index.html


问:
Xcode 9.1 iOS simulator Window > Physical Size disabled
I need to make screen shots (specifically iPad Pro 12.9") for the App Store. I resized the simulator to fit it on my mac's screen. Now I can't resize it back to 100%, which is required to make a new screen shot. Both sizing options, Physical Size (Cmd-1) and Pixel Accurate (Cmd-2) are grayed out. How do I reset the simulator back to 100%?

Workaround: I was able to manually resize the simulator window using the mouse to grab the corner (the new way to adjust size in 9.1). Using trial-and-error by resizing, making new screen shots, and checking the resulting pixel dimensions, I was able to manually get it back to 100% (2048x2732). The original question still remains; is there a way to reset the simulator to 100% without using this workaround?

答: Just resize up the simulator window dragging until the size reaches a size greater than or equal the original size, this worked for me.</p>


问:
Mutable and Immutable Strings in python
I was just going through mutable and immutable structures in python.
It was written that "Strings are immutable" in Python i.e We cannot alter them
Consider the code:

```<code>str1='Rohit'
str1.replace('R','M')
</code>```

This gives the output:

```<code>'Mohit'
</code>```

Now, somebody said that it is the variable str1 which is pointing to the string 'Rohit' and after str1.replace() it points to 'Mohit'
Consider this code:

```<code>'Rohit'.replace('R','M')
</code>```

This also gives me the output:

```<code>'Mohit'
</code>```

Then what is meant by 'Strings are immutable'?

答:
you can check mutability by checking id of variable before and after the change

```<code>In [3]: s1 = 'Rohit'

In [4]: id(s1)
Out[4]: 140510191375440

In [5]: s1.replace('R', 'M')
Out[5]: 'Mohit'

In [6]: id(s1)
Out[6]: 140510191375440
</code>```

Title: Mutable and Immutable Strings in python

Body:
I was just going through mutable and immutable structures in python.
It was written that "Strings are immutable" in Python i.e We cannot alter them
Consider the code:

str1='Rohit'
str1.replace('R','M')

This gives the output:

'Mohit'

Now, somebody said that it is the variable str1 which is pointing to the string 'Rohit' and after str1.replace() it points to 'Mohit'
Consider this code:

'Rohit'.replace('R','M')

This also gives me the output:

'Mohit'

Then what is meant by 'Strings are immutable'?

Body:
you can check mutability by checking id of variable before and after the change

In [3]: s1 = 'Rohit'

In [4]: id(s1)
Out[4]: 140510191375440

In [5]: s1.replace('R', 'M')
Out[5]: 'Mohit'

In [6]: id(s1)
Out[6]: 140510191375440


问:
Optimization issues in multitier architecture w/ PDO queries
I've been working on a PHP project for about 6 month where I'm using a multitier architecture (Data Access Layer , Business Logic Layer, ...).

One of the page of my website has a really long loading time, so I investigated and I realised it was the function from a BLL file that took a longer time to process.

Here's a example of a function in my DAL (here called DAL_Releve) files :

```<code>public static function getReleveByAffectationID($id){
    $conn = MgtConnexion::getConnexion();

    $sql = "SELECT *"
        . "FROM releve "
        . "WHERE Affectation_ID = :id "
        . "AND Date_Releve >= :date ;";

    $req = $conn->prepare($sql);
    $req->bindValue(":id", $id);
    $req->bindValue(":date", $_SESSION["year"]-1 ."-01-01");
    $req->execute();

    MgtConnexion::closeConnexion($conn);

    return $req;
}
</code>```

Here's a example of a function in my BLL (here called MgtReleve) files :

```<code>public static function getReleveByAffectationID($id){

    $req = DAL_Releve::getReleveByAffectationID($id);

    $releveArray = array();

    while($row = $req->fetch(PDO::FETCH_ASSOC)){
        $releveArray[] = new releve($row);
    }

    return $releveArray;
}
</code>```

As you can see, I return the PDOStatement object $req from the DAL and then fetch it in the BLL.

My problem is here : In my interface file, I'm looping through a array of Affectation and each of them have Releves (so each Releves have an attribute Affectation_ID), like this:

```<code>$lesAff = MgtAffectation::getAllAffectation();
//This doesn't return an array of objects but just an Array of arrays like : $array[<number>]["key"] = value;

foreach ($lesAff as $affect){
    $lesReleves = MgtReleve::getReleveByAffectationID($affect["Affectation_ID"]);
    foreach ($lesReleves as $rel){
        //DO STUFF HERE
    }
}
</code>```

FYI : The page loads in 6.622 seconds with the code above and in 0.014 seconds if I remove everything inside the first foreach (except for html code which is not showed here).

Now I'm starting to question my understanding of the multitiers architecture :

If I decide not to fetch $req in my BLL file but in my interface (to loop only once in my queries results instead of twice), what's the purpose of the BLL then if only to return the PDOStatement object? Is there another way to return the data with more efficiency ?

答:
There are many areas of optimization:

Technological optimization: instead of connecting to the database every time you are running a query, you should connect only once and then use this connection through the entire application. I wrote an article on the common errors of Database wrappers, you may find it interesting to read, and especially the part on the database connection.

Architectural optimization. It seems that you could benefit from lazy loading when instead of selecting database rows one by one you could do it in batches. Check this answer on how to run a PDO query with multiple ids at once. So it will take you to run only 68 queries instead of 1200

Database optimization. Make sure that all queries involved are running fast.

Body:
I've been working on a PHP project for about 6 month where I'm using a multitier architecture (Data Access Layer , Business Logic Layer, ...).

One of the page of my website has a really long loading time, so I investigated and I realised it was the function from a BLL file that took a longer time to process.

Here's a example of a function in my DAL (here called DAL_Releve) files :

public static function getReleveByAffectationID($id){
    $conn = MgtConnexion::getConnexion();

    $sql = "SELECT *"
        . "FROM releve "
        . "WHERE Affectation_ID = :id "
        . "AND Date_Releve >= :date ;";

    $req = $conn->prepare($sql);
    $req->bindValue(":id", $id);
    $req->bindValue(":date", $_SESSION["year"]-1 ."-01-01");
    $req->execute();

    MgtConnexion::closeConnexion($conn);

    return $req;
}

Here's a example of a function in my BLL (here called MgtReleve) files :

public static function getReleveByAffectationID($id){

    $req = DAL_Releve::getReleveByAffectationID($id);

    $releveArray = array();

    while($row = $req->fetch(PDO::FETCH_ASSOC)){
        $releveArray[] = new releve($row);
    }

    return $releveArray;
}

As you can see, I return the PDOStatement object $req from the DAL and then fetch it in the BLL.

My problem is here : In my interface file, I'm looping through a array of Affectation and each of them have Releves (so each Releves have an attribute Affectation_ID), like this:

$lesAff = MgtAffectation::getAllAffectation();
//This doesn't return an array of objects but just an Array of arrays like : $array[<number>]["key"] = value;

foreach ($lesAff as $affect){
    $lesReleves = MgtReleve::getReleveByAffectationID($affect["Affectation_ID"]);
    foreach ($lesReleves as $rel){
        //DO STUFF HERE
    }
}

FYI : The page loads in 6.622 seconds with the code above and in 0.014 seconds if I remove everything inside the first foreach (except for html code which is not showed here).

Now I'm starting to question my understanding of the multitiers architecture :

If I decide not to fetch $req in my BLL file but in my interface (to loop only once in my queries results instead of twice), what's the purpose of the BLL then if only to return the PDOStatement object? Is there another way to return the data with more efficiency ?


问:
Reading i-cal/ics attributes with line-breaks / line-folding
I want to implement i very basic calendar feature in PHP. But the customer wants to be able to import his own calendars from another source. I've got an generic ics file.
I've discovered that sometimes large lines, e.g  Long Descriptions or some apple iCal lines break down to a new line with a whitespace as the first character.

I want to get every single attribute with a regex via preg_match_all.

Here's an example that contains example lines from google and apple attributes as well as an similar description as i got it from the customer.

```<code>BEGIN:VEVENT
DTSTART:20150123T060000Z
DTEND:20150123T070000Z
DTSTAMP:20171027T205827Z
UID:1234567894567890ß6543
CREATED:20150131T171526Z
ORGANIZER;CN=someemail@mail.com:mailto:email@server.com
UID:1234567890
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;CN=So
 me NameX-NUM-GUESTS=0:mailto:name@server.com
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;CN=Anoth
 er Name;X-NUM-GUESTS=0:mailto:name@server.com
DESCRIPTION: this is a very long d\nescription. It brea
 ks down if the l\nine is too long. It seems to be quit
 e normal. But it \n also contains \n's.
X-APPLE-STRUCTURED-LOCATION;VALUE=URI;X-APPLE-MAPKIT-HANDLE=CAESmQIaEgnfNH1
 2wAtJQBFuMT83NE0hQCKcAQoLRGV1dHNjaGxhbmQSAkRFGgZIZXNzZW4qEUZyYW5rZnVydCBhbS
 BNYWluMhFGcmFua2Z1cnQgYW0gTWFpbjoFNjA1MjhCBFPDvGRSGUhlaW5yaWNoLUhvZmZtYW5uL
 VN0cmHDn2VaAjEwYhxIZWlucmljaC1Ib2ZmbWFubi1TdHJhw59lIDEwigEJTmllZGVycmFkigEE
 U8O8ZCocSGVpbnJpY2gtSG9mZm1hbm4tU3RyYcOfZSAxMDIcSGVpbnJpY2gtSG9mZm1hbm4tU3R
 yYcOfZSAxMDIXNjA1MjggRnJhbmtmdXJ0IGFtIE1haW4yC0RldXRzY2hsYW5kODlAAA==;X-APP
 LE-RADIUS=49.91306619367188;X-APPLE-REFERENCEFRAME=1;X-TITLE="A location , Frankfurt am Main, Germany":geo:12.345678,9.123456
LAST-MODIFIED:20150131T171526Z
LOCATION:
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY: The Title
TRANSP:OPAQUE
END:VEVENT
</code>```

The regex i got seems to work fine for lines that don't continue on the next line:

```<code>/(((.*?:)(.*?)).*)/
</code>```

for

```<code>BEGIN:VEVENT
DTSTART:20150123T060000Z
DTEND:20150123T070000Z
DTSTAMP:20171027T205827Z
UID:1234567894567890ß6543
CREATED:20150131T171526Z
UID:1234567890
DESCRIPTION: some description
LAST-MODIFIED:20150131T171526Z
LOCATION:
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY: The Title
TRANSP:OPAQUE
END:VEVENT
</code>```

gives this:

```<code>array(5
0   =>  array(15
0   =>  BEGIN:VEVENT
1   =>  DTSTART:20150123T060000Z
2   =>  DTEND:20150123T070000Z
3   =>  DTSTAMP:20171027T205827Z
4   =>  UID:1234567894567890ß6543
5   =>  CREATED:20150131T171526Z
6   =>  UID:1234567890
7   =>  DESCRIPTION: some description
8   =>  LAST-MODIFIED:20150131T171526Z
9   =>  LOCATION:
10  =>  SEQUENCE:0
11  =>  STATUS:CONFIRMED
12  =>  SUMMARY: The Title
13  =>  TRANSP:OPAQUE
14  =>  END:VEVENT
)
</code>```

http://www.phpliveregex.com/p/lXX (preg_match_all)

I can surely work with that, but i can't figure out how to detect line-breaks in attributes that can have any number of line-breaks.
http://www.phpliveregex.com/p/lXY (preg_match_all)

Like, for the exact example i provided, following regex seems to work:

```<code>(DESCRIPTION:(.*))|(X-APPLE(.*?)geo:(.*))|(((.*?:)(.*?)).*)|((.*)\n(.*):mailto:.*)|((.*):mailto:.*)
</code>```

http://www.phpliveregex.com/p/lXW (preg_match_all)

But I can't cover any single case as the runtime would probably explode.

Solved

I wasn't seeing this from the right perspective.
I'd just have to preg_replace the line breaks away:

```<code>preg_replace("/\n /", "", $input_lines);
</code>```

It's important to have a whitespace after the \n.
After that, I can just proceed to get any lines properly.

答:
Since you are not actually matching an expression, it will run faster as a str_replace rather than preg_replace.

```<code>$input_lines = str_replace("\n ", "", $input_lines);
</code>```

I think you could speed up the rest of the searching as well by exploding on \n, using strpos to find the first colon and than using substr to get the text before/after it, but that is more function calls so you might want to time that on a large ical file.  If the files are small, it's probably not worth the complexity to re-write that part.

Body:
I want to implement i very basic calendar feature in PHP. But the customer wants to be able to import his own calendars from another source. I've got an generic ics file.
I've discovered that sometimes large lines, e.g  Long Descriptions or some apple iCal lines break down to a new line with a whitespace as the first character.

I want to get every single attribute with a regex via preg_match_all.

Here's an example that contains example lines from google and apple attributes as well as an similar description as i got it from the customer.

BEGIN:VEVENT
DTSTART:20150123T060000Z
DTEND:20150123T070000Z
DTSTAMP:20171027T205827Z
UID:1234567894567890ß6543
CREATED:20150131T171526Z
ORGANIZER;CN=someemail@mail.com:mailto:email@server.com
UID:1234567890
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;CN=So
 me NameX-NUM-GUESTS=0:mailto:name@server.com
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;CN=Anoth
 er Name;X-NUM-GUESTS=0:mailto:name@server.com
DESCRIPTION: this is a very long d\nescription. It brea
 ks down if the l\nine is too long. It seems to be quit
 e normal. But it \n also contains \n's.
X-APPLE-STRUCTURED-LOCATION;VALUE=URI;X-APPLE-MAPKIT-HANDLE=CAESmQIaEgnfNH1
 2wAtJQBFuMT83NE0hQCKcAQoLRGV1dHNjaGxhbmQSAkRFGgZIZXNzZW4qEUZyYW5rZnVydCBhbS
 BNYWluMhFGcmFua2Z1cnQgYW0gTWFpbjoFNjA1MjhCBFPDvGRSGUhlaW5yaWNoLUhvZmZtYW5uL
 VN0cmHDn2VaAjEwYhxIZWlucmljaC1Ib2ZmbWFubi1TdHJhw59lIDEwigEJTmllZGVycmFkigEE
 U8O8ZCocSGVpbnJpY2gtSG9mZm1hbm4tU3RyYcOfZSAxMDIcSGVpbnJpY2gtSG9mZm1hbm4tU3R
 yYcOfZSAxMDIXNjA1MjggRnJhbmtmdXJ0IGFtIE1haW4yC0RldXRzY2hsYW5kODlAAA==;X-APP
 LE-RADIUS=49.91306619367188;X-APPLE-REFERENCEFRAME=1;X-TITLE="A location , Frankfurt am Main, Germany":geo:12.345678,9.123456
LAST-MODIFIED:20150131T171526Z
LOCATION:
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY: The Title
TRANSP:OPAQUE
END:VEVENT

The regex i got seems to work fine for lines that don't continue on the next line:

/(((.*?:)(.*?)).*)/

for

BEGIN:VEVENT
DTSTART:20150123T060000Z
DTEND:20150123T070000Z
DTSTAMP:20171027T205827Z
UID:1234567894567890ß6543
CREATED:20150131T171526Z
UID:1234567890
DESCRIPTION: some description
LAST-MODIFIED:20150131T171526Z
LOCATION:
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY: The Title
TRANSP:OPAQUE
END:VEVENT

gives this:

array(5
0   =>  array(15
0   =>  BEGIN:VEVENT
1   =>  DTSTART:20150123T060000Z
2   =>  DTEND:20150123T070000Z
3   =>  DTSTAMP:20171027T205827Z
4   =>  UID:1234567894567890ß6543
5   =>  CREATED:20150131T171526Z
6   =>  UID:1234567890
7   =>  DESCRIPTION: some description
8   =>  LAST-MODIFIED:20150131T171526Z
9   =>  LOCATION:
10  =>  SEQUENCE:0
11  =>  STATUS:CONFIRMED
12  =>  SUMMARY: The Title
13  =>  TRANSP:OPAQUE
14  =>  END:VEVENT
)

http://www.phpliveregex.com/p/lXX (preg_match_all)

I can surely work with that, but i can't figure out how to detect line-breaks in attributes that can have any number of line-breaks.
http://www.phpliveregex.com/p/lXY (preg_match_all)

Like, for the exact example i provided, following regex seems to work:

(DESCRIPTION:(.*))|(X-APPLE(.*?)geo:(.*))|(((.*?:)(.*?)).*)|((.*)\n(.*):mailto:.*)|((.*):mailto:.*)

http://www.phpliveregex.com/p/lXW (preg_match_all)

But I can't cover any single case as the runtime would probably explode.

Solved

I wasn't seeing this from the right perspective.
I'd just have to preg_replace the line breaks away:

preg_replace("/\n /", "", $input_lines);

It's important to have a whitespace after the \n.
After that, I can just proceed to get any lines properly.

Body:
Since you are not actually matching an expression, it will run faster as a str_replace rather than preg_replace.

$input_lines = str_replace("\n ", "", $input_lines);

I think you could speed up the rest of the searching as well by exploding on \n, using strpos to find the first colon and than using substr to get the text before/after it, but that is more function calls so you might want to time that on a large ical file.  If the files are small, it's probably not worth the complexity to re-write that part.


问:
Can this be optimized even further using object methods or other way in javascript?
Hello I am trying to remove a user from an array in react javascript the text is given to the function that needs to be deleted and runs through the function below, this.state.users contain objects with properties like:

0: {user_id: "001"  , first_name: "john", last_name: "doe", email:
  "john@doe.com"}

1: {user_id: "002"  , first_name: "mike", last_name: "ty", email:
  "mike@ty.com"}

I'm wondering if this can be optimized even further for large sets of data? or is it already optimized thanks!

```<code>removeUser(text){
  var updatedUsers = this.state.users;
  var i = 0;
  for (i = 0; i< updatedUsers.length;i++)
  {
    if(updatedUsers[i].user_id == text)
      break;
    }
    updatedUsers.splice(i,1);
    this.setState({users: updatedUsers});
  }
}
</code>```

答:
You could use array's filter:

```<code>removeUser (text) {
  this.setState({
    users: this.state.users.filter((u) => u.user_id !== text)
  })
}
</code>```

Body:
Hello I am trying to remove a user from an array in react javascript the text is given to the function that needs to be deleted and runs through the function below, this.state.users contain objects with properties like:

0: {user_id: "001"  , first_name: "john", last_name: "doe", email:
  "john@doe.com"}

1: {user_id: "002"  , first_name: "mike", last_name: "ty", email:
  "mike@ty.com"}

I'm wondering if this can be optimized even further for large sets of data? or is it already optimized thanks!

removeUser(text){
  var updatedUsers = this.state.users;
  var i = 0;
  for (i = 0; i< updatedUsers.length;i++)
  {
    if(updatedUsers[i].user_id == text)
      break;
    }
    updatedUsers.splice(i,1);
    this.setState({users: updatedUsers});
  }
}

Body:
You could use array's filter:

removeUser (text) {
  this.setState({
    users: this.state.users.filter((u) => u.user_id !== text)
  })
}


问:
Slow query log logs queries that are fast during testing
My slow query log is full of queries with following query time and rows examined:

```<code># Query_time: 26.370100  Lock_time: 0.000213  Rows_sent: 0  Rows_examined: 30976475
</code>```

If I copy and paste the exact query from the log into phpmyadmin and run it, result comes instantly, even trying EXPLAIN upon that query reveals no flaws in indexes or bad structure.

As far as I can tell, for some reason a small fraction of queries fail to use indexes and trying to reproduce that event is next to impossible during testing.

How should I prevent these occasional slow queries which in vast majority of cases work as intended?

--- EDIT #1 ---

My create tables are:

```<code>CREATE TABLE msgs (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  sender text NOT NULL,
  receiver text NOT NULL,
  cont blob NOT NULL,
  img text NOT NULL,
  orient text NOT NULL,
  d_t datetime NOT NULL,
  convo text NOT NULL,
  u_code text NOT NULL,
  viewed datetime NOT NULL,
  stat int(11) NOT NULL,
  device text NOT NULL,
  addr text NOT NULL,
  PRIMARY KEY (id),
  KEY msg_u_code (`u_code`(24)),
  KEY receiver (`receiver`(24)),
  KEY sender (`sender`(24)),
  KEY img (`img`(28)),
  KEY convo (`convo`(49))
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

CREATE TABLE usrs (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  usr_name text NOT NULL,
  img text NOT NULL,
  orient text NOT NULL,
  `password` text NOT NULL,
  u_code text NOT NULL,
  d_t datetime NOT NULL,
  stat int(11) NOT NULL,
  device text NOT NULL,
  addr text NOT NULL,
  PRIMARY KEY (id),
  KEY img (`img`(28)),
  KEY usr_code (`u_code`(24))
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
</code>```

And my slow query log entry is:

```<code> # Time: 171115  6:26:37
 # User@Host: xxx[xxx] @ localhost []
 # Thread_id: 25524888  Schema: xxx  QC_hit: No
 # Query_time: 32.423430  Lock_time: 0.000425  Rows_sent: 1  Rows_examined: 30998008
 # Rows_affected: 0
 use xxx;
 SET timestamp=1510723597;
 select msg_cont, msg_u_code, msg_d_t, msg_viewed, usr_u_code, usr_name from
        (select
            msgs.id as msg_id,
            msgs.cont as msg_cont,
            msgs.u_code as msg_u_code,
            msgs.d_t as msg_d_t,
            msgs.viewed as msg_viewed,
            usrs.u_code as usr_u_code,
            usrs.usr_name as usr_name
            from msgs
            left join usrs on msgs.sender = usrs.u_code
    where  msgs.convo = 'aaaaaaaaaabfbaghdgcigfid_aaaaaaaaaabeiaccjfhjfach'
      and  (msgs.sender = 'aaaaaaaaaabfbaghdgcigfid'
              or  msgs.receiver = 'aaaaaaaaaabfbaghdgcigfid'
           )
      and  msgs.stat = '1'
      and  usrs.stat = '1'
      and  usrs.u_code not in('aaaaaaaaaabfaagfbgggiejh',
                              'aaaaaaaaaabfabgbjdfjigbd',
                ...... !!!!![here go 400 more usr_u_codes]!!!!!
                          )
      and  msgs.id > 30997997
        ) a order by msg_id asc;
</code>```

Caution, this query shall contain on average 400 elements in the not in function.

--- EDIT #2 ---

答:
You probably have the "Query cache" turned on.  It captures queries and their resultsets.  When you run exactly the same query again, it simply echos the saved resultset, instead of re-evaluating it.

The QC can be avoided by adding as little as a single space in the statement, or by saying SELECT SQL_NO_CACHE ....

To further discuss why the query needs to look at 31M rows, let's see the query and SHOW CREATE TABLE.

After seing query

I want to start by focusing on ON msgs.sender = usrs.u_code and the "prefix" indexes.

Based on the sample values, it seems that sender, u_code and several other columns might always be under some small length?  If this is true, then

Change from TEXT to VARCHAR(nn) where nn is some realistic limit;

Get rid of the prefixing (eg: KEY sender (sender(24)) --> KEY (sender).

These changes should make the JOIN much more efficient, thereby improving performance.  If that is not adequate, come back for more advice.

Body:
My slow query log is full of queries with following query time and rows examined:

# Query_time: 26.370100  Lock_time: 0.000213  Rows_sent: 0  Rows_examined: 30976475

If I copy and paste the exact query from the log into phpmyadmin and run it, result comes instantly, even trying EXPLAIN upon that query reveals no flaws in indexes or bad structure.

As far as I can tell, for some reason a small fraction of queries fail to use indexes and trying to reproduce that event is next to impossible during testing.

How should I prevent these occasional slow queries which in vast majority of cases work as intended?

--- EDIT #1 ---

My create tables are:

CREATE TABLE msgs (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  sender text NOT NULL,
  receiver text NOT NULL,
  cont blob NOT NULL,
  img text NOT NULL,
  orient text NOT NULL,
  d_t datetime NOT NULL,
  convo text NOT NULL,
  u_code text NOT NULL,
  viewed datetime NOT NULL,
  stat int(11) NOT NULL,
  device text NOT NULL,
  addr text NOT NULL,
  PRIMARY KEY (id),
  KEY msg_u_code (`u_code`(24)),
  KEY receiver (`receiver`(24)),
  KEY sender (`sender`(24)),
  KEY img (`img`(28)),
  KEY convo (`convo`(49))
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

CREATE TABLE usrs (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  usr_name text NOT NULL,
  img text NOT NULL,
  orient text NOT NULL,
  `password` text NOT NULL,
  u_code text NOT NULL,
  d_t datetime NOT NULL,
  stat int(11) NOT NULL,
  device text NOT NULL,
  addr text NOT NULL,
  PRIMARY KEY (id),
  KEY img (`img`(28)),
  KEY usr_code (`u_code`(24))
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

And my slow query log entry is:

 # Time: 171115  6:26:37
 # User@Host: xxx[xxx] @ localhost []
 # Thread_id: 25524888  Schema: xxx  QC_hit: No
 # Query_time: 32.423430  Lock_time: 0.000425  Rows_sent: 1  Rows_examined: 30998008
 # Rows_affected: 0
 use xxx;
 SET timestamp=1510723597;
 select msg_cont, msg_u_code, msg_d_t, msg_viewed, usr_u_code, usr_name from
        (select
            msgs.id as msg_id,
            msgs.cont as msg_cont,
            msgs.u_code as msg_u_code,
            msgs.d_t as msg_d_t,
            msgs.viewed as msg_viewed,
            usrs.u_code as usr_u_code,
            usrs.usr_name as usr_name
            from msgs
            left join usrs on msgs.sender = usrs.u_code
    where  msgs.convo = 'aaaaaaaaaabfbaghdgcigfid_aaaaaaaaaabeiaccjfhjfach'
      and  (msgs.sender = 'aaaaaaaaaabfbaghdgcigfid'
              or  msgs.receiver = 'aaaaaaaaaabfbaghdgcigfid'
           )
      and  msgs.stat = '1'
      and  usrs.stat = '1'
      and  usrs.u_code not in('aaaaaaaaaabfaagfbgggiejh',
                              'aaaaaaaaaabfabgbjdfjigbd',
                ...... !!!!![here go 400 more usr_u_codes]!!!!!
                          )
      and  msgs.id > 30997997
        ) a order by msg_id asc;

Caution, this query shall contain on average 400 elements in the not in function.

--- EDIT #2 ---


问:
equivalent of getbuffer for BytesIO in Python 2
In Python 3, I can get the size of a ByteIO object via object.getbuffer().nbytes (where object = ByteIO()), but what would be the best equivalent for getbuffer() in Python 2? Doing some exploring, I found out I can use len(object.getvalue()) or sys.getsizeof(object), but I don't know if Python 2 will accept them.

答:
You can use getvalue()

Example:

```<code>from io import BytesIO
if __name__ == "__main__":
    out = BytesIO()
    out.write(b"test\0")
    print len(out.getvalue())
</code>```

See: https://docs.python.org/2/library/io.html#io.BytesIO.getvalue

Body:
You can use getvalue()

Example:

from io import BytesIO
if __name__ == "__main__":
    out = BytesIO()
    out.write(b"test\0")
    print len(out.getvalue())

See: https://docs.python.org/2/library/io.html#io.BytesIO.getvalue


问:
How can I edit the NGINX configuration on Google App Engine flexible environment?
How can I edit the Google App Engine NGINX configuration?

There doesn't seem to be much support in the Google docs in regards to the NGINX configuration for apps running in the Google App Engine flexible environment.

My app is running fine, but I get this 413 error when I try and upload an audio file (.wav or .mp3).

413 Request Entity Too Large -- nginx

My app is running Django (python 3), with Cloud Postgres SQL and Cloud Storage enabled.

I researched the error, and it seems I can set a nginx.config file so that it includes "client_max_body_size 80M" - but like I said, there is no documentation regarding how to manually config NGINX on deploy.

Any suggestions?

答:
So upon contacting Google Support, the suggested solution for uploading files larger than 32MB is as follows:

"The way to circumvent App Engine's 32MB limit is to send the requests directly to Cloud Storage, for instance using the resumable upload process. You can still use App Engine to serve your app, but the clientside portion of the app would be the one handling the upload to Google Cloud Storage. For this you would have your application generate a signed URL which the client can use to gain access to your Cloud Storage bucket for the purpose of uploading an image."

I went with this solution.  It saves money in the end.


问:
For Loop NullPointerException with Apache POI
First of all, I apologize for my bad english, it's not my primary language.
I'm having a problem with my code when it's reading an excel file (xlsx). The first time I used my code it works perfectly, but now I can't use it.
The excel content is printed on the console, but next to it there is a NullPointerException that is caused by the for loop marked with the (-->>>).
If anyone can help me, I would be very thankful, this code has given me several headaches. </p>

```<code>package modleerjava;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class leerExcel {
public void readExcel(String rutaFile,String nombreFile, String sheetName )
 throws IOException {
    File file = new File ("C:/Users/Pablo/Desktop/prueba.xlsx");
    FileInputStream inputStream = new FileInputStream(file);
    XSSFWorkbook excelWorkbook ;
    excelWorkbook = new XSSFWorkbook(inputStream);
    Sheet excelSheet = excelWorkbook.getSheet(sheetName);
    int filasCount = excelSheet.getLastRowNum()-excelSheet.getFirstRowNum();

    for (int i=0; i< filasCount+1 ; i++) {
        Row filas;
        filas = excelSheet.getRow(i);

 -->>>  for (int j=0 ; j < filas.getLastCellNum(); j++) {
            System.out.print(filas.getCell(j).getStringCellValue()+"|| ");
        }
        System.out.println();
    }

}

}
</code>```

答:
Your sheet probably has missing rows or cells. The best way to iterate over a spreadsheet in poi is using the for each syntax like this.

```<code>package modleerjava;
import java.io.File;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

public class leerExcel {
public void readExcel(String rutaFile,String nombreFile, String sheetName )
    throws IOException {
    Workbook wb = WorkbookFactory.create(new File("C:/Users/Pablo/Desktop/prueba.xlsx"));
    Sheet excelSheet = wb.getSheet(sheetName);

    for (Row filas: excelSheet) {
        for (Cell cell: filas) {
            System.out.print(cell.getStringCellValue()+"|| ");
        }
        System.out.println();
    }

}

}
</code>```

Many simple questions can be answered by looking at the quick guide on the poi website.

Body:
First of all, I apologize for my bad english, it's not my primary language.
I'm having a problem with my code when it's reading an excel file (xlsx). The first time I used my code it works perfectly, but now I can't use it.
The excel content is printed on the console, but next to it there is a NullPointerException that is caused by the for loop marked with the (-->>>).
If anyone can help me, I would be very thankful, this code has given me several headaches.

package modleerjava;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class leerExcel {
public void readExcel(String rutaFile,String nombreFile, String sheetName )
 throws IOException {
    File file = new File ("C:/Users/Pablo/Desktop/prueba.xlsx");
    FileInputStream inputStream = new FileInputStream(file);
    XSSFWorkbook excelWorkbook ;
    excelWorkbook = new XSSFWorkbook(inputStream);
    Sheet excelSheet = excelWorkbook.getSheet(sheetName);
    int filasCount = excelSheet.getLastRowNum()-excelSheet.getFirstRowNum();

    for (int i=0; i< filasCount+1 ; i++) {
        Row filas;
        filas = excelSheet.getRow(i);

 -->>>  for (int j=0 ; j < filas.getLastCellNum(); j++) {
            System.out.print(filas.getCell(j).getStringCellValue()+"|| ");
        }
        System.out.println();
    }

}

}

Body:
Your sheet probably has missing rows or cells. The best way to iterate over a spreadsheet in poi is using the for each syntax like this.

package modleerjava;
import java.io.File;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

public class leerExcel {
public void readExcel(String rutaFile,String nombreFile, String sheetName )
    throws IOException {
    Workbook wb = WorkbookFactory.create(new File("C:/Users/Pablo/Desktop/prueba.xlsx"));
    Sheet excelSheet = wb.getSheet(sheetName);

    for (Row filas: excelSheet) {
        for (Cell cell: filas) {
            System.out.print(cell.getStringCellValue()+"|| ");
        }
        System.out.println();
    }

}

}

Many simple questions can be answered by looking at the quick guide on the poi website.


问:
FiwareLab Cygnus always get error to install
According to this manual, I've try to install Cygnus on my Centos instance of FiwareLab but always I get the following error "Permission denied".

I have used the default user "centos" but I don't get any result.
Anyone can help me?
Thanks a lot!!

Here's a supplementary screen shot:

答:
The error you were facing was because the user has no permission to perform that operation on the specified directory.

The solution, in this case, is use sudo:

```<code>sudo cat > /etc/yum.repos.d/fiware.repo <<EOL (continue the lines)
</code>```

I hope it had helped you.

Body:
The error you were facing was because the user has no permission to perform that operation on the specified directory.

The solution, in this case, is use sudo:

sudo cat > /etc/yum.repos.d/fiware.repo <<EOL (continue the lines)

I hope it had helped you.


问:
Change jQuery UI Autocomplete Position - Pop up, instead of down
I am placing an autocomplete box at the bottom of my page and I would like the results to pop up OVER the text box, instead of below.  How can I do this? </p>

答:
Seems as if I've been able to answer my own question already.  I'm open to a better solution if someones got it.  I added this to the autocomplete start up.. essentially it repositions the box on open to a new offset.</p>

```<code>open: function(event, ui) {
    var autocomplete = $(".ui-autocomplete");
    var oldTop = autocomplete.offset().top;
    var newTop = oldTop - autocomplete.height() - $("#quick_add").height() - 10;

    autocomplete.css("top", newTop);
}
</code>```

Body:
Seems as if I've been able to answer my own question already.  I'm open to a better solution if someones got it.  I added this to the autocomplete start up.. essentially it repositions the box on open to a new offset.

open: function(event, ui) {
    var autocomplete = $(".ui-autocomplete");
    var oldTop = autocomplete.offset().top;
    var newTop = oldTop - autocomplete.height() - $("#quick_add").height() - 10;

    autocomplete.css("top", newTop);
}


问:
How to prematurely finish mysql_use_result() / mysql_fetch_row()?
I am in the process of writing my first C client for MySQL 5.5 and have stumbled across the following page in the documentation. Nearly at the end, it states (bold emphasis mine, italic emphasis not mine):

An advantage of mysql_use_result() is [...]. Disadvantages are that
  [...]. Furthermore, you must retrieve all the rows even if you
  determine in mid-retrieval that you've found the information you were
  looking for.

The last sentence is not clear to me.

1) What happens if I don't follow that line?

2) I think that there actually must be a way to prematurely end fetching rows if I decide that I have enough information (otherwise, this whole thing wouldn't make much sense in my eyes).

I understand that something bad could happen if I just stop fetching rows and then try to execute the next statement, but isn't there a function like mysql_finish_fetch() or something like that?

And what happens if I call mysql_free_result()? This should free the result even if I haven't fetched all rows yet, so it should be safe to call it in mid-retrieval and continue with whatever I'd like to do. Am I wrong here?

答:
This sounds like an internal threading issue that MySQL exposes to the client.  Chalk it up to the various MySQL gotchas.  The short of it is that MySQL apparently has a finite number of "searchers" internally, and using mysql_use_result() apparently dedicates one of them to your API request.  Further, MySQL apparently has no exposed API call to cancel such a request.  The only option is to see the fetch through until the end.

The slightly longer version: internally, MySQL's cursors apparently have a single code path -- I imagine for performance in the common cases.  That code path exits only when the cursor finds no more results.  When you use the more common mysql_store_result(), MySQL has done this already before returning the result to the application.  When you use mysql_use_result(), however, MySQL requires that you do "the dirty work" of iterating the rest of the result set so as to clear the cursor.  Fun.

From the documentation:

mysql_use_result() initiates a result set retrieval but does not actually read the result set into the client like mysql_store_result() does. Instead, each row must be retrieved individually by making calls to mysql_fetch_row(). This reads the result of a query directly from the server without storing it in a temporary table or local buffer, which is somewhat faster and uses much less memory than mysql_store_result(). The client allocates memory only for the current row and a communication buffer that may grow up to max_allowed_packet bytes.

On the other hand, you should not use mysql_use_result() for locking reads if you are doing a lot of processing for each row on the client side, or if the output is sent to a screen on which the user may type a ^S (stop scroll). This ties up the server and prevent other threads from updating any tables from which the data is being fetched.

When using mysql_use_result(), you must execute mysql_fetch_row() until a NULL value is returned, otherwise, the unfetched rows are returned as part of the result set for your next query. The C API gives the error Commands out of sync; you can't run this command now if you forget to do this!

So, to actually answer your questions:

1) What happens if I don't follow that line?

The C API will return the error message: Commands out of sync; you can't run this command now

2)  I think that there actually must be a way to prematurely end fetching rows if I decide that I have enough information (otherwise, this whole thing wouldn't make much sense in my eyes).

One would think, but no.  You must iterate the result set completely.


问:
stop BR tag breaking with CSS
Is there a way to stop a
 tag breaking using only CSS?

I tried br{display:none} whick works, but it also gets rid of the space between the two words, which I need to keep.

This is only for webkit (iPhone) so any CSS3 extravaganza is just fine.

I can't edit the content from the CMS, so simply removing the tag unfortunately isn't an option for me.

thanks!

答:
```<code>content: " ";
padding-right: 5px; // ok, same as margin-right
</code>```

Title: stop BR tag breaking with CSS


问:
angular ui router- urlRouterProvider otherwise redirection
It seems like the $urlRouterProvider.otherwise('/') only works for url which consist 1 segment only i.e abc.com/abcdefg will be redirected to abc.com/ if abcdefg is not defined as part of the state.

But something like abc.com/abc/abcd or abc.com/abc/abcd/abcde/abcdef and so on (url with more than 1 segments ) won't get redirected to abc.com/

Does the $urlRouterProvider.otherwise only works on url with 1 segment only?

答: managed to resolved this issue. it was a false positive as the issue is on my laravel side. thanks everybody</p>


问:
Insert 1000+ nodes and attributes with XMLStarlet - Running Slow
This is a matter of efficiency rather than troubleshooting. I have the following code snippet:

```<code># The -R flag restores malformed XML
xmlstarlet -q fo -R <<<"$xml_content" | \
    # Delete xml_data
    xmlstarlet ed -d "$xml_data" | \
    # Delete index
    xmlstarlet ed -d "$xml_index" | \
    # Delete specific objects
    xmlstarlet ed -d "$xml_nodes/objects" | \
    # Append new node
    xmlstarlet ed -s "$xml_nodes" -t elem -n subnode -v "Hello World" | \
        # Add x attribute to node
        xmlstarlet ed -i "($xml_nodes)[last()]" -t attr -n x -v "0" | \
        # Add y attribute to node
        xmlstarlet ed -i "($xml_nodes)[last()]" -t attr -n y -v "0" | \
        # Add z attribute to node
        xmlstarlet ed -i "($xml_nodes)[last()]" -t attr -n z -v "1" \
            > "$output_file"
</code>```

The variable $xml_content contains the xml tree of contents and

nodes parsed from a file with size 472.6 MB using the cat command.

The variable $output_file as its name indicates, contains the path
to the output file.

The rest of the variables simply contain the according XPaths I want to edit.

According to this brief article which helped come up with this code, it indicates that:

This is a bit ineffeciant since the xml file is parsed and written twice.

In my case, it is parsed and written more than twice (eventually in a loop over 1000 times).

So, taking the above script, the execution time alone of that short fragment is 4 mins and 7 secs.

Assuming the excessive, repetitive and perhaps inefficient piping together with the file size is why the code runs slow, the more subnodes I ultimately insert/delete will eventually cause it to execute even slower.

I apologise in advance if I might sound monotonous by reiterating myself or by bringing out an old and probably already answered topic, however, I'm really keen to understand how xmlstarlet works in detail with large XML documents.

UPDATE

As claimed by @Cyrus in his prior answer:

Those two xmlstarlets should do the job:

```<code>xmlstarlet -q fo -R <<<"$xml_content" |\
  xmlstarlet ed \
    -d "$xml_data" \
    -d "$xml_index" \
    -d "$xml_nodes/objects" \
    -s "$xml_nodes" -t elem -n subnode -v "Hello World" \
    -i "($xml_nodes)[last()]" -t attr -n x -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n y -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n z -v "1" > "$output_file"
</code>```

This produced the following errors:

-:691.84: Attribute x redefined

-:691.84: Attribute z redefined

-:495981.9: xmlSAX2Characters: huge text node: out of memory

-:495981.9: Extra content at the end of the document

I honestly don't know how these errors where produced because I changed the code too often testing various scenarios and potential alternatives, however, this is what did the trick for me:

```<code>xmlstarlet ed --omit-decl -L \
    -d "$xml_data" \
    -d "$xml_index" \
    -d "$xml_nodes/objects" \
    -s "$xml_nodes" -t elem -n subnode -v "Hello World" \
    "$temp_xml_file"

xmlstarlet ed --omit-decl -L \
    -i "($xml_nodes)[last()]" -t attr -n x -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n y -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n z -v "1" \
    "$temp_xml_file"
</code>```

Regarding the actual data that is inserted, this is what I have at the beginning:

```<code>...
<node>
    <subnode>A</subnode>
    <subnode>B</subnode>
    <objects>1</objects>
    <objects>2</objects>
    <objects>3</objects>
    ...
</node>
...
</code>```

Executing the above (split) code gives me what I want:

```<code>...
<node>
    <subnode>A</subnode>
    <subnode>B</subnode>
    <subnode x="0" y="0" z="1">Hello World</subnode>
</node>
...
</code>```

By splitting them, xmlstarlet is able to insert the attributes into the newly created node, else it will add them to the last() instance of the selected Xpath before the --subnode is even created. To some extent this is still inefficient, nevertheless, the code runs in less than a minute now.

The following code,

```<code>xmlstarlet ed --omit-decl -L \
    -d "$xml_data" \
    -d "$xml_index" \
    -d "$xml_nodes/objects" \
    -s "$xml_nodes" -t elem -n subnode -v "Hello World" \
    -i "($xml_nodes)[last()]" -t attr -n x -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n y -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n z -v "1" \
    "$temp_xml_file"
</code>```

However, gives me this:

```<code>...
<node>
    <subnode>A</subnode>
    <subnode x="0" y="0" z="1">B</subnode>
    <subnode>Hello World</subnode>
</node>
...
</code>```

By joining the xmlstarlets into one like in this post also answered by @Cyrus, it somehow first adds the attributes and then creates the --subnode where the innerText is Hello World.

Can anyone explain why this strange behaviour is happening??

This is another reference which states that "every edit operation is performed in sequence"

The above article explains exactly what I'm looking for, yet I cannot manage to make it work all in one xmlstarlet ed \. Alternatively, I tried:

Replacing ($xml_nodes)[last()] with $xml_nodes[text() = 'Hello World']

Using $prev (or $xstar:prev) as the argument to -i like in this answer. [Examples]

The temporary element name trick via -r to rename the temp node after the attr are added

All of the above insert the --subnode but leave the new element without attributes.

Note: I run XMLStarlet 1.6.1 on OS X El Capitan v 10.11.3

BONUS

As I mentioned in the beginning I wish to use a loop like something along these lines:

```<code>list="$(tr -d '\r' < $names)"

for name in $list; do
    xmlstarlet ed --omit-decl -L \
    -d "$xml_data" \
    -d "$xml_index" \
    -d "$xml_nodes/objects" \
    -s "$xml_nodes" -t elem -n subnode -v "$name" \
    -i "($xml_nodes)[last()]" -t attr -n x -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n y -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n z -v "1" \
    "$temp_xml_file"
done
</code>```

The $list contains over a thousand different names which need to be added with their respective attributes. The --value of each attribute may vary with every loop as well. Given the above model:

What is the fastest and most accurate version of such loop given that the attributes are added correctly to the corresponding node?

Would it be faster to create the list of nodes in an external txt file and later add those xml elements (inside the txt file) into  another XML file. If yes, how? Perhaps with sed or grep?

Regarding the last question, I refer to something like this. The node where the xml from the txt should be added has to be specific, e.g. selectable by XPath at least because I want to edit certain nodes only.

Note: The above model is just an example. The actual loop will add 26 --subnodes for each loop and 3 or 4 attr for each --subnode.  Thats why it's important for xmlstarlet to add the attr properly and not to some other element. They have to be added in order.

答:
Why not use parallel (or sem) so that you can parallelise the job over the number of cores available on the machine?
The code I use is parsing an array with 2 variables, that I export in local just to make sure processes are isolated.</p>

```<code>for array in "${listofarrays[@]}"; do
    local var1;local var2
    IFS=, read var1 var2 <<< $array
    sem -j +0
    <code goes here>
done
sem --wait
</code>```

Body:
This is a matter of efficiency rather than troubleshooting. I have the following code snippet:

# The -R flag restores malformed XML
xmlstarlet -q fo -R <<<"$xml_content" | \
    # Delete xml_data
    xmlstarlet ed -d "$xml_data" | \
    # Delete index
    xmlstarlet ed -d "$xml_index" | \
    # Delete specific objects
    xmlstarlet ed -d "$xml_nodes/objects" | \
    # Append new node
    xmlstarlet ed -s "$xml_nodes" -t elem -n subnode -v "Hello World" | \
        # Add x attribute to node
        xmlstarlet ed -i "($xml_nodes)[last()]" -t attr -n x -v "0" | \
        # Add y attribute to node
        xmlstarlet ed -i "($xml_nodes)[last()]" -t attr -n y -v "0" | \
        # Add z attribute to node
        xmlstarlet ed -i "($xml_nodes)[last()]" -t attr -n z -v "1" \
            > "$output_file"

The variable $xml_content contains the xml tree of contents and

nodes parsed from a file with size 472.6 MB using the cat command.

The variable $output_file as its name indicates, contains the path
to the output file.

The rest of the variables simply contain the according XPaths I want to edit.

According to this brief article which helped come up with this code, it indicates that:

This is a bit ineffeciant since the xml file is parsed and written twice.

In my case, it is parsed and written more than twice (eventually in a loop over 1000 times).

So, taking the above script, the execution time alone of that short fragment is 4 mins and 7 secs.

Assuming the excessive, repetitive and perhaps inefficient piping together with the file size is why the code runs slow, the more subnodes I ultimately insert/delete will eventually cause it to execute even slower.

I apologise in advance if I might sound monotonous by reiterating myself or by bringing out an old and probably already answered topic, however, I'm really keen to understand how xmlstarlet works in detail with large XML documents.

UPDATE

As claimed by @Cyrus in his prior answer:

Those two xmlstarlets should do the job:

xmlstarlet -q fo -R <<<"$xml_content" |\
  xmlstarlet ed \
    -d "$xml_data" \
    -d "$xml_index" \
    -d "$xml_nodes/objects" \
    -s "$xml_nodes" -t elem -n subnode -v "Hello World" \
    -i "($xml_nodes)[last()]" -t attr -n x -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n y -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n z -v "1" > "$output_file"

This produced the following errors:

-:691.84: Attribute x redefined

-:691.84: Attribute z redefined

-:495981.9: xmlSAX2Characters: huge text node: out of memory

-:495981.9: Extra content at the end of the document

I honestly don't know how these errors where produced because I changed the code too often testing various scenarios and potential alternatives, however, this is what did the trick for me:

xmlstarlet ed --omit-decl -L \
    -d "$xml_data" \
    -d "$xml_index" \
    -d "$xml_nodes/objects" \
    -s "$xml_nodes" -t elem -n subnode -v "Hello World" \
    "$temp_xml_file"

xmlstarlet ed --omit-decl -L \
    -i "($xml_nodes)[last()]" -t attr -n x -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n y -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n z -v "1" \
    "$temp_xml_file"

Regarding the actual data that is inserted, this is what I have at the beginning:

...
<node>
    <subnode>A</subnode>
    <subnode>B</subnode>
    <objects>1</objects>
    <objects>2</objects>
    <objects>3</objects>
    ...
</node>
...

Executing the above (split) code gives me what I want:

...
<node>
    <subnode>A</subnode>
    <subnode>B</subnode>
    <subnode x="0" y="0" z="1">Hello World</subnode>
</node>
...

By splitting them, xmlstarlet is able to insert the attributes into the newly created node, else it will add them to the last() instance of the selected Xpath before the --subnode is even created. To some extent this is still inefficient, nevertheless, the code runs in less than a minute now.

The following code,

xmlstarlet ed --omit-decl -L \
    -d "$xml_data" \
    -d "$xml_index" \
    -d "$xml_nodes/objects" \
    -s "$xml_nodes" -t elem -n subnode -v "Hello World" \
    -i "($xml_nodes)[last()]" -t attr -n x -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n y -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n z -v "1" \
    "$temp_xml_file"

However, gives me this:

...
<node>
    <subnode>A</subnode>
    <subnode x="0" y="0" z="1">B</subnode>
    <subnode>Hello World</subnode>
</node>
...

By joining the xmlstarlets into one like in this post also answered by @Cyrus, it somehow first adds the attributes and then creates the --subnode where the innerText is Hello World.

Can anyone explain why this strange behaviour is happening??

This is another reference which states that "every edit operation is performed in sequence"

The above article explains exactly what I'm looking for, yet I cannot manage to make it work all in one xmlstarlet ed \. Alternatively, I tried:

Replacing ($xml_nodes)[last()] with $xml_nodes[text() = 'Hello World']

Using $prev (or $xstar:prev) as the argument to -i like in this answer. [Examples]

The temporary element name trick via -r to rename the temp node after the attr are added

All of the above insert the --subnode but leave the new element without attributes.

Note: I run XMLStarlet 1.6.1 on OS X El Capitan v 10.11.3

BONUS

As I mentioned in the beginning I wish to use a loop like something along these lines:

list="$(tr -d '\r' < $names)"

for name in $list; do
    xmlstarlet ed --omit-decl -L \
    -d "$xml_data" \
    -d "$xml_index" \
    -d "$xml_nodes/objects" \
    -s "$xml_nodes" -t elem -n subnode -v "$name" \
    -i "($xml_nodes)[last()]" -t attr -n x -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n y -v "0" \
    -i "($xml_nodes)[last()]" -t attr -n z -v "1" \
    "$temp_xml_file"
done

The $list contains over a thousand different names which need to be added with their respective attributes. The --value of each attribute may vary with every loop as well. Given the above model:

What is the fastest and most accurate version of such loop given that the attributes are added correctly to the corresponding node?

Would it be faster to create the list of nodes in an external txt file and later add those xml elements (inside the txt file) into  another XML file. If yes, how? Perhaps with sed or grep?

Regarding the last question, I refer to something like this. The node where the xml from the txt should be added has to be specific, e.g. selectable by XPath at least because I want to edit certain nodes only.

Note: The above model is just an example. The actual loop will add 26 --subnodes for each loop and 3 or 4 attr for each --subnode.  Thats why it's important for xmlstarlet to add the attr properly and not to some other element. They have to be added in order.

Body:
Why not use parallel (or sem) so that you can parallelise the job over the number of cores available on the machine?
The code I use is parsing an array with 2 variables, that I export in local just to make sure processes are isolated.

for array in "${listofarrays[@]}"; do
    local var1;local var2
    IFS=, read var1 var2 <<< $array
    sem -j +0
    <code goes here>
done
sem --wait