问:
How to create login system through Google OAuth
I am new in Google API and I am trying to create a login system, fetch email id and youtube channel data through Oauth Google API. Below my code is worked perfectly for fetching data but I am not able to create a login system also when I refresh the page I lost whole data and its again ask for login. Pls guide me how to acheive login system and also please check my code is correct or can be shorten</p>

```<code>$client_id = "xxxxxxxxxxxxxxxxxxx";
$client_secret = "xxxxxxxxxxxxxxx";
$redirect_uri = "http://localhost/mysite/oauth2callback";
$code = $_GET["code"];

$oauth2token_url = "https://accounts.google.com/o/oauth2/token";
$clienttoken_post = array(
        "code" => $code,
        "client_id" => $client_id,
        "client_secret" => $client_secret,
        "redirect_uri" => $redirect_uri,
        "grant_type" => "authorization_code"
);

$curl = curl_init($oauth2token_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$json_response = curl_exec($curl);
curl_close($curl);
$authObj = json_decode($json_response);
$access_token = $authObj->access_token;
$token_type = $authObj->token_type;
$expires_in = $authObj->expires_in;
$refresh_token = $authObj->refresh_token;
$Id_token = $authObj->id_token;

session_start();
$_SESSION['access_token'] = $access_token;

//getting the email id
$email_url = 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='.$_SESSION['access_token'];
$em = curl_init();
curl_setopt( $em, CURLOPT_URL, $email_url );
curl_setopt($em, CURLOPT_HEADER, 0);
curl_setopt( $em, CURLOPT_RETURNTRANSFER, 1 );
$eamilOBJ = json_decode( curl_exec( $em ) );
$email = $eamilOBJ->email;

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
    $url = 'https://www.googleapis.com/youtube/v3/channels?fields=items(id,snippet(title,description,customUrl,thumbnails(default)),statistics(viewCount,subscriberCount))&part=snippet%2Cstatistics&mine=true&access_token='.$_SESSION['access_token'];

    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    $channelOBJ = json_decode( curl_exec( $ch ) );

    $channel_id = $channelOBJ->items[0]->id;
    $thumbnail_url = $channelOBJ->items[0]->snippet->thumbnails->default->url;
    $youtubetitle = $channelOBJ->items[0]->snippet->title;
    $description = $channelOBJ->items[0]->snippet->description;
    $total_subscriber = $channelOBJ->items[0]->statistics->subscriberCount;

    echo 'Email ID : '.$email;
    echo 'Image: URL: '.$thumbnail_url;
    echo 'Channel Title: '.$youtubetitle;
    echo 'Total Subscriber: '.$total_subscriber;
}
else{
    echo '<a href="https://accounts.google.com/o/oauth2/auth?
        redirect_uri=http://localhost/mysite/oauth2callback&
        response_type=code&
        client_id=xxxxxxxxxxxxxxx&
        scope=https://www.googleapis.com/auth/youtube.readonly+https://www.googleapis.com/auth/userinfo.email&
        approval_prompt=force&
        access_type=offline">
        <button class="loginBtn loginBtn--google">Sign in with Google</button></a>';
   }
</code>```

答:
The access_token you get from the above request is what you will be using to make requests to the service. After one hour your access token will have expired you will need to request a new access_token you take the refresh_token that you got above and HTTP Post it to: Note: grant_type=refresh_token

```<code>https://accounts.google.com/o/oauth2/token
client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&refresh_token=1/ffYmfI0sjR54Ft9oupubLzrJhD1hZS5tWQcyAvNECCA&grant_type=refresh_token
</code>```

This is the response:

```<code>{
"access_token" : "ya29.1.AADtN_XK16As2ZHlScqOxGtntIlevNcasMSPwGiE3pe5ANZfrmJTcsI3ZtAjv4sDrPDRnQ",
"token_type" : "Bearer",
"expires_in" : 3600
}
</code>```

Body:
I am new in Google API and I am trying to create a login system, fetch email id and youtube channel data through Oauth Google API. Below my code is worked perfectly for fetching data but I am not able to create a login system also when I refresh the page I lost whole data and its again ask for login. Pls guide me how to acheive login system and also please check my code is correct or can be shorten

$client_id = "xxxxxxxxxxxxxxxxxxx";
$client_secret = "xxxxxxxxxxxxxxx";
$redirect_uri = "http://localhost/mysite/oauth2callback";
$code = $_GET["code"];

$oauth2token_url = "https://accounts.google.com/o/oauth2/token";
$clienttoken_post = array(
        "code" => $code,
        "client_id" => $client_id,
        "client_secret" => $client_secret,
        "redirect_uri" => $redirect_uri,
        "grant_type" => "authorization_code"
);

$curl = curl_init($oauth2token_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$json_response = curl_exec($curl);
curl_close($curl);
$authObj = json_decode($json_response);
$access_token = $authObj->access_token;
$token_type = $authObj->token_type;
$expires_in = $authObj->expires_in;
$refresh_token = $authObj->refresh_token;
$Id_token = $authObj->id_token;

session_start();
$_SESSION['access_token'] = $access_token;

//getting the email id
$email_url = 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='.$_SESSION['access_token'];
$em = curl_init();
curl_setopt( $em, CURLOPT_URL, $email_url );
curl_setopt($em, CURLOPT_HEADER, 0);
curl_setopt( $em, CURLOPT_RETURNTRANSFER, 1 );
$eamilOBJ = json_decode( curl_exec( $em ) );
$email = $eamilOBJ->email;

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
    $url = 'https://www.googleapis.com/youtube/v3/channels?fields=items(id,snippet(title,description,customUrl,thumbnails(default)),statistics(viewCount,subscriberCount))&part=snippet%2Cstatistics&mine=true&access_token='.$_SESSION['access_token'];

    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    $channelOBJ = json_decode( curl_exec( $ch ) );

    $channel_id = $channelOBJ->items[0]->id;
    $thumbnail_url = $channelOBJ->items[0]->snippet->thumbnails->default->url;
    $youtubetitle = $channelOBJ->items[0]->snippet->title;
    $description = $channelOBJ->items[0]->snippet->description;
    $total_subscriber = $channelOBJ->items[0]->statistics->subscriberCount;

    echo 'Email ID : '.$email;
    echo 'Image: URL: '.$thumbnail_url;
    echo 'Channel Title: '.$youtubetitle;
    echo 'Total Subscriber: '.$total_subscriber;
}
else{
    echo '
        <button class="loginBtn loginBtn--google">Sign in with Google</button>';
   }

Body:
The access_token you get from the above request is what you will be using to make requests to the service. After one hour your access token will have expired you will need to request a new access_token you take the refresh_token that you got above and HTTP Post it to: Note: grant_type=refresh_token

https://accounts.google.com/o/oauth2/token
client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&refresh_token=1/ffYmfI0sjR54Ft9oupubLzrJhD1hZS5tWQcyAvNECCA&grant_type=refresh_token

This is the response:

{
"access_token" : "ya29.1.AADtN_XK16As2ZHlScqOxGtntIlevNcasMSPwGiE3pe5ANZfrmJTcsI3ZtAjv4sDrPDRnQ",
"token_type" : "Bearer",
"expires_in" : 3600
}


来源: stackexchange

问:
How can i show menu icon and not back arrow on navbar moving from page 1 to page 2 - IONIC
When i open my app, the 1st page which appears is Login.html , after filling the form, it navigates to dashboard.html

Problem:  When it goes to Dashboard.html , it shows back arrow on the top left and not the menu icon. I want it to show menu icon here and not the back arrow

This is the code i am using for navigation in login.ts:

```<code>if(data[0].USR==1)
       {
         this.navCtrl.push(DashboardPage);

       }
</code>```

Image of dashboard.html, please notice the arrow on left side

I have to click this arrow > go back to login > then from menu icon, i open menu and select dashboard page, then i see menu icon on dashboard.. why so  ?

I have also created a video , sharing its youtube link - http://youtu.be/1eA5KXJkSDE?hd=1

答:
Seems like you want to set the DashboardPage as a root page, so instead of the push method, use setRoot:

