问:
Pandas: Apply rolling function to compute new column value
I am trying to compute a new column Y on each row by checking the 9 previous rows and current row values of column X. Basically the new column Y value on each row will tell us the percentage on values of column X were greater than 1 for previous 10 records including the current record . Below is the code i am using but getting a different result than expected

[EDITED]

```<code>def count_pcnt(x):
 return ((np.sum(x > 1) / len(x)) * 100.0)

def run():
df = pd.DataFrame(
data={'X': ['8.12', '7.13', '-5.30', '3.21', '4.21', '3.14','8.65',
            '7.33', '-5.10', '3.01']
      })

df['Y'] = df['X'].rolling(window=10, min_periods=1).apply(lambda x:
          count_pcnt(x)).apply(int)
</code>```

Expected Result  [ EDITED ]

```<code>     X    Y(%)
0   8.12  100
1   7.13  100
2  -5.30  66.67
3   3.21  75
4   4.21  80
5   3.14  83.33
6   8.65  85.71
7   7.33  87.50
8  -5.10  77.77
9   3.01  80
</code>```

Actual

```<code>      X    Y
 0   8.12  100
 1   7.13  100
 2  -5.30  0
 3   3.21  0
 4   4.21  0
 5   3.14  0
 6   8.65  0
 7   7.33  0
 8  -5.10  0
 9   3.01  0
</code>```

UPDATE I used this option recommended below and it worked. Though there are other options i felt this is much cleaner

```<code>df['Y'] = df['X'].astype(float)
             .rolling(window=w, min_periods=1)
             .apply(lambda x: (x>1).mean()) * 100
</code>```

if you want to compute column values based on next 10 rows rather than previous 10 rows -  below is the solution (Thanks to jezrael who provided it)

```<code>df['Y'] = (df['X'].astype(float).iloc[::-1].rolling(window=10, min_periods=1).apply(lambda x: (x>1).mean()) * 100)[::-1]
</code>```

Body:
I am trying to compute a new column Y on each row by checking the 9 previous rows and current row values of column X. Basically the new column Y value on each row will tell us the percentage on values of column X were greater than 1 for previous 10 records including the current record . Below is the code i am using but getting a different result than expected

[EDITED]

def count_pcnt(x):
 return ((np.sum(x > 1) / len(x)) * 100.0)

def run():
df = pd.DataFrame(
data={'X': ['8.12', '7.13', '-5.30', '3.21', '4.21', '3.14','8.65',
            '7.33', '-5.10', '3.01']
      })

df['Y'] = df['X'].rolling(window=10, min_periods=1).apply(lambda x:
          count_pcnt(x)).apply(int)

Expected Result  [ EDITED ]

     X    Y(%)
0   8.12  100
1   7.13  100
2  -5.30  66.67
3   3.21  75
4   4.21  80
5   3.14  83.33
6   8.65  85.71
7   7.33  87.50
8  -5.10  77.77
9   3.01  80

Actual

      X    Y
 0   8.12  100
 1   7.13  100
 2  -5.30  0
 3   3.21  0
 4   4.21  0
 5   3.14  0
 6   8.65  0
 7   7.33  0
 8  -5.10  0
 9   3.01  0

UPDATE I used this option recommended below and it worked. Though there are other options i felt this is much cleaner

df['Y'] = df['X'].astype(float)
             .rolling(window=w, min_periods=1)
             .apply(lambda x: (x>1).mean()) * 100

if you want to compute column values based on next 10 rows rather than previous 10 rows -  below is the solution (Thanks to jezrael who provided it)

df['Y'] = (df['X'].astype(float).iloc[::-1].rolling(window=10, min_periods=1).apply(lambda x: (x>1).mean()) * 100)[::-1]

Body:
It seems your data type for X is object instead of float. Try the following to see if it works.

 df['Y'] = (
    df.assign(X2=(df.X.astype(float)>0)).X2.rolling(window=10,min_periods=1)
      .apply(lambda x: sum(x)*100.0/len(x))
    )

df
Out[92]:
       X           Y
0   8.12  100.000000
1   7.13  100.000000
2  -5.30   66.666667
3   3.21   75.000000
4   4.21   80.000000
5   3.14   83.333333
6   8.65   85.714286
7   7.33   87.500000
8  -5.10   77.777778
9   3.01   80.000000


来源: stackexchange

问:
Duplicate 'Content' items were included. The .NET SDK includes 'Content' items from your project directory by default
Whenever I add a javascript or css file to my asp.net core project and I execute dotnet run in my bash terminal, I get the following error:

/usr/share/dotnet/sdk/1.0.1/Sdks/Microsoft.NET.Sdk/build/Microsoft

.NET.Sdk.DefaultItems.targets(188,5): error : Duplicate 'Content'
  items were included. The .NET SDK includes 'Content' items from your
  project directory by default. You can either remove these items from
  your project file, or set the 'EnableDefaultContentItems' property to
  'false' if you want to explicitly include them in your project file.
  For more information, see https://aka.ms/sdkimplicititems. The
  duplicate items were: 'wwwroot/css/BasicQuotation.css';
  'wwwroot/js/BasicQuotation.js'
  [/mnt/c/Dev/myproject/MyProject/MyProject.csproj]

The build failed. Please fix the build errors and run again.

I can fix this by removing the ItemGroup from my csproj file, but I don't think that's very productive.

This happens in the default Visual Studio 2017 ASP.NET Core Web Application (.NET Core) template. I add the files to my project by right clicking the wwwroot > js folder and then select Add > New Item > JavaScript File

This is my .csproj file:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <PropertyGroup>
    <PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback>
  </PropertyGroup>

  <PropertyGroup>
    <UserSecretsId>aspnet-MyProject-7e1906d8-5dbd-469a-b237-d7a563081253</UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <Compile Remove="wwwroot\lib\jquery-validation\**" />
    <Content Remove="wwwroot\lib\jquery-validation\**" />
    <EmbeddedResource Remove="wwwroot\lib\jquery-validation\**" />
    <None Remove="wwwroot\lib\jquery-validation\**" />
  </ItemGroup>

  <ItemGroup>
    <Content Include="wwwroot\css\BasicQuotation.css" />
    <Content Include="wwwroot\js\BasicQuotation.js" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" PrivateAssets="All" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" PrivateAssets="All" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.0" PrivateAssets="All" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
    <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.0" />
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />
  </ItemGroup>
  <ItemGroup>
    <Folder Include="Data\Commands\" />
    <Folder Include="Data\Queries\" />
    <Folder Include="wwwroot\images\" />
  </ItemGroup>

</Project>
</code>```

答:
So I ran into this same issue.  I didn't want to turn off DefaultCompileItems because I knew that wouldn't "fix" the problem.  So I unloaded my project and opened the .csproj file in text mode in Visual Studio and saw this.

```<code><ItemGroup>
    <Content Include="wwwroot\css\custom-bootstrap-navbar.css" />
    <Content Include="wwwroot\images\friends-eating\image1.jpg" />
    <Content Include="wwwroot\images\friends-eating\image2.jpg" />
    <Content Include="wwwroot\images\friends-eating\image3.jpg" />
</ItemGroup>
<ItemGroup>
    <Folder Include="wwwroot\images\friends-eating\" />
