问:
Google Calendar Push Notification Channel Creation
Dear Google Calendar Team,

We want to develop Push Notification for calendar.
I have gone through the article https://developers.google.com/google-apps/calendar/v3/push.

But I have couple of questions:-

Do we have calendar push notification in C also?

How to get notification channel id?

What does domain means in this context? Domain will be gmail.com always.

Can you share a sample which can show working push notification of calendar?

-Rahul

答:
Do we have calendar push notification in C also?

The Google Calendar API supports push notifcations you can use the Google Calendar api in any language that supports http post or http get.

How to get notification channel id?

From the documentation documentation

Register the domain of your receiving URL.

For example, if you plan to use https://example.com/notifications as your receiving URL, you need to register https://example.com.
Set up your receiving URL, or "Webhook" callback receiver.

This is an HTTPS server that handles the API notification messages that are triggered when a resource changes.

Set up a notification channel for each resource endpoint you want to watch.

A channel specifies routing information for notification messages. As part of the channel setup, you identify the specific URL where you want to receive notifications. Whenever a channel's resource changes, the Google Calendar API sends a notification message as a POST request to that URL.

Directly from the documentation

What does domain means in this context? Domain will be gmail.com always.

Domain will always be your domain you don't have control of gmail.com so cant get satisfaction to that.

Can you share a sample which can show working push notification of calendar?

The documentation page contains information on how to use push notifications.  this is not in C.  you will need to code your own implementation of this.


来源: stackexchange

问:
How to create and add custom httpHandler to existing IIS WebSite
I need to add a custom httpHandler to an existing IIS WebSite. I have a Windows Server 2012 R2 with IIS and in IIS i have a WebSite which runs an ASP.NET solution where i have no access to the sources. The ApplicationPool is configured to run with .Net 4.0 and in Integrated Mode.

We want to develop a custom httpHandler as .dll and register this within the WebSite under Handler Mappings. To do so we have created in Visual Studio 2015 a new Dynamic Linked Libary project with the following code:

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace MinimalStandaloneHttpHandler
{
    public class Class1 : IHttpHandler
    {
        public Class1()
        {

        }

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest Request = context.Request;
            HttpResponse Response = context.Response;
            // This handler is called whenever a file ending
            // in .sample is requested. A file with that extension
            // does not need to exist.

            context.Server.Transfer("http://www.google.com", false);
        }

        public bool IsReusable
        {
            // To enable pooling, return true here.
            // This keeps the handler in memory.
            get { return false; }
        }

    }
}
</code>```

We have compiled it and the went to IIS -> WebSite -> Handler Mappings -> Add Wildcard Script Map.

Here we added "*" as Request Path, the full path to the .dll and a friendly name. Under Handler Mappings -> My Handler -> Right click -> Request Restrictions -> Mapping -> Unchecked "Invoke handler only if request is mapped to:".

The handler is now listed under the enabled handlers. Now the web.config got modified:

```<code><configuration>
    <system.webServer>
        <handlers>
            <add name="asdasd" path="*" verb="*" modules="IsapiModule" scriptProcessor="C:\inetpub\wwwroot\WebSiteStaticTest\MinimalStandaloneHttpHandler.dll" resourceType="File" requireAccess="None" preCondition="bitness32" />
        </handlers>
    </system.webServer>
</configuration>
</code>```

But when we execute the page on the website the handler does not seem to work, cause we are not getting redirected to Google. What is wrong here?

答:
I see you have used * in the path which you want to respond to all requests. HTTPhandler is normally used as end point where you register to particular type of requests say *.mspx where all type of mspx requests(default.mspx ,home.mspx etc() comes to your handler for execution.From MSDN

An ASP.NET HTTP handler is the process (frequently referred to as the
  "endpoint") that runs in response to a request made to an ASP.NET Web
  application. The most common handler is an ASP.NET page handler that
  processes .aspx files.

What you really need is an HTTPModule which will hook into every request and do a response.

An HTTP module is an assembly that is called on every request that is
  made to your application.

So look into this ,here's a sample implementation.

```<code>using System;
using System.Web;
public class HelloWorldModule : IHttpModule
{
    public HelloWorldModule()
    {
    }

    public String ModuleName
    {
        get { return "HelloWorldModule"; }
    }

    // In the Init function, register for HttpApplication
    // events by adding your handlers.
    public void Init(HttpApplication application)
    {
        application.BeginRequest +=
            (new EventHandler(this.Application_BeginRequest));

    }

    private void Application_BeginRequest(Object source,
         EventArgs e)
    {
    // Create HttpApplication and HttpContext objects to access
    // request and response properties.
        HttpApplication application = (HttpApplication)source;
        HttpContext context = application.Context;
        context.Response.Redirect("http://www.google.com", false);
    }

    public void Dispose() { }
}
</code>```

And register the module like this

```<code><configuration>
<system.webServer><modules><add name="HelloWorldModule" type="HelloWorldModule"/></modules></system.webServer>
</configuration>
</code>```

You can also add a wildcard handler (like you did) but there are many other handlers in asp.net which can interfere the request before your handler get's it.Check this ,this

Please note that you used Server.Transfer in your code to transfer request to goole.com,which is not possible.server.Transfer can only used to transfer request on the same request context,not to another website or domain

ContentLicense: CC BY-SA 3.0

Body:
I need to add a custom httpHandler to an existing IIS WebSite. I have a Windows Server 2012 R2 with IIS and in IIS i have a WebSite which runs an ASP.NET solution where i have no access to the sources. The ApplicationPool is configured to run with .Net 4.0 and in Integrated Mode.

We want to develop a custom httpHandler as .dll and register this within the WebSite under Handler Mappings. To do so we have created in Visual Studio 2015 a new Dynamic Linked Libary project with the following code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace MinimalStandaloneHttpHandler
{
    public class Class1 : IHttpHandler
    {
        public Class1()
        {

        }

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest Request = context.Request;
            HttpResponse Response = context.Response;
            // This handler is called whenever a file ending
            // in .sample is requested. A file with that extension
            // does not need to exist.

            context.Server.Transfer("http://www.google.com", false);
        }

        public bool IsReusable
        {
            // To enable pooling, return true here.
            // This keeps the handler in memory.
            get { return false; }
        }

    }
}

We have compiled it and the went to IIS -> WebSite -> Handler Mappings -> Add Wildcard Script Map.

Here we added "*" as Request Path, the full path to the .dll and a friendly name. Under Handler Mappings -> My Handler -> Right click -> Request Restrictions -> Mapping -> Unchecked "Invoke handler only if request is mapped to:".

The handler is now listed under the enabled handlers. Now the web.config got modified:

<configuration>
    <system.webServer>
        <handlers>
            <add name="asdasd" path="*" verb="*" modules="IsapiModule" scriptProcessor="C:\inetpub\wwwroot\WebSiteStaticTest\MinimalStandaloneHttpHandler.dll" resourceType="File" requireAccess="None" preCondition="bitness32" />
        </handlers>
    </system.webServer>
</configuration>

But when we execute the page on the website the handler does not seem to work, cause we are not getting redirected to Google. What is wrong here?

Body:
I see you have used * in the path which you want to respond to all requests. HTTPhandler is normally used as end point where you register to particular type of requests say *.mspx where all type of mspx requests(default.mspx ,home.mspx etc() comes to your handler for execution.From MSDN

An ASP.NET HTTP handler is the process (frequently referred to as the
  "endpoint") that runs in response to a request made to an ASP.NET Web
  application. The most common handler is an ASP.NET page handler that
  processes .aspx files.

What you really need is an HTTPModule which will hook into every request and do a response.

An HTTP module is an assembly that is called on every request that is
  made to your application.

So look into this ,here's a sample implementation.

using System;
using System.Web;
public class HelloWorldModule : IHttpModule
{
    public HelloWorldModule()
    {
    }

    public String ModuleName
    {
        get { return "HelloWorldModule"; }
    }

    // In the Init function, register for HttpApplication
    // events by adding your handlers.
    public void Init(HttpApplication application)
    {
        application.BeginRequest +=
            (new EventHandler(this.Application_BeginRequest));

    }

    private void Application_BeginRequest(Object source,
         EventArgs e)
    {
    // Create HttpApplication and HttpContext objects to access
    // request and response properties.
        HttpApplication application = (HttpApplication)source;
        HttpContext context = application.Context;
        context.Response.Redirect("http://www.google.com", false);
    }

    public void Dispose() { }
}

And register the module like this

<configuration>
<system.webServer><modules><add name="HelloWorldModule" type="HelloWorldModule"/></modules></system.webServer>
</configuration>

You can also add a wildcard handler (like you did) but there are many other handlers in asp.net which can interfere the request before your handler get's it.Check this ,this

Please note that you used Server.Transfer in your code to transfer request to goole.com,which is not possible.server.Transfer can only used to transfer request on the same request context,not to another website or domain


问:
Element removing while collection iterating
I'm wondering what is really going on behind the scene when I'm executing the following peace of code:

```<code>    List<Object> list = new ArrayList<Object>();
    fillTheList(); // Filling a list with 10 objects
    int count = 0;
    for (Object o : list) {
        count++;
        if (count == 5) {
            list.remove(count);
        }
        o.toString();
     }