```<code>if(data[0].USR == 1) {
  this.navCtrl.setRoot(DashboardPage);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When i open my app, the 1st page which appears is Login.html , after filling the form, it navigates to dashboard.html

Problem:  When it goes to Dashboard.html , it shows back arrow on the top left and not the menu icon. I want it to show menu icon here and not the back arrow

This is the code i am using for navigation in login.ts:

if(data[0].USR==1)
       {
         this.navCtrl.push(DashboardPage);

       }

Image of dashboard.html, please notice the arrow on left side

I have to click this arrow > go back to login > then from menu icon, i open menu and select dashboard page, then i see menu icon on dashboard.. why so  ?

I have also created a video , sharing its youtube link - http://youtu.be/1eA5KXJkSDE?hd=1

Body:
Seems like you want to set the DashboardPage as a root page, so instead of the push method, use setRoot:

if(data[0].USR == 1) {
  this.navCtrl.setRoot(DashboardPage);
}


问:
Detect Enable/Disable Bluetooth
I made an application to turn on/off bluetooth. To turn on/off i used a switch button. Here is the code:

```<code>public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private final static int REQUEST_ENABLE_BT = 1;
BluetoothAdapter mBluetoothAdapter = null;

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(mBluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);

            switch (state){
                case BluetoothAdapter.STATE_OFF:

                    break;
                case BluetoothAdapter.STATE_ON:
                    break;
            }
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Switch bluetoothSwitch = (Switch) findViewById(R.id.bluetoothSwitch);

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null){
        //Device does not support bluetooth
    }
    else{
        bluetoothSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(bluetoothSwitch.isChecked() && !mBluetoothAdapter.isEnabled()){
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

                    IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
                    registerReceiver(mReceiver, BTIntent);
                }
                if(!bluetoothSwitch.isChecked() && mBluetoothAdapter.isEnabled()){
                    mBluetoothAdapter.disable();
                    IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
                    registerReceiver(mReceiver, BTIntent);
                }
            }
        });
    }
}
</code>```

}

The problem is that if i turn on/off bluetooth from settings and not from my app the switch doesn't change.
I have implemented a broadcast receiver but i can't access the switch from it.
I tried:

```<code>bluetoothSwich.setChecked(true)
</code>```

inside the broadcast receiver but it doesn't work.

Ty

EDIT :
I partially solved the problem with the global switch but to catch the on/off action from settings first i have to click the on/off button from my app at least one time. any suggestion?

答:
To detect the state change of bluetooth you need to add following permission to your AndroidManifest.xml.

```<code><uses-permission android:name="android.permission.BLUETOOTH" />
</code>```

Use a Local broadcast preferably. You do not need to register it in Manifest . register it at runtime where you need it.(If need throughout the app then register it in Manifest)

```<code>private final BroadcastReceiver bStateReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
            if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_OFF) {
                // Bluetooth is disconnected, do handling here
            }
        }
    }

};
</code>```

Runtime register:

```<code>LocalBroadcastManager.getInstance(this).registerReceiver(bStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
</code>```

Runtime unregister : Don't forget to unregister the broadcast.

```<code>LocalBroadcastManager.getInstance(this).unregisterReceiver(bStateReceiver);
</code>```

Static Register:

```<code><receiver
    android:name=".FullyQualifiedBroadcastReceiverClassName"
    android:enabled="true">
<intent-filter>
    <action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
</intent-filter>
</code>```

Title: Detect Enable/Disable Bluetooth

Body:
I made an application to turn on/off bluetooth. To turn on/off i used a switch button. Here is the code:

public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private final static int REQUEST_ENABLE_BT = 1;
BluetoothAdapter mBluetoothAdapter = null;

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(mBluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);

            switch (state){
                case BluetoothAdapter.STATE_OFF:

                    break;
                case BluetoothAdapter.STATE_ON:
                    break;
            }
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Switch bluetoothSwitch = (Switch) findViewById(R.id.bluetoothSwitch);

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null){
        //Device does not support bluetooth
    }
    else{
        bluetoothSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(bluetoothSwitch.isChecked() && !mBluetoothAdapter.isEnabled()){
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

                    IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
                    registerReceiver(mReceiver, BTIntent);
                }
                if(!bluetoothSwitch.isChecked() && mBluetoothAdapter.isEnabled()){
                    mBluetoothAdapter.disable();
                    IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
                    registerReceiver(mReceiver, BTIntent);
                }
            }
        });
    }
}

}

The problem is that if i turn on/off bluetooth from settings and not from my app the switch doesn't change.
I have implemented a broadcast receiver but i can't access the switch from it.
I tried:

bluetoothSwich.setChecked(true)

inside the broadcast receiver but it doesn't work.

Ty

EDIT :
I partially solved the problem with the global switch but to catch the on/off action from settings first i have to click the on/off button from my app at least one time. any suggestion?

Body:
To detect the state change of bluetooth you need to add following permission to your AndroidManifest.xml.

<uses-permission android:name="android.permission.BLUETOOTH" />

Use a Local broadcast preferably. You do not need to register it in Manifest . register it at runtime where you need it.(If need throughout the app then register it in Manifest)

private final BroadcastReceiver bStateReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
            if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_OFF) {
                // Bluetooth is disconnected, do handling here
            }
        }
    }

};

Runtime register:

LocalBroadcastManager.getInstance(this).registerReceiver(bStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

Runtime unregister : Don't forget to unregister the broadcast.

LocalBroadcastManager.getInstance(this).unregisterReceiver(bStateReceiver);

Static Register:

<receiver
    android:name=".FullyQualifiedBroadcastReceiverClassName"
    android:enabled="true">
<intent-filter>
    <action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
</intent-filter>


问:
footer won't stick in IE compatibility mode (can't find an answer anywhere)
Here's the website:

http://www.uiowa.edu/~ucoll/academicmisconduct.shtml

When I go into compatability mode my footer jumps up to the bottom of my header.  I have a wrap with a virtually included header, then a content area, then a virtually included footer (fs-footer).  I'm pretty sure it's something to do with the min-height element.  I've tried a bunch of work arounds and alternatives.  I've also searched googles and forums but haven't found a good answer.  Please help :)

Code:

```<code>html {
 height: 100%;

}

body {
 padding: 0;
 margin: 0 0 0 0;
 font-family: Lucida Grande, Lucida Sans, Verdana, Arial, Helvetica, sans-serif;
 font-size: 12px;
 background-color:#999;
 background-position:center;
 height: 100%;
}

#wrap {
 width: 1024px;
 height:100%;
 margin: auto;
 padding: 0;
 min-width: 1024px;
 position: relative;
}

#mainContentPage {
 background-image: url(images/backgrounducContent.png);
 background-repeat:no-repeat;
 padding: 0;
 font-family: Arial, Helvetica, sans-serif;
 font-size: 12px;
 width: 1024px;
 margin: 0;
 float: right;
 border-bottom:thick;
 border-bottom-color: #000;
 background-color: #FFF;
 min-height: 100%;
}

.fs-footer {
 clear:both;
 float:left;
 padding-bottom:30px;
 padding-top:0px;
 width:1024px;
 border-top:thick;
 border-top-color:#000;
 border-top-style:groove;
 border-top-width:thick;
 background-color:#FFF;
 background-image:url(images/ucfooter2.png);
 height: auto;

}
</code>```

答:
Tested in IE8, IE8's Compatibility mode, Firefox:

From .fs-footer, remove float: left and add overflow: auto.

I don't think it's relevant to your problem, but you have code like this:

```<code><a href="index.shtml" id="headLink" title="Banner Link">
  <div id="header">
    ...
  </div>
</a>
</code>```

This is not good - you generally should not put block elements (such as
 tags) inside inline elements (such as  tags).

Also, you have:

```<code><div id="generalInfoMainContent">

<h1>Classroom Policies - Academic Misconduct</h1>
<p> </p>

<li><a href="academicmisconduct.shtml#fraud">Academic misconduct</a></li>

  <li><a href="academicmisconduct.shtml#consequences">Consequences of Academic misconduct</a></li>
  <li><a href="academicmisconduct.shtml#forgery">Academic Misconduct: Forgery</a></li>
  </ul>
<hr />
</code>```

You appear to be missing an opening
 tag.

As noted in a comment on your question, you should ensure that your markup validates.

ContentLicense: CC BY-SA 2.5

Body:
Here's the website:

http://www.uiowa.edu/~ucoll/academicmisconduct.shtml

When I go into compatability mode my footer jumps up to the bottom of my header.  I have a wrap with a virtually included header, then a content area, then a virtually included footer (fs-footer).  I'm pretty sure it's something to do with the min-height element.  I've tried a bunch of work arounds and alternatives.  I've also searched googles and forums but haven't found a good answer.  Please help :)

Code:

html {
 height: 100%;

}

body {
 padding: 0;
 margin: 0 0 0 0;
 font-family: Lucida Grande, Lucida Sans, Verdana, Arial, Helvetica, sans-serif;
 font-size: 12px;
 background-color:#999;
 background-position:center;
 height: 100%;
}

#wrap {
 width: 1024px;
 height:100%;
 margin: auto;
 padding: 0;
 min-width: 1024px;
 position: relative;
}

#mainContentPage {
 background-image: url(images/backgrounducContent.png);
 background-repeat:no-repeat;
 padding: 0;
 font-family: Arial, Helvetica, sans-serif;
 font-size: 12px;
 width: 1024px;
 margin: 0;
 float: right;
 border-bottom:thick;
 border-bottom-color: #000;
 background-color: #FFF;
 min-height: 100%;
}

.fs-footer {
 clear:both;
 float:left;
 padding-bottom:30px;
 padding-top:0px;
 width:1024px;
 border-top:thick;
 border-top-color:#000;
 border-top-style:groove;
 border-top-width:thick;
 background-color:#FFF;
 background-image:url(images/ucfooter2.png);
 height: auto;

}

Body:
Tested in IE8, IE8's Compatibility mode, Firefox:

From .fs-footer, remove float: left and add overflow: auto.

I don't think it's relevant to your problem, but you have code like this:

<a href="index.shtml" id="headLink" title="Banner Link">
  <div id="header">
    ...
  </div>
</a>

This is not good - you generally should not put block elements (such as <div> tags) inside inline elements (such as <a> tags).

Also, you have:

<div id="generalInfoMainContent">

<h1>Classroom Policies - Academic Misconduct</h1>
<p>&nbsp;</p>

<li><a href="academicmisconduct.shtml#fraud">Academic misconduct</a></li>

  <li><a href="academicmisconduct.shtml#consequences">Consequences of Academic misconduct</a></li>
  <li><a href="academicmisconduct.shtml#forgery">Academic Misconduct: Forgery</a></li>
  </ul>
<hr />

You appear to be missing an opening <ul> tag.

As noted in a comment on your question, you should ensure that your markup validates.


问:
How do I allow cross origin request
I am a backend developer and i am providing a spring boot rest API with JWT security to consume for a front end developer who calls the api from local host.So when he calls a POST request he says he gets an CORS error.So I added the part

```<code> @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

        chain.doFilter(request, response);
    }
</code>```

But still he gets the error.What may be the cause.Any help is appreciated

```<code>OPTIONS https:my.domain/url 401 (Unauthorized)
</code>```

when it is a POST request.

Controller code:

```<code>@RestController
public class RegistrationController {

    @Autowired
    @Qualifier("restTemplateUserRegitration")
    private RestTemplate restTemplateUserRegitration;
@RequestMapping(value="${user.endpoint}",produces={MediaType.APPLICATION_JSON_VALUE},method=RequestMethod.POST)
    public ResponseEntity<?> registerUser(@RequestBody Model ModelRequest){

                Map<String, Object> Status=new HashMap<String, Object>();
                FeedBackStatus = restTemplateUserRegitration.postForObject("http:serviceurl",registration/single",Model.class,Map.class );
                return ResponseEntity.ok(Status);
    }
}
</code>```

答:
This is one option. Not sure if its an elegant one

```<code> @Bean
  public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
  }
