问:
The left parenthesis '(' found at 'foo.cpp' was not matched correctly
Location of the error is indicated in a comment below. Please help fix this.</p>

```<code>#include<iostream.h>
#include<string.h>
#include<stdlib.h>
class String
{
private:
    enum{sz=80};
    char str[sz];
public:
    String()
    {
        strcpy(str,"");
    }

    String (char s[])
    {
        strcpy(str,s);
    }

    void display() const
    {
        cout<<str;
    }
    String operator +(String ss) const
    {
        String temp;
        if(strlen(str) + (strlen(ss.str) < sz)
        {
            strcpy(temp.str,str);
            strcat(temp.str , ss.str);
        } // Error is reported here!
        else
        {
            cout<<"\nstring overflow";
            exit(1);
        }
        return temp;
    }

};
int main()
{
    String s1="\nMerry christmas";
    String s2="happy new year";
    String s3;

    s1.display();
    s2.display();
    s3.display();

    s3=s1+s2;
    s3.display();
    cout<<endl;
    return 0;
}
</code>```

答:
```<code>if(strlen(str) + (strlen(ss.str) < sz)
</code>```

should be

```<code>if(strlen(str) + strlen(ss.str) < sz)
</code>```

Notice how you have 4 ( but only 3 ) in the original line. These need to match up, but they don't. Since the ( before the second strlen() is superfluous (there is no need to wrap strlen(ss.str) in brackets), you can remove it.

Original code with changes to the #includes and fixed code. Note that I had to change the #includes from string.h to cstring for ideone. It's the preferred choice anyway. I also had to add using namespace std; as your code wasn't explicitly using the std namepsace where required, e.g. using cout. You should also take care of those warnings.

The reason the compiler error points to 4 lines down is because that's the line where it realises "Oh no, there's a problem here I'm never going to be able to parse this code!" GCC is pretty crappy at error reporting, but a but a compiler (e.g. clang) that does a better job of it would backtrack to the appropriate line where the root cause of the error actually lies and may even suggest a fix for you.

Body:
Location of the error is indicated in a comment below. Please help fix this.

#include<iostream.h>
#include<string.h>
#include<stdlib.h>
class String
{
private:
    enum{sz=80};
    char str[sz];
public:
    String()
    {
        strcpy(str,"");
    }

    String (char s[])
    {
        strcpy(str,s);
    }

    void display() const
    {
        cout<<str;
    }
    String operator +(String ss) const
    {
        String temp;
        if(strlen(str) + (strlen(ss.str) < sz)
        {
            strcpy(temp.str,str);
            strcat(temp.str , ss.str);
        } // Error is reported here!
        else
        {
            cout<<"\nstring overflow";
            exit(1);
        }
        return temp;
    }

};
int main()
{
    String s1="\nMerry christmas";
    String s2="happy new year";
    String s3;

    s1.display();
    s2.display();
    s3.display();

    s3=s1+s2;
    s3.display();
    cout<<endl;
    return 0;
}

Body:
if(strlen(str) + (strlen(ss.str) < sz)

should be

if(strlen(str) + strlen(ss.str) < sz)

Notice how you have 4 ( but only 3 ) in the original line. These need to match up, but they don't. Since the ( before the second strlen() is superfluous (there is no need to wrap strlen(ss.str) in brackets), you can remove it.

Original code with changes to the #includes and fixed code. Note that I had to change the #includes from string.h to cstring for ideone. It's the preferred choice anyway. I also had to add using namespace std; as your code wasn't explicitly using the std namepsace where required, e.g. using cout. You should also take care of those warnings.

The reason the compiler error points to 4 lines down is because that's the line where it realises "Oh no, there's a problem here I'm never going to be able to parse this code!" GCC is pretty crappy at error reporting, but a but a compiler (e.g. clang) that does a better job of it would backtrack to the appropriate line where the root cause of the error actually lies and may even suggest a fix for you.


来源: stackexchange

问:
Why doesn't this ES6 default argument value give the desired result?
I found this ES6 code in a book:

```<code>let value = 5;

function getValue() {
    return value++;
}

function add(first, second = getValue()) {
    return first + second;
}

console.log(add(1, 1));     // 2
console.log(add(1));        // 6
</code>```

Why does running console.log(add(1)); return 6 as the value, which means it is taking the parameter second as 5 although my code explicitly specifies that the getValue function should return value++ - which means the first time it is run, the getValue function should be returning 6 and add should be returning 7. I am running this code in the Firefox console - am I missing something?

答:
```<code>value++
</code>```

gets the value before increasing it,you should do either

```<code>++value
</code>```

or

```<code>value+=1;
return value
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I found this ES6 code in a book:

let value = 5;

function getValue() {
    return value++;
}

function add(first, second = getValue()) {
    return first + second;
}

console.log(add(1, 1));     // 2
console.log(add(1));        // 6

Why does running console.log(add(1)); return 6 as the value, which means it is taking the parameter second as 5 although my code explicitly specifies that the getValue function should return value++ - which means the first time it is run, the getValue function should be returning 6 and add should be returning 7. I am running this code in the Firefox console - am I missing something?

Body:
value++

gets the value before increasing it,you should do either

++value

or

value+=1;
return value


问:
How are same hash vs same key handled?
This question is not specific to any programming language, I am more interested in a generic logic.

Generally, associative maps take a key and map it to a value. As far as I know, implementations require the keys to be unique otherwise values get overwritten. Alright.

So let us assume that the above is done by some hash implementation.
What if two DIFFERENT keys get the same hash value? I am thinking of this in the form of an underlying array whose indices are in a result of hash on said keys. It could be possible that more than one unique key gets mapped to the same value yes? If so, how does such an implementation handle this?
How is handling same hash different from handling same key? Since same key results in overwriting and same hash HAS to retain the value.

I understand hashing with collision, so I know chaining and probing. Do implementations iterate over the current values which are hashed to a particular index and determine if the key is the same?

While I was searching for the answer I came across these links:

1. What happens when a duplicate key is put into a HashMap?

2. HashMap with multiple values under the same key

They don't answer my question however. How do we distinguish between same hash vs same key?

答:
You can not tell what a key is from the index, so no you can not iterate over the values to find any information about the keys. You will either have to guarantee 0 collisions or store the information that was hashed to give the index.

If you only have values stored in your structure, there is no way to tell if they have the same key or just the same hash. You will need to store the key along with the value to know.

Title: How are same hash vs same key handled?


问:
ansible sudo: sorry, you must have a tty to run sudo
I need to run playbooks on Vagrant boxes and on aws when I setup environment with cloud formation.

In Vagrant file I use ansible-local and everything works fine

```<code>name: Setup Unified Catalog Webserver
    hosts: 127.0.0.1
    connection: local
  become: yes
  become_user: root
  roles: generic
</code>```

However when I create instance in AWS the ansible playbook fails with error:

sudo: sorry, you must have a tty to run sudo

This happen because it is run as root and it doesnt have tty. But I dont know how to fix it without making change in /etc/sudoers to allow !requiretty

Is there any flags I can setup in ansible.cfg or in my Cloud Formation template?

```<code>  "#!/bin/bash\n", "\n", "
 echo 'Installing Git'\n","
  yum --nogpgcheck -y install git ansible htop nano wget\n",
 "wget https://s3.eu-central-1.amazonaws.com/XXX -O /root/.ssh/id_rsa\n",
"chmod 600 /root/.ssh/id_rsa\n",
"ssh-keyscan 172.31.7.235 >> /root/.ssh/known_hosts\n",
 "git clone git@172.31.7.235:something/repo.git /root/repo\n",
"ansible-playbook /root/env/ansible/test.yml\n
</code>```

答: I was able to fix this by setting the transport = paramiko configuration in ansible.cfg.

Body:
I need to run playbooks on Vagrant boxes and on aws when I setup environment with cloud formation.

In Vagrant file I use ansible-local and everything works fine

name: Setup Unified Catalog Webserver
    hosts: 127.0.0.1
    connection: local
  become: yes
  become_user: root
  roles: generic

However when I create instance in AWS the ansible playbook fails with error:

sudo: sorry, you must have a tty to run sudo

This happen because it is run as root and it doesnt have tty. But I dont know how to fix it without making change in /etc/sudoers to allow !requiretty

Is there any flags I can setup in ansible.cfg or in my Cloud Formation template?

  "#!/bin/bash\n", "\n", "
 echo 'Installing Git'\n","
  yum --nogpgcheck -y install git ansible htop nano wget\n",
 "wget https://s3.eu-central-1.amazonaws.com/XXX -O /root/.ssh/id_rsa\n",
"chmod 600 /root/.ssh/id_rsa\n",
"ssh-keyscan 172.31.7.235 >> /root/.ssh/known_hosts\n",
 "git clone git@172.31.7.235:something/repo.git /root/repo\n",
"ansible-playbook /root/env/ansible/test.yml\n


问:
Variable path PowerShell - Win10
I've downloaded "openSSH-Win64", so I can ssh into a Linux server using my PowerShell.

It works if I go into the folder and call the ssh.exe.
I don't wanna go into the folder every time I need to use SSH.

I've tried this tutorial but it doesn't work. When typing ssh on powershell I get this error:

```<code>ComSpec : The term 'ComSpec' is not recognized as the name of a cmdlet, function, script file, or operable program.
</code>```

QUESTION:

How can I create a variable path or something so every time I type ssh into my PowerShell it will automatically call this executable file C:\Users\druml\Downloads\OpenSSH-Win64\OpenSSH-Win64\ssh.exe?

UPDATE:

I was able to get this working on the Command Line (cmd), not using PowerShell. In my case I really need to use PowerShell.

答:
I was able to do this by following: https://superuser.com/questions/949560/how-do-i-set-system-environment-variables-in-windows-10

Once you have added the new Variable, make sure to restart PowerShell as @J. Bergmann has mentioned.

Title: Variable path PowerShell - Win10

Body:
I've downloaded "openSSH-Win64", so I can ssh into a Linux server using my PowerShell.

It works if I go into the folder and call the ssh.exe.
I don't wanna go into the folder every time I need to use SSH.

I've tried this tutorial but it doesn't work. When typing ssh on powershell I get this error:

ComSpec : The term 'ComSpec' is not recognized as the name of a cmdlet, function, script file, or operable program.

QUESTION:

How can I create a variable path or something so every time I type ssh into my PowerShell it will automatically call this executable file C:\Users\druml\Downloads\OpenSSH-Win64\OpenSSH-Win64\ssh.exe?

UPDATE:

I was able to get this working on the Command Line (cmd), not using PowerShell. In my case I really need to use PowerShell.


问:
custom view extends LinearLayout can't display in Android N but in Android M is well
my custom view code:

```<code>public class IndicatorView extends LinearLayout {
private int[] mColors = new int[]{Color.RED, Color.GREEN, Color.MAGENTA, Color.BLUE, Color.YELLOW, Color.GRAY};

public IndicatorView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    init();
}

private void init() {
    this.setOrientation(LinearLayout.HORIZONTAL);
    fillParent();
}

private void fillParent() {
    for(int i = 0;i<6;i++) {
        TextView textView = new TextView(getContext());
        textView.setText("i");
        textView.setBackgroundColor(mColors[i]);
        textView.setLayoutParams(new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1.0F));
        this.addView(textView);
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int desiredWidth = this.getChildAt(0).getWidth() + getPaddingLeft() + getPaddingRight();

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int indicatorViewWidth = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int indicatorViewHeight = MeasureSpec.getSize(heightMeasureSpec);
    switch (widthMode) {
        case MeasureSpec.EXACTLY:
            break;
        case MeasureSpec.AT_MOST:
            indicatorViewWidth = Math.min(desiredWidth, indicatorViewWidth);
            break;
        case MeasureSpec.UNSPECIFIED:
            indicatorViewWidth = desiredWidth;
            break;
    }

    setMeasuredDimension(indicatorViewWidth,indicatorViewHeight);
}
</code>```

}

This is the result in Android M:
enter image description here
.This is the result in Android N:
enter image description here
.The desiredWidth is always 0 see in Log.
I know there are some changes in View's measure method after Android N, but what's wrong in my code & how to solve it ?

答:
Change to

```<code>int desiredWidth = this.getChildAt(0).getMeasureWidth() + getPaddingLeft() + getPaddingRight();
</code>```

the problem can be solved.

Body:
my custom view code:

public class IndicatorView extends LinearLayout {
private int[] mColors = new int[]{Color.RED, Color.GREEN, Color.MAGENTA, Color.BLUE, Color.YELLOW, Color.GRAY};

public IndicatorView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    init();
}

private void init() {
    this.setOrientation(LinearLayout.HORIZONTAL);
    fillParent();
}

private void fillParent() {
    for(int i = 0;i<6;i++) {
        TextView textView = new TextView(getContext());
        textView.setText("i");
        textView.setBackgroundColor(mColors[i]);
        textView.setLayoutParams(new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1.0F));
        this.addView(textView);
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int desiredWidth = this.getChildAt(0).getWidth() + getPaddingLeft() + getPaddingRight();

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int indicatorViewWidth = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int indicatorViewHeight = MeasureSpec.getSize(heightMeasureSpec);
    switch (widthMode) {
        case MeasureSpec.EXACTLY:
            break;
        case MeasureSpec.AT_MOST:
            indicatorViewWidth = Math.min(desiredWidth, indicatorViewWidth);
            break;
        case MeasureSpec.UNSPECIFIED:
            indicatorViewWidth = desiredWidth;
            break;
    }

    setMeasuredDimension(indicatorViewWidth,indicatorViewHeight);
}

}

This is the result in Android M:
enter image description here
.This is the result in Android N:
enter image description here
.The desiredWidth is always 0 see in Log.
I know there are some changes in View's measure method after Android N, but what's wrong in my code & how to solve it ?

Body:
Change to

int desiredWidth = this.getChildAt(0).getMeasureWidth() + getPaddingLeft() + getPaddingRight();

the problem can be solved.


问:
is there an alternative to window iteration in Selenium?
I'm currently making automated tests for an application which opens up and uses a lot of windows. I'm trying to figure out a way to switch between these windows and focus in the most recent opened one but iterating through the window handles and comparing the title or URL is just too slow for us since this application opens so many windows!

Have you guys found a way to do this without the regular approach of getting the windowHandles and iterating through it?
Thanks a lot!

答:
getWindowHandles() returns LinkedHashSet witch maintains insertion order. The last opened window will be the last item in the Set. The Set interface itself doesn't have an option to get last item but you can do something like

```<code>Set<String> windowHandles = driver.getWindowHandles();
String lastWindow = windowHandles.toArray()[windowHandles.size() - 1];
driver.switchTo().window(lastWindow);
</code>```

Body:
getWindowHandles() returns LinkedHashSet witch maintains insertion order. The last opened window will be the last item in the Set. The Set interface itself doesn't have an option to get last item but you can do something like

Set<String> windowHandles = driver.getWindowHandles();
String lastWindow = windowHandles.toArray()[windowHandles.size() - 1];
driver.switchTo().window(lastWindow);


问:
Sharepoint change Content Type in Sharepoint Designer using workflow
i trying to change document content type. I must use workflow, and the best way will by workflow create in sharepoint desingner. I know how do it programatical in visual studio</p>

答:
I'm pretty sure you can't, certainly not from a SP Designer workflow.

You have to remember that there is no way SharePoint can be sure that the two contenttypes (before and after) have the same sorts of columns, and even if they did, couldn't easily map values from the old contenttype to the new.

Since you noted you can program in Visual Studio, I checked your options with regard to the SharePoint object model. There's no method available on either an SPListItem or an SPFile with which to change the associated contenttype. So, as far as I know, you'd be reduced to reading the values from the old listitem and creating a new one (with the new contenttype association), using custom code.

I'm not sure if that's something I'd wanna do, besides the fact that you'd lose the Created and Modified information from the old listitem.

But yeah, that's your only option, I think...

ContentLicense: CC BY-SA 2.5


问:
How to get Selected Text in WebView Android
I am developing an application in which I need the get the selected text.

I have a custom contextual action bar, that shows up when user selects a text in webview. I want to get highlighted text under selection handlers, on click of my action bar button.

Question was previously asked,
How to get the selected text in android webview.

But had no solution.

I am trying something like myWebView.getSelection()

答:
I posted an answer to a similar question. Sharing it here for quick access to the answer.

For API >= 19 you can use evaluateJavascript

```<code>mWebview.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
    @Override
    public void onReceiveValue(String value)
    {
        Log.v(TAG, "Webview selected text: " + value);
    }
});
</code>```

For API < 19 you can use evaluateJavascript you use the loadUrl method like below:

```<code>mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.addJavascriptInterface(new JavaScriptInterface(), "javascriptinterface");
</code>```

Then when you want to get the selection use the following:

mWebview.loadUrl("javascript:javascriptinterface.callback(window.getSelection().toString())");

And define a WebAppInterface class as below:

```<code>public class JavaScriptInterface
{
    @JavascriptInterface
    public void callback(String value)
    {
        Log.v(TAG, "SELECTION:" + value);
    }
}
</code>```

Body:
I posted an answer to a similar question. Sharing it here for quick access to the answer.

For API >= 19 you can use evaluateJavascript

mWebview.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
    @Override
    public void onReceiveValue(String value)
    {
        Log.v(TAG, "Webview selected text: " + value);
    }
});

For API < 19 you can use evaluateJavascript you use the loadUrl method like below:

mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.addJavascriptInterface(new JavaScriptInterface(), "javascriptinterface");

Then when you want to get the selection use the following:

mWebview.loadUrl("javascript:javascriptinterface.callback(window.getSelection().toString())");

And define a WebAppInterface class as below:

public class JavaScriptInterface
{
    @JavascriptInterface
    public void callback(String value)
    {
        Log.v(TAG, "SELECTION:" + value);
    }
}


问:
Laravel multiple routes file for api
I am working on a API for 2 client application, mobile application and angular2 admin panel.

If I write the routes for both application in a single default routes/api.php, this will be very huge.

So, I want to split the api routes file as :

routes/admin.api.php for angular app

routes/app.api.php for mobile app

I have modified the RouteServiceProvide as below

```<code><?php