</ItemGroup>
</code>```

When I commented out the first ItemGroup block, it worked.  What I assume is happening is that the project is adding the entire \images\friends-eating\ folder and then adding each individual image, causing a duplication.

As far as the custom css and js, the project automatically adds wwwroot\css and wwwroot\js so if you have an individual file added (like wwwroot\css\custom-bootstrap-navbar.css) it'll count as a duplicate.

ContentLicense: CC BY-SA 3.0

Body:
Whenever I add a javascript or css file to my asp.net core project and I execute dotnet run in my bash terminal, I get the following error:

/usr/share/dotnet/sdk/1.0.1/Sdks/Microsoft.NET.Sdk/build/Microsoft

.NET.Sdk.DefaultItems.targets(188,5): error : Duplicate 'Content'
  items were included. The .NET SDK includes 'Content' items from your
  project directory by default. You can either remove these items from
  your project file, or set the 'EnableDefaultContentItems' property to
  'false' if you want to explicitly include them in your project file.
  For more information, see https://aka.ms/sdkimplicititems. The
  duplicate items were: 'wwwroot/css/BasicQuotation.css';
  'wwwroot/js/BasicQuotation.js'
  [/mnt/c/Dev/myproject/MyProject/MyProject.csproj]

The build failed. Please fix the build errors and run again.

I can fix this by removing the ItemGroup from my csproj file, but I don't think that's very productive.

This happens in the default Visual Studio 2017 ASP.NET Core Web Application (.NET Core) template. I add the files to my project by right clicking the wwwroot > js folder and then select Add > New Item > JavaScript File

This is my .csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <PropertyGroup>
    <PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback>
  </PropertyGroup>

  <PropertyGroup>
    <UserSecretsId>aspnet-MyProject-7e1906d8-5dbd-469a-b237-d7a563081253</UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <Compile Remove="wwwroot\lib\jquery-validation\**" />
    <Content Remove="wwwroot\lib\jquery-validation\**" />
    <EmbeddedResource Remove="wwwroot\lib\jquery-validation\**" />
    <None Remove="wwwroot\lib\jquery-validation\**" />
  </ItemGroup>

  <ItemGroup>
    <Content Include="wwwroot\css\BasicQuotation.css" />
    <Content Include="wwwroot\js\BasicQuotation.js" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" PrivateAssets="All" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" PrivateAssets="All" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.0" PrivateAssets="All" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
    <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.0" />
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />
  </ItemGroup>
  <ItemGroup>
    <Folder Include="Data\Commands\" />
    <Folder Include="Data\Queries\" />
    <Folder Include="wwwroot\images\" />
  </ItemGroup>

</Project>

Body:
So I ran into this same issue.  I didn't want to turn off DefaultCompileItems because I knew that wouldn't "fix" the problem.  So I unloaded my project and opened the .csproj file in text mode in Visual Studio and saw this.

<ItemGroup>
    <Content Include="wwwroot\css\custom-bootstrap-navbar.css" />
    <Content Include="wwwroot\images\friends-eating\image1.jpg" />
    <Content Include="wwwroot\images\friends-eating\image2.jpg" />
    <Content Include="wwwroot\images\friends-eating\image3.jpg" />
</ItemGroup>
<ItemGroup>
    <Folder Include="wwwroot\images\friends-eating\" />
</ItemGroup>

When I commented out the first ItemGroup block, it worked.  What I assume is happening is that the project is adding the entire \images\friends-eating\ folder and then adding each individual image, causing a duplication.

As far as the custom css and js, the project automatically adds wwwroot\css and wwwroot\js so if you have an individual file added (like wwwroot\css\custom-bootstrap-navbar.css) it'll count as a duplicate.


问:
How to lower integrity of WCF named pipe
I have an Internet Explorer add-in, written in C#, which talks via a WCF named-pipe to a .NET desktop application.  The desktop app creates the ServiceHost for the netNamedPipeBinding, and each instance of the IE add-in creates a ChannelFactory to talk to the app.  Everything works fine under Windows XP, but an exception is thrown under IE's protected mode in Windows 7.

System.ServiceModel.CommunicationException: Cannot connect to endpoint 'net.pipe://localhost/MyApp.MyID'. ---> System.IO.PipeException: A pipe endpoint exists for '\.\pipe...guid...', but the connect failed: Access is denied. (5, 0x5)

Running the add-in under protected mode is a scenario I must support.  My understanding is that if I lower the integrity level of the named-pipe, then my IE add-in will be allowed to talk through it.  My question is how to do that.  I have things setup to use WCF, and would preferably like to keep it that way.  Can I make WCF create the named pipe with the lower integrity level?  What code do I write to make that happen?

答:
I don't think this is going to be possible.

The problem is that the integrity label has to be specified in the security descriptor provided when the Named Pipe is created. In the standard NetNamedPipeBinding, that call to CreateNamedPipe happens inside the private CreatePipe() method of the internal WCF class System.ServiceModel.Channels.PipeConnectionListener. I can't see a way to change how it specifies the initial security descriptor for the pipe.

See this question and answer for an outline of what we need to achieve.

Writing a custom named pipe transport binding element from scratch seems like the only way at present to get round this, failing which we'll just have to wait for Microsoft to add some enabling features in a future version of WCF. If you have access to Microsoft Connect, you could add your voice to the others requesting this feature.

EDIT:
I was too pessimistic. I have now found a way to do this.

The key was that it turned out you don't necessarily have to specify the integrity label in the security descriptor when the pipe is created - but you do have to modify the SACL using the handle returned from CreateNamedPipe when the listener is opened - i.e. the very first server-side handle to the pipe. Using any other handle, the attempt to add the integrity label always fails, because the dwOpenMode flag parameter to CreateNamedPipe overloads the use of one of the bits to mean both FILE_FLAG_FIRST_PIPE_INSTANCE and WRITE_OWNER. We need the latter access permission in order to add the integrity label, but the presence of the former causes the call to fail on any but the first pipe instance.

Getting hold of the first pipe handle is not a trivial undertaking. WCF squirrels it away in an instance of the type System.ServiceModel.Channels.PipeConnectionListener.PendingAccept, stored in a list maintained by the pipe connection listener. The connection listener is not the same thing as the channel listener (which can be grabbed straightforwardly by overriding the BuildChannelListener<> method of a binding element), and it is much harder to get at. It involves heroics using reflection, to locate the TransportManager for the endpoint, which holds a reference to the endpoint's connection listener, and then working down a chain of connection listeners (which varies according to configuration of tracing etc) until the pipe connection listener is found. If we are lucky the first pipe handle can then be found in the listener's pending accept list (though there is a race condition here - if a client connects before we get hold of the handle, it will be gone forever).

Once the handle is available, lowering the integrity to allow low integrity clients to communicate wth the service is just a matter of calling SetSecurityInfo on the handle to add the integrity label.

I plan to cover this is some detail on my blog soon.

ContentLicense: CC BY-SA 2.5


问:
VS2017 can't find git from command line in W7 Professional
I have two VS2017 systems next to me.  One is on a W7 Home Premium x64.  The other is on a W7 Professional x64.  And both instances of VS2017 were installed from the same files at around the same time. (although I can't remember if they were installed with exactly the same options)

On the Home Premium system I can go to the Team Explorer tab, right click on a repository, select open command prompt and then use git from that command line.

On the Professional system, once I get to the command prompt I get the message:

'git' is not recognized as an external or internal command, operable
  program or batch file.

Yet I have not had any indication from within VS2017 that there was anything wrong with any git operations.

On both machines I find Git at

C:\Program Files (x86)\Microsoft Visual
  Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team
  Explorer\Git

But on the working machine there is no explicit path to this location.

What is going on with my non-working W7 Professional system?

Forehead slap

While there is nothing in the path pointing to the version of git being used by VS2017 for my W7 Home Premium, when I looked more closely at the path I realized that at some point in the past I had manually installed Git for Windows directly from Git-Scm, and that this was the version being referenced from with in the VS2017 command line window.

As such the real question should have been

Why is Git working from the command line on my W7 Home Premium system
  in the first place?

答:
What is going on with my non-working W7 Professional system?

Check the value of your current environment value PATH on both machine, which is used when Visual Studio is launched. Maybe one has that folder in it, or even is referencing another Git for Windows installed elsewhere (as recommended in "Get started with Git from the command line").

See if the Visual Studio 2017 Git QuickStart is working.


问:
Yii2 - Merge two models and return as JSON
In Yii2 Framework, is it possible to merge two models and return it as a one JSON object.
Below are the two object retrieved from database</p>

```<code>public function actionJson()
{
   \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
   $result = Result::findOne(1);
   $user = User::findOne(1);
   // Merge two objects
   // Something like this
   $model = $result + $user;
   return $model;
}
</code>```

答:
You could assign the 2 to  an associative  array  with key based on the model name</p>

```<code>  public function actionJson()
  {
     \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
     $result = Result::findOne(1);
     $user = User::findOne(1);

     //
     $myModels['result'] = $result;
     $myModels['user'] = $user;

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

Body:
In Yii2 Framework, is it possible to merge two models and return it as a one JSON object.
Below are the two object retrieved from database

public function actionJson()
{
   \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
   $result = Result::findOne(1);
   $user = User::findOne(1);
   // Merge two objects
   // Something like this
   $model = $result + $user;
   return $model;
}

Body:
You could assign the 2 to  an associative  array  with key based on the model name

  public function actionJson()
  {
     \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
     $result = Result::findOne(1);
     $user = User::findOne(1);

     //
     $myModels['result'] = $result;
     $myModels['user'] = $user;

      return $myModels;
  }


问:
how to get synonyms list from ms word using C#
In word automation, how to get synonyms list through ms word using c# language. please advice me.</p>

答:
Use SynonymInfo Object

Refer this
http://msdn.microsoft.com/en-us/library/bb178951.aspx


问:
checking router.isActive on nested Routes in React
I'm trying to check routes with Router.isActive

If the current route is /animals/edit

```<code>(router.isActive('/animals/edit')
</code>```

is true.

But if the current route is /animals/edit/23

```<code>(router.isActive('/animals/edit/')
</code>```

is false.

How can I make a route that encompasses trailing params?

答:
Unfortunately I don't think this is possible with router.isActive as it doesn't support path params (i.e. router.isActive('/animals/edit/:number')).

As an alternative, using React Router v4's matchPath you could do:

```<code>import { matchPath } from 'react-router'

const match = matchPath(currentPath, {
  path: '/animals/edit(/:number)',
  exact: true,
  strict: false
})
</code>```

Body:
I'm trying to check routes with Router.isActive

If the current route is /animals/edit

(router.isActive('/animals/edit')

is true.

But if the current route is /animals/edit/23

(router.isActive('/animals/edit/')

is false.

How can I make a route that encompasses trailing params?

Body:
Unfortunately I don't think this is possible with router.isActive as it doesn't support path params (i.e. router.isActive('/animals/edit/:number')).

As an alternative, using React Router v4's matchPath you could do:

import { matchPath } from 'react-router'

const match = matchPath(currentPath, {
  path: '/animals/edit(/:number)',
  exact: true,
  strict: false
})


问:
Couchbase Lite: reading document vs querying data
I'm switching an Android project to using Couchbase Lite, and I'm confused with ways for fetching the data from the database.

I have a document, which contains only one property:

```<code>Map<String, Object> properties = new HashMap<String, Object>();
properties.put("data_key", json);
Document document = database.getDocument("data_doc_id");
document.putProperties(properties);
</code>```

The next my step is getting the stored data from the database. I found two ways:

The first approach is reading the document

```<code>Document doc = database.getDocument("data_doc_id");
String json = (String) doc.getProperty("data_key");
</code>```

The second one is querying

```<code>View view = database.getView("data_json");
view.setMap(new Mapper() {

@Override
public void map(Map<String, Object> document, Emitter emitter) {
    if ("data_doc_id".equals(document.get("_id")) {
        String json = (String) doc.getProperty("data_key");
        emitter.emit("data_key", json);
    }
}
}, "1.0");
QueryEnumerator queryEnumerator = view.createQuery().run();
String dataJson = "";

for (QueryRow queryRow : run) {
    if ("data_key".equals(queryRow.getKey()) {
        json = (String) queryRow.getValue();
    }
}
</code>```

Is it okay to use the first approach to get the stored JSON?

For what cases the second approach should be used? It has far more code than the first one, maybe it has something to do with caching or/and speed/performance? What are the pros and cons of this approach?

答:
The first approach is retrieving the document directly.  This is the fastest way to do it.

With databases, though, often you want to retrieve documents based on some feature of the data.  To do this you want the ability to create queries about the data.  That's what the second approach is for.

ContentLicense: CC BY-SA 4.0

Body:
I'm switching an Android project to using Couchbase Lite, and I'm confused with ways for fetching the data from the database.

I have a document, which contains only one property:

Map<String, Object> properties = new HashMap<String, Object>();
properties.put("data_key", json);
Document document = database.getDocument("data_doc_id");
document.putProperties(properties);

The next my step is getting the stored data from the database. I found two ways:

The first approach is reading the document

Document doc = database.getDocument("data_doc_id");
String json = (String) doc.getProperty("data_key");

The second one is querying

View view = database.getView("data_json");
view.setMap(new Mapper() {

@Override
public void map(Map<String, Object> document, Emitter emitter) {
    if ("data_doc_id".equals(document.get("_id")) {
        String json = (String) doc.getProperty("data_key");
        emitter.emit("data_key", json);
    }
}
}, "1.0");
QueryEnumerator queryEnumerator = view.createQuery().run();
String dataJson = "";

for (QueryRow queryRow : run) {
    if ("data_key".equals(queryRow.getKey()) {
        json = (String) queryRow.getValue();
    }
}

Is it okay to use the first approach to get the stored JSON?

For what cases the second approach should be used? It has far more code than the first one, maybe it has something to do with caching or/and speed/performance? What are the pros and cons of this approach?


问:
Installing PyDev IDE for Eclipse 5.4.0 on Eclipse Mars 4.5.2 throws error "Profile id _SELF_ is not registered"
Problems occurred while performing provisioning operation: Profile id SELF is not registered.
Profile id SELF is not registered.

Please share your thought on this Thanks

Part of Error Log:

```<code>!ENTRY org.eclipse.epp.logging.aeri.core 2 1 2017-01-07 20:55:23.822
!MESSAGE AERI failed with an error. Please report this error: null ; version: 1.100.0.v20160211-1103
!STACK 0
java.lang.NullPointerException
</code>```

答:
from run go to the %userprofile%   --> C:\users\
go to .p2 folder --- delete all folders/files
run the eclipse .....  close the eclipse ... and start again...</p>

Body:
Problems occurred while performing provisioning operation: Profile id SELF is not registered.
Profile id SELF is not registered.

Please share your thought on this Thanks

Part of Error Log:

!ENTRY org.eclipse.epp.logging.aeri.core 2 1 2017-01-07 20:55:23.822
!MESSAGE AERI failed with an error. Please report this error: null ; version: 1.100.0.v20160211-1103
!STACK 0
java.lang.NullPointerException


问:
Is it possible to commit/rollback SqlTransaction in asynchronous?
I'm trying to commit/rollback SqlTransaction in asynchronous. But it look like asynchronous is not supported. Is there any way to make it asynchronous without using raw SQL to start transaction?

答:
```<code>using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
    . . .
}
</code>```


问:
500 (Internal Server Error) while testing restful api from mysql database
I have created a restful webservice from mysql database and used it's default world schema. I used Glassfish Server 4.1.1.

Now, when I test the restful webservice with another test web project a 500 (Internal Server Error) occurs.

```<code>GET RequestFailed RequestFailed --> Status: (500)
Response:{

HTTP Status 500 - Internal Server Error
type: Exception report
message: Internal Server Error
description: The server encountered an internal error that prevented it from fulfilling this request.

exception: javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: javax/xml/parsers/ParserConfigurationException

root cause:
org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: javax/xml/parsers/ParserConfigurationException

java.lang.NoClassDefFoundError: javax/xml/parsers/ParserConfigurationException

java.lang.ClassNotFoundException: javax.xml.parsers.ParserConfigurationException not found by org.eclipse.persistence.moxy [227]
</code>```

Notes:

1) My entity classes are working fine. When run the url http://localhost:8080/RestfulAPI/webresources/com.rakin.city  then i could see all the data in a xml file.

2) I tried some solutions and add jersy libraries in the webservice but it didn't solve my problem either. After adding jersy libraries it couldn't access WADL

I restarted the glassfish server and the resp application but the same problem occurs again and again.

3)My project file and libraries:

答:
add javax.xml.parsers dependency into your pom.xml file.

https://mvnrepository.com/artifact/javax.xml.parsers/jaxp-api/1.4.5

Body:
I have created a restful webservice from mysql database and used it's default world schema. I used Glassfish Server 4.1.1.

Now, when I test the restful webservice with another test web project a 500 (Internal Server Error) occurs.

GET RequestFailed RequestFailed --> Status: (500)
Response:{

HTTP Status 500 - Internal Server Error
type: Exception report
message: Internal Server Error
description: The server encountered an internal error that prevented it from fulfilling this request.

exception: javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: javax/xml/parsers/ParserConfigurationException

root cause:
org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: javax/xml/parsers/ParserConfigurationException

java.lang.NoClassDefFoundError: javax/xml/parsers/ParserConfigurationException

java.lang.ClassNotFoundException: javax.xml.parsers.ParserConfigurationException not found by org.eclipse.persistence.moxy [227]

Notes:

1) My entity classes are working fine. When run the url http://localhost:8080/RestfulAPI/webresources/com.rakin.city  then i could see all the data in a xml file.

2) I tried some solutions and add jersy libraries in the webservice but it didn't solve my problem either. After adding jersy libraries it couldn't access WADL

I restarted the glassfish server and the resp application but the same problem occurs again and again.

3)My project file and libraries:


问:
Cassandra Data Modeling : Dynamic column
I have a table user_activity.

```<code>user_activity
{
user_id text
user_name text
email_id text
password text
activity1 text}
</code>```

Is it possible to add column dynamically?

```<code>for ex -

user1(user_id : Rowkey)

user_name, emai_id, password, activity1, activity2

user2(user_id : Rowkey)

user_name, emai_id, password, activity1, activity2, activity3

user3(user_id : Rowkey)

user_name, emai_id, password, activity1
</code>```

since activities could be of any number.

thanks in advance :)

答:
You can use Map

For example :

```<code>CREATE TABLE user_activity (
    user_id text primary key,
    emai_id text,
    password text,
    activity map<text,text>
);
</code>```

Insert :

```<code>INSERT INTO user_activity (user_id, emai_id, password, activity) VALUES ('1', 'a1@b.com','password1', {'activity1'  : 'test activity 1', 'activity2' : 'test acitivty 2' });
</code>```

Update :

```<code>UPDATE user_activity SET activity['activity1'] = 'updated test activity 1' where user_id = '1';
</code>```

Delete :

```<code>DELETE activity['activity2'] FROM user_activity WHERE user_id = '1';
</code>```

Note : Keep the collection (map) size small, In Cassandra for map Maximum number of keys: 65535 and values size: 65535

Body:
I have a table user_activity.

user_activity
{
user_id text
user_name text
email_id text
password text
activity1 text}

Is it possible to add column dynamically?

for ex -

user1(user_id : Rowkey)

user_name, emai_id, password, activity1, activity2

user2(user_id : Rowkey)

user_name, emai_id, password, activity1, activity2, activity3

user3(user_id : Rowkey)

user_name, emai_id, password, activity1

since activities could be of any number.

thanks in advance :)

Body:
You can use Map

For example :

CREATE TABLE user_activity (
    user_id text primary key,
    emai_id text,
    password text,
    activity map<text,text>
);

Insert :

INSERT INTO user_activity (user_id, emai_id, password, activity) VALUES ('1', 'a1@b.com','password1', {'activity1'  : 'test activity 1', 'activity2' : 'test acitivty 2' });

Update :

UPDATE user_activity SET activity['activity1'] = 'updated test activity 1' where user_id = '1';

Delete :

DELETE activity['activity2'] FROM user_activity WHERE user_id = '1';

Note : Keep the collection (map) size small, In Cassandra for map Maximum number of keys: 65535 and values size: 65535


问:
WebApp giving DEBUG error on some of the browsers
After a quick research I was able to build a very basic Django app to find the weather using the openweathermap api.I deployed it using Digital Ocean after getting a free domain from freenom.Problem is when I sent to to some of my friends to see it wont open in some of them, giving the error as follows:
Change that to False, and Django will
 display a standard page generated by the handler for this status code.
Thanks! Here is the link to the app:
http://currweather.cf
PS:It's not much as I am new to Django

答: Check your settings.py, You need to add DEBUG=False


问:
android: Fragment for RecycleView
I read about ListView and RecycleView. I understood that RecycleView is a more advanced and flexible version of ListView. So like ListFragment for listView, Is there any inbuilt fragment for RecyleView? If i need a RecycleView inside a fragment then what is the proper way to implement it?

答:
Check out these tutorials

Using the recycler view

Multiple views in recycler view

Title: android: Fragment for RecycleView


问:
Build minimum height BST from a sorted std::list<float> with C++
I'm having trouble writing the code to build minimum height BST from a sorted std::list.
For the node class:

```<code>class cBTNode
{
private:
    cBTNode* m_LeftChild;
    cBTNode* m_RightChild;
    float m_Data;
}
</code>```

For the BST class:

```<code>class cBTNodeTree
{
private:
    cBTNode* m_Root;
public:
    void LoadBalancedMain(std::list<float>& ls)；
    void LoadBalanced(std::list<float>& ls, cBTNode* root);
}
</code>```

Implementation: (basically my method is to find the middle element of the list ls, put that into the root, put all the elements smaller than the middle element into ls_left, and all the elements bigger than it into ls_right. Then recursively build up the left and right subtree by recursively calling the same function on ls_left and ls_right)

```<code>void cBTNodeTree::LoadBalancedMain(std::list<float>& ls)
{
    LoadBalanced(ls, m_Root); // m_Root is the root of the tree
}

void cBTNodeTree::LoadBalanced(std::list<float>& ls, cBTNode* root)
{
     // Stopping Condition I:
    if (ls.size() <= 0)
    {
        root = nullptr;
        return;
    }

    //  Stopping Condition II:
    if (ls.size() == 1)
    {
        root = new cBTNode(ls.front());
        return;
    }

    //  When we have at least 2 elements in the list
    //  Step 1: Locate the middle element

    if (ls.size() % 2 == 0)
    {
        //  Only consider the case of even numbers for the moment
        int middle = ls.size() / 2;
        std::list<float> ls_left;
        std::list<float> ls_right;
        int index = 0;

        // Obtain ls_left consisting elements smaller than the middle one
        while (index < middle)
        {
            ls_left.push_back(ls.front());
            ls.pop_front();
            index += 1;
        }
        //  Now we reach the middle element
        root = new cBTNode(ls.front());
        ls.pop_front();
        //  The rest is actually ls_right
        while (ls.size() > 0)
        {
            ls_right.push_back(ls.front());
            ls.pop_front();
        }
        //  Now we have the root and two lists
        cBTNode* left = root->GetLeftChild();
        cBTNode* right = root->GetRightChild();
        if (ls_left.size() > 0)
        {
            LoadBalanced(ls_left, left);
            root->SetLeftChild(left);
        }
        else
        {
            left = nullptr;
        }
        if (ls_right.size() > 0)
        {
            LoadBalanced(ls_right, right);
            root->SetRightChild(left);
        }
        else
        {
            right = nullptr;
        }
    }
}
</code>```