</code>```

Put this in any spring bean.

ContentLicense: CC BY-SA 4.0

Title: How do I allow cross origin request

Body:
I am a backend developer and i am providing a spring boot rest API with JWT security to consume for a front end developer who calls the api from local host.So when he calls a POST request he says he gets an CORS error.So I added the part

 @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

        chain.doFilter(request, response);
    }

But still he gets the error.What may be the cause.Any help is appreciated

OPTIONS https:my.domain/url 401 (Unauthorized)

when it is a POST request.

Controller code:

@RestController
public class RegistrationController {

    @Autowired
    @Qualifier("restTemplateUserRegitration")
    private RestTemplate restTemplateUserRegitration;
@RequestMapping(value="${user.endpoint}",produces={MediaType.APPLICATION_JSON_VALUE},method=RequestMethod.POST)
    public ResponseEntity<?> registerUser(@RequestBody Model ModelRequest){

                Map<String, Object> Status=new HashMap<String, Object>();
                FeedBackStatus = restTemplateUserRegitration.postForObject("http:serviceurl",registration/single",Model.class,Map.class );
                return ResponseEntity.ok(Status);
    }
}

Body:
This is one option. Not sure if its an elegant one

 @Bean
  public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
  }

Put this in any spring bean.


问:
How to remove column from dataTable
I have a dataTable and having trash icon at the "th". I need to remove entire column when click on the trash icon(need to remove all data from all pages). I tried the following code but which is not working under pagination.Please help me...

```<code>$(document).on("click", ".a_datatbl_trash", function (e)
{
   var indexToRemove = $(this).parent().index();
   $("#datatable-buttons tbody tr").each(function() {
      $(this).find("td:eq("+indexToRemove+")").remove();
   });
   $(this).closest("th").remove();
)};
</code>```

This is the html structure

```<code><thead>
<tr role="row">
  <th class="sorting_asc" tabindex="0" aria-controls="datatable-buttons" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Article title: activate to sort column descending">Article title
  <a href="" class="dragtable-drag-handle" style="background: none; width: 15px;"><i class="fa fa-fw fa-arrows"></i></a>
  <a href="" class="a_datatbl_trash" style="float: right;"><i class="fa fa-fw fa-trash datatbl_trash" style="float: right;"></i></a>
  </th>
</tr>
</thead>
</code>```

答:
Why don't you use the visible API? Does it not fit your need?
that could be something like:

```<code>yourDatatable.column(columnIndex).visible(false);
</code>```

Or you go to destroy the data first and update.

Title: How to remove column from dataTable

Body:
I have a dataTable and having trash icon at the "th". I need to remove entire column when click on the trash icon(need to remove all data from all pages). I tried the following code but which is not working under pagination.Please help me...

$(document).on("click", ".a_datatbl_trash", function (e)
{
   var indexToRemove = $(this).parent().index();
   $("#datatable-buttons tbody tr").each(function() {
      $(this).find("td:eq("+indexToRemove+")").remove();
   });
   $(this).closest("th").remove();
)};

This is the html structure

  Article title

Body:
Why don't you use the visible API? Does it not fit your need?
that could be something like:

yourDatatable.column(columnIndex).visible(false);

Or you go to destroy the data first and update.


答:
It's default of Ionic when you navigate using push

If you wanna show menu toggle icon, you should use setRoot

Example:

```<code>onClickNavigate() {
  console.log("onNavigate");

 this.navCtrl.setRoot("PageTwo")
}
</code>```

in "PageTwo" html, you need to add toggle button on the header too

```<code><ion-header>
    <ion-navbar>
        <button ion-button menuToggle>
          <ion-icon name="menu"></ion-icon>
        </button>
        <ion-title>page-two</ion-title>
    </ion-navbar>
</ion-header>
</code>```

Title: How can i show menu icon and not back arrow on navbar moving from page 1 to page 2 - IONIC

Body:
It's default of Ionic when you navigate using push

If you wanna show menu toggle icon, you should use setRoot

Example:

onClickNavigate() {
  console.log("onNavigate");

 this.navCtrl.setRoot("PageTwo")
}

in "PageTwo" html, you need to add toggle button on the header too

<ion-header>
    <ion-navbar>
        <button ion-button menuToggle>
          <ion-icon name="menu"></ion-icon>
        </button>
        <ion-title>page-two</ion-title>
    </ion-navbar>
</ion-header>


问:
How to map a base url to the contentBase in webpack-dev-server
I don't know how this can be achieved through the webpack-dev-server (2.4.5).

My app's base url is http://localhost:3001/app

All the static assets including the bundle.js is placed in the folder "/dist" under the project.

I had the following settings, but it can't find the images.

```<code>devServer: {
  publicPath: '/app',
  contentBase: '/dist'
}
</code>```

All the requests of static assets also follow the baseUrl. e.g.
http://localhost:3001/app/image1.jpg

I think it can't find the images because there is no folder "app" existed in the project.

Could some one advise me how to achieve this goal without changing the directory in the project? Or, is there any way that webpack can map the baseUrl to the contentBase?

答:
Your devServer.publicPath should be the same as output.publicPath. So in your config you probably should have this:

```<code>output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist/app/'),
    publicPath: '/app/'
}
</code>```

The webpack-dev-server also takes a hint from publicPath, using it to determine where to serve the output files from. https://webpack.js.org/configuration/output/#output-publicpath

Body:
I don't know how this can be achieved through the webpack-dev-server (2.4.5).

My app's base url is http://localhost:3001/app

All the static assets including the bundle.js is placed in the folder "/dist" under the project.

I had the following settings, but it can't find the images.

devServer: {
  publicPath: '/app',
  contentBase: '/dist'
}

All the requests of static assets also follow the baseUrl. e.g.
http://localhost:3001/app/image1.jpg

I think it can't find the images because there is no folder "app" existed in the project.

Could some one advise me how to achieve this goal without changing the directory in the project? Or, is there any way that webpack can map the baseUrl to the contentBase?

Body:
Your devServer.publicPath should be the same as output.publicPath. So in your config you probably should have this:

output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist/app/'),
    publicPath: '/app/'
}

The webpack-dev-server also takes a hint from publicPath, using it to determine where to serve the output files from. https://webpack.js.org/configuration/output/#output-publicpath


问:
How to make click reveal in css/js?
Just want to know how to make click reveal when I click a button the word
"Phone" will change to "+971235051"

```<code><button type="button" class="btn btn-primary">Phone</button>
<span>+971235051</span>
</code>```

Any hint for this?I found a toggle, But can't find for click reveal.

Thankyou

答:
Sorry, this answer is off tracks

Maybe look after the new HTML 5.1 element:  (here goes the MDN reference):

```<code><details>
  <summary>Phone</summary>
  <p>+971235051</p>
</details>
</code>```

If you want a more customizable way, you should try it using JQuery and the toggleClass() method:

Edited the code, it was messy, sorry ^^

$("button").click(function() {
  $("span").toggleClass("btn_active");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {
  display: none;
}

.btn_active {
  display: inline;
}</code>```

<button type="button" class="btn btn-primary">Phone</button>
+971235051```

W3C reference

Hope it may help :)

Title: How to make click reveal in css/js?

Body:
Just want to know how to make click reveal when I click a button the word
"Phone" will change to "+971235051"

<button type="button" class="btn btn-primary">Phone</button>
+971235051

Any hint for this?I found a toggle, But can't find for click reveal.

Thankyou

Body:
Sorry, this answer is off tracks

Maybe look after the new HTML 5.1 element: <summary> (here goes the MDN reference):

<details>
  <summary>Phone</summary>
  <p>+971235051</p>
</details>

If you want a more customizable way, you should try it using JQuery and the toggleClass() method:

Edited the code, it was messy, sorry ^^

$("button").click(function() {
  $("span").toggleClass("btn_active");
});

span {
  display: none;
}

.btn_active {
  display: inline;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-primary">Phone</button>
<span>+971235051</span>

W3C reference

Hope it may help :)


问:
How to export generator function in TypeScript?
I have this example in JS:

```<code>export function* mySaga () {
    yield takeEvery('USER_FETCH_REQUESTED', fetchUser);
}
</code>```

Can I rewrite it as an arrow function in TypeScript, something like this below?

```<code>export const mySaga* = () {
    yield takeEvery('USER_FETCH_REQUESTED', fetchUser);
}
</code>```

答:
Remember that TypeScript tries, mostly, to be JavaScript-plus-types (but early-adopting newer features). There is no arrow form of a generator function. However, Brendan Eich and Domenic Denicola are supposed to be working on one.

(The TypeScript specificaton just has a placeholder for its Generator Functions section [that link will rot as it's to a section number], and neither the issue related to implementing generators in TypeScript nor a related pull request mentions an arrow form.)

Body:
I have this example in JS:

export function* mySaga () {
    yield takeEvery('USER_FETCH_REQUESTED', fetchUser);
}

Can I rewrite it as an arrow function in TypeScript, something like this below?

export const mySaga* = () {
    yield takeEvery('USER_FETCH_REQUESTED', fetchUser);
}


问:
How to store username and password in one application and retrieve values in another application nativescript angular2
I just want to save user name and password in one nativescript application. Then in Second nativescript application, I have to retrieve the saved username and password.

I don't know how to achieve this in nativescript angular2. Any help is appreciated.thanks.

答:
Try using LDAP server to store username and password .

Access these information in Webserver using any of server side languages using LDAP protocol .

Expose this functionality using known protocol like HTTP. Then Angular can access user information using any  REST Api call .


问:
What is the difference between an expression and a statement in Python?
In Python, what is the difference between expressions and statements?</p>

答:
Python calls expressions "expression statements", so the question is perhaps not fully formed.

A statement consists of pretty much anything you can do in Python: calculating a value, assigning a value, deleting a variable, printing a value, returning from a function, raising an exception, etc. The full list is here: http://docs.python.org/reference/simple_stmts.html#

An expression statement is limited to calling functions (e.g.,
math.cos(theta)"), operators ( e.g., "2+3"), etc.  to produce a value.


问:
Change button color all edittext fields filled?
I have button and text fields like below in my layout file

```<code><EditText
        android:id="@+id/et_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView4"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/btn_app_signup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_password"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="63dp"
        android:background="@drawable/button"
        android:text="SIGN UP"
        android:textColor="@color/white" />
</code>```

How can I change this background into @drawable/button_success to if all edit text fields filled my Activity class like below

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);
        btn_app_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String name = et_name.getText().toString();
                String email = et_email.getText().toString();
                String password = et_password.getText().toString();

                registerAccount(name, email, password);
            }
        });
    }

    private void registerAccount(String name, String email, String password) {

        if(TextUtils.isEmpty(name) || TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
            Toast.makeText(SignupActivity.this, "All fields required", Toast.LENGTH_LONG).show();
        }
        else {

            //save data in datbase
        }
    }
</code>```

How can I do that if I fill all my edit text fields fill change the button button background