namespace App\Providers;

use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    protected $namespace = 'App\Http\Controllers';

    public function boot()
    {
        //

        parent::boot();
    }

    public function map()
    {
        $this->mapAdminApiRoutes();

        $this->mapApiRoutes();

        $this->mapWebRoutes();

        //
    }

    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }

    protected function mapApiRoutes()
    {
        Route::prefix('api/v1')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }

    protected function mapAdminApiRoutes()
    {
        Route::prefix('api/v1')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/admin.api.php'));
    }
}
</code>```

I'm getting the following error

```<code>(1/1) FatalErrorException
Illuminate\Routing\Router::loadRoutes(): Failed opening required 'D:\Workspace\Project Izzmart\izzmart\routes/api.php' (include_path='.;C:\php\pear')
in Router.php (line 329)
</code>```

答:
create two route files: admin.api.php and app.api.php.

edit the RouteServiceProvider.php file as below:

    <?php

    namespace App\Providers;

    use Illuminate\Support\Facades\Route;

    class RouteServiceProvider extends ServiceProvider
    {
        protected $namespace = 'App\Http\Controllers';
        protected $apiNamespace = 'App\Http\Controllers\Api\v1';

        public function boot()
        {

            parent::boot();
        }

        public function map(Router $router) {
            $router->group(['namespace' => $this->namespace], function ($router) {
                require app_path('Http/routes/web.php');
            });
            $router->group(['namespace' => $this->apiNamespace], function ($router) {
                require app_path('Http/api.php');
            });
            $router->group(['namespace' => $this->apiNamespace], function ($router) {
                require app_path('Http/admin.api.php');
            });
        }

    }
```

For more detail see here.

Title: Laravel multiple routes file for api

Body:
I am working on a API for 2 client application, mobile application and angular2 admin panel.

If I write the routes for both application in a single default routes/api.php, this will be very huge.

So, I want to split the api routes file as :

routes/admin.api.php for angular app

routes/app.api.php for mobile app

I have modified the RouteServiceProvide as below

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    protected $namespace = 'App\Http\Controllers';

    public function boot()
    {
        //

        parent::boot();
    }

    public function map()
    {
        $this->mapAdminApiRoutes();

        $this->mapApiRoutes();

        $this->mapWebRoutes();

        //
    }

    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }

    protected function mapApiRoutes()
    {
        Route::prefix('api/v1')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }

    protected function mapAdminApiRoutes()
    {
        Route::prefix('api/v1')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/admin.api.php'));
    }
}

I'm getting the following error

(1/1) FatalErrorException
Illuminate\Routing\Router::loadRoutes(): Failed opening required 'D:\Workspace\Project Izzmart\izzmart\routes/api.php' (include_path='.;C:\php\pear')
in Router.php (line 329)

