问:
my application bug and stop I don't know why
I made a navigation drawer in my project, then I wanted to make a button for sliding left and right but my app stops and blocks.

I get this error:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{radiofm.arabelradio/radiofm.arabelradio.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
</code>```

Program:

```<code>package radiofm.arabelradio;

import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import java.io.IOException;

import static android.media.AudioManager.STREAM_MUSIC;

public class MainActivity extends AppCompatActivity {

    ImageButton id_play;
    MediaPlayer mediaPlayer;
    boolean prepared = false;
    boolean started =false;
    String stream ="http://arabelfm.ice.infomaniak.ch/arabelprodcastfm.mp3";
    //main_page contain arabel_photo player for radio

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /////////////////////////////////////////////////////////////////////////////
        id_play = (ImageButton) findViewById(R.id.id_play);
        id_play.setEnabled(false);
        //id_play.setText("LOADING");
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        new PlayerTask().execute(stream);
        id_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (started){
                    started=false;
                    mediaPlayer.pause();
                    id_play.setImageResource(R.drawable.play);
                   // id_play.setText("PLAY");
                }
                else {
                    started=true;
                    mediaPlayer.start();
                    id_play.setImageResource(R.drawable.pause);

                    //id_play.setText("PAUSE");
                }
            }
        });
        //main_page contain arabel_photo player for radio//////////////////////////:

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle=new ActionBarDrawerToggle(this,mDrawerLayout, R.string.open,R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////
    class PlayerTask extends AsyncTask<String,Void,Boolean>{

        @Override
        protected Boolean doInBackground(String... strings) {

            try {
                mediaPlayer.setDataSource(strings[0] );
                mediaPlayer.prepare();
                prepared=true;
            } catch (IOException e) {
                e.printStackTrace();
            }

            return prepared;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            id_play.setEnabled(true);
            id_play.setImageResource(R.drawable.play);

            // id_play.setText("PLAY");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(started){
            mediaPlayer.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(started){
            mediaPlayer.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(prepared){
            mediaPlayer.release();
        }
    }
/////////////////////////////////////////////////////////////////////////////////////////////////////
    //main_page contain arabel_photo player for radio//////////////////////////:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mToggle.onOptionsItemSelected(item))
        {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

答:
just add this in your code</p>

```<code>getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
</code>```

Body:
I made a navigation drawer in my project, then I wanted to make a button for sliding left and right but my app stops and blocks.

I get this error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{radiofm.arabelradio/radiofm.arabelradio.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference

Program:

package radiofm.arabelradio;

import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import java.io.IOException;

import static android.media.AudioManager.STREAM_MUSIC;

public class MainActivity extends AppCompatActivity {

    ImageButton id_play;
    MediaPlayer mediaPlayer;
    boolean prepared = false;
    boolean started =false;
    String stream ="http://arabelfm.ice.infomaniak.ch/arabelprodcastfm.mp3";
    //main_page contain arabel_photo player for radio

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /////////////////////////////////////////////////////////////////////////////
        id_play = (ImageButton) findViewById(R.id.id_play);
        id_play.setEnabled(false);
        //id_play.setText("LOADING");
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        new PlayerTask().execute(stream);
        id_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (started){
                    started=false;
                    mediaPlayer.pause();
                    id_play.setImageResource(R.drawable.play);
                   // id_play.setText("PLAY");
                }
                else {
                    started=true;
                    mediaPlayer.start();
                    id_play.setImageResource(R.drawable.pause);

                    //id_play.setText("PAUSE");
                }
            }
        });
        //main_page contain arabel_photo player for radio//////////////////////////:

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle=new ActionBarDrawerToggle(this,mDrawerLayout, R.string.open,R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////
    class PlayerTask extends AsyncTask<String,Void,Boolean>{

        @Override
        protected Boolean doInBackground(String... strings) {

            try {
                mediaPlayer.setDataSource(strings[0] );
                mediaPlayer.prepare();
                prepared=true;
            } catch (IOException e) {
                e.printStackTrace();
            }

            return prepared;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            id_play.setEnabled(true);
            id_play.setImageResource(R.drawable.play);

            // id_play.setText("PLAY");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(started){
            mediaPlayer.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(started){
            mediaPlayer.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(prepared){
            mediaPlayer.release();
        }
    }
/////////////////////////////////////////////////////////////////////////////////////////////////////
    //main_page contain arabel_photo player for radio//////////////////////////:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mToggle.onOptionsItemSelected(item))
        {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Body:
just add this in your code

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);


来源: stackexchange

问:
How to set text to go over an image strictly in HTML?
I am writing an emailed newsletter, and need to set an image as the footer, with a few clickable links over it. I have figured it out using both HTML and CSS, but no matter where I searched I could not find a way to do this strictly using HTML. Can anyone help me out?

```<code><!--Footer-->
                        <tr id="footer">
                        <td id="footer" style="font-family: 'Titillium Web', sans-serif;;-webkit-text-size-adjust:none;background-image: url" img url"" templates\uuaemail-foot.jpg";padding-left:="" 20px;padding-right:="" 20px;padding-top:="" 10px;padding-bottom:="" 20px;"="">
                        <table height="101" width="602">
                        <tbody>
                            <tr>
                                <td id="footer" style="font-size: 10px;color:white;" height="95" valign="top" width="600" align="center"><p><br></p><p class="style3"><strong><span style="font-size: 12px;">admissions.rutgers.edu<br></span></strong></p><p class="style3"><span class="style7"><span style="font-size: 8px;"><strong> University Undergraduate Admissions</strong>, Operations Center<br>©2017 , an equal opportunity, affirmative action institution.</span></span></p></td>
                            </tr>
                        </tbody>
                    </table>
                </td>
</code>```

Is what I currently have (with CSS styling)

update: My issue is that the email is widely sent to Ms Outlook 2016, which I have both heard and seen through testing that it does not process CSS styles very well. When I opened this code in Outlook, it showed the CSS styling commands at the top of the message, and did not apply it at all.

答: CSS is just an organized way for the the stylesheet. Although not recommended, you can use inline styles with just the HTML to achieve almost everything, if you post your code, may be some of us can suggest a definite answer.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am writing an emailed newsletter, and need to set an image as the footer, with a few clickable links over it. I have figured it out using both HTML and CSS, but no matter where I searched I could not find a way to do this strictly using HTML. Can anyone help me out?

admissions.rutgers.edu

 University Undergraduate Admissions, Operations Center
©2017 , an equal opportunity, affirmative action institution.

Is what I currently have (with CSS styling)

update: My issue is that the email is widely sent to Ms Outlook 2016, which I have both heard and seen through testing that it does not process CSS styles very well. When I opened this code in Outlook, it showed the CSS styling commands at the top of the message, and did not apply it at all.


问:
How to Optimize and Scale Ruby on Rails App with Nginx and Passenger
I have an app in production which uses Ruby on Rails with Nginx and Passenger, the performance is good at the start but as the time goes by (after an hour or more) it slows down, I need to restart the Nginx for it to increase its performance again. May I know how to make it more optimize and scalable and avoid in keep on restarting. Thanks, guys need your help so bad.

答:
There are some settings you can do to optimize your Nginx server.

If you have root access to your server and have Nginx correctly added, you can consider some changes.

1) Run sudo vim /etc/nginx/nginx.conf & consider these settings based on what are your needs (don't replace the whole code into your server as some of the default setting are not here. Just add ones you neeed):

```<code>user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
        worker_connections 768;
        multi_accept on;
        use                 epoll;
}

worker_rlimit_nofile 40000;

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        client_body_timeout 500s;
        client_header_timeout 500s;
        keepalive_timeout 500s;
        send_timeout 300s;
        types_hash_max_size 2048;
        # server_tokens off;
        client_max_body_size 100000M;
        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log off;
        #access_log /var/log/nginx/access.log;
        #error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;
        gzip_disable "msie6";
                gzip_vary on;
        # gzip_proxied any;
        gzip_comp_level 2;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        gzip_min_length  10240;
        gzip_proxied     expired no-cache no-store private auth;
        gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
        gzip_disable "MSIE [1-6]\.";

}
</code>```

You can change the numbers based on your application and needs.

2) Run sudo vim /etc/nginx/sites-enabled/default & consider these settings based on what are your needs (don't replace the whole code into your server as some of the default setting are not here. Just add ones you neeed):

```<code>server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        passenger_enabled on;

        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    location ~*  \.(jpg|jpeg|png|gif|ico)$ {
        access_log        off;
        log_not_found     off;
        expires 30d;
    }

    location ~*  \.(js)$ {
        access_log        off;
        log_not_found     off;
        expires 150d;
    }
    location ~*  \.(css)$ {
        access_log        off;
        log_not_found     off;
        expires 150d;
    }
}
</code>```

You can change the numbers based on your application and needs.

Remember to restart ngnix after changes.

Again be careful to what you add or remove and again DO NOT copy & paste the whole code as some default settings are not here.

One other thing would be take a look at your logs & tmp files/folder as you can eliminate logs to take less memory and space. You can also take a look tmp folder and settings.

You can also consider (recommended) doing caching in your views. As you know rails has Fragment and Russian doll caching. Caching will always help boosting response time.

If you are not familier with caching, there is also something called progressive rendering. You can use gem 'progressive_render' and watch this toturial.

Hope it helps.

Body:
There are some settings you can do to optimize your Nginx server.

If you have root access to your server and have Nginx correctly added, you can consider some changes.

1) Run sudo vim /etc/nginx/nginx.conf & consider these settings based on what are your needs (don't replace the whole code into your server as some of the default setting are not here. Just add ones you neeed):

user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
        worker_connections 768;
        multi_accept on;
        use                 epoll;
}

worker_rlimit_nofile 40000;

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        client_body_timeout 500s;
        client_header_timeout 500s;
        keepalive_timeout 500s;
        send_timeout 300s;
        types_hash_max_size 2048;
        # server_tokens off;
        client_max_body_size 100000M;
        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log off;
        #access_log /var/log/nginx/access.log;
        #error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;
        gzip_disable "msie6";
                gzip_vary on;
        # gzip_proxied any;
        gzip_comp_level 2;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        gzip_min_length  10240;
        gzip_proxied     expired no-cache no-store private auth;
        gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
        gzip_disable "MSIE [1-6]\.";

}

You can change the numbers based on your application and needs.

2) Run sudo vim /etc/nginx/sites-enabled/default & consider these settings based on what are your needs (don't replace the whole code into your server as some of the default setting are not here. Just add ones you neeed):

server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        passenger_enabled on;

        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    location ~*  \.(jpg|jpeg|png|gif|ico)$ {
        access_log        off;
        log_not_found     off;
        expires 30d;
    }

    location ~*  \.(js)$ {
        access_log        off;
        log_not_found     off;
        expires 150d;
    }
    location ~*  \.(css)$ {
        access_log        off;
        log_not_found     off;
        expires 150d;
    }
}

You can change the numbers based on your application and needs.

Remember to restart ngnix after changes.

Again be careful to what you add or remove and again DO NOT copy & paste the whole code as some default settings are not here.

One other thing would be take a look at your logs & tmp files/folder as you can eliminate logs to take less memory and space. You can also take a look tmp folder and settings.

You can also consider (recommended) doing caching in your views. As you know rails has Fragment and Russian doll caching. Caching will always help boosting response time.

If you are not familier with caching, there is also something called progressive rendering. You can use gem 'progressive_render' and watch this toturial.

Hope it helps.


问:
GROUP_CONCAT with limit
I have table with player-s in many-to-many relation with skill-s

The goal is to list the players and their "top 3 skills" with a single query.

fiddle

```<code>create table player(
  id int primary key
);

create table skill(
  id int primary key,
  title varchar(100)
);

create table player_skills (
  id int primary key,
  player_id int,
  skill_id int,
  value int
);
</code>```

Query:

```<code>SELECT
p.id,
group_concat(s.title  SEPARATOR ', ') as skills

FROM player p
LEFT JOIN player_skills ps ON ps.player_id = p.id
LEFT JOIN skill s ON s.id = ps.skill_id

WHERE ps.value > 2
-- skills limit 3 some how ...
group by p.id
order by s.id

-- expected result
-- player_ID, skills
-- 1 , 'one'
-- 2 , 'one'
-- 3 , 'two, three, four'
</code>```

As you can see in the fiddle the result of the query is missing only the limit of 3 skills.

I tried several variation of sub queries.. joins and so but with no effect.

答:
There is a much cleaner solution. Wrap it inside another SELECT statement.

```<code>SELECT GROUP_CONCAT(id) FROM (
    SELECT DISTINCT id FROM people LIMIT 4
) AS ids;

/* Result 134756,134754,134751,134750 */
</code>```

Title: GROUP_CONCAT with limit

Body:
I have table with player-s in many-to-many relation with skill-s

The goal is to list the players and their "top 3 skills" with a single query.

fiddle

create table player(
  id int primary key
);

create table skill(
  id int primary key,
  title varchar(100)
);

create table player_skills (
  id int primary key,
  player_id int,
  skill_id int,
  value int
);

Query:

SELECT
p.id,
group_concat(s.title  SEPARATOR ', ') as skills

FROM player p
LEFT JOIN player_skills ps ON ps.player_id = p.id
LEFT JOIN skill s ON s.id = ps.skill_id

WHERE ps.value > 2
-- skills limit 3 some how ...
group by p.id
order by s.id

-- expected result
-- player_ID, skills
-- 1 , 'one'
-- 2 , 'one'
-- 3 , 'two, three, four'

As you can see in the fiddle the result of the query is missing only the limit of 3 skills.

I tried several variation of sub queries.. joins and so but with no effect.

Body:
There is a much cleaner solution. Wrap it inside another SELECT statement.

SELECT GROUP_CONCAT(id) FROM (
    SELECT DISTINCT id FROM people LIMIT 4
) AS ids;

/* Result 134756,134754,134751,134750 */


问:
How to get integer values from array based on first digits java
I have int number value and int[] numberArray.

I want to get all values from numberArray that starts with number.

What I am trying to do is

```<code>for (int i=0;i<numbers.length;i++){
    if(numberArray[i] "starts with" number){
        System.out.print(numberArray[i]);
     }
}
</code>```

I also need to use 2 and 3 digit numbers.

Could you help me find a solution for that?

EDIT: Thanks for help, found a solution. At the end code look like that:

```<code>String num = String.valueOf(number);
for (int i =0; i< numberArray.size();i++) {
    String anumber = String.valueOf(numberArray[i]);
    if (anumber.startsWith(num)){
        System.out.print(numberArray[i])
    }
}
</code>```

答:
```<code>class Test
{ static int firstDigit(int x)
    {
        // Keep dividing by 10 until it is
        // greater than equal to 10
        while(x >= 10)
            x = x/10;
        return x;
    }

    // Driver method
    public static void main(String args[])
    {
        System.out.println(firstDigit(12345));
        System.out.println(firstDigit(5432));
    }
}
</code>```

Body:
I have int number value and int[] numberArray.

I want to get all values from numberArray that starts with number.

What I am trying to do is

for (int i=0;i<numbers.length;i++){
    if(numberArray[i] "starts with" number){
        System.out.print(numberArray[i]);
     }
}

I also need to use 2 and 3 digit numbers.

Could you help me find a solution for that?

EDIT: Thanks for help, found a solution. At the end code look like that:

String num = String.valueOf(number);
for (int i =0; i< numberArray.size();i++) {
    String anumber = String.valueOf(numberArray[i]);
    if (anumber.startsWith(num)){
        System.out.print(numberArray[i])
    }
}


问:
Remove DIV dynamically with JQuery
i have a problem to reference an identifier of a DIV. I allow to add a div with a text field and a button to delete the text field, and i set a id to the DIV like an array with this code:

```<code>$('#aggiungi').on('click',function () {
        $count ++;
        $('#corsi').append(
            '<div class="form-group row" id="corso['+$count+']>' +
                '<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
                '<div class="col-sm-10 form-inline">' +
                    '<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
                    '<a class="btn btn-default" id="eliminacorso['+$count+']" aria-label="Elimina">' +
                        '<i class="fa fa-times" aria-hidden="true"></i>' +
                    '</a>' +
                '</div>' +
            '</div>' +
        '');
    });
</code>```

So.. if i press on the botton at the at the side of the text area, i'll call a function that will remove it.
The skeleton of the function is the follow:

```<code>$('#eliminacorso[]').on('click', function() {
  $count --;
  $('#corso[]').remove();
});
</code>```

So my ask is: How can i insert between the square brackets the right identifier of the div?

答:
A better choice is:-

1.Instead of using id use button class

2.And then use event delegation concept like below:-

```<code>$(document).on('click','.btn-default',function(){
 $(this).closest('.form-group').remove();
});
</code>```

Reference:- https://api.jquery.com/closest/

Title: Remove DIV dynamically with JQuery

Body:
i have a problem to reference an identifier of a DIV. I allow to add a div with a text field and a button to delete the text field, and i set a id to the DIV like an array with this code:

$('#aggiungi').on('click',function () {
        $count ++;
        $('#corsi').append(
            '
' +
                'Corso ' + $count +'' +
                '
' +
                    '<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
                    '' +
                        '' +
                    '' +
                '
' +
            '
' +
        '');
    });

So.. if i press on the botton at the at the side of the text area, i'll call a function that will remove it.
The skeleton of the function is the follow:

$('#eliminacorso[]').on('click', function() {
  $count --;
  $('#corso[]').remove();
});

So my ask is: How can i insert between the square brackets the right identifier of the div?

Body:
A better choice is:-

1.Instead of using id use button class

2.And then use event delegation concept like below:-

$(document).on('click','.btn-default',function(){
 $(this).closest('.form-group').remove();
});

Reference:- https://api.jquery.com/closest/


问:
mysql - selecting values from a table given column number
is it possible in mysql to select a value from a table by specifying the column number instead of the column name ?</p>

答:
I think for that you have to execute a single query using variables recursively.
like using for loop to do that. </p>

ContentLicense: CC BY-SA 2.5


问:
Is an undefined ng-bind more expensive than an ng-bind and ng-show?
Supposing toShowVar us undefined, which is more expensive?

```<code><span ng-bind="toShowVar" ng-show="toShowVar"></span>
</code>```

or

```<code><span ng-bind="toShowVar"></span>
</code>```

The latter would obviously not print anything on the screen if the variable is undefined.

答:
If you use ng-bind="toShowVar" the ng-show="toShowVar" will be useless, because using ng-bind is sufficient to render the span with an empty content if toShowVar was undefined.

So using both of them will be more expensive due to the second useless test in ng-show="toShowVar", as it will check again for the value of toShowVar and then try to add the class .ng-hide to the element.

But the difference is that with only ng-bind the span will be rendered in the page with empty content, and using ng-show will render it but with dispaly:none from .ng-hide class.

Body:
Supposing toShowVar us undefined, which is more expensive?

or

The latter would obviously not print anything on the screen if the variable is undefined.


问:
Run Debian Bash script with PHP
I'm having trouble to run a bash file using PHP.

PHP File :

```<code>chdir('/var/www/PATH/inc/bash/');
exec('./status.sh argument, $output);
</code>```

Bash File :

```<code>#!/bin/bash
echo 'test' >> /var/www/PATH/inc/bashOutput/test.txt
</code>```

PHP File (ls -al handler.func.php) :

```<code>-rw-r--r-- 1 root root 461 Jul  5 11:35 handler.func.php
</code>```

Bash File (ls -al status.sh) :

```<code>-rwxr-xr-x 1 root root 255 Jul  5 11:39 status.sh
</code>```

Script is working using through root with SSH.

I'm not a pro on Linux.
But I think it's a problem come with the file owner.

But I have already done some damages in the past with "chown" so If it is indead the problem I would prefer some guidance from more experienced people.

Thanks for you help,
Konorr.

答:
Script is working using through root with SSH. There is the problem. When a PHP script run via a web request it usually runs as the user www-data. In anycase <?php exec('./status.sh argument, $output);?> in a security hole. Most server admins would have this disabled.

Your other option is to put sudo in your exec function exec('sudo bash /var/www/PATH/inc/bash/status.sh'). Along with running the script with an absolute path bash /var/www/PATH/inc/bash/status.sh

Why can't you run a cron on your script?

Title: Run Debian Bash script with PHP

Body:
I'm having trouble to run a bash file using PHP.

PHP File :

chdir('/var/www/PATH/inc/bash/');
exec('./status.sh argument, $output);

Bash File :

#!/bin/bash
echo 'test' >> /var/www/PATH/inc/bashOutput/test.txt

PHP File (ls -al handler.func.php) :

-rw-r--r-- 1 root root 461 Jul  5 11:35 handler.func.php

Bash File (ls -al status.sh) :

-rwxr-xr-x 1 root root 255 Jul  5 11:39 status.sh

Script is working using through root with SSH.

I'm not a pro on Linux.
But I think it's a problem come with the file owner.

But I have already done some damages in the past with "chown" so If it is indead the problem I would prefer some guidance from more experienced people.

Thanks for you help,
Konorr.


问:
Serial Receiving from Arduino to Raspberry Pi with PySerial stops after a while
I'm working on a project in which I have to receive some 25 character data at a time in order to process it in Raspberry Pi. Here is the example code that generates some data I want to receive from Arduino:

```<code>char i =0;
char  a =0;
char b=0;

void setup(){

 Serial.begin(9600);
 for(i=0;i<25;i++){

    Serial.print('l');}
    Serial.print('\n');
    delay(2000);
}

void loop(){

 for(i=0;i<25;i++){
     for(a=0;a<i;a++){
      if((a==9)||(a==19)||(a==24))
          Serial.print('l');
      else
          Serial.print('d');
     }
     for(b=0;b<25-i;b++){
          Serial.print('l');
     }

     delay(2000);
  }
}
</code>```

It sends a line like this 'llllddddllldddd...' This line is 25 characters length. Now, I want to receive this with Raspberry Pi. Here is the code I'm trying to work:

```<code>ser = serial.Serial('/dev/AMA0',9600,timeout=1)
ser.open()

try:
   serial_data = ser.readline()
   print serial_data
except serial.serialutil.SerialException:
   pass
</code>```

This code receives data very correctly for like 5 seconds, and then suddenly stops receiving.

Moreover, when I try the following, I get no output, or Input/output errors.

```<code>serial_data = ser.readline()
print serial_data
</code>```

EDIT1:
Okay, I commented the exception now. It gives the following error:

```<code> raise SerialException('device reporst rediness to read but returned no data (device disconnected?)')
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)
</code>```

What is the correct way to receive a 25 character data from arduino into raspberry via PySerial? Any help will be greately appreciated.

答:
Try sudo rasbpi-config,
choose interface option, say 'no' to first message ("kernel login"), 'yes' to second message ("serial communication on").  I found if the first message is on it throws errors.  Saying 'no' fixes it.

Body:
I'm working on a project in which I have to receive some 25 character data at a time in order to process it in Raspberry Pi. Here is the example code that generates some data I want to receive from Arduino:

char i =0;
char  a =0;
char b=0;

void setup(){

 Serial.begin(9600);
 for(i=0;i<25;i++){

    Serial.print('l');}
    Serial.print('\n');
    delay(2000);
}

void loop(){

 for(i=0;i<25;i++){
     for(a=0;a<i;a++){
      if((a==9)||(a==19)||(a==24))
          Serial.print('l');
      else
          Serial.print('d');
     }
     for(b=0;b<25-i;b++){
          Serial.print('l');
     }

     delay(2000);
  }
}

It sends a line like this 'llllddddllldddd...' This line is 25 characters length. Now, I want to receive this with Raspberry Pi. Here is the code I'm trying to work:

ser = serial.Serial('/dev/AMA0',9600,timeout=1)
ser.open()

try:
   serial_data = ser.readline()
   print serial_data
except serial.serialutil.SerialException:
   pass

This code receives data very correctly for like 5 seconds, and then suddenly stops receiving.

Moreover, when I try the following, I get no output, or Input/output errors.

serial_data = ser.readline()
print serial_data

EDIT1:
Okay, I commented the exception now. It gives the following error:

 raise SerialException('device reporst rediness to read but returned no data (device disconnected?)')
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)

What is the correct way to receive a 25 character data from arduino into raspberry via PySerial? Any help will be greately appreciated.


问:
How to set store id to cms block output
I am using below code to display static block content but it display only first store block every time.I am load this cms block on admin side.
I have two block with same identifier but assign it to diffrent store so i would like to display it store wise.

Here is code i m using but it didn't help.

```<code>Mage::app()->getLayout()->createBlock('cms/block')->setBlockId('pdf_page_of')->setStoreId($storeId)->toHtml()
</code>```

答:
Try this</p>

```<code>/* set required store */
    Mage::app()->setCurrentStore($storeId);
            $addresBlock =  Mage::app()->getLayout()->createBlock('cms/block')->setBlockId('pdfaddress')->toHtml();
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
/* reset admin store after wind up our purpose.*/
</code>```

Title: How to set store id to cms block output

Body:
I am using below code to display static block content but it display only first store block every time.I am load this cms block on admin side.
I have two block with same identifier but assign it to diffrent store so i would like to display it store wise.

Here is code i m using but it didn't help.

Mage::app()->getLayout()->createBlock('cms/block')->setBlockId('pdf_page_of')->setStoreId($storeId)->toHtml()

Body:
Try this

/* set required store */
    Mage::app()->setCurrentStore($storeId);
            $addresBlock =  Mage::app()->getLayout()->createBlock('cms/block')->setBlockId('pdfaddress')->toHtml();
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
/* reset admin store after wind up our purpose.*/


问:
How to handle ImageFiled in Django rest framework?
I am new to django rest framework and trying to handle image data. After adding an ImageFiled i can upload image to my model. But on accessing that image via browser, the browser returns a page not found error.

My model

```<code>from __future__ import unicode_literals
from django.conf import settings
from django.db import models
from rest_framework import serializers
from urlparse import urljoin

class Item(models.Model):
    name = models.CharField(max_length=64, verbose_name='name')
    address = models.CharField(max_length=64, verbose_name='address')
    image = models.ImageField(max_length=None, null=True)

def __str__(self):
    return self.name
</code>```

Model serializer

```<code>class ItemSerializer(serializers.ModelSerializer):

class Meta:
    model = Hotel
    fields = ('name','address','id','image')
</code>```

The field image returns a url and on hitting that url the browser returns a 404 error. So what is the proper way to implemet an api with image data?

答:
You may need to add in your urls.py,

```<code>from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

Body:
I am new to django rest framework and trying to handle image data. After adding an ImageFiled i can upload image to my model. But on accessing that image via browser, the browser returns a page not found error.

My model

from __future__ import unicode_literals
from django.conf import settings
from django.db import models
from rest_framework import serializers
from urlparse import urljoin

class Item(models.Model):
    name = models.CharField(max_length=64, verbose_name='name')
    address = models.CharField(max_length=64, verbose_name='address')
    image = models.ImageField(max_length=None, null=True)

def __str__(self):
    return self.name

Model serializer

class ItemSerializer(serializers.ModelSerializer):

class Meta:
    model = Hotel
    fields = ('name','address','id','image')

The field image returns a url and on hitting that url the browser returns a 404 error. So what is the proper way to implemet an api with image data?

Body:
You may need to add in your urls.py,

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


问:
RxJava Zip two observables without completing them
I have two observables: first is from library RxAndroidBle:

```<code>Observable<RxBleConnection> bluetoothObservable = RxBleClient.create(getBaseContext()).getBleDevice(macAddress)
.establishConnection(false)
</code>```

Which connects to device and keeps connection while it has subscribers, and another

```<code>Observable<Response> serverObservable = Observable.fromCallable(() -> callServer())
</code>```

Then I zip them together

```<code>bluetoothObservable.zipWith(serverObservable , (rxBleConnection, s) -> {
                                Log.d(TAG, "zip done");
                                return "mock result";
                            }).subscribe((s) -> {},
                                    Throwable::printStackTrace);
</code>```

But after zip bluetoothObservable gets unsubscribed and connection immediately falls. What should I do to zip those observables and keep bluetoothObservable alive/subscribed?

答:
Instead of .zip() you can use:

```<code>Observable.combineLatest(
  bluetoothObservable,
  serverObservable,
  (rxBleConnection, s) -> {
    Log.d(TAG, "combined");
    return "mock result";
  }
)
  .subscribe(
    (s) -> {},
    Throwable::printStackTrace
  )
</code>```

Explanation: zip tries to combine outputs from both Observables one by one. If one of them will complete and all previous emissions from that Observable were matched — there is no point of keeping the subscription to the other Observable as the subsequent emissions will not be used. combineLatest just tries to combine all emissions from both Observables into pairs that are the latest.

Body:
I have two observables: first is from library RxAndroidBle:

Observable<RxBleConnection> bluetoothObservable = RxBleClient.create(getBaseContext()).getBleDevice(macAddress)
.establishConnection(false)

Which connects to device and keeps connection while it has subscribers, and another

Observable<Response> serverObservable = Observable.fromCallable(() -> callServer())

Then I zip them together

bluetoothObservable.zipWith(serverObservable , (rxBleConnection, s) -> {
                                Log.d(TAG, "zip done");
                                return "mock result";
                            }).subscribe((s) -> {},
                                    Throwable::printStackTrace);

But after zip bluetoothObservable gets unsubscribed and connection immediately falls. What should I do to zip those observables and keep bluetoothObservable alive/subscribed?

Body:
Instead of .zip() you can use:

Observable.combineLatest(
  bluetoothObservable,
  serverObservable,
  (rxBleConnection, s) -> {
    Log.d(TAG, "combined");
    return "mock result";
  }
)
  .subscribe(
    (s) -> {},
    Throwable::printStackTrace
  )

Explanation: zip tries to combine outputs from both Observables one by one. If one of them will complete and all previous emissions from that Observable were matched — there is no point of keeping the subscription to the other Observable as the subsequent emissions will not be used. combineLatest just tries to combine all emissions from both Observables into pairs that are the latest.


问:
Hello World is not displaying in react native android
Hi I have made Hello World program in react-native for android. I followed this https://facebook.github.io/react-native/docs/tutorial.html#content but it is not diplaying "Hello World" on screen when it launch app.

It is displaying empty screen. How can I fix this issue.

index.android.js

```<code>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  Text
} from 'react-native';

export default class AwesomeProject extends Component {
  render() {
    return (
        <Text>Hello World!</Text>
    );
  }
}

AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
</code>```

Build Logs

```<code>E:\React Programming\AwesomeProject>react-native run-android
Starting JS server...
Running C:\Users\ch-e00925\AppData\Local\Android\sdk/platform-tools/adb -s ZY223
8CX5L reverse tcp:8081 tcp:8081
Building and installing the app on the device (cd android && gradlew.bat install
Debug...
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72301Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72301Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42321Library UP-TO-DATE
:app:prepareComFacebookFrescoDrawee0110Library UP-TO-DATE
:app:prepareComFacebookFrescoFbcore0110Library UP-TO-DATE
:app:prepareComFacebookFrescoFresco0110Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipeline0110Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipelineBase0110Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipelineOkhttp30110Library UP-TO-DATE
:app:prepareComFacebookReactReactNative0350Library UP-TO-DATE
:app:prepareComFacebookSoloaderSoloader010Library UP-TO-DATE
:app:prepareOrgWebkitAndroidJscR174650Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:bundleDebugJsAndAssets SKIPPED
:app:processDebugManifest UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:processDebugJavaRes UP-TO-DATE
:app:compileDebugJavaWithJavac UP-TO-DATE
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources UP-TO-DATE
:app:preDexDebug UP-TO-DATE
:app:dexDebug UP-TO-DATE
:app:validateDebugSigning
:app:packageDebug UP-TO-DATE
:app:zipalignDebug UP-TO-DATE
:app:assembleDebug UP-TO-DATE
:app:installDebug
Installing APK 'app-debug.apk' on 'Moto G (4) - 6.0.1'
Installed on 1 device.

BUILD SUCCESSFUL

Total time: 1 mins 9.699 secs
Starting the app on ZY2238CX5L (C:\Users\ch-e00925\AppData\Local\Android\sdk/pla
tform-tools/adb -s ZY2238CX5L shell am start -n com.awesomeproject/.MainActivity
)...
Starting: Intent { cmp=com.awesomeproject/.MainActivity }
</code>```

答: You need to first use react-native start to start the running packager and then use react-native run-android to start the emulator.

Body:
Hi I have made Hello World program in react-native for android. I followed this https://facebook.github.io/react-native/docs/tutorial.html#content but it is not diplaying "Hello World" on screen when it launch app.

It is displaying empty screen. How can I fix this issue.

index.android.js

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  Text
} from 'react-native';

export default class AwesomeProject extends Component {
  render() {
    return (
        <Text>Hello World!</Text>
    );
  }
}

AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

Build Logs

E:\React Programming\AwesomeProject>react-native run-android
Starting JS server...
Running C:\Users\ch-e00925\AppData\Local\Android\sdk/platform-tools/adb -s ZY223
8CX5L reverse tcp:8081 tcp:8081
Building and installing the app on the device (cd android && gradlew.bat install
Debug...
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72301Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72301Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42321Library UP-TO-DATE
:app:prepareComFacebookFrescoDrawee0110Library UP-TO-DATE
:app:prepareComFacebookFrescoFbcore0110Library UP-TO-DATE
:app:prepareComFacebookFrescoFresco0110Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipeline0110Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipelineBase0110Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipelineOkhttp30110Library UP-TO-DATE
:app:prepareComFacebookReactReactNative0350Library UP-TO-DATE
:app:prepareComFacebookSoloaderSoloader010Library UP-TO-DATE
:app:prepareOrgWebkitAndroidJscR174650Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:bundleDebugJsAndAssets SKIPPED
:app:processDebugManifest UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:processDebugJavaRes UP-TO-DATE
:app:compileDebugJavaWithJavac UP-TO-DATE
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources UP-TO-DATE
:app:preDexDebug UP-TO-DATE
:app:dexDebug UP-TO-DATE
:app:validateDebugSigning
:app:packageDebug UP-TO-DATE
:app:zipalignDebug UP-TO-DATE
:app:assembleDebug UP-TO-DATE
:app:installDebug
Installing APK 'app-debug.apk' on 'Moto G (4) - 6.0.1'
Installed on 1 device.

BUILD SUCCESSFUL

Total time: 1 mins 9.699 secs
Starting the app on ZY2238CX5L (C:\Users\ch-e00925\AppData\Local\Android\sdk/pla
tform-tools/adb -s ZY2238CX5L shell am start -n com.awesomeproject/.MainActivity
)...
Starting: Intent { cmp=com.awesomeproject/.MainActivity }


问:
Using submit_form in rvest
I have tried to scrape a website for data. Below is a simpliefied version of the script I am using. In this example the disease.table retreived by html_table in the last line should include all the years from 2014 to 2017. Currently, it only contains 2017.

```<code># Initiate wahis.session website session.
url <- "http://www.oie.int/wahis_2/public/wahid.php/Diseaseinformation/statusdetail"
wahis.session <- html_session(url)

# Get forms with searchable fields in current session.
form <- html_form(wahis.session)

#------------------------------------------------------------------------------
# Fill out and submit forms

# First, Copy form.
filled.form <- form

# Set values in form #3
filled.form[[3]] <- set_values(filled.form[[3]],
                               selected_start_year = "2014") # start year
# Set form url to empty character string to prevent error message when
# submitting.
filled.form[[3]]$url <- ""

# Submit form #3
submit_form(session = wahis.session,
        form = filled.form[[3]],
        submit = 'disease_id_terrestrial')

#------------------------------------------------------------------------------
# Retreive data

# Find data table
disease.table <- wahis.session %>%
  html_node("div.OverflowAutoScroll table.TableFoyers") %>%
  html_table(fill = TRUE)
</code>```

答:
I found an answer. The submit_form() function needs to be applied to the active html session. Submitting the form using the following code worked:

```<code># Submit form #3
wahis.session <- submit_form(session = wahis.session,
        form = filled.form[[3]],
        submit = 'disease_id_terrestrial'
</code>```

No other changes were needed.

Title: Using submit_form in rvest

Body:
I have tried to scrape a website for data. Below is a simpliefied version of the script I am using. In this example the disease.table retreived by html_table in the last line should include all the years from 2014 to 2017. Currently, it only contains 2017.

# Initiate wahis.session website session.
url <- "http://www.oie.int/wahis_2/public/wahid.php/Diseaseinformation/statusdetail"
wahis.session <- html_session(url)

# Get forms with searchable fields in current session.
form <- html_form(wahis.session)

#------------------------------------------------------------------------------
# Fill out and submit forms

# First, Copy form.
filled.form <- form

# Set values in form #3
filled.form[[3]] <- set_values(filled.form[[3]],
                               selected_start_year = "2014") # start year
# Set form url to empty character string to prevent error message when
# submitting.
filled.form[[3]]$url <- ""

# Submit form #3
submit_form(session = wahis.session,
        form = filled.form[[3]],
        submit = 'disease_id_terrestrial')

#------------------------------------------------------------------------------
# Retreive data

# Find data table
disease.table <- wahis.session %>%
  html_node("div.OverflowAutoScroll table.TableFoyers") %>%
  html_table(fill = TRUE)

Body:
I found an answer. The submit_form() function needs to be applied to the active html session. Submitting the form using the following code worked:

# Submit form #3
wahis.session <- submit_form(session = wahis.session,
        form = filled.form[[3]],
        submit = 'disease_id_terrestrial'

No other changes were needed.


问:
Align text on the side and top of other text css
How can I achieve this using css?

This is what I've tried:

R$
    54.133
    48```

答:
This is the css solution to achieve the superscript.Just try this:

    R$
    54.133
    48```

Body:
This is the css solution to achieve the superscript.Just try this:

    <label style="position:relative; top:-0.5em; margin-left: 20px; font-family: 'Segoe UI Light'; font-size:18px"">R$</label>
    <label style="margin-left:45px; font-size: 35px; font-family: 'Segoe UI Light'" runat="server" id="lblBalancePeriod">54.133</label>
    <label style="position:relative; top:-0.8em;">48</label>


问:
Concatenate two std::vectors in one line using C++11
Is there a way, using C++11, to concatenate two std::vectors in one code line, with the first defined in a local variable, the second returned from a function:

```<code>#include <vector>
#include <iostream>
#include <iterator>

std::vector<int> getNewVector()
{
    return {4,5,6};
}

int main(int argc, char** argv)
{
  std::vector<int> dest;
  std::vector<int> src{1,2,3};

  dest = src + getNewVector(); //Error: no operator "+" matches these operands

  return 0;
}
</code>```

EDIT: differently from this question, that is not using C++11, I would like to know if the new C++11 standard give some useful functionality that would help my task.
As an example, I've used the + operator even if it's not working, but just to give an idea of what I'm looking for.

答:
as per  Maxim Egorushkin suggesion

```<code>a.insert(a.end(), b.begin(), b.end());
</code>```

will be more efficient.

use std::transform,below code if you want to modify values of 'b' and insert into into 'a'

```<code>std::transform( b.begin(), b.end(), std::back_inserter(a), [](int i)->int   { return i + delta; } );
</code>```

complete code

```<code>int main()
{
    std::vector<int> a = {1,2,3,4,5};
    std::vector<int> b = {11,22,33,44,55};

//to copy
 a.insert(a.end(), b.begin(), b.end());

//to transform
    std::transform( b.begin(), b.end(), std::back_inserter(a), [](int i)->int   { return i + delta; } );

    return 0;
}
</code>```

Body:
Is there a way, using C++11, to concatenate two std::vectors in one code line, with the first defined in a local variable, the second returned from a function:

#include <vector>
#include <iostream>
#include <iterator>

std::vector<int> getNewVector()
{
    return {4,5,6};
}

int main(int argc, char** argv)
{
  std::vector<int> dest;
  std::vector<int> src{1,2,3};

  dest = src + getNewVector(); //Error: no operator "+" matches these operands

  return 0;
}

EDIT: differently from this question, that is not using C++11, I would like to know if the new C++11 standard give some useful functionality that would help my task.
As an example, I've used the + operator even if it's not working, but just to give an idea of what I'm looking for.

Body:
as per  Maxim Egorushkin suggesion

a.insert(a.end(), b.begin(), b.end());

will be more efficient.

use std::transform,below code if you want to modify values of 'b' and insert into into 'a'

std::transform( b.begin(), b.end(), std::back_inserter(a), [](int i)->int   { return i + delta; } );

complete code

int main()
{
    std::vector<int> a = {1,2,3,4,5};
    std::vector<int> b = {11,22,33,44,55};

//to copy
 a.insert(a.end(), b.begin(), b.end());

//to transform
    std::transform( b.begin(), b.end(), std::back_inserter(a), [](int i)->int   { return i + delta; } );

    return 0;
}


问:
Click VBA button in excel using powershell
I need to automate something in excel. The first step should be to run a macro that is started by clicking a VBA-Button. Is there a way I can click a VBA-Button using Powershell?

Thanks!

答:
Provide macro name hidden inside this button, as an argument of cmd command.

Steps for you:

get macro name (main sub) from VBA project.

get path of excel application on your system.

get path of excel file where VBA macro is stored.

Try running with Powershell:

```<code>"path_to_excel_app" "path_to_excel_file_with_macro" /x macro_name
</code>```

Here is my working exaple with MS access:

```<code>"C:\Program Files (x86)\Microsoft Office\Office15\MSACCESS.EXE" "R:\path_to_macro_file\AccessFileWithMacro.accdb" /x macroName
</code>```

Body:
Provide macro name hidden inside this button, as an argument of cmd command.

Steps for you:

get macro name (main sub) from VBA project.

get path of excel application on your system.

get path of excel file where VBA macro is stored.

Try running with Powershell:

"path_to_excel_app" "path_to_excel_file_with_macro" /x macro_name

Here is my working exaple with MS access:

"C:\Program Files (x86)\Microsoft Office\Office15\MSACCESS.EXE" "R:\path_to_macro_file\AccessFileWithMacro.accdb" /x macroName


问:
Unable to read Unicode characters from Oracle variable
I'm using an Oracle database that is not globally set up for Unicode -- but I have been able to work with Unicode characters as needed using the NVARCHAR2 data type in columns where it is needed.

This has worked fine for data stored in the database -- but my current use case is for a temporary variable. For the purposes of the question, the following illustrates my problem:

```<code>VAR TEST NVARCHAR2(50);
DEFINE TEST = 'This string contains “Unicode” characters';

SELECT '&&TEST' AS TEST
FROM DUAL;
</code>```

I would expect this output to be:

```<code>This string contains “Unicode” characters
</code>```

But instead it is:

```<code>This string contains ¿Unicode¿ characters
</code>```

Is this failure because of the global database settings? If so, is there a workaround without changing those settings?

(I tested some of the solutions I found in other questions, such as experimenting with CAST and TO_NCHAR, and also saving the script on a page explicitly coded for UTF-8 -- but none of those strategies was successful. I think the fact that I am using a local variable distinguishes this from existing questions.)

Follow-up to Comments

laubster asked for the output from:

```<code>SELECT VALUE FROM NLS_DATABASE_PARAMETERS WHERE PARAMETER = 'NLS_CHARACTERSET'
</code>```

That output is WE8ISO8859P15.

Alex Poole asked about the client and character settings.

The client is SQL Developer. OS is Windows 10. I'm not entirely sure where to look for client character settings -- but perhaps the answer is the same as the result from laubster's query: WE8ISO8859P15.

In any event, that may be a moot point. The N'text' strategy (which I'd never heard of before) worked.

I think I've got what I need. It doesn't look like Alex Poole is hurting for points -- but if he* wants to post that as an answer, I'll certainly upvote and mark as correct.

* I'm assuming "he" based on the avatar. Apologies if I'm mistaken.

答:
Problem

Okay, based on the information provided by Alex Poole, the key to making this work is the N'text' notation for a text literal. Going back to the example in my question above:

```<code>VAR TEST VARCHAR2(50);
DEFINE TEST = 'This string contains “Unicode” characters';

SELECT '&&TEST' AS TEST
FROM DUAL;
</code>```

Gives the result:

```<code>This string contains ¿Unicode¿ characters
</code>```

Solution

But the N'text' strategy:

```<code>SELECT N'&&TEST' AS TEST
FROM DUAL;
</code>```

Gives the expected result:

```<code>This string contains “Unicode” characters
</code>```

In my real-world example, this functionality was wrapped in a CASE statement, which added a little more complexity. If I used the N'text' notation only in the line where Unicode characters were expected, it triggered error "ORA-12704: character set mismatch". to make it work, I had to add the N in front of the non-Unicode text in the ELSE line as well:

```<code>SELECT
  CASE
    WHEN 1 = 1 THEN N'&&TEST'
    ELSE N'(Some other output)'
  END AS TEST_OUTPUT
FROM DUAL;
</code>```

Settings Information

In case it is helpful to others in a similar situation, here are the relevant settings that Alex Poole suggested I provide:

Oracle version: 11g (11.2.0.4.0) - 64 bit

NLS_CHARACTERSET: WE8ISO8859P15

NLS_NCHAR_CHARACTERSET: AL16UTF16

SQL Developer version: 4.1.5.21

SQL Developer Encoding: UTF-8

Body:
I'm using an Oracle database that is not globally set up for Unicode -- but I have been able to work with Unicode characters as needed using the NVARCHAR2 data type in columns where it is needed.

This has worked fine for data stored in the database -- but my current use case is for a temporary variable. For the purposes of the question, the following illustrates my problem:

VAR TEST NVARCHAR2(50);
DEFINE TEST = 'This string contains “Unicode” characters';

SELECT '&&TEST' AS TEST
FROM DUAL;

I would expect this output to be:

This string contains “Unicode” characters

But instead it is:

This string contains ¿Unicode¿ characters

Is this failure because of the global database settings? If so, is there a workaround without changing those settings?

(I tested some of the solutions I found in other questions, such as experimenting with CAST and TO_NCHAR, and also saving the script on a page explicitly coded for UTF-8 -- but none of those strategies was successful. I think the fact that I am using a local variable distinguishes this from existing questions.)

Follow-up to Comments

laubster asked for the output from:

SELECT VALUE FROM NLS_DATABASE_PARAMETERS WHERE PARAMETER = 'NLS_CHARACTERSET'

That output is WE8ISO8859P15.

Alex Poole asked about the client and character settings.

The client is SQL Developer. OS is Windows 10. I'm not entirely sure where to look for client character settings -- but perhaps the answer is the same as the result from laubster's query: WE8ISO8859P15.

In any event, that may be a moot point. The N'text' strategy (which I'd never heard of before) worked.

I think I've got what I need. It doesn't look like Alex Poole is hurting for points -- but if he* wants to post that as an answer, I'll certainly upvote and mark as correct.

* I'm assuming "he" based on the avatar. Apologies if I'm mistaken.

Body:
Problem

Okay, based on the information provided by Alex Poole, the key to making this work is the N'text' notation for a text literal. Going back to the example in my question above:

VAR TEST VARCHAR2(50);
DEFINE TEST = 'This string contains “Unicode” characters';

SELECT '&&TEST' AS TEST
FROM DUAL;

Gives the result:

This string contains ¿Unicode¿ characters

Solution

But the N'text' strategy:

SELECT N'&&TEST' AS TEST
FROM DUAL;

Gives the expected result:

This string contains “Unicode” characters

In my real-world example, this functionality was wrapped in a CASE statement, which added a little more complexity. If I used the N'text' notation only in the line where Unicode characters were expected, it triggered error "ORA-12704: character set mismatch". to make it work, I had to add the N in front of the non-Unicode text in the ELSE line as well:

SELECT
  CASE
    WHEN 1 = 1 THEN N'&&TEST'
    ELSE N'(Some other output)'
  END AS TEST_OUTPUT
FROM DUAL;

Settings Information

In case it is helpful to others in a similar situation, here are the relevant settings that Alex Poole suggested I provide:

Oracle version: 11g (11.2.0.4.0) - 64 bit

NLS_CHARACTERSET: WE8ISO8859P15

NLS_NCHAR_CHARACTERSET: AL16UTF16

SQL Developer version: 4.1.5.21

SQL Developer Encoding: UTF-8


问:
Perl in Windows Vista 32bit?
I want to practice Perl in Windows Vista 32bit, how can I do it ?

Thanks.

答: Just an alternative to active perl is strawberry perl, each has it's own merits to use, but I would say that the initially active perl is better implemented (for instance it implements the .pl extension by default, adds perl to the PATH variable etc.) but strawberry perl makes it incredibly easy to install new modules, and generally is really good to use as well.</p>

Title: Perl in Windows Vista 32bit?


问:
jQuery .html() of all matched elements
.html() function on class selector ($('.class').html()) applies only to the first element that matches it. I'd like to get a value of all elements with class .class.

答:
If you turn your jQuery object into an Array you can reduce over it.

```<code>const fullHtml = $('.class')
   .toArray()
   .reduce((result, el) => result.concat($(el).html()), '')
</code>```

Title: jQuery .html() of all matched elements

Body:
If you turn your jQuery object into an Array you can reduce over it.

const fullHtml = $('.class')
   .toArray()
   .reduce((result, el) => result.concat($(el).html()), '')


问:
What does the Settings > Accessibility > Automate setting do on Android?
I can't find documentation for this setting anywhere and I'm not sure which versions it has been included with.

What does this accessibility toggle change/enable specifically?

答:
I misunderstood how AccessibilityServices were implemented on Android systems. The toggle enables/disables the ability to start/stop a preregistered accessibility service that has been installed.

The one named "Automate" was installed by the Automate app I downloaded from Android store.


问:
ionic 2 application long loading time
I have developed ionic 2 application but the main issue i am facing is the load time on start of application it takes minutes to load application. I am using limited plugins but still facing the issue also a white screen is shown after splash screen manually hides.</p>

答: Are you mass importing in app.component.ts? Usually when you have a ton of imports, you slow down the entire application. I would check when you test in the browser, all of the unused imports. That would at least help speed up the initial load time.

Title: ionic 2 application long loading time


问:
Kubernetes ACS engine: containers (pods) do not have internet access
I'm using a Kubernetes cluster, deployed on Azure using the ACS-engine. My cluster is composed of 5 nodes.

1 master (unix VM) (v1.6.2)

2 unix agent (v1.6.2)

2 windows agent (v1.6.0-alpha.1.2959+451473d43a2072)

I have created a unix pod defined by the following YAML:

```<code>Name:           ping-with-unix
Node:           k8s-linuxpool1-25103419-0/10.240.0.5
Start Time:     Fri, 30 Jun 2017 14:27:28 +0200
Status:         Running
IP:             10.244.2.6
Controllers:    <none>
Containers:
  ping-with-unix-2:
    Container ID:
    Image:              willfarrell/ping
    Port:
    State:              Running
      Started:          Fri, 30 Jun 2017 14:27:29 +0200
    Ready:              True
    Restart Count:      0
    Environment:
      HOSTNAME: google.com
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-1nrh5 (ro)
Conditions:
  Type          Status
  Initialized   True
  Ready         True
  PodScheduled  True
Volumes:
  default-token-1nrh5:
    Type:       Secret (a volume populated by a Secret)
    SecretName: default-token-1nrh5
    Optional:   false
QoS Class:      BestEffort
Node-Selectors: beta.kubernetes.io/os=linux
Tolerations:    <none>
Events:         <none>
</code>```

This pod does not have internet access.

```<code>2017-06-30T12:27:29.512885000Z ping google.com every 300 sec
2017-06-30T12:27:29.521968000Z PING google.com (172.217.17.78): 56 data bytes
2017-06-30T12:27:39.698081000Z --- google.com ping statistics ---
2017-06-30T12:27:39.698305000Z 1 packets transmitted, 0 packets received, 100% packet loss
</code>```

I created a 2nd pod, targeting windows container, with a custom docker image. This image instantiates an HttpClient and request an endpoint. It also does not have internet access. I can access the container to run interactive PowerShell. I cannot not access any DNS (due to lack of internet access).

```<code>PS C:\app> ping github.com
Ping request could not find host github.com. Please check the name and try again.
PS C:\app> ping 192.30.253.112

Pinging 192.30.253.112 with 32 bytes of data:
Request timed out.
Request timed out.

Ping statistics for 192.30.253.112:
    Packets: Sent = 2, Received = 0, Lost = 2 (100% loss),
Control-C
</code>```

What do I have to configure to allow my containers to access internet?

Remarks: I have not defined any Network policy.

答:
I've updated my cluster using the api version '2017-07-01' and the kubernetes version '1.6.6'. Both my unix and windows pods have Internet access.

Note, for Windows pods :

Internet is available 2 or 3 minutes after the pod starts

I can't set the DnsPolicy to "Default", only "ClusterFirst" or "ClusterFirstWithHostNet" works.

Body:
I'm using a Kubernetes cluster, deployed on Azure using the ACS-engine. My cluster is composed of 5 nodes.

1 master (unix VM) (v1.6.2)

2 unix agent (v1.6.2)

2 windows agent (v1.6.0-alpha.1.2959+451473d43a2072)

I have created a unix pod defined by the following YAML:

Name:           ping-with-unix
Node:           k8s-linuxpool1-25103419-0/10.240.0.5
Start Time:     Fri, 30 Jun 2017 14:27:28 +0200
Status:         Running
IP:             10.244.2.6
Controllers:    <none>
Containers:
  ping-with-unix-2:
    Container ID:
    Image:              willfarrell/ping
    Port:
    State:              Running
      Started:          Fri, 30 Jun 2017 14:27:29 +0200
    Ready:              True
    Restart Count:      0
    Environment:
      HOSTNAME: google.com
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-1nrh5 (ro)
Conditions:
  Type          Status
  Initialized   True
  Ready         True
  PodScheduled  True
Volumes:
  default-token-1nrh5:
    Type:       Secret (a volume populated by a Secret)
    SecretName: default-token-1nrh5
    Optional:   false
QoS Class:      BestEffort
Node-Selectors: beta.kubernetes.io/os=linux
Tolerations:    <none>
Events:         <none>

This pod does not have internet access.

2017-06-30T12:27:29.512885000Z ping google.com every 300 sec
2017-06-30T12:27:29.521968000Z PING google.com (172.217.17.78): 56 data bytes
2017-06-30T12:27:39.698081000Z --- google.com ping statistics ---
2017-06-30T12:27:39.698305000Z 1 packets transmitted, 0 packets received, 100% packet loss

I created a 2nd pod, targeting windows container, with a custom docker image. This image instantiates an HttpClient and request an endpoint. It also does not have internet access. I can access the container to run interactive PowerShell. I cannot not access any DNS (due to lack of internet access).

PS C:\app> ping github.com
Ping request could not find host github.com. Please check the name and try again.
PS C:\app> ping 192.30.253.112

Pinging 192.30.253.112 with 32 bytes of data:
Request timed out.
Request timed out.

Ping statistics for 192.30.253.112:
    Packets: Sent = 2, Received = 0, Lost = 2 (100% loss),
Control-C

What do I have to configure to allow my containers to access internet?

Remarks: I have not defined any Network policy.


问:
Excel: SUMIF column A = x and (y or z)
Here is an example of the data I am using.

```<code>0 |      A      |    B
1 | Information |   Time
2 | ----------- | ---------
3 |   x y abc   |    3
4 |   x z abc   |    4
5 |   y z abc   |    5
</code>```

I would expect this to return the value 7.

I understand SUMIF(B:B,A:A,"x") and using SUMIF for multiple criteria but I am struggling to figure out how to integrate the ability for an and/or SUMIF.

DATA TABLE

```<code>50e flute dolley tripped twice          |   0.29
dolly tripped paser flute               |   0.21
No 5 tripeed. Waiting for sparky.       |   0.18
No 2 tripped - waiting for sparky.      |   0.14
No 2 dolly tripped - waiting for sparky |   0.09
Dolly tripped, waiting for sparky       |   0.08
No 2 dolly - waiting for sparky         |   0.08
50e flute dolly                         |   0.07
dolly tripped 50e flute                 |   0.06
no 2 dolley tripped                     |   0.06
50e flute dolley (side 1) tripped       |   0.06
No 2 - waiting for sparky               |   0.06
</code>```

I want 5 different functions for the 5 different reel dollies. So for number 5, I want to ensure I am only counting the no 5 dolly and not the 50e flute dolly. This is a dataset entered external so I want to be able to cover criteria that includes wrongly spelled words and multiple names for a particular reel dolly.

答:
You might be looking for this:

```<code>=SUM(SUMIFS(B:B,A:A, "*x*",A:A, {"*y*","*z*"}))
</code>```

Which means to sum column B *where A contains "x" and either of "y" and "z".

The logic in this construction is:

mandatory criteria come alone

"ORed" criteria come inside the {...} array.

Example, dolley no 2:

```<code>=SUM(SUMIFS(B:B,A:A, "* 2 *",A:A, {"*dolly*","*dolley*", "no *"}))
</code>```

Title: Excel: SUMIF column A = x and (y or z)

Body:
Here is an example of the data I am using.

0 |      A      |    B
1 | Information |   Time
2 | ----------- | ---------
3 |   x y abc   |    3
4 |   x z abc   |    4
5 |   y z abc   |    5

I would expect this to return the value 7.

I understand SUMIF(B:B,A:A,"x") and using SUMIF for multiple criteria but I am struggling to figure out how to integrate the ability for an and/or SUMIF.

DATA TABLE

50e flute dolley tripped twice          |   0.29
dolly tripped paser flute               |   0.21
No 5 tripeed. Waiting for sparky.       |   0.18
No 2 tripped - waiting for sparky.      |   0.14
No 2 dolly tripped - waiting for sparky |   0.09
Dolly tripped, waiting for sparky       |   0.08
No 2 dolly - waiting for sparky         |   0.08
50e flute dolly                         |   0.07
dolly tripped 50e flute                 |   0.06
no 2 dolley tripped                     |   0.06
50e flute dolley (side 1) tripped       |   0.06
No 2 - waiting for sparky               |   0.06

I want 5 different functions for the 5 different reel dollies. So for number 5, I want to ensure I am only counting the no 5 dolly and not the 50e flute dolly. This is a dataset entered external so I want to be able to cover criteria that includes wrongly spelled words and multiple names for a particular reel dolly.

Body:
You might be looking for this:

=SUM(SUMIFS(B:B,A:A, "*x*",A:A, {"*y*","*z*"}))

Which means to sum column B *where A contains "x" and either of "y" and "z".

The logic in this construction is:

mandatory criteria come alone

"ORed" criteria come inside the {...} array.

Example, dolley no 2:

=SUM(SUMIFS(B:B,A:A, "* 2 *",A:A, {"*dolly*","*dolley*", "no *"}))


问:
Why mySQL table won't export properly as HTML table
I use bootstrap 3 template and connect to a mysql database, sort the table and export some datas as HTML table in order to display it on bootstrap webpage.

Here is the mySQL look like :

The following code won't get expected results:

```<code><div class="well">

<?php

//MySQL Database Connect
include '/includes/dbconnect.php';

$result = mysqli_query($conn,"SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");

if(mysqli_num_rows($result) >= 1) {

    echo '<table class="table table-striped table-bordered table-hover">';
    echo "<tr><th>ID</th><th>NAME:</th><th>EPOCH</th></tr>";
    while($row = mysqli_fetch_array($results)) {
        echo "<tr><td>";
        echo $row['ID'];
        echo "</td><td>";
        echo $row['NAME'];
        echo "</td><td>";
        echo $row['NEXT_EVENT'];
        echo "</td></tr>";
    }
    echo "</table>";
}
?>
</div>  <!-- well -->
</code>```

dbconnect.php :

```<code><?php

$localhost="xxx.xx.xxx.com";
$username="dboxxxxxxx";
$password="xxxxxx";
$database="dbxxxxxx";

$conn = mysqli_connect($localhost,$username,$password,$database);

//test if connection failed
if(mysqli_connect_errno()){
    die("connection failed: "
        . mysqli_connect_error()
        . " (" . mysqli_connect_errno()
        . ")");
}
?>
</code>```

original page link can be found here : http://s529471052.onlinehome.fr/bs3/gpio/dyntable.htm

答:
I'm assuming that your connection to the database is OK (though the given page link suggests otherwise).

It seems the table is not exporting properly because $result was misspelled as $results in the code segment printing the data rows: $row = mysqli_fetch_array($results).

Try the modification below (also refactored for better readability):

```<code><div class="well">

<?php

  //MySQL Database Connect
  include '/includes/dbconnect.php';

  $result = mysqli_query($conn,"SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");

  if(mysqli_num_rows($result) >= 1)
  {
    echo '<table class="table table-striped table-bordered table-hover">';
    echo "<tr><th>ID</th><th>NAME:</th><th>EPOCH</th></tr>";
    while($row = mysqli_fetch_array($result))
    {
      echo "<tr>";
      echo "<td>$row['ID']</td>";
      echo "<td>$row['NAME']</td>";
      echo "<td>$row['NEXT_EVENT']</td>";
      echo "</tr>";
    }
    echo "</table>";
  }

?>
</div>  <!-- well -->
</code>```

Also, you may want to check that $results and $row contain the expected data in the expected formats using print_r($results) and print_r($row).

Body:
I use bootstrap 3 template and connect to a mysql database, sort the table and export some datas as HTML table in order to display it on bootstrap webpage.

Here is the mySQL look like :

The following code won't get expected results:

<?php

//MySQL Database Connect
include '/includes/dbconnect.php';

$result = mysqli_query($conn,"SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");

if(mysqli_num_rows($result) >= 1) {

    echo '
';
    echo "
ID	NAME:	EPOCH
";
    while($row = mysqli_fetch_array($results)) {
        echo "
";
        echo $row['ID'];
        echo "	";
        echo $row['NAME'];
        echo "	";
        echo $row['NEXT_EVENT'];
        echo "
";
    }
    echo "
";
}
?>

dbconnect.php :

<?php

$localhost="xxx.xx.xxx.com";
$username="dboxxxxxxx";
$password="xxxxxx";
$database="dbxxxxxx";

$conn = mysqli_connect($localhost,$username,$password,$database);

//test if connection failed
if(mysqli_connect_errno()){
    die("connection failed: "
        . mysqli_connect_error()
        . " (" . mysqli_connect_errno()
        . ")");
}
?>

original page link can be found here : http://s529471052.onlinehome.fr/bs3/gpio/dyntable.htm

Body:
I'm assuming that your connection to the database is OK (though the given page link suggests otherwise).

It seems the table is not exporting properly because $result was misspelled as $results in the code segment printing the data rows: $row = mysqli_fetch_array($results).

Try the modification below (also refactored for better readability):

<div class="well">

<?php

  //MySQL Database Connect
  include '/includes/dbconnect.php';

  $result = mysqli_query($conn,"SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");

  if(mysqli_num_rows($result) >= 1)
  {
    echo '<table class="table table-striped table-bordered table-hover">';
    echo "<tr><th>ID</th><th>NAME:</th><th>EPOCH</th></tr>";
    while($row = mysqli_fetch_array($result))
    {
      echo "<tr>";
      echo "<td>$row['ID']</td>";
      echo "<td>$row['NAME']</td>";
      echo "<td>$row['NEXT_EVENT']</td>";
      echo "</tr>";
    }
    echo "</table>";
  }

?>
</div>  <!-- well -->

Also, you may want to check that $results and $row contain the expected data in the expected formats using print_r($results) and print_r($row).


问:
C# switch statement limitations - why?
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.

For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!),

```<code>  Type t = typeof(int);

  switch (t) {

    case typeof(int):
      Console.WriteLine("int!");
      break;

    case typeof(string):
      Console.WriteLine("string!");
      break;

    default:
      Console.WriteLine("unknown!");
      break;
  }
</code>```

Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.

Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is,  primitive). What is the justification?

答:
This is not a reason why, but the C# specification section 8.7.2 states the following:

The governing type of a switch statement is established by the switch expression. If the type of the switch expression is sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or an enum-type, then that is the governing type of the switch statement. Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the type of the switch expression to one of the following possible governing types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if more than one such implicit conversion exists, a compile-time error occurs.

The C# 3.0 specification is located at:
http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc

OwnerDisplayName: kronoz

Title: C# switch statement limitations - why?

Body:
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.

For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!),

  Type t = typeof(int);

  switch (t) {

    case typeof(int):
      Console.WriteLine("int!");
      break;

    case typeof(string):
      Console.WriteLine("string!");
      break;

    default:
      Console.WriteLine("unknown!");
      break;
  }

Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.

Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is,  primitive). What is the justification?

LastEditorDisplayName: ecleel

OwnerDisplayName: Mark


问:
Can you import a SQL file into a SQL 2005/8 script?
If I have scripts in multiple files, and I would like to execute each one in a known sequence, can I simply import them into a T-SQL script and execute them, or must I run sqlcmd or similar against each file? I'm sure Oracle has a feature to import/include script content from another file (maybe with @@ ?).

I want all of the scripts to run automatically. I.e. I don't want to manually load and run each file of SQL script.

答: I think you can import them into a T-SQL script and execute. Better yet though, use SSMS and a maintenance plan. That way you can run the individual SQL and have some checks on success before executing the next statements.</p>

OwnerDisplayName: Bernhard Hofmann

LastEditorDisplayName: Bernhard Hofmann

OwnerDisplayName: MkUltra


问:
Rails and association in to_json
I have an association one to many from foo and bar.

i do a foo.to_json(:include => :bar) but i want to display not all the rows of bar, but only the last, how to do?

答:
I know it's an old question, but in case you're still looking for an answer...

You'll probably have to build the JSON hash yourself, like so:

```<code>{
  'foo' => {
    'title': foo.title,
    ...,
    'bars' => [foo.bars.last.attributes]
  }
}
</code>```

or if you don't want to list each attribute,

```<code>{
  'foo' => {
    'bars' => [foo.bars.last.attributes]
  }.merge(foo.attributes)
}
</code>```

Hope that helps!

Title: Rails and association in to_json

Body:
I know it's an old question, but in case you're still looking for an answer...

You'll probably have to build the JSON hash yourself, like so:

{
  'foo' => {
    'title': foo.title,
    ...,
    'bars' => [foo.bars.last.attributes]
  }
}

or if you don't want to list each attribute,

{
  'foo' => {
    'bars' => [foo.bars.last.attributes]
  }.merge(foo.attributes)
}

Hope that helps!


问:
Oracle - Not a single-group group function
For the following sql command

```<code>select h.hacker_id
    ,h.name
    ,challenges_created
from hackers h
inner join (
    select hacker_id
        ,count(*) as challenges_created /* line 1 */
    from challenges
    group by hacker_id
    order by 2 desc
    ) tmp on h.hacker_id = tmp.hacker_id
order by challenges_created desc
    ,h.hacker_id;
</code>```

so far so good but

As soon as I try to add max(count(*)) as maximum to the line 1 it give error as:

Not a single-group group function

This is the code for which it gives error :

```<code>select h.hacker_id
    ,h.name
    ,challenges_created
from hackers h
inner join (
    select hacker_id
        ,count(*) as challenges_created
        ,max(count(*)) as maximum
    from challenges
    group by hacker_id
    ) tmp on h.hacker_id = tmp.hacker_id
order by challenges_created desc
    ,h.hacker_id;
</code>```

I am basically interested in getting the maximum count i.e. maximum number of challenges created so far.

I am new to sql, kindly help and oblige. Thanks in advance. And yes, of course! I know many such question have been asked in recent past but none matches my situation which is why I am asking it again.

答:
Try this:</p>

```<code>with x as (
  select h.hacker_id, h.name, count(*) challenges_created
  from hackers h
  inner join challenges on h.hacker_id = challenges.hacker_id
  group by h.hacker_id, h.name
)
select x.*,
       (select max(challenges_created) from x) as "max"
from x
order by challenges_created desc, hacker_id;
</code>```

Body:
For the following sql command

select h.hacker_id
    ,h.name
    ,challenges_created
from hackers h
inner join (
    select hacker_id
        ,count(*) as challenges_created /* line 1 */
    from challenges
    group by hacker_id
    order by 2 desc
    ) tmp on h.hacker_id = tmp.hacker_id
order by challenges_created desc
    ,h.hacker_id;

so far so good but

As soon as I try to add max(count(*)) as maximum to the line 1 it give error as:

Not a single-group group function

This is the code for which it gives error :

select h.hacker_id
    ,h.name
    ,challenges_created
from hackers h
inner join (
    select hacker_id
        ,count(*) as challenges_created
        ,max(count(*)) as maximum
    from challenges
    group by hacker_id
    ) tmp on h.hacker_id = tmp.hacker_id
order by challenges_created desc
    ,h.hacker_id;

I am basically interested in getting the maximum count i.e. maximum number of challenges created so far.

I am new to sql, kindly help and oblige. Thanks in advance. And yes, of course! I know many such question have been asked in recent past but none matches my situation which is why I am asking it again.

Body:
Try this:

with x as (
  select h.hacker_id, h.name, count(*) challenges_created
  from hackers h
  inner join challenges on h.hacker_id = challenges.hacker_id
  group by h.hacker_id, h.name
)
select x.*,
       (select max(challenges_created) from x) as "max"
from x
order by challenges_created desc, hacker_id;


问:
Sending Local Notifications in Android
I want to use local notification in android for my application.
If the app is not opened for 24 hours than a local notification is send.
Can any one let me know how it should be done.</p>

答:
```<code>Intent intent = new Intent(context, yourActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder b = new NotificationCompat.Builder(context);

    b.setAutoCancel(true)
     .setDefaults(Notification.DEFAULT_ALL)
     .setWhen(System.currentTimeMillis())
     .setSmallIcon(R.drawable.ic_launcher)
     .setTicker("notification")
     .setContentTitle("notification")
     .setContentText("notification")
     .setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
     .setContentIntent(pIntent)
     .setContentInfo("Info");

    NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1, b.build());
</code>```

Title: Sending Local Notifications in Android


问:
Responsive html layout height 100% is not according to parent div
I'm really new in html

This is my code

```<code><div class="w3-row">
    <div class="w3-container w3-half w3-padding-64 w3-orange w3-text-white w3-center" style="height:100%">
        <p style="font-size:calc(11px + 1vw);"> OUR <b>VISION</b></br></br>
        To become the best foundation that is able to nurture holistic global leaders</p>
    </div>

    <div class="w3-container w3-half w3-padding-64 w3-orange w3-text-white w3-center" style="height:100%">
        <p style="font-size:calc(11px + 1vw);"> OUR <b>MISSION</b></br></br>
        Developing young muslim leaders by nurturing entrepreneurial mindset in order to provide the best
        solution for mankind through Islamic values</p>
    </div>
</div>
</code>```

So I have 2 column in a row. This is what happened

my first column leaves empty white space below it

Is there any way to have both my columns to extend to 100% parent div's height?

答:
One solution is to use flex like @Supraja suggested, but an even simpler solution is to give the orange bg to the container of the columns instead of the column itself.

so put .w3-orange on the div with w3-row class:

```<code><div class="w3-row w3-orange">
</code>```

Body:
I'm really new in html

This is my code

 OUR VISION

        To become the best foundation that is able to nurture holistic global leaders

 OUR MISSION

        Developing young muslim leaders by nurturing entrepreneurial mindset in order to provide the best
        solution for mankind through Islamic values

So I have 2 column in a row. This is what happened

my first column leaves empty white space below it

Is there any way to have both my columns to extend to 100% parent div's height?

Body:
One solution is to use flex like @Supraja suggested, but an even simpler solution is to give the orange bg to the container of the columns instead of the column itself.

so put .w3-orange on the div with w3-row class:

<div class="w3-row w3-orange">


问:
Laravel yield attribute
I'm trying to set an attribute using @yield and @section, but how?
I tried to use

```<code><html @yield('mainApp')>
</code>```

and

```<code>@section('mainApp','id="myid"')
</code>```

but it returns id="myid" instead of id="myid"

I know that I can manage it with a default id but I don't like this way, and also what if I need to use a custom attribute?

答:
If you check the Upgrade Guide from the link below you will see few lines below under Blade:
https://laravel.com/docs/5.4/upgrade

```<code>    @section Escaping
</code>```

In Laravel 5.4, inline content passed to a section is automatically escaped:

```<code>    @section('title', $content)
</code>```

If you would like to render unescaped content in a section, you must declare the section using the traditional "long form" style:

```<code>    @section('title')
        {!! $content !!}
    @stop
</code>```

So the get the result for for your query you need to as below:

```<code>    @section('mainApp', {!! 'id="myid"' !!})
</code>```

Title: Laravel yield attribute

Body:
I'm trying to set an attribute using @yield and @section, but how?
I tried to use

and

@section('mainApp','id="myid"')

but it returns id="myid" instead of id="myid"

I know that I can manage it with a default id but I don't like this way, and also what if I need to use a custom attribute?

Body:
If you check the Upgrade Guide from the link below you will see few lines below under Blade:
https://laravel.com/docs/5.4/upgrade

    @section Escaping

In Laravel 5.4, inline content passed to a section is automatically escaped:

    @section('title', $content)

If you would like to render unescaped content in a section, you must declare the section using the traditional "long form" style:

    @section('title')
        {!! $content !!}
    @stop

So the get the result for for your query you need to as below:

    @section('mainApp', {!! 'id="myid"' !!})


问:
using jQuery (put at the bottom of the page) on specific page
Because of performance purposes I put loading of jQuery scripts at the bottom of the page (just before the closing body tag).

My question is how to enable page specific scripts? I don't want to put everything inside $(document).ready method (again because of performance purposes).

Update: I'm using a template system so I put jQuery loading in the template. That way jQuery calls don't get recognized even if I put them at the end of a specific page because jQuery is not loaded at that point.

答: This allows you to call jQuery plugin methods in the body and load jQuery plugin on to bottom of the page headjs</p>


问:
How to replace a particular string in js
I have a variable with the following data

Peaks in mesothelioma incidence were expected to take place between 2014 and 2021 in Australia, between 2011 and 2015 in the United Kingdom, between 2015 and 2024 in Italy, in 2010 in the United States, in 2015 in Denmark, in 2017 in the Netherlands, and in 2027 in Japan.

Here I want to replace

```<code><img src="test" />
</code>```

To

```<code><amp-img src="test"></amp-img>
</code>```

But here I am getting the data of 100 records as an example I put

```<code> <img src="test" />
</code>```

But I am not sure what my img tag contains.So I van replace img with

```<code>replace('<img',<amp-img>);
</code>```

But how can I replace the end tag i.e

```<code>  ('/>','></amp-img>').
</code>```

Can any one please suggest me help.Thanks.

答:
With regards to this...

...

```<code><img src="test" />
</code>```

But I am not sure what my img tag contains.So I van replace img with

```<code>replace('<img',<amp-img>);
</code>```

...

The JavaScript String Replace method takes two arguments, the first being either a Regular Expression or an exact string, and the second taking a replacement string or function.  If you only need to make one specifc change then using strings as both arguments is the way to go, and multiple 'replacers' can be chained for more complex operations.

So this...

```<code>var sampleString = '<img src="test" />';
</code>```

..can be 'replaced' like so...

```<code>var newString = sampleString.replace('<img','<amp-img')
                            .replace(' />','</amp-img>');
</code>```

The newString variable now contains the changes you just made to the contents of the sampleString variable.

Hope that helped :)

Body:
I have a variable with the following data

Peaks in mesothelioma incidence were expected to take place between 2014 and 2021 in Australia, between 2011 and 2015 in the United Kingdom, between 2015 and 2024 in Italy, in 2010 in the United States, in 2015 in Denmark, in 2017 in the Netherlands, and in 2027 in Japan.

Here I want to replace

To

<amp-img src="test"></amp-img>

But here I am getting the data of 100 records as an example I put

But I am not sure what my img tag contains.So I van replace img with

replace('<img',<amp-img>);

But how can I replace the end tag i.e

  ('/>','></amp-img>').

Can any one please suggest me help.Thanks.

Body:
With regards to this...

...

<img src="test" />

But I am not sure what my img tag contains.So I van replace img with

replace('<img',<amp-img>);

...

The JavaScript String Replace method takes two arguments, the first being either a Regular Expression or an exact string, and the second taking a replacement string or function.  If you only need to make one specifc change then using strings as both arguments is the way to go, and multiple 'replacers' can be chained for more complex operations.

So this...

var sampleString = '<img src="test" />';

..can be 'replaced' like so...

var newString = sampleString.replace('<img','<amp-img')
                            .replace(' />','</amp-img>');

The newString variable now contains the changes you just made to the contents of the sampleString variable.

Hope that helped :)


问:
Align text on the side and top of other text css
How can I achieve this using css?

This is what I've tried:

R$
    54.133
    48```

答:
HTML:

```<code><span class="currency">
  <span class="prefix">R$</span>
  54.133
  <span class="suffix">73</span>
</span>
</code>```

CSS:

```<code>.currency {
  color: green;
  font-size: 40px;
  line-height: 40px;
}

.prefix, .suffix {
  font-size: 20px;
  vertical-align: text-top;
}
</code>```

Shown in Plunker.

Body:
HTML:

<span class="currency">
  <span class="prefix">R$</span>
  54.133
  <span class="suffix">73</span>
</span>

CSS:

.currency {
  color: green;
  font-size: 40px;
  line-height: 40px;
}

.prefix, .suffix {
  font-size: 20px;
  vertical-align: text-top;
}

Shown in Plunker.


问:
Haar Cascades Emgu CV C# error
I tried using Haar Cascade algorithm for facial detection. However, I got problems in running the code. The error is located in the form and yes, I declared a global variable called haar.

Here is my code:

```<code>private void Form1_Load(object sender, EventArgs e)
        {
            capture = new Capture(0);
            haar = new HaarCascade("haarcascade_frontalface_default.xml");
        }
</code>```

The error is this:

System.DllNotFoundException: 'Unable to load DLL 'cvextern': The specified module could not be found. (Exception from HRESULT: 0x8007007E)'

I really need your help guys. This is for my thesis.

答:
Have a look at the EmguCV documentation especially the "Open CV unmanaged dll" section Here, you need to copy the "x64" and/or "x86" directories from EmguCV/bin to the root of your application.

If you are running your application from Visual Studio as Debug, it would be MyApp/bin/Debug/ and don't forget to add EmguCV references in your project.

Title: Haar Cascades Emgu CV C# error

Body:
I tried using Haar Cascade algorithm for facial detection. However, I got problems in running the code. The error is located in the form and yes, I declared a global variable called haar.

Here is my code:

private void Form1_Load(object sender, EventArgs e)
        {
            capture = new Capture(0);
            haar = new HaarCascade("haarcascade_frontalface_default.xml");
        }

The error is this:

System.DllNotFoundException: 'Unable to load DLL 'cvextern': The specified module could not be found. (Exception from HRESULT: 0x8007007E)'

I really need your help guys. This is for my thesis.