答:
```<code>et_name.addTextChangedListener(new TextWatcher(){

    @Override
    public void beforeTextChanged(CharSequence s,int start,int count,int after){

    }

    @Override
    public void onTextChanged(CharSequence s,int start,int before,int count){
    String name=et_name.getText().toString();
    String email=et_email.getText().toString();
    String password=et_password.getText().toString();

    valiadte(name,email,password);
    }

    @Override
    public void afterTextChanged(Editable s){

    }
    });

    et_email.addTextChangedListener(new TextWatcher(){

    @Override
    public void beforeTextChanged(CharSequence s,int start,int count,int after){

    }

    @Override
    public void onTextChanged(CharSequence s,int start,int before,int count){
    String name=et_name.getText().toString();
    String email=et_email.getText().toString();
    String password=et_password.getText().toString();

    valiadte(name,email,password);
    }

    @Override
    public void afterTextChanged(Editable s){

    }
    });
    et_password.addTextChangedListener(new TextWatcher(){

    @Override
    public void beforeTextChanged(CharSequence s,int start,int count,int after){

    }

    @Override
    public void onTextChanged(CharSequence s,int start,int before,int count){
    String name=et_name.getText().toString();
    String email=et_email.getText().toString();
    String password=et_password.getText().toString();

    valiadte(name,email,password);
    }

    @Override
    public void afterTextChanged(Editable s){

    }
    });
</code>```

<p>and invalidate function do </p>

```<code> private void valiadte(String name,String email,String password){
              if(!TextUtils.isEmpty(name)&&!TextUtils.isEmpty(email)&&!TextUtils.isEmpty(password){
               btn_app_signup.setBackground(ContextCompat.getDrawable(this,R.drawable.ic_android_black_24dp));
               // set here your backgournd to button
  }

 }
</code>```

Body:
I have button and text fields like below in my layout file

<EditText
        android:id="@+id/et_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView4"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/btn_app_signup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_password"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="63dp"
        android:background="@drawable/button"
        android:text="SIGN UP"
        android:textColor="@color/white" />

How can I change this background into @drawable/button_success to if all edit text fields filled my Activity class like below

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);
        btn_app_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String name = et_name.getText().toString();
                String email = et_email.getText().toString();
                String password = et_password.getText().toString();

                registerAccount(name, email, password);
            }
        });
    }

    private void registerAccount(String name, String email, String password) {

        if(TextUtils.isEmpty(name) || TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
            Toast.makeText(SignupActivity.this, "All fields required", Toast.LENGTH_LONG).show();
        }
        else {

            //save data in datbase
        }
    }

How can I do that if I fill all my edit text fields fill change the button button background

Body:
et_name.addTextChangedListener(new TextWatcher(){

    @Override
    public void beforeTextChanged(CharSequence s,int start,int count,int after){

    }

    @Override
    public void onTextChanged(CharSequence s,int start,int before,int count){
    String name=et_name.getText().toString();
    String email=et_email.getText().toString();
    String password=et_password.getText().toString();

    valiadte(name,email,password);
    }

    @Override
    public void afterTextChanged(Editable s){

    }
    });

    et_email.addTextChangedListener(new TextWatcher(){

    @Override
    public void beforeTextChanged(CharSequence s,int start,int count,int after){

    }

    @Override
    public void onTextChanged(CharSequence s,int start,int before,int count){
    String name=et_name.getText().toString();
    String email=et_email.getText().toString();
    String password=et_password.getText().toString();

    valiadte(name,email,password);
    }

    @Override
    public void afterTextChanged(Editable s){

    }
    });
    et_password.addTextChangedListener(new TextWatcher(){

    @Override
    public void beforeTextChanged(CharSequence s,int start,int count,int after){

    }

    @Override
    public void onTextChanged(CharSequence s,int start,int before,int count){
    String name=et_name.getText().toString();
    String email=et_email.getText().toString();
    String password=et_password.getText().toString();

    valiadte(name,email,password);
    }

    @Override
    public void afterTextChanged(Editable s){

    }
    });

and invalidate function do

 private void valiadte(String name,String email,String password){
              if(!TextUtils.isEmpty(name)&&!TextUtils.isEmpty(email)&&!TextUtils.isEmpty(password){
               btn_app_signup.setBackground(ContextCompat.getDrawable(this,R.drawable.ic_android_black_24dp));
               // set here your backgournd to button
  }

 }


问:
Input and Store names in array - Java
I have been trying out this questions however I still cannot find the solution to it. Any help is appreciated! Thanks

Question - Declare and create an array to store the names of four players.  Call the array pNames.

Ask the user to input the names of the four players and store their names in the pNames array.

```<code>  Enter Name of Player 1 > Johnny
  Enter Name of Player 2 > Jackie
  Enter Name of Player 3 > Jessie
  Enter Name of Player 4 > Jeremy
</code>```

Output a hello message to greet each player.

```<code>Hello Johnny
Hello Jackie
Hello Jessie
Hello Jeremy
</code>```

Answer:

```<code>  import java.util.Scanner;
  public class Q2 {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String [] pNames = new String[4];

    for(int i = 1; i <= pNames.length; i++) {

        System.out.print("Enter name of Player" + " " + i + " > ");

        pNames[i] = sc.nextLine();
    }

    System.out.println("Hello" + " " + pNames[0]);
    System.out.println("Hello" + " " + pNames[1]);
    System.out.println("Hello" + " " + pNames[2]);
    System.out.println("Hello" + " " + pNames[3]);
}
</code>```

}

答:
Arrays are 0 index based.

In the loop you are using a 1 index base.

Change

```<code>for(int i = 1; i <= pNames.length; i++) {

    System.out.print("Enter name of Player" + " " + i + " > ");

    pNames[i] = sc.nextLine();
}
</code>```

to

```<code>for(int i = 1; i <= pNames.length; i++) {

    System.out.print("Enter name of Player" + " " + i + " > ");

    // The index of pNames must start from 0!
    pNames[i-1] = sc.nextLine();
}
</code>```

A solution closer to the mode of reasoning of programmers is to use a loop starting from 0 and change the System.out as follow:

```<code>// Loop start from 0 and goes to 4 excluded
for (int i = 0; i < pNames.length; i++) {

    // To print Enter name of Player 1 change i to (i + 1)
    System.out.print("Enter name of Player" + " " + (i + 1) + " > ");

    pNames[i] = sc.nextLine();
}
</code>```

Title: Input and Store names in array - Java

Body:
I have been trying out this questions however I still cannot find the solution to it. Any help is appreciated! Thanks

Question - Declare and create an array to store the names of four players.  Call the array pNames.

Ask the user to input the names of the four players and store their names in the pNames array.

  Enter Name of Player 1 > Johnny
  Enter Name of Player 2 > Jackie
  Enter Name of Player 3 > Jessie
  Enter Name of Player 4 > Jeremy

Output a hello message to greet each player.

Hello Johnny
Hello Jackie
Hello Jessie
Hello Jeremy

Answer:

  import java.util.Scanner;
  public class Q2 {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String [] pNames = new String[4];

    for(int i = 1; i <= pNames.length; i++) {

        System.out.print("Enter name of Player" + " " + i + " > ");

        pNames[i] = sc.nextLine();
    }

    System.out.println("Hello" + " " + pNames[0]);
    System.out.println("Hello" + " " + pNames[1]);
    System.out.println("Hello" + " " + pNames[2]);
    System.out.println("Hello" + " " + pNames[3]);
}

}

Body:
Arrays are 0 index based.

In the loop you are using a 1 index base.

Change

for(int i = 1; i <= pNames.length; i++) {

    System.out.print("Enter name of Player" + " " + i + " > ");

    pNames[i] = sc.nextLine();
}

to

for(int i = 1; i <= pNames.length; i++) {

    System.out.print("Enter name of Player" + " " + i + " > ");

    // The index of pNames must start from 0!
    pNames[i-1] = sc.nextLine();
}

A solution closer to the mode of reasoning of programmers is to use a loop starting from 0 and change the System.out as follow:

// Loop start from 0 and goes to 4 excluded
for (int i = 0; i < pNames.length; i++) {

    // To print Enter name of Player 1 change i to (i + 1)
    System.out.print("Enter name of Player" + " " + (i + 1) + " > ");

    pNames[i] = sc.nextLine();
}


问:
App has conflicting provisioning settings in Build Settings
I have generated a certificate and created a provisioning profile for my project so that I could make push notification in it, but when in Build Setting -> CodeSigning I write the name of provisioning profile and give my team name in General an error appears that AppName has conflicting provisioning settings.

How can I correct this?

The error looks like this

答: Deselect automatically manage signing and select your provisioning profile in the respective field.</p>