Body:
create two route files: admin.api.php and app.api.php.

edit the RouteServiceProvider.php file as below:

    <?php

    namespace App\Providers;

    use Illuminate\Support\Facades\Route;

    class RouteServiceProvider extends ServiceProvider
    {
        protected $namespace = 'App\Http\Controllers';
        protected $apiNamespace = 'App\Http\Controllers\Api\v1';

        public function boot()
        {

            parent::boot();
        }

        public function map(Router $router) {
            $router->group(['namespace' => $this->namespace], function ($router) {
                require app_path('Http/routes/web.php');
            });
            $router->group(['namespace' => $this->apiNamespace], function ($router) {
                require app_path('Http/api.php');
            });
            $router->group(['namespace' => $this->apiNamespace], function ($router) {
                require app_path('Http/admin.api.php');
            });
        }

    }

For more detail see here.

ContentLicense: CC BY-SA 4.0


答:
Default arguments are evaluated at call time, meaning the function getValue invoked every time you invoke add - not when the code is initially run. Since you're using postfix increment, getValue will return 5 the first time you invoke add, then 6, 7, etc. Postfix increment returns the previous value, then increments, for example:

```<code>var x = 5
var foo = x++;
</code>```

Here, foo is given the value 5, then x is incremented. Thus, in your example, the getValue function is actually returning 5 instead 6, then incrementing value when you first invoke it. If you want 6, 7, 8, use prefix increment which returns the value after incrementing:

```<code>++x;
</code>```

This will increment value, then return that incremented value. You could even use compound addition:

```<code>x += 1;
</code>```

This explicitly reassigns x before you access it again. Further reading on those operators here.

Title: Why doesn't this ES6 default argument value give the desired result?

Body:
Default arguments are evaluated at call time, meaning the function getValue invoked every time you invoke add - not when the code is initially run. Since you're using postfix increment, getValue will return 5 the first time you invoke add, then 6, 7, etc. Postfix increment returns the previous value, then increments, for example:

var x = 5
var foo = x++;

Here, foo is given the value 5, then x is incremented. Thus, in your example, the getValue function is actually returning 5 instead 6, then incrementing value when you first invoke it. If you want 6, 7, 8, use prefix increment which returns the value after incrementing:

++x;

This will increment value, then return that incremented value. You could even use compound addition:

x += 1;

This explicitly reassigns x before you access it again. Further reading on those operators here.


问:
Is there an Objective-C equivalent to Swift's fatalError?
I want to discard superclass's default init method.I can achieve this easily with fatalError in Swift:

```<code>class subClass:NSObject{
  private var k:String!

  override init(){
    fatalError("init() has not been implemented")
  }

  init(kk:String){
    k = kk
  }
}
</code>```

How can I do it in Objective-C?

答:
```<code>NSAssert(NO, @"balabala");
</code>```

or

```<code>- (instancetype)init NS_UNAVAILABLE;
</code>```

========== Update ==========

Thanks to @Cœur

NSAssert is disabled by default in production, which is different with FatalError. NSException is better.

Body:
I want to discard superclass's default init method.I can achieve this easily with fatalError in Swift:

class subClass:NSObject{
  private var k:String!

  override init(){
    fatalError("init() has not been implemented")
  }

  init(kk:String){
    k = kk
  }
}

How can I do it in Objective-C?

Body:
NSAssert(NO, @"balabala");

or

- (instancetype)init NS_UNAVAILABLE;

========== Update ==========

Thanks to @Cœur

NSAssert is disabled by default in production, which is different with FatalError. NSException is better.


问:
ADT plugin install sticks at 49% on Eclipse Classic 3.6
I am having a strange problem that the ADT plugin installation sticks at 49% on Eclipse Classic 3.6 for infinite time, as shown below...

Please help me out to solve this problem...

Thanks..

答:
I installed a fresh Eclipse 3.6 just yesterday and also noticed this dialog froze up... until I moved the mouse pointer within it, at which point it magically woke up and continued.

To complete installation of ADT etc I merely had to wiggle the mouse a few dozen times on top of the dialog box. It was very odd behaviour, never saw 3.5 doing that.


问:
rbind.fill error in train() function in R caret package
A similar question was closed and the solution accepted was to check if the package caret was installed correctly. As instructed in the solutions I checked if caret package was installed and loaded correctly. I have reloaded the package and it is available in the current session. The following lines using train(...) is producing the error:

```<code>model <- train(
price ~ ., diamonds,
method = "lm",
trControl = trainControl(
    method = "cv", number = 10
    , verboseIter = TRUE
))
</code>```

Here I am trying to train and cross validate the famous diamonds dataset on a linear model. However, the following error is observed:

```<code>Error: All inputs to rbind.fill must be data.frames
</code>```

It doesn't provide any further information about the error. My warnings are on. Is there any way I can debug this?

答: I copy pasted your code in my console and it worked just fine. Try updating your caret package.</p>

Body:
A similar question was closed and the solution accepted was to check if the package caret was installed correctly. As instructed in the solutions I checked if caret package was installed and loaded correctly. I have reloaded the package and it is available in the current session. The following lines using train(...) is producing the error:

model <- train(
price ~ ., diamonds,
method = "lm",
trControl = trainControl(
    method = "cv", number = 10
    , verboseIter = TRUE
))

Here I am trying to train and cross validate the famous diamonds dataset on a linear model. However, the following error is observed:

Error: All inputs to rbind.fill must be data.frames

It doesn't provide any further information about the error. My warnings are on. Is there any way I can debug this?


问:
JPA how to avoid updating associated entity in @ManyToOne or @OneToOne
I have two entities like this:

```<code>@Entity
@Table(name = "article")
@EntityListeners({AuditingEntityListener.class})
public class Notification implements Serializable {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private Integer id;

    @OneToMany(mappedBy = "notification", cascade = {CascadeType.PERSIST})
    private List<NotificationLang> langs;

    @OneToMany(mappedBy = "notification", cascade = {CascadeType.PERSIST})
    private List<NotificationTarget> targets;

    @LastModifiedDate
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updated_at")
    private Date updatedAt;

    @CreatedDate
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_at")
    private Date createdAt;

}

@Entity
@Table(name = "article_count")
@EntityListeners({AuditingEntityListener.class})
public class NotificationTarget implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonIgnore
    private Integer id;

    @Column(name = "user_id")
    private String userId;

    @ManyToOne(optional = false)
    @JoinColumn(name = "notification_id")
    private Notification notification;
}
</code>```

Notification and NotificationTarget are associated, If I update NotificationTarget:

```<code>NotificationTarget notificationTarget = notificationTargetRepository.findByNotificationIdAndUserId(
        notificationId, userId);
notificationTarget.setUserId(userId);
notificationTargetRepository.save(notificationTarget);
</code>```

hibernate will update Notification too.
I have checked update Notification because Notification has EntityListener,  AuditingEntityListener will change updatedAt field when DefaultFlushEntityEventListener invoke Interceptor. But in this business case, I don't want to change Notification when updating NotificationTarget, is there some advice?

Sorry, I think the problem describe is wrong.

I debugged and found that update both because of NotificationLang list is check as dirty in CollectionType.isEqual. But I don't know why it is dirty??

答:
You have added cascade = {CascadeType.PERSIST} to targets in Notification class, this will propagate persistence operations to all the related entity managers.

Just remove it.

Body:
I have two entities like this:

@Entity
@Table(name = "article")
@EntityListeners({AuditingEntityListener.class})
public class Notification implements Serializable {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private Integer id;

    @OneToMany(mappedBy = "notification", cascade = {CascadeType.PERSIST})
    private List<NotificationLang> langs;

    @OneToMany(mappedBy = "notification", cascade = {CascadeType.PERSIST})
    private List<NotificationTarget> targets;

    @LastModifiedDate
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updated_at")
    private Date updatedAt;

    @CreatedDate
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_at")
    private Date createdAt;

}

@Entity
@Table(name = "article_count")
@EntityListeners({AuditingEntityListener.class})
public class NotificationTarget implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonIgnore
    private Integer id;

    @Column(name = "user_id")
    private String userId;

    @ManyToOne(optional = false)
    @JoinColumn(name = "notification_id")
    private Notification notification;
}

Notification and NotificationTarget are associated, If I update NotificationTarget:

NotificationTarget notificationTarget = notificationTargetRepository.findByNotificationIdAndUserId(
        notificationId, userId);
notificationTarget.setUserId(userId);
notificationTargetRepository.save(notificationTarget);

hibernate will update Notification too.
I have checked update Notification because Notification has EntityListener,  AuditingEntityListener will change updatedAt field when DefaultFlushEntityEventListener invoke Interceptor. But in this business case, I don't want to change Notification when updating NotificationTarget, is there some advice?

Sorry, I think the problem describe is wrong.

I debugged and found that update both because of NotificationLang list is check as dirty in CollectionType.isEqual. But I don't know why it is dirty??


问:
Android Recyclerview GridLayoutManager column spacing
How do you set the column spacing with a RecyclerView using a GridLayoutManager?
 Setting the margin/padding inside my layout has no effect.</p>

答:
If you want to FIXED the size of your RecyclerView item in all devices. You can do like this

```<code>public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int mSpanCount;
    private float mItemSize;

    public GridSpacingItemDecoration(int spanCount, int itemSize) {
        this.mSpanCount = spanCount;
        mItemSize = itemSize;
    }

    @Override
    public void getItemOffsets(final Rect outRect, final View view, RecyclerView parent,
            RecyclerView.State state) {
        final int position = parent.getChildLayoutPosition(view);
        final int column = position % mSpanCount;
        final int parentWidth = parent.getWidth();
        int spacing = (int) (parentWidth - (mItemSize * mSpanCount)) / (mSpanCount + 1);
        outRect.left = spacing - column * spacing / mSpanCount;
        outRect.right = (column + 1) * spacing / mSpanCount;

        if (position < mSpanCount) {
            outRect.top = spacing;
        }
        outRect.bottom = spacing;
    }
}
</code>```

recyclerview_item.xml

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="@dimen/recycler_view_item_width"
    ...
    >
    ...
</LinearLayout>
</code>```

dimens.xml

```<code> <dimen name="recycler_view_item_width">60dp</dimen>
</code>```

Activity

```<code>int numberOfColumns = 3;
mRecyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
mRecyclerView.setAdapter(...);
mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(3,
        getResources().getDimensionPixelSize(R.dimen.recycler_view_item_width)));
