问:
Process the command without launching MainActivity, in Android
I am new to android and stuck at one point with my new screen off test application. I am trying to develop an Android application to turn off or lock the screen directly by clicking the app launcher icon of the application.

I am able to lock the screen with the functionality I want but with one problem. While i click on the screen lock icon in the launcher it takes around a second and then locks the screen (Time is taken by to MainActivity to launch).

I want that time delay to be removed and just wanted to process the command to lock phone when user tap on the app icon in the launcher. But am not able to figure it out.

Here is AndroidManifest.xml

```<code><application
    android:theme="@android:style/Theme.NoDisplay"
    android:label="@string/app_name"
    android:icon="@drawable/ic_launcher"
    android:allowBackup="true">

    <activity android:name=".MainActivity"
        android:excludeFromRecents="true"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name="ScreenOffAdminReceiver"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data android:name="android.app.device_admin"
            android:resource="@xml/permissions" />
        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
        </intent-filter>
    </receiver>

</application>
</code>```

MainActivity.java

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

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        DevicePolicyManager deviceManger = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        ComponentName compName = new ComponentName(this, ScreenOffAdminReceiver.class);
        if (deviceManger.isAdminActive(compName)) {
            deviceManger.lockNow();
            finish();
        } else {
            Intent intent = new Intent("android.app.action.ADD_DEVICE_ADMIN");
            intent.putExtra("android.app.extra.DEVICE_ADMIN", compName);
            intent.putExtra("android.app.extra.ADD_EXPLANATION", getString(R.string.devicePolicyManagerMsg));
            startActivityForResult(intent, 0);
        }
        Process.killProcess(Process.myPid());
    }
}
</code>```

ScreenOffAdminReceiver.java

```<code>public class ScreenOffAdminReceiver extends DeviceAdminReceiver {
    public void onDisabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminDisabled, Toast.LENGTH_SHORT).show();
    }

    public void onEnabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminEnabled, Toast.LENGTH_SHORT).show();
    }
}
</code>```

permissions.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <force-lock />
    </uses-policies>
</device-admin>
</code>```

I just want to remove the DELAY while locking the screen. Any help will be highly appreciated. Thanks

答:
I don't think you could achieve near zero response time as long as your "trigger" is clicking on the app launcher icon for two reasons:

When you click on the app icon a request is sent to the "system" (if you want to read more about it - it's called the zygote process).
The system then creates the process for your application to run and only then the app is launched.
This is guaranteed to take some time.

The first code to be executed is your application onCreate() method BUT if your application is still kept in the background/phone memory this method won't be executed when clicking on the app launcher icon, so this solution is not really what you're looking for.

Body:
I am new to android and stuck at one point with my new screen off test application. I am trying to develop an Android application to turn off or lock the screen directly by clicking the app launcher icon of the application.

I am able to lock the screen with the functionality I want but with one problem. While i click on the screen lock icon in the launcher it takes around a second and then locks the screen (Time is taken by to MainActivity to launch).

I want that time delay to be removed and just wanted to process the command to lock phone when user tap on the app icon in the launcher. But am not able to figure it out.

Here is AndroidManifest.xml

<application
    android:theme="@android:style/Theme.NoDisplay"
    android:label="@string/app_name"
    android:icon="@drawable/ic_launcher"
    android:allowBackup="true">

    <activity android:name=".MainActivity"
        android:excludeFromRecents="true"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name="ScreenOffAdminReceiver"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data android:name="android.app.device_admin"
            android:resource="@xml/permissions" />
        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
        </intent-filter>
    </receiver>

</application>

MainActivity.java

public class MainActivity extends Activity {

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        DevicePolicyManager deviceManger = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        ComponentName compName = new ComponentName(this, ScreenOffAdminReceiver.class);
        if (deviceManger.isAdminActive(compName)) {
            deviceManger.lockNow();
            finish();
        } else {
            Intent intent = new Intent("android.app.action.ADD_DEVICE_ADMIN");
            intent.putExtra("android.app.extra.DEVICE_ADMIN", compName);
            intent.putExtra("android.app.extra.ADD_EXPLANATION", getString(R.string.devicePolicyManagerMsg));
            startActivityForResult(intent, 0);
        }
        Process.killProcess(Process.myPid());
    }
}

ScreenOffAdminReceiver.java

public class ScreenOffAdminReceiver extends DeviceAdminReceiver {
    public void onDisabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminDisabled, Toast.LENGTH_SHORT).show();
    }

    public void onEnabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminEnabled, Toast.LENGTH_SHORT).show();
    }
}

permissions.xml

<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <force-lock />
    </uses-policies>
</device-admin>

I just want to remove the DELAY while locking the screen. Any help will be highly appreciated. Thanks


来源: stackexchange

问:
What Ruby technique does Rails use to make my controller methods render views?
Just curious if anybody knows what Ruby technique is used to accomplish the following in the Rails framework.

If I don't write, say, an index method on a Rails controller, Rails will still render the index view file if the URL matches that route. That makes sense, because my controller inherits from a parent class, which must have its own index method.

However, if I do define an index method, and only tell it to set an instance variable, it still renders the appropriate view. For example:

```<code>def index
  @weasels = Weasel.all

  # If I omit this line, Rails renders the index anyway.
  # If this behavior is defined in the parent class's index method,
  # it seems that by overriding the method, my index wouldn't do it.
  # I'm not explicitly calling super to get the method from
  # ActionController::Base, but maybe Rails is doing something like that?
  render :index
end
</code>```

In pure Ruby, I would expect to have to call super to get that behavior.

I assume that Rails uses some kind of metaprogramming technique to guarantee that my controller methods will call super. If so, can anyone explain it? Can you point to the source code that does this?

Update

As Mladen Jablanović has pointed out, my initial mental model was wrong; the controller method doesn't normally render the view; instead, both the controller method and the view rendering are called by some framework code. This is apparent because I can make a controller method with any name - for example, search - and the search view will get rendered. So clearly I'm not overriding a parent method in that case, and some framework code is parsing the controller method name and looking for the matching view.

Still, the framework must be able to detect whether or not the controller method has already called render. So that's another small mystery to me.

答:
Jamis Buck wrote quite a bit about implicit routes a few years ago here.

I believe the code you're looking for is in Resources. Rails looks at the inbound request and (for RESTful routes) goes here to determine the controller and action if they aren't specified.

Update: Controllers are a really complex part of the Rails framework. It isn't quite as simple as a single Ruby class with a single method (which is why super isn't really needed, but a series of calls both before and after your individual method is called.

Rack handles the request and passes it to Rails which does the routing, delegates to the instance of ActionController for the action (which may or may not have been coded by you), then passes the result of that to the rendering process.

ContentLicense: CC BY-SA 2.5

Body:
Just curious if anybody knows what Ruby technique is used to accomplish the following in the Rails framework.

If I don't write, say, an index method on a Rails controller, Rails will still render the index view file if the URL matches that route. That makes sense, because my controller inherits from a parent class, which must have its own index method.

However, if I do define an index method, and only tell it to set an instance variable, it still renders the appropriate view. For example:

def index
  @weasels = Weasel.all

  # If I omit this line, Rails renders the index anyway.
  # If this behavior is defined in the parent class's index method,
  # it seems that by overriding the method, my index wouldn't do it.
  # I'm not explicitly calling super to get the method from
  # ActionController::Base, but maybe Rails is doing something like that?
  render :index
end

In pure Ruby, I would expect to have to call super to get that behavior.

I assume that Rails uses some kind of metaprogramming technique to guarantee that my controller methods will call super. If so, can anyone explain it? Can you point to the source code that does this?

Update

As Mladen Jablanović has pointed out, my initial mental model was wrong; the controller method doesn't normally render the view; instead, both the controller method and the view rendering are called by some framework code. This is apparent because I can make a controller method with any name - for example, search - and the search view will get rendered. So clearly I'm not overriding a parent method in that case, and some framework code is parsing the controller method name and looking for the matching view.

Still, the framework must be able to detect whether or not the controller method has already called render. So that's another small mystery to me.


问:
How to upgrade all Python packages with pip
Is it possible to upgrade all Python packages at one time with pip?

Note: that there is a feature request for this on the official issue tracker.

答:
This is a PowerShell solution for Python 3:

pip3 list --outdated --format=legacy | ForEach { pip3 install -U $_.split(" ")[0] }
```
<p>And for Python 2:</p>
<pre class="lang-none prettyprint-override"><code>pip2 list --outdated --format=legacy | ForEach { pip2 install -U $_.split(" ")[0] }
</code>```

This upgrades the packages one by one. So a

pip3 check
pip2 check
```

afterwards should make sure no dependencies are broken.

ContentLicense: CC BY-SA 4.0

Body:
This is a PowerShell solution for Python 3:

pip3 list --outdated --format=legacy | ForEach { pip3 install -U $_.split(" ")[0] }

And for Python 2:

pip2 list --outdated --format=legacy | ForEach { pip2 install -U $_.split(" ")[0] }

This upgrades the packages one by one. So a

pip3 check
pip2 check

afterwards should make sure no dependencies are broken.


问:
SSL still displaying as unsecure
I'm trying to set up my SSL certificate but the site still says that https is unsecure.

I've edited the 000-default.conf as follows:

```<code><VirtualHost *:80>
    ServerName millingtonmayers.co.uk
    Redirect permanent / https://millingtonmayers.co.uk/
 </VirtualHost>

 <VirtualHost *:443>
    ServerName millingtonmayers.co.uk
    SSLEngine on
    SSLCertificateFile /home/bensleym/millingtonmayers.co.uk.crt
    SSLCertificateKeyFile /home/bensleym/millingtonmayers.co.uk.key
    SSLCertificateChainFile /home/bensleym/intermediate.crt
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless

    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
 </VirtualHost>