问:
How to stop hammer.js event propagation
How to stop event propagation in Hammer.js (2.0.2)? The technique used in the relevant test (https://github.com/hammerjs/hammer.js/blob/master/tests/unit/test_propagation.js) does not apply to all type of events. If you replace the 'tap' event with a 'press' one, the test fails. </p>

答: In your parent dom bind click event, and stopPropagation it</p>

Title: How to stop hammer.js event propagation


问:
Open a local PDF file on  tag
I'm running create-react-app, and I want to open a local PDF file stored inside my repo with a relative path.

```<code><a href="../file.pdf" target="_blank">
    <button name="Click here" />
</a>
</code>```

After I click it, it takes me to localhost:3000/file.pdf. How do I open up a new window with a PDF?

Title: Open a local PDF file on <a> tag

Body:
I'm running create-react-app, and I want to open a local PDF file stored inside my repo with a relative path.

    <button name="Click here" />

After I click it, it takes me to localhost:3000/file.pdf. How do I open up a new window with a PDF?


问:
sql query with two joins and a simple logic
Please find the fiddle
http://sqlfiddle.com/#!9/4a4aff/7

Friends_list Table

```<code> | id | user_id | Friend_id | status
 |  1 |   1     |    24     |   P
 |  2 |   18    |    26     |   P
</code>```

User Table

```<code>| ID | email   | password  |  ..N
 |  1 |   xx    |    xx     |   xx
 |  2 |   xx    |    xx     |   xx
</code>```

from those both table i want to get all the users listed without the users whose status was P or B in friends list table it seems to be simple using joins but in wordpress this code is not working and the query is as below.

```<code>select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.friend_id=u.ID
WHERE f.status  NOT IN ('P', 'B')
</code>```

答:
Just change the binding column like this :-</p>

```<code>select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.user_id=u.ID
WHERE f.status NOT IN ('P', 'B');
</code>```

Body:
Please find the fiddle
http://sqlfiddle.com/#!9/4a4aff/7

Friends_list Table

 | id | user_id | Friend_id | status
 |  1 |   1     |    24     |   P
 |  2 |   18    |    26     |   P

User Table

| ID | email   | password  |  ..N
 |  1 |   xx    |    xx     |   xx
 |  2 |   xx    |    xx     |   xx

from those both table i want to get all the users listed without the users whose status was P or B in friends list table it seems to be simple using joins but in wordpress this code is not working and the query is as below.

select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.friend_id=u.ID
WHERE f.status  NOT IN ('P', 'B')

Body:
Just change the binding column like this :-

select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.user_id=u.ID
WHERE f.status NOT IN ('P', 'B');


问:
how to test method that prints to console in golang?
I have next struct.

```<code>package logger

import "fmt"

type IPrinter interface {
    Print(value string)
}

type ConsolePrinter struct{}

func (cp *ConsolePrinter) Print(value string) {
    fmt.Printf("this is value: %s", value)
}
</code>```

Test coverage says I need to test that ConsolePrinter Print method.

How can I cover this method?

Thanks.

答:
Following comment that @icza wrote, I've written test below.

```<code>func TestPrint(t *testing.T) {
    rescueStdout := os.Stdout
    r, w, _ := os.Pipe()
    os.Stdout = w

    cp := &ConsolePrinter{}
    cp.Print("test")

    w.Close()
    out, _ := ioutil.ReadAll(r)
    os.Stdout = rescueStdout

    if string(out) != "this is value: test" {
        t.Errorf("Expected %s, got %s", "this is value: test", out)
    }
}
</code>```

I've found example in question What is the best way to convert byte array to string?.

Body:
I have next struct.

package logger

import "fmt"

type IPrinter interface {
    Print(value string)
}

type ConsolePrinter struct{}

func (cp *ConsolePrinter) Print(value string) {
    fmt.Printf("this is value: %s", value)
}

Test coverage says I need to test that ConsolePrinter Print method.

How can I cover this method?

Thanks.

Body:
Following comment that @icza wrote, I've written test below.

func TestPrint(t *testing.T) {
    rescueStdout := os.Stdout
    r, w, _ := os.Pipe()
    os.Stdout = w

    cp := &ConsolePrinter{}
    cp.Print("test")

    w.Close()
    out, _ := ioutil.ReadAll(r)
    os.Stdout = rescueStdout

    if string(out) != "this is value: test" {
        t.Errorf("Expected %s, got %s", "this is value: test", out)
    }
}

I've found example in question What is the best way to convert byte array to string?.


问:
Testing iOS Applications with latest Appium Tool
I need to test iOS Application. I have installed appium on Mac.

I have installed below Tools:

1) XCODE

2) JDK

3) Commmand Line Tools

4) Appium

I am getting following errors while running appium server for testing sample iOS application.

Anybody tell me the steps to how to perform iOS Application Testing Using Latest Appium Tool?

Must appreciate for any better Suggestions for testing iOS Applications

Thanks for your help in advance.

答:
Starting with iOS 9.3 appium is using XCUITest for testing iOS apps.

So you need to read official documentation about required setup.

And there is another doc about setup for real device execution.

Note: for Xcode 9.1 you have to use Appium server 1.7.2-beta and above


问:
Testing ldap connection
I want to validate user entered ldap settings. On settings page user enters ldap url, manager dn and password. I have a 'Test settings' button on this page so that user can quickly verify the ldap connection. How to do this easily and quickly?

Our application using spring security and in the process of adding ldap authentication to it.
I am kind of new to java and ldap, so pointing me to right direction is greatly appreciated.

Thanks.

答:
Test the LDAP connection using Spring LDAP authentication:

i.e. with the authenticate() method:

```<code>ldapTemplate.authenticate(query, password);
</code>```

or even better, with getContext() method:

```<code>ldapTemplate.getContextSource().getContext(userDn, userPassword));
</code>```

Catch the org.springframework.ldap.CommunicationException to check if the connection succeeds.

The full code snippet should look like this:

```<code>// Create the spring LdapTemplates; i.e. connections to the source and target ldaps:
try {
    // Note: I'm using the direct LdapTemplate initialization rather than with bean creation (Spring ldap supports both)
    log.info("Connecting to LDAP " + sourceHost + ":" + sourcePort + "...");
    LdapContextSource sourceLdapCtx = new LdapContextSource();
    sourceLdapCtx.setUrl("ldap://" + sourceHost + ":" + sourcePort + "/");
    sourceLdapCtx.setUserDn(sourceBindAccount);
    sourceLdapCtx.setPassword(sourcePassword);
    sourceLdapCtx.setDirObjectFactory(DefaultDirObjectFactory.class);
    sourceLdapCtx.afterPropertiesSet();
    sourceLdapTemplate = new LdapTemplate(sourceLdapCtx);
    // Authenticate:
    sourceLdapTemplate.getContextSource().getContext(sourceBindAccount, sourcePassword);
} catch (Exception e) {
    throw new Exception("Failed to connect to LDAP - " + e.getMessage(), e);
}
</code>```

Note: I'm using spring LDAP 2.3.x version:

```<code><dependency>
    <groupId>org.springframework.ldap</groupId>
    <artifactId>spring-ldap-core</artifactId>
</dependency>
</code>```

Title: Testing ldap connection

Body:
Test the LDAP connection using Spring LDAP authentication:

i.e. with the authenticate() method:

ldapTemplate.authenticate(query, password);

or even better, with getContext() method:

ldapTemplate.getContextSource().getContext(userDn, userPassword));

Catch the org.springframework.ldap.CommunicationException to check if the connection succeeds.

The full code snippet should look like this:

// Create the spring LdapTemplates; i.e. connections to the source and target ldaps:
try {
    // Note: I'm using the direct LdapTemplate initialization rather than with bean creation (Spring ldap supports both)
    log.info("Connecting to LDAP " + sourceHost + ":" + sourcePort + "...");
    LdapContextSource sourceLdapCtx = new LdapContextSource();
    sourceLdapCtx.setUrl("ldap://" + sourceHost + ":" + sourcePort + "/");
    sourceLdapCtx.setUserDn(sourceBindAccount);
    sourceLdapCtx.setPassword(sourcePassword);
    sourceLdapCtx.setDirObjectFactory(DefaultDirObjectFactory.class);
    sourceLdapCtx.afterPropertiesSet();
    sourceLdapTemplate = new LdapTemplate(sourceLdapCtx);
    // Authenticate:
    sourceLdapTemplate.getContextSource().getContext(sourceBindAccount, sourcePassword);
} catch (Exception e) {
    throw new Exception("Failed to connect to LDAP - " + e.getMessage(), e);
}

Note: I'm using spring LDAP 2.3.x version:

<dependency>
    <groupId>org.springframework.ldap</groupId>
    <artifactId>spring-ldap-core</artifactId>
</dependency>


问:
Is there a way to add coverage report to gitlab?
I understand that gitlab has support to Jenkins CI, but what I need is a lot less than that.

I have a Rails application and get the coverage from the tests using simplecov. It generates HTML output in a directory by running a rake task. I would like to see the current coverage through gitlab. Is there a simple way to integrate this report with gitlab?

答: See Publish Code Coverage Report with GitLab Pages</p>


问:
how to iterate throught an array of objects and concate the contents
I have the object (obj1) that is posted below. As shown  in it, it contains an array of objects called "favoritePlayers".

what I am trying to do is, to create a function or add an array prototype so that I can iterate through each element in the array separately and get the following output:

"messi plays in barcelona"
"totti plays in roma"

I tried to solve it as shown below but what I get is

```<code>[ 'undefinedplays in[object Object]',
'undefinedplays in[object Object]' ]
</code>```

obj1:

```<code>var obj1 = {
score: [10, 22, 30, 55, 70, 90],
lettersOfMyName: ["a", "m", "r"],
avgScore: null,
favoritePlayers: [
    {
        name: "messi",
        club: "barcelona"
    },

    {
        name: "totti",
        club: "roma"
    }
],

calcAvgScore: function () {
    var sumOfScores = this.score.reduce(function (prev, cur, index, array)
{

        return prev + cur;

    })

    return (sumOfScores / this.score.length);
},

myFavoritePlayersInfo: function () {
    console.log(this.favoritePlayers.join());
},

}
</code>```

my attempts:
    //this code was added outside the scope of obj1

```<code>Array.prototype.concat1 = ( (array) => {
var tempArray = [];

for (var i = 0; i < array.length; i++) {

tempArray[i] = array.slice(i, i+1).name + "plays in" + array.slice(i,
i+1);

}

return tempArray;

});
</code>```

update_1

I added the following lines to obj1:

```<code>getPlaysIn:function() {
    this.favoritePlayers.forEach( (favoritePlayer)=> {
        return favoritePlayer.name + " plays in " + favoritePlayer.club;
</code>```

and I call it as follows:

```<code>console.log(obj1.getPlaysIn());
</code>```

but the results i get is

```<code>undefined
</code>```

答:
Try below code.

var obj1 = {
score: [10, 22, 30, 55, 70, 90],
lettersOfMyName: ["a", "m", "r"],
avgScore: null,
favoritePlayers: [
    {
        name: "messi",
        club: "barcelona"
    },

    {
        name: "totti",
        club: "roma"
    }
],
getPlaysIn:function() {
   var returnVal = "";
   this.favoritePlayers.forEach( (favoritePlayer)=> {
        returnVal += favoritePlayer.name + " plays in " + favoritePlayer.club+"\n";
        });
    return returnVal;
   }
}