</code>```

Once element is removed I'm getting ConcurrentModificationException exception.

I don't understand why after one of elements removing it is impossible just to take the next one available in the collection and proceed with a cycle.

答:
Basically you're not allowed to refer to the collection (list in this case) inside the foreach loop.

Try this instead:

```<code>List<Object> list = new ArrayList<Object>();
fillTheList(); // Filling a list with 10 objects
int count = 0;
ListIterator<Object> it = list.listIterator();
while (it.hasNext()) {
    Object o = it.next();
    count++;
    if (count == 5) {
        it.remove();
    }
    o.toString();
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm wondering what is really going on behind the scene when I'm executing the following peace of code:

    List<Object> list = new ArrayList<Object>();
    fillTheList(); // Filling a list with 10 objects
    int count = 0;
    for (Object o : list) {
        count++;
        if (count == 5) {
            list.remove(count);
        }
        o.toString();
     }

Once element is removed I'm getting ConcurrentModificationException exception.

I don't understand why after one of elements removing it is impossible just to take the next one available in the collection and proceed with a cycle.

Body:
Basically you're not allowed to refer to the collection (list in this case) inside the foreach loop.

Try this instead:

List<Object> list = new ArrayList<Object>();
fillTheList(); // Filling a list with 10 objects
int count = 0;
ListIterator<Object> it = list.listIterator();
while (it.hasNext()) {
    Object o = it.next();
    count++;
    if (count == 5) {
        it.remove();
    }
    o.toString();
}


问:
Java if else with nested loop
I am having some problem with my java assignment and currently am stuck at the nested if else statement.I am actually trying to get an input age from the user and store in as a variable.After executing my code i am getting error when i run the program.Am i doing this correctly or is there some other way to program this?

Error message that i got

```
    Enter your selection:
    1
    You have selected No.1
    Please enter your age**Exception in thread "main"
    java.lang.IllegalStateException: Scanner closed
    at java.util.Scanner.ensureOpen(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Assignment.main(Assignment.java:48)**
```

```<code>public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println(
       "1. Add player" + "\n" +
       "2.Display transaction" + "\n" +
       "3.Begin the ride");
    System.out.println("");
    System.out.println("Enter your selection: ");
    char selection = sc.findInLine(".").charAt(0);
    sc.close();
    switch(selection)  {
    case '1' :
        System.out.println("You have selected No.1");
        break;
    case '2' :
        System.out.println("You have selected No.2" );
        break;
    case '3' :
        System.out.println("You have selected No.3" );
        break;
    default:
        System.out.println("Please make a selection");
        break;
   }
   if (selection=='1') {
        int age=0;
        System.out.print("Please enter your age");
        age = sc.nextInt();
        while (age<100) {
            age+=age;
        }
    }
    else if (selection=='2') {
        System.out.println("Display daily transaction");
    }
    else if (selection=='3') {
        System.out.println("Begin the ride");
    }
    else {
        System.out.println("Please enter a valid input");
    }
}
</code>```

答:
The exception is pretty clear on the problem: java.lang.IllegalStateException: Scanner closed

Before your code enters the switch, you're closing the scanner with sc.close();. But later on you're trying to read from it again:

```<code>if (selection=='1') {
    int age=0;
    System.out.print("Please enter your age");
    age = sc.nextInt();  // <---- Here
    while (age<100) {
        age+=age;
    }
}
</code>```

But this will fail if the scanner is already closed. To solve this, you can simply put the line sc.close() to the end of your main.

As an alternative you could wrap everything into a try-with-resources block, so that you don't have to care about closing the scanner anymore because it will be closed automatically after leaving the block.

Title: Java if else with nested loop

Body:
I am having some problem with my java assignment and currently am stuck at the nested if else statement.I am actually trying to get an input age from the user and store in as a variable.After executing my code i am getting error when i run the program.Am i doing this correctly or is there some other way to program this?

Error message that i got

    Enter your selection:
    1
    You have selected No.1
    Please enter your age**Exception in thread "main"
    java.lang.IllegalStateException: Scanner closed
    at java.util.Scanner.ensureOpen(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Assignment.main(Assignment.java:48)**

public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println(
       "1. Add player" + "\n" +
       "2.Display transaction" + "\n" +
       "3.Begin the ride");
    System.out.println("");
    System.out.println("Enter your selection: ");
    char selection = sc.findInLine(".").charAt(0);
    sc.close();
    switch(selection)  {
    case '1' :
        System.out.println("You have selected No.1");
        break;
    case '2' :
        System.out.println("You have selected No.2" );
        break;
    case '3' :
        System.out.println("You have selected No.3" );
        break;
    default:
        System.out.println("Please make a selection");
        break;
   }
   if (selection=='1') {
        int age=0;
        System.out.print("Please enter your age");
        age = sc.nextInt();
        while (age<100) {
            age+=age;
        }
    }
    else if (selection=='2') {
        System.out.println("Display daily transaction");
    }
    else if (selection=='3') {
        System.out.println("Begin the ride");
    }
    else {
        System.out.println("Please enter a valid input");
    }
}

Body:
The exception is pretty clear on the problem: java.lang.IllegalStateException: Scanner closed

Before your code enters the switch, you're closing the scanner with sc.close();. But later on you're trying to read from it again:

if (selection=='1') {
    int age=0;
    System.out.print("Please enter your age");
    age = sc.nextInt();  // <---- Here
    while (age<100) {
        age+=age;
    }
}

But this will fail if the scanner is already closed. To solve this, you can simply put the line sc.close() to the end of your main.

As an alternative you could wrap everything into a try-with-resources block, so that you don't have to care about closing the scanner anymore because it will be closed automatically after leaving the block.


问:
Ansible module to attach an IAM role to existing EC2 instances
I am trying to attach an IAM role to multiple EC2 instances based on tags. Is there a module already available which I can use. I have been searching for a bit but couldn't find anything specific.

答:
Attaching an IAM role to existing EC2 instances is a relatively new feature (announced in Feb 2017). There is no support for that in Ansible currently. If you AWS CLI 1.11.46 or higher installed, then you can use shell module to invoke the AWS CLI and achieve desired result.

See: New! Attach an AWS IAM Role to an Existing Amazon EC2 Instance by Using the AWS CLI


问:
Why is there a little padding at bottom of my UITableView?
UPDATE 1: I have confirmed that this is NOT the footer.

Here is what it looks like. Notice the small space below the last cell. Also shown in the picture, the scroll IS at the proper spot:

Here are the settings of the view controller:

答: Try to set adjust scroll view insets to true.


问:
how to create a landing page for the first time visitors only in PHP
I'm creating a website which I realized is lacking a permanent option to choose the city, so I want index.php to check if a cookie is available and if it is show the normal index with the defined cookie variable, if not show the page where you choose the city and store it in the cookie, the question is, how to set that switch that shows one of two pages?</p>

答:
Just simple if cookie value and store cookie</p>

```<code>if (isset($_POST['city'])) {
    // store cookie
    setcookie('city', $_POST['city'], time()+60*60*24*30);
    $_COOKIE['city'] = $_POST['city']; // or do redirect on this page
}

if (isset($_COOKIE['city'])) {
     // show normal page
} else {
     // show choose city page
}
</code>```

Body:
Just simple if cookie value and store cookie

if (isset($_POST['city'])) {
    // store cookie
    setcookie('city', $_POST['city'], time()+60*60*24*30);
    $_COOKIE['city'] = $_POST['city']; // or do redirect on this page
}

if (isset($_COOKIE['city'])) {
     // show normal page
} else {
     // show choose city page
}


问:
How to prevent more than one click on an Anchor tag button
I have an anchor tag (namely Cancel button) with a class attribute and href attribute in a jsp file .

I have written an onclick event for the class attribute in a seperate js file. So when the button is clicked, the onclick event executes and then takes to the href link.

When the button is clicked more than once it takes me to an empty page or an error page.

I want to prevent more than one click on the button.

I have tried using event.preventdefault() function inside my onclick() function but the href link is not working if I do that.
Any other way?

My JS code:

```<code>$('.cancel-btn').on('click',function(evt){
            //evt.preventDefault();
           //My Code

        });
</code>```

答:
jQuery one() method will perform click event only once:

$('.cancel-btn').one('click',function(evt){
  // evt.preventDefault();
  // code here
});
```
<p>Also possible using jQuery <code>on()</code> method that may be more useful when the event should be removed conditionally:</p>
<pre class="lang-js prettyprint-override"><code>let count = 0; // or may be a boolean flag
$('.cancel-btn').on('click', function(evt){
  if (count == 0) {
    count++;
    // code here
  } else {
    return false;
    // or evt.preventDefault();
  }
});
</code>```

Or like this:

$('.cancel-btn').on('click', function(evt) {
  // code here
  // then remove the event handler.
  $(this).off('click');
});
```

Body:
I have an anchor tag (namely Cancel button) with a class attribute and href attribute in a jsp file .

I have written an onclick event for the class attribute in a seperate js file. So when the button is clicked, the onclick event executes and then takes to the href link.

When the button is clicked more than once it takes me to an empty page or an error page.

I want to prevent more than one click on the button.

I have tried using event.preventdefault() function inside my onclick() function but the href link is not working if I do that.
Any other way?

My JS code:

$('.cancel-btn').on('click',function(evt){
            //evt.preventDefault();
           //My Code

        });

Body:
jQuery one() method will perform click event only once:

$('.cancel-btn').one('click',function(evt){
  // evt.preventDefault();
  // code here
});

Also possible using jQuery on() method that may be more useful when the event should be removed conditionally:

let count = 0; // or may be a boolean flag
$('.cancel-btn').on('click', function(evt){
  if (count == 0) {
    count++;
    // code here
  } else {
    return false;
    // or evt.preventDefault();
  }
});

Or like this:

$('.cancel-btn').on('click', function(evt) {
  // code here
  // then remove the event handler.
  $(this).off('click');
});

ContentLicense: CC BY-SA 4.0


问:
How To Go back to previous version of Ionic
I had created an Ionic project ago. Now my Ionic is updated. I want to go back to old version to make some changes to the project. It is showing error.

This is the version of my ionic project:

This is the error I get when installing ionic:

答:
"ionic-bower" is not a NPM package. You cannot use npm to install it using the npm command line, or through the package.json.

"ionic-bower" is a bower package.  You can install it using bower.  After installing the bower package manager, try something like from your command line:

```<code>bower install driftyco/ionic-bower#v1.3.3
</code>```

After downloading Ionic with bower, you'll probably have a bower_components folder created in the directory you ran the command under. And in that directory, there will be an Ionic directory. That old version of Ionic is just a JS+CSS library.  Not the Ionic-CLI.

If you want to download old(er) version of Ionic using NPM, you can run this command to get a list of old versions.

```<code>npm view ionic versions --json
</code>```

You would have to know what version of Ionic you want.  But if an old version of Ionic references an old version of another dependency, you simply may not able to install that old version of Ionic. You can attempt to install any of the old(er) versions with this command:

```<code>npm install -g ionic@2.0.0
</code>```

Replacing 2.0.0 is whatever version you need.

Seriously consider using a new version of Ionic. You'll be better off.

That's all the help I can give you. Hope this helps.

Body:
"ionic-bower" is not a NPM package. You cannot use npm to install it using the npm command line, or through the package.json.

"ionic-bower" is a bower package.  You can install it using bower.  After installing the bower package manager, try something like from your command line:

bower install driftyco/ionic-bower#v1.3.3

After downloading Ionic with bower, you'll probably have a bower_components folder created in the directory you ran the command under. And in that directory, there will be an Ionic directory. That old version of Ionic is just a JS+CSS library.  Not the Ionic-CLI.

If you want to download old(er) version of Ionic using NPM, you can run this command to get a list of old versions.

npm view ionic versions --json

You would have to know what version of Ionic you want.  But if an old version of Ionic references an old version of another dependency, you simply may not able to install that old version of Ionic. You can attempt to install any of the old(er) versions with this command:

npm install -g ionic@2.0.0

Replacing 2.0.0 is whatever version you need.

Seriously consider using a new version of Ionic. You'll be better off.

That's all the help I can give you. Hope this helps.


问:
casting to (id<protocol>) to guarantee a property is there
if i have a number of classes with something like

```<code>@property (nonatomic, retain) NSString* myString;
</code>```

and want to access that property in a object that is one of these classes (but don't know which so it is type id), i obviously get "request for member 'myString' in something not a structure or union" error.

so if each of these classes conforms to :

```<code>@protocol myProtocol <NSObject>

@required

@property (nonatomic, retain) NSString* myString;

@end
</code>```

then i cast like this to get the property:

```<code>(id<myProtocol>)anObject.myString
</code>```

why doesn't this work? i still get the same error.

答:
In this case I prefer the messages-sending notation over the dot-notation, as it shows clearly, when the cast will happen:

These lines are equal:

```<code>[(id<MyProtocol>)anObject myString]
((id<MyProtocol>)anObject).myString
</code>```

And these are:

```<code>(id<MyProtocol>)[anObject myString]
(id<MyProtocol>)anObject.myString
</code>```

Body:
if i have a number of classes with something like

@property (nonatomic, retain) NSString* myString;

and want to access that property in a object that is one of these classes (but don't know which so it is type id), i obviously get "request for member 'myString' in something not a structure or union" error.

so if each of these classes conforms to :

@protocol myProtocol <NSObject>

@required

@property (nonatomic, retain) NSString* myString;

@end

then i cast like this to get the property:

(id<myProtocol>)anObject.myString

why doesn't this work? i still get the same error.

Body:
In this case I prefer the messages-sending notation over the dot-notation, as it shows clearly, when the cast will happen:

These lines are equal:

[(id<MyProtocol>)anObject myString]
((id<MyProtocol>)anObject).myString

And these are:

(id<MyProtocol>)[anObject myString]
(id<MyProtocol>)anObject.myString


问:
Storing functions in array. Is it a good practice?
```<code>var sing = function(name) {
    console.log(name + " is SINGING");
}

var cry = function(name) {
    console.log(name + " is CRYING");
}

var list = [sing, cry];

for(var func of list) {
    func('foo');
}
</code>```

This is exactly what I want in my code. But I am not sure if its a good practice.

答:
```<code>var functionName = function(name, action) {
console.log(name + " is "+ action );
}
functionName("Aditya", "Programing");
</code>```

Aditya,  I think you should choose this format. It is always good practice to keep a single function for similar kind of tasks to perform.

Body:
var sing = function(name) {
    console.log(name + " is SINGING");
}

var cry = function(name) {
    console.log(name + " is CRYING");
}

var list = [sing, cry];

for(var func of list) {
    func('foo');
}

This is exactly what I want in my code. But I am not sure if its a good practice.

Body:
var functionName = function(name, action) {
console.log(name + " is "+ action );
}
functionName("Aditya", "Programing");

Aditya,  I think you should choose this format. It is always good practice to keep a single function for similar kind of tasks to perform.


问:
Get nullpointerexception while inflating in custom adapter of RecyclerView
This is onCreateViewHolder of my adapter :

```<code>    @Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    try
    {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.faviorate_video_item, parent, false);
        return new ViewHolder(v);
    }
    catch (Exception e)
    {
        return  null ;
    }

}
</code>```

and this line throw NullPointException :

```<code>    LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.faviorate_video_item, parent, false);
</code>```

I debugged function but nothing was null  , so I dont understand what causes problem ?

答:
Please remove try block. like below</p>

```<code>@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.faviorate_video_item, parent, false);
        return new ViewHolder(v);

}
</code>```

Body:
This is onCreateViewHolder of my adapter :

    @Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    try
    {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.faviorate_video_item, parent, false);
        return new ViewHolder(v);
    }
    catch (Exception e)
    {
        return  null ;
    }

}

and this line throw NullPointException :

    LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.faviorate_video_item, parent, false);

I debugged function but nothing was null  , so I dont understand what causes problem ?

Body:
Please remove try block. like below

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.faviorate_video_item, parent, false);
        return new ViewHolder(v);

}


问:
How to return multiple values within a group of rows.
I have tried to use Max(), subqueries, and joins, but my knowledge is limited enough that I am not sure how to organize them. I was willing to just use several nested select statements, knowing it could be resource intensive, but I can't get it to work.

I need to return any nulls, as well as the highest ConfigID for each Location.

```<code>TABLE
ID     Location     ConfigID
1      AA           NULL
2      AA           2
3      AA           1
4      BB           5
5      BB           4
6      BB           3
7      CC           NULL
8      CC           6
</code>```

I want to see the results:

```<code>ID     Location     ConfigID
1      AA           NULL
2      AA           2
4      BB           5
7      CC           NULL
8      CC           6
</code>```

I have tried:

```<code>select ID, Location, ConfigID
from Table
where ConfigID is null
      or configID = (select ConfigID
                     from table
                     where Location in (select distinct Location
                                        from Table
                                        order by ConfigID desc
                                        )
                     )