</code>```

The redirect doesn't seem to be working either any ideas?

答:
Have signed the certificate(millingtonmayers.co.uk.crt) from CA? when i inspect it says :

```<code>Start Time: 1499176042
Timeout   : 300 (sec)
Verify return code: 18 (self signed certificate)
</code>```

if it is self-singed it is untrusted.
you can check this using "openssl s_client -connect millingtonmayers.co.uk:443" on a console

ContentLicense: CC BY-SA 3.0

Title: SSL still displaying as unsecure

Body:
I'm trying to set up my SSL certificate but the site still says that https is unsecure.

I've edited the 000-default.conf as follows:

<VirtualHost *:80>
    ServerName millingtonmayers.co.uk
    Redirect permanent / https://millingtonmayers.co.uk/
 </VirtualHost>

 <VirtualHost *:443>
    ServerName millingtonmayers.co.uk
    SSLEngine on
    SSLCertificateFile /home/bensleym/millingtonmayers.co.uk.crt
    SSLCertificateKeyFile /home/bensleym/millingtonmayers.co.uk.key
    SSLCertificateChainFile /home/bensleym/intermediate.crt
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless

    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
 </VirtualHost>

The redirect doesn't seem to be working either any ideas?

Body:
Have signed the certificate(millingtonmayers.co.uk.crt) from CA? when i inspect it says :

Start Time: 1499176042
Timeout   : 300 (sec)
Verify return code: 18 (self signed certificate)

if it is self-singed it is untrusted.
you can check this using "openssl s_client -connect millingtonmayers.co.uk:443" on a console


问:
How to bind Kibana to multiple host names / IPs
Is there a way to bind Kibana to more than one IP address using kibana's config file: kibana.yml?
Right now, if I modify the line

server.host: "127.0.0.1"

to

server.host: ["127.0.0.1","123.45.67.89"]

which is valid YML, I get an error.

Is there any way to accomplish this from within Kibana or do I need to do it through a proxy/nginx?

答:
Install ngrok from https://ngrok.com/, then from your command line type:

```<code>ngrok http 5601
</code>```

Ngrok will create a tunnel to the server and provide you with a url from which you can access your kibana UI.

If you need to acceess the ngrok and the 4040 port is closed on the server then do the same

```<code>ngrok http 4040
</code>```

Body:
Install ngrok from https://ngrok.com/, then from your command line type:

ngrok http 5601

Ngrok will create a tunnel to the server and provide you with a url from which you can access your kibana UI.

If you need to acceess the ngrok and the 4040 port is closed on the server then do the same

ngrok http 4040


问:
Wordpress numeric pagination without words
My work's Wordpress site needs a numeric pagination for the posts page, however as it's a multilingual site I can't have any words in it like "Previous page" or "Page 1 of 3".

I've tried a couple of different examples that I've found (as I'm not skilled enough to write it myself yet), but they all contain words hidden within queries and I can't figure out how to change them. Eg:

```<code>function pagination($pages = '', $range = 4)
{
     $showitems = ($range * 2)+1;

     global $paged;
     if(empty($paged)) $paged = 1;

     if($pages == '')
     {
         global $wp_query;
         $pages = $wp_query->max_num_pages;
         if(!$pages)
         {
             $pages = 1;
         }
     }

     if(1 != $pages)
     {
         echo "<div class=\"pagination\"><span>Page ".$paged." of ".$pages."</span>";
         if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>« First</a>";
         if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>‹ Previous</a>";

         for ($i=1; $i <= $pages; $i++)
         {
             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
             {
                 echo ($paged == $i)? "<span class=\"current\">".$i."</span>":"<a href='".get_pagenum_link($i)."' class=\"inactive\">".$i."</a>";
             }
         }

         if ($paged < $pages && $showitems < $pages) echo "<a href=\"".get_pagenum_link($paged + 1)."\">Next ›</a>";
         if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>Last »</a>";
         echo "</div>\n";
     }
}
</code>```

This code shows "Page 1 of 2". If I could just change that to 1/2 for example, that would be perfect. Is anyone able to explain how I could do this, or any alternative methods? Many thanks!

答:
Please find the code :

```<code>    function theme_pagination()
    {
        echo paginate_links( array(
           'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
           'format' => '?paged=%#%',
           'type'=>'list',
           'current' => max( 1, get_query_var('paged') ),
           'total' => $wp_query->max_num_pages,
           'prev_text'    => '',
           'next_text'    => '',
        ));

    }
</code>```

Hope this will do the work

Body:
My work's Wordpress site needs a numeric pagination for the posts page, however as it's a multilingual site I can't have any words in it like "Previous page" or "Page 1 of 3".

I've tried a couple of different examples that I've found (as I'm not skilled enough to write it myself yet), but they all contain words hidden within queries and I can't figure out how to change them. Eg:

function pagination($pages = '', $range = 4)
{
     $showitems = ($range * 2)+1;

     global $paged;
     if(empty($paged)) $paged = 1;

     if($pages == '')
     {
         global $wp_query;
         $pages = $wp_query->max_num_pages;
         if(!$pages)
         {
             $pages = 1;
         }
     }

     if(1 != $pages)
     {
         echo "
Page ".$paged." of ".$pages."";
         if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "« First";
         if($paged > 1 && $showitems < $pages) echo "‹ Previous";

         for ($i=1; $i <= $pages; $i++)
         {
             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
             {
                 echo ($paged == $i)? "".$i."":"".$i."";
             }
         }

         if ($paged < $pages && $showitems < $pages) echo "Next ›";
         if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "Last »";
         echo "
\n";
     }
}

This code shows "Page 1 of 2". If I could just change that to 1/2 for example, that would be perfect. Is anyone able to explain how I could do this, or any alternative methods? Many thanks!

Body:
Please find the code :

    function theme_pagination()
    {
        echo paginate_links( array(
           'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
           'format' => '?paged=%#%',
           'type'=>'list',
           'current' => max( 1, get_query_var('paged') ),
           'total' => $wp_query->max_num_pages,
           'prev_text'    => '',
           'next_text'    => '',
        ));

    }

Hope this will do the work


问:
Are Structs in C++ allocated memory sequentially? Somehow getting correct answer for pointer comparison everytime
I'm trying to solve a problem.

Problem definition:  Given a singly linked list containing n nodes. Modify the value of first half nodes such that 1st node’s new value is equal to the last node’s value minus first node’s current value, 2nd node’s new value is equal to the second last node’s value minus 2nd node’s current value, likewise for first half nodes. If n is odd then the value of the middle node remains unchanged. Note that the half nodes of linked list remain unmodified.

EG :  6 3 5 4 10

ans:
-4 -1 5 4 10

I wrote a program to keep track of nodes in the second half in reverse order needed for processing using recursion. But, out of carelessness, I compared both the pointers to check whether both the pointers have crossed each other to stop processing them.

I am getting the output, everytime correctly.

FULL CODE:

```<code>#include <bits/stdc++.h>
using namespace std;
struct Node
{
    int data;
    struct Node* next;
};
struct Node* modifyTheList(struct Node *head);
void push(struct Node **head_ref, int new_data)
{
  struct Node* new_node =(struct Node*) malloc(sizeof(struct Node));
  new_node->data = new_data;
  new_node->next = *head_ref;
  *head_ref = new_node;
}
void printList(struct Node *head)
{
    if (!head)
        return;
    while (head->next != NULL)
    {
        cout << head->data << " ";
        head = head->next;
    }
    cout << head->data << endl;
}
int main()
{
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        struct Node *head = NULL;
        while(n--){
            int a;
            cin>>a;
            push(&head, a);
        }
        head = modifyTheList(head);
        printList(head);
    }
    return 0;
}

