问:
PHP: Syntax error, unexpected '<<' (T_SL)
I am trying to create a backend REST API using php Laravel, but I encountered the strange error from my title in the following code:

```<code>Route::get('/', function () {
    return view('main');
});

 Route::group(['prefix' => 'api'], function () {
            // Authentication Routes
            Route::post('/login', 'Auth\LoginController@login');
            Route::post('/logout', 'Auth\LoginController@logout');
            Route::post('/register', 'Auth\RegisterController@store');
            Route::post('/register/student', 'Auth\RegisterStudentController@store');

            // Model routes
            Route::resource('/internships', 'InternshipController');
            Route::resource('/companies', 'CompanyController');
            Route::resource('/students', 'StudentController');
        });
</code>```

At the following line:

```<code>Route::post('/register', 'Auth\RegisterController@store');
</code>```

I'm getting this error:

Syntax error, unexpected '<<' (T_SL)

The problem is that I don't have any  << in this line. I tried to delete the line, but the error moves just before });, on the last ;.

What am I doing wrong?

答:
T_SL references to <<.

You should not use tabs or spaces before you use END;

Body:
I am trying to create a backend REST API using php Laravel, but I encountered the strange error from my title in the following code:

Route::get('/', function () {
    return view('main');
});

 Route::group(['prefix' => 'api'], function () {
            // Authentication Routes
            Route::post('/login', 'Auth\LoginController@login');
            Route::post('/logout', 'Auth\LoginController@logout');
            Route::post('/register', 'Auth\RegisterController@store');
            Route::post('/register/student', 'Auth\RegisterStudentController@store');

            // Model routes
            Route::resource('/internships', 'InternshipController');
            Route::resource('/companies', 'CompanyController');
            Route::resource('/students', 'StudentController');
        });

At the following line:

Route::post('/register', 'Auth\RegisterController@store');

I'm getting this error:

Syntax error, unexpected '<<' (T_SL)

The problem is that I don't have any  << in this line. I tried to delete the line, but the error moves just before });, on the last ;.

What am I doing wrong?


来源: stackexchange

问:
How can I pass props down in Angular 2+ like React?
In react I can arbitrarily pass props down like so:

```<code>function SomeComponent(props) {
  const {takeOutProp, ...restOfProps} = props;
  return <div {...restOfProps}/>;
}
</code>```

How can I do the same thing in Angular?

--

More specifically, I want to write a custom dropdown component and pass props down to a select box.

答:
As opposed to React components, Angular components aren't recompiled on input changes and use @Input property decorators to enable change detection. All properties that are expected to be passed should be explicitly defined as component inputs.

There are no better options than this one for custom select component. It's possible to read static attributes from current component element and set them on nested component element, but this won't set up bindings.

As for React recipe for deep props in wrapped components:

```<code>const Baz = props => <p>{props.baz}</p>;
const Bar = props => <Baz {...props} />;
const Foo = props => <Bar {...props} />;
</code>```

This is usually handled by Angular DI and a hierarchy of injectors. A provider can be defined on respective injector in order to make data and behaviour available to nested components.

ContentLicense: CC BY-SA 3.0

Body:
In react I can arbitrarily pass props down like so:

function SomeComponent(props) {
  const {takeOutProp, ...restOfProps} = props;
  return
;
}

How can I do the same thing in Angular?

--

More specifically, I want to write a custom dropdown component and pass props down to a select box.

Body:
As opposed to React components, Angular components aren't recompiled on input changes and use @Input property decorators to enable change detection. All properties that are expected to be passed should be explicitly defined as component inputs.

There are no better options than this one for custom select component. It's possible to read static attributes from current component element and set them on nested component element, but this won't set up bindings.

As for React recipe for deep props in wrapped components:

const Baz = props => <p>{props.baz}</p>;
const Bar = props => <Baz {...props} />;
const Foo = props => <Bar {...props} />;

This is usually handled by Angular DI and a hierarchy of injectors. A provider can be defined on respective injector in order to make data and behaviour available to nested components.


问:
Passing an inner array to a function
I am trying to pass an inner array to a function in Perl.
Here is my Perl program.

```<code>#!/usr/bin/perl
use strict;
use warnings;

my %data = (
    'a' => (
        x => 'Hello',
        y => 'World'
    ),
    'b' => (
        x => 'Foo',
        y => 'Bar'
    )
);

#prototype
sub p(\%);

{ #main
    p(%data{'a'}); # should print "Hello Wolrd".
}

sub p(\%) {
    print "$_[0]{x} $_[0]{y}\n";
}
</code>```

Instead, I get the following error: Type of arg 1 to main::p must be hash (not key/value hash slice).

This works:

```<code>#!/usr/bin/perl
use strict;
use warnings;

#prototype
sub p(\%);

{ #main
    my %a = (
        x => 'Hello',
        y => 'World'
    );
    p(%a);
}

sub p(\%) {
    print "$_[0]{x} $_[0]{y}\n";
}
</code>```