My Question: Somehow I found that actually none of the elements has been inserted into the tree. For example, if I check the value of m_Root, the root of the tree, I got an error because it's still nullprt. I'm not sure where did I go wrong? I hope it's some stupid pointer mistake because I haven't slept well. (I'm pretty sure the 'new cBTNode(ls.front())' line works)

BTW although I have written a dozen functions for the BST, I'm still struggling with BST recursion. I noticed that in all the textbooks that I read, for the linked list version of BST, the insertion ALWAYS need a helper function that return a pointer to a node. I begin to feel that I don't actually understand the things going on behind the recursion...

答:
1:

```<code>void cBTNodeTree::LoadBalanced(std::list<float>& ls, cBTNode* root)
</code>```

Here cBTNode* root is passed by value.

Instead, you should pass by reference & or cBTNode** (pointer to a pointer).

Passing by reference would be simple, you won't need to change anything except the function signature.

```<code>void cBTNodeTree::LoadBalanced(std::list<float>& ls, cBTNode*& root)
</code>```

Notice & before root in above statement.

2:

```<code>if (ls_right.size() > 0)
        {
            LoadBalanced(ls_right, right);
            root->SetRightChild(left);
        }
</code>```

You are setting right child to left root which is not what you desire.

3:

```<code>cBTNode* left = root->GetLeftChild();
cBTNode* right = root->GetRightChild();
</code>```

These are unnecessary.

4:

```<code>if (ls.size() % 2 == 0)
</code>```

No need for two separate cases.

You can achieve this by just appropriately setting middle:

```<code>int middle = (ls.size()-1) / 2;
</code>```

Body:
I'm having trouble writing the code to build minimum height BST from a sorted std::list.
For the node class:

class cBTNode
{
private:
    cBTNode* m_LeftChild;
    cBTNode* m_RightChild;
    float m_Data;
}

For the BST class:

class cBTNodeTree
{
private:
    cBTNode* m_Root;
public:
    void LoadBalancedMain(std::list<float>& ls)；
    void LoadBalanced(std::list<float>& ls, cBTNode* root);
}

Implementation: (basically my method is to find the middle element of the list ls, put that into the root, put all the elements smaller than the middle element into ls_left, and all the elements bigger than it into ls_right. Then recursively build up the left and right subtree by recursively calling the same function on ls_left and ls_right)

void cBTNodeTree::LoadBalancedMain(std::list<float>& ls)
{
    LoadBalanced(ls, m_Root); // m_Root is the root of the tree
}

void cBTNodeTree::LoadBalanced(std::list<float>& ls, cBTNode* root)
{
     // Stopping Condition I:
    if (ls.size() <= 0)
    {
        root = nullptr;
        return;
    }

    //  Stopping Condition II:
    if (ls.size() == 1)
    {
        root = new cBTNode(ls.front());
        return;
    }

    //  When we have at least 2 elements in the list
    //  Step 1: Locate the middle element

    if (ls.size() % 2 == 0)
    {
        //  Only consider the case of even numbers for the moment
        int middle = ls.size() / 2;
        std::list<float> ls_left;
        std::list<float> ls_right;
        int index = 0;

        // Obtain ls_left consisting elements smaller than the middle one
        while (index < middle)
        {
            ls_left.push_back(ls.front());
            ls.pop_front();
            index += 1;
        }
        //  Now we reach the middle element
        root = new cBTNode(ls.front());
        ls.pop_front();
        //  The rest is actually ls_right
        while (ls.size() > 0)
        {
            ls_right.push_back(ls.front());
            ls.pop_front();
        }
        //  Now we have the root and two lists
        cBTNode* left = root->GetLeftChild();
        cBTNode* right = root->GetRightChild();
        if (ls_left.size() > 0)
        {
            LoadBalanced(ls_left, left);
            root->SetLeftChild(left);
        }
        else
        {
            left = nullptr;
        }
        if (ls_right.size() > 0)
        {
            LoadBalanced(ls_right, right);
            root->SetRightChild(left);
        }
        else
        {
            right = nullptr;
        }
    }
}

My Question: Somehow I found that actually none of the elements has been inserted into the tree. For example, if I check the value of m_Root, the root of the tree, I got an error because it's still nullprt. I'm not sure where did I go wrong? I hope it's some stupid pointer mistake because I haven't slept well. (I'm pretty sure the 'new cBTNode(ls.front())' line works)

BTW although I have written a dozen functions for the BST, I'm still struggling with BST recursion. I noticed that in all the textbooks that I read, for the linked list version of BST, the insertion ALWAYS need a helper function that return a pointer to a node. I begin to feel that I don't actually understand the things going on behind the recursion...

Body:
1:

void cBTNodeTree::LoadBalanced(std::list<float>& ls, cBTNode* root)

Here cBTNode* root is passed by value.

Instead, you should pass by reference & or cBTNode** (pointer to a pointer).

Passing by reference would be simple, you won't need to change anything except the function signature.

void cBTNodeTree::LoadBalanced(std::list<float>& ls, cBTNode*& root)

Notice & before root in above statement.

2:

if (ls_right.size() > 0)
        {
            LoadBalanced(ls_right, right);
            root->SetRightChild(left);
        }

You are setting right child to left root which is not what you desire.

3:

cBTNode* left = root->GetLeftChild();
cBTNode* right = root->GetRightChild();

These are unnecessary.

4:

if (ls.size() % 2 == 0)

No need for two separate cases.

You can achieve this by just appropriately setting middle:

int middle = (ls.size()-1) / 2;


问:
Error in enabling a selector using jQuery
I'm trying to enable a multi selector only when a checkbox is checked. My code is generating an alert, but won't enable the selector

Selector & checkbox html+Script:

Enabling function:

```<code>$("#checkbox").bind("click", function () {

     if ($('#checkbox').is(":checked"))
          {  alert("checked");
            $("#sel").attr('disabled',false);

          }
    else
          {
            //Do nothing
          }
});
</code>```

答:
disable item is logically not editable, you need to remove the attribute</p>

```<code>element.removeAttribute("disabled");
</code>```

Body:
I'm trying to enable a multi selector only when a checkbox is checked. My code is generating an alert, but won't enable the selector

Selector & checkbox html+Script:

Enabling function:

$("#checkbox").bind("click", function () {

     if ($('#checkbox').is(":checked"))
          {  alert("checked");
            $("#sel").attr('disabled',false);

          }
    else
          {
            //Do nothing
          }
});

Body:
disable item is logically not editable, you need to remove the attribute

element.removeAttribute("disabled");


答:
Try this:</p>

```<code>$("#sel").removeAttr('disabled');
</code>```

Title: Error in enabling a selector using jQuery

Body:
Try this:

$("#sel").removeAttr('disabled');


问:
I want only values of 1st index then 2nd and then 3rd index. How can I iterate through this with a loop and get the values dynamically?
I want the values from this array for each index. I tried to access the values using foreach but I can´t figure out how to get all values for each index (i.e. for 1st, 2nd, 3rd)</p>

```<code>Array
    (
        [1] => Array
            (
                [0] => 244
                [1] => 6014
                [2] => 5067
                [3] => 5059
                [4] => 1726
                [5] => 56
                [6] => 1234
                [7] => 56
            )

        [2] => Array
            (
                [0] => 122
                [1] => 123
                [2] => 56
                [3] => 246
                [4] => 7360
                [5] => 8058
                [6] => 1290
                [7] => 1234
                [8] => 5454
            )

        [3] => Array
            (
                [0] => 7890
                [1] => 5454
            )

    )
</code>```

答:
Please try this. hopefully It will help u.

```<code>foreach ($array as $currencyId => $subArray){
    echo $currencyId . "<br>";

            foreach ($subArray as $value) {

                echo $value . "<br>";
            }
        }
</code>```

Body:
I want the values from this array for each index. I tried to access the values using foreach but I can´t figure out how to get all values for each index (i.e. for 1st, 2nd, 3rd)

Array
    (
        [1] => Array
            (
                [0] => 244
                [1] => 6014
                [2] => 5067
                [3] => 5059
                [4] => 1726
                [5] => 56
                [6] => 1234
                [7] => 56
            )

        [2] => Array
            (
                [0] => 122
                [1] => 123
                [2] => 56
                [3] => 246
                [4] => 7360
                [5] => 8058
                [6] => 1290
                [7] => 1234
                [8] => 5454
            )

        [3] => Array
            (
                [0] => 7890
                [1] => 5454
            )

    )

Body:
Please try this. hopefully It will help u.

foreach ($array as $currencyId => $subArray){
    echo $currencyId . "<br>";

            foreach ($subArray as $value) {

                echo $value . "<br>";
            }
        }


问:
Server action never invoked - JSON deserialization failure?
I have simple action in my controller:

```<code>[HttpPost]
public JsonResult Action(MenuSet menuSet)
{
   //...
}
</code>```

where MenuSet is:

```<code>public class MenuSet
{
    private IEnumerable<MenuEntry> _menuEntries;

    public IEnumerable<MenuEntry> MenuEntries
    {
        get { return _menuEntries; }
        set { _menuEntries = value; }
    }
}

public class MenuEntry
{
    private string _parentPageName;
    private IEnumerable<string> _orderedPages;

    public string ParentPageName
    {
        get { return _parentPageName; }
        set { _parentPageName = value; }
    }
    public IEnumerable<string> OrderedPages
    {
        get { return _orderedPages; }
        set { _orderedPages = value; }
    }
}
</code>```

From the client side, I'm invoking this action in the way below:

```<code>$.post("Controller/Action",
       $.param({ MenuEntries: prepareData() }, true),
       null,
       "json");
</code>```

where prepareData() function returns MenuEntries collection:

```<code>function prepareData() {
    var menuEntries = new Array();
    var menuEntry = {
        ParentPageName: null,
        OrderedPages: getPagesOrder()
    }
    menuEntries.push(menuEntry);
    return menuEntries;
}

function getPagesOrder() {
    var values = new Array();
    values.push('samplePageName')
    return values;
}
</code>```

But the JSON object appears to be not deserialized to the model at the server side - the controller action is never invoked. How to make this work ?

答:
First

You could as well use IList<MenuEntry> as parameter type in your action method.

Second

These two blog posts will help you get things done with automatic model validation which is not the case with the other guy's solution.

Asp.net MVC model binding to List<T>

Sending complex JSON objects to Asp.net MVC using jQuery

Body:
I have simple action in my controller:

[HttpPost]
public JsonResult Action(MenuSet menuSet)
{
   //...
}

where MenuSet is:

public class MenuSet
{
    private IEnumerable<MenuEntry> _menuEntries;

    public IEnumerable<MenuEntry> MenuEntries
    {
        get { return _menuEntries; }
        set { _menuEntries = value; }
    }
}

public class MenuEntry
{
    private string _parentPageName;
    private IEnumerable<string> _orderedPages;

    public string ParentPageName
    {
        get { return _parentPageName; }
        set { _parentPageName = value; }
    }
    public IEnumerable<string> OrderedPages
    {
        get { return _orderedPages; }
        set { _orderedPages = value; }
    }
}

From the client side, I'm invoking this action in the way below:

$.post("Controller/Action",
       $.param({ MenuEntries: prepareData() }, true),
       null,
       "json");

where prepareData() function returns MenuEntries collection:

function prepareData() {
    var menuEntries = new Array();
    var menuEntry = {
        ParentPageName: null,
        OrderedPages: getPagesOrder()
    }
    menuEntries.push(menuEntry);
    return menuEntries;
}

function getPagesOrder() {
    var values = new Array();
    values.push('samplePageName')
    return values;
}

But the JSON object appears to be not deserialized to the model at the server side - the controller action is never invoked. How to make this work ?


问:
Appending a value from dialog box to HTML body
I am having a problem of appending a value from the textbox in the dialog box to my html body.

```<code><div id="dialog-form">
  <form>
    <label for="name">Name</label>
     <input type="text" name="name" id="txt2 codein" class="text ui-widget-content ui-corner-all" />
  </form>
</div>
<p>Please are you <span id="addname"></span>

setTimeout( function() {

$( "#dialog-form" ).dialog({
    modal: true,
    draggable: false,
    height: 300,
    width: 500,
    open: function () {
      $('body').addClass('stop-scrolling');
    },
});

},4000);

var keeptrying = function(e) {
var addmust = $('#dialog-form #codein').val();

$("#addname").append("#dialog-form #codein");
}
</code>```

Any help and answer is appreciated thanks

答:
Here you go with the solution https://jsfiddle.net/g9m1pqmu/

```<code>setTimeout( function() {
    $( "#dialog-form" ).dialog({
        modal: true,
        draggable: false,
        height: 300,
        width: 500,
        open: function () {
            $('body').addClass('stop-scrolling');
        }
    });
},4000);

$('#codein').keypress(function() {
    $("#addname").html($('#codein').val());
});
</code>```

I guess this is what you are looking for.

Body:
I am having a problem of appending a value from the textbox in the dialog box to my html body.

  <form>
    Name
     <input type="text" name="name" id="txt2 codein" class="text ui-widget-content ui-corner-all" />
  </form>

Please are you

setTimeout( function() {

$( "#dialog-form" ).dialog({
    modal: true,
    draggable: false,
    height: 300,
    width: 500,
    open: function () {
      $('body').addClass('stop-scrolling');
    },
});

},4000);

var keeptrying = function(e) {
var addmust = $('#dialog-form #codein').val();

$("#addname").append("#dialog-form #codein");
}

Any help and answer is appreciated thanks

Body:
Here you go with the solution https://jsfiddle.net/g9m1pqmu/

setTimeout( function() {
    $( "#dialog-form" ).dialog({
        modal: true,
        draggable: false,
        height: 300,
        width: 500,
        open: function () {
            $('body').addClass('stop-scrolling');
        }
    });
},4000);

$('#codein').keypress(function() {
    $("#addname").html($('#codein').val());
});

I guess this is what you are looking for.


问:
On click of submit button I want to get an success alert and then clicking on OK I should get redirected to a new page for PHP
I am submitting data to the database. On successful submission, I want to display an alert stating the submission was successful and then clicking on OK I want to redirect to a new page displaying the data. I am doing this for PHP. I am not getting the success message I am being redirected to the display data page.</p>

```<code>if ($conn->query($sql) === TRUE) {
    //echo "New record created successfully";
    $message = "New record created successfully";
    echo "<script type='text/javascript'>alert('$message');</script>";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
header("Location:displaydata.php");
exit;
</code>```

答:
You can try this using ajax

for onclick button click

```<code><form id="form-search">
    <span><span class="style2">Enter you email here</span>:</span>
    <input name="email" type="email" id="email" required/>
    <input type="button" value="subscribe" class="submit" id="save"/>
</form>

$(document).on('click','#save',function(e) {
    var data = $("#form-search").serialize();
    $.ajax({
         data: data,
         type: "post",
         url: "yourinsertpage.php",
         dataType: "JSON",
         success: function(data){
              if(data.message == 'Success'){
                 alert('New record created successfully');
              }else{
                 alert('Failed to create new record');
              }
         }
    });
});
</code>```

your php file yourinsertpage.php

```<code><?php

    $jsonArray = array();
    if ($conn->query($sql) === TRUE) {
        $jsonArray['message'] = "Success";
    } else {
        $jsonArray['message'] = "Failed";
    }

    header('Content-Type: application/json');
    echo json_encode($jsonArray);

?>
</code>```

Body:
I am submitting data to the database. On successful submission, I want to display an alert stating the submission was successful and then clicking on OK I want to redirect to a new page displaying the data. I am doing this for PHP. I am not getting the success message I am being redirected to the display data page.

if ($conn->query($sql) === TRUE) {
    //echo "New record created successfully";
    $message = "New record created successfully";
    echo "";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}
header("Location:displaydata.php");
exit;

Body:
You can try this using ajax

for onclick button click

<form id="form-search">
    <span><span class="style2">Enter you email here</span>:</span>
    <input name="email" type="email" id="email" required/>
    <input type="button" value="subscribe" class="submit" id="save"/>
</form>

$(document).on('click','#save',function(e) {
    var data = $("#form-search").serialize();
    $.ajax({
         data: data,
         type: "post",
         url: "yourinsertpage.php",
         dataType: "JSON",
         success: function(data){
              if(data.message == 'Success'){
                 alert('New record created successfully');
              }else{
                 alert('Failed to create new record');
              }
         }
    });
});

your php file yourinsertpage.php

<?php

    $jsonArray = array();
    if ($conn->query($sql) === TRUE) {
        $jsonArray['message'] = "Success";
    } else {
        $jsonArray['message'] = "Failed";
    }

    header('Content-Type: application/json');
    echo json_encode($jsonArray);

?>


问:
Using Round function in yii2 query
I've a query to get mrp*rate from table productbatch upto 2 decimal point.
I've tried the following query Productbatch::find()->select('mrp, rate, round((mrp*rate),2) as  rateval')->asArray()->one();

When I use only mrp*rate it gives the result but there's 6 or 7 digits after decimal. Please let me know how can I get the result upto 2 decimal points.

example

If I don't use round and if mrp = 32 and rate = 24.64, the result of mrp*rate it gives - 788.47998046875..
If I use Round as shown in the code it doesn't give the result.
What I want is - 788.48.

Productbatch Model

```<code><?php

namespace frontend\modules\invoice\models;

use Yii;

/**
 * This is the model class for table "productbatch".
 *
 * @property integer $itemid
 * @property string $productname
 * @property string $batchno
 * @property string $mfgdate
 * @property string $expdate
 * @property double $mrp
 * @property double $rate
 *
 * @property Productnames $productname0
 */
class Productbatch extends \yii\db\ActiveRecord
{
    public $rateval;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'productbatch';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['batchno'], 'string'],
            [['mfgdate', 'expdate'], 'safe'],
            [['mrp', 'rate'], 'number'],
            [['productname'], 'string', 'max' => 25],
            [['productname'], 'exist', 'skipOnError' => true, 'targetClass' => Productnames::className(), 'targetAttribute' => ['productname' => 'productnames_productname']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'itemid' => 'Itemid',
            'productname' => 'Productname',
            'batchno' => 'Batchno',
            'mfgdate' => 'Mfgdate',
            'expdate' => 'Expdate',
            'mrp' => 'Mrp',
            'rate' => 'Rate',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProductname0()
    {
        return $this->hasOne(Productnames::className(), ['productnames_productname' => 'productname']);
    }

    public static function getBatchNo($cat_id)
    {
        $out = [];
        $data = Productbatch::find()
                ->where(['productname' => $cat_id])
                ->orDerBy([
                        'expdate'=>SORT_DESC,
                    ])
                ->limit(5)
                ->asArray()
                ->all();
        foreach ($data as $dat) {
            $out[] = ['id' => $dat['batchno'], 'name' => $dat['batchno']];
        }
        return $output = [
            'output' => $out,
            'selected' => ''
        ];
    }
    public static function getItemdetails($cat_id, $subcat_id)
    {
        $out = [];
        $data = Productbatch::find()
                ->where(['productname' => $cat_id])
                ->andWhere(['batchno' => $subcat_id])
                ->orDerBy([
                        'expdate'=>SORT_DESC,
                    ])
                ->limit(5)
                ->asArray()
                ->all();
        foreach ($data as $dat) {
            $out[] = ['id' => $dat['itemid'], 'name' => $dat['itemid']];
        }
        return $output = [
            'output' => $out,
            'selected' => ''
        ];
    }
    // public static function getItemdetails($cat_id, $subcat_id)
    // {
    //     $out = [];
    //     $data = Productbatch::find()
    //             ->where(['productname' => $cat_id])
    //             ->andWhere(['batchno' => $subcat_id])
    //             ->orDerBy([
    //                     'expdate'=>SORT_DESC,
    //                 ])
    //             ->limit(5)
    //             ->asArray()
    //             ->all();
    //     foreach ($data as $dat) {
    //         $out[] = ['id' => $dat['itemid'], 'name' => $dat['itemid']];
    //     }
    //     return $output = [
    //         'output' => $out,
    //         'selected' => ''
    //     ];
    // }
}
</code>```

Controller Action -

```<code>public function actionGetForItemid($prodname , $batchno)
    {
        $item = Productbatch::find()->joinWith(['productname0'])->joinWith(['productname0', 'productname0.hsncode'])->select('max(itemid) as itemid, expdate, mrp,rate, productname, batchno, round(rate*mrp,2) as rateval')->where(['productname'=>$prodname])->andWhere(['batchno'=>$batchno])->asArray()->one();
        echo Json::encode($item);
    }
</code>```

Javascript that is calling the controller action -

```<code><?php
/* start getting the itemid */
$script = <<< JS
function getItemID(item) {
    var index  = item.attr("id").replace(/[^0-9.]/g, "");
    var batch = product = 0;
    var id = item.attr("id");
    var myString = id.split("-").pop();

    if (myString == "productname") {
        fetch = index.concat("-batchno");
        product = item.val();
        batch = $("#productsales-"+fetch+"").val();
    } else {
       fetch = index.concat("-productname");
       batch = item.val();
       product = $("#productsales-"+fetch+"").val();
    }
    $.get('index.php?r=invoice/bills/get-for-itemid',{ prodname : product,batchno : batch}, function(data){
       alert(data);
       var data = $.parseJSON(data);
       var getItemid = data;
       itemID = "productsales-".concat(index).concat("-itemid");
       $("#"+itemID+"").val(getItemid["itemid"]);
       expDate = "productsales-".concat(index).concat("-expdate");
       $("#"+expDate+"").val(getItemid["expdate"]);
       mRP = "productsales-".concat(index).concat("-mrp");
       $("#"+mRP+"").val(getItemid["mrp"]);
       rATE = "productsales-".concat(index).concat("-rate");
       $("#"+rATE+"").val(getItemid["rateval"]);

   });
}
JS;
$this->registerJs($script, View::POS_END);
/* end getting the itemid */
?>
</code>```

Form fields that is being populated -

```<code><?= $form->field($modelsProductsales, "[{$i}]rate")->label(false)->textInput(['maxlength' => true,'class' => 'rate','placeholder' => 'Rate']) ?>
</code>```

答:
Be sure your Productbatch model has a publica var  rateval

```<code>class Productbatch extends \yii\db\ActiveRecord
{
    public $rateval
    ...
</code>```

and then you can refer to the rateval content in you views  using

```<code>   $model->rateval;
</code>```

OR do the fact you have the result not rounded  whet you use mrp*rate
a simple solution could be round in javascript

```<code>  Math.round(num * 100) / 100
</code>```

and in your case

```<code> $("#"+rATE+"").val( Math.round( getItemid["rateval"]*100)/100  );
</code>```

Title: Using Round function in yii2 query

Body:
I've a query to get mrp*rate from table productbatch upto 2 decimal point.
I've tried the following query Productbatch::find()->select('mrp, rate, round((mrp*rate),2) as  rateval')->asArray()->one();

When I use only mrp*rate it gives the result but there's 6 or 7 digits after decimal. Please let me know how can I get the result upto 2 decimal points.

example

If I don't use round and if mrp = 32 and rate = 24.64, the result of mrp*rate it gives - 788.47998046875..
If I use Round as shown in the code it doesn't give the result.
What I want is - 788.48.

Productbatch Model

<?php

namespace frontend\modules\invoice\models;

use Yii;

/**
 * This is the model class for table "productbatch".
 *
 * @property integer $itemid
 * @property string $productname
 * @property string $batchno
 * @property string $mfgdate
 * @property string $expdate
 * @property double $mrp
 * @property double $rate
 *
 * @property Productnames $productname0
 */
class Productbatch extends \yii\db\ActiveRecord
{
    public $rateval;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'productbatch';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['batchno'], 'string'],
            [['mfgdate', 'expdate'], 'safe'],
            [['mrp', 'rate'], 'number'],
            [['productname'], 'string', 'max' => 25],
            [['productname'], 'exist', 'skipOnError' => true, 'targetClass' => Productnames::className(), 'targetAttribute' => ['productname' => 'productnames_productname']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'itemid' => 'Itemid',
            'productname' => 'Productname',
            'batchno' => 'Batchno',
            'mfgdate' => 'Mfgdate',
            'expdate' => 'Expdate',
            'mrp' => 'Mrp',
            'rate' => 'Rate',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProductname0()
    {
        return $this->hasOne(Productnames::className(), ['productnames_productname' => 'productname']);
    }

    public static function getBatchNo($cat_id)
    {
        $out = [];
        $data = Productbatch::find()
                ->where(['productname' => $cat_id])
                ->orDerBy([
                        'expdate'=>SORT_DESC,
                    ])
                ->limit(5)
                ->asArray()
                ->all();
        foreach ($data as $dat) {
            $out[] = ['id' => $dat['batchno'], 'name' => $dat['batchno']];
        }
        return $output = [
            'output' => $out,
            'selected' => ''
        ];
    }
    public static function getItemdetails($cat_id, $subcat_id)
    {
        $out = [];
        $data = Productbatch::find()
                ->where(['productname' => $cat_id])
                ->andWhere(['batchno' => $subcat_id])
                ->orDerBy([
                        'expdate'=>SORT_DESC,
                    ])
                ->limit(5)
                ->asArray()
                ->all();
        foreach ($data as $dat) {
            $out[] = ['id' => $dat['itemid'], 'name' => $dat['itemid']];
        }
        return $output = [
            'output' => $out,
            'selected' => ''
        ];
    }
    // public static function getItemdetails($cat_id, $subcat_id)
    // {
    //     $out = [];
    //     $data = Productbatch::find()
    //             ->where(['productname' => $cat_id])
    //             ->andWhere(['batchno' => $subcat_id])
    //             ->orDerBy([
    //                     'expdate'=>SORT_DESC,
    //                 ])
    //             ->limit(5)
    //             ->asArray()
    //             ->all();
    //     foreach ($data as $dat) {
    //         $out[] = ['id' => $dat['itemid'], 'name' => $dat['itemid']];
    //     }
    //     return $output = [
    //         'output' => $out,
    //         'selected' => ''
    //     ];
    // }
}

Controller Action -

public function actionGetForItemid($prodname , $batchno)
    {
        $item = Productbatch::find()->joinWith(['productname0'])->joinWith(['productname0', 'productname0.hsncode'])->select('max(itemid) as itemid, expdate, mrp,rate, productname, batchno, round(rate*mrp,2) as rateval')->where(['productname'=>$prodname])->andWhere(['batchno'=>$batchno])->asArray()->one();
        echo Json::encode($item);
    }

Javascript that is calling the controller action -

<?php
/* start getting the itemid */
$script = <<< JS
function getItemID(item) {
    var index  = item.attr("id").replace(/[^0-9.]/g, "");
    var batch = product = 0;
    var id = item.attr("id");
    var myString = id.split("-").pop();

    if (myString == "productname") {
        fetch = index.concat("-batchno");
        product = item.val();
        batch = $("#productsales-"+fetch+"").val();
    } else {
       fetch = index.concat("-productname");
       batch = item.val();
       product = $("#productsales-"+fetch+"").val();
    }
    $.get('index.php?r=invoice/bills/get-for-itemid',{ prodname : product,batchno : batch}, function(data){
       alert(data);
       var data = $.parseJSON(data);
       var getItemid = data;
       itemID = "productsales-".concat(index).concat("-itemid");
       $("#"+itemID+"").val(getItemid["itemid"]);
       expDate = "productsales-".concat(index).concat("-expdate");
       $("#"+expDate+"").val(getItemid["expdate"]);
       mRP = "productsales-".concat(index).concat("-mrp");
       $("#"+mRP+"").val(getItemid["mrp"]);
       rATE = "productsales-".concat(index).concat("-rate");
       $("#"+rATE+"").val(getItemid["rateval"]);

   });
}
JS;
$this->registerJs($script, View::POS_END);
/* end getting the itemid */
?>

Form fields that is being populated -

<?= $form->field($modelsProductsales, "[{$i}]rate")->label(false)->textInput(['maxlength' => true,'class' => 'rate','placeholder' => 'Rate']) ?>

Body:
Be sure your Productbatch model has a publica var  rateval

class Productbatch extends \yii\db\ActiveRecord
{
    public $rateval
    ...

and then you can refer to the rateval content in you views  using

   $model->rateval;

OR do the fact you have the result not rounded  whet you use mrp*rate
a simple solution could be round in javascript

  Math.round(num * 100) / 100

and in your case

 $("#"+rATE+"").val( Math.round( getItemid["rateval"]*100)/100  );


问:
Pandas: Apply rolling function to compute new column value
I am trying to compute a new column Y on each row by checking the 9 previous rows and current row values of column X. Basically the new column Y value on each row will tell us the percentage on values of column X were greater than 1 for previous 10 records including the current record . Below is the code i am using but getting a different result than expected

[EDITED]

```<code>def count_pcnt(x):
 return ((np.sum(x > 1) / len(x)) * 100.0)

def run():
df = pd.DataFrame(
data={'X': ['8.12', '7.13', '-5.30', '3.21', '4.21', '3.14','8.65',
            '7.33', '-5.10', '3.01']
      })

df['Y'] = df['X'].rolling(window=10, min_periods=1).apply(lambda x:
          count_pcnt(x)).apply(int)
</code>```

Expected Result  [ EDITED ]

```<code>     X    Y(%)
0   8.12  100
1   7.13  100
2  -5.30  66.67
3   3.21  75
4   4.21  80
5   3.14  83.33
6   8.65  85.71
7   7.33  87.50
8  -5.10  77.77
9   3.01  80
</code>```

Actual

```<code>      X    Y
 0   8.12  100
 1   7.13  100
 2  -5.30  0
 3   3.21  0
 4   4.21  0
 5   3.14  0
 6   8.65  0
 7   7.33  0
 8  -5.10  0
 9   3.01  0
</code>```

UPDATE I used this option recommended below and it worked. Though there are other options i felt this is much cleaner

```<code>df['Y'] = df['X'].astype(float)
             .rolling(window=w, min_periods=1)
             .apply(lambda x: (x>1).mean()) * 100
</code>```

if you want to compute column values based on next 10 rows rather than previous 10 rows -  below is the solution (Thanks to jezrael who provided it)

```<code>df['Y'] = (df['X'].astype(float).iloc[::-1].rolling(window=10, min_periods=1).apply(lambda x: (x>1).mean()) * 100)[::-1]
</code>```

Body:
I am trying to compute a new column Y on each row by checking the 9 previous rows and current row values of column X. Basically the new column Y value on each row will tell us the percentage on values of column X were greater than 1 for previous 10 records including the current record . Below is the code i am using but getting a different result than expected

[EDITED]

def count_pcnt(x):
 return ((np.sum(x > 1) / len(x)) * 100.0)

def run():
df = pd.DataFrame(
data={'X': ['8.12', '7.13', '-5.30', '3.21', '4.21', '3.14','8.65',
            '7.33', '-5.10', '3.01']
      })

df['Y'] = df['X'].rolling(window=10, min_periods=1).apply(lambda x:
          count_pcnt(x)).apply(int)

Expected Result  [ EDITED ]

     X    Y(%)
0   8.12  100
1   7.13  100
2  -5.30  66.67
3   3.21  75
4   4.21  80
5   3.14  83.33
6   8.65  85.71
7   7.33  87.50
8  -5.10  77.77
9   3.01  80

Actual

      X    Y
 0   8.12  100
 1   7.13  100
 2  -5.30  0
 3   3.21  0
 4   4.21  0
 5   3.14  0
 6   8.65  0
 7   7.33  0
 8  -5.10  0
 9   3.01  0

UPDATE I used this option recommended below and it worked. Though there are other options i felt this is much cleaner

df['Y'] = df['X'].astype(float)
             .rolling(window=w, min_periods=1)
             .apply(lambda x: (x>1).mean()) * 100

if you want to compute column values based on next 10 rows rather than previous 10 rows -  below is the solution (Thanks to jezrael who provided it)

df['Y'] = (df['X'].astype(float).iloc[::-1].rolling(window=10, min_periods=1).apply(lambda x: (x>1).mean()) * 100)[::-1]

Body:
You can use:

first convert column X to float by astype

add parameter min_periods to Series.rolling

instead custom function use lambda with (x>1).mean() with same output

df = pd.DataFrame(
data={'X': ['8.12', '7.13', '-5.30', '3.21', '4.21', '3.14','8.65',
            '7.33', '-5.10', '3.01']
      })
w = 10
df['Y'] = df['X'].astype(float)
                 .rolling(window=w, min_periods=1)
                 .apply(lambda x: (x>1).mean()) * 100
print(df)

      X           Y
0  8.12  100.000000
1  7.13  100.000000
2 -5.30   66.666667
3  3.21   75.000000
4  4.21   80.000000
5  3.14   83.333333
6  8.65   85.714286
7  7.33   87.500000
8 -5.10   77.777778
9  3.01   80.000000

Solution with custom function:

def count_pcnt(x):
    return ((np.sum(x>1))/ len(x))*100.0

w = 10
df['Y'] = df['X'].astype(float).rolling(window=w, min_periods=1).apply(count_pcnt)
print(df)
       X           Y
0   8.12  100.000000
1   7.13  100.000000
2  -5.30   66.666667
3   3.21   75.000000
4   4.21   80.000000
5   3.14   83.333333
6   8.65   85.714286
7   7.33   87.500000
8  -5.10   77.777778
9   3.01   80.000000

EDIT:

Function can be changed by:

def count_pcnt(x):
    return ((x>1).sum() / len(x))*100.0

or:

def count_pcnt(x):
    return (x>1).mean()*100.0


问:
Python Updating Mayavi Using a Timer While Running Other Threads
Is it possible to create a Mayavi visualization that is updated on a timed bases rather than through Trait events?

I have a visualization that I need to update continually, but the data I am updating is coming from an external source (I.E. not an event from a user input from the graphical interface).

In the mean time, I need to be running a separate thread - so the Mayavi visualization can't control the main loop.

Can this be done? And if so How??

Any help would be very greatly appreciated.

Some dummy code for how I'm trying to tackle this is below:

```<code>import numpy

from mayavi.sources.array_source import ArraySource

from pyface.api import GUI
from mayavi.modules.api import Surface
from mayavi.api import Engine

import threading
import time

# Class runs a given function on a given thread at a given scan time
class TimedThread(threading.Thread):
    def __init__(self, thread, scan_time, funct, *funct_args):
        threading.Thread.__init__(self)

        # Thread for the function to operate in
        self.thread = thread

        # Defines the scan time the function is to be run at
        self.scan_time = scan_time

        # Function to be run
        self.run_function = funct

        # Function arguments
        self.funct_args = funct_args

    def run(self):
        while True:
            # Locks the relevant thread
            self.thread.acquire()

            # Begins timer for elapsed time calculation
            start_time = time.time()

            # Runs the function that was passed to the thread
            self.run_function(*self.funct_args)

            # Wakes up relevant threads to listen for the thread release
            self.thread.notify_all()

            # Releases thread
            self.thread.release()

            # Calculates the elapsed process time & sleeps for the remainder of the scan time
            end_time = time.time()
            elapsed_time = end_time - start_time
            sleep_time = self.scan_time - elapsed_time

            if sleep_time > 0:
                time.sleep(sleep_time)
            else:
                print 'Process time exceeds scan time'

# Function to update the visualisation
def update_visualisation(source):
    print("Updating Visualization...")

    # Pretend the data is being updated externally
    x = numpy.array([0, numpy.random.rand()])
    y = z = x
    data = [x, y, z]
    source.scalar_data = data
    GUI.invoke_later(source.update)

# Function to run the visualisation
def run_main():
    print 'Running Main Controller'

if __name__ == '__main__':
    c = threading.Condition()

    # Create a new Engine for Mayavi and start it
    engine = Engine()
    engine.start()

    # Create a new Scene
    engine.new_scene()

    # Create the data
    x = numpy.linspace(0, 10, 2)
    y = z = x
    data = [x, y, z]

    # Create a new Source, map the data to the source and add it to the Engine
    src = ArraySource()
    src.scalar_data = data
    engine.add_source(src)

    # Create a Module
    surf = Surface()

    # Add the Module to the Engine
    engine.add_module(surf)

    # Create timed thread classes
    visualisation_thread = TimedThread(c, 2.0, update_visualisation, src)
    main_thread = TimedThread(c, 1.0, run_main)

    # Start & join the threads
    main_thread.start()
    visualisation_thread.start()
    main_thread.join()
    visualisation_thread.join()
</code>```

答:
Found solution in the following link:
Animating a mayavi points3d plot

Solved by using the @mlab.animator to call the update function and using the yield command to release the animation to allow for user manipulation.

Solution below:

```<code>import numpy as np
import threading
import time

from mayavi import mlab
from mayavi.api import Engine

# Class runs a given function on a given thread at a given scan time
class SafeTimedThread(threading.Thread):
    def __init__(self, thread_condition, scan_time, funct, *funct_args):
        threading.Thread.__init__(self)

        # Thread condition for the function to operate with
        self.tc = thread_condition

        # Defines the scan time the function is to be run at
        self.scan_time = scan_time

        # Function to be run
        self.run_function = funct

        # Function arguments
        self.funct_args = funct_args

    def run(self):
        while True:
            # Locks the relevant thread
            self.tc.acquire()

            # Begins timer for elapsed time calculation
            start_time = time.time()

            # Runs the function that was passed to the thread
            self.run_function(*self.funct_args)

            # Wakes up relevant threads to listen for the thread release
            self.tc.notify_all()

            # Releases thread
            self.tc.release()

            # Calculates the elapsed process time & sleep for the remainder of the scan time
            end_time = time.time()
            elapsed_time = end_time - start_time
            sleep_time = self.scan_time - elapsed_time

            if sleep_time > 0:
                time.sleep(sleep_time)
            else:
                print 'Process time exceeds scan time'

# Function to run the main controller
def run_main():
    print 'Running Main Controller'

def init_vis():
    # Creates a new Engine, starts it and creates a new scene
    engine = Engine()
    engine.start()
    engine.new_scene()

    # Initialise Plot
    data = np.random.random((3, 2))
    x = data[0]
    y = data[1]
    z = data[2]

    drawing = mlab.plot3d(x, y, z, np.ones_like(x))

    return drawing

@mlab.animate(delay=500, ui=False)
def update_visualisation(drawing):
    while True:
        print ('Updating Visualisation')
        # Pretend to receive data from external source
        data = np.random.random((3, 2))
        x = data[0]
        y = data[1]
        z = data[2]

        drawing.mlab_source.set(x=x, y=y, z=z)
        yield

if __name__ == '__main__':
    # Create Condition for Safe Threading
    c = threading.Condition()

    # Create display window
    dwg = init_vis()

    # Create safe timed thread for main thread and start
    main_thread = SafeTimedThread(c, 1.0, run_main).start()

    # Update using mlab animator
    vis_thread = update_visualisation(dwg)

    mlab.show()
</code>```

Body:
Is it possible to create a Mayavi visualization that is updated on a timed bases rather than through Trait events?

I have a visualization that I need to update continually, but the data I am updating is coming from an external source (I.E. not an event from a user input from the graphical interface).

In the mean time, I need to be running a separate thread - so the Mayavi visualization can't control the main loop.

Can this be done? And if so How??

Any help would be very greatly appreciated.

Some dummy code for how I'm trying to tackle this is below:

import numpy

from mayavi.sources.array_source import ArraySource

from pyface.api import GUI
from mayavi.modules.api import Surface
from mayavi.api import Engine

import threading
import time

# Class runs a given function on a given thread at a given scan time
class TimedThread(threading.Thread):
    def __init__(self, thread, scan_time, funct, *funct_args):
        threading.Thread.__init__(self)

        # Thread for the function to operate in
        self.thread = thread

        # Defines the scan time the function is to be run at
        self.scan_time = scan_time

        # Function to be run
        self.run_function = funct

        # Function arguments
        self.funct_args = funct_args

    def run(self):
        while True:
            # Locks the relevant thread
            self.thread.acquire()

            # Begins timer for elapsed time calculation
            start_time = time.time()

            # Runs the function that was passed to the thread
            self.run_function(*self.funct_args)

            # Wakes up relevant threads to listen for the thread release
            self.thread.notify_all()

            # Releases thread
            self.thread.release()

            # Calculates the elapsed process time & sleeps for the remainder of the scan time
            end_time = time.time()
            elapsed_time = end_time - start_time
            sleep_time = self.scan_time - elapsed_time

            if sleep_time > 0:
                time.sleep(sleep_time)
            else:
                print 'Process time exceeds scan time'

# Function to update the visualisation
def update_visualisation(source):
    print("Updating Visualization...")

    # Pretend the data is being updated externally
    x = numpy.array([0, numpy.random.rand()])
    y = z = x
    data = [x, y, z]
    source.scalar_data = data
    GUI.invoke_later(source.update)

# Function to run the visualisation
def run_main():
    print 'Running Main Controller'

if __name__ == '__main__':
    c = threading.Condition()

    # Create a new Engine for Mayavi and start it
    engine = Engine()
    engine.start()

    # Create a new Scene
    engine.new_scene()

    # Create the data
    x = numpy.linspace(0, 10, 2)
    y = z = x
    data = [x, y, z]

    # Create a new Source, map the data to the source and add it to the Engine
    src = ArraySource()
    src.scalar_data = data
    engine.add_source(src)

    # Create a Module
    surf = Surface()

    # Add the Module to the Engine
    engine.add_module(surf)

    # Create timed thread classes
    visualisation_thread = TimedThread(c, 2.0, update_visualisation, src)
    main_thread = TimedThread(c, 1.0, run_main)

    # Start & join the threads
    main_thread.start()
    visualisation_thread.start()
    main_thread.join()
    visualisation_thread.join()

Body:
Found solution in the following link:
Animating a mayavi points3d plot

Solved by using the @mlab.animator to call the update function and using the yield command to release the animation to allow for user manipulation.

Solution below:

import numpy as np
import threading
import time

from mayavi import mlab
from mayavi.api import Engine

# Class runs a given function on a given thread at a given scan time
class SafeTimedThread(threading.Thread):
    def __init__(self, thread_condition, scan_time, funct, *funct_args):
        threading.Thread.__init__(self)

        # Thread condition for the function to operate with
        self.tc = thread_condition

        # Defines the scan time the function is to be run at
        self.scan_time = scan_time

        # Function to be run
        self.run_function = funct

        # Function arguments
        self.funct_args = funct_args

    def run(self):
        while True:
            # Locks the relevant thread
            self.tc.acquire()

            # Begins timer for elapsed time calculation
            start_time = time.time()

            # Runs the function that was passed to the thread
            self.run_function(*self.funct_args)

            # Wakes up relevant threads to listen for the thread release
            self.tc.notify_all()

            # Releases thread
            self.tc.release()

            # Calculates the elapsed process time & sleep for the remainder of the scan time
            end_time = time.time()
            elapsed_time = end_time - start_time
            sleep_time = self.scan_time - elapsed_time

            if sleep_time > 0:
                time.sleep(sleep_time)
            else:
                print 'Process time exceeds scan time'

# Function to run the main controller
def run_main():
    print 'Running Main Controller'

def init_vis():
    # Creates a new Engine, starts it and creates a new scene
    engine = Engine()
    engine.start()
    engine.new_scene()

    # Initialise Plot
    data = np.random.random((3, 2))
    x = data[0]
    y = data[1]
    z = data[2]

    drawing = mlab.plot3d(x, y, z, np.ones_like(x))

    return drawing

@mlab.animate(delay=500, ui=False)
def update_visualisation(drawing):
    while True:
        print ('Updating Visualisation')
        # Pretend to receive data from external source
        data = np.random.random((3, 2))
        x = data[0]
        y = data[1]
        z = data[2]

        drawing.mlab_source.set(x=x, y=y, z=z)
        yield

if __name__ == '__main__':
    # Create Condition for Safe Threading
    c = threading.Condition()

    # Create display window
    dwg = init_vis()

    # Create safe timed thread for main thread and start
    main_thread = SafeTimedThread(c, 1.0, run_main).start()

    # Update using mlab animator
    vis_thread = update_visualisation(dwg)

    mlab.show()


问:
C++ header file with default arguments in C program
I have a C++ library, with functions declared in a header file. My function declarations include default arguments.

I would like to use this library in Mathematica via the Wolfram Mathematica WSTP Template Compiler (wscc). This requires writing a C interface to my library. I have used this pattern

```<code>#ifdef __cplusplus
extern "C" {
#endif

double my_function(double x, double abs_error = 1E-3);

#ifdef __cplusplus
}
#endif
</code>```

to prevent name-mangling in my library (compiled with C++). But what about the default arguments? I don't think they're standard C. From Wolfram Mathematica WSTP Template Compiler (wscc), I find

error: expected ‘;’, ‘,’ or ‘)’ before ‘=’ token
                   double abs_error = 1E-3,

Do I have to make separate C and C++ declarations (essentially two header files)? Is this a common problem or is it related to my use of wscc? Perhaps wscc doesn't support this syntax, although it is usually acceptable?

答:
C does not support default arguments.

I'm therefore assuming you want to keep them for your C++ code, but you're okay with requiring C callers (in your case, Mathematica) to pass values for all arguments.

One possible approach is to define a macro which expands to the default value initializer in C++, but to nothing in C. It's not pretty, but it works:

```<code>#ifdef __cplusplus
#define DEFAULT_VALUE(x) = x
#else
#define DEFAULT_VALUE(x)
#endif

#ifdef __cplusplus
extern "C" {
#endif

void foo(int x DEFAULT_VALUE(42), void *y DEFAULT_VALUE(nullptr));

// In C, this becomes   void foo(int x, void *y);
// In C++, this becomes void foo(int x = 42, void *y = nullptr);

#ifdef __cplusplus
}
#endif
</code>```

Body:
I have a C++ library, with functions declared in a header file. My function declarations include default arguments.

I would like to use this library in Mathematica via the Wolfram Mathematica WSTP Template Compiler (wscc). This requires writing a C interface to my library. I have used this pattern

#ifdef __cplusplus
extern "C" {
#endif

double my_function(double x, double abs_error = 1E-3);

#ifdef __cplusplus
}
#endif

to prevent name-mangling in my library (compiled with C++). But what about the default arguments? I don't think they're standard C. From Wolfram Mathematica WSTP Template Compiler (wscc), I find

error: expected ‘;’, ‘,’ or ‘)’ before ‘=’ token
                   double abs_error = 1E-3,

Do I have to make separate C and C++ declarations (essentially two header files)? Is this a common problem or is it related to my use of wscc? Perhaps wscc doesn't support this syntax, although it is usually acceptable?

Body:
C does not support default arguments.

I'm therefore assuming you want to keep them for your C++ code, but you're okay with requiring C callers (in your case, Mathematica) to pass values for all arguments.

One possible approach is to define a macro which expands to the default value initializer in C++, but to nothing in C. It's not pretty, but it works:

#ifdef __cplusplus
#define DEFAULT_VALUE(x) = x
#else
#define DEFAULT_VALUE(x)
#endif

#ifdef __cplusplus
extern "C" {
#endif

void foo(int x DEFAULT_VALUE(42), void *y DEFAULT_VALUE(nullptr));

// In C, this becomes   void foo(int x, void *y);
// In C++, this becomes void foo(int x = 42, void *y = nullptr);

#ifdef __cplusplus
}
#endif


问:
C# process start focus issue

When I start a new process, it automatically gets the focus. how can I prevent it from getting the focus or instead get back the focus to my application?

here is the code I'm using:

```<code>string path = @"c:\temp\myprocess.exe";
ProcessStartInfo info = new ProcessStartInfo(path);
info.WorkingDirectory = path;
Process p = Process.Start(info);
</code>```

I just need the executed process not to get the focus.

Thank you very much,

Adi Barda

答: Maybe setting the WindowStyle property to Minimized can help.</p>

Title: C# process start focus issue

Body:
When I start a new process, it automatically gets the focus. how can I prevent it from getting the focus or instead get back the focus to my application?

here is the code I'm using:

string path = @"c:\temp\myprocess.exe";
ProcessStartInfo info = new ProcessStartInfo(path);
info.WorkingDirectory = path;
Process p = Process.Start(info);

I just need the executed process not to get the focus.

Thank you very much,

Adi Barda


问:
Rails 5 api only app with home page
I have generated a rails 5 api application. But I want my app with home page. For that I generated a home controller and added view file i respective views/home/index.html.erb

But when I tried accessing it I am getting below response

Started GET "/home/index" for 127.0.0.1 at 2016-07-14 11:14:03 +0530
  Processing by HomeController#index as HTML Completed 204 No Content in
  0ms

Started GET "/home/index.js" for 127.0.0.1 at 2016-07-14 11:14:20
  +0530 Processing by HomeController#index as JS Completed 204 No Content in 0ms

But I could not see index page content displayed on the web.

Kindly share your thoughts.

答: If all you need is just a static HTML page (with some simple css/js), i think another method is just to edit the index.html page under public folder.

Title: Rails 5 api only app with home page


问:
Colored Log output, not parsing '%highlight{...}{..}' in log4j.properties
I am trying to configure my log output using Log4j and a log4j.properties file, but I am having trouble setting up colored output based on log level.

It appears that the logging utilities simply do not parse the %highlight ... conversion command.

I can tell that I am on the right track with the configuration, as the other parts of the pattern are working correctly.

I am basing my current code off of this S/O answer: log4j 2 adding multiple colors to console appender

I am assuming it is something simple that I am not seeing, as I am rather new to this. Unfortunately the documentation is hard to piece together, or is meant for xml based configurations.

Thanks for any help in advance.

Some resources I have been looking through already:

http://logging.apache.org/log4j/1.2/manual.html

https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

http://saltnlight5.blogspot.com/2013/08/how-to-configure-slf4j-with-different.html

http://logging.apache.org/log4j/2.x/manual/layouts.html

Here are the relevant files/code:

log4j.properties:

```<code>log4j.rootLogger=TRACE, STDOUT
log4j.logger.deng=INFO
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%highlight{%d %-5p [%t] (%F:%L) - %m%n}{FATAL=red, ERROR=red, WARN=yellow bold, INFO=black, DEBUG=green bold, TRACE=blue}
</code>```

Gradle dependencies:

```<code>dependencies {
    // The production code uses the SLF4J logging API at compile time
    compile 'org.slf4j:slf4j-api:1.7.+'
    compile 'org.slf4j:slf4j-log4j12:1.7.+'
    testCompile 'junit:junit:4.12'
}
</code>```

Test to test logging:

```<code>@Test
public void testLogger(){
    LOGGER.info("Info level log");
    LOGGER.debug("Debug level log");
    LOGGER.warn("Warn level log");
    LOGGER.error("Error level log");
    LOGGER.trace("Trace level log");
}
</code>```

Output:

```<code>log4j:ERROR Unexpected char [h] at position 2 in conversion patterrn.
%highlight{2017-07-08 13:18:21,243 INFO  [main] (LongLinkedListTest.java:40) - Info level log
}{FATAL=red, ERROR=red, WARN=yellow bold, INFO=black, DEBUG=green bold, TRACE=blue}%highlight{2017-07-08 13:18:21,246 DEBUG [main] (LongLinkedListTest.java:41) - Debug level log
}{FATAL=red, ERROR=red, WARN=yellow bold, INFO=black, DEBUG=green bold, TRACE=blue}%highlight{2017-07-08 13:18:21,246 WARN  [main] (LongLinkedListTest.java:42) - Warn level log
}{FATAL=red, ERROR=red, WARN=yellow bold, INFO=black, DEBUG=green bold, TRACE=blue}%highlight{2017-07-08 13:18:21,246 ERROR [main] (LongLinkedListTest.java:43) - Error level log
}{FATAL=red, ERROR=red, WARN=yellow bold, INFO=black, DEBUG=green bold, TRACE=blue}%highlight{2017-07-08 13:18:21,246 TRACE [main] (LongLinkedListTest.java:44) - Trace level log
}{FATAL=red, ERROR=red, WARN=yellow bold, INFO=black, DEBUG=green bold, TRACE=blue}
Process finished with exit code 0
</code>```

Final results:

For posterity, I ended up with the following:

Gradle Dependencies:

```<code>dependencies {
    //logging dependencies
    compile 'org.apache.logging.log4j:log4j-slf4j-impl:2.+'
    compile 'org.apache.logging.log4j:log4j-api:2.+'
    compile 'org.apache.logging.log4j:log4j-core:2.+'
    compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2+'
    compile 'com.fasterxml.jackson.core:jackson-databind:2+'

    ...
}
</code>```

Once I updated dependencies, I was able to move to a yaml based configuration, and using the %highlight notation worked like a charm!

If anyone wishes to see the final configuration, it can be found here: https://github.com/Epic-Breakfast-Productions/OWAT/blob/master/implementations/java/src/main/resources/log4j2.yaml

答:
Is it possible that you're mixing up Log4j2 with log4j 1.x? The log4j:ERROR error is an legacy log4j 1.2 error message.

Please simplify matters by only using Log4j2 dependencies and using a Log4j2 configuration. The configuration file is called log4j2.xml by default.

Please remove the org.slf4j:slf4j-log4j12:1.7.+ dependency and instead use log4j-api-2.x, log4j-core-2.x and log4j-slf4j-impl-2.x.

Useful links:

Which jars

Console appender

PatternLayout with colors and highlighting

Configuration

Log4j 1.2 became End of Life in summer 2015. Let's upgrade! :-)

Body:
I am trying to configure my log output using Log4j and a log4j.properties file, but I am having trouble setting up colored output based on log level.

It appears that the logging utilities simply do not parse the %highlight ... conversion command.

I can tell that I am on the right track with the configuration, as the other parts of the pattern are working correctly.

I am basing my current code off of this S/O answer: log4j 2 adding multiple colors to console appender

I am assuming it is something simple that I am not seeing, as I am rather new to this. Unfortunately the documentation is hard to piece together, or is meant for xml based configurations.

Thanks for any help in advance.

Some resources I have been looking through already:

http://logging.apache.org/log4j/1.2/manual.html

https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

http://saltnlight5.blogspot.com/2013/08/how-to-configure-slf4j-with-different.html

http://logging.apache.org/log4j/2.x/manual/layouts.html

Here are the relevant files/code:

log4j.properties:

log4j.rootLogger=TRACE, STDOUT
log4j.logger.deng=INFO
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%highlight{%d %-5p [%t] (%F:%L) - %m%n}{FATAL=red, ERROR=red, WARN=yellow bold, INFO=black, DEBUG=green bold, TRACE=blue}

Gradle dependencies:

dependencies {
    // The production code uses the SLF4J logging API at compile time
    compile 'org.slf4j:slf4j-api:1.7.+'
    compile 'org.slf4j:slf4j-log4j12:1.7.+'
    testCompile 'junit:junit:4.12'
}

Test to test logging:

@Test
public void testLogger(){
    LOGGER.info("Info level log");
    LOGGER.debug("Debug level log");
    LOGGER.warn("Warn level log");
    LOGGER.error("Error level log");
    LOGGER.trace("Trace level log");
}

Output:

log4j:ERROR Unexpected char [h] at position 2 in conversion patterrn.
%highlight{2017-07-08 13:18:21,243 INFO  [main] (LongLinkedListTest.java:40) - Info level log
}{FATAL=red, ERROR=red, WARN=yellow bold, INFO=black, DEBUG=green bold, TRACE=blue}%highlight{2017-07-08 13:18:21,246 DEBUG [main] (LongLinkedListTest.java:41) - Debug level log
}{FATAL=red, ERROR=red, WARN=yellow bold, INFO=black, DEBUG=green bold, TRACE=blue}%highlight{2017-07-08 13:18:21,246 WARN  [main] (LongLinkedListTest.java:42) - Warn level log
}{FATAL=red, ERROR=red, WARN=yellow bold, INFO=black, DEBUG=green bold, TRACE=blue}%highlight{2017-07-08 13:18:21,246 ERROR [main] (LongLinkedListTest.java:43) - Error level log
}{FATAL=red, ERROR=red, WARN=yellow bold, INFO=black, DEBUG=green bold, TRACE=blue}%highlight{2017-07-08 13:18:21,246 TRACE [main] (LongLinkedListTest.java:44) - Trace level log
}{FATAL=red, ERROR=red, WARN=yellow bold, INFO=black, DEBUG=green bold, TRACE=blue}
Process finished with exit code 0

Final results:

For posterity, I ended up with the following:

Gradle Dependencies:

dependencies {
    //logging dependencies
    compile 'org.apache.logging.log4j:log4j-slf4j-impl:2.+'
    compile 'org.apache.logging.log4j:log4j-api:2.+'
    compile 'org.apache.logging.log4j:log4j-core:2.+'
    compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2+'
    compile 'com.fasterxml.jackson.core:jackson-databind:2+'

    ...
}

Once I updated dependencies, I was able to move to a yaml based configuration, and using the %highlight notation worked like a charm!

If anyone wishes to see the final configuration, it can be found here: https://github.com/Epic-Breakfast-Productions/OWAT/blob/master/implementations/java/src/main/resources/log4j2.yaml