</code>```

Body:
If you want to FIXED the size of your RecyclerView item in all devices. You can do like this

public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int mSpanCount;
    private float mItemSize;

    public GridSpacingItemDecoration(int spanCount, int itemSize) {
        this.mSpanCount = spanCount;
        mItemSize = itemSize;
    }

    @Override
    public void getItemOffsets(final Rect outRect, final View view, RecyclerView parent,
            RecyclerView.State state) {
        final int position = parent.getChildLayoutPosition(view);
        final int column = position % mSpanCount;
        final int parentWidth = parent.getWidth();
        int spacing = (int) (parentWidth - (mItemSize * mSpanCount)) / (mSpanCount + 1);
        outRect.left = spacing - column * spacing / mSpanCount;
        outRect.right = (column + 1) * spacing / mSpanCount;

        if (position < mSpanCount) {
            outRect.top = spacing;
        }
        outRect.bottom = spacing;
    }
}

recyclerview_item.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="@dimen/recycler_view_item_width"
    ...
    >
    ...
</LinearLayout>

dimens.xml

 <dimen name="recycler_view_item_width">60dp</dimen>

Activity

int numberOfColumns = 3;
mRecyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
mRecyclerView.setAdapter(...);
mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(3,
        getResources().getDimensionPixelSize(R.dimen.recycler_view_item_width)));


问:
Multipe action="" attribute urls
I am wanting to know if you can add more than one url in the action attribute in the form element? I know a lot of people are asking that but the ones I am adding in are: a php self and a mailto action. This is a feedback form so when any one sends some feedback it should check the php of validation of it and send a email at the same time once the submit button is clicked. But I tested that but when I clicked the submit button it came up as an error page. Can any one please help me?

HTML:

```<code><form action="<?php echo htmlspecialchars($_server['php_self']);?>
    , mailto:example@gmail.com" method="post" name="feedbackForm" id="ff" class="feedback"> <label for="first">First Name:</label>
    <input type="text" id="first" name="fname" class="namef" placeholder="First Name" required="required"/><span class="error"><?php echo $fnameErr;?>
    </span><br/>
    <label for="last">Last Name:</label>
    <input type="text" id="last" name="lname" class="namel" placeholder="Last Name" required="required"/><span class="error"><?php echo $lnameErr;?>
    </span><br/>
    <label for="mail">Email:</label>
    <input type="email" id="mail" name="email" class="u-email" placeholder="any email is fine!" required="required"/><span class="error"><?php echo
    $emailErr;?>
    </span><br/>
    <label for="yearLevel">Year Level:</label>
    <select name="yearLevel" id="yearLevel" onchange="MM_jumpMenu('parent',this,0)">
        <option>Year 8</option>
        <option>Year 9</option>
        <option>Year 10</option>
        <option>Year 11</option>
        <option>Year 12</option>
        <option>Uni Student</option>
        <option>Other</option>
    </select>
    <label for"comment">Comment:</label>
    <textarea id="comment" name="comment" class="userComment" rows="12" cols="" "55" ">
    </textarea><br/><br/>
    <input type="submit" name="submitFeed" id="subff" class="sub" onclick="ask()" style="margin-left:20%;"/>
</form>
</code>```

PHP:

```<code><?php
//feedback form validation code
//start

//variables
$fnameErr = $lnameErr = $yearleErr = $emailErr = "";
$firstName = $lastName = $comment = $yearLevel = $email = "";

//the function of validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["fname"])) {
        $fnameErr = "* Your first name is required!";
    } else {
        $firstName = test_input($_POST["fname"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z]*$/", $firstName)) {
            $fnameErr = "* Only letters and white space allowed!";
        }
    }

    if (empty($_POST["lname"])) {
        $lnameErr = "* Your last name is required!";
    } else {
        $lastName = test_input($_POST["lname"]);
        if (!preg_match("/^[a-zA-Z]*$/", $lastName)) {
            $lnameErr = "* Only letters and white space allowed!";
        }
    }

    if(empty($_POST["comment"])) {
        $comment = "* the comment box is required!";
    } else {
        $comment = test_input($_post["comment"]);
    }

    if (empty($_POST["email"])) {
        $emailErr = "* Your email is required!";
    } else {
        $email = test_input($_POST["email"]);
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
           $emailErr = "* Invalid Email Format!";
        }
    }
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
//end
?>
</code>```

JS script for a confirm when the user clicks submit. so it makes sense to the form.

```<code><script type="text/javascript">
//confrim before submitting.
function ask() {
    var box = confirm("Are you sure you want to send this feeback? If yes
that you are sure click ok or if not then click canel to edit it.");
    if (box == true) {
        document.getElementById('firstPart').style.display = "none";
        document.getElementById('nextPart').style.display = "block";
        console.log("Thanks for sending your feedback");
        return true;
    } else {
        console.log("edit!");
        return false;
    }
}

</script>
</code>```

答:
Simple answer: No, you cannot add multiple actions for  tag, how you would the distinguish between which one to choose?

If you need to select different actions according to some configuration on form choices (or whatever), use Javascript to set new action of form.

In your case, use mail PHP function to send mail from PHP script when you pass your validation.

```<code><form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" name="feedbackForm" id="ff" class="feedback">
</code>```

and then in PHP

```<code>mail('somebody@example.com', 'Subject', 'Body', optionalHeaders);
</code>```

Title: Multipe action="" attribute urls

Body:
I am wanting to know if you can add more than one url in the action attribute in the form element? I know a lot of people are asking that but the ones I am adding in are: a php self and a mailto action. This is a feedback form so when any one sends some feedback it should check the php of validation of it and send a email at the same time once the submit button is clicked. But I tested that but when I clicked the submit button it came up as an error page. Can any one please help me?

HTML:

<form action="<?php echo htmlspecialchars($_server['php_self']);?>
    , mailto:example@gmail.com" method="post" name="feedbackForm" id="ff" class="feedback"> First Name:
    <input type="text" id="first" name="fname" class="namef" placeholder="First Name" required="required"/><?php echo $fnameErr;?>

    Last Name:
    <input type="text" id="last" name="lname" class="namel" placeholder="Last Name" required="required"/><?php echo $lnameErr;?>

    Email:
    <input type="email" id="mail" name="email" class="u-email" placeholder="any email is fine!" required="required"/><?php echo
    $emailErr;?>

    Year Level:
    <select name="yearLevel" id="yearLevel" onchange="MM_jumpMenu('parent',this,0)">
        <option>Year 8</option>
        <option>Year 9</option>
        <option>Year 10</option>
        <option>Year 11</option>
        <option>Year 12</option>
        <option>Uni Student</option>
        <option>Other</option>
    </select>
    Comment:
    <textarea id="comment" name="comment" class="userComment" rows="12" cols="" "55" ">
    </textarea>

    <input type="submit" name="submitFeed" id="subff" class="sub" onclick="ask()" style="margin-left:20%;"/>
</form>

PHP:

<?php
//feedback form validation code
//start

//variables
$fnameErr = $lnameErr = $yearleErr = $emailErr = "";
$firstName = $lastName = $comment = $yearLevel = $email = "";

//the function of validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["fname"])) {
        $fnameErr = "* Your first name is required!";
    } else {
        $firstName = test_input($_POST["fname"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z]*$/", $firstName)) {
            $fnameErr = "* Only letters and white space allowed!";
        }
    }

    if (empty($_POST["lname"])) {
        $lnameErr = "* Your last name is required!";
    } else {
        $lastName = test_input($_POST["lname"]);
        if (!preg_match("/^[a-zA-Z]*$/", $lastName)) {
            $lnameErr = "* Only letters and white space allowed!";
        }
    }

    if(empty($_POST["comment"])) {
        $comment = "* the comment box is required!";
    } else {
        $comment = test_input($_post["comment"]);
    }

    if (empty($_POST["email"])) {
        $emailErr = "* Your email is required!";
    } else {
        $email = test_input($_POST["email"]);
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
           $emailErr = "* Invalid Email Format!";
        }
    }
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
//end
?>

JS script for a confirm when the user clicks submit. so it makes sense to the form.

Body:
Simple answer: No, you cannot add multiple actions for  tag, how you would the distinguish between which one to choose?

If you need to select different actions according to some configuration on form choices (or whatever), use Javascript to set new action of form.

In your case, use mail PHP function to send mail from PHP script when you pass your validation.

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" name="feedbackForm" id="ff" class="feedback">

and then in PHP

mail('somebody@example.com', 'Subject', 'Body', optionalHeaders);


问:
Is there a way to use proxies with scrapy without using middleware?
From searching how to use proxies with scrapy I mostly found solutions that requires me to use some sort of middleware. Is there a way to just have the spider.py file handle the proxy itself when its doing requests? For example, in the Python requests library you can add a proxy argument when creating a request, is there something similar like that when using scrapy?</p>

答:
Without using middleware? No, that's the point of middleware! However scrapy has inbuilt middlewares for that and you don't need to download or enable anything.
You can set proxy for any individual Request via proxy key in meta attribute:

```<code>Request('someurl', meta={'proxy': 'http://some_proxy_server:port'})
</code>```

Checkout HttpProxyMiddleware

Body:
Without using middleware? No, that's the point of middleware! However scrapy has inbuilt middlewares for that and you don't need to download or enable anything.
You can set proxy for any individual Request via proxy key in meta attribute:

Request('someurl', meta={'proxy': 'http://some_proxy_server:port'})

Checkout HttpProxyMiddleware


问:
SQL - char field with date - how to search between two dates
I have simple problem with SQL query.. I would like to search fields, where dates begin and ends in specific date and time.

Field is defined as CHAR and have structure: DD.MM.YYYY hh:mm:ss and I cannot change it.

I tried to declare some variables and search by this, also tried by Converting.

This is what I tried and didn't work:

```<code>SELECT date FROM table WHERE date BETWEEN '1.01.2017 00:00:00' AND '1.02.2017 23:59:59'

SELECT date FROM table WHERE date >= '1.01.2017 00:00:00' AND date <= '1.02.2017 00:00:00'

SELECT date FROM table WHERE date >= Convert(DATETIME, '1.01.2017', 104) AND date <= Convert(DATETIME, '1.02.2017', 104)
</code>```

Always after this query I get all dates, not this what I asked.

答:
```<code>SELECT date FROM table WHERE STR_TO_DATE(date, '%d.%m.%Y %H:%i:%s') BETWEEN '2017-01-01 00:00:00' AND '2017-02-01 23:59:59'
</code>```

OR

You can use STR_TO_DATE() function.

```<code>SELECT date FROM table WHERE STR_TO_DATE(date, '%d.%m.%Y %H:%i:%s') BETWEEN STR_TO_DATE('1.01.2017 00:00:00','%d.%m.%Y %H:%i:%s') AND STR_TO_DATE('1.02.2017 23:59:59','%d.%m.%Y %H:%i:%s')
</code>```

You can try above query.

Body:
I have simple problem with SQL query.. I would like to search fields, where dates begin and ends in specific date and time.

Field is defined as CHAR and have structure: DD.MM.YYYY hh:mm:ss and I cannot change it.

I tried to declare some variables and search by this, also tried by Converting.

This is what I tried and didn't work:

SELECT date FROM table WHERE date BETWEEN '1.01.2017 00:00:00' AND '1.02.2017 23:59:59'

SELECT date FROM table WHERE date >= '1.01.2017 00:00:00' AND date <= '1.02.2017 00:00:00'

SELECT date FROM table WHERE date >= Convert(DATETIME, '1.01.2017', 104) AND date <= Convert(DATETIME, '1.02.2017', 104)

Always after this query I get all dates, not this what I asked.

Body:
SELECT date FROM table WHERE STR_TO_DATE(date, '%d.%m.%Y %H:%i:%s') BETWEEN '2017-01-01 00:00:00' AND '2017-02-01 23:59:59'

OR

You can use STR_TO_DATE() function.

SELECT date FROM table WHERE STR_TO_DATE(date, '%d.%m.%Y %H:%i:%s') BETWEEN STR_TO_DATE('1.01.2017 00:00:00','%d.%m.%Y %H:%i:%s') AND STR_TO_DATE('1.02.2017 23:59:59','%d.%m.%Y %H:%i:%s')

You can try above query.


问:
Echo php with echoed html php
I currently have a php which echo my html template.

However in that HTML template there is another echo which calls from another php script.

Just wondering how do I do that? Because once I echo my html template the other it doesn't seems to echo my content from the other php script.

HTML TEMPLATE

```<code><php? $html = '<span>name:<?php echo $name; ?></span><span>email:<?php echo $email; ?></span>' ?>
</code>```

CONTACT TEMPLATE

```<code><php? $name = "hello world"; $email = "hello@world.com"; ?>
</code>```

答: Try to use include. The include statement includes and evaluates the specified file, in this case - your template.

Title: Echo php with echoed html php

Body:
I currently have a php which echo my html template.

However in that HTML template there is another echo which calls from another php script.

Just wondering how do I do that? Because once I echo my html template the other it doesn't seems to echo my content from the other php script.

HTML TEMPLATE

<php? $html = 'name:<?php echo $name; ?>email:<?php echo $email; ?>' ?>

CONTACT TEMPLATE

<php? $name = "hello world"; $email = "hello@world.com"; ?>


问:
How i can find the exact error?
I am getting the below error. But i am unable to find what the error is.

```<code>Caused by: java.lang.NullPointerException
    at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1481)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1419)
    at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1375)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:717)
    at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
    ... 91 more