So there must be something wrong with the method call. But what? The content of a is a hash, so the first character after p( must be % (I tried p($data{'a'}); too, but it leaves me with another error (which seems logical, since the content of a isn’t a scalar). I do not have to manually create a reference to the hash and dereference because I declare the function prototype. What am I missing?

答:
Your definition of the structure is wrong. Inner hashes need to use {}, not ().

```<code>my %data = (
    a => {
        x => 'Hello',
        y => 'World'
    },
    b => {
        x => 'Foo',
        y => 'Bar'
    }
);
</code>```

Also, to get a single hash element, use $data{'a'} (or even $data{a}), not %data{'a'}.

Moreover, see Why are Perl 5's function prototypes bad? on why not to use prototypes. After correcting the syntax as above, the code works even without the prototype. If you really need the prototype, use %, not \%. But you clearly don't know exactly what purpose prototypes serve, so don't use them.

Title: Passing an inner array to a function

Body:
I am trying to pass an inner array to a function in Perl.
Here is my Perl program.

#!/usr/bin/perl
use strict;
use warnings;

my %data = (
    'a' => (
        x => 'Hello',
        y => 'World'
    ),
    'b' => (
        x => 'Foo',
        y => 'Bar'
    )
);

#prototype
sub p(\%);

{ #main
    p(%data{'a'}); # should print "Hello Wolrd".
}

sub p(\%) {
    print "$_[0]{x} $_[0]{y}\n";
}

Instead, I get the following error: Type of arg 1 to main::p must be hash (not key/value hash slice).

This works:

#!/usr/bin/perl
use strict;
use warnings;

#prototype
sub p(\%);

{ #main
    my %a = (
        x => 'Hello',
        y => 'World'
    );
    p(%a);
}

sub p(\%) {
    print "$_[0]{x} $_[0]{y}\n";
}

So there must be something wrong with the method call. But what? The content of a is a hash, so the first character after p( must be % (I tried p($data{'a'}); too, but it leaves me with another error (which seems logical, since the content of a isn’t a scalar). I do not have to manually create a reference to the hash and dereference because I declare the function prototype. What am I missing?

Body:
Your definition of the structure is wrong. Inner hashes need to use {}, not ().

my %data = (
    a => {
        x => 'Hello',
        y => 'World'
    },
    b => {
        x => 'Foo',
        y => 'Bar'
    }
);

Also, to get a single hash element, use $data{'a'} (or even $data{a}), not %data{'a'}.

Moreover, see Why are Perl 5's function prototypes bad? on why not to use prototypes. After correcting the syntax as above, the code works even without the prototype. If you really need the prototype, use %, not \%. But you clearly don't know exactly what purpose prototypes serve, so don't use them.


问:
How to better structure an Array of Arrays in JSON
In the following JSON object:

```<code>var employees = { "accounting" : [   // accounting is an array in employees.
                                { "firstName" : "John",  // First element
                                  "lastName"  : "Doe",
                                  "age"       : 23 },

                                { "firstName" : "Mary",  // Second Element
                                  "lastName"  : "Smith",
                                  "age"       : 32 }
                              ], // End "accounting" array.
              "sales"       : [ // Sales is another array in employees.
                                { "firstName" : "Sally", // First Element
                                  "lastName"  : "Green",
                                  "age"       : 27 },

                                { "firstName" : "Jim",   // Second Element
                                  "lastName"  : "Galley",
                                  "age"       : 41 }
                              ] // End "sales" Array.
            } // End Employees
</code>```

How do I restructure the object so I can access each employee first name like this:

```<code>employees[0].firstName
employees[1].firstName
// etc
</code>```

答:
It would require restructuring it so that you'd eliminate the "accounting/sales" properties and make employees an Array of Objects.

Example: http://jsfiddle.net/hgMXw/

```<code>var employees = [
    {
    "dept": "accounting", // new property for this object
    "firstName": "John",
    // First element
    "lastName": "Doe",
    "age": 23
    },
    {
    "dept": "accounting", // new property for this object
    "firstName": "Mary",
    // Second Element
    "lastName": "Smith",
    "age": 32
    },
    {
    "dept": "sales", // new property for this object
    "firstName": "Sally",
    // Third Element
    "lastName": "Green",
    "age": 27
    },
    {
    "dept": "sales", // new property for this object
    "firstName": "Jim",
    // Fourth Element
    "lastName": "Galley",
    "age": 41
    }
]
</code>```

Body:
In the following JSON object:

var employees = { "accounting" : [   // accounting is an array in employees.
                                { "firstName" : "John",  // First element
                                  "lastName"  : "Doe",
                                  "age"       : 23 },

                                { "firstName" : "Mary",  // Second Element
                                  "lastName"  : "Smith",
                                  "age"       : 32 }
                              ], // End "accounting" array.
              "sales"       : [ // Sales is another array in employees.
                                { "firstName" : "Sally", // First Element
                                  "lastName"  : "Green",
                                  "age"       : 27 },

                                { "firstName" : "Jim",   // Second Element
                                  "lastName"  : "Galley",
                                  "age"       : 41 }
                              ] // End "sales" Array.
            } // End Employees

How do I restructure the object so I can access each employee first name like this:

employees[0].firstName
employees[1].firstName
// etc

Body:
It would require restructuring it so that you'd eliminate the "accounting/sales" properties and make employees an Array of Objects.

Example: http://jsfiddle.net/hgMXw/

var employees = [
    {
    "dept": "accounting", // new property for this object
    "firstName": "John",
    // First element
    "lastName": "Doe",
    "age": 23
    },
    {
    "dept": "accounting", // new property for this object
    "firstName": "Mary",
    // Second Element
    "lastName": "Smith",
    "age": 32
    },
    {
    "dept": "sales", // new property for this object
    "firstName": "Sally",
    // Third Element
    "lastName": "Green",
    "age": 27
    },
    {
    "dept": "sales", // new property for this object
    "firstName": "Jim",
    // Fourth Element
    "lastName": "Galley",
    "age": 41
    }
]


问:
can someone please explain how this jquery code works
i picked this code online but i'm unable to understand how it works. without understanding i cannot edit it for my use. it is for closing a panel by up-slide when i click on "x" button. i want to know how is the effect created in the script?
here is the html:

```<code><div class="col-md-3 col-sm-6 col-xs-6">
    <div class="panel panel-info">
        <div class="panel-heading">
            <h3 class="panel-title">Using Slide Up</h3>
            <span class="pull-right clickable" data-effect="slideUp">x</span>
        </div>
        <div class="panel-body">Panel content</div>
        <div class="panel-footer">Panel footer</div>
    </div>
</div>
</code>```

the script working on this is:

```<code>    $(function() {
        $('.clickable').on('click', function() {
            var effect = $(this).data('effect');
            $(this).closest('.panel')[effect]();
        });
    });
</code>```

答:
It's very simple. This is the jQuery code. There is a click event bound to all elements with class clickable:

```<code>$('.clickable').on('click', function() {...});
</code>```

Then you want to know what effect you would like to have. To do so, you take the data-effect attribute value:

```<code>var effect = $(this).data('effect'); // returns 'slideUp'
</code>```

At the end, you want to slide up the closest element with class panel attached to it:

```<code>$(this).closest('.panel')[effect]();
</code>```

I understand that this part may be kind of hard to understand. The trick here is that you keep the effect name in a variable. And want to call the method with that name on the .panel element. This is how you do it in JS- you put the variable in square brackets and append parentheses. This way you call the .slideUp() method. It is evaluated to something like this:

```<code>$(this).closest('.panel').slideUp();
</code>```

Also, I suggest you read something about jQuery: https://api.jquery.com/

Body:
i picked this code online but i'm unable to understand how it works. without understanding i cannot edit it for my use. it is for closing a panel by up-slide when i click on "x" button. i want to know how is the effect created in the script?
here is the html:

Using Slide Up

            x

Panel content

Panel footer

the script working on this is:

    $(function() {
        $('.clickable').on('click', function() {
            var effect = $(this).data('effect');
            $(this).closest('.panel')[effect]();
        });
    });

Body:
It's very simple. This is the jQuery code. There is a click event bound to all elements with class clickable:

$('.clickable').on('click', function() {...});

Then you want to know what effect you would like to have. To do so, you take the data-effect attribute value:

var effect = $(this).data('effect'); // returns 'slideUp'

At the end, you want to slide up the closest element with class panel attached to it:

$(this).closest('.panel')[effect]();

I understand that this part may be kind of hard to understand. The trick here is that you keep the effect name in a variable. And want to call the method with that name on the .panel element. This is how you do it in JS- you put the variable in square brackets and append parentheses. This way you call the .slideUp() method. It is evaluated to something like this:

$(this).closest('.panel').slideUp();

Also, I suggest you read something about jQuery: https://api.jquery.com/


问:
chrome inspect blinking with remote debugging
I'm trying to use Chrome's support for remote debugging with my Android device. I've been successful doing this many times, even though it is a bit tricky to setup up.

(I need 'port forwarding' and 'virtual host mapping' so my device can access domain names on my local server.)

The problem is that (today) chrome://inspect shows the tabs on my device for only a second, then hides them, then shows them again, then hides them...

When Chrome hides all the tabs on my device, the following message appears:

Pending authentication: please accept debugging session on the device.

Bad Blink

Good Blink

I see no notification on my device that I can 'accept'.

Even stranger, if I am quick to click on my host, I actually seem to be able to able to use the dev tools for the device like in previous successful situations.

Why is chrome://inspect blinking and how can I fix it?

My setup

Device: Android 5.0 Galaxy S4 for AT&T, with Developer options enabled.

Device's wifi settings require Proxy, with info for Charles running on host.

Device connected via USB.

chrome://inspect has Port Forwarding enabled.

Chrome: Version 44.0.2403.157 m.

Android bridge performed by starting Android Studio (version 1.3.1).

答:
You just have to upload your chrome for android, and it will work.

I also came across this problem, but as I updated my chrome for android, the problem got sorted out and now it is working fine.


问:
XSLT / Muenchian grouping: how to select element with certain sub-element from group?
I would like to be able to select one element from group of duplicates (done with Muenchian grouping) having certain sub-element. My XML looks like this:

```<code><waybill>
<shipment>
    <parcel>
        <sscc>SSCC1</sscc>
        <consignee>Receiver1</consignee>
        <date>Date1</date>
        <status>Status1</status>
    </parcel>
    <parcel>
        <sscc>SSCC2</sscc>
        <consignee>Receiver2</consignee>
        <attention>Note2</attention>
    </parcel>
    <parcel>
        <sscc>SSCC3</sscc>
        <consignee>Receiver3</consignee>
    </parcel>
    <parcel>
        <sscc>SSCC4</sscc>
        <consignee>Receiver4</consignee>
    </parcel>
    <parcel>
        <sscc>SSCC1</sscc>
        <consignee>Receiver1</consignee>
        <attention>Note1</attention>
        <date>Date2</date>
        <status>Status2</status>
    </parcel>
    <parcel>
        <sscc>SSCC3</sscc>
        <consignee>Receiver3</consignee>
        <attention>Note3</attention>
    </parcel>
</shipment>
</waybill>
</code>```

and my XSLT looks like this:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" version="2.0">
<xsl:output method="text" version="1.0" encoding="ISO-8859-1" indent="yes"/>
<xsl:key name="ean" match="parcel" use="sscc"/>
<xsl:template match="/">
    <xsl:for-each select="/waybill/shipment/parcel[generate-id()=generate-id(key('ean',sscc))]">
        <xsl:value-of select="current()/sscc"/>
        <xsl:text>§</xsl:text>
        <xsl:value-of select="current()/consignee"/>
        <xsl:text>§</xsl:text>
        <xsl:value-of select="current()/attention"/>
        <xsl:text>
</xsl:text>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code>```

The output now looks like this:

```<code>SSCC1§Receiver1§
SSCC2§Receiver2§Note2
SSCC3§Receiver3§
SSCC4§Receiver4§
</code>```

so my XSLT will now pick the first hit from the grouped elements and what I would like to have as a the result is:

```<code>SSCC1§Receiver1§Note1
SSCC2§Receiver2§Note2
SSCC3§Receiver3§Note3
SSCC4§Receiver4§
</code>```

So the XSLT should find those duplicates from group with has the most data. Not first or last one, but the one with certain sub-element (or in my final case: sub-sub-element)

In this case not all of the element has the sub-element (here SSCC4) and those should be used with the data they have (should not be ignored).

What is the correct way to find the "best" element from the grouped similar elements?

Any help is highly appreciated :)

答:
You can navigate from the key(), like this:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" version="2.0">
    <xsl:output method="text" version="1.0" encoding="ISO-8859-1" indent="yes"/>
    <xsl:key name="ean" match="parcel" use="sscc"/>

    <xsl:template match="/">
        <xsl:for-each select="/waybill/shipment/parcel[generate-id()=generate-id(key('ean',sscc))]">
            <xsl:variable name="group" select="key('ean',sscc)" />
            <xsl:value-of select="sscc"/>
            <xsl:text>§</xsl:text>
            <xsl:value-of select="$group/consignee"/>
            <xsl:text>§</xsl:text>
            <xsl:value-of select="$group/attention"/>
            <xsl:text>
</xsl:text>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
</code>```

key('ean',sscc) would select all <parcel> elements of the current group and key('ean',sscc)/attention all <attention> elements beneath them.

In XSLT 2.0+ you can also use <xsl:for-each-group> and the current-group() function for the same effect.

Using key('ean',sscc)/attention in a <xsl:value-of> would only print the value of the first match, which is what your intention seems to be anyway.

Using current() explicitly like you did is not really necessary. current() is meant to be used inside XPath predicates, in a normal select expression it doesn't add any value.

ContentLicense: CC BY-SA 4.0

Body:
I would like to be able to select one element from group of duplicates (done with Muenchian grouping) having certain sub-element. My XML looks like this:

<waybill>
<shipment>
    <parcel>
        <sscc>SSCC1</sscc>
        <consignee>Receiver1</consignee>
        <date>Date1</date>
        <status>Status1</status>
    </parcel>
    <parcel>
        <sscc>SSCC2</sscc>
        <consignee>Receiver2</consignee>
        <attention>Note2</attention>
    </parcel>
    <parcel>
        <sscc>SSCC3</sscc>
        <consignee>Receiver3</consignee>
    </parcel>
    <parcel>
        <sscc>SSCC4</sscc>
        <consignee>Receiver4</consignee>
    </parcel>
    <parcel>
        <sscc>SSCC1</sscc>
        <consignee>Receiver1</consignee>
        <attention>Note1</attention>
        <date>Date2</date>
        <status>Status2</status>
    </parcel>
    <parcel>
        <sscc>SSCC3</sscc>
        <consignee>Receiver3</consignee>
        <attention>Note3</attention>
    </parcel>
</shipment>
</waybill>

and my XSLT looks like this:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" version="2.0">
<xsl:output method="text" version="1.0" encoding="ISO-8859-1" indent="yes"/>
<xsl:key name="ean" match="parcel" use="sscc"/>
<xsl:template match="/">
    <xsl:for-each select="/waybill/shipment/parcel[generate-id()=generate-id(key('ean',sscc))]">
        <xsl:value-of select="current()/sscc"/>
        <xsl:text>§</xsl:text>
        <xsl:value-of select="current()/consignee"/>
        <xsl:text>§</xsl:text>
        <xsl:value-of select="current()/attention"/>
        <xsl:text>
</xsl:text>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

The output now looks like this:

SSCC1§Receiver1§
SSCC2§Receiver2§Note2
SSCC3§Receiver3§
SSCC4§Receiver4§

so my XSLT will now pick the first hit from the grouped elements and what I would like to have as a the result is:

SSCC1§Receiver1§Note1
SSCC2§Receiver2§Note2
SSCC3§Receiver3§Note3
SSCC4§Receiver4§

So the XSLT should find those duplicates from group with has the most data. Not first or last one, but the one with certain sub-element (or in my final case: sub-sub-element)

In this case not all of the element has the sub-element (here SSCC4) and those should be used with the data they have (should not be ignored).

What is the correct way to find the "best" element from the grouped similar elements?

Any help is highly appreciated :)

Body:
You can navigate from the key(), like this:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" version="2.0">
    <xsl:output method="text" version="1.0" encoding="ISO-8859-1" indent="yes"/>
    <xsl:key name="ean" match="parcel" use="sscc"/>

    <xsl:template match="/">
        <xsl:for-each select="/waybill/shipment/parcel[generate-id()=generate-id(key('ean',sscc))]">
            <xsl:variable name="group" select="key('ean',sscc)" />
            <xsl:value-of select="sscc"/>
            <xsl:text>§</xsl:text>
            <xsl:value-of select="$group/consignee"/>
            <xsl:text>§</xsl:text>
            <xsl:value-of select="$group/attention"/>
            <xsl:text>&#xd;</xsl:text>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

key('ean',sscc) would select all <parcel> elements of the current group and key('ean',sscc)/attention all <attention> elements beneath them.

In XSLT 2.0+ you can also use <xsl:for-each-group> and the current-group() function for the same effect.

Using key('ean',sscc)/attention in a <xsl:value-of> would only print the value of the first match, which is what your intention seems to be anyway.

Using current() explicitly like you did is not really necessary. current() is meant to be used inside XPath predicates, in a normal select expression it doesn't add any value.


问:
Mongo Exception
I recently had some storage issues on my PC so I changed the mongo.conf file to reduce the size of the journal. These are the lines which I put in.

```<code>mmapv1:
    smallFiles: true
</code>```

However, every time when I try to run mongo with the new changes I get this error(without the change it works just fine). Can you tell me what's the problem?

2016-02-11T22:32:14.002+0000 I FTDC     [ftdc] Unclean full-time diagnostic data capture shutdown detected, found interim file, some metrics may have been lost. OK

2016-02-11T22:32:14.023+0000 W FTDC     [ftdc] Uncaught exception in 'UnknownError Caught std::exception of type boost::filesystem::filesystem_error: boost::filesystem::file_size: No such file or directory: "/data/db/diagnostic.data/metrics.interim.temp"' in full-time diagnostic data capture subsystem. Shutting down the full-time diagnostic data capture subsystem.

答:
In case you are using nodejs, try to disable/remove debug mode in your server code.

Steps:

rm -rf /{your_db_name}/diagnostic.data/

remove or comment out mongoose.set('debug', true);

restart mongo and node server

Title: Mongo Exception

Body:
I recently had some storage issues on my PC so I changed the mongo.conf file to reduce the size of the journal. These are the lines which I put in.

mmapv1:
    smallFiles: true

However, every time when I try to run mongo with the new changes I get this error(without the change it works just fine). Can you tell me what's the problem?

2016-02-11T22:32:14.002+0000 I FTDC     [ftdc] Unclean full-time diagnostic data capture shutdown detected, found interim file, some metrics may have been lost. OK

2016-02-11T22:32:14.023+0000 W FTDC     [ftdc] Uncaught exception in 'UnknownError Caught std::exception of type boost::filesystem::filesystem_error: boost::filesystem::file_size: No such file or directory: "/data/db/diagnostic.data/metrics.interim.temp"' in full-time diagnostic data capture subsystem. Shutting down the full-time diagnostic data capture subsystem.


问:
Cucumber click only working when @javascript is used?
I know there's a simple fix for this but for the life of me I can't remember what it is.

My feature file is as following:

```<code>  Scenario: Editing locations
    When I edit "Western Australia"
      And fill in "Name" with "Tasmania"
      And I press "Save"
    Then I should see a form success message
</code>```

And I've defined the 'Edit' step as the following:

```<code>When /^I edit "([^"]*)"$/ do |name|
  within(:xpath, "//tr[./td[contains(text(), '#{name}')]]") do
    find(:css, "a img[alt=Edit]").click
  end
end
</code>```

The HTML for the index page it works on is as follows:

```<code><tr>
    <td>Western Australia</td>
    <td>WA</td>
    <td>
        <a href="/admin/locations/2/edit"><img alt="Edit" src="/images/icons/pencil.png" title="Edit" /></a>
    </td>
</tr>
</code>```

And then the form HTML:

```<code><%= semantic_form_for [:admin, @location] do |f| %>
<%= f.inputs do %>
    <%= f.input :name %>
    <%= f.input :abbreviation %>
<% end %>

    <%= f.submit "Save" %></li>
<% end %>
</code>```

As it is, it doesn't work - I get the following error:

```<code>And fill in "Name" with "Tasmania"                           # features/step_definitions/web_steps.rb:39
  cannot fill in, no text field, text area or password field with id, name, or label 'Name' found (Capybara::ElementNotFound)
</code>```

But the form element 'name' is clearly there on the page.

If I add 'Then show me the page' before the 'Fill in' then capybara saves the index page, leading me to think it isn't getting to the edit form at all.

... Yet if I add the '@javascript' tag to the feature, it works perfectly, even though there is no Javascript on this page.

I've solved this once before, but for the life of me I can't work out how...

答:
Well I managed to solve the problem - the issue was with my CSS selector that was clicking the 'Edit' link. I don't know why it didn't work as-was, but I changed the find(:css, "a img[alt=Edit]").click to read click_link('Edit') and it worked perfectly.

Source: http://groups.google.com/group/ruby-capybara/browse_thread/thread/9c997395306d40e2/

ContentLicense: CC BY-SA 2.5

Body:
I know there's a simple fix for this but for the life of me I can't remember what it is.

My feature file is as following:

  Scenario: Editing locations
    When I edit "Western Australia"
      And fill in "Name" with "Tasmania"
      And I press "Save"
    Then I should see a form success message

And I've defined the 'Edit' step as the following:

When /^I edit "([^"]*)"$/ do |name|
  within(:xpath, "//tr[./td[contains(text(), '#{name}')]]") do
    find(:css, "a img[alt=Edit]").click
  end
end

The HTML for the index page it works on is as follows:

    Western Australia
    WA

And then the form HTML:

<%= semantic_form_for [:admin, @location] do |f| %>
<%= f.inputs do %>
    <%= f.input :name %>
    <%= f.input :abbreviation %>
<% end %>

    <%= f.submit "Save" %>

<% end %>

As it is, it doesn't work - I get the following error:

And fill in "Name" with "Tasmania"                           # features/step_definitions/web_steps.rb:39
  cannot fill in, no text field, text area or password field with id, name, or label 'Name' found (Capybara::ElementNotFound)

But the form element 'name' is clearly there on the page.

If I add 'Then show me the page' before the 'Fill in' then capybara saves the index page, leading me to think it isn't getting to the edit form at all.

... Yet if I add the '@javascript' tag to the feature, it works perfectly, even though there is no Javascript on this page.

I've solved this once before, but for the life of me I can't work out how...


问:
How to make lighter keyboard letter for iOS app?
I don't understand why my app is getting "Bold Keyboard Letter" while other app like "Contact" is not?

I'm using UISearchbar and has configured as follow,

```<code>    keySearchBar = UISearchBar()
    keySearchBar!.translatesAutoresizingMaskIntoConstraints = false
    keySearchBar!.delegate = self
    keySearchBar!.placeholder = "Search"
    keySearchBar!.searchBarStyle = .minimal
    keySearchBar!.layer.borderWidth = 0
    keySearchBar!.keyboardAppearance = .light
</code>```

What wrong with my setting and how?

Thanks

答: As I manually setup the view without storyboard so, adding "Lunch Screen" solved the problem.</p>

Body:
I don't understand why my app is getting "Bold Keyboard Letter" while other app like "Contact" is not?

I'm using UISearchbar and has configured as follow,

    keySearchBar = UISearchBar()
    keySearchBar!.translatesAutoresizingMaskIntoConstraints = false
    keySearchBar!.delegate = self
    keySearchBar!.placeholder = "Search"
    keySearchBar!.searchBarStyle = .minimal
    keySearchBar!.layer.borderWidth = 0
    keySearchBar!.keyboardAppearance = .light

What wrong with my setting and how?

Thanks


问:
duplicate symbol _OBJC_METACLASS_$_ClassName
I am trying to run my cocos2d application and facing this error, as I have recently upgraded my sdk to 4.2 and my cocos2d to 0.99.5.

I tried to clean my project even change the Target ios Deployment but error remains the same. Also rename the className aswell in order to avoid duplication from Library classes names of cocos2d.

ld: duplicate symbol _OBJC_METACLASS_$_MenuSceneNew in
  /Users/umaidsaleem/Desktop/functionalityTest/build/Debug-iphonesimulator/libcocos2d
  libraries.a(MenuScene.o) and
  /Users/umaidsaleem/Desktop/functionalityTest/build/functionalityTest.build/Debug-iphonesimulator/functionalityTest.build/Objects-normal/i386/MenuScene.o

答: In my case this was happening because of Xcode automatically generating my NSManagedObject class, which then clashed with my manually created NSManagedObject class. In this case you can set "Codegen" to "Manual/None" in the Data Model Inspector for your newly created Entity.</p>


问:
Filtering based on subquery result
I have mysql query and I want to filter based on gigcount when i use where clause ie where gigcount=0 I get error unknown column

```<code>SELECT
tbl_musicvenue.id AS id,

(SELECT

    COUNT(1)AS A1
    FROM
        smliveclaims AS Extent5
    WHERE
        Extent5.tbl_MusicVenueId = tbl_musicvenue.id and (Extent5.IsDeleted =0 or Extent5.IsDeleted is null)) AS gigcount

FROM

tbl_musicvenue
</code>```

Is there any way to get all items where gigcount is 0

答:
You can rewrite your query as </p>

```<code>SELECT
a.id,
COUNT(b.tbl_MusicVenueId) gigcount
FROM
tbl_musicvenue a
LEFT JOIN smliveclaims b ON a.id = b.tbl_MusicVenueId AND (b.IsDeleted =0 OR b.IsDeleted IS NULL)
GROUP BY a.id
HAVING gigcount = 0
</code>```

<p>for your question to use gigcount in where clause, Where can be used for known column(s) of table(s) involved in query. In your case gigcount is an alias not a predefined column so you cannot access this in where clause. to filter on such columns use having clause </p>

Title: Filtering based on subquery result

Body:
I have mysql query and I want to filter based on gigcount when i use where clause ie where gigcount=0 I get error unknown column

SELECT
tbl_musicvenue.id AS id,

(SELECT

    COUNT(1)AS A1
    FROM
        smliveclaims AS Extent5
    WHERE
        Extent5.tbl_MusicVenueId = tbl_musicvenue.id and (Extent5.IsDeleted =0 or Extent5.IsDeleted is null)) AS gigcount

FROM

tbl_musicvenue

Is there any way to get all items where gigcount is 0

Body:
You can rewrite your query as

SELECT
a.id,
COUNT(b.tbl_MusicVenueId) gigcount
FROM
tbl_musicvenue a
LEFT JOIN smliveclaims b ON a.id = b.tbl_MusicVenueId AND (b.IsDeleted =0 OR b.IsDeleted IS NULL)
GROUP BY a.id
HAVING gigcount = 0

for your question to use gigcount in where clause, Where can be used for known column(s) of table(s) involved in query. In your case gigcount is an alias not a predefined column so you cannot access this in where clause. to filter on such columns use having clause


问:
how to add NicEdit textarea Scroll bar?
I am using NicEdit editor in my application but when i am writing text in the text area it is increasing the size instead of adding scrollbar to textarea . Please help with solution how can i add scrollbar to nicEdit editor text area Scrollbar .</p>

答:
set height according to you</p>

```<code><style>
    .nicEdit-main {
        overflow: auto !important;
        height: 5.5em;
    }
</style>
</code>```

Title: how to add NicEdit textarea Scroll bar?

Body:
set height according to you

<style>
    .nicEdit-main {
        overflow: auto !important;
        height: 5.5em;
    }
</style>


问:
Android TabLayout Android Design
I'm trying to get the new TabLayout in the android design library working.

I'm following this post:

http://android-developers.blogspot.com/2015/05/android-design-support-library.html

and the documentation:

http://developer.android.com/reference/android/support/design/widget/TabLayout.html

And have come up with the following code in my activity but the tablayout isn't showing up when I run the activity.

I tried adding   in the activity layout file, but it says it can't find that xml tag.

```<code>public class TabActivity extends BaseActivity {

    SectionPagerAdapter mSectionsPagerAdapter;
    ViewPager mViewPager;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_tab);

        LinearLayout v = (LinearLayout)findViewById(R.id.tabContainer);

        TabLayout tabLayout = new TabLayout(this);
        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));

        tabLayout.setLayoutParams(new LinearLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 50));

        v.addView(tabLayout);

        mSectionsPagerAdapter = new SectionPagerAdapter(getFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        tabLayout.setupWithViewPager(mViewPager);
        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    }

    public class SectionPagerAdapter extends FragmentPagerAdapter {

        private String TAG = "SectionPagerAdapter";

        public SectionPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position)
        {
            return new Fragment();
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return "test";
                case 1:
                    return "test";
                case 2:
            }
            return null;
        }
    }
}
</code>```

Added the following to my gradle file

```<code> compile 'com.android.support:design:22.2.0'
</code>```

答:
I try to solve here is my code.

first add dependency in build.gradle(app).

```<code>dependencies {
    compile 'com.android.support:design:23.1.1'
}
</code>```

Create PagerAdapter.class

```<code>public class PagerAdapter extends FragmentPagerAdapter {

    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public PagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        Log.i("PosTabItem",""+position);
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Log.i("PosTab",""+position);

        return mFragmentTitleList.get(position);
    }
}
</code>```

create activity_main.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/toolbar"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/tab_layout" />

</RelativeLayout>
</code>```

create MainActivity.class

```<code>public class MainActivity extends AppCompatActivity {

    Pager pager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
         pager = new Pager(getSupportFragmentManager());

        pager.addFragment(new FragmentOne(), "One");

        viewPager.setAdapter(pager);

        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        tabLayout.setSmoothScrollingEnabled(true);

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

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

and finally create fragment to add in viewpager

crate fragment_one.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="Location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
</code>```

Create FragmentOne.class

```<code>public class FragmentOne extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_one, container,false);
        return view;
    }
}
</code>```

Title: Android TabLayout Android Design

Body:
I'm trying to get the new TabLayout in the android design library working.

I'm following this post:

http://android-developers.blogspot.com/2015/05/android-design-support-library.html

and the documentation:

http://developer.android.com/reference/android/support/design/widget/TabLayout.html

And have come up with the following code in my activity but the tablayout isn't showing up when I run the activity.

I tried adding   in the activity layout file, but it says it can't find that xml tag.

public class TabActivity extends BaseActivity {

    SectionPagerAdapter mSectionsPagerAdapter;
    ViewPager mViewPager;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_tab);

        LinearLayout v = (LinearLayout)findViewById(R.id.tabContainer);

        TabLayout tabLayout = new TabLayout(this);
        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));

        tabLayout.setLayoutParams(new LinearLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 50));

        v.addView(tabLayout);

        mSectionsPagerAdapter = new SectionPagerAdapter(getFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        tabLayout.setupWithViewPager(mViewPager);
        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    }

    public class SectionPagerAdapter extends FragmentPagerAdapter {

        private String TAG = "SectionPagerAdapter";

        public SectionPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position)
        {
            return new Fragment();
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return "test";
                case 1:
                    return "test";
                case 2:
            }
            return null;
        }
    }
}

Added the following to my gradle file

 compile 'com.android.support:design:22.2.0'

Body:
I try to solve here is my code.

first add dependency in build.gradle(app).

dependencies {
    compile 'com.android.support:design:23.1.1'
}

Create PagerAdapter.class

public class PagerAdapter extends FragmentPagerAdapter {

    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public PagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        Log.i("PosTabItem",""+position);
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Log.i("PosTab",""+position);

        return mFragmentTitleList.get(position);
    }
}

create activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/toolbar"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/tab_layout" />

</RelativeLayout>

create MainActivity.class

public class MainActivity extends AppCompatActivity {

    Pager pager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
         pager = new Pager(getSupportFragmentManager());

        pager.addFragment(new FragmentOne(), "One");

        viewPager.setAdapter(pager);

        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        tabLayout.setSmoothScrollingEnabled(true);

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
}

and finally create fragment to add in viewpager

crate fragment_one.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="Location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Create FragmentOne.class

public class FragmentOne extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_one, container,false);
        return view;
    }
}


问:
drop first and last row from within each group
This is a follow up question to get first and last values in a groupby

How do I drop first and last rows within each group?

I have this df

```<code>df = pd.DataFrame(np.arange(20).reshape(10, -1),
                  [['a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd'],
                   ['a', 'a', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']],
                  ['X', 'Y'])

df
</code>```

I intentionally made the second row have the same index value as the first row.  I won't have control over the uniqueness of the index.

```<code>      X   Y
a a   0   1
  a   2   3
  c   4   5
  d   6   7
b e   8   9
  f  10  11
  g  12  13
c h  14  15
  i  16  17
d j  18  19
</code>```

I want this

```<code>        X   Y
a b   2.0   3
  c   4.0   5
b f  10.0  11
</code>```

Because both groups at level 0 equal to 'c' and 'd' have less than 3 rows, all rows should be dropped.

答:
Note: in pandas version 0.20.0 and above, ix is deprecated  and the use of iloc is encouraged instead.

So the df.ix[1:-1] should be replaced by df.iloc[1:-1].

Body:
This is a follow up question to get first and last values in a groupby

How do I drop first and last rows within each group?

I have this df

df = pd.DataFrame(np.arange(20).reshape(10, -1),
                  [['a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd'],
                   ['a', 'a', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']],
                  ['X', 'Y'])

df

I intentionally made the second row have the same index value as the first row.  I won't have control over the uniqueness of the index.

      X   Y
a a   0   1
  a   2   3
  c   4   5
  d   6   7
b e   8   9
  f  10  11
  g  12  13
c h  14  15
  i  16  17
d j  18  19

I want this

        X   Y
a b   2.0   3
  c   4.0   5
b f  10.0  11

Because both groups at level 0 equal to 'c' and 'd' have less than 3 rows, all rows should be dropped.


问:
Increase index of a form's input field's name attribute in a dynamic form
Suppose I have this form with indexed input fields username and level:

```<code><form>
 <table>
  <tr class="trToClone">
    <td>
      <label>Username:</label>
      <input type="text" name="username[0]" />
    </td>
    <td>
      <label>Level:</label>
      <select name="level[0]">
        <option value="">---</option>
        <option value="a">A</option>
        <option value="b">B</option>
        <option value="c">C</option>
      </select>
    </td>
    <td><input type="button" class="addField" value="Add" /></td>
  </tr>
 </table>
</form>
</code>```

The row can be repeated using this jQuery:

```<code>$("input.addField").on('click', function() {
  var $tr = $(this).closest('.trToClone');
  var $clone = $tr.clone();
  $clone.find(':text').val('');
  $tr.after($clone);
});
</code>```

Now for every subsequent row I add, I want to increase the indices of the name attribute (i.e. username[1],level[1]; username[2],level[2]; and so on...). How can I do this? I've looked for possible solutions, but to no avail.

答:
UPDATE: changing name attributes dynamically.

you can use a counter for counting your clicks! You have to move the "add" click button out of the table row.
HTML:

```<code><form>
 <input type="button" class="addField" value="Add" />
 <table>
  <tr class="trToClone">
    <td>
      <label>Username:</label>
      <input type="text" name="username[0]" />
    </td>
    <td>
      <label>Level:</label>
      <select name="level[0]">
        <option value="">---</option>
        <option value="a">A</option>
        <option value="b">B</option>
        <option value="c">C</option>
      </select>
    </td>
    <td></td>
  </tr>
 </table>
</form>
</code>```

JS:

```<code>var counter = 0;
$("input.addField").on('click', function() {
    counter++;
  var $tr = $('.trToClone:eq(0)');
  var $clone = $tr.clone();
  var newTextName = $clone.find(':text').attr('name').replace(/\[(\d)+\]/,'[+ counter +']');
  $clone.find(':text').attr('name',newTextName);
  $clone.find('.dropdown').attr('name','level['+ counter + ']');
  $tr.parent().append($clone);
});
</code>```

check out this fiddle: https://jsfiddle.net/gknrfw1g/2/

Body:
Suppose I have this form with indexed input fields username and level:

<form>

      Username:
      <input type="text" name="username[0]" />

      Level:
      <select name="level[0]">
        <option value="">---</option>
        <option value="a">A</option>
        <option value="b">B</option>
        <option value="c">C</option>
      </select>

    <input type="button" class="addField" value="Add" />

</form>

The row can be repeated using this jQuery:

$("input.addField").on('click', function() {
  var $tr = $(this).closest('.trToClone');
  var $clone = $tr.clone();
  $clone.find(':text').val('');
  $tr.after($clone);
});

Now for every subsequent row I add, I want to increase the indices of the name attribute (i.e. username[1],level[1]; username[2],level[2]; and so on...). How can I do this? I've looked for possible solutions, but to no avail.

Body:
UPDATE: changing name attributes dynamically.

you can use a counter for counting your clicks! You have to move the "add" click button out of the table row.
HTML:

<form>
 <input type="button" class="addField" value="Add" />
 <table>
  <tr class="trToClone">
    <td>
      <label>Username:</label>
      <input type="text" name="username[0]" />
    </td>
    <td>
      <label>Level:</label>
      <select name="level[0]">
        <option value="">---</option>
        <option value="a">A</option>
        <option value="b">B</option>
        <option value="c">C</option>
      </select>
    </td>
    <td></td>
  </tr>
 </table>
</form>

JS:

var counter = 0;
$("input.addField").on('click', function() {
    counter++;
  var $tr = $('.trToClone:eq(0)');
  var $clone = $tr.clone();
  var newTextName = $clone.find(':text').attr('name').replace(/\[(\d)+\]/,'[+ counter +']');
  $clone.find(':text').attr('name',newTextName);
  $clone.find('.dropdown').attr('name','level['+ counter + ']');
  $tr.parent().append($clone);
});

check out this fiddle: https://jsfiddle.net/gknrfw1g/2/


问:
How to access Class member variables from SpringApplication in Spring Boot
How do you access a member variable when starting the application using SpringApplication in SpringBoot ?

In the below code I am getting compilation errors on the assignment to Environment and BuildProperties. I think there must be a way to reference these properties via the SpringApplication or ConfigurableApplicationContext but I don't know how.

The compile error I am getting is,
non-static variable environment cannot be referenced from a static context
which I understand its just how to get around it.

I think my question really is - does SpringApplication return a Class level reference in the same way as doing a normal java MyClass myClass = new MyClass() does ?

```<code>@Slf4j
@EnableIntegration
@EnableLoaderApplication
@SpringBootApplication
@EnableDiscoveryClient
public class ExampleApplication {

    private Environment environment;
    private BuildProperties buildProperties;

    public ExampleApplication(Environment env, BuildProperties buildProp) {
        environment = env;
        buildProperties = buildProp;
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(ExampleApplication.class);
        ConfigurableApplicationContext context = app.run(args);

        environment = context.getEnvironment();  //compile error
        buildProperties = context.getBean(BuildProperties.class); //compile error

    DisplaySysInfo displaySysInfo = new DisplaySysInfo(environment, buildProperties, log);
    displaySysInfo.splash();

    }

}
</code>```

答:
You can Either inject Environment in your DisplaySysInfo class

```<code>@Autowire
Environment env;
</code>```

Or retrieve environment from the context itself

```<code> ConfigurableApplicationContext run = SpringApplication.run(ExampleApplication.class, args);
 ConfigurableEnvironment environment = run.getEnvironment();
</code>```

Body:
How do you access a member variable when starting the application using SpringApplication in SpringBoot ?

In the below code I am getting compilation errors on the assignment to Environment and BuildProperties. I think there must be a way to reference these properties via the SpringApplication or ConfigurableApplicationContext but I don't know how.

The compile error I am getting is,
non-static variable environment cannot be referenced from a static context
which I understand its just how to get around it.

I think my question really is - does SpringApplication return a Class level reference in the same way as doing a normal java MyClass myClass = new MyClass() does ?

@Slf4j
@EnableIntegration
@EnableLoaderApplication
@SpringBootApplication
@EnableDiscoveryClient
public class ExampleApplication {

    private Environment environment;
    private BuildProperties buildProperties;

    public ExampleApplication(Environment env, BuildProperties buildProp) {
        environment = env;
        buildProperties = buildProp;
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(ExampleApplication.class);
        ConfigurableApplicationContext context = app.run(args);

        environment = context.getEnvironment();  //compile error
        buildProperties = context.getBean(BuildProperties.class); //compile error

    DisplaySysInfo displaySysInfo = new DisplaySysInfo(environment, buildProperties, log);
    displaySysInfo.splash();

    }

}

Body:
You can Either inject Environment in your DisplaySysInfo class

@Autowire
Environment env;

Or retrieve environment from the context itself

 ConfigurableApplicationContext run = SpringApplication.run(ExampleApplication.class, args);
 ConfigurableEnvironment environment = run.getEnvironment();


问:
Get subject DN from clients certificate in Go gRPC handler
I'm using Golang gRPC with mutual tls. Is it possible to get client's certificate subject DN from rpc method?

```<code>// ...
func main() {
    // ...
    creds := credentials.NewTLS(&tls.Config{
        ClientAuth:   tls.RequireAndVerifyClientCert,
        Certificates: []tls.Certificate{certificate},
        ClientCAs:    certPool,
        MinVersion:   tsl.VersionTLS12,
    })
    s := NewMyService()
    gs := grpc.NewServer(grpc.Creds(creds))
    RegisterGRPCZmqProxyServer(gs, s)
    er := gs.Serve(lis)
    // ...
}

// ...
func (s *myService) Foo(ctx context.Context, req *FooRequest) (*FooResonse, error) {
    $dn := // What should be here?
    // ...
}
</code>```

Is it possible?

答:
You can use peer.Peer from ctx context.Context for access to the OID registry in x509.Certificate.

```<code>func (s *myService) Foo(ctx context.Context, req *FooRequest) (*FooResonse, error) {
    p, ok := peer.FromContext(ctx)
        if ok {
            tlsInfo := p.AuthInfo.(credentials.TLSInfo)
            subject := tlsInfo.State.VerifiedChains[0][0].Subject
            // do something ...
        }
}
</code>```

Subject it is pkix.Name and in docs write:

Name represents an X.509 distinguished name

And I used code from this answer and it well work.

Body:
I'm using Golang gRPC with mutual tls. Is it possible to get client's certificate subject DN from rpc method?

// ...
func main() {
    // ...
    creds := credentials.NewTLS(&tls.Config{
        ClientAuth:   tls.RequireAndVerifyClientCert,
        Certificates: []tls.Certificate{certificate},
        ClientCAs:    certPool,
        MinVersion:   tsl.VersionTLS12,
    })
    s := NewMyService()
    gs := grpc.NewServer(grpc.Creds(creds))
    RegisterGRPCZmqProxyServer(gs, s)
    er := gs.Serve(lis)
    // ...
}

// ...
func (s *myService) Foo(ctx context.Context, req *FooRequest) (*FooResonse, error) {
    $dn := // What should be here?
    // ...
}

Is it possible?

Body:
You can use peer.Peer from ctx context.Context for access to the OID registry in x509.Certificate.

func (s *myService) Foo(ctx context.Context, req *FooRequest) (*FooResonse, error) {
    p, ok := peer.FromContext(ctx)
        if ok {
            tlsInfo := p.AuthInfo.(credentials.TLSInfo)
            subject := tlsInfo.State.VerifiedChains[0][0].Subject
            // do something ...
        }
}

Subject it is pkix.Name and in docs write:

Name represents an X.509 distinguished name

And I used code from this answer and it well work.


问:
Fill listview with database table in C#
Im trying to fill listView1 with the first table of my database. But it is not working, can someone help me?

The function LoadList is not recognizing the DataTable DT

Here is the code I am using

```<code>namespace Project.Data_Layer
{
    class Leerling
    {
        public static DataTable ExecSelect(string Leerling)
        {
            DataSet DS = new DataSet();
            SqlDataAdapter DA;
            DA = new SqlDataAdapter(Leerling, SQLString.Conn);
            DS.Clear();
            DA.Fill(DS);
            // 1e tabel uit database
            DataTable DT = DS.Tables[0];
            return DT;
        }

        public static bool ExecOverig(string Leerling)
        {
            bool gelukt = true;
            SqlConnection Connect = new SqlConnection(SQLString.Conn);
            SqlCommand Cmd = new SqlCommand(Leerling, Connect);
            try
            {
                Cmd.Connection.Open();
                Cmd.ExecuteNonQuery();
                Connect.Close();
            }
            catch
            {
                gelukt = false;
            }
            return gelukt;
        }

        public void LoadList()
        {
            if(DT.tables.count > 0)
            {
                listView1.DataSource = DT;
                listView1.DataBind();
            }
            else
            {
                //
            }
        }
    }
}
</code>```

答:
```<code>[enter image description here][1]
string sel = "select * from EmployeeMaster";
        DataTable dt = new DataTable();
        dt = con.filldata(sel);
        foreach(DataRow r in dt.Rows)
        {
            listView1.Items.Add(r["E_Name"].ToString());
            listView1.Items.Add(r["Salary"].ToString());

        }

  [1]: https://i.stack.imgur.com/72fmI.png
</code>```

Title: Fill listview with database table in C#

Body:
Im trying to fill listView1 with the first table of my database. But it is not working, can someone help me?

The function LoadList is not recognizing the DataTable DT

Here is the code I am using

namespace Project.Data_Layer
{
    class Leerling
    {
        public static DataTable ExecSelect(string Leerling)
        {
            DataSet DS = new DataSet();
            SqlDataAdapter DA;
            DA = new SqlDataAdapter(Leerling, SQLString.Conn);
            DS.Clear();
            DA.Fill(DS);
            // 1e tabel uit database
            DataTable DT = DS.Tables[0];
            return DT;
        }

        public static bool ExecOverig(string Leerling)
        {
            bool gelukt = true;
            SqlConnection Connect = new SqlConnection(SQLString.Conn);
            SqlCommand Cmd = new SqlCommand(Leerling, Connect);
            try
            {
                Cmd.Connection.Open();
                Cmd.ExecuteNonQuery();
                Connect.Close();
            }
            catch
            {
                gelukt = false;
            }
            return gelukt;
        }

        public void LoadList()
        {
            if(DT.tables.count > 0)
            {
                listView1.DataSource = DT;
                listView1.DataBind();
            }
            else
            {
                //
            }
        }
    }
}


问:
SQL query for percentage calculation - single column, all data, using like/wildcard
I'm looking for SQL query that will give me a simple percentage value based upon the number of occurrences of a value in a table with a single data column.
Example:
Table has single column of data, which has a header and 10 data rows:

```<code>COLUMN_HEADER
XYZ://abc123xyz456-0
XYZ://abc123xyz456-1
XYZ://abc123xyz456-2
XYZ://abc123xyz456-3
ABC://abc123xyz456-4
XYZ://abc123xyz456-5
XYZ://abc123xyz456-6
ABC://abc123xyz456-7
XYZ://abc123xyz456-8
XYZ://abc123xyz456-9
</code>```

I'm looking for the query to look for all data that does not start with XYZ://*
and give that as a % of the row count.

In the above example, there are two rows that start with ABC:// and eight that start XYZ:// therefore the result should be:
80.00%

(so 8 out of 10 rows do not start with XYZ://)

As you can tell by now I'm a noob in SQL.

MS SQL 2014

Thanks in advance.

答:
You can do this with conditional aggregation:

```<code>select avg(case when COLUMN_HEADER like 'XYZ://%' then 1.0 else 0 end) as xyz_ratio
</code>```

Your logic and examples are backwards.  80% of the rows have values that do start with "XYZ://".  Use like or not like as appropriate.

Body:
I'm looking for SQL query that will give me a simple percentage value based upon the number of occurrences of a value in a table with a single data column.
Example:
Table has single column of data, which has a header and 10 data rows:

COLUMN_HEADER
XYZ://abc123xyz456-0
XYZ://abc123xyz456-1
XYZ://abc123xyz456-2
XYZ://abc123xyz456-3
ABC://abc123xyz456-4
XYZ://abc123xyz456-5
XYZ://abc123xyz456-6
ABC://abc123xyz456-7
XYZ://abc123xyz456-8
XYZ://abc123xyz456-9

I'm looking for the query to look for all data that does not start with XYZ://*
and give that as a % of the row count.

In the above example, there are two rows that start with ABC:// and eight that start XYZ:// therefore the result should be:
80.00%

(so 8 out of 10 rows do not start with XYZ://)

As you can tell by now I'm a noob in SQL.

MS SQL 2014

Thanks in advance.

Body:
You can do this with conditional aggregation:

select avg(case when COLUMN_HEADER like 'XYZ://%' then 1.0 else 0 end) as xyz_ratio

Your logic and examples are backwards.  80% of the rows have values that do start with "XYZ://".  Use like or not like as appropriate.


问:
Qt - QPixmap converts png to gray scale?
In Qt I used the following method to load images and set them as the background of QLabels:

```<code>QPixmap *pixmap= new QPixmap("home\\Images\\circle.png");
ui->cell11_Image->setPixmap(*pixmap);
ui->cell11_Image->setMask(pixmap->mask());
ui->cell11_Image->show();

delete(pixmap);
</code>```

With the following result

The thing is: the images are in grayscale. However, here is one of the images

Does anyone know what is going on?

答: I think your label or one of parent widget is disable. Try to enable and check. </p>

Body:
In Qt I used the following method to load images and set them as the background of QLabels:

QPixmap *pixmap= new QPixmap("home\\Images\\circle.png");
ui->cell11_Image->setPixmap(*pixmap);
ui->cell11_Image->setMask(pixmap->mask());
ui->cell11_Image->show();

delete(pixmap);

With the following result

The thing is: the images are in grayscale. However, here is one of the images

Does anyone know what is going on?


问:
Update Subquery Question, with foreign key
I misremembered what the key was for this Templates table and therefore I added the wrong field as a foreign key. Now I need to add the foreign key and I want to populate its values based on this other field that is already populated. I started trying to do this with an update statement, but I'm not sure how to do it.

Part of my schema:

Products Table:

```<code>ProductName (key)
TemplateName
TemplateID
...
</code>```

I've added TemplateID, but it has no data in it yet and is nullable.

Templates Table:

```<code>TemplateID (key)
TemplateName
...
</code>```

I want to use the Templates table to find the matching TemplateID for each TemplateName in the Products table and fill that in the foreign key reference in the Products table.

Can I do this with a subquery in Update, or do I need to write some kind of Stored Proc? I'm using Sql Server 2008

答:
```<code>update Templates
set TemplateId=Products.TemplateId
from Templates
inner join Products
   on Templates.TemplateName=Products.TemplateName
</code>```

OwnerDisplayName: Tony Peterson

Body:
I misremembered what the key was for this Templates table and therefore I added the wrong field as a foreign key. Now I need to add the foreign key and I want to populate its values based on this other field that is already populated. I started trying to do this with an update statement, but I'm not sure how to do it.

Part of my schema:

Products Table:

ProductName (key)
TemplateName
TemplateID
...

I've added TemplateID, but it has no data in it yet and is nullable.

Templates Table:

TemplateID (key)
TemplateName
...

I want to use the Templates table to find the matching TemplateID for each TemplateName in the Products table and fill that in the foreign key reference in the Products table.

Can I do this with a subquery in Update, or do I need to write some kind of Stored Proc? I'm using Sql Server 2008

OwnerDisplayName: Josh


问:
How to better structure an Array of Arrays in JSON
In the following JSON object:

```<code>var employees = { "accounting" : [   // accounting is an array in employees.
                                { "firstName" : "John",  // First element
                                  "lastName"  : "Doe",
                                  "age"       : 23 },

                                { "firstName" : "Mary",  // Second Element
                                  "lastName"  : "Smith",
                                  "age"       : 32 }
                              ], // End "accounting" array.
              "sales"       : [ // Sales is another array in employees.
                                { "firstName" : "Sally", // First Element
                                  "lastName"  : "Green",
                                  "age"       : 27 },

                                { "firstName" : "Jim",   // Second Element
                                  "lastName"  : "Galley",
                                  "age"       : 41 }
                              ] // End "sales" Array.
            } // End Employees
</code>```

How do I restructure the object so I can access each employee first name like this:

```<code>employees[0].firstName
employees[1].firstName
// etc
</code>```

答:
From jsFiddle</p>

```<code>var employees = { "firstName" : "John",  // First element
                  "lastName"  : "Doe",
                  "age"       : 23 },

                { "firstName" : "Mary",  // Second Element
                  "lastName"  : "Smith",
                  "age"       : 32 }
                 ;
alert(employees);
</code>```

Body:
In the following JSON object:

var employees = { "accounting" : [   // accounting is an array in employees.
                                { "firstName" : "John",  // First element
                                  "lastName"  : "Doe",
                                  "age"       : 23 },

                                { "firstName" : "Mary",  // Second Element
                                  "lastName"  : "Smith",
                                  "age"       : 32 }
                              ], // End "accounting" array.
              "sales"       : [ // Sales is another array in employees.
                                { "firstName" : "Sally", // First Element
                                  "lastName"  : "Green",
                                  "age"       : 27 },

                                { "firstName" : "Jim",   // Second Element
                                  "lastName"  : "Galley",
                                  "age"       : 41 }
                              ] // End "sales" Array.
            } // End Employees

How do I restructure the object so I can access each employee first name like this:

employees[0].firstName
employees[1].firstName
// etc

Body:
From jsFiddle

var employees = { "firstName" : "John",  // First element
                  "lastName"  : "Doe",
                  "age"       : 23 },

                { "firstName" : "Mary",  // Second Element
                  "lastName"  : "Smith",
                  "age"       : 32 }
                 ;
alert(employees);


问:
Mean of 3 rows in matrix
I have a matrix of the following setup:

```<code>d <- read.table(text='Sample     Target    Value
Sample1    A          NA
Sample1    A          2
Sample1    A          3
Sample2    A          1
Sample2    A          2
Sample2    A          3
Sample1    B          1
Sample1    B          2
Sample1    B          3
Sample2    B          NA
Sample2    B          2
Sample2    B          3',  header=TRUE)
</code>```

I would like to take the means of the Value column for each data repetition.
So the mean of all rows that have Sample=Sample1 and Target=A, Sample=Sample2 and Target=B and so on and so forth.

The output should be a matrix like this:

```<code>result <- read.table(text='Sample     Target    Value
Sample1    A          mean
Sample2    A          mean
Sample1    B          mean
Sample2    B          mean' ,  header=TRUE)
</code>```

I tried to solve this with aggregate(), but I am unsure how to code it, so it preserves the Sample and Target columns and disregard the NA

Thank you!

答:
I think aggregate is ok in this case. Try:

```<code>aggregate(d$Value, list(d$Sample, d$Target), mean, na.rm = TRUE)
  Group.1 Group.2   x
1 Sample1       A 2.5
2 Sample2       A 2.0
3 Sample1       B 2.0
4 Sample2       B 2.5
</code>```

Title: Mean of 3 rows in matrix

Body:
I have a matrix of the following setup:

d <- read.table(text='Sample     Target    Value
Sample1    A          NA
Sample1    A          2
Sample1    A          3
Sample2    A          1
Sample2    A          2
Sample2    A          3
Sample1    B          1
Sample1    B          2
Sample1    B          3
Sample2    B          NA
Sample2    B          2
Sample2    B          3',  header=TRUE)

I would like to take the means of the Value column for each data repetition.
So the mean of all rows that have Sample=Sample1 and Target=A, Sample=Sample2 and Target=B and so on and so forth.

The output should be a matrix like this:

result <- read.table(text='Sample     Target    Value
Sample1    A          mean
Sample2    A          mean
Sample1    B          mean
Sample2    B          mean' ,  header=TRUE)

I tried to solve this with aggregate(), but I am unsure how to code it, so it preserves the Sample and Target columns and disregard the NA

Thank you!

Body:
I think aggregate is ok in this case. Try:

aggregate(d$Value, list(d$Sample, d$Target), mean, na.rm = TRUE)
  Group.1 Group.2   x
1 Sample1       A 2.5
2 Sample2       A 2.0
3 Sample1       B 2.0
4 Sample2       B 2.5


问:
Iterate through an array of var chained variables in jQuery
I have a simple function in javascript that hides all css divs on page load:

```<code>function hideAllDivs() {
    var a5 = jQuery('.a5'),
        a2 = jQuery('.a2'),
        b2 = jQuery('.b2'),
        hd3 = jQuery('.hd3'),
        hd6 = jQuery('.hd6');

    a5.hide();
    a2.hide();
    b2.hide();
    hd3.hide();
    hd6.hide();
}
</code>```

As you can see I have to go through each one by one to hide them. Is there a way to store these into an array and just iterate through them all at once? That way if I add a new var chained query, I don't have to then go further down the function and manually hide it?

Any help would be greatly appreciated.

答:
You could give them a common class and then hide using this class as a selector that combine all those targeted elements for this operation, e.g :

```<code>function hideAllDivs() {
    jQuery('.common_class').hide();
}
</code>```

Hope this helps.

Body:
I have a simple function in javascript that hides all css divs on page load:

function hideAllDivs() {
    var a5 = jQuery('.a5'),
        a2 = jQuery('.a2'),
        b2 = jQuery('.b2'),
        hd3 = jQuery('.hd3'),
        hd6 = jQuery('.hd6');

    a5.hide();
    a2.hide();
    b2.hide();
    hd3.hide();
    hd6.hide();
}

As you can see I have to go through each one by one to hide them. Is there a way to store these into an array and just iterate through them all at once? That way if I add a new var chained query, I don't have to then go further down the function and manually hide it?

Any help would be greatly appreciated.

Body:
You could give them a common class and then hide using this class as a selector that combine all those targeted elements for this operation, e.g :

function hideAllDivs() {
    jQuery('.common_class').hide();
}

Hope this helps.


问:
Python Tkinter, destroy toplevel after function
I'm programming some drives with python using Tkinter as GUI. When my machine is running, I'd like to show the user a toplevel window with some information which should close itself after the function completes. This is my minimal example:

```<code>from Tkinter import *
import time

def button_1():
     window = Toplevel()
     window.title("info")
     msg = Message(window, text='running...', width=200)
     msg.pack()
     time.sleep(5.0)
     window.destroy()

master = Tk()
frame = Frame(width=500,height=300)
frame.grid()
button_one = Button(frame, text ="Button 1", command = button_1)
button_one.grid(row = 0, column = 0, sticky = W + E)
mainloop()
</code>```

The main problem is, that the toplevel window just appears after 5 seconds are over. Any suggestions?
Thanks!

答:
time.sleep(5) is launched before the GUI has time to update, that's why the toplevel only appears after the 5 seconds are over. To correct this, you can add window.update_idletasks() before time.sleep(5) to force the update the display.

But, as Bryan Oakley points out in his answer, the GUI is frozen while time.sleep(5) is executed. I guess that your ultimate goal is not to execute time.sleep but some time consuming operation. So, if you do not want to freeze the GUI but do not know how long the execution will take, you can execute your function in a separated thread and check regularly whether it is finished using after:

```<code>import Tkinter as tk
import time
import multiprocessing

def function():
    time.sleep(5)

def button_1():
    window = tk.Toplevel(master)
    window.title("info")
    msg = tk.Message(window, text='running...', width=200)
    msg.pack()
    thread = multiprocessing.Process(target=function)
    thread.start()
    window.after(1000, check_if_running, thread, window)

def check_if_running(thread, window):
    """Check every second if the function is finished."""
    if thread.is_alive():
        window.after(1000, check_if_running, thread, window)
    else:
        window.destroy()

master = tk.Tk()
frame = tk.Frame(width=500,height=300)
frame.grid()
button_one = tk.Button(frame, text ="Launch", command=button_1)
button_one.grid(row = 0, column = 0, sticky = "we")
master.mainloop()
</code>```

Body:
I'm programming some drives with python using Tkinter as GUI. When my machine is running, I'd like to show the user a toplevel window with some information which should close itself after the function completes. This is my minimal example:

from Tkinter import *
import time

def button_1():
     window = Toplevel()
     window.title("info")
     msg = Message(window, text='running...', width=200)
     msg.pack()
     time.sleep(5.0)
     window.destroy()

master = Tk()
frame = Frame(width=500,height=300)
frame.grid()
button_one = Button(frame, text ="Button 1", command = button_1)
button_one.grid(row = 0, column = 0, sticky = W + E)
mainloop()

The main problem is, that the toplevel window just appears after 5 seconds are over. Any suggestions?
Thanks!

Body:
time.sleep(5) is launched before the GUI has time to update, that's why the toplevel only appears after the 5 seconds are over. To correct this, you can add window.update_idletasks() before time.sleep(5) to force the update the display.

But, as Bryan Oakley points out in his answer, the GUI is frozen while time.sleep(5) is executed. I guess that your ultimate goal is not to execute time.sleep but some time consuming operation. So, if you do not want to freeze the GUI but do not know how long the execution will take, you can execute your function in a separated thread and check regularly whether it is finished using after:

import Tkinter as tk
import time
import multiprocessing

def function():
    time.sleep(5)

def button_1():
    window = tk.Toplevel(master)
    window.title("info")
    msg = tk.Message(window, text='running...', width=200)
    msg.pack()
    thread = multiprocessing.Process(target=function)
    thread.start()
    window.after(1000, check_if_running, thread, window)

def check_if_running(thread, window):
    """Check every second if the function is finished."""
    if thread.is_alive():
        window.after(1000, check_if_running, thread, window)
    else:
        window.destroy()

master = tk.Tk()
frame = tk.Frame(width=500,height=300)
frame.grid()
button_one = tk.Button(frame, text ="Launch", command=button_1)
button_one.grid(row = 0, column = 0, sticky = "we")
master.mainloop()


问:
Hosting ASP.NET MVC Project on godaddy.com
Is there a way that I can run a ASP.NET MVC Project on Godaddy.com ?

I published the project and tried, but not working.
It worked in IIS but not working in Godaddy.
I am new on hosting in Godaddy.
Please tell me the solution for that.

In Godaddy ASP.NET MVC Project, how to set the default start page ?

答:
Step 1: Get Windows Hosting Plan from Go Daddy to host your Asp.Net related project

Step 2 :

Login to your  GoDaddy Account add new temporary domain to test your application

Create a folder to publish your project build

Create new FTP account

If you have database create new SQL Server Database

For clear understanding Check here from Step 1 to Step 12

Step 3:

This step is using FileZilla FTP software, if you want to use Visual Studio FTP then follow steps in this article.

Publish your project to File System

Download FileZilla Client Using FileZilla FTP login to your GoDaddy FTP account and upload your project files and dll's.

Type your temporary domain name in browser to check your hosted application , if you still get errors you can research and fix it or ask a new question related to your error.


问:
Tabs menu android - not correct call fragments
Hi, to all!

I have a problem with the TabMenu, below i've posted a GIF, which shows how it works, it doesn't work correctly.

How it works in code:

MainActivity(ViewPager, TabsLayout)->FragmnetAdapter(For tabs layout)

How its must be: "Home"(HomeFragment), "History"(HistoryFragment), "Places"(PlacesFragment)

Now when its start at "Home" start "Home" but and  call "History" on "Hstory" call "Places"

But in code i didnt see some problems can you help me, please:)

Here is the code:

MainActivity:

```<code>public class MainActivity extends AppCompatActivity {

@BindView(R.id.appToolbarMainTabs)
Toolbar appToolbar;
@BindView(R.id.tabLayoutTabs)
TabLayout tabs;
@BindView(R.id.viewPager)
ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(appToolbar);
    setupViewPager(viewPager);
    tabs.setupWithViewPager(viewPager);
}

// Add Fragments to Tabs
private void setupViewPager(ViewPager viewPager) {
    FragmentTabsAdapter adapter = new FragmentTabsAdapter(getSupportFragmentManager());
    adapter.addFragment(new HomeFragment(), getString(R.string.home_tab));
    adapter.addFragment(new HistoryFragment(), getString(R.string.history_tab));
    adapter.addFragment(new PlacesFragment(), getString(R.string.places_tab));
    viewPager.setAdapter(adapter);
}}
</code>```

FragmentAdapter:

```<code>public class FragmentTabsAdapter  extends FragmentPagerAdapter {

private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public FragmentTabsAdapter(FragmentManager manager) {
    super(manager);
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}

@Override
public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
}

public void addFragment(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
}}
</code>```

Home&History&PlaceFragment don't needed i think so:)

Thanks a lot!:)

答:
The tabs and the ViewPager are ok, it always preloads at least the previous and the next fragments.

You could only show the dialog when the fragment is shown and it is still loading the info.

```<code>@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
  super.setUserVisibleHint(isVisibleToUser);
  if (isVisibleToUser) {
    if (fragmentIsLoadingInfo()) { // implement this
      showLoading(); // implement this
    }
  }
}
</code>```

Also check the setOffscreenPageLimit of a ViewPager to understand what is happening and to update this value if you, for example, want all the three fragments to load at once. Its a shame that if you set it to 0 it still works as if it was 1.

Body:
Hi, to all!

I have a problem with the TabMenu, below i've posted a GIF, which shows how it works, it doesn't work correctly.

How it works in code:

MainActivity(ViewPager, TabsLayout)->FragmnetAdapter(For tabs layout)

How its must be: "Home"(HomeFragment), "History"(HistoryFragment), "Places"(PlacesFragment)

Now when its start at "Home" start "Home" but and  call "History" on "Hstory" call "Places"

But in code i didnt see some problems can you help me, please:)

Here is the code:

MainActivity:

public class MainActivity extends AppCompatActivity {

@BindView(R.id.appToolbarMainTabs)
Toolbar appToolbar;
@BindView(R.id.tabLayoutTabs)
TabLayout tabs;
@BindView(R.id.viewPager)
ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(appToolbar);
    setupViewPager(viewPager);
    tabs.setupWithViewPager(viewPager);
}

// Add Fragments to Tabs
private void setupViewPager(ViewPager viewPager) {
    FragmentTabsAdapter adapter = new FragmentTabsAdapter(getSupportFragmentManager());
    adapter.addFragment(new HomeFragment(), getString(R.string.home_tab));
    adapter.addFragment(new HistoryFragment(), getString(R.string.history_tab));
    adapter.addFragment(new PlacesFragment(), getString(R.string.places_tab));
    viewPager.setAdapter(adapter);
}}

FragmentAdapter:

public class FragmentTabsAdapter  extends FragmentPagerAdapter {

private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public FragmentTabsAdapter(FragmentManager manager) {
    super(manager);
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}

@Override
public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
}

public void addFragment(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
}}

Home&History&PlaceFragment don't needed i think so:)

Thanks a lot!:)

Body:
The tabs and the ViewPager are ok, it always preloads at least the previous and the next fragments.

You could only show the dialog when the fragment is shown and it is still loading the info.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
  super.setUserVisibleHint(isVisibleToUser);
  if (isVisibleToUser) {
    if (fragmentIsLoadingInfo()) { // implement this
      showLoading(); // implement this
    }
  }
}

Also check the setOffscreenPageLimit of a ViewPager to understand what is happening and to update this value if you, for example, want all the three fragments to load at once. Its a shame that if you set it to 0 it still works as if it was 1.


问:
Difference between inline operation and calculate before operation in foreach
I make it simple (because i didn't find anything on Google, maybe because i don't know either what search).

What is the difference beetween this:

```<code>foreach(var x in g.GetList())
{
 code
}
</code>```

and this:

```<code>IEnumerable<object> list = g.GetList();
foreach(var x in list)
{
 code
}
</code>```

in terms of performance or in terms of best practices, or whatever?

答:
In the below code, you  are directly calling the g.GetList() method in your foreach

```<code>foreach(var x in g.GetList())
{
 code
}
</code>```

In the below code, You are assigned the g.GetList() method in a variable, then You are calling the variable in your foreach. Comparing with the first code, The performance vice, no difference. Just the compiler compile extra one line. that's all.

```<code>IEnumerable<object> list = g.GetList();
foreach(var x in list)
{
 code
}
</code>```

But your first code may threw a null reference error if g.GetList(); method return null. So the best practice is check null condition before use the variable/method in foreach

```<code>IEnumerable<object> list = g.GetList();
if(list == null)
{
retur false;
}
foreach(var x in list)
{
 code
}
</code>```

And must use real object instead of using object and dynamic data types due to type safe.

```<code>IEnumerable<Employee> list = g.GetList();// as per employee is your class name
</code>```

Performance is very important for clients, But Standard and understandable coding's are important for developers. I hope you can understand what is am explained.

Body:
I make it simple (because i didn't find anything on Google, maybe because i don't know either what search).

What is the difference beetween this:

foreach(var x in g.GetList())
{
 code
}

and this:

IEnumerable<object> list = g.GetList();
foreach(var x in list)
{
 code
}

in terms of performance or in terms of best practices, or whatever?

Body:
In the below code, you  are directly calling the g.GetList() method in your foreach

foreach(var x in g.GetList())
{
 code
}

In the below code, You are assigned the g.GetList() method in a variable, then You are calling the variable in your foreach. Comparing with the first code, The performance vice, no difference. Just the compiler compile extra one line. that's all.

IEnumerable<object> list = g.GetList();
foreach(var x in list)
{
 code
}

But your first code may threw a null reference error if g.GetList(); method return null. So the best practice is check null condition before use the variable/method in foreach

IEnumerable<object> list = g.GetList();
if(list == null)
{
retur false;
}
foreach(var x in list)
{
 code
}

And must use real object instead of using object and dynamic data types due to type safe.

IEnumerable<Employee> list = g.GetList();// as per employee is your class name

Performance is very important for clients, But Standard and understandable coding's are important for developers. I hope you can understand what is am explained.


问:
Web Socket connection with Basic Access Authentication
I'm trying to establish connection (client side) with Web Socket which requires Basic Access Authentication. From documentation I know that I should use username and password with base64 encryption. It's node.js application so I decide to use npm package SockJS-client. It seems to be good solution because:

Under the hood SockJS tries to use native WebSockets first. If that fails it can use a variety of browser-specific transport protocols and presents them through WebSocket-like abstractions.

But I have no clue how to establish connection using Basic Access Authentication. I have tried solution from here, but this one

```<code>var ws = new WebSocket("ws://username:password@example.com/service");
</code>```

does not work, I got an error like:

SyntaxError: The URL's scheme must be either 'http:' or 'https:'. 'ws:' is not allowed.

When I'm trying with http/https I got:

Error: InvalidStateError: The connection has not been established yet

When I'm trying to call

```<code>sock.send('test');
</code>```

Another solutions like that below is impossible to implement because I have no access to server side of Web Socket.

```<code>var ws = new WebSocket("ws://example.com/service?key1=value1&key2=value2");
</code>```

I have no idea how to correctly establish authenticated connection with Web Socket, if you know any solutions let me know.

答:
Solution was pretty simple, but I think it is worth to place it here for next generations.

Finally, I implemented it by ws, you can find it here.
First of all, I added header with field Authorization which contains encoded token. Another thing was a flag perMessageDeflate set to false.

The client will only use the extension if it is supported and enabled on the server.

That's how code looks like, works perfectly fine for me:

```<code>const WebSocket = require('ws');

const webSocket = new WebSocket(url, {
  perMessageDeflate: false,
  headers: {
    Authorization: `Basic ${encodedToken}`,
  },
});

webSocket.on('open', function open() {
  console.log('Connection has been established.');
});
</code>```

I hope it will save you a lot of time.

Body:
I'm trying to establish connection (client side) with Web Socket which requires Basic Access Authentication. From documentation I know that I should use username and password with base64 encryption. It's node.js application so I decide to use npm package SockJS-client. It seems to be good solution because:

Under the hood SockJS tries to use native WebSockets first. If that fails it can use a variety of browser-specific transport protocols and presents them through WebSocket-like abstractions.

But I have no clue how to establish connection using Basic Access Authentication. I have tried solution from here, but this one

var ws = new WebSocket("ws://username:password@example.com/service");

does not work, I got an error like:

SyntaxError: The URL's scheme must be either 'http:' or 'https:'. 'ws:' is not allowed.

When I'm trying with http/https I got:

Error: InvalidStateError: The connection has not been established yet

When I'm trying to call

sock.send('test');

Another solutions like that below is impossible to implement because I have no access to server side of Web Socket.

var ws = new WebSocket("ws://example.com/service?key1=value1&key2=value2");

I have no idea how to correctly establish authenticated connection with Web Socket, if you know any solutions let me know.

Body:
Solution was pretty simple, but I think it is worth to place it here for next generations.

Finally, I implemented it by ws, you can find it here.
First of all, I added header with field Authorization which contains encoded token. Another thing was a flag perMessageDeflate set to false.

The client will only use the extension if it is supported and enabled on the server.

That's how code looks like, works perfectly fine for me:

const WebSocket = require('ws');

const webSocket = new WebSocket(url, {
  perMessageDeflate: false,
  headers: {
    Authorization: `Basic ${encodedToken}`,
  },
});

webSocket.on('open', function open() {
  console.log('Connection has been established.');
});

I hope it will save you a lot of time.


问:
Field 'browser' doesn't contain a valid alias configuration for react
Im currently doing TylerMcginnes React Fundamentals course , while I am relatively new to front end I wish to learn to the current accepted style so am linting with eslint airbnb config and prettier, however since i changed from Tyler's coding a.k.a(no imports, all requires, no es6 functionality) i have got this "Field "browser" doesnt contain a valid alias configuration error and it says that my index.jsx doesnt exist in the exact location that it is??

My Env is Ubuntu 16.04

Attached is my bash error screen, file tree,package.json and webpack.config anyone who can lend some assistance and put me out of my 6 hours of searching and atemping would be greatly appreciated

I have looked at every other answer regarding this issue and most seem to be typo's, it would drive me crazy if I'm so blind i couldn't see it after the time I've spent looking

答: Your entry value in your webpack.config.js should just be ./app/index.jsx</p>