</code>```

SQL server didn't like that because I cannot have an order by in a subquery unless Top is used. Now that I am looking at it again, I don't think that the order by is even within the correct subquery. It was as close as I could get. I was hopeful when I saw Select Max from each subset, but that was a dead-end, I think. Also, I don't believe that a self-join will work because the data I would self-join on is all in one column.

答:
```<code>-- ID     Location     ConfigID

WITH CTE_TMP (ID, LOCATION, CONFIGID)
AS
(
SELECT 1 ID, 'AA' LOCATION, NULL CONFIGID
UNION
SELECT 2, 'AA', 2
UNION
SELECT 3, 'AA', 1
UNION
SELECT 4, 'BB', 5
UNION
SELECT 5, 'BB', 4
UNION
SELECT 6, 'BB', 3
UNION
SELECT 7, 'CC', NULL
UNION
SELECT 8, 'CC', 6
)
SELECT DISTINCT ID, LOCATION, CONFIGID FROM CTE_TMP WHERE CONFIGID IS NULL
UNION
SELECT A.ID, A.LOCATION, B.CONFIGID
FROM CTE_TMP A
  JOIN (SELECT LOCATION, MAX(CONFIGID) CONFIGID FROM CTE_TMP
       GROUP BY LOCATION) B ON A.LOCATION = B.LOCATION AND A.CONFIGID = B.CONFIGID