</code>```

Thanks in advance.

答:
```<code>Caused by: java.lang.NullPointerException
    at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1481)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1419)
    at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1375)
</code>```

That error means you put an annotation to an object that is missing. Ex: you put @JoinColumn into private Car car but that Car object is nowhere to be found.

Title: How i can find the exact error?

Body:
I am getting the below error. But i am unable to find what the error is.

Caused by: java.lang.NullPointerException
    at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1481)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1419)
    at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1375)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:717)
    at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
    ... 91 more

Thanks in advance.

Body:
Caused by: java.lang.NullPointerException
    at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1481)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1419)
    at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1375)

That error means you put an annotation to an object that is missing. Ex: you put @JoinColumn into private Car car but that Car object is nowhere to be found.


问:
Interop issue in .NET
I have a 32 bit managed assembly that access a 32 bit COM component. When i compile the assembly using the 64 bit flag, i get an error when i try to access the 32 bit COM component from it.

Is there a way around this problem?

答: You should find and install the 64 bit version of this com component. If it is not available, You will have to target your .net application to run as 32 bit application. The com component is running in your process. And you can't run both 32bit and 64bit code together in the same process.</p>

OwnerDisplayName: Nick

Title: Interop issue in .NET

OwnerDisplayName: Igal Serban


问:
Export products table via CSV in CMS
Ive been trying to extend ProductCatalogAdmin, because thats the ModelAdmin that holds the Products I want to export. The code below works fine when added to core code (Which I don't want to do), but fails to do anything when added as an Extension.

PHP

```<code><?php

class ProductCatalogAdminExtension extends DataExtension {

    public function getExportFields() {
            return array(
                'ID' => 'ID',
                'InternalItemID' => 'InternalItemID',
                'Model' => 'Model',
                'Content' => 'Content',
                'CostPrice' => 'CostPrice',
                'BasePrice' => 'BasePrice',
                'Weight' => 'Weight',
                'Height' => 'Height',
                'Width' => 'Width',
                'Depth' => 'Depth',
                'Featured' => 'Featured',
                'AllowPurchase' => 'AllowPurchase',
                'Popularity' => 'Popularity',
                'PromoActive' => 'PromoActive',
                'PromoDisplay' => 'PromoDisplay',
                'PromoType' => 'PromoType',
                'PromoAmount' => 'PromoAmount',
                'PromoPercent' => 'PromoPercent',
                'PromoStartDate' => 'PromoStartDate',
                'PromoEndDate' => 'PromoEndDate',
                'Image.URL' => 'Image',
                'WholesalePrice' => 'WholesalePrice',
                'ParentID' => 'ParentID',
                'ProductCategory.ID' => 'AdditionalCategories'
            );
    }

}
</code>```

YML

```<code>---
Name: mysite
After:
  - 'framework/*'
  - 'cms/*'
---
# YAML configuration for SilverStripe
# See http://doc.silverstripe.org/framework/en/topics/configuration
# Caution: Indentation through two spaces, not tabs
SSViewer:
  theme: 'simple'
SiteConfig:
  extensions:
    - SiteConfigExtension
ProductCatalogAdmin:
  extensions:
    - ProductCatalogAdminExtension
</code>```

I've been told, ModelAdmin's getExportFields() doesn't have an extend() call, so I'll have to use inheritance rather than an Extension. However doing it under inheritance for ModelAdmin seems to do nothing also.
Interestingly I get no error messages, it doesn't really fail.

答:
You could subclass the ProductCatalogAdmin and use Injector, as pointed out by wmk, but you can also use an Extension instead. This works for any ModelAdmin setup:

```<code><?php
class CustomExportExtension extends Extension
{
    private $exportFields = [
        'ID' => 'ID',
        'Reference' => 'Order Number',
        // … all your other fields
    ];

    public function updateEditForm($form) {
        // Get the gridfield for the model we want, in this case 'Product'
        if ($gridField = $form->Fields()->fieldByName('Product')) {
            // Get the export button instance from the GridField config
            if ($exportButton = $gridField->getConfig()->getComponentByType(GridFieldExportButton::class)) {
                // Apply custom export columns to the export button
                $exportButton->setExportColumns($this->exportFields);
            }
        }
    }
}
</code>```

Then just apply the extension to ProductCatalogAdmin, as you did via YML:

```<code>ProductCatalogAdmin:
  extensions:
    - CustomExportExtension
</code>```

You could also rewrite the Extension to be more flexible and re-usable for any ModelAdmin, by making the exportFields part of the DataObject config the extension is being attached to. But for a single use-case like yours the above works just fine.

A reusable approach

Here's a slightly modified Version of the above extension that can be used to configure the export fields on any ModelAdmin, without having to create multiple Extensions.

```<code><?php
class CustomExportExtension extends Extension
{
    private $modelClass = null;

    public function updateEditForm($form)
    {
        // Get the gridfield for the current model
        if ($gridField = $form->Fields()->fieldByName($this->modelClass)) {
            // Get the export button instance from the gridfield config
            if ($exportButton = $gridField->getConfig()->getComponentByType(GridFieldExportButton::class)) {
                // Look for custom exportFields config
                $exportFields = Config::inst()->get($this->modelClass, 'exportFields');
                // If custom exportFields aren't set, fall back to summaryfields
                if (!$exportFields || !is_array($exportFields)) {
                    $exportFields = $this->owner->getExportFields();
                }
                $exportButton->setExportColumns($exportFields);
            }
        }
    }

    public function onBeforeInit() {
        // Grab the current model-class from the controller
        $this->modelClass = $this->owner->getRequest()->param('ModelClass');
    }
}
</code>```

This extension looks for a config setting exportFields on the model that should be exported. If none is given, the default summary_fields are being used.

Here's how you could apply that extension to different ModelAdmins:

```<code># In your YML File
ProductCatalogAdmin:
  extensions:
    - CustomExportExtension

Product:
  exportFields:
    ID: ID
    Model: Model
    # More fields to export

OrdersAdmin:
  extensions:
    - CustomExportExtension

Order:
  exportFields:
    ID: ID
    Reference: 'Order Number'
    # More fields to export