void modify(Node *head ,Node** left)
{
    if(head!=NULL)
    {
        modify(head->next,left);
        if(head >= *left )            //line of concern, comparing pointers
            return;
        else
        {
            (*left)->data=(*left)->data-head->data;
            (*left)=(*left)->next;
        }
    }
}
struct Node* modifyTheList(struct Node *head)
{
    if(head==NULL || head->next==NULL )
        return head;
    struct Node *temp = head;
    modify(head,&temp);
    return head;
}
</code>```

Can someone tell me is it valid to compare this way?

If this is not valid, how it passed the test cases of an online judge?

答:
Can someone tell me is it valid to compare this way?

You can't directly compare pointers unless they point to subobjects of the same array, or members of the same object. Formally, objects that are not part of the same array are considered part of separate 1-element arrays. There is no defined result for comparing their pointers. To quote N4296:

§5.9 Relational operators [expr.rel] ְְ¶3

Comparing pointers to objects86 is defined as follows:

  (3.1) — If two pointers point to different elements of the same array, or to
  subobjects thereof, the pointer to the element with the higher
  subscript compares greater.

  (3.2) — If one pointer points to an
  element of an array, or to a subobject thereof, and another pointer
  points one past the last element of the array, the latter pointer
  compares greater.

  (3.3) — If two pointers point to different
  non-static data members of the same object, or to subobjects of such
  members, recursively, the pointer to the later declared member
  compares greater provided the two members have the same access control
  (Clause 11) and provided their class is not a union.

86) An object that is not an array element is considered to belong to a single-element array for this purpose; see 5.3.1.

So you can't compare directly, and your program is officially with undefined behavior. However, such comparison can be useful, which is why the standard gives you another way:

§20.9.6 Comparisons [comparisons] ְְ¶14

For templates greater, less, greater_equal, and less_equal, the specializations for any pointer type
  yield a total order, even if the built-in operators <, >, <=, >= do not.

So your code can be made well defined, by simply replacing head >= *left with a call to std::greater_equal<Node*>(head, *left).

If this is not valid, how it passed the test cases of an online judge?

Undefined behavior means any outcome is allowed by the language specification. "Working" is a possible outcome. You just can't rely on it to always be the outcome.

Body:
I'm trying to solve a problem.

Problem definition:  Given a singly linked list containing n nodes. Modify the value of first half nodes such that 1st node’s new value is equal to the last node’s value minus first node’s current value, 2nd node’s new value is equal to the second last node’s value minus 2nd node’s current value, likewise for first half nodes. If n is odd then the value of the middle node remains unchanged. Note that the half nodes of linked list remain unmodified.

EG :  6 3 5 4 10

ans:
-4 -1 5 4 10

I wrote a program to keep track of nodes in the second half in reverse order needed for processing using recursion. But, out of carelessness, I compared both the pointers to check whether both the pointers have crossed each other to stop processing them.

I am getting the output, everytime correctly.

FULL CODE:

#include <bits/stdc++.h>
using namespace std;
struct Node
{
    int data;
    struct Node* next;
};
struct Node* modifyTheList(struct Node *head);
void push(struct Node **head_ref, int new_data)
{
  struct Node* new_node =(struct Node*) malloc(sizeof(struct Node));
  new_node->data = new_data;
  new_node->next = *head_ref;
  *head_ref = new_node;
}
void printList(struct Node *head)
{
    if (!head)
        return;
    while (head->next != NULL)
    {
        cout <data << " ";
        head = head->next;
    }
    cout <data << endl;
}
int main()
{
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        struct Node *head = NULL;
        while(n--){
            int a;
            cin>>a;
            push(&head, a);
        }
        head = modifyTheList(head);
        printList(head);
    }
    return 0;
}

void modify(Node *head ,Node** left)
{
    if(head!=NULL)
    {
        modify(head->next,left);
        if(head >= *left )            //line of concern, comparing pointers
            return;
        else
        {
            (*left)->data=(*left)->data-head->data;
            (*left)=(*left)->next;
        }
    }
}
struct Node* modifyTheList(struct Node *head)
{
    if(head==NULL || head->next==NULL )
        return head;
    struct Node *temp = head;
    modify(head,&temp);
    return head;
}

Can someone tell me is it valid to compare this way?

If this is not valid, how it passed the test cases of an online judge?


问:
JQuery Selector code validation for list of select options
I'm having situation like 3 select box is there in a form

```<code>    <form>
   <select name="select1">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 </select>

<select name="select2">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 </select>
  <select name="select3">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 </select> </form>
</code>```

On submitting this form i have to check atleast one of the select box value should be "a".

Is there any one line selctor query like jQuery['form'].find('select val=="a"').length() like this .

Thanks,
Nithish.

答:
Example: http://jsfiddle.net/patrick_dw/Zvmfg/

```<code>jQuery('form select option:selected[value="a"]').length;
</code>```

So you could do:

```<code>if( jQuery('form select option:selected[value="a"]').length ) {
    alert( 'at least one was selected' );
} else {
    alert( 'no "a" values selected' );
}
</code>```

Body:
I'm having situation like 3 select box is there in a form

    <form>
   <select name="select1">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 </select>

<select name="select2">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 </select>
  <select name="select3">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 </select> </form>

On submitting this form i have to check atleast one of the select box value should be "a".

Is there any one line selctor query like jQuery['form'].find('select val=="a"').length() like this .

Thanks,
Nithish.

Body:
Example: http://jsfiddle.net/patrick_dw/Zvmfg/

jQuery('form select option:selected[value="a"]').length;

So you could do:

if( jQuery('form select option:selected[value="a"]').length ) {
    alert( 'at least one was selected' );
} else {
    alert( 'no "a" values selected' );
}


问:
Spinner (Spin.js.org) in Meteor React
I'm trying to add a loading spinner. Per the docs for html and meteor, I installed the atmosphere package. Here is my attempt:

renderSpinner() {
  Meteor.Spinner.options = {
      lines: 13,
      ...
      left: 'auto'
    };
    var target = document.getElementById('spinner');
    var spinner = new Spinner(options).spin(target);
}
```

<p>And:</p>

<pre class="lang-js prettyprint-override"><code>render() {
  <span id="spinner"></span>
  {this.renderSpinner()}
}
</code>```

But that doesn't produce desired outcome. So I guess my questions are:

How do I import the package into one of my files? (Or I don't need to?)

What is the equivalent of {{> spinner}} in React?

How do I make it work?

Sorry if these questions are very basic, I'm starting out and I bet I'm not the only one!

答:
Ok I'm retarded. The solution is to just have

var options = { lines: 13, ... };

Easy peasy

Title: Spinner (Spin.js.org) in Meteor React

Body:
I'm trying to add a loading spinner. Per the docs for html and meteor, I installed the atmosphere package. Here is my attempt:

renderSpinner() {
  Meteor.Spinner.options = {
      lines: 13,
      ...
      left: 'auto'
    };
    var target = document.getElementById('spinner');
    var spinner = new Spinner(options).spin(target);
}

And:

render() {

  {this.renderSpinner()}
}

But that doesn't produce desired outcome. So I guess my questions are:

How do I import the package into one of my files? (Or I don't need to?)

What is the equivalent of {{> spinner}} in React?

How do I make it work?

Sorry if these questions are very basic, I'm starting out and I bet I'm not the only one!


问:
Is it possible to upgrade from Solr 4.x directly to Solr 6.1?
We are looking to upgrade from SolrCloud 4.10.3 to SolrCloud 6.1.  The documentation for Solr 6.1 is not very clear on backward compatibility.

I came across this post on the LucidWorks site.

The index format is backward compatible between two consecutive major
  Solr versions. So a Solr 3.x index is compatible with a Solr 4.x
  index. However if you have a Solr 1.x index and want to upgrade to
  Solr 4.x then you would need to first upgrade to Solr 3.x first.

It was written before Solr 6.x was out, and the wording of "between two consecutive major Solr versions" is unclear.  The example skips the exact scenario that I'm interested in (skipping exactly 1 major version).

Do I have to first upgrade to Solr 5.x and then go to Solr 6.1?

答:
Since I face same situation on upgrading SOLR from 4.x to 6.x I have been lucky and found on git hub next script, that is making the upgrade:

https://github.com/cominvent/solr-tools.git/

All the credits goes to "cominvent" for this script.
Since the folder cores  vers 4.x structure is not same with version 6.x I have made a script that is creating the right tree configuration, then is applying upgradeindex.sh.

The script (buildsorltree.sh) can be found on https://github.com/cradules/bash_scripts and the repo dose have upgradeindex.sh too. Since I have linked this too scripts, I put them on same repo. Good luck!


问:
Adding notebook tabs in tkinter - how do I do it with a class-based structure? (Python 3)
I wrote a tkinter application that had widgets displayed on two frames, similar to this example, which successfully runs.

```<code>from tkinter import *
from tkinter import ttk

root = Tk()
root.title("Example")

notebook = ttk.Notebook(root)
frame1 = ttk.Frame(notebook)
frame2 = ttk.Frame(notebook)
notebook.add(frame1, text="Frame One")
notebook.add(frame2, text="Frame Two")
notebook.pack()

#(The labels are examples, but the rest of the code is identical in structure).

labelA = ttk.Label(frame1, text = "This is on Frame One")
labelA.grid(column=1, row=1)

labelB = ttk.Label(frame2, text = "This is on Frame Two")
labelB.grid(column=1, row=1)

root.mainloop()
</code>```

I decided that I should try to restructure the program to use a class (which I'm admittedly not very familiar with). However, I'm unsure what I should do to allow the widgets to appear on different frames (everything else works okay). For instance, the following produces a "TypeError: init() takes from 1 to 2 positional arguments but 3 were given." So presumably I'd need to initialise with an extra argument, but I'm not sure how the notebook would be worked into that, or if that's even the approach I should be taking. (The program will run if the "frame1" and "frame2" arguments are removed from the labels, it will, however, display the same thing on both frames).

```<code>from tkinter import *
from tkinter import ttk

class MainApplication(ttk.Frame):
    def __init__(self, parent):
        ttk.Frame.__init__(self, parent)

        self.labelA = ttk.Label(self, frame1, text = "This is on Frame One")
        self.labelA.grid(column=1, row=1)

        self.labelB = ttk.Label(self, frame2, text = "This is on Frame Two")
        self.labelB.grid(column=1, row=1)