</code>```

Body:
I have tried to use Max(), subqueries, and joins, but my knowledge is limited enough that I am not sure how to organize them. I was willing to just use several nested select statements, knowing it could be resource intensive, but I can't get it to work.

I need to return any nulls, as well as the highest ConfigID for each Location.

TABLE
ID     Location     ConfigID
1      AA           NULL
2      AA           2
3      AA           1
4      BB           5
5      BB           4
6      BB           3
7      CC           NULL
8      CC           6

I want to see the results:

ID     Location     ConfigID
1      AA           NULL
2      AA           2
4      BB           5
7      CC           NULL
8      CC           6

I have tried:

select ID, Location, ConfigID
from Table
where ConfigID is null
      or configID = (select ConfigID
                     from table
                     where Location in (select distinct Location
                                        from Table
                                        order by ConfigID desc
                                        )
                     )

SQL server didn't like that because I cannot have an order by in a subquery unless Top is used. Now that I am looking at it again, I don't think that the order by is even within the correct subquery. It was as close as I could get. I was hopeful when I saw Select Max from each subset, but that was a dead-end, I think. Also, I don't believe that a self-join will work because the data I would self-join on is all in one column.


问:
How to inject a service to the main controller in angularjs?
I was able to inject AuthDetails service to other components of my app, but I am having trouble injecting AuthDetails service to my main controller in the app, I have tried following but it does not work. It says: Uncaught ReferenceError: AuthDetails is not defined

```<code>MPlayApp.controller('MainCtrl','AuthDetails', [AuthDetails,
function MainCtrl(AuthDetails) {
    var subscription = AuthDetails.subscribe(function onNext(d) {
        console.log(d);
        if(d.success){
            this.loggedIn = true;
        }
    });
}]);
</code>```

I have added the service to app as follows

```<code>var MPlayApp = angular.module('MPlayApp', [
// ...which depends on the MPlayApp module
'player',
'core',
'userMenu',
'home',
'songUpload',
'loginSignUp',
'details',
'angularSoundManager',
'angularFileUpload',
'ngAnimate',
'rx',
'ui.router',
'core.auth'
]);
</code>```

AuthDetails service is under core.auth module

答:
The syntax is wrong. It should be

```<code>MPlayApp.controller('MainCtrl', ['AuthDetails', function MainCtrl(AuthDetails) {
</code>```

Or better, use ng-annotate, and let it generate this ugly, error-prone syntax for you during the build, from the basic, intuitive syntax:

```<code>MPlayApp.controller('MainCtrl', function MainCtrl(AuthDetails) {
</code>```

Body:
I was able to inject AuthDetails service to other components of my app, but I am having trouble injecting AuthDetails service to my main controller in the app, I have tried following but it does not work. It says: Uncaught ReferenceError: AuthDetails is not defined

MPlayApp.controller('MainCtrl','AuthDetails', [AuthDetails,
function MainCtrl(AuthDetails) {
    var subscription = AuthDetails.subscribe(function onNext(d) {
        console.log(d);
        if(d.success){
            this.loggedIn = true;
        }
    });
}]);

I have added the service to app as follows

var MPlayApp = angular.module('MPlayApp', [
// ...which depends on the MPlayApp module
'player',
'core',
'userMenu',
'home',
'songUpload',
'loginSignUp',
'details',
'angularSoundManager',
'angularFileUpload',
'ngAnimate',
'rx',
'ui.router',
'core.auth'
]);

AuthDetails service is under core.auth module

Body:
The syntax is wrong. It should be

MPlayApp.controller('MainCtrl', ['AuthDetails', function MainCtrl(AuthDetails) {

Or better, use ng-annotate, and let it generate this ugly, error-prone syntax for you during the build, from the basic, intuitive syntax:

MPlayApp.controller('MainCtrl', function MainCtrl(AuthDetails) {


问:
Padding not visible inside div block?
Please check the jsFiddle link and tell why padding is not visible inside div container?

body {
  background-color: #B8C4BB;
}

.container {
  text-align: center;
}

.section_two {
  border: 2px solid red;
  padding: 10 px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="section">
    Change the value of the color property to see how it changes the text color of this element.
  </div>
  <div class="section_two">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt, alias, aliquid fugiat dolorem repudiandae quidem. Molestiae illum pariatur officia voluptate cumque. Necessitatibus earum consequuntur explicabo minus ratione mollitia illum nam.
  </div>
</div></code>```

答:
It is not working because you have put a space between 10 and px. It should be like following code.</p>

```<code>.section_two {
   border: 2px solid red;
   padding: 50px;
}
</code>```

Title: Padding not visible inside div block?

Body:
Please check the jsFiddle link and tell why padding is not visible inside div container?

body {
  background-color: #B8C4BB;
}

.container {
  text-align: center;
}

.section_two {
  border: 2px solid red;
  padding: 10 px;
}

    Change the value of the color property to see how it changes the text color of this element.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt, alias, aliquid fugiat dolorem repudiandae quidem. Molestiae illum pariatur officia voluptate cumque. Necessitatibus earum consequuntur explicabo minus ratione mollitia illum nam.

Body:
It is not working because you have put a space between 10 and px. It should be like following code.

.section_two {
   border: 2px solid red;
   padding: 50px;
}


答:
NullPointerException is thrown when an application attempts to use an
  object reference that has the null value.

FYI

Java try block is used to enclose the code that might throw an
  exception. So no need to create try-catch block here.

You can try with

```<code>View viewOBJ = LayoutInflater.from(parent.getContext()).inflate(R.layout.faviorate_video_item, parent, false);
ViewHolder viewHolderOBJ = new ViewHolder(viewOBJ);
return viewHolderOBJ;
</code>```

Title: Get nullpointerexception while inflating in custom adapter of RecyclerView

Body:
NullPointerException is thrown when an application attempts to use an
  object reference that has the null value.

FYI

Java try block is used to enclose the code that might throw an
  exception. So no need to create try-catch block here.

You can try with

View viewOBJ = LayoutInflater.from(parent.getContext()).inflate(R.layout.faviorate_video_item, parent, false);
ViewHolder viewHolderOBJ = new ViewHolder(viewOBJ);
return viewHolderOBJ;


问:
Javascript clone node is not copying all values from cloned to new object
```<code><div class="container">
  <select class="btn" name="item">
    <option>Alpha</option>
    <option>Beta</option>
    <option>Gamma</option>
    <option>Theta</option>
  </select>
  <input type="text" class="desc" name="desc">
</div>
</code>```

In this example, element selected by default in the "select" dropdown is "Alpha". I want to clone the complete node with values. If i select a different value in the dropdown and enter some text in the input box, and then clone the node, only the text box value is cloned. The value of "select" dropdown in the new object remains the default (Alpha).

Why is the behavior of cloning different for "select" vs "input"?

```<code>var parent = document.querySelector(".container");
var button = parent.querySelector(".btn");
var textbox = parent.querySelector(".desc");

  > textbox.value
  < "some random text"
  > button.value
  < "Gamma"

var cloned = parent.cloneNode(true);
var childButton = cloned.querySelector(".btn");
var childTextbox = cloned.querySelector(".desc");

  > childTextbox.value
  < "some random text"
  > childButton.value
  < "Alpha"
</code>```

答:
I use the getElementsByClass() method to get the interesting elements.Then via for loop I add an onchange event to clone the container.Note the at the end of the function i assign the value pf the parent select element to the cloned select elm.

var parent = document.getElementsByClassName("container");
var button = document.getElementsByClassName("btn");

for(var i=0;i<button.length;i++){
button[i].onchange=function(){
var cloned = parent[0].cloneNode(true);
 console.log(cloned);
 document.body.appendChild(cloned);
  cloned.childNodes[1].value=this.value;
};
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <select class="btn" name="item">
    <option>Alpha</option>
    <option>Beta</option>
    <option>Gamma</option>
    <option>Theta</option>
  </select>
  <input type="text" class="desc" name="desc">
</div></code>```

Body:
  <select class="btn" name="item">
    <option>Alpha</option>
    <option>Beta</option>
    <option>Gamma</option>
    <option>Theta</option>
  </select>
  <input type="text" class="desc" name="desc">

In this example, element selected by default in the "select" dropdown is "Alpha". I want to clone the complete node with values. If i select a different value in the dropdown and enter some text in the input box, and then clone the node, only the text box value is cloned. The value of "select" dropdown in the new object remains the default (Alpha).

Why is the behavior of cloning different for "select" vs "input"?

var parent = document.querySelector(".container");
var button = parent.querySelector(".btn");
var textbox = parent.querySelector(".desc");

  > textbox.value
  < "some random text"
  > button.value
  < "Gamma"

var cloned = parent.cloneNode(true);
var childButton = cloned.querySelector(".btn");
var childTextbox = cloned.querySelector(".desc");

  > childTextbox.value
  < "some random text"
  > childButton.value
  < "Alpha"

Body:
I use the getElementsByClass() method to get the interesting elements.Then via for loop I add an onchange event to clone the container.Note the at the end of the function i assign the value pf the parent select element to the cloned select elm.

var parent = document.getElementsByClassName("container");
var button = document.getElementsByClassName("btn");

for(var i=0;i<button.length;i++){
button[i].onchange=function(){
var cloned = parent[0].cloneNode(true);
 console.log(cloned);
 document.body.appendChild(cloned);
  cloned.childNodes[1].value=this.value;
};
}

<div class="container">
  <select class="btn" name="item">
    <option>Alpha</option>
    <option>Beta</option>
    <option>Gamma</option>
    <option>Theta</option>
  </select>
  <input type="text" class="desc" name="desc">
</div>


问:
Text Editor for gigabyte sized files

Possible Duplicate:

  Text editor to open big (giant, huge, large) text files

I saw text editor to open big text files but that question referred to megabyte sized files. I work with 7GB csv files and find that even vim and gedit take a long time to open up.

What text editor do you use for for gigabyte sized files?

Appreciate any advice I can get.

答: You can use total commander </p>

Title: Text Editor for gigabyte sized files

Body: You can use total commander


问:
Partial Indexing of an XML file (Bleve)
I am evaluating a couple different libraries to see which one will best fit what I need.

Right now I am looking at Bleve, but I am happy to use any library.

I am looking to index full files except specific ones which are in XML format. For those I only want Bleve to index specific tags as most of the tags are worthless to search. I am trying to evaluate if this is possible but, being new to Bleve, I am not sure what part I need to customize.

The documentation is very good, but I can't seem to find this answer. All I need is an explanation with keywords and steps, no code is required, I just need a push as I have spent hours spinning my wheels with google searches and I am getting no where.

答:
There are probably many ways to approach this. Here's one.

Bleve indexes documents which are collections of key/value metadata pairs.

In your case, a document could be represented by 2 key/value pairs: name of .xml file (to uniquely identify the document) and content of the file.

```<code>type Doc struct {
    Name string
    Body string
}
</code>```

The issue is that body is XML and Bleve doesn't support XML out-of-the-box.

A way to address it would be to pre-process XML file by stripping unwanted tags and content. You can do it using encoding/xml standard library.

For an example of a similar task you can see the code of https://github.com/blevesearch/fosdem-search/

In there they index file in custom format (https://github.com/blevesearch/fosdem-search/blob/master/fosdem.ical) by parsing it into a format they can submit to Bleve for indexing (https://github.com/blevesearch/fosdem-search/blob/master/ical.go).

Title: Partial Indexing of an XML file (Bleve)

Body:
There are probably many ways to approach this. Here's one.

Bleve indexes documents which are collections of key/value metadata pairs.

In your case, a document could be represented by 2 key/value pairs: name of .xml file (to uniquely identify the document) and content of the file.

type Doc struct {
    Name string
    Body string
}

The issue is that body is XML and Bleve doesn't support XML out-of-the-box.

A way to address it would be to pre-process XML file by stripping unwanted tags and content. You can do it using encoding/xml standard library.

For an example of a similar task you can see the code of https://github.com/blevesearch/fosdem-search/

In there they index file in custom format (https://github.com/blevesearch/fosdem-search/blob/master/fosdem.ical) by parsing it into a format they can submit to Bleve for indexing (https://github.com/blevesearch/fosdem-search/blob/master/ical.go).


问:
Simple ajax function send NULL id
I'm trying to make simple delete ajax function. I'm not very good ad JS at all but when I click on button delete I can see in Chrome Dev Console that id = NULL and when I refresh the page the entry is back. The ajax function is pretty simple

```<code>$("body").on("click",".remove-item",function(){
    var entry_id = $(this).parent("td").data('entry_id');
    var c_obj = $(this).parents("tr");

    $.ajax({
        dataType: 'json',
        type:'POST',
        url: 'delete.php',
        data:{entry_id:entry_id}
    }).done(function(data){
        c_obj.remove();
        toastr.success('Item Deleted Successfully.', 'Success Alert', {timeOut: 5000});

    });
});
</code>```

And the button

```<code><button  class="btn btn-danger remove-item" > Delete</button>
</code>```

And this is the delete.php

```<code>$entry_id  = $_POST["entry_id"];
$stmt = $pdo->prepare("DELETE FROM entries WHERE entry_id = :entry_id");
$stmt->bindParam(':entry_id', $entry_id, PDO::PARAM_INT);
$stmt->execute();

echo json_encode([$entry_id]);
</code>```

Any idea what can be wrong?

update. The table

```<code>    echo '<table class="table">
        <thead>
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>Transaction Quote</th>
                <th>Action</th>
            </tr>
        </thead>';
        foreach($pdo->query("SELECT * FROM entries ORDER BY entry_id DESC LIMIT 20") as $row){
            echo '
                <tbody>
                <tr>
                    <td>'.$row['entry_id'].'</td>
                    <td>'.$row['entry_name'].'</td>
                    <td>'.$row['entry_transaction_quote'].'</td>
                    <td><button  class="btn btn-sm btn-danger remove-item" ><i class="glyphicon glyphicon-trash"></i> Delete</button></td>
                </tr>
                </tbody>  ';
        }
        echo '  </table>
</code>```

答:
Try this

Html should be like

```<code><tr entry_id="<?=$row['entry_id']?>">
   <td><button  class="btn btn-sm btn-danger remove-item" ><i class="glyphicon glyphicon-trash"></i> Delete</button></td>
</tr>
</code>```

Js code  should be like

```<code>var entry_id = $(this).parent().parent().attr("entry_id");
</code>```

Title: Simple ajax function send NULL id

Body:
I'm trying to make simple delete ajax function. I'm not very good ad JS at all but when I click on button delete I can see in Chrome Dev Console that id = NULL and when I refresh the page the entry is back. The ajax function is pretty simple

$("body").on("click",".remove-item",function(){
    var entry_id = $(this).parent("td").data('entry_id');
    var c_obj = $(this).parents("tr");

    $.ajax({
        dataType: 'json',
        type:'POST',
        url: 'delete.php',
        data:{entry_id:entry_id}
    }).done(function(data){
        c_obj.remove();
        toastr.success('Item Deleted Successfully.', 'Success Alert', {timeOut: 5000});

    });
});

And the button

<button  class="btn btn-danger remove-item" > Delete</button>

And this is the delete.php

$entry_id  = $_POST["entry_id"];
$stmt = $pdo->prepare("DELETE FROM entries WHERE entry_id = :entry_id");
$stmt->bindParam(':entry_id', $entry_id, PDO::PARAM_INT);
$stmt->execute();

echo json_encode([$entry_id]);

Any idea what can be wrong?

update. The table

    echo '

                #
                Name
                Transaction Quote
                Action

';
        foreach($pdo->query("SELECT * FROM entries ORDER BY entry_id DESC LIMIT 20") as $row){
            echo '

                    '.$row['entry_id'].'
                    '.$row['entry_name'].'
                    '.$row['entry_transaction_quote'].'
                    <button  class="btn btn-sm btn-danger remove-item" > Delete</button>

  ';
        }
        echo '

Body:
Try this

Html should be like

<tr entry_id="<?=$row['entry_id']?>">
   <td><button  class="btn btn-sm btn-danger remove-item" ><i class="glyphicon glyphicon-trash"></i> Delete</button></td>
</tr>

Js code  should be like

var entry_id = $(this).parent().parent().attr("entry_id");


答:
Try using a boolean flag to make sure the function executes only once </p>

```<code>var executeOnce = false;
$('.cancel-btn').on('click',function(evt){
   if(!executeOnce){
     //evt.preventDefault();
     //My Code
     executeOnce = true;
   }
});
</code>```

Title: How to prevent more than one click on an Anchor tag button

Body:
I have an anchor tag (namely Cancel button) with a class attribute and href attribute in a jsp file .

I have written an onclick event for the class attribute in a seperate js file. So when the button is clicked, the onclick event executes and then takes to the href link.

When the button is clicked more than once it takes me to an empty page or an error page.

I want to prevent more than one click on the button.

I have tried using event.preventdefault() function inside my onclick() function but the href link is not working if I do that.
Any other way?

My JS code:

$('.cancel-btn').on('click',function(evt){
            //evt.preventDefault();
           //My Code

        });

Body:
Try using a boolean flag to make sure the function executes only once

var executeOnce = false;
$('.cancel-btn').on('click',function(evt){
   if(!executeOnce){
     //evt.preventDefault();
     //My Code
     executeOnce = true;
   }
});


问:
Applying images on top of a background image
I seem to be having problems with my CSS code. I want to have a background image at 100% of the page width and height, and then other images strategically placed on top of the background image. The problem I am having is that when I absolutely place the images on top, unless I specify an actual height of the background image, the actual image does not show up in the background. Can anyone suggest a way around actually specifying a height for the background image?

#map {
  background-image: url("images/middleearth_map.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

#registermap {
  position: absolute;
  top: 5%;
  right: 2%;
}

#gollum {
  position: absolute;
  top: 40%;
  right: 15%;
}

#playtrailer {
  position: absolute;
  top: 30%;
  left: 0%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="map">
  <div id="registermap">

      <img src="images/middle-earth_map1.png" alt="Registration Link" class="wobble" />

  </div>

  <div id="gollum">

      <img src="images/gollum.png" alt="Cast and Crew Link" class="wobble" />

  </div>

  <div id="playtrailer">

      <img src="images/play_button.png" alt="Movie Trailer Link" class="wobble" />

  </div>
</div></code>```

答:
You can set background-image for body to be sure that it occupies all window.

body {
  background-image: url("https://i.stack.imgur.com/6JzYG.jpg");
  background-size: 100% 100%; /* Picture stretches */
  min-height: 100vh; /* Body occupies at least all screen */
  margin: 0;
}```


问:
How to convert java CharSequence to c++ char* through JNI
I feel that this should have a simple answer as I can do it easily with a java String, but something is going wrong with the CharSequence. My java code initializes a cppGenerator, passes a functionBlock object to its generateImplementation method, and returns a CharSequence. Here is my code:

```<code>jobject fBlock = env->CallObjectMethod(structuredTextModel, getFunction);
jclass CPPGenerator = lookForClass(env, "Path/CPPGenerator");
jobject CPPGeneratorImpl = invokeClassObj(env, CPPGenerator);
    jmethodID generateImplementation = env->GetMethodID(CPPGenerator, "generateImplementation", "(LPath/FunctionBlock;)Ljava/lang/CharSequence;");
jobject mid = env->CallObjectMethod(CPPGeneratorImpl, generateImplementation, fBlock);
jstring jresult = (jstring)mid;
char* result = (char*)env->GetStringUTFChars(jresult, 0);
</code>```

This logic has worked for me when using String but this function returns a CharSequence. No classes, objects, or methods are returning null. The program crashes in jni.h attempting to call GetStringUTFChars. So i know I cannot use this method for CharSequence. Is there just a jni method I am missing or do I have to do something completely different for a CharSequence?

答:
Why not use toString directly?

```<code>jclass clzCharSequence = env->GetObjectClass(mid);
jmethodID toString = env->GetMethodID(clzCharSequence, "toString", "()Ljava/lang/String;");
jobject s = env->CallObjectMethod(mid, toString);
const char* cstr = env->GetStringUTFChars(static_cast<jstring>(s), NULL);
// do something with cstr
env->ReleaseStringUTFChars(static_cast<jstring>(s), cstr);
</code>```

Body:
I feel that this should have a simple answer as I can do it easily with a java String, but something is going wrong with the CharSequence. My java code initializes a cppGenerator, passes a functionBlock object to its generateImplementation method, and returns a CharSequence. Here is my code:

jobject fBlock = env->CallObjectMethod(structuredTextModel, getFunction);
jclass CPPGenerator = lookForClass(env, "Path/CPPGenerator");
jobject CPPGeneratorImpl = invokeClassObj(env, CPPGenerator);
    jmethodID generateImplementation = env->GetMethodID(CPPGenerator, "generateImplementation", "(LPath/FunctionBlock;)Ljava/lang/CharSequence;");
jobject mid = env->CallObjectMethod(CPPGeneratorImpl, generateImplementation, fBlock);
jstring jresult = (jstring)mid;
char* result = (char*)env->GetStringUTFChars(jresult, 0);

This logic has worked for me when using String but this function returns a CharSequence. No classes, objects, or methods are returning null. The program crashes in jni.h attempting to call GetStringUTFChars. So i know I cannot use this method for CharSequence. Is there just a jni method I am missing or do I have to do something completely different for a CharSequence?

Body:
Why not use toString directly?

jclass clzCharSequence = env->GetObjectClass(mid);
jmethodID toString = env->GetMethodID(clzCharSequence, "toString", "()Ljava/lang/String;");
jobject s = env->CallObjectMethod(mid, toString);
const char* cstr = env->GetStringUTFChars(static_cast<jstring>(s), NULL);
// do something with cstr
env->ReleaseStringUTFChars(static_cast<jstring>(s), cstr);


问:
Preserve whitespaces when using split() and join() in python
I have a data file with columns like

```<code>BBP1   0.000000  -0.150000    2.033000  0.00 -0.150   1.77
</code>```

and the individual columns are separated by a varying number of whitespaces.

My goal is to read in those lines, do some math on several rows, for example multiplying column 4 by .95, and write them out to a new file. The new file should look like the original one, except for the values that I modified.

My approach would be reading in the lines as items of a list. And then I would use split() on those rows I am interested in, which will give me a sublist with the individual column values. Then I do the modification, join() the columns together and write the lines from the list to a new text file.

The problem is that I have those varying amount of whitespaces. I don't know how to introduce them back in the same way I read them in. The only way I could think of is to count characters in the line before I split them, which would be very tedious. Does someone have a better idea to tackle this problem?

答:
Other way to do this is:

```<code>s = 'BBP1   0.000000  -0.150000    2.033000  0.00 -0.150   1.77'
s.split(' ')
>>> ['BBP1', '', '', '0.000000', '', '-0.150000', '', '', '', '2.033000', '', '0.00', '-0.150', '', '', '1.77']
</code>```

If we specify space character argument in split function, it creates list without eating successive space characters. So, original numbers of space characters are restored after 'join' function.

Body:
I have a data file with columns like

BBP1   0.000000  -0.150000    2.033000  0.00 -0.150   1.77

and the individual columns are separated by a varying number of whitespaces.

My goal is to read in those lines, do some math on several rows, for example multiplying column 4 by .95, and write them out to a new file. The new file should look like the original one, except for the values that I modified.

My approach would be reading in the lines as items of a list. And then I would use split() on those rows I am interested in, which will give me a sublist with the individual column values. Then I do the modification, join() the columns together and write the lines from the list to a new text file.

The problem is that I have those varying amount of whitespaces. I don't know how to introduce them back in the same way I read them in. The only way I could think of is to count characters in the line before I split them, which would be very tedious. Does someone have a better idea to tackle this problem?

Body:
Other way to do this is:

s = 'BBP1   0.000000  -0.150000    2.033000  0.00 -0.150   1.77'
s.split(' ')
>>> ['BBP1', '', '', '0.000000', '', '-0.150000', '', '', '', '2.033000', '', '0.00', '-0.150', '', '', '1.77']

If we specify space character argument in split function, it creates list without eating successive space characters. So, original numbers of space characters are restored after 'join' function.


问:
How to approach the generation of tables based on conditionals using xtable
I am only in the beginning of the use of packages like xtable or `stargazer. Bellow is a sample dataset, the original one is much larger.

```<code>set.seed(1)
df <- data.frame(rep(
    sample(c(2012,2016),10, replace = T)),
    sample(c('Treat','Control'),10,replace = T),
    runif(10,0,1),
    runif(10,0,1),
    runif(10,0,1))

colnames(df) <- c('Year','Group','V1','V2','V3')
</code>```

I would like to generate well-formatted tables displaying descriptive statistics for the data set above.

However, is there a way xtable could directly generate a table in which I can see statistics for the whole dataset, separating by group (Treat and Control) and by year (2012, 2016)? Or maybe even by combining groups and years?

Or should I filter the original df according to these settings and run xtable on each one?

Another thing I would want is to, instead of displaying the mean, display the median of the variables, among other statistics. Is it possible, or do I have to manually calculate that using R?

Any solutions considering stargazer are valid!

Thank you!

答:
Below are some examples of what you can do in an rmarkdown document, although you can go a lot further in formatting the table than I've done here. I've included some examples using xtable and then a couple of examples with the new kableExtra package, which, unless you're already skilled with latex, makes it easier to format complex table layouts when compared with xtable. See the vignettes for xtable and kableExtra for more information.

For summarizing and reshaping the data, I've used functions from the dplyr and tidyr packages (which are part of the tidyverse suite of packages). You can also summarize and reshape with base R functions, such as aggregate and reshape, and with the data.table package.

rmarkdown document

```<code>---
title: "Tables"
author: "eipi10"
date: "7/7/2017"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo=FALSE, warning=FALSE)
library(xtable)
options(xtable.comment=FALSE, xtable.include.rownames=FALSE)
library(tidyverse)
```

```{r}
set.seed(1)
df <- data.frame(Year=rep(
    sample(c(2012,2016), 10, replace = T)),
    Group=sample(c('Treat','Control'),10,replace = T),
    V1=runif(10,0,1),
    V2=runif(10,0,1),
    V3=runif(10,0,1))
```

```{r, results="asis"}
# Mean by Year and Group
summary.table = df %>%
               group_by(Year, Group) %>%
               summarise_all(funs(mean))

print(xtable(summary.table,
             caption="Mean by Year and Group",
             digits=c(1,0,0,2,2,2)))
```

```{r, results="asis"}
# Median by Year and Group
summary.table = df %>%
               group_by(Year, Group) %>%
               summarise_all(funs(median))

print(xtable(summary.table,
             caption="Median by Year and Group",
             digits=c(1,0,0,2,2,2)))
```

```{r, results="asis"}
# Mean and Median by Year and Group
summary.table = df %>%
               group_by(Year, Group) %>%
               summarise_all(funs(mean, median))

print(xtable(summary.table,
             caption="Mean and Median by Year and Group",
             digits=c(1,0,0,rep(2,6))))
```

```{r}
# Create a function that takes the summary function calls as arguments
xtab_fnc = function(data, caption, ...) {

  # quosure to dispatch functions properly (see Programming with dplyr vignette)
  funcs = quos(...)

  summary.table = data %>%
    group_by(Year, Group) %>%
    summarise_all(funs(!!!funcs))

  # Get rid of repeated years
  for(i in nrow(summary.table):2) {
    if(identical(summary.table$Year[i-1], summary.table$Year[i])) {
      summary.table$Year[i] = ""
    }
  }

  xtable(summary.table,
         caption=caption,
         digits=c(1,0,0,rep(2,ncol(summary.table) - 2)))
}
```

```{r, results="asis"}
# Run the function
print(xtab_fnc(df, "Mean, Median, and Sum by Year and Group", mean, median, sum),
      size="scriptsize")
```

```{r, results="asis"}
# Run the function
print(xtab_fnc(df, "Mean by Year and Group", mean),
      size="large")
```

```{r}
# You can do more complex formatting in xtable, but it's probably easier with kableExtra
library(knitr)
library(kableExtra)
```

```{r}
summary.table = df %>%
  group_by(Year, Group) %>%
  summarise_all(funs(mean,sd,min,median,max))

# Get rid of repeated years
for(i in nrow(summary.table):2) {
  if(identical(summary.table$Year[i-1], summary.table$Year[i])) {
    summary.table$Year[i] = ""
  }
}

# Get rid of "_mean", and "_median" in column names
names(summary.table) = gsub("_.*","",names(summary.table))

# LaTeX Table
kable(summary.table, format = "latex",
      booktabs = T, caption = "kableExtra to format spanning columns",
      digits=c(0,0,rep(3,15))) %>%
  kable_styling(latex_options = c("striped", "hold_position", "scale_down"),
                full_width=F) %>%
  add_header_above(c("","","Mean"=3,"SD"=3,"Min"=3,"Median[note]"=3,"Max"=3)) %>%
  add_footnote(c("Note, means and medians are often the same with this data."))
```

```{r}
# Reshape table to turn V1-V3 into rows
summary.table = df %>%
  group_by(Year, Group) %>%
  summarise_all(funs(mean,sd,min,median,max)) %>%
  gather(key, value, -Year, -Group) %>%
  separate(key, into=c("var", "stat")) %>%
  unite(stat_Group, stat, Group) %>%
  spread(stat_Group, value)

# Get rid of repeated years
for(i in nrow(summary.table):2) {
  if(identical(summary.table$Year[i-1], summary.table$Year[i])) {
    summary.table$Year[i] = ""
  }
}

names(summary.table) = gsub(".*_", "", names(summary.table))

# LaTeX Table
kable(summary.table, format = "latex",
      booktabs = T, caption = "kableExtra to format spanning columns",
      digits=c(0,0,rep(3,10))) %>%
  kable_styling(latex_options = c("striped", "hold_position", "scale_down"),
                full_width=F) %>%
  add_header_above(c("","","Max"=2,"Mean"=2,"Median"=2,"Min"=2,"SD"=2))
```

```{r}
# Reshape table to turn V1-V3 into rows; also add a column summarizing all subjects
summary.table = df %>%
  group_by(Year, Group) %>%
  summarise_all(funs(mean,sd,min,median,max)) %>%
  bind_rows(df %>%                                              # bind_rows block adds the "All" column
              mutate(Group="All") %>%                           # |
              group_by(Year, Group) %>%                         # |
              summarise_all(funs(mean,sd,min,median,max))) %>%  # |
  gather(key, value, -Year, -Group) %>%
  separate(key, into=c("var", "stat")) %>%
  unite(stat_Group, stat, Group) %>%
  spread(stat_Group, value)

# Get rid of repeated years
for(i in nrow(summary.table):2) {
  if(identical(summary.table$Year[i-1], summary.table$Year[i])) {
    summary.table$Year[i] = ""
  }
}

names(summary.table) = gsub(".*_", "", names(summary.table))

# LaTeX Table
kable(summary.table, format = "latex",
      booktabs = T, caption = "kableExtra to format spanning columns; also add an 'All' column",
      digits=c(0,0,rep(3,15))) %>%
  kable_styling(latex_options = c("striped", "hold_position", "scale_down"),
                full_width=F) %>%
  add_header_above(c("","","Max"=3,"Mean"=3,"Median"=3,"Min"=3,"SD"=3))
```
</code>```

PDF Output File

Body:
I am only in the beginning of the use of packages like xtable or `stargazer. Bellow is a sample dataset, the original one is much larger.

set.seed(1)
df <- data.frame(rep(
    sample(c(2012,2016),10, replace = T)),
    sample(c('Treat','Control'),10,replace = T),
    runif(10,0,1),
    runif(10,0,1),
    runif(10,0,1))

colnames(df) <- c('Year','Group','V1','V2','V3')

I would like to generate well-formatted tables displaying descriptive statistics for the data set above.

However, is there a way xtable could directly generate a table in which I can see statistics for the whole dataset, separating by group (Treat and Control) and by year (2012, 2016)? Or maybe even by combining groups and years?

Or should I filter the original df according to these settings and run xtable on each one?

Another thing I would want is to, instead of displaying the mean, display the median of the variables, among other statistics. Is it possible, or do I have to manually calculate that using R?

Any solutions considering stargazer are valid!

Thank you!

Body:
Below are some examples of what you can do in an rmarkdown document, although you can go a lot further in formatting the table than I've done here. I've included some examples using xtable and then a couple of examples with the new kableExtra package, which, unless you're already skilled with latex, makes it easier to format complex table layouts when compared with xtable. See the vignettes for xtable and kableExtra for more information.

For summarizing and reshaping the data, I've used functions from the dplyr and tidyr packages (which are part of the tidyverse suite of packages). You can also summarize and reshape with base R functions, such as aggregate and reshape, and with the data.table package.

rmarkdown document

---
title: "Tables"
author: "eipi10"
date: "7/7/2017"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo=FALSE, warning=FALSE)
library(xtable)
options(xtable.comment=FALSE, xtable.include.rownames=FALSE)
library(tidyverse)
```

```{r}
set.seed(1)
df <- data.frame(Year=rep(
    sample(c(2012,2016), 10, replace = T)),
    Group=sample(c('Treat','Control'),10,replace = T),
    V1=runif(10,0,1),
    V2=runif(10,0,1),
    V3=runif(10,0,1))
```

```{r, results="asis"}
# Mean by Year and Group
summary.table = df %>%
               group_by(Year, Group) %>%
               summarise_all(funs(mean))

print(xtable(summary.table,
             caption="Mean by Year and Group",
             digits=c(1,0,0,2,2,2)))
```

```{r, results="asis"}
# Median by Year and Group
summary.table = df %>%
               group_by(Year, Group) %>%
               summarise_all(funs(median))

print(xtable(summary.table,
             caption="Median by Year and Group",
             digits=c(1,0,0,2,2,2)))
```

```{r, results="asis"}
# Mean and Median by Year and Group
summary.table = df %>%
               group_by(Year, Group) %>%
               summarise_all(funs(mean, median))

print(xtable(summary.table,
             caption="Mean and Median by Year and Group",
             digits=c(1,0,0,rep(2,6))))
```

```{r}
# Create a function that takes the summary function calls as arguments
xtab_fnc = function(data, caption, ...) {

  # quosure to dispatch functions properly (see Programming with dplyr vignette)
  funcs = quos(...)

  summary.table = data %>%
    group_by(Year, Group) %>%
    summarise_all(funs(!!!funcs))

  # Get rid of repeated years
  for(i in nrow(summary.table):2) {
    if(identical(summary.table$Year[i-1], summary.table$Year[i])) {
      summary.table$Year[i] = ""
    }
  }

  xtable(summary.table,
         caption=caption,
         digits=c(1,0,0,rep(2,ncol(summary.table) - 2)))
}
```

```{r, results="asis"}
# Run the function
print(xtab_fnc(df, "Mean, Median, and Sum by Year and Group", mean, median, sum),
      size="scriptsize")
```

```{r, results="asis"}
# Run the function
print(xtab_fnc(df, "Mean by Year and Group", mean),
      size="large")
```

```{r}
# You can do more complex formatting in xtable, but it's probably easier with kableExtra
library(knitr)
library(kableExtra)
```

```{r}
summary.table = df %>%
  group_by(Year, Group) %>%
  summarise_all(funs(mean,sd,min,median,max))

# Get rid of repeated years
for(i in nrow(summary.table):2) {
  if(identical(summary.table$Year[i-1], summary.table$Year[i])) {
    summary.table$Year[i] = ""
  }
}

# Get rid of "_mean", and "_median" in column names
names(summary.table) = gsub("_.*","",names(summary.table))

# LaTeX Table
kable(summary.table, format = "latex",
      booktabs = T, caption = "kableExtra to format spanning columns",
      digits=c(0,0,rep(3,15))) %>%
  kable_styling(latex_options = c("striped", "hold_position", "scale_down"),
                full_width=F) %>%
  add_header_above(c("","","Mean"=3,"SD"=3,"Min"=3,"Median[note]"=3,"Max"=3)) %>%
  add_footnote(c("Note, means and medians are often the same with this data."))
```

```{r}
# Reshape table to turn V1-V3 into rows
summary.table = df %>%
  group_by(Year, Group) %>%
  summarise_all(funs(mean,sd,min,median,max)) %>%
  gather(key, value, -Year, -Group) %>%
  separate(key, into=c("var", "stat")) %>%
  unite(stat_Group, stat, Group) %>%
  spread(stat_Group, value)

# Get rid of repeated years
for(i in nrow(summary.table):2) {
  if(identical(summary.table$Year[i-1], summary.table$Year[i])) {
    summary.table$Year[i] = ""
  }
}

names(summary.table) = gsub(".*_", "", names(summary.table))

# LaTeX Table
kable(summary.table, format = "latex",
      booktabs = T, caption = "kableExtra to format spanning columns",
      digits=c(0,0,rep(3,10))) %>%
  kable_styling(latex_options = c("striped", "hold_position", "scale_down"),
                full_width=F) %>%
  add_header_above(c("","","Max"=2,"Mean"=2,"Median"=2,"Min"=2,"SD"=2))
```

```{r}
# Reshape table to turn V1-V3 into rows; also add a column summarizing all subjects
summary.table = df %>%
  group_by(Year, Group) %>%
  summarise_all(funs(mean,sd,min,median,max)) %>%
  bind_rows(df %>%                                              # bind_rows block adds the "All" column
              mutate(Group="All") %>%                           # |
              group_by(Year, Group) %>%                         # |
              summarise_all(funs(mean,sd,min,median,max))) %>%  # |
  gather(key, value, -Year, -Group) %>%
  separate(key, into=c("var", "stat")) %>%
  unite(stat_Group, stat, Group) %>%
  spread(stat_Group, value)

# Get rid of repeated years
for(i in nrow(summary.table):2) {
  if(identical(summary.table$Year[i-1], summary.table$Year[i])) {
    summary.table$Year[i] = ""
  }
}

names(summary.table) = gsub(".*_", "", names(summary.table))

# LaTeX Table
kable(summary.table, format = "latex",
      booktabs = T, caption = "kableExtra to format spanning columns; also add an 'All' column",
      digits=c(0,0,rep(3,15))) %>%
  kable_styling(latex_options = c("striped", "hold_position", "scale_down"),
                full_width=F) %>%
  add_header_above(c("","","Max"=3,"Mean"=3,"Median"=3,"Min"=3,"SD"=3))
```

PDF Output File


问:
center align grid without gaps and floating
I have a grid set up where the blocks are centre aligned, thus I've done this using display: inline block and set text-align: center to the container. BUT now the client wants variable heights on the blocks which now leaves big gaps in the grid as they're inline-block. Alternatively I could use float: left but this won't work as the blocks need to be centred. I have a codepen setup here: https://codepen.io/anon/pen/WOaeve

I usually use the isotope plugin for grids but there's no layout mode that'll allow for centre aligned blocks so I need a solution that'll allow for all the gaps in the grid to be filled AND for the blocks to be centred. Here's my CSS markup also:

```<code>.feed-grid {
  position: relative;
  display: block;
  width: 100%;
  height: auto;
  text-align: center;
  font-size: 0;
}

.feed-grid .grid-block {
  display: inline-block;
  vertical-align: top;
  margin-left: 6px;
  margin-right: 6px;
  margin-bottom: 12px;
  width: auto;
  height: 255px;
}

.feed-grid .grid-block.large {
  height: 522px;
}

.feed-grid .grid-block img {
  position: relative;
  display: block;
  width: auto;
  height: 255px;
}

.feed-grid .grid-block.large img {
  height: 522px;
}
</code>```

Any solutions to this would be greatly appreciated!

答:
What about a vertical middle alignement in the cases you have a smaller image than its "row" ?

Here is a CodePen

```<code>$(document).ready(function(){
  var rowHeight = 0;
  var rowHeights = [];
  var rowCount = 0;
  var offset = $(".grid-block").first().offset().top;

  // Loop throught all images to get their heights.
  $(".grid-block img").each(function(){

    // If on the same row
    if($(this).offset().top == offset){
      // Find the biggest height
      if($(this).height() > rowHeight){
        rowHeight = $(this).height();
        rowHeights[rowCount] = rowHeight;
      }

      // If the row is different.
    }else{
      // Get the new row offset.
      offset = $(this).offset().top;
      rowCount++;

      rowHeight = $(this).height();
      rowHeights.push(rowHeight);
    }

    // Set a custom attribute to apply the right margins.
    $(this).attr("data-row",rowCount);
  });

  //Here you have the array of row heights in console.
  console.log(JSON.stringify(rowHeights));

  // Loop again to apply some margins.
  $(".grid-block img").each(function(){
    var thisRowHeight = rowHeights[parseInt($(this).data("row"))];

    // Apply the margin if this image is smaller than the row height.
    if( $(this).height() < thisRowHeight ){
      var margin = (thisRowHeight - $(this).height() )/2;
      $(this).css({"margin":margin+"px 0"});
    }
  });
});
</code>```

It "measures" the row height to apply a margin to small images... Making them at the middle.

Body:
I have a grid set up where the blocks are centre aligned, thus I've done this using display: inline block and set text-align: center to the container. BUT now the client wants variable heights on the blocks which now leaves big gaps in the grid as they're inline-block. Alternatively I could use float: left but this won't work as the blocks need to be centred. I have a codepen setup here: https://codepen.io/anon/pen/WOaeve

I usually use the isotope plugin for grids but there's no layout mode that'll allow for centre aligned blocks so I need a solution that'll allow for all the gaps in the grid to be filled AND for the blocks to be centred. Here's my CSS markup also:

.feed-grid {
  position: relative;
  display: block;
  width: 100%;
  height: auto;
  text-align: center;
  font-size: 0;
}

.feed-grid .grid-block {
  display: inline-block;
  vertical-align: top;
  margin-left: 6px;
  margin-right: 6px;
  margin-bottom: 12px;
  width: auto;
  height: 255px;
}

.feed-grid .grid-block.large {
  height: 522px;
}

.feed-grid .grid-block img {
  position: relative;
  display: block;
  width: auto;
  height: 255px;
}

.feed-grid .grid-block.large img {
  height: 522px;
}

Any solutions to this would be greatly appreciated!

Body:
What about a vertical middle alignement in the cases you have a smaller image than its "row" ?

Here is a CodePen

$(document).ready(function(){
  var rowHeight = 0;
  var rowHeights = [];
  var rowCount = 0;
  var offset = $(".grid-block").first().offset().top;

  // Loop throught all images to get their heights.
  $(".grid-block img").each(function(){

    // If on the same row
    if($(this).offset().top == offset){
      // Find the biggest height
      if($(this).height() > rowHeight){
        rowHeight = $(this).height();
        rowHeights[rowCount] = rowHeight;
      }

      // If the row is different.
    }else{
      // Get the new row offset.
      offset = $(this).offset().top;
      rowCount++;

      rowHeight = $(this).height();
      rowHeights.push(rowHeight);
    }

    // Set a custom attribute to apply the right margins.
    $(this).attr("data-row",rowCount);
  });

  //Here you have the array of row heights in console.
  console.log(JSON.stringify(rowHeights));

  // Loop again to apply some margins.
  $(".grid-block img").each(function(){
    var thisRowHeight = rowHeights[parseInt($(this).data("row"))];

    // Apply the margin if this image is smaller than the row height.
    if( $(this).height() < thisRowHeight ){
      var margin = (thisRowHeight - $(this).height() )/2;
      $(this).css({"margin":margin+"px 0"});
    }
  });
});

It "measures" the row height to apply a margin to small images... Making them at the middle.


问:
How to write a function f("123")=123+12+23+1+2+3 as a recurrence relationship
I'm wondering if someone can help me try to figure this out.

I want f(str) to take a string str of digits and return the sum of all substrings as numbers, and I want to write f as a function of itself so that I can try to solve this with memoization.

It's not jumping out at me as I stare at

```<code>        Solve("1") = 1
        Solve("2") = 2
        Solve("12") = 12 + 1 + 2
        Solve("29") = 29 + 2 + 9
        Solve("129") = 129 + 12 + 29 + 1 + 2 + 9
        Solve("293") = 293 + 29 + 93 + 2 + 9 + 3
        Solve("1293") = 1293 + 129 + 293 + 12 + 29 + 93 + 1 + 2 + 9 + 3
        Solve("2395") = 2395 + 239 + 395 + 23 + 39 + 95 + 2 + 3 + 9 + 5
        Solve("12395") = 12395 + 1239 + 2395 + 123 + 239 + 395 + 12 + 23 + 39 + 95 + 1 + 2 + 3 + 9 + 5
</code>```

答:
You have to break f down into two functions.

Let N[i] be the ith digit of the input. Let T[i] be the sum of substrings of the first i-1 characters of the input. Let B[i] be the sum of suffixes of the first i characters of the input.

So if the input is "12395", then B[3] = 9+39+239+1239, and T[3] = 123+12+23+1+2+3.

The recurrence relations are:

```<code>T[0] = B[0] = 0
T[i+1] = T[i] + B[i]
B[i+1] = B[i]*10 + (i+1)*N[i]
</code>```

The last line needs some explanation: the suffixes of the first i+2 characters are the suffixes of the first i+1 characters with the N[i] appended on the end, as well as the single-character string N[i]. The sum of these is (B[i]*10+N[i]*i) + N[i] which is the same as B[i]*10+N[i]*(i+1).

Also f(N) = T[len(N)] + B[len(N)].

This gives a short, linear-time, iterative solution, which you could consider to be a dynamic program:

```<code>def solve(n):
    rt, rb = 0, 0
    for i in xrange(len(n)):
        rt, rb = rt+rb, rb*10+(i+1)*int(n[i])
    return rt+rb

print solve("12395")
</code>```

Body:
I'm wondering if someone can help me try to figure this out.

I want f(str) to take a string str of digits and return the sum of all substrings as numbers, and I want to write f as a function of itself so that I can try to solve this with memoization.

It's not jumping out at me as I stare at

        Solve("1") = 1
        Solve("2") = 2
        Solve("12") = 12 + 1 + 2
        Solve("29") = 29 + 2 + 9
        Solve("129") = 129 + 12 + 29 + 1 + 2 + 9
        Solve("293") = 293 + 29 + 93 + 2 + 9 + 3
        Solve("1293") = 1293 + 129 + 293 + 12 + 29 + 93 + 1 + 2 + 9 + 3
        Solve("2395") = 2395 + 239 + 395 + 23 + 39 + 95 + 2 + 3 + 9 + 5
        Solve("12395") = 12395 + 1239 + 2395 + 123 + 239 + 395 + 12 + 23 + 39 + 95 + 1 + 2 + 3 + 9 + 5

Body:
You have to break f down into two functions.

Let N[i] be the ith digit of the input. Let T[i] be the sum of substrings of the first i-1 characters of the input. Let B[i] be the sum of suffixes of the first i characters of the input.

So if the input is "12395", then B[3] = 9+39+239+1239, and T[3] = 123+12+23+1+2+3.

The recurrence relations are:

T[0] = B[0] = 0
T[i+1] = T[i] + B[i]
B[i+1] = B[i]*10 + (i+1)*N[i]

The last line needs some explanation: the suffixes of the first i+2 characters are the suffixes of the first i+1 characters with the N[i] appended on the end, as well as the single-character string N[i]. The sum of these is (B[i]*10+N[i]*i) + N[i] which is the same as B[i]*10+N[i]*(i+1).

Also f(N) = T[len(N)] + B[len(N)].

This gives a short, linear-time, iterative solution, which you could consider to be a dynamic program:

def solve(n):
    rt, rb = 0, 0
    for i in xrange(len(n)):
        rt, rb = rt+rb, rb*10+(i+1)*int(n[i])
    return rt+rb

print solve("12395")


问:
Passing Arrays back to main body
I am pondering upon available functions in the net for my optimization project.. I have stumbled upon an available code by Bateesh and i found it very useful. But I want to slightly modify his code such that

**instead from printing the output, it will be transferred in my main body to be used in the next process.

How do i do it? I have new in C++ so any suggestions will help. I am currently reading about passing arrays but i am dazed by the new ideas.

Thank you.

```<code>    // Program to print all combination of size r in an array of size n
#include <stdio.h>
#include <stdlib.h>
void combinationUtil(int arr[], int n, int r, int count, int data[], int i);

// Needed for qsort.  See http://w...content-available-to-author-only...s.com/reference/cstdlib/qsort/
int compare (const void * a, const void * b)
{
    return ( *(int*)a - *(int*)b );
}

// The main function that prints all combinations of size r
// in arr[] of size n. This function mainly uses combinationUtil()
void printCombination(int arr[], int n, int r)
{
    // A temporary array to store all combination one by one
    int data[r];

    // Sort array to handle duplicates
    qsort (arr, n, sizeof(int), compare);

    // Print all combination using temprary array 'data[]'
    combinationUtil(arr, n, r, 0, data, 0);
}

/* arr[]  ---> Input Array
   n      ---> Size of input array
   r      ---> Size of a combination to be printed
   index  ---> Current index in data[]
   data[] ---> Temporary array to store current combination
   i      ---> index of current element in arr[]     */
void combinationUtil(int arr[], int n, int r, int index, int data[], int i)
{
    // Current cobination is ready, print it
    if (index == r)
    {
        for (int j=0; j<r; j++)
            printf("%d ",data[j]);
        printf("\n");
        return;
    }

    // When no more elements are there to be put
    if (i >= n)
        return;

    // current is included, put next at next location
    data[index] = arr[i];
    combinationUtil(arr, n, r, index+1, data, i+1);

    // Remove duplicates
    while (arr[i] == arr[i+1])
        i++;

    // current is excluded, replace it with next (Note that
    // i+1 is passed, but index is not changed)
    combinationUtil(arr, n, r, index, data, i+1);
}

// Driver program to test above functions
int main()
{
    int arr[] = {1, 2, 1, 3, 1};
    int r = 3;
    int n = sizeof(arr)/sizeof(arr[0]);
    printCombination(arr, n, r);
    return 0;
}
</code>```

答: You can return an array by changing the return type to std::vector<std::string> in function printCombination. Since combinationUtil() is called recursive hence it would be good idea to pass a reference of std::vector<std::string> variable from printCombination function and let it be filled by combinationUtil(). Finally you can return that variable from printCombination and make it available to main().

Title: Passing Arrays back to main body

Body:
I am pondering upon available functions in the net for my optimization project.. I have stumbled upon an available code by Bateesh and i found it very useful. But I want to slightly modify his code such that

**instead from printing the output, it will be transferred in my main body to be used in the next process.

How do i do it? I have new in C++ so any suggestions will help. I am currently reading about passing arrays but i am dazed by the new ideas.

Thank you.

    // Program to print all combination of size r in an array of size n
#include <stdio.h>
#include <stdlib.h>
void combinationUtil(int arr[], int n, int r, int count, int data[], int i);

// Needed for qsort.  See http://w...content-available-to-author-only...s.com/reference/cstdlib/qsort/
int compare (const void * a, const void * b)
{
    return ( *(int*)a - *(int*)b );
}

// The main function that prints all combinations of size r
// in arr[] of size n. This function mainly uses combinationUtil()
void printCombination(int arr[], int n, int r)
{
    // A temporary array to store all combination one by one
    int data[r];

    // Sort array to handle duplicates
    qsort (arr, n, sizeof(int), compare);

    // Print all combination using temprary array 'data[]'
    combinationUtil(arr, n, r, 0, data, 0);
}

/* arr[]  ---> Input Array
   n      ---> Size of input array
   r      ---> Size of a combination to be printed
   index  ---> Current index in data[]
   data[] ---> Temporary array to store current combination
   i      ---> index of current element in arr[]     */
void combinationUtil(int arr[], int n, int r, int index, int data[], int i)
{
    // Current cobination is ready, print it
    if (index == r)
    {
        for (int j=0; j<r; j++)
            printf("%d ",data[j]);
        printf("\n");
        return;
    }

    // When no more elements are there to be put
    if (i >= n)
        return;

    // current is included, put next at next location
    data[index] = arr[i];
    combinationUtil(arr, n, r, index+1, data, i+1);

    // Remove duplicates
    while (arr[i] == arr[i+1])
        i++;

    // current is excluded, replace it with next (Note that
    // i+1 is passed, but index is not changed)
    combinationUtil(arr, n, r, index, data, i+1);
}

// Driver program to test above functions
int main()
{
    int arr[] = {1, 2, 1, 3, 1};
    int r = 3;
    int n = sizeof(arr)/sizeof(arr[0]);
    printCombination(arr, n, r);
    return 0;
}


问:
Can not install angularjs in .net core Visual Studio 2015
i am trying to install angularjs in asp.net core but it is shows dependencies(Restroing...)

答:
try this

AngularJS and ASP.net Core 1.0

Body:
try this

AngularJS and ASP.net Core 1.0


问:
Get the data of xelement in c#
I have this xml as you can see :

```<code><ResultTest>
  <BackLeftShockAbsorber>0</BackLeftShockAbsorber>
  <BackRightBrak>0</BackRightBrak>
  <BackRightShockAbsorber>0</BackRightShockAbsorber>
  <BackShockAbsorber>0</BackShockAbsorber>
  <BackSideSlip>0</BackSideSlip>
  <BackWeight>0</BackWeight>
  <BrakeAcceleration>0</BrakeAcceleration>
  <CarReceiptionId>7</CarReceiptionId>
  <CO>0</CO>
  <CO2>0</CO2>
  <FrontBrake>0</FrontBrake>
  <FrontLeftBrake>0</FrontLeftBrake>
  <FrontLeftShockAbsorber>0</FrontLeftShockAbsorber>
  <FrontRightShockAbsorber>0</FrontRightShockAbsorber>
  <FrontShockAbsorber>0</FrontShockAbsorber>
  <FrontSideSlip>0</FrontSideSlip>
  <FrontWeight>0</FrontWeight>
  <FuelSystem>0</FuelSystem>
  <HandBrake>0</HandBrake>
  <HandBrake>0</HandBrake>
  <HandBrakeAcceleration>0</HandBrakeAcceleration>
  <HandBrakeLeft>0</HandBrakeLeft>
  <HandBrakeRight>0</HandBrakeRight>
  <LabelApplication>0</LabelApplication>
  <Lambda>0</Lambda>
  <NOX>0</NOX>
  <O2>0</O2>
  <Opacity>0</Opacity>
  <OutsideState>0</OutsideState>
  <PlayDetectorState>0</PlayDetectorState>
  <TechnicalReviewCenterLineId>0</TechnicalReviewCenterLineId>
  <TotalWeight>0</TotalWeight>
</ResultTest>
</code>```

I want to get the data in each element as you can see here :

```<code>        float CurrentData = float.Parse(xd.Root.Elements("CO").ToString());
</code>```

But i get this error :

An exception of type 'System.FormatException' occurred in
  mscorlib.dll but was not handled in user code

```<code>Additional information: Input string was not in a correct format.
</code>```

答:
Real simple to take this xml and put into a dictionary</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, int> dict = doc.Descendants("ResultTest").Elements()
                .GroupBy(x => x.Name.LocalName, y => (int)y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}
</code>```

Title: Get the data of xelement in c#

Body:
I have this xml as you can see :

<ResultTest>
  <BackLeftShockAbsorber>0</BackLeftShockAbsorber>
  <BackRightBrak>0</BackRightBrak>
  <BackRightShockAbsorber>0</BackRightShockAbsorber>
  <BackShockAbsorber>0</BackShockAbsorber>
  <BackSideSlip>0</BackSideSlip>
  <BackWeight>0</BackWeight>
  <BrakeAcceleration>0</BrakeAcceleration>
  <CarReceiptionId>7</CarReceiptionId>
  <CO>0</CO>
  <CO2>0</CO2>
  <FrontBrake>0</FrontBrake>
  <FrontLeftBrake>0</FrontLeftBrake>
  <FrontLeftShockAbsorber>0</FrontLeftShockAbsorber>
  <FrontRightShockAbsorber>0</FrontRightShockAbsorber>
  <FrontShockAbsorber>0</FrontShockAbsorber>
  <FrontSideSlip>0</FrontSideSlip>
  <FrontWeight>0</FrontWeight>
  <FuelSystem>0</FuelSystem>
  <HandBrake>0</HandBrake>
  <HandBrake>0</HandBrake>
  <HandBrakeAcceleration>0</HandBrakeAcceleration>
  <HandBrakeLeft>0</HandBrakeLeft>
  <HandBrakeRight>0</HandBrakeRight>
  <LabelApplication>0</LabelApplication>
  <Lambda>0</Lambda>
  <NOX>0</NOX>
  <O2>0</O2>
  <Opacity>0</Opacity>
  <OutsideState>0</OutsideState>
  <PlayDetectorState>0</PlayDetectorState>
  <TechnicalReviewCenterLineId>0</TechnicalReviewCenterLineId>
  <TotalWeight>0</TotalWeight>
</ResultTest>

I want to get the data in each element as you can see here :

        float CurrentData = float.Parse(xd.Root.Elements("CO").ToString());

But i get this error :

An exception of type 'System.FormatException' occurred in
  mscorlib.dll but was not handled in user code

Additional information: Input string was not in a correct format.

Body:
Real simple to take this xml and put into a dictionary

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, int> dict = doc.Descendants("ResultTest").Elements()
                .GroupBy(x => x.Name.LocalName, y => (int)y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}


问:
ReferenceError: json is not defined when AJAX call the server method
I want to call the server method through the AJAX call. But when I am click the button and call the AJAX function at that time it shows an error.

Here is my code

```<code><input type="button" id="btn_findsubmit" value="Edit" class="button" />

$(document).on("click", "#btn_findsubmit", function (e) {
    var c = $find("<%=cmbobx_search.ClientID %>");
    $.ajax({
        type: "POST",
        url: "schoolregistration.aspx/GetSchoolName",
        data: json.stringify({ schoolname: c.get_textboxcontrol().value }),
        contenttype: "application/json; charset=utf-8",
        datatype: "json",
        success: OnSuccessGetSchoolName,
        failure: function () {
            alert("error! try again...");
        }
    });
});
</code>```

[WebMethod]
[ScriptMethod]

```<code>public static string GetSchoolName(string schoolName){
   //Here is the code
}
</code>```

Now when I click the button at that time JavaScript button click event is working but the ajax method do not calling the server method GetSchoolName (I know by doing debug mode).

And throws a error that:

ReferenceError: json is not defined

答:
```<code> <input type="button" id="btn_findsubmit" value="Edit" class="button" />

<script>

    $(document).on("click", "#btn_findsubmit", function (e) {

        $.ajax({
            type: "POST",
            url: "Default.aspx/GetSchoolName",
            data: JSON.stringify({ schoolName: "school name" }),
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            success: function (data) {
                alert(data.d);
            },
            failure: function () {
                alert("error! try again...");
            }
        });
    });

</script>

 [WebMethod]
 public static string GetSchoolName(string schoolName)
  {
     //Here is the code
     return "success";
  }
</code>```

first of all it must be JSON.stringify not json.stringify, second it must be contentType not contenttype third the name of parameters in [WebMethod] must be same as in your ajax data.
in this case schoolName not schoolname.
hope it help you.

Body:
I want to call the server method through the AJAX call. But when I am click the button and call the AJAX function at that time it shows an error.

Here is my code

<input type="button" id="btn_findsubmit" value="Edit" class="button" />

$(document).on("click", "#btn_findsubmit", function (e) {
    var c = $find("<%=cmbobx_search.ClientID %>");
    $.ajax({
        type: "POST",
        url: "schoolregistration.aspx/GetSchoolName",
        data: json.stringify({ schoolname: c.get_textboxcontrol().value }),
        contenttype: "application/json; charset=utf-8",
        datatype: "json",
        success: OnSuccessGetSchoolName,
        failure: function () {
            alert("error! try again...");
        }
    });
});

[WebMethod]
[ScriptMethod]

public static string GetSchoolName(string schoolName){
   //Here is the code
}

Now when I click the button at that time JavaScript button click event is working but the ajax method do not calling the server method GetSchoolName (I know by doing debug mode).

And throws a error that:

ReferenceError: json is not defined

Body:
 <input type="button" id="btn_findsubmit" value="Edit" class="button" />

<script>

    $(document).on("click", "#btn_findsubmit", function (e) {

        $.ajax({
            type: "POST",
            url: "Default.aspx/GetSchoolName",
            data: JSON.stringify({ schoolName: "school name" }),
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            success: function (data) {
                alert(data.d);
            },
            failure: function () {
                alert("error! try again...");
            }
        });
    });

</script>

 [WebMethod]
 public static string GetSchoolName(string schoolName)
  {
     //Here is the code
     return "success";
  }

first of all it must be JSON.stringify not json.stringify, second it must be contentType not contenttype third the name of parameters in [WebMethod] must be same as in your ajax data.
in this case schoolName not schoolname.
hope it help you.