</code>```

Title: Export products table via CSV in CMS

Body:
Ive been trying to extend ProductCatalogAdmin, because thats the ModelAdmin that holds the Products I want to export. The code below works fine when added to core code (Which I don't want to do), but fails to do anything when added as an Extension.

PHP

<?php

class ProductCatalogAdminExtension extends DataExtension {

    public function getExportFields() {
            return array(
                'ID' => 'ID',
                'InternalItemID' => 'InternalItemID',
                'Model' => 'Model',
                'Content' => 'Content',
                'CostPrice' => 'CostPrice',
                'BasePrice' => 'BasePrice',
                'Weight' => 'Weight',
                'Height' => 'Height',
                'Width' => 'Width',
                'Depth' => 'Depth',
                'Featured' => 'Featured',
                'AllowPurchase' => 'AllowPurchase',
                'Popularity' => 'Popularity',
                'PromoActive' => 'PromoActive',
                'PromoDisplay' => 'PromoDisplay',
                'PromoType' => 'PromoType',
                'PromoAmount' => 'PromoAmount',
                'PromoPercent' => 'PromoPercent',
                'PromoStartDate' => 'PromoStartDate',
                'PromoEndDate' => 'PromoEndDate',
                'Image.URL' => 'Image',
                'WholesalePrice' => 'WholesalePrice',
                'ParentID' => 'ParentID',
                'ProductCategory.ID' => 'AdditionalCategories'
            );
    }

}

YML

---
Name: mysite
After:
  - 'framework/*'
  - 'cms/*'
---
# YAML configuration for SilverStripe
# See http://doc.silverstripe.org/framework/en/topics/configuration
# Caution: Indentation through two spaces, not tabs
SSViewer:
  theme: 'simple'
SiteConfig:
  extensions:
    - SiteConfigExtension
ProductCatalogAdmin:
  extensions:
    - ProductCatalogAdminExtension

I've been told, ModelAdmin's getExportFields() doesn't have an extend() call, so I'll have to use inheritance rather than an Extension. However doing it under inheritance for ModelAdmin seems to do nothing also.
Interestingly I get no error messages, it doesn't really fail.

Body:
You could subclass the ProductCatalogAdmin and use Injector, as pointed out by wmk, but you can also use an Extension instead. This works for any ModelAdmin setup:

<?php
class CustomExportExtension extends Extension
{
    private $exportFields = [
        'ID' => 'ID',
        'Reference' => 'Order Number',
        // … all your other fields
    ];

    public function updateEditForm($form) {
        // Get the gridfield for the model we want, in this case 'Product'
        if ($gridField = $form->Fields()->fieldByName('Product')) {
            // Get the export button instance from the GridField config
            if ($exportButton = $gridField->getConfig()->getComponentByType(GridFieldExportButton::class)) {
                // Apply custom export columns to the export button
                $exportButton->setExportColumns($this->exportFields);
            }
        }
    }
}

Then just apply the extension to ProductCatalogAdmin, as you did via YML:

ProductCatalogAdmin:
  extensions:
    - CustomExportExtension

You could also rewrite the Extension to be more flexible and re-usable for any ModelAdmin, by making the exportFields part of the DataObject config the extension is being attached to. But for a single use-case like yours the above works just fine.

A reusable approach

Here's a slightly modified Version of the above extension that can be used to configure the export fields on any ModelAdmin, without having to create multiple Extensions.

<?php
class CustomExportExtension extends Extension
{
    private $modelClass = null;

    public function updateEditForm($form)
    {
        // Get the gridfield for the current model
        if ($gridField = $form->Fields()->fieldByName($this->modelClass)) {
            // Get the export button instance from the gridfield config
            if ($exportButton = $gridField->getConfig()->getComponentByType(GridFieldExportButton::class)) {
                // Look for custom exportFields config
                $exportFields = Config::inst()->get($this->modelClass, 'exportFields');
                // If custom exportFields aren't set, fall back to summaryfields
                if (!$exportFields || !is_array($exportFields)) {
                    $exportFields = $this->owner->getExportFields();
                }
                $exportButton->setExportColumns($exportFields);
            }
        }
    }

    public function onBeforeInit() {
        // Grab the current model-class from the controller
        $this->modelClass = $this->owner->getRequest()->param('ModelClass');
    }
}

This extension looks for a config setting exportFields on the model that should be exported. If none is given, the default summary_fields are being used.

Here's how you could apply that extension to different ModelAdmins:

# In your YML File
ProductCatalogAdmin:
  extensions:
    - CustomExportExtension

Product:
  exportFields:
    ID: ID
    Model: Model
    # More fields to export

OrdersAdmin:
  extensions:
    - CustomExportExtension

Order:
  exportFields:
    ID: ID
    Reference: 'Order Number'
    # More fields to export


问:
Laravel Cashier: should I add a trial period in Stripe too?
Quoting Laravel Cashier documentation:

If you would like to offer trial periods to your customers while still collecting payment method information up front, You should use the trialDays method when creating your subscriptions.

Assuming I want to add a 30 days trial period to my subscriptions, I can create a subscription with this code:

```<code>$user->newSubscription('main', 'monthly')
        ->trialDays(30)
        ->create($stripeToken);
</code>```

As a Stripe user, should I add a trial period in Stripe plan too?

I'm not sure to understand the logic of Laravel Cashier here. It seems redundant to declare something at two different places.

答: If you define a trial period in stripe then there is no need to do it in code. If you you don't want trial every time someone subscribes you might want to have it in code. </p>

Body:
Quoting Laravel Cashier documentation:

If you would like to offer trial periods to your customers while still collecting payment method information up front, You should use the trialDays method when creating your subscriptions.

Assuming I want to add a 30 days trial period to my subscriptions, I can create a subscription with this code:

$user->newSubscription('main', 'monthly')
        ->trialDays(30)
        ->create($stripeToken);

As a Stripe user, should I add a trial period in Stripe plan too?

I'm not sure to understand the logic of Laravel Cashier here. It seems redundant to declare something at two different places.


问:
How to not return null value in sql server?
I have this data set like shown below;

Company | Address | Business            | Telephone Number | Contact Person

```<code>A&B     | Perak   | Khmer Restaurants   | 012541           | Mr. Yu Lee
A&B     | Perak   | F&B                 | 012541           | Mr. Yu Lee
King Co.| Ipoh    | Paper Distributors  | 021453           | Mrs. Cheng
King Co.| Ipoh    | Paper Distributors  | Null             | Mrs. Cheng
DinoX   | Sunway  | Guesthouses         | 0124587          | Mr. Hong
Dinox   | Sunway  | Guesthouses         | 0124587          | Mr. Q
</code>```

After making some query like shown below, i get a new dataset :

```<code>IF OBJECT_ID('tempdb..#tCat') IS NOT NULL DROP TABLE #tcat
GO
DECLARE @portal varchar(100) = 'A4E7890F-A188-4663-89EB-176D94DF6774'
SELECT * INTO #tcat
FROM (
SELECT DISTINCT  list.[name]
                ,lc.listing_uuid
                ,dCat.[name]  as Category
                ,catg.[name]  as Sub_Category
                ,comm.[value] as Telephone_Number
                ,pp.title + ' ' + pp.first_name + ' ' + pp.last_name as Contact_Person
FROM panpages.listings as list
LEFT JOIN panpages.listing_categories as lc on lc.listing_uuid=list.uuid AND lc.portal_uuid=@portal
LEFT JOIN panpages.categories as catg on catg.uuid=lc.category_uuid AND catg.portal_uuid=@portal
left join panpages.listing_people as lp on lp.listing_uuid = list.uuid
left join panpages.people as pp on pp.id = lp.person_id
left join panpages.person_communications as comm on comm.person_id = lp.person_id and (comm.communication_type = 'Mobile Phone' or comm.communication_type = 'Tel')
LEFT JOIN ( SELECT DISTINCT uuid,[name] FROM panpages.categories WHERE parent_uuid IS NULL ) as dCat on dCat.uuid=catg.parent_uuid
WHERE list.portal_uuid=@portal and list.is_active=1
)as tCat

select
     list.[name] as [Company]
    ,list.[address] as [Address]
    ,replace(cats.Sub_Category,'&','&')     as [Nature of Business]
    ,replace(cats.Telephone_Number,'&','&') as [Telephone Number]
    ,replace(cats.Contact_Person,'&','&')   as [Contact Person]

from [panpages].[listings] as list
left join (

            SELECT DISTINCT tc1.listing_uuid,tc1.[name],
            Sub_Category = STUFF(( SELECT   ',   ' + tc2.Sub_Category
            FROM
                (
                SELECT Sub_Category, MIN(listing_uuid) AS listing_uuid
                FROM #tCat
                GROUP BY Sub_Category
                ) AS tc2
                WHERE tc1.listing_uuid = tc2.listing_uuid
                ORDER BY tc2.Sub_Category
                FOR XML PATH('')), 1, 1, ''),
            Telephone_Number = STUFF(( SELECT   ',  ' + tc2.Telephone_Number
            FROM
                (
                SELECT Telephone_Number, MAX(listing_uuid) AS listing_uuid
                FROM #tCat
                GROUP BY Telephone_Number
                ) AS tc2
                WHERE tc1.listing_uuid = tc2.listing_uuid
                ORDER BY tc2.Telephone_Number
                FOR XML PATH('')), 1, 1, ''),
            Contact_Person = STUFF(( SELECT   ',  ' + tc2.Contact_Person
            FROM
                (
                SELECT Contact_Person, MAX(listing_uuid) AS listing_uuid
                FROM #tCat
                GROUP BY Contact_Person
                ) AS tc2
                WHERE tc1.listing_uuid = tc2.listing_uuid
                ORDER BY tc2.Contact_Person
                FOR XML PATH('')), 1, 1, '')
            FROM #tCat as tc1 where tc1.listing_uuid is not null
        ) cats on cats.listing_uuid=list.uuid
where
    list.[portal_uuid]=@portal and
    list.[is_active]=1
</code>```

And below is the new dataset :

```<code>Company |Address| Business              | Telephone Number | Contact Person