console.log(obj1.getPlaysIn());```

Body:
I have the object (obj1) that is posted below. As shown  in it, it contains an array of objects called "favoritePlayers".

what I am trying to do is, to create a function or add an array prototype so that I can iterate through each element in the array separately and get the following output:

"messi plays in barcelona"
"totti plays in roma"

I tried to solve it as shown below but what I get is

[ 'undefinedplays in[object Object]',
'undefinedplays in[object Object]' ]

obj1:

var obj1 = {
score: [10, 22, 30, 55, 70, 90],
lettersOfMyName: ["a", "m", "r"],
avgScore: null,
favoritePlayers: [
    {
        name: "messi",
        club: "barcelona"
    },

    {
        name: "totti",
        club: "roma"
    }
],

calcAvgScore: function () {
    var sumOfScores = this.score.reduce(function (prev, cur, index, array)
{

        return prev + cur;

    })

    return (sumOfScores / this.score.length);
},

myFavoritePlayersInfo: function () {
    console.log(this.favoritePlayers.join());
},

}

my attempts:
    //this code was added outside the scope of obj1

Array.prototype.concat1 = ( (array) => {
var tempArray = [];

for (var i = 0; i < array.length; i++) {

tempArray[i] = array.slice(i, i+1).name + "plays in" + array.slice(i,
i+1);

}

return tempArray;

});

update_1

I added the following lines to obj1:

getPlaysIn:function() {
    this.favoritePlayers.forEach( (favoritePlayer)=> {
        return favoritePlayer.name + " plays in " + favoritePlayer.club;

and I call it as follows:

console.log(obj1.getPlaysIn());

but the results i get is

undefined


问:
A puzzle about time complexity calculation and real time consumption
While learning the basic knowledge of algorithm, I find puzzle about the time complexity calculation and the real time consumption when run the codes.

The demo codes specify the problem.

```<code>function calcDemo1(){
    var init = 0;
    for(var i=0;i<40;i++){
        init += 0;
    }
    return init;
}

function calcDemo2(){
    var init = 0;
    init += (0+1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39);
    return init;
}
</code>```

Does calcDemo1's time complexity is O(1) even if it's a "for loop"?

In case their time complexity were both O(1), do they take the same amount of time in the worst-case scenario when run the code?

The relative question is here

答:
Constant time complexity O(1) means that the execution takes the same amount of time, no matter how big the input.

Linear time complexity O(n) means that execution takes longer to the same degree that the input size increases.

Your examples

It depends on what you define as your input. In my analysis below I am assuming that your input is the number of times to loop/add a number (40). If there is no input at all, then any code will just be of constant time complexity O(1).

calcDemo1 most likely has linear complexity because the javascript compiler isn't smart enough to figure out that it could just skip the loop. It will actually increase i 40 times and then add 0 to init 40 times (or at least check if it actually has to add anything). Therefore, each rotation of the loop actually takes some time and, say, looping 4000 times would 100 times longer than 40 times.

calcDemo2 also has linear complexity O(n): Adding 1 million numbers should take roughly 1000 times as long as just adding 1000 numbers.

Body:
While learning the basic knowledge of algorithm, I find puzzle about the time complexity calculation and the real time consumption when run the codes.

The demo codes specify the problem.

function calcDemo1(){
    var init = 0;
    for(var i=0;i<40;i++){
        init += 0;
    }
    return init;
}

function calcDemo2(){
    var init = 0;
    init += (0+1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39);
    return init;
}

Does calcDemo1's time complexity is O(1) even if it's a "for loop"?

In case their time complexity were both O(1), do they take the same amount of time in the worst-case scenario when run the code?

The relative question is here


问:
How do I edit this plugin to add a field in the shortcode?
I'm working on this theme in Wordpress and attempting to edit the plugin so that in when added in Visual Composer it will ask the question how many posts would you like to display? I added this to the Attributes 'number_of_post' => '4', and added this 'posts_per_page' => $number_of_post, to the WP_Query Arguments and it still doesn't seem to be working.

Here is the actual code for the plugin:

```<code>//Work Area
function ratio_work_area( $atts , $content = null ){
 // Attributes
    extract( shortcode_atts(
        array(
            'sec_title_before' => 'Latest',
            'sec_title_after' => 'works',
            'sec_btn_text' => 'See More Work',
            'sec_btn_link' => '#',
            'number_of_post' => '4',
        ), $atts )
    );
ob_start();
?>

<!-- START PORTFOLIO -->
<section id="portfolio" class="works_area section-padding">
    <div class="container-fluid">
        <div class="row text-center">
            <div class="section-title wow zoomIn">
                <h2><?php echo esc_html($sec_title_before);?> <span><?php echo esc_html($sec_title_after);?></span></h2>
                <div></div>
            </div>
            <div class="col-md-12">
                <div class="our_work_menu">

                    <?php $terms = get_terms('cat_portfolios');
                        if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
                    ?>
                    <ul>
                        <li class="filter wow fadeIn" data-wow-duration="1.5s" data-wow-delay=".25s" data-filter="all"><?php esc_html_e('All' , 'ratio');?></li>
                        <?php foreach ( $terms as $term ) :?>
                        <li class="filter" data-filter=".<?php echo esc_attr($term->slug); ?>"><?php echo esc_html($term->name); ?></li>
                        <?php endforeach;?>
                    </ul>
                    <?php }?>

                </div>
            </div>

            <div class="work_all_item">
    <?php

                // WP_Query arguments
                $args = array (
                    'post_type'              => array( 'portfolios' ),
                    'posts_per_page'              => $number_of_post,
                );

                // The Query
                $ratio_port_query = new WP_Query( $args );

                // The Loop
                if ( $ratio_port_query->have_posts() ) {
                    while ( $ratio_port_query->have_posts() ) {
                        $ratio_port_query->the_post();
                        $ratio_port_image = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()),'ratio_image_1200_1200');
                        ?>
                        <?php

                            $portfolio_terms = get_the_terms(get_the_id(), 'cat_portfolios');

                            if ( ! empty( $portfolio_terms ) && ! is_wp_error( $portfolio_terms ) ):

                                $portfolios_cat_slug = array();

                                foreach($portfolio_terms as $portfolio_term){
                                    $portfolios_cat_slug[] = $portfolio_term->slug ;
                                }

                                $portfolios_cat_array = join(" ", $portfolios_cat_slug);
                                $portfolios_class_array = join(" ", $portfolios_cat_slug);
                            endif;
                        ?>

                        <div class="grid-item col-md-3 col-sm-6 col-xs-12 mix all <?php echo esc_attr($portfolios_class_array);?>">
                            <div class="single_our_work">
                                <div class="sing_work_photo">
                                    <figure>
                                        <img src="<?php echo esc_url($ratio_port_image['0']);?>" alt="">
                                        <div class="sing_work_text_link">
                                            <div class="sing_work_content_wrap">
                                                <div class="sing_work_content">
                                                    <div class="sing_link_img">
                                                        <a href="<?php echo esc_url($ratio_port_image['0']);?>" class="lightbox search" data-gall="gall-work"><i class="fa fa-eye"></i></a>
                                                        <a href="<?php the_permalink();?>" class="link"><i class="fa fa-link"></i></a>
                                                    </div>

                                                    <h5><?php the_title();?></h5>
                                                <?php $terms = get_the_terms(get_the_ID(), 'cat_portfolios');
                                                        if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
                                                            foreach ( $terms as $term ) {
                                                    ?>
                                                    <p><?php echo esc_html($term->name); ?></p>

                                                    <?php
                                                            }
                                                    } ?>
                                                </div>
                                            </div>
                                        </div>
                                    </figure>
                                </div>
                            </div>
                        </div>

                <?php   }
                } else {
                    // no posts found
                }

                // Restore original Post Data
                wp_reset_postdata();

            ?>

            </div>
        </div>
        <?php if($sec_btn_link){ ?>
            <div class="portfolio_btn text-center">
                <a href="<?php echo esc_url($sec_btn_link);?>" class="btn-light-bg"><?php echo esc_html($sec_btn_text);?></a>
            </div>
        <?php } ?>
    </div>
</section>
<!-- END PORTFOLIO -->

<?php
  return ob_get_clean();
}
add_shortcode ('work_area', 'ratio_work_area' );
</code>```

答:
Please try to use 'number_of_posts' => '4',; You have missed letter s.
If that doesn't work, try to use posts_per_page instead of number_of_posts. It's depend on version you using.

Body:
I'm working on this theme in Wordpress and attempting to edit the plugin so that in when added in Visual Composer it will ask the question how many posts would you like to display? I added this to the Attributes 'number_of_post' => '4', and added this 'posts_per_page' => $number_of_post, to the WP_Query Arguments and it still doesn't seem to be working.

Here is the actual code for the plugin:

//Work Area
function ratio_work_area( $atts , $content = null ){
 // Attributes
    extract( shortcode_atts(
        array(
            'sec_title_before' => 'Latest',
            'sec_title_after' => 'works',
            'sec_btn_text' => 'See More Work',
            'sec_btn_link' => '#',
            'number_of_post' => '4',
        ), $atts )
    );
ob_start();
?>

<?php echo esc_html($sec_title_before);?> <?php echo esc_html($sec_title_after);?>

                    <?php $terms = get_terms('cat_portfolios');
                        if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
                    ?>

<?php esc_html_e('All' , 'ratio');?>

                        <?php foreach ( $terms as $term ) :?>
                        <li class="filter" data-filter=".<?php echo esc_attr($term->slug); ?>"><?php echo esc_html($term->name); ?>

                        <?php endforeach;?>

                    <?php }?>

    <?php

                // WP_Query arguments
                $args = array (
                    'post_type'              => array( 'portfolios' ),
                    'posts_per_page'              => $number_of_post,
                );

                // The Query
                $ratio_port_query = new WP_Query( $args );

                // The Loop
                if ( $ratio_port_query->have_posts() ) {
                    while ( $ratio_port_query->have_posts() ) {
                        $ratio_port_query->the_post();
                        $ratio_port_image = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()),'ratio_image_1200_1200');
                        ?>
                        <?php

                            $portfolio_terms = get_the_terms(get_the_id(), 'cat_portfolios');

                            if ( ! empty( $portfolio_terms ) && ! is_wp_error( $portfolio_terms ) ):

                                $portfolios_cat_slug = array();

                                foreach($portfolio_terms as $portfolio_term){
                                    $portfolios_cat_slug[] = $portfolio_term->slug ;
                                }

                                $portfolios_cat_array = join(" ", $portfolios_cat_slug);
                                $portfolios_class_array = join(" ", $portfolios_cat_slug);
                            endif;
                        ?>

                        <div class="grid-item col-md-3 col-sm-6 col-xs-12 mix all <?php echo esc_attr($portfolios_class_array);?>">

                                        <img src="<?php echo esc_url($ratio_port_image['0']);?>" alt="">

                                                        <a href="<?php echo esc_url($ratio_port_image['0']);?>" class="lightbox search" data-gall="gall-work">
                                                        <a href="<?php the_permalink();?>" class="link">

<?php the_title();?>

                                                <?php $terms = get_the_terms(get_the_ID(), 'cat_portfolios');
                                                        if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
                                                            foreach ( $terms as $term ) {
                                                    ?>

<?php echo esc_html($term->name); ?>

                                                    <?php
                                                            }
                                                    } ?>

                <?php   }
                } else {
                    // no posts found
                }

                // Restore original Post Data
                wp_reset_postdata();

            ?>

        <?php if($sec_btn_link){ ?>

                <a href="<?php echo esc_url($sec_btn_link);?>" class="btn-light-bg"><?php echo esc_html($sec_btn_text);?>

        <?php } ?>

<?php
  return ob_get_clean();
}
add_shortcode ('work_area', 'ratio_work_area' );


问:
How do I check if a given `Method` object accepts a given `Tuple` of types in Julia 0.6?
The goal is to define a function that takes a method, and a tuple of types,
and returns true those types are a valid input for that method.
Not function, method

accepts(meth::Method, types::Tuple)::Bool

Here is a testset for this

```<code>using Base.Test
@testset "accepts method checker" begin
    concrete = first(methods(length, (String,)))
    #length(s::String) in Base at strings/string.jl:162

    abstract_ = last(collect(methods(length,(AbstractArray,))))
    #length(t::AbstractArray) in Base at abstractarray.jl:131

    triangular = first(methods(length, (StepRange,)))
    # length(r::StepRange{T,S} where S) where T<:Union{Int64, UInt64} in Base at range.jl:381

    a = "hello"
    a_t = (typeof(a),) #(String,)
    @test accepts(concrete, a_t)
    @test !accepts(abstract_, a_t)
    @test !accepts(triangular, a_t)

    b = 1.5:10
    b_t = (typeof(b),) #(StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}})
    @test !accepts(concrete, b_t)
    @test accepts(abstract_, b_t)
    @test !accepts(triangular, b_t)

    c_t = (StepRange{Float64, Float64},) # Nothing real has this type as it can't be constructed
    @test !accepts(concrete, c_t)
    @test accepts(abstract_, c_t)
    @test !accepts(triangular, c_t)

    d = 1:2:10
    d_t = (typeof(d),) #(StepRange{Int64,Int64}
    @test !accepts(concrete, d_t)
    @test accepts(abstract_, d_t)
    @test accepts(triangular, d_t)