root = Tk()
root.title("Example")
notebook = ttk.Notebook(root)
frame1 = ttk.Frame(notebook)
frame2 = ttk.Frame(notebook)
notebook.add(frame1, text="Frame One")
notebook.add(frame2, text="Frame Two")
notebook.pack()
MainApplication(root).pack()
root.mainloop()
</code>```

I'm interested in a solution, but I'm also interested in learning what the class is doing differently compared to the standalone widgets.

答:
I suggest you split the different Frames within notebook into separate files.
I used from tab2 import * because I wanted this to remain in the namespace without adding the file/class prefix ie. I didn't want to write: tab1.Tab1(notebook)

main.py

```<code>import tkinter as tk
from tkinter import ttk

from tab1 import *
from tab2 import *

class MainApplication(tk.Frame):
  def __init__(self, parent, *args, **kwargs):
    tk.Frame.__init__(self, parent, *args, **kwargs)

    notebook = ttk.Notebook(parent)

    Tab1frame = Tab1(notebook)
    Tab2frame = Tab2(notebook)

    notebook.add(Typ1frame, text='TAB1')
    notebook.add(Typ2frame, text='TAB2')
    notebook.pack()

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root).pack(side="top", fill="both", expand=True)
    root.mainloop()
</code>```

tab1.py

```<code>import tkinter as tk
from tkinter import ttk

class Typ14(tk.Frame):
  def __init__(self, parent, *args, **kwargs):
    tk.Frame.__init__(self, parent, *args, **kwargs)
    shell_frame=tk.LabelFrame(self, text="Sample Label Frame", padx=5,pady=5)
    shell_frame.grid(row=0,column=0,padx=5,pady=5)
</code>```

Body:
I wrote a tkinter application that had widgets displayed on two frames, similar to this example, which successfully runs.

from tkinter import *
from tkinter import ttk

root = Tk()
root.title("Example")

notebook = ttk.Notebook(root)
frame1 = ttk.Frame(notebook)
frame2 = ttk.Frame(notebook)
notebook.add(frame1, text="Frame One")
notebook.add(frame2, text="Frame Two")
notebook.pack()

#(The labels are examples, but the rest of the code is identical in structure).

labelA = ttk.Label(frame1, text = "This is on Frame One")
labelA.grid(column=1, row=1)

labelB = ttk.Label(frame2, text = "This is on Frame Two")
labelB.grid(column=1, row=1)

root.mainloop()

I decided that I should try to restructure the program to use a class (which I'm admittedly not very familiar with). However, I'm unsure what I should do to allow the widgets to appear on different frames (everything else works okay). For instance, the following produces a "TypeError: init() takes from 1 to 2 positional arguments but 3 were given." So presumably I'd need to initialise with an extra argument, but I'm not sure how the notebook would be worked into that, or if that's even the approach I should be taking. (The program will run if the "frame1" and "frame2" arguments are removed from the labels, it will, however, display the same thing on both frames).

from tkinter import *
from tkinter import ttk

class MainApplication(ttk.Frame):
    def __init__(self, parent):
        ttk.Frame.__init__(self, parent)

        self.labelA = ttk.Label(self, frame1, text = "This is on Frame One")
        self.labelA.grid(column=1, row=1)

        self.labelB = ttk.Label(self, frame2, text = "This is on Frame Two")
        self.labelB.grid(column=1, row=1)

root = Tk()
root.title("Example")
notebook = ttk.Notebook(root)
frame1 = ttk.Frame(notebook)
frame2 = ttk.Frame(notebook)
notebook.add(frame1, text="Frame One")
notebook.add(frame2, text="Frame Two")
notebook.pack()
MainApplication(root).pack()
root.mainloop()

I'm interested in a solution, but I'm also interested in learning what the class is doing differently compared to the standalone widgets.

Body:
I suggest you split the different Frames within notebook into separate files.
I used from tab2 import * because I wanted this to remain in the namespace without adding the file/class prefix ie. I didn't want to write: tab1.Tab1(notebook)

main.py

import tkinter as tk
from tkinter import ttk

from tab1 import *
from tab2 import *

class MainApplication(tk.Frame):
  def __init__(self, parent, *args, **kwargs):
    tk.Frame.__init__(self, parent, *args, **kwargs)

    notebook = ttk.Notebook(parent)

    Tab1frame = Tab1(notebook)
    Tab2frame = Tab2(notebook)

    notebook.add(Typ1frame, text='TAB1')
    notebook.add(Typ2frame, text='TAB2')
    notebook.pack()

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

tab1.py

import tkinter as tk
from tkinter import ttk

class Typ14(tk.Frame):
  def __init__(self, parent, *args, **kwargs):
    tk.Frame.__init__(self, parent, *args, **kwargs)
    shell_frame=tk.LabelFrame(self, text="Sample Label Frame", padx=5,pady=5)
    shell_frame.grid(row=0,column=0,padx=5,pady=5)


问:
Cookies On Mobile Phone
can I use a cookie or session object in my mobile website to control login from a PHP page? </p>

答: Keep in mind that some networks or transcoding proxies of networks may block cookies. it would be better to use url based session state if you care about every visitor.</p>

Title: Cookies On Mobile Phone


问:
how can i access to child in object in as3
i want to access the child of Object!
for instance:
 we a have child(that name is a1) in k1 object.
how can i access it(my means a1 which in the k1)

```<code>var k1:keypad=new keypad();
k1.x=7.05;
k1.y=229.20;
add Child(k1);
this.k1.a1.addEventListener(Mouse Event.CLICK,ts);
function ts(event:Mouse Event):void{
 trace("OK");

};
</code>```

thank you.

答:
You are doing it wrong. You declare a local variable k1:

```<code>var k1:keypad
</code>```

which is not a member of this object, you cannot access it

```<code>this.k1
</code>```

So your code will probably work this way:

```<code>// Bad class name: lowercase.
var k1:keypad = new keypad;

k1.x = 7.05;
k1.y = 229.20;

// This is addChild() method, it is spelled without space.
addChild(k1);

// Then you access k1 just as you did above, without this.

// This will work if you designed your keypad with
// Adobe Flash IDE on default publish settings.
k1.a1.addEventListener(Mouse Event.CLICK, onA1);

// This will work too if a1's instance name is a1:
// k1.getChildByName("a1").addEventListener(Mouse Event.CLICK, onA1);

// Event handler. MouseEvent is a class name,
// it has no space inside.
function onA1(e:MouseEvent):void
{
    trace("OK");
}
// Normally you don't need ; after function body.
</code>```

Body:
i want to access the child of Object!
for instance:
 we a have child(that name is a1) in k1 object.
how can i access it(my means a1 which in the k1)

var k1:keypad=new keypad();
k1.x=7.05;
k1.y=229.20;
add Child(k1);
this.k1.a1.addEventListener(Mouse Event.CLICK,ts);
function ts(event:Mouse Event):void{
 trace("OK");

};

thank you.

Body:
You are doing it wrong. You declare a local variable k1:

var k1:keypad

which is not a member of this object, you cannot access it

this.k1

So your code will probably work this way:

// Bad class name: lowercase.
var k1:keypad = new keypad;

k1.x = 7.05;
k1.y = 229.20;

// This is addChild() method, it is spelled without space.
addChild(k1);

// Then you access k1 just as you did above, without this.

// This will work if you designed your keypad with
// Adobe Flash IDE on default publish settings.
k1.a1.addEventListener(Mouse Event.CLICK, onA1);

// This will work too if a1's instance name is a1:
// k1.getChildByName("a1").addEventListener(Mouse Event.CLICK, onA1);

// Event handler. MouseEvent is a class name,
// it has no space inside.
function onA1(e:MouseEvent):void
{
    trace("OK");
}
// Normally you don't need ; after function body.


问:
Hide <div class="kk-star-ratings top-right rgt" data-id="18">
Hi I can hide the element :  in all our site but I want to hide just on certains page. Which CSS code I can use as to hide only certains data-id : </p>

```<code><div class="kk-star-ratings  top-right rgt" data-id="18">
<div class="kk-star-ratings  top-right rgt" data-id="9036">
</code>```

答:
In you CSS, using attribute selectors you could :

```<code>[data-id="18"] {
  /* styles */
}
</code>```

With a class try this:

```<code>.kk-star-ratings[data-id="18"] {
   /* styles */
}
</code>```

Notice, there is no space between ratings[data

Body:
In you CSS, using attribute selectors you could :

[data-id="18"] {
  /* styles */
}

With a class try this:

.kk-star-ratings[data-id="18"] {
   /* styles */
}

Notice, there is no space between ratings[data


问:
centering a grow effect for a centered text
Because of transform: translateZ(0); position of h1 changes. If I remove it, effect not working properly.

How can I change below code and have h1 centered, and grow effect happens at the center of text?

I found a grow effect from here but the codes has transforms that conflict with each other

h1{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

}
.hvr-grow {
    transform-origin:center center;
    display: inline-block;
    vertical-align: middle;
    /*transform: translateZ(0);*/
    box-shadow: 0 0 1px rgba(0, 0, 0, 0);
    backface-visibility: hidden;
    -moz-osx-font-smoothing: grayscale;
    transition-duration: 0.3s;
    transition-property: transform;
}

.hvr-grow:hover,
.hvr-grow:focus,
.hvr-grow:active {
    transform: scale(1.8);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="position:relative">
<h1 class="hvr-grow">Hello I'm centered</h1>
</div></code>```

答:
That is because you have applied two different CSS transforms to the same element: first, you have applied translate(-50%, -50%), and then you apply scale(1.8). The annoying thing about CSS transforms is that they do not stack, so basically your scaling will overwrite the translate... in other words, with your original code, the following styles will apply in the hover state:

```<code>transform: translate(-50%, -50%);  /* This will be overwritten! */
transform: scale(1.8);             /* Overwrites all preceding transforms */
</code>```

What you can do is simply to combine them in the :hover selector, i.e.

```<code>transform: translate(-50%, -50%) scale(1.8);
</code>```

p/s: On a side note, since you are using the CSS transform trick to vertically center your element, you do not need to use display: inline-block and vertical-align: middle tricks.

Here is a working example:

h1{
    position: absolute;
    top: 50%;
    left: 50%;
}
.hvr-grow {
    box-shadow: 0 0 1px rgba(0, 0, 0, 0);
    backface-visibility: hidden;
    -moz-osx-font-smoothing: grayscale;
    transition-duration: 0.3s;
    transition-property: transform;
    transform: translate(-50%, -50%);
}

.hvr-grow:hover,
.hvr-grow:focus,
.hvr-grow:active {
    transform: translate(-50%, -50%) scale(1.8);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="position:relative">
<h1 class="hvr-grow">Hello I'm centered</h1>
</div></code>```

Body:
Because of transform: translateZ(0); position of h1 changes. If I remove it, effect not working properly.

How can I change below code and have h1 centered, and grow effect happens at the center of text?

I found a grow effect from here but the codes has transforms that conflict with each other

h1{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

}
.hvr-grow {
    transform-origin:center center;
    display: inline-block;
    vertical-align: middle;
    /*transform: translateZ(0);*/
    box-shadow: 0 0 1px rgba(0, 0, 0, 0);
    backface-visibility: hidden;
    -moz-osx-font-smoothing: grayscale;
    transition-duration: 0.3s;
    transition-property: transform;
}

.hvr-grow:hover,
.hvr-grow:focus,
.hvr-grow:active {
    transform: scale(1.8);
}

Hello I'm centered

Body:
That is because you have applied two different CSS transforms to the same element: first, you have applied translate(-50%, -50%), and then you apply scale(1.8). The annoying thing about CSS transforms is that they do not stack, so basically your scaling will overwrite the translate... in other words, with your original code, the following styles will apply in the hover state:

transform: translate(-50%, -50%);  /* This will be overwritten! */
transform: scale(1.8);             /* Overwrites all preceding transforms */

What you can do is simply to combine them in the :hover selector, i.e.

transform: translate(-50%, -50%) scale(1.8);

p/s: On a side note, since you are using the CSS transform trick to vertically center your element, you do not need to use display: inline-block and vertical-align: middle tricks.

Here is a working example:

h1{
    position: absolute;
    top: 50%;
    left: 50%;
}
.hvr-grow {
    box-shadow: 0 0 1px rgba(0, 0, 0, 0);
    backface-visibility: hidden;
    -moz-osx-font-smoothing: grayscale;
    transition-duration: 0.3s;
    transition-property: transform;
    transform: translate(-50%, -50%);
}

.hvr-grow:hover,
.hvr-grow:focus,
.hvr-grow:active {
    transform: translate(-50%, -50%) scale(1.8);
}

<div style="position:relative">
<h1 class="hvr-grow">Hello I'm centered</h1>
</div>


问:
How to clean an Azure storage Blob container?
I just want to clean (dump, zap, del .) an Azure Blob container. How can I do that?

Note: The container is used by IIS (running Webrole) logs (wad-iis-logfiles).

答:
If you are interested in a CLI way, then the following piece of code will help you out:

```<code>for i in `az storage blob list -c "Container-name" --account-name "Storage-account-name" --account-key "Storage-account-access-key" --output table | awk {'print $1'} | sed '1,2d' | sed '/^$/d'`; do az storage blob delete --name $i -c "Container-name" --account-name "Storage-account-name" --account-key "Storage-account-access-key" --output table; done
</code>```

It first fetches the list of blobs in the container and deletes them one by one.

Body:
If you are interested in a CLI way, then the following piece of code will help you out:

for i in `az storage blob list -c "Container-name" --account-name "Storage-account-name" --account-key "Storage-account-access-key" --output table | awk {'print $1'} | sed '1,2d' | sed '/^$/d'`; do az storage blob delete --name $i -c "Container-name" --account-name "Storage-account-name" --account-key "Storage-account-access-key" --output table; done

It first fetches the list of blobs in the container and deletes them one by one.


问:
@UIScope annotation not respected for spring view?
I am facing an issue with the Vaadin spring annotation @UIScope, defined as follows:

```<code>@SpringComponent
@SpringView(name = AdminView.VIEW_NAME)
@UIScope
public class AdminView extends NavigatingView {
    ...
}
</code>```

The view is created every time the navigation is opening the view. I would expect that it is created only once, on first time access.

However, if I replace @UIScope with @Scope(UIScopeImpl.VAADIN_UI_SCOPE_NAME) then it works as expected. Did I miss something?

答:
It's related to the order of the @SpringView and @UIScope annotations, as the tutorial and the older wiki page briefly suggest:

// Pay attention to the order of annotations

It's probably related to how and when the annotations are processed. I did not dig that deep into the Vaadin code, but as per the the @SpringView javadoc it puts the view into a view-scope by default. Furthermore, I don't think you require the @SpringComponent annotation because you're already using @SpringView to register it a spring component.

Annotation to be placed on View-classes that should be handled by the SpringViewProvider.

This annotation is also a stereotype annotation, so Spring will automatically detect the annotated classes. By default, this annotation also puts the view into the view scope. You can override this by using another scope annotation, such as the UI scope, on your view class. However, the singleton scope will not work!

In the sample below, you'll find 2 views, the first one with the annotations in the correct order, and the second one with them swapped:

```<code>@SpringUI
@SpringViewDisplay
public class MyVaadinUI extends UI implements ViewDisplay {

    /* UI */

    private Panel springViewDisplay;

    @Override
    protected void init(VaadinRequest request) {
        VerticalLayout mainLayout = new VerticalLayout();
        HorizontalLayout buttonLayout = new HorizontalLayout();
        springViewDisplay = new Panel();

        buttonLayout.addComponent(new Button("1", event -> getNavigator().navigateTo(FirstView.VIEW_NAME)));
        buttonLayout.addComponent(new Button("2", event -> getNavigator().navigateTo(SecondView.VIEW_NAME)));
        mainLayout.addComponents(buttonLayout, springViewDisplay);
        setContent(mainLayout);

    }

    @Override
    public void showView(View view) {
        springViewDisplay.setContent((Component) view);
    }

    /* VIEWS */

    @UIScope
    @SpringView(name = FirstView.VIEW_NAME)
    public static class FirstView extends HorizontalLayout implements View {

        public static final String VIEW_NAME = "";

        @PostConstruct
        private void init() {
            System.out.println("Created first view");
            addComponent(new Label("First view - " + LocalDateTime.now()));
        }

        @Override
        public void enter(ViewChangeListener.ViewChangeEvent event) {
            // no-op
        }
    }

    @SpringView(name = SecondView.VIEW_NAME)
    @UIScope
    public static class SecondView extends HorizontalLayout implements View {

        public static final String VIEW_NAME = "secondView";

        @PostConstruct
        private void init() {
            System.out.println("Created second view");
            addComponent(new Label("Second view - " + LocalDateTime.now()));
        }

        @Override
        public void enter(ViewChangeListener.ViewChangeEvent event) {
            // no-op
        }
    }
}
</code>```

As you'll notice in the animation below, when navigating to the second view a new instance is always created, while navigating to the first one will reuse the initial instance:

Body:
I am facing an issue with the Vaadin spring annotation @UIScope, defined as follows:

@SpringComponent
@SpringView(name = AdminView.VIEW_NAME)
@UIScope
public class AdminView extends NavigatingView {
    ...
}

The view is created every time the navigation is opening the view. I would expect that it is created only once, on first time access.

However, if I replace @UIScope with @Scope(UIScopeImpl.VAADIN_UI_SCOPE_NAME) then it works as expected. Did I miss something?

Body:
It's related to the order of the @SpringView and @UIScope annotations, as the tutorial and the older wiki page briefly suggest:

// Pay attention to the order of annotations

It's probably related to how and when the annotations are processed. I did not dig that deep into the Vaadin code, but as per the the @SpringView javadoc it puts the view into a view-scope by default. Furthermore, I don't think you require the @SpringComponent annotation because you're already using @SpringView to register it a spring component.

Annotation to be placed on View-classes that should be handled by the SpringViewProvider.

This annotation is also a stereotype annotation, so Spring will automatically detect the annotated classes. By default, this annotation also puts the view into the view scope. You can override this by using another scope annotation, such as the UI scope, on your view class. However, the singleton scope will not work!

In the sample below, you'll find 2 views, the first one with the annotations in the correct order, and the second one with them swapped:

@SpringUI
@SpringViewDisplay
public class MyVaadinUI extends UI implements ViewDisplay {

    /* UI */

    private Panel springViewDisplay;

    @Override
    protected void init(VaadinRequest request) {
        VerticalLayout mainLayout = new VerticalLayout();
        HorizontalLayout buttonLayout = new HorizontalLayout();
        springViewDisplay = new Panel();

        buttonLayout.addComponent(new Button("1", event -> getNavigator().navigateTo(FirstView.VIEW_NAME)));
        buttonLayout.addComponent(new Button("2", event -> getNavigator().navigateTo(SecondView.VIEW_NAME)));
        mainLayout.addComponents(buttonLayout, springViewDisplay);
        setContent(mainLayout);

    }

    @Override
    public void showView(View view) {
        springViewDisplay.setContent((Component) view);
    }

    /* VIEWS */

    @UIScope
    @SpringView(name = FirstView.VIEW_NAME)
    public static class FirstView extends HorizontalLayout implements View {

        public static final String VIEW_NAME = "";

        @PostConstruct
        private void init() {
            System.out.println("Created first view");
            addComponent(new Label("First view - " + LocalDateTime.now()));
        }

        @Override
        public void enter(ViewChangeListener.ViewChangeEvent event) {
            // no-op
        }
    }

    @SpringView(name = SecondView.VIEW_NAME)
    @UIScope
    public static class SecondView extends HorizontalLayout implements View {

        public static final String VIEW_NAME = "secondView";

        @PostConstruct
        private void init() {
            System.out.println("Created second view");
            addComponent(new Label("Second view - " + LocalDateTime.now()));
        }

        @Override
        public void enter(ViewChangeListener.ViewChangeEvent event) {
            // no-op
        }
    }
}

As you'll notice in the animation below, when navigating to the second view a new instance is always created, while navigating to the first one will reuse the initial instance:


问:
Difference Between Datasets
Here is the problem statement:

I have 2 datasets from different years(2013 dataset and 2014 dataset), the data is multivariate with each dataset containing 38 attributes, I want to find out any difference/delta that might have occured in between two datasets in these consecutive years, this difference should be a numerical value.

So far I have applied following techniques:

1)ANOVA (This tells me that difference is there but it doesn't tell me how much the difference is)

2)Wilcoxon-Mann-Whitney U test (Same problem as ANOVA)

3)Finding the Mean Square Error between the mean of the datasets.

Questions:

1) Is their any other method/test that can be applied which would give me a numerical value of the difference between datasets?

2) If I label the 2013 dataset as "1" and 2014 dataset as "2" then can the weight's of  neural network trained to classify these dataset be used to somehow find the difference between datasets?

Note: Due to confidentiality agreement I cannot share the data here.

答:
Don't know if you have found an answer or not.

Have you tried using RMSE? You can create a score for every column of a dataset and then combine them to get an average score for the whole data.

It's not a perfect method but it should give a scale of difference when comparing multiple dataset to eachother.

If you did find a better answer than what I suggested, please so let me know as I would be interested in it.

All the best.

Title: Difference Between Datasets


答:
The problem lies in the positioning of your header. As you position it absolutely, the transform is starting always 50% from the edge. In order to have text animated properly, you can make the
 container 100% wide and then center the text inside using text centering CSS:

h1{
    position: relative;
    width: 100%;
    text-align: center;
}
.hvr-grow {
    transform-origin:center center;
    display: inline-block;
    vertical-align: middle;
    /*transform: translateZ(0);*/
    box-shadow: 0 0 1px rgba(0, 0, 0, 0);
    backface-visibility: hidden;
    -moz-osx-font-smoothing: grayscale;
    transition-duration: 0.3s;
    transition-property: transform;
}

.hvr-grow:hover,
.hvr-grow:focus,
.hvr-grow:active {
    transform: scale(1.8);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="position:relative">
<h1 class="hvr-grow">Hello I'm centered</h1>
</div></code>```

Title: centering a grow effect for a centered text

Body:
The problem lies in the positioning of your header. As you position it absolutely, the transform is starting always 50% from the edge. In order to have text animated properly, you can make the <h1/> container 100% wide and then center the text inside using text centering CSS:

h1{
    position: relative;
    width: 100%;
    text-align: center;
}
.hvr-grow {
    transform-origin:center center;
    display: inline-block;
    vertical-align: middle;
    /*transform: translateZ(0);*/
    box-shadow: 0 0 1px rgba(0, 0, 0, 0);
    backface-visibility: hidden;
    -moz-osx-font-smoothing: grayscale;
    transition-duration: 0.3s;
    transition-property: transform;
}

.hvr-grow:hover,
.hvr-grow:focus,
.hvr-grow:active {
    transform: scale(1.8);
}

<div style="position:relative">
<h1 class="hvr-grow">Hello I'm centered</h1>
</div>


答:
No, there is absolutely no guarantee about the relational position of memory from different allocations.

If this is not valid, how it passed the test cases of an online judge?

The easy answer (from me) is to say you got (un)lucky. The truth is that the mechanism of memory allocation/mapping is complex and covers more layers: application (malloc), C library implementation, OS and hardware. It is possible and in some situations even probable that consecutive malloc requests return memory that is somewhat consecutive. This is in by no way a guarantee and can easily break (e.g. after a series of intertwined mallocs and frees).

Moreover, as @StoryTeller shows, comparing pointers (except equality) to different objects is UB.

Title: Are Structs in C++ allocated memory sequentially? Somehow getting correct answer for pointer comparison everytime


问:
Static Web Assets over CDN and Optimal Number of Hosting Aliases
What is the optimal number of host aliases (i.e. storage-1.host, storage-2.host, etc.) to have with a content delivery network? I'm using Amazon Cloud Front and can set up to 10 different CNAME records. My understanding is that browsers will initiate two parallel connections to any given host, but I'm wondering if browsers will connect to an unlimited number of different hosts or is a limit set in place? I have taken a look through a few large services (such as YouTube and Flickr) and noticed that they tend to use 4 different host aliases. Is this the optimal number? Thanks!

答:
It sounds like the ideal number is 10, then. :)