A&B     | Perak | Khmer Restaurants, F&B| 012541           | Mr. Yu Lee
King Co.| Ipoh  | Paper Distributors    | 021453, Null     | Mrs. Cheng
DinoX   | Sunway| Guesthouses           | 0124587          | Mr. Hong, Mr Q
</code>```

How to not return the null value? I dont want to return the "Null" value.

答:
You can either use ISNULL function prior to check or you can use COALESCE function as below

```<code>   SELECT COALESCE(Telephone_Number,''), MAX(listing_uuid) AS listing_uuid
</code>```

Replace whatever you want to return within ' '. If you just want an empty string, leave it at ''

Body:
I have this data set like shown below;

Company | Address | Business            | Telephone Number | Contact Person

A&B     | Perak   | Khmer Restaurants   | 012541           | Mr. Yu Lee
A&B     | Perak   | F&B                 | 012541           | Mr. Yu Lee
King Co.| Ipoh    | Paper Distributors  | 021453           | Mrs. Cheng
King Co.| Ipoh    | Paper Distributors  | Null             | Mrs. Cheng
DinoX   | Sunway  | Guesthouses         | 0124587          | Mr. Hong
Dinox   | Sunway  | Guesthouses         | 0124587          | Mr. Q

After making some query like shown below, i get a new dataset :

IF OBJECT_ID('tempdb..#tCat') IS NOT NULL DROP TABLE #tcat
GO
DECLARE @portal varchar(100) = 'A4E7890F-A188-4663-89EB-176D94DF6774'
SELECT * INTO #tcat
FROM (
SELECT DISTINCT  list.[name]
                ,lc.listing_uuid
                ,dCat.[name]  as Category
                ,catg.[name]  as Sub_Category
                ,comm.[value] as Telephone_Number
                ,pp.title + ' ' + pp.first_name + ' ' + pp.last_name as Contact_Person
FROM panpages.listings as list
LEFT JOIN panpages.listing_categories as lc on lc.listing_uuid=list.uuid AND lc.portal_uuid=@portal
LEFT JOIN panpages.categories as catg on catg.uuid=lc.category_uuid AND catg.portal_uuid=@portal
left join panpages.listing_people as lp on lp.listing_uuid = list.uuid
left join panpages.people as pp on pp.id = lp.person_id
left join panpages.person_communications as comm on comm.person_id = lp.person_id and (comm.communication_type = 'Mobile Phone' or comm.communication_type = 'Tel')
LEFT JOIN ( SELECT DISTINCT uuid,[name] FROM panpages.categories WHERE parent_uuid IS NULL ) as dCat on dCat.uuid=catg.parent_uuid
WHERE list.portal_uuid=@portal and list.is_active=1
)as tCat

select
     list.[name] as [Company]
    ,list.[address] as [Address]
    ,replace(cats.Sub_Category,'&','&')     as [Nature of Business]
    ,replace(cats.Telephone_Number,'&','&') as [Telephone Number]
    ,replace(cats.Contact_Person,'&','&')   as [Contact Person]

from [panpages].[listings] as list
left join (

            SELECT DISTINCT tc1.listing_uuid,tc1.[name],
            Sub_Category = STUFF(( SELECT   ',   ' + tc2.Sub_Category
            FROM
                (
                SELECT Sub_Category, MIN(listing_uuid) AS listing_uuid
                FROM #tCat
                GROUP BY Sub_Category
                ) AS tc2
                WHERE tc1.listing_uuid = tc2.listing_uuid
                ORDER BY tc2.Sub_Category
                FOR XML PATH('')), 1, 1, ''),
            Telephone_Number = STUFF(( SELECT   ',  ' + tc2.Telephone_Number
            FROM
                (
                SELECT Telephone_Number, MAX(listing_uuid) AS listing_uuid
                FROM #tCat
                GROUP BY Telephone_Number
                ) AS tc2
                WHERE tc1.listing_uuid = tc2.listing_uuid
                ORDER BY tc2.Telephone_Number
                FOR XML PATH('')), 1, 1, ''),
            Contact_Person = STUFF(( SELECT   ',  ' + tc2.Contact_Person
            FROM
                (
                SELECT Contact_Person, MAX(listing_uuid) AS listing_uuid
                FROM #tCat
                GROUP BY Contact_Person
                ) AS tc2
                WHERE tc1.listing_uuid = tc2.listing_uuid
                ORDER BY tc2.Contact_Person
                FOR XML PATH('')), 1, 1, '')
            FROM #tCat as tc1 where tc1.listing_uuid is not null
        ) cats on cats.listing_uuid=list.uuid
where
    list.[portal_uuid]=@portal and
    list.[is_active]=1

And below is the new dataset :

Company |Address| Business              | Telephone Number | Contact Person

A&B     | Perak | Khmer Restaurants, F&B| 012541           | Mr. Yu Lee
King Co.| Ipoh  | Paper Distributors    | 021453, Null     | Mrs. Cheng
DinoX   | Sunway| Guesthouses           | 0124587          | Mr. Hong, Mr Q

How to not return the null value? I dont want to return the "Null" value.

Body:
You can either use ISNULL function prior to check or you can use COALESCE function as below

   SELECT COALESCE(Telephone_Number,''), MAX(listing_uuid) AS listing_uuid

Replace whatever you want to return within ' '. If you just want an empty string, leave it at ''


问:
Variable init in Go
I see following code (I simplified it a bit).

```<code>func getEndpoints(db *sqlx.DB) s.Endpoints {
    var endpoints s.Endpoints
    {
        repository := acl.NewRepository(db)
        service := stat.NewService(repository)
        endpoints = s.Endpoints{
            GetEndpoint: s.MakeEndpoint(service),
        }
    }

    return endpoints
}
</code>```

If I understand this code correctly, code inside var endpoints s.Endpoints{...} is executed line by line and endpoints = s.Endpoints ... line initialises var endpoints variable declared above.

I suppose that it's correct to rewrite it like this (correct me if I'm wrong):

```<code>func getEndpoints(db *sqlx.DB) s.Endpoints {

    repository := acl.NewRepository(db)
    service := stat.NewService(repository)
    endpoints := s.Endpoints{
        GetEndpoint: s.MakeEndpoint(service),
    }

    return endpoints
}
</code>```

So can somebody explain me why initialisation is written inside var endpoints s.Endpoints{...}. Is there any idea to do it like this? Am I missing something?

答:
They are equivalent.

The {...} block has nothing to do with the variable declaration with the var keyword. It just happens to be written one after the other.

The {...} is a simple block, nothing else. The var declaration does not require that block, and even if there is one, it is not related to the variable declaration. You can insert a block wherever you would insert a statement.

The rare case when an explicit block is used (when there isn't required one) is to group statements, and to control the scope of the variables and other identifiers declared inside them, because the scope of the variables end at the end of the innermost containing block (Spec: Declarations and Scope).

Title: Variable init in Go

Body:
I see following code (I simplified it a bit).

func getEndpoints(db *sqlx.DB) s.Endpoints {
    var endpoints s.Endpoints
    {
        repository := acl.NewRepository(db)
        service := stat.NewService(repository)
        endpoints = s.Endpoints{
            GetEndpoint: s.MakeEndpoint(service),
        }
    }

    return endpoints
}

If I understand this code correctly, code inside var endpoints s.Endpoints{...} is executed line by line and endpoints = s.Endpoints ... line initialises var endpoints variable declared above.

I suppose that it's correct to rewrite it like this (correct me if I'm wrong):

func getEndpoints(db *sqlx.DB) s.Endpoints {

    repository := acl.NewRepository(db)
    service := stat.NewService(repository)
    endpoints := s.Endpoints{
        GetEndpoint: s.MakeEndpoint(service),
    }

    return endpoints
}

So can somebody explain me why initialisation is written inside var endpoints s.Endpoints{...}. Is there any idea to do it like this? Am I missing something?


问:
Typescript keyof object recursively
Is it possible to have strong type from key object in Typescript recursively?

Here is example code I have.

```<code>const test = {
  name: 'abc',
  author: {
    email: 'abc@example.com',
    url: 'http://example.com/'
  }
}

type AType = keyof typeof test
type AObjectKeyToValue = {
  [K in AType]: K  // <- K is just the keys!
}
</code>```

And then I want to create new variable that used type of AObjectKeyToValue so I can get power autocomplete from that.

```<code>const b: AObjectKeyToValue
b.
  ▾▾▾
  name
  author
</code>```

As you can see, I got autocomplete exactly like what I need. But my problem is coming when I need get autocomplete from author child.

```<code>const b: AObjectKeyToValue
b.author.
         ▾▾▾
         // Just string property. Can't find `email` and `url`
</code>```

How to write good types, so I can get email and url keys when access b.author.?

答:
We can create a type from a value (that is determined at compile time), and use it for other values:</p>

```<code>let b: typeof test = ...;
b.author.email // will be of type "string"
</code>```

Title: Typescript keyof object recursively

Body:
Is it possible to have strong type from key object in Typescript recursively?

Here is example code I have.

const test = {
  name: 'abc',
  author: {
    email: 'abc@example.com',
    url: 'http://example.com/'
  }
}

type AType = keyof typeof test
type AObjectKeyToValue = {
  [K in AType]: K  // <- K is just the keys!
}

And then I want to create new variable that used type of AObjectKeyToValue so I can get power autocomplete from that.

const b: AObjectKeyToValue
b.
  ▾▾▾
  name
  author

As you can see, I got autocomplete exactly like what I need. But my problem is coming when I need get autocomplete from author child.

const b: AObjectKeyToValue
b.author.
         ▾▾▾
         // Just string property. Can't find `email` and `url`

How to write good types, so I can get email and url keys when access b.author.?

Body:
We can create a type from a value (that is determined at compile time), and use it for other values:

let b: typeof test = ...;
b.author.email // will be of type "string"


问:
Spring - Loading XML bean definitions from class path resource [Beans.xml]- NoClassDefFoundError
I'm a newbie for Spring and I was referring to this tutorial for my first Spring project. After follow all the instruction, I try to run the program but I'm having this error.

```<code>May 26, 2015 11:42:45 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@31221be2: startup date [Tue May 26 11:42:45 CST 2015]; root of context hierarchy
May 26, 2015 11:42:45 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/expression/ParserContext
    at org.springframework.context.support.AbstractApplicationContext.prepareBeanFactory(AbstractApplicationContext.java:553)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:455)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.tutorialspoint.MainApp.main(MainApp.java:9)
Caused by: java.lang.ClassNotFoundException: org.springframework.expression.ParserContext
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 5 more
</code>```

Any idea where I did the wrong. As I know I was following the tutorial correctly.

CODE

```<code>package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
             new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

      obj.getMessage();
   }
}
</code>```

Beans.XML

```<code><?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="helloWorld" class="com.tutorialspoint.HelloWorld">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>
</code>```

答:
I was having the same issue. But I found my mistake.

My mistake was, I created "Beans.xml" inside com.tutorialspont package.

The solution for me was "Beans.xml" has to be created directly under src folder.

Body:
I'm a newbie for Spring and I was referring to this tutorial for my first Spring project. After follow all the instruction, I try to run the program but I'm having this error.

May 26, 2015 11:42:45 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@31221be2: startup date [Tue May 26 11:42:45 CST 2015]; root of context hierarchy
May 26, 2015 11:42:45 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/expression/ParserContext
    at org.springframework.context.support.AbstractApplicationContext.prepareBeanFactory(AbstractApplicationContext.java:553)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:455)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.tutorialspoint.MainApp.main(MainApp.java:9)
Caused by: java.lang.ClassNotFoundException: org.springframework.expression.ParserContext
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 5 more

Any idea where I did the wrong. As I know I was following the tutorial correctly.

CODE

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =
             new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

      obj.getMessage();
   }
}

Beans.XML

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="helloWorld" class="com.tutorialspoint.HelloWorld">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>


问:
Laravel how to get the average of two result values
So I have a query that return all the stats of a player from their last season and current season. What I want to do is get the average of a player from last season and current season and make in to a one object only. Below is my query and sample result.

Query

```<code>public static function getAllTimeLeaders($request) {
        $competitionIds = self::getLasTwoSeason();
        $data = DB::table('leader_board_stats as lbs')
            ->select([
                'sGamesStarted',
                'sMinutesAverage',
                'sPointsAverage',
                'sFieldGoalsMadeAverage',
                'sFieldGoalsAttemptedAverage',
                'sFieldGoalsPercentage',
                'sTwoPointersMadeAverage',
                'sTwoPointersAttemptedAverage',
                'sThreePointersMadeAverage',
                'sThreePointersAttemptedAverage',
                'sThreePointersPercentage',
                'sFreeThrowsMadeAverage',
                'sFreeThrowsAttemptedAverage',
                'sReboundsTotalAverage',
                'sAssistsAverage',
                'sStealsAverage',
                'sBlocksAverage',
                'sTurnoversAverage',
                'sFoulsPersonalAverage',
                'firstName',
                'familyName',
                'personId',
                'teamId',
                'competitionId'
            ])
            ->where('lbs.periodNumber', '0')
            ->whereIn('lbs.competitionId', [$competitionIds[0]->competitionId, $competitionIds[1]->competitionId])
            ->get();
        echo '```';
        var_dump($data);
    }