end
</code>```

Since julia don't have much of a public reflection API (as I have griped before), I am fine with code that is going to break potentially every patch version

The goal of this question is to help me understand what I am going to need to do to update this part of InterfaceTesting.jl from 0.5 to 0.6

The thing that makes my old code no longer work is changes that were introduced to allow for triangular dispatch.
So the triangular tests are the hard ones to pass.

答:
This is frankly scary code but:

```<code>function accepts(d::Method, ts::Tuple)
    ps = Base.unwrap_unionall(d.sig).parameters[2:end]
    length(ts) != length(ps) && return false

    all(zip(ts, ps)) do tp
        t, p = tp
        x = Base.rewrap_unionall(p, d.sig)
        Base.type_close_enough(x, t) || t <: x
    end
end
</code>```

passes all of your tests.
I'm not certain there isn't some corner case it misses though.
You have no tests with multiple types in that Tuple.
It is basically ripped off from methodswith

Body:
The goal is to define a function that takes a method, and a tuple of types,
and returns true those types are a valid input for that method.
Not function, method

accepts(meth::Method, types::Tuple)::Bool

Here is a testset for this

using Base.Test
@testset "accepts method checker" begin
    concrete = first(methods(length, (String,)))
    #length(s::String) in Base at strings/string.jl:162

    abstract_ = last(collect(methods(length,(AbstractArray,))))
    #length(t::AbstractArray) in Base at abstractarray.jl:131

    triangular = first(methods(length, (StepRange,)))
    # length(r::StepRange{T,S} where S) where T<:Union{Int64, UInt64} in Base at range.jl:381

    a = "hello"
    a_t = (typeof(a),) #(String,)
    @test accepts(concrete, a_t)
    @test !accepts(abstract_, a_t)
    @test !accepts(triangular, a_t)

    b = 1.5:10
    b_t = (typeof(b),) #(StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}})
    @test !accepts(concrete, b_t)
    @test accepts(abstract_, b_t)
    @test !accepts(triangular, b_t)

    c_t = (StepRange{Float64, Float64},) # Nothing real has this type as it can't be constructed
    @test !accepts(concrete, c_t)
    @test accepts(abstract_, c_t)
    @test !accepts(triangular, c_t)

    d = 1:2:10
    d_t = (typeof(d),) #(StepRange{Int64,Int64}
    @test !accepts(concrete, d_t)
    @test accepts(abstract_, d_t)
    @test accepts(triangular, d_t)
end

Since julia don't have much of a public reflection API (as I have griped before), I am fine with code that is going to break potentially every patch version

The goal of this question is to help me understand what I am going to need to do to update this part of InterfaceTesting.jl from 0.5 to 0.6

The thing that makes my old code no longer work is changes that were introduced to allow for triangular dispatch.
So the triangular tests are the hard ones to pass.

Body:
This is frankly scary code but:

function accepts(d::Method, ts::Tuple)
    ps = Base.unwrap_unionall(d.sig).parameters[2:end]
    length(ts) != length(ps) && return false

    all(zip(ts, ps)) do tp
        t, p = tp
        x = Base.rewrap_unionall(p, d.sig)
        Base.type_close_enough(x, t) || t <: x
    end
end

passes all of your tests.
I'm not certain there isn't some corner case it misses though.
You have no tests with multiple types in that Tuple.
It is basically ripped off from methodswith


问:
backbonejs function is is not defined
I am encountering a function is not defined .

I getting key value pairs and executing function on forEach.

the structure

```<code>var AppView = Backbone.View.extend({
  initialize: function() {
    this.render();
  },
  render: function() {
    this.$el.html("Hello World");
    this.one();
  },
  one: function() {
    this.two();
  },
  two: function() {
    var object = {
      "labname4": "423",
      "Path": "4",
      "X": "4"
    };
    console.log('two');

    Object.keys(object).map(function(objectKey, index) {
      var value = object[objectKey];
      this.three();
    });
  },
  three: function() {
    console.log('three');
  },
});