The more hosts you have, the better - the whole idea is that you want as many downloads running in parallel as possible, and more hosts = more parallel downloads.


问:
Using kafka streams to create a table based on elasticsearch events
Is it possible to use Kafka streaming to create a pipeline that reads JSON from a Kafka topic and then do some logic with them and send the results to another Kafka topic or something else?

For example, I populate my topic using logs from elasticsearch. That is pretty easy using a simple logstash pipeline.

Once I have my logs in the kafka topic, I want to extract some pieces of information from the log and put them in a sort of "table" with N column(is Kafka capable of this?) and then put the table somewhere else (another topic or a db).

I didn't find any example that satisfies my criteria.

thanks

答:
Yes, it's possible.

There is no concept of columns in kafka or kafka-streams. However, you typically just define a plain old java object of your choice, with the fields that your want (fields being the equivalent of columns in this case). You produce the output in that format to an output topic (using an appropriately chosen serializer). Finally, if you want to store the result in a relational database, you map the fields into columns, typically using a kafka connect jdbc sink:
http://docs.confluent.io/current/connect/connect-jdbc/docs/sink_connector.html


问:
Crashlytics manual update to 3.8.4 causing linker errors
I have a very old legacy project (Dating somewhere from 2010). Its Crashlytics kit was last updated somewhere during 2013.

I was trying to update it. It doesn't use pods so I used the official Manual update guide.

I downloaded the updated kits.

Replaced the old Crashlytics with new one as suggested. The old one didn't have a Fabric kit so I just pasted it there and linked the library in Project settings.

These are the only two steps described there. But doing that causes linker errors:

```<code>Undefined symbols for architecture x86_64:
  "___gxx_personality_v0", referenced from:
      +[CLSDemangleOperation demangleBlockInvokeCppSymbol:] in Crashlytics(CLSDemangleOperation.o)
      +[CLSDemangleOperation demangleSwiftSymbol:] in Crashlytics(CLSDemangleOperation.o)
      -[CLSDemangleOperation main] in Crashlytics(CLSDemangleOperation.o)
      ___28-[CLSDemangleOperation main]_block_invoke in Crashlytics(CLSDemangleOperation.o)
      Dwarf Exception Unwind Info (__eh_frame) in Crashlytics(CLSDemangleOperation.o)
  "vtable for __cxxabiv1::__pointer_type_info", referenced from:
      typeinfo for std::exception const* in Crashlytics(CLSException.o)
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
  "vtable for __cxxabiv1::__vmi_class_type_info", referenced from:
      typeinfo for std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > in Crashlytics(CLSException.o)
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
  "___cxa_begin_catch", referenced from:
      CLSTerminateHandler() in Crashlytics(CLSException.o)
      ___clang_call_terminate in Crashlytics(CLSException.o)
  "std::get_terminate()", referenced from:
      _CLSExceptionCheckHandlers in Crashlytics(CLSException.o)
  "typeinfo for char const*", referenced from:
      GCC_except_table1 in Crashlytics(CLSException.o)
  "typeinfo for std::bad_alloc", referenced from:
      GCC_except_table1 in Crashlytics(CLSException.o)
  "typeinfo for std::exception", referenced from:
      GCC_except_table1 in Crashlytics(CLSException.o)
      typeinfo for std::exception const* in Crashlytics(CLSException.o)
  "___cxa_current_exception_type", referenced from:
      CLSTerminateHandler() in Crashlytics(CLSException.o)
  "___cxa_rethrow", referenced from:
      CLSTerminateHandler() in Crashlytics(CLSException.o)
  "vtable for __cxxabiv1::__class_type_info", referenced from:
      typeinfo for std::__1::__basic_string_common<true> in Crashlytics(CLSException.o)
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
  "___cxa_end_catch", referenced from:
      CLSTerminateHandler() in Crashlytics(CLSException.o)
  "___cxa_demangle", referenced from:
      +[CLSDemangleOperation demangleCppSymbol:] in Crashlytics(CLSDemangleOperation.o)
  "std::terminate()", referenced from:
      ___clang_call_terminate in Crashlytics(CLSException.o)
  "std::set_terminate(void (*)())", referenced from:
      _CLSExceptionInitialize in Crashlytics(CLSException.o)
      CLSTerminateHandler() in Crashlytics(CLSException.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

Things I have tried:

Removing both references of Crashlytics and Fabrics and relinking them.

Removing physical instances of both kits and readding them.

Cleaning derived data of XCode.

Cleaning the project.

Installing latest version via Cocoapods.

Upgrading via Fabric App

But the errors persist. Right now, I am at my wits end. Any ideas on how to fix this issue?

答:
I figured it out.

The problem was, the previous guy had modified the linker and compiler flags and removed the $(inherited) flag from them which was overriding the Cocoapods configs which in turn caused failure in linking main project with Cocoapods and therefore missing symbols as XCode couldn't find the symbols without linking.

First I removed the manual Crashlytics and then installed them via cocoapods. Now it said that symbols were missing.

To fix this:

Go to "Preprocessor Macros" and make sure $(inherited) is added to both debug and release configs.

Go to "Other Linker Flags" and make sure $(inherited) flag is added there as well.

Crashlytics 3.8.4 is now up and running.

Body:
I have a very old legacy project (Dating somewhere from 2010). Its Crashlytics kit was last updated somewhere during 2013.

I was trying to update it. It doesn't use pods so I used the official Manual update guide.

I downloaded the updated kits.

Replaced the old Crashlytics with new one as suggested. The old one didn't have a Fabric kit so I just pasted it there and linked the library in Project settings.

These are the only two steps described there. But doing that causes linker errors:

Undefined symbols for architecture x86_64:
  "___gxx_personality_v0", referenced from:
      +[CLSDemangleOperation demangleBlockInvokeCppSymbol:] in Crashlytics(CLSDemangleOperation.o)
      +[CLSDemangleOperation demangleSwiftSymbol:] in Crashlytics(CLSDemangleOperation.o)
      -[CLSDemangleOperation main] in Crashlytics(CLSDemangleOperation.o)
      ___28-[CLSDemangleOperation main]_block_invoke in Crashlytics(CLSDemangleOperation.o)
      Dwarf Exception Unwind Info (__eh_frame) in Crashlytics(CLSDemangleOperation.o)
  "vtable for __cxxabiv1::__pointer_type_info", referenced from:
      typeinfo for std::exception const* in Crashlytics(CLSException.o)
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
  "vtable for __cxxabiv1::__vmi_class_type_info", referenced from:
      typeinfo for std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > in Crashlytics(CLSException.o)
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
  "___cxa_begin_catch", referenced from:
      CLSTerminateHandler() in Crashlytics(CLSException.o)
      ___clang_call_terminate in Crashlytics(CLSException.o)
  "std::get_terminate()", referenced from:
      _CLSExceptionCheckHandlers in Crashlytics(CLSException.o)
  "typeinfo for char const*", referenced from:
      GCC_except_table1 in Crashlytics(CLSException.o)
  "typeinfo for std::bad_alloc", referenced from:
      GCC_except_table1 in Crashlytics(CLSException.o)
  "typeinfo for std::exception", referenced from:
      GCC_except_table1 in Crashlytics(CLSException.o)
      typeinfo for std::exception const* in Crashlytics(CLSException.o)
  "___cxa_current_exception_type", referenced from:
      CLSTerminateHandler() in Crashlytics(CLSException.o)
  "___cxa_rethrow", referenced from:
      CLSTerminateHandler() in Crashlytics(CLSException.o)
  "vtable for __cxxabiv1::__class_type_info", referenced from:
      typeinfo for std::__1::__basic_string_common<true> in Crashlytics(CLSException.o)
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
  "___cxa_end_catch", referenced from:
      CLSTerminateHandler() in Crashlytics(CLSException.o)
  "___cxa_demangle", referenced from:
      +[CLSDemangleOperation demangleCppSymbol:] in Crashlytics(CLSDemangleOperation.o)
  "std::terminate()", referenced from:
      ___clang_call_terminate in Crashlytics(CLSException.o)
  "std::set_terminate(void (*)())", referenced from:
      _CLSExceptionInitialize in Crashlytics(CLSException.o)
      CLSTerminateHandler() in Crashlytics(CLSException.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Things I have tried:

Removing both references of Crashlytics and Fabrics and relinking them.

Removing physical instances of both kits and readding them.

Cleaning derived data of XCode.

Cleaning the project.

Installing latest version via Cocoapods.

Upgrading via Fabric App

But the errors persist. Right now, I am at my wits end. Any ideas on how to fix this issue?


问:
Error: $injector:modulerr Module Error p0=task
i have a simple angular code with wont run due to this error;
ive add the angular-router file the server found it but it keeps giving me this error

```<code>Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.5/$injector/modulerr?p0=task&p1=Error%3A%20…0Uc%20(http%3A%2F%2Flocalhost%3A3000%2Fangular%2Fangular.min.js%3A22%3A332)
    at angular.min.js:7
    at angular.min.js:43
    at p (angular.min.js:8)
    at g (angular.min.js:42)
    at gb (angular.min.js:46)
    at c (angular.min.js:22)
    at Uc (angular.min.js:22)
    at xe (angular.min.js:21)
    at angular.min.js:333
    at HTMLDocument.b (angular.min.js:38)
</code>```

my view code is

```<code><html >
    <head>
        <title>
        </title>
    </head>
    <body ng-app="task" ng-init="first = 1;">
        <h1>Task List</h1>

        <div ng-controller="ctrl">
            <span>Values: {{first}}</span>
            <input type="text" ng-model="first" />
        </div>

        <script src="angular/angular.min.js"></script>
        <script src="bower_components/angular-route/angular-route.js"></script>
         <script src="angular/app.js"></script>
    </body>

</html>
</code>```

my app.js code

```<code>var task = angular.module('myApp', ['ngRoute']);
task.controller('ctrl', function($scope){
    $scope.first = 1;
});
</code>```

please help.

答:
Also you can do like this

```<code>var task = angular.module('myApp', ['ngRoute']);
task.controller('ctrl', taskCtrl);

function taskCtrl($scope){
 // your logic here
}
</code>```

Also move your ng-app tag to separate div and below it put JS script tags

Body:
i have a simple angular code with wont run due to this error;
ive add the angular-router file the server found it but it keeps giving me this error

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.5/$injector/modulerr?p0=task&p1=Error%3A%20…0Uc%20(http%3A%2F%2Flocalhost%3A3000%2Fangular%2Fangular.min.js%3A22%3A332)
    at angular.min.js:7
    at angular.min.js:43
    at p (angular.min.js:8)
    at g (angular.min.js:42)
    at gb (angular.min.js:46)
    at c (angular.min.js:22)
    at Uc (angular.min.js:22)
    at xe (angular.min.js:21)
    at angular.min.js:333
    at HTMLDocument.b (angular.min.js:38)

my view code is

        <title>
        </title>

Task List

            Values: {{first}}
            <input type="text" ng-model="first" />

my app.js code

var task = angular.module('myApp', ['ngRoute']);
task.controller('ctrl', function($scope){
    $scope.first = 1;
});

please help.

Body:
Also you can do like this

var task = angular.module('myApp', ['ngRoute']);
task.controller('ctrl', taskCtrl);

function taskCtrl($scope){
 // your logic here
}

Also move your ng-app tag to separate div and below it put JS script tags


问:
Choosing a simple web application framework
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages. </p>

<p>I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail. </p>

答: ASP.NET / ASP.NET MVC</p>

OwnerDisplayName: nagul

Body:
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages.

I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail.

LastEditorDisplayName: Marko Dumic

Body: ASP.NET / ASP.NET MVC

OwnerDisplayName: MarlonRibunal


答: Try this: $('form#yourform option:selected[value="a"]').length > 0

Title: JQuery Selector code validation for list of select options

Body:
I'm having situation like 3 select box is there in a form

    <form>
   <select name="select1">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 </select>

<select name="select2">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 </select>
  <select name="select3">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 </select> </form>

On submitting this form i have to check atleast one of the select box value should be "a".

Is there any one line selctor query like jQuery['form'].find('select val=="a"').length() like this .

Thanks,
Nithish.


问:
VBA refering to a variable named range to move values
Code works as expected until the last line where I attempt to move values from one range to another at which point I'm getting a "run time error 1004", so must be doing something wrong.

the range "NewRng" does produce the correct string "$A$1883:$R$2105" which if entered manually into the last line (replacing the "NewRng" reference) it produces the correct results.

Thanks in advance

```<code>    Dim NevwebLR As String
    With Sheets("NevWeb file")
    NevwebLR = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    Dim DropShipLR As String
    With Sheets("Drop Shipments")
    DropShipLR = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    Dim NevwebLR1 As String
    NevwebLR1 = NevwebLR + 1

    Dim dropshipglue As Long
    dropshipglue = Val(NevwebLR) + Val(DropShipLR)

    Dim rng1 As Range, rng2 As Range
    Dim NewRng As Range

        With ThisWorkbook.Sheets("Results")
            Set rng1 = .Range("A" & NevwebLR1)
            Set rng2 = .Range("R" & dropshipglue)

            Set NewRng = .Range(rng1, rng2)

            Debug.Print NewRng.Address
        End With

    Sheets("results").Range(NewRng).Value = Sheets("Drop Shipments").Range("A1:R" & DropShipLR).Value