```

<p><strong>Sample of returned value</strong></p>

```[
    [0]=> object(stdClass)#262 (24) {
      ["sGamesStarted"]=>
      int(6)
      ["sMinutesAverage"]=>
      float(17.66)
      ["sPointsAverage"]=>
      float(7.71)
      ["sFieldGoalsMadeAverage"]=>
      float(2.59)
      ["sFieldGoalsAttemptedAverage"]=>
      float(5.62)
      ["sFieldGoalsPercentage"]=>
      float(0.46)
      ["sTwoPointersMadeAverage"]=>
      float(1.47)
      ["sTwoPointersAttemptedAverage"]=>
      float(2.53)
      ["sThreePointersMadeAverage"]=>
      float(1.12)
      ["sThreePointersAttemptedAverage"]=>
      float(3.09)
      ["sThreePointersPercentage"]=>
      float(0.36)
      ["sFreeThrowsMadeAverage"]=>
      float(1.41)
      ["sFreeThrowsAttemptedAverage"]=>
      float(1.76)
      ["sReboundsTotalAverage"]=>
      float(2.85)
      ["sAssistsAverage"]=>
      float(1.71)
      ["sStealsAverage"]=>
      float(0.68)
      ["sBlocksAverage"]=>
      float(0.21)
      ["sTurnoversAverage"]=>
      float(0.91)
      ["sFoulsPersonalAverage"]=>
      float(2.35)
      ["firstName"]=>
      string(3) "Person1"
      ["familyName"]=>
      string(8) "Familyname"
      ["personId"]=>
      int(28831)
      ["teamId"]=>
      int(3749)
      ["competitionId"]=>
      int(9224)
    },
    [88]=> object(stdClass)#527 (24) {
      ["sGamesStarted"]=>
      int(11)
      ["sMinutesAverage"]=>
      float(23.28)
      ["sPointsAverage"]=>
      float(9.5)
      ["sFieldGoalsMadeAverage"]=>
      float(3.07)
      ["sFieldGoalsAttemptedAverage"]=>
      float(7.97)
      ["sFieldGoalsPercentage"]=>
      float(0.38)
      ["sTwoPointersMadeAverage"]=>
      float(1.4)
      ["sTwoPointersAttemptedAverage"]=>
      float(3.47)
      ["sThreePointersMadeAverage"]=>
      float(1.67)
      ["sThreePointersAttemptedAverage"]=>
      float(4.5)
      ["sThreePointersPercentage"]=>
      float(0.37)
      ["sFreeThrowsMadeAverage"]=>
      float(1.7)
      ["sFreeThrowsAttemptedAverage"]=>
      float(2.2)
      ["sReboundsTotalAverage"]=>
      float(3.57)
      ["sAssistsAverage"]=>
      float(1.43)
      ["sStealsAverage"]=>
      float(0.93)
      ["sBlocksAverage"]=>
      float(0.23)
      ["sTurnoversAverage"]=>
      float(0.97)
      ["sFoulsPersonalAverage"]=>
      float(2.77)
      ["firstName"]=>
      string(3) "Person1"
      ["familyName"]=>
      string(8) "Familyname"
      ["personId"]=>
      int(28831)
      ["teamId"]=>
      int(3749)
      ["competitionId"]=>
      int(2254)
    }
]
```

答:
Try: avg() is easier and cleaner.

Docs: https://laravel.com/docs/5.4/collections#method-avg

Body:
So I have a query that return all the stats of a player from their last season and current season. What I want to do is get the average of a player from last season and current season and make in to a one object only. Below is my query and sample result.

Query

public static function getAllTimeLeaders($request) {
        $competitionIds = self::getLasTwoSeason();
        $data = DB::table('leader_board_stats as lbs')
            ->select([
                'sGamesStarted',
                'sMinutesAverage',
                'sPointsAverage',
                'sFieldGoalsMadeAverage',
                'sFieldGoalsAttemptedAverage',
                'sFieldGoalsPercentage',
                'sTwoPointersMadeAverage',
                'sTwoPointersAttemptedAverage',
                'sThreePointersMadeAverage',
                'sThreePointersAttemptedAverage',
                'sThreePointersPercentage',
                'sFreeThrowsMadeAverage',
                'sFreeThrowsAttemptedAverage',
                'sReboundsTotalAverage',
                'sAssistsAverage',
                'sStealsAverage',
                'sBlocksAverage',
                'sTurnoversAverage',
                'sFoulsPersonalAverage',
                'firstName',
                'familyName',
                'personId',
                'teamId',
                'competitionId'
            ])
            ->where('lbs.periodNumber', '0')
            ->whereIn('lbs.competitionId', [$competitionIds[0]->competitionId, $competitionIds[1]->competitionId])
            ->get();
        echo '
';
        var_dump($data);
    }

Sample of returned value

[
    [0]=> object(stdClass)#262 (24) {
      ["sGamesStarted"]=>
      int(6)
      ["sMinutesAverage"]=>
      float(17.66)
      ["sPointsAverage"]=>
      float(7.71)
      ["sFieldGoalsMadeAverage"]=>
      float(2.59)
      ["sFieldGoalsAttemptedAverage"]=>
      float(5.62)
      ["sFieldGoalsPercentage"]=>
      float(0.46)
      ["sTwoPointersMadeAverage"]=>
      float(1.47)
      ["sTwoPointersAttemptedAverage"]=>
      float(2.53)
      ["sThreePointersMadeAverage"]=>
      float(1.12)
      ["sThreePointersAttemptedAverage"]=>
      float(3.09)
      ["sThreePointersPercentage"]=>
      float(0.36)
      ["sFreeThrowsMadeAverage"]=>
      float(1.41)
      ["sFreeThrowsAttemptedAverage"]=>
      float(1.76)
      ["sReboundsTotalAverage"]=>
      float(2.85)
      ["sAssistsAverage"]=>
      float(1.71)
      ["sStealsAverage"]=>
      float(0.68)
      ["sBlocksAverage"]=>
      float(0.21)
      ["sTurnoversAverage"]=>
      float(0.91)
      ["sFoulsPersonalAverage"]=>
      float(2.35)
      ["firstName"]=>
      string(3) "Person1"
      ["familyName"]=>
      string(8) "Familyname"
      ["personId"]=>
      int(28831)
      ["teamId"]=>
      int(3749)
      ["competitionId"]=>
      int(9224)
    },
    [88]=> object(stdClass)#527 (24) {
      ["sGamesStarted"]=>
      int(11)
      ["sMinutesAverage"]=>
      float(23.28)
      ["sPointsAverage"]=>
      float(9.5)
      ["sFieldGoalsMadeAverage"]=>
      float(3.07)
      ["sFieldGoalsAttemptedAverage"]=>
      float(7.97)
      ["sFieldGoalsPercentage"]=>
      float(0.38)
      ["sTwoPointersMadeAverage"]=>
      float(1.4)
      ["sTwoPointersAttemptedAverage"]=>
      float(3.47)
      ["sThreePointersMadeAverage"]=>
      float(1.67)
      ["sThreePointersAttemptedAverage"]=>
      float(4.5)
      ["sThreePointersPercentage"]=>
      float(0.37)
      ["sFreeThrowsMadeAverage"]=>
      float(1.7)
      ["sFreeThrowsAttemptedAverage"]=>
      float(2.2)
      ["sReboundsTotalAverage"]=>
      float(3.57)
      ["sAssistsAverage"]=>
      float(1.43)
      ["sStealsAverage"]=>
      float(0.93)
      ["sBlocksAverage"]=>
      float(0.23)
      ["sTurnoversAverage"]=>
      float(0.97)
      ["sFoulsPersonalAverage"]=>
      float(2.77)
      ["firstName"]=>
      string(3) "Person1"
      ["familyName"]=>
      string(8) "Familyname"
      ["personId"]=>
      int(28831)
      ["teamId"]=>
      int(3749)
      ["competitionId"]=>
      int(2254)
    }
]


问:
PHP/MySQL Show first X results, hide the rest
Does anyone know how to bring in all of a mysql tables' results, only show the first X, (say 10), and then hide the rest using jquery? I just need to know how to show only the first X results in one page, then the rest in a seperate page using href.

My aim is to only show the first 10 results, but provide a link at the bottom of the page allowing the user to show all of the results. Was thinking the hyperlink could just re-execute the query but thought it would be easier to show/hide using jquery.Thanks

答:
Rather than using jquery, you can use MySQL to retrieve only the desired results.

```<code>SELECT * FROM TableName LIMIT 10
</code>```

That will retreive the first 10 results. Then, to display the next 10 on the next page,

```<code>SELECT * FROM TableName LIMIT 10 OFFSET 10
</code>```

and the next page

```<code>SELECT * FROM TableName LIMIT 10 OFFSET 20
</code>```

If you are using PHP, you can build your query to show the correct results depending on which page you are on:

```<code>// $currentPage is set elsewhere in the script, and is zero-based.
$resultsPerPage = 10;

$currentOffset = $resultsInPage * $currentPage;
$query = "SELECT * FROM TableName LIMIT $resultsInPage OFFSET $currentOffset";
</code>```

Body:
Rather than using jquery, you can use MySQL to retrieve only the desired results.

SELECT * FROM TableName LIMIT 10

That will retreive the first 10 results. Then, to display the next 10 on the next page,

SELECT * FROM TableName LIMIT 10 OFFSET 10

and the next page

SELECT * FROM TableName LIMIT 10 OFFSET 20

If you are using PHP, you can build your query to show the correct results depending on which page you are on:

// $currentPage is set elsewhere in the script, and is zero-based.
$resultsPerPage = 10;

$currentOffset = $resultsInPage * $currentPage;
$query = "SELECT * FROM TableName LIMIT $resultsInPage OFFSET $currentOffset";