var appView = new AppView();
console.log("done");
</code>```

Using:

jquery/1.7.2

underscore.js/1.3.3

backbone.js/0.9.2

答:
Because you change the scope when you call Object.keys(object).map this will change too so you can't access the original value by using it. Aliasing it to that allows you still to access the original value of this. Your code will loook like this.

```<code>var AppView = Backbone.View.extend({

  initialize: function(){
    this.render();
  },
  render: function(){
    this.$el.html("Hello World");
    this.one();
  },

  one: function(){
  this.two();
  },
  two: function(){
  var that = this;
  var object = { "labname4": "423",
                "Path": "4",
                "X": "4"};
    console.log('two');

    Object.keys(object).map(function(objectKey, index) {
        var value = object[objectKey];
        that.three();
    });

  },
  three: function(){
    console.log('three');
  },
});
var appView = new AppView();
console.log("done");
</code>```

Edit 1 var that = this vs bind

To me, it seems that .bind definitely has it's place. For instance when you have a function in a variable and you want to attach it to a particular this.

That said, in the case of nested anonymous functions I think that using var that = this; is straightforward and requires less mental accounting vs. using .bind. For example, say we have two nested functions:

```<code>function foo() {
  return (function() {
    doSomething((function() {
      return this.name; // what is `this` again?
    }).bind(this));
  }).bind(this);
}
</code>```

vs

```<code>function foo() {
  var that = this;
  return (function() {
    doSomething((function() {
      return that.name; // `that` is easy to know because its defined
    })
  })
}
</code>```

Of course, because this is a matter of style the issue of "mental accounting" will differ from person to person. But to me, given the semtanics of Javascript's this, I think that that = this is easy to comprehend when you have nested callbacks.

Title: backbonejs function is is not defined

Body:
I am encountering a function is not defined .

I getting key value pairs and executing function on forEach.

the structure

var AppView = Backbone.View.extend({
  initialize: function() {
    this.render();
  },
  render: function() {
    this.$el.html("Hello World");
    this.one();
  },
  one: function() {
    this.two();
  },
  two: function() {
    var object = {
      "labname4": "423",
      "Path": "4",
      "X": "4"
    };
    console.log('two');

    Object.keys(object).map(function(objectKey, index) {
      var value = object[objectKey];
      this.three();
    });
  },
  three: function() {
    console.log('three');
  },
});

var appView = new AppView();
console.log("done");

Using:

jquery/1.7.2

underscore.js/1.3.3

backbone.js/0.9.2

Body:
Because you change the scope when you call Object.keys(object).map this will change too so you can't access the original value by using it. Aliasing it to that allows you still to access the original value of this. Your code will loook like this.

var AppView = Backbone.View.extend({

  initialize: function(){
    this.render();
  },
  render: function(){
    this.$el.html("Hello World");
    this.one();
  },

  one: function(){
  this.two();
  },
  two: function(){
  var that = this;
  var object = { "labname4": "423",
                "Path": "4",
                "X": "4"};
    console.log('two');

    Object.keys(object).map(function(objectKey, index) {
        var value = object[objectKey];
        that.three();
    });

  },
  three: function(){
    console.log('three');
  },
});
var appView = new AppView();
console.log("done");

Edit 1 var that = this vs bind

To me, it seems that .bind definitely has it's place. For instance when you have a function in a variable and you want to attach it to a particular this.

That said, in the case of nested anonymous functions I think that using var that = this; is straightforward and requires less mental accounting vs. using .bind. For example, say we have two nested functions:

function foo() {
  return (function() {
    doSomething((function() {
      return this.name; // what is `this` again?
    }).bind(this));
  }).bind(this);
}

vs

function foo() {
  var that = this;
  return (function() {
    doSomething((function() {
      return that.name; // `that` is easy to know because its defined
    })
  })
}

Of course, because this is a matter of style the issue of "mental accounting" will differ from person to person. But to me, given the semtanics of Javascript's this, I think that that = this is easy to comprehend when you have nested callbacks.


问:
Camel and Elasticsearch with shield plugin
How one can use Camel with Elasticsearch endpoint but with added shield plugin?

How to specify endpoint URI?

How to parametrize user and password?

Documentation states nothing about, how to set user name and password.

There is long explanation about Camel and Elasticsearch  usage but there is nothing about shield plugin.

I am sure that Elasticsearch works with shield, as by using curl I can access DB setting proper username and password.

答:
Authentication with Elasticsearch is supported from camel version 2.20. Please refer the below links.

https://issues.apache.org/jira/browse/CAMEL-115971

https://github.com/apache/camel/blob/master/components/camel-elasticsearch5/src/main/docs/elasticsearch5-component.adoc


问:
Row selectable in ag-grid
As the title, I want to make a row selectable by some conditions with using ag-grid in angularjs.

In the past, I used ui-grid and its property "isRowSelectable" to make it.

```<code>$scope.options = {
    ...
    isRowSelectable:function(row){
    return row.entity.taskExecutionStatus===0?true:false;
  }
}
</code>```

However, the ag-grid doesn't have the property "isRowSelectable" like ui-grid.
How can I fix it now?

答:
To select Single row in ag-grid:</p>

```<code> $scope.Gridoptions:{
    columnDefs:...,

    rowData:...,

      onRowClicked: RowClick,

     rowSelection: 'single',

    };

 function RowClick(param) {

    //To Find CurrentRow Index
    var currentRowIndex = param.rowIndex;

    //GridData

    var gridData = $scope.gridOptionsInstrumentRegister.rowData;

    //Item ShowS RoWData

    var Item = params.data;

    }
</code>```

Title: Row selectable in ag-grid

Body:
As the title, I want to make a row selectable by some conditions with using ag-grid in angularjs.

In the past, I used ui-grid and its property "isRowSelectable" to make it.

$scope.options = {
    ...
    isRowSelectable:function(row){
    return row.entity.taskExecutionStatus===0?true:false;
  }
}

However, the ag-grid doesn't have the property "isRowSelectable" like ui-grid.
How can I fix it now?

Body:
To select Single row in ag-grid:

 $scope.Gridoptions:{
    columnDefs:...,

    rowData:...,

      onRowClicked: RowClick,

     rowSelection: 'single',

    };

 function RowClick(param) {

    //To Find CurrentRow Index
    var currentRowIndex = param.rowIndex;

    //GridData

    var gridData = $scope.gridOptionsInstrumentRegister.rowData;

    //Item ShowS RoWData

    var Item = params.data;

    }


问:
How to query 2 seperate things within the same SQL query
I would like to return the values of both Metric 447 and 615 however because the 447 will return in the QSA.NumValue and the 615 will return in the QSA.DateTimeValue. I need it return when they are populated so if it is 615 then don't allow DateTimeValue to be NULL and if 447 then don't allow NumValue to be NULL because a simple OR statement will not work when included in the WHERE statement.

Is this possible?

```<code>  SELECT
  Q.ID
  ,Q.Title
  ,QS.ID
  ,QSA.QMID
  ,QSA.NumValue
  ,QSA.DateTimeValue
  ,QM.MetricID
  ,S.Date
FROM
  QSA
  INNER JOIN QM
    ON QSA.QMID = QM.ID
  INNER JOIN QS
    ON QSA.SessionID = QS.ID
  INNER JOIN Q
    ON QS.ID = Q.ID
  INNER JOIN SQ
    ON Q.ID = SQ.ID
  INNER JOIN S
    ON SQ.ID = S.ID
WHERE
  QM.MetricID IN (447, 615)
  AND QSA.DateTimeValue IS NOT NULL
</code>```

Thank you in advance.

答:
You can use the following WHERE:

```<code>WHERE
  (QM.MetricID = 447 AND QSA.NumValue IS NOT NULL)
  OR (QM.MetricID = 615 AND QSA.DateTimeValue IS NOT NULL)
</code>```

Body:
I would like to return the values of both Metric 447 and 615 however because the 447 will return in the QSA.NumValue and the 615 will return in the QSA.DateTimeValue. I need it return when they are populated so if it is 615 then don't allow DateTimeValue to be NULL and if 447 then don't allow NumValue to be NULL because a simple OR statement will not work when included in the WHERE statement.

Is this possible?

  SELECT
  Q.ID
  ,Q.Title
  ,QS.ID
  ,QSA.QMID
  ,QSA.NumValue
  ,QSA.DateTimeValue
  ,QM.MetricID
  ,S.Date
FROM
  QSA
  INNER JOIN QM
    ON QSA.QMID = QM.ID
  INNER JOIN QS
    ON QSA.SessionID = QS.ID
  INNER JOIN Q
    ON QS.ID = Q.ID
  INNER JOIN SQ
    ON Q.ID = SQ.ID
  INNER JOIN S
    ON SQ.ID = S.ID
WHERE
  QM.MetricID IN (447, 615)
  AND QSA.DateTimeValue IS NOT NULL

Thank you in advance.

Body:
You can use the following WHERE:

WHERE
  (QM.MetricID = 447 AND QSA.NumValue IS NOT NULL)
  OR (QM.MetricID = 615 AND QSA.DateTimeValue IS NOT NULL)


问:
Escape double quote in velocity
I'm using velocity 1.7 and the template is below.

```<code>var jsCode = "${code}";
eval(jsCode);
</code>```

if code is "var id = 123", then the actual js code is

```<code>var jsCode = "var id = 123";
eval(jsCode);
</code>```

there is no problem.

However, if the code is "var name = "lucy"", then the actual js code is

```<code>var jsCode = "var name = "lucy"";
eval(jsCode);
</code>```

obviously there is syntax error.

And if the code is var jsonStr = "{\"id\":1, \"name\":\"lucy\"}", the the problem is more serious.

The code is unknown, it can be anything.

How to solve this problem?

答:
Velocity developed also EscapeTool inside velocity-tools project which escape with different options

Tool for working with escaping in Velocity templates. It provides methods to escape outputs for Velocity, Java, JavaScript, HTML, HTTP, XML and SQL

In your case it's javascript so use $esc.javascript( example:

$javascript                  -> He didn't say, "Stop!"

$esc.javascript($javascript) -> He didn\'t say, \"Stop!\"

Title: Escape double quote in velocity

Body:
I'm using velocity 1.7 and the template is below.

var jsCode = "${code}";
eval(jsCode);

if code is "var id = 123", then the actual js code is

var jsCode = "var id = 123";
eval(jsCode);

there is no problem.

However, if the code is "var name = "lucy"", then the actual js code is

var jsCode = "var name = "lucy"";
eval(jsCode);

obviously there is syntax error.

And if the code is var jsonStr = "{\"id\":1, \"name\":\"lucy\"}", the the problem is more serious.

The code is unknown, it can be anything.

How to solve this problem?


问:
App has conflicting provisioning settings in Build Settings
I have generated a certificate and created a provisioning profile for my project so that I could make push notification in it, but when in Build Setting -> CodeSigning I write the name of provisioning profile and give my team name in General an error appears that AppName has conflicting provisioning settings.

How can I correct this?

The error looks like this

答:
Just uncheck Automatically manage signing and check it again and select appropriate team.

Xcode will automatically fix the causing issue on its own.


问:
unable to get component variable value in angular 2 in frontend
Am unable to display mapLoc value in front end... any help?

Here is my component.ts file

```<code>export class mycomponent{

 mapLoc:any;

 constructor(){...}

openImageModal(lat,lng){
 this.mapLoc = '';
 var latlng = new google.maps.LatLng(lat, lng);
        var geocoder = geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        console.log(results[1].formatted_address); //able to console
                        this.mapLoc = results[1].formatted_address;
                    }
                }
            });
}
</code>```

this is mycomponent.html file

```<code><ngui-map zoom="{{zoom}}" center="{{lat}}, {{lng}}" (mapReady$)="onMapReady($event,lat,lng)" (mapClick)="onMapClick($event)" (idle)="onIdle($event)">
                <marker *ngFor="let pos of position" [position]="[pos.lat, pos.lng]" draggable="true" (initialized$)="onMarkerInit($event)"></marker>
                    <info-window id="iw">
                        <div *ngIf="marker.display">
                        {{mapLoc}}
                        </div>
                    </info-window>
            </ngui-map>
</code>```

答:
That is very common issue of scoping :

Just change :

```<code>geocoder.geocode({ 'latLng': latlng }, function (results, status) {
</code>```

to

```<code>geocoder.geocode({ 'latLng': latlng }, (results, status) => {
</code>```

OR

```<code>geocoder.geocode({ 'latLng': latlng }, function (results, status) { ... }).bind(this)
</code>```

For More Detail Ref : https://stackoverflow.com/a/47278161/2349407

Body:
Am unable to display mapLoc value in front end... any help?

Here is my component.ts file

export class mycomponent{

 mapLoc:any;

 constructor(){...}

openImageModal(lat,lng){
 this.mapLoc = '';
 var latlng = new google.maps.LatLng(lat, lng);
        var geocoder = geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        console.log(results[1].formatted_address); //able to console
                        this.mapLoc = results[1].formatted_address;
                    }
                }
            });
}

this is mycomponent.html file

<ngui-map zoom="{{zoom}}" center="{{lat}}, {{lng}}" (mapReady$)="onMapReady($event,lat,lng)" (mapClick)="onMapClick($event)" (idle)="onIdle($event)">
                <marker *ngFor="let pos of position" [position]="[pos.lat, pos.lng]" draggable="true" (initialized$)="onMarkerInit($event)"></marker>
                    <info-window id="iw">

                        {{mapLoc}}

                    </info-window>
            </ngui-map>

Body:
That is very common issue of scoping :

Just change :

geocoder.geocode({ 'latLng': latlng }, function (results, status) {

to

geocoder.geocode({ 'latLng': latlng }, (results, status) => {

OR

geocoder.geocode({ 'latLng': latlng }, function (results, status) { ... }).bind(this)

For More Detail Ref : https://stackoverflow.com/a/47278161/2349407


问:
static variables in c
Static variables when declared in a file cannot be accessed from outside the file.
But if we declare a static variable inside a file and a global pointer and then assign the address of the static variable to the pointer and then externing the pointer, it can be accessed.

So is it right saying that static variables can't be accessed directly but it can be accessed indirectly using global pointers and then externing?

答: Anything within a process can be accessed if you have a pointer to it, barring architecture-specific mechanisms for restricting access.Redundantly saying that a variable can be accessed via a pointer is redundant.</p>

OwnerDisplayName: maddy

Title: static variables in c

OwnerDisplayName: Ignacio Vazquez-Abrams