</code>```

答:
You have your destination range already as Range-object, so change the last line to

NewRng.Value = Sheets("Drop Shipments").Range("A1:R" & DropShipLR).Value

Body:
Code works as expected until the last line where I attempt to move values from one range to another at which point I'm getting a "run time error 1004", so must be doing something wrong.

the range "NewRng" does produce the correct string "$A$1883:$R$2105" which if entered manually into the last line (replacing the "NewRng" reference) it produces the correct results.

Thanks in advance

    Dim NevwebLR As String
    With Sheets("NevWeb file")
    NevwebLR = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    Dim DropShipLR As String
    With Sheets("Drop Shipments")
    DropShipLR = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    Dim NevwebLR1 As String
    NevwebLR1 = NevwebLR + 1

    Dim dropshipglue As Long
    dropshipglue = Val(NevwebLR) + Val(DropShipLR)

    Dim rng1 As Range, rng2 As Range
    Dim NewRng As Range

        With ThisWorkbook.Sheets("Results")
            Set rng1 = .Range("A" & NevwebLR1)
            Set rng2 = .Range("R" & dropshipglue)

            Set NewRng = .Range(rng1, rng2)

            Debug.Print NewRng.Address
        End With

    Sheets("results").Range(NewRng).Value = Sheets("Drop Shipments").Range("A1:R" & DropShipLR).Value


问:
Laravel group routing with parameter
I have this group in my route:
}

```<code>Route::group(['prefix' => 'v1/en'], function() {}
</code>```

is it possible to change the 'en' segment uri in a parameter, so it can be changed depending on the request? Something like this:

```<code>Route::group(['prefix' => 'v1/{lang}'], function() {}
</code>```

答:
How about to generate dynamically another route group with prefix $lang inside of group with v1 prefix?

```<code>$langs = ['en', 'de', 'it'];

Route::group(['prefix' => 'v1'], function() use ($langs) {
  foreach($langs AS $lang) :

    Route::group(['prefix' => $lang], function() {

      Route::get('something', 'SomethingController@list');

    });

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

or same logic (taken from here):

```<code>Route::group(['prefix' => 'v1'], function() use ($langs) {
    Route::group(['prefix' => '{lang}'], function() {
      Route::get('something', 'SomethingController@list');
    });
});
</code>```

Title: Laravel group routing with parameter

Body:
I have this group in my route:
}

Route::group(['prefix' => 'v1/en'], function() {}

is it possible to change the 'en' segment uri in a parameter, so it can be changed depending on the request? Something like this:

Route::group(['prefix' => 'v1/{lang}'], function() {}

Body:
How about to generate dynamically another route group with prefix $lang inside of group with v1 prefix?

$langs = ['en', 'de', 'it'];

Route::group(['prefix' => 'v1'], function() use ($langs) {
  foreach($langs AS $lang) :

    Route::group(['prefix' => $lang], function() {

      Route::get('something', 'SomethingController@list');

    });

  endforeach;
});

or same logic (taken from here):

Route::group(['prefix' => 'v1'], function() use ($langs) {
    Route::group(['prefix' => '{lang}'], function() {
      Route::get('something', 'SomethingController@list');
    });
});


答:
Use attribute selector

[attr=value]

Represents an element with an attribute name of attr and whose value is exactly "value".

and hide like this:

[data-id="18"], [data-id="9036"]  {
   display:none
}
```

<p><strong>Snippet:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>[data-id="18"],
[data-id="9036"] {
  display: none
}</code>```

hide

hide

show

show
```

Title: Hide <div class="kk-star-ratings top-right rgt" data-id="18">

Body: Hi I can hide the element :  in all our site but I want to hide just on certains page. Which CSS code I can use as to hide only certains data-id :

Body:
Use attribute selector

[attr=value]

Represents an element with an attribute name of attr and whose value is exactly "value".

and hide like this:

[data-id="18"], [data-id="9036"]  {
   display:none
}

Snippet:

[data-id="18"],
[data-id="9036"] {
  display: none
}

<div class="kk-star-ratings  top-right rgt" data-id="18">hide</div>
<div class="kk-star-ratings  top-right rgt" data-id="9036">hide</div>

<div class="kk-star-ratings  top-right rgt" data-id="11218">show</div>
<div class="kk-star-ratings  top-right rgt" data-id="98756036">show</div>


问:
@ExceptionHandler doesn't catch HttpMessageNotReadableException
I have the following exception handler:

```<code>@ControllerAdvice
public class MyExceptionHandler {
  private static final Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);
    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void handle(HttpMessageNotReadableException e) {
        logger.warn("HttpMessageNotReadableException occurred.", e);
        throw e;
    }
</code>```

But it doesn't catch HttpMessageNotReadableException?! In my logs I see (it prints spring itself):

```<code>2017-07-04 13:26:38,699 DEBUG org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.getMethodArgumentValues:164 - Failed to resolve argument 0 of type 'com.finvale.model.Client'
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize value of type java.time.LocalDate from String "Invalid date": Text 'Invalid date' could not be parsed at index 0
 at [Source: java.io.PushbackInputStream@4f30395; line: 1, column: 103] (through reference chain: com.finvale.model.Client["birthDay"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.time.LocalDate from String "Invalid date": Text 'Invalid date' could not be parsed at index 0
 at [Source: java.io.PushbackInputStream@4f30395; line: 1, column: 103] (through reference chain: com.finvale.model.Client["birthDay"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:240)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:225)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:201)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:150)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:128)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:108)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
</code>```

Is it possible to catch this exception in my ExceptionHandler ?

P.S.

I agree that my code contains mistake. I neeed to specify type in annotation.
I changed it like this:

```<code> @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void handle(HttpMessageNotReadableException e) {
</code>```

but I still see same behaviour.

handle method doesn't invoke

答:
Finally I found solution:

Root cause was that there was 2 places with @ExceptionHandler

Inside controller

Inside the Separated class MyExceptionHandler described in question.

I moved method to MyExceptionHandler ans it became working.

Body:
I have the following exception handler:

@ControllerAdvice
public class MyExceptionHandler {
  private static final Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);
    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void handle(HttpMessageNotReadableException e) {
        logger.warn("HttpMessageNotReadableException occurred.", e);
        throw e;
    }

But it doesn't catch HttpMessageNotReadableException?! In my logs I see (it prints spring itself):

2017-07-04 13:26:38,699 DEBUG org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.getMethodArgumentValues:164 - Failed to resolve argument 0 of type 'com.finvale.model.Client'
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize value of type java.time.LocalDate from String "Invalid date": Text 'Invalid date' could not be parsed at index 0
 at [Source: java.io.PushbackInputStream@4f30395; line: 1, column: 103] (through reference chain: com.finvale.model.Client["birthDay"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.time.LocalDate from String "Invalid date": Text 'Invalid date' could not be parsed at index 0
 at [Source: java.io.PushbackInputStream@4f30395; line: 1, column: 103] (through reference chain: com.finvale.model.Client["birthDay"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:240)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:225)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:201)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:150)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:128)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:108)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

Is it possible to catch this exception in my ExceptionHandler ?

P.S.

I agree that my code contains mistake. I neeed to specify type in annotation.
I changed it like this:

 @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void handle(HttpMessageNotReadableException e) {

but I still see same behaviour.

handle method doesn't invoke


问:
404 error when I click a link while I'm under a tag page
first of all sorry for my English.

And my problem is: If I'm on a "tag" page and click a link which refers to another page in my site I got 404 error. Links are working when I'm in category page or main page.

What should I do?

答:
The link you posted in your footer isn't properly formed to resolve correctly. The href in that link is simply href="kullanici-sozlesmesi", with no url before it.

Changing that footer link to href="http://blog.ajuans.com/tag/kullanici-sozlesmesi" should fix the problem


问:
Permission Error on Video File Open
I am trying to write a Python script to play a video, but I'm getting this permission error:

```<code>Traceback (most recent call last):
  File "alarm.py", line 17, in <module>
    print play_video()
  File "alarm.py", line 14, in play_video
    p = subprocess.Popen([vlc_path, video])
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 13] Permission denied
</code>```

I've changed the permissions to both the video and the video player to 755 (confirmed that they are set to -rwxrwxr-x), but outside of that I can't think of what to do.

alarm.py

```<code>import os
import subprocess

def play_video():
    video = "/path_to_video"
    vlc_path = "/path_to_vlc"
    p = subprocess.Popen([vlc_path, video])

if __name__ == '__main__':
    print play_video()
</code>```

答:
Not sure why I got the unhelpful error message that I did, but I had the command wrong.  It should have been:

p = subprocess.Popen(['open', '-a', vlc_path, video])

Title: Permission Error on Video File Open

Body:
I am trying to write a Python script to play a video, but I'm getting this permission error:

Traceback (most recent call last):
  File "alarm.py", line 17, in <module>
    print play_video()
  File "alarm.py", line 14, in play_video
    p = subprocess.Popen([vlc_path, video])
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 13] Permission denied

I've changed the permissions to both the video and the video player to 755 (confirmed that they are set to -rwxrwxr-x), but outside of that I can't think of what to do.

alarm.py

import os
import subprocess

def play_video():
    video = "/path_to_video"
    vlc_path = "/path_to_vlc"
    p = subprocess.Popen([vlc_path, video])

if __name__ == '__main__':
    print play_video()