问:
Using Google account to log in to an Android Application
I’m developing an application on Android and I want to allow users to log in with their Google account. How can I achieve this?</p>

答:
```<code>    **Dependency**
    **Need Internet Permission**

**Working Code   see Link on  play Store**
https://play.google.com/store/search?q=com.codecube.airbucks

    compile 'com.google.android.gms:play-services:8.3.0'

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <com.google.android.gms.common.SignInButton
            android:id="@+id/sign_in_button"
            android:layout_width="200dp"
            android:layout_marginTop="20dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal" />
        <Button
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_gravity="center_horizontal"
            android:text="Logout"
            android:id="@+id/btn"/>
    </LinearLayout>

    package com.keshav.geofencing;

    import android.Manifest;
    import android.annotation.TargetApi;
    import android.app.ProgressDialog;
    import android.content.BroadcastReceiver;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Bundle;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.support.v4.content.LocalBroadcastManager;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.LinearLayout;
    import android.widget.TextView;

    import com.facebook.CallbackManager;
    import com.facebook.FacebookCallback;
    import com.facebook.FacebookException;
    import com.facebook.FacebookSdk;
    import com.facebook.GraphRequest;
    import com.facebook.GraphResponse;
    import com.facebook.login.LoginManager;
    import com.facebook.login.LoginResult;
    import com.google.android.gms.appindexing.Action;
    import com.google.android.gms.appindexing.AppIndex;
    import com.google.android.gms.auth.api.Auth;
    import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
    import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
    import com.google.android.gms.auth.api.signin.GoogleSignInResult;
    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.GoogleApiAvailability;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.common.api.OptionalPendingResult;
    import com.google.android.gms.common.api.ResultCallback;
    import com.google.android.gms.common.api.Status;

    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.Arrays;

    import utilities.CommonMethod;
    import utilities.LoginPreferences;

    public class LoginWithGmail extends AppCompatActivity
            implements GoogleApiClient.OnConnectionFailedListener {

        private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
        private static final String TAG = "LoginActivity";
        private static final int RC_SIGN_IN = 9001;
        Button loginSub;
        LinearLayout signInButton;

        String gmailId;
        String gmailName;
        String gmailUserEmailId;
        Uri gmailUserPhoto;
        String savePassword;
        LinearLayout btnlogin;
        TextView btnsigning;
        ProgressDialog prgDialog;

        private CallbackManager callbackManager;

        private BroadcastReceiver mRegistrationBroadcastReceiver;
        private LinearLayout fbloginButton;
    //    private CallbackManager callbackManager;
        private ProgressDialog mProgressDialog;
        private GoogleApiClient mGoogleApiClient;

        EditText edtEmail;

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

            checkPermission();

            GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

            mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .addApi(AppIndex.API).build();

            // Google Sign up Button
            signInButton = (LinearLayout) findViewById(R.id.sign_in_button);

            signInButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        int permissionCheck = ContextCompat.checkSelfPermission(LoginWithGmail.this, Manifest.permission.CAMERA);
                        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                            //showing dialog to select image

                            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                            signInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivityForResult(signInIntent, RC_SIGN_IN);
                            Log.e("permission", "granted");
                        } else {
                            ActivityCompat.requestPermissions(LoginWithGmail.this,
                                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
                        }
                    } else {
                        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                        signInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivityForResult(signInIntent, RC_SIGN_IN);
                    }

                }
            });

        }

        public void checkPermission() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                int permissionCheck = ContextCompat.checkSelfPermission(LoginWithGmail.this,
                        Manifest.permission.CAMERA);

                if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                    //showing dialog to select image
                    if (CommonMethod.isNetworkAvailable(LoginWithGmail.this)) {
                        Log.e("keshav", "Permission if part marsh");
                    } else {
                        CommonMethod.showAlert("Internet Connectivity Failure", LoginWithGmail.this);
                    }

                    Log.e("keshav", "permission granted");
                } else {
                    ActivityCompat.requestPermissions(LoginWithGmail.this,
                            new String[]{Manifest.permission.CAMERA,
                                    Manifest.permission.ACCESS_FINE_LOCATION,
                                    Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
                }
            }
        }

        @Override
        protected void onResume() {
            super.onResume();
    //        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
    //                new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
        }

        @Override
        protected void onPause() {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
            super.onPause();
        }

        @Override
        public void onBackPressed() {
            super.onBackPressed();

        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

            if (requestCode == RC_SIGN_IN) {
                GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                handleSignInResult(result);
            }
        }

        // TODO ADD ME

        @Override
        public void onStart() {
            super.onStart();

            OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
            if (opr.isDone()) {
                // If the user's cached credentials are valid, the OptionalPendingResult will be "done"
                // and the GoogleSignInResult will be available instantly.
                Log.e(TAG, "Got cached sign-in");
                GoogleSignInResult result = opr.get();
                handleSignInResult(result);
            } else {
                // If the user has not previously signed in on this device or the sign-in has expired,
                // this asynchronous branch will attempt to sign in the user silently.  Cross-device
                // single sign-on will occur in this branch.
                showProgressDialog();
                opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                    @Override
                    public void onResult(GoogleSignInResult googleSignInResult) {
                        hideProgressDialog();
                        handleSignInResult(googleSignInResult);
                    }
                });
            }
        }

        // [START signOut]
        private void signOut() {
            Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                    new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status status) {
                            // [START_EXCLUDE]
    //                        updateUI(false);
                            // [END_EXCLUDE]
                        }
                    });
        }
        // [END signOut]

        // [START revokeAccess]
        private void revokeAccess() {
            Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                    new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status status) {
                            // [START_EXCLUDE]
    //                        updateUI(false);
                            // [END_EXCLUDE]
                        }
                    });
        }
        // [END revokeAccess]

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            // An unresolvable error has occurred and Google APIs (including Sign-In) will not
            // be available.
            Log.e(TAG, "onConnectionFailed:" + connectionResult);
        }

        private void showProgressDialog() {
            if (mProgressDialog == null) {
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Loading...");
                mProgressDialog.setIndeterminate(true);
            }
            if (LoginWithGmail.this != null && mProgressDialog != null && !mProgressDialog.equals("null"))
                mProgressDialog.show();
        }

        private void hideProgressDialog() {
            if (mProgressDialog != null && mProgressDialog.isShowing()&& !mProgressDialog.equals("null")) {
                mProgressDialog.hide();
            }
        }

        // TODO ADD ME ENd

        private void handleSignInResult(GoogleSignInResult result) {
            Log.e("&&&s", "handleSignInResult:" + result.isSuccess());
            if (result.isSuccess()) {
                // Signed in successfully, show authenticated UI.
                GoogleSignInAccount acct = result.getSignInAccount();

                gmailId = acct.getId();
                gmailName = acct.getDisplayName();
                gmailUserEmailId = acct.getEmail();
                gmailUserPhoto = acct.getPhotoUrl();

                Log.e("gmailId", "is -->" + gmailId);
                Log.e("gmailName", "is -->" + gmailName);
                Log.e("gmailUserEmailId", "is -->" + gmailUserEmailId);
                Log.e("gmailUserPhoto", "is -->" + gmailUserPhoto);

                LoginPreferences.getActiveInstance(LoginWithGmail.this).setUserName(gmailName);
                LoginPreferences.getActiveInstance(LoginWithGmail.this).setProfileImage(""+gmailUserPhoto);

                Log.e("information", "using Gmail is > " + gmailId + " " + gmailName + "" + gmailUserEmailId + "" + gmailUserPhoto);

                if (CommonMethod.isNetworkAvailable(LoginWithGmail.this)) {
                    Log.e("SignUp gmail", "Hit API..........................");
                    Intent i=new Intent(LoginWithGmail.this,DrawerActivity.class);
                    LoginPreferences.getActiveInstance(LoginWithGmail.this).setIsLoggedIn(true);
                    startActivity(i);
                    finish();

                    // TODO Here Registered User in own Database call Volley Retrofit2 Api ....
                    new SignUpSocialFacebookAsyncTask().execute();
                } else {
                    CommonMethod.showAlert("Intenet Connectivity Failure", LoginWithGmail.this);
                }

            } else {

            }
            // TODO ADD ME KESHAV Google GMail Logout
            Auth.GoogleSignInApi.signOut(mGoogleApiClient);
        }

        @Override
        public void onStop() {
            super.onStop();

            // ATTENTION: This was auto-generated to implement the App Indexing API.
            // See https://g.co/AppIndexing/AndroidStudio for more information.
            Action viewAction = Action.newAction(
                    Action.TYPE_VIEW, // TODO: choose an action type.
                    "Login Page", // TODO: Define a title for the content shown.
                    // TODO: If you have web page content that matches this app activity's content,
                    // make sure this auto-generated web page URL is correct.
                    // Otherwise, set the URL to null.
                    Uri.parse("http://host/path"),
                    // TODO: Make sure this auto-generated app deep link URI is correct.
                    Uri.parse("android-app://com.keshav.geofencing/http/host/path")
            );
            AppIndex.AppIndexApi.end(mGoogleApiClient, viewAction);
            mGoogleApiClient.disconnect();
        }

        //Todo  add new method for permission
        @TargetApi(Build.VERSION_CODES.M)
        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            if (requestCode == RC_SIGN_IN) {
                Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                signInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivityForResult(signInIntent, RC_SIGN_IN);

            }
        }

    }

    **Dependency**
    **Need Internet Permission**

**Working Code   see Link on  play Store**
https://play.google.com/store/search?q=com.codecube.airbucks
</code>```


来源: stackexchange

问:
Addressing instance name string in __init__(self) in Python
I am doing something like this:

```<code>class Class(object):
    def __init__(self):
        self.var=#new instance name string#
</code>```

How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:

```<code>c=Class()
</code>```

I want c.var equal to 'c'.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

```<code>c=Class()
</code>```

Then, suppose:

```<code>del c
</code>```

Later on:

```<code>c=Class()
</code>```

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

```<code>c=Class()
</code>```

Then, suppose:

```<code>del c
</code>```

Later on:

```<code>c=Class()
</code>```

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

答:
You can't (short of incredible hacks like examining the stack frame and inspecting the bytecode).  There may not even be a name, or there could be multiple such names.  What should be given for the following code fragments for instance:

```<code>l = [Class(), Class()]
a=b=c=d=Class()
</code>```

OwnerDisplayName: xktybot

ContentLicense: CC BY-SA 3.0

Body:
I am doing something like this:

class Class(object):
    def __init__(self):
        self.var=#new instance name string#

How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:

c=Class()

I want c.var equal to 'c'.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

c=Class()

Then, suppose:

del c

Later on:

c=Class()

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

c=Class()

Then, suppose:

del c

Later on:

c=Class()

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

LastEditorDisplayName: xktybot

Body:
You can't (short of incredible hacks like examining the stack frame and inspecting the bytecode).  There may not even be a name, or there could be multiple such names.  What should be given for the following code fragments for instance:

l = [Class(), Class()]
a=b=c=d=Class()

OwnerDisplayName: Brian

ContentLicense: CC BY-SA 2.5


问:
Restricting only few actions in zf2 using bjyauthorize
Consider that in a controller we have 10 actions in that 8 actions can be accessed by anyone but remaining two actions should be accessed by particular user roles.

This I tried using by setting Guard\Controller, but using this 10 actions are accessible to all users or 2 restricted actions are able to access particular user roles still I'm not getting how to configure as per my requirement.

答:
In Zend Framework there are Event Listener and ACL. You should create ACL for each action and after it catch ROUTE event. Here is the documatation of ACL.

In this URL is step by step tutorial:
Zend Framework 2 ACL setup in 5 minutes – tutorial


问:
How do I store a floating point number in Android resource file
I am using font size percentage 0.96f which is floating point. On different devices I might want higher font size percent. How do I store this as a resource? I suppose I could store as 95 and divide by 100 but anyway how do you store floating point numbers in resource file which might give different value depending on device resolution/size etc. just like for layout files. If you are curious about the percent its because I am reducing the size of the font by 4% to fit a TextView onto my view. Soon there will be in Android O a new TextView to do the scaling but not now.

Thanks

答:
To get different integer based on device resolution from resource, you have to add Different values folder for different screens in res directory. For ex:
- values
- values-small
- values-large
- values-sw600dp

Add dimens.xml in every values folder and add dimensions according to resolution.

16dp


问:
Reaching a control, within a ContentControl from view's code behind
My view's XAML is only containing a custom control.

A bit further, in a Resource Dictionary, I have a Style for this custom control, and inside this, I have a TextBox. My goal would be to reach this TextBox from the view's code behind, and set it's focus, when the view's DataContext changed.

I tried to use x:Name to give a name to the custom control on the view's XAML, and also give a name to the TextBox inside the control's style (so essentially trying to reach it from code behind like: this.MyCustomControl.SearchTextBox). This did not work.

What would be the best practice to solve this issue?

答:
This is what I would do.

Create a TemplatePart attribute on top of your custom control for the TextBox.

[TemplatePart(Name = "YourTextBoxName", Type = typeof(TextBox))]

Then inside the OnApplyTemplate override method, get a reference of the TextBox.

```<code>// You might want to add property error handling here
// so if the TextBox is not found, throw an exception.
// Doing so forces other people will have to implement
// the SAME PART in their own stylings.
_textBox = (TextBox)GetTemplateChild("YourTextBoxName");
</code>```

Then all you need is to create a public method SetFocus that your code behind class can have access to.

public void SetFocus() => _textBox.Focus(FocusState.Programmatic);

Body:
This is what I would do.

Create a TemplatePart attribute on top of your custom control for the TextBox.

[TemplatePart(Name = "YourTextBoxName", Type = typeof(TextBox))]

Then inside the OnApplyTemplate override method, get a reference of the TextBox.

// You might want to add property error handling here
// so if the TextBox is not found, throw an exception.
// Doing so forces other people will have to implement
// the SAME PART in their own stylings.
_textBox = (TextBox)GetTemplateChild("YourTextBoxName");

Then all you need is to create a public method SetFocus that your code behind class can have access to.

public void SetFocus() => _textBox.Focus(FocusState.Programmatic);


问:
Flex 4 - Using MXML as views - Any references?
I'm looking to create a flashBuilder document which uses seperate MXML files as "views" which are controlled by states - I believe it's a design pattern of sorts but I'm relatively new to FlashBuilder. I was wondering if anyone knew what design pattern it was and if I can be pointed in the direction of some good references!

FYI I'm looking into using FlashBuilder to design Android apps so any better suggestions would be much appreciated.

Cheers

答:
You can do that the way you want. Just consider such file (MXML) as object. It can be easily added to some outer component, ie. UIComponent. You should read something about it but I bet it's quite simple. Just remember - MXML is just a language that describes an object - you could do that using AS 3.0 instead but it's obviously more convenient to use MXML. Considering this fact all the MXML files are compiled before they run so you can easily manipulate them.

Just try to add such object to some outer component like UIComponent - you can read a few words about it here: HTML in Flex. Just take a look at the function createWindow

Good luck!


问:
How to make Doc2Vec document vectors all positive?
I'm trying to use nonnegative matrix factorization on the output of Doc2Vec. However there is a constraint that there can be no negative input. How do I make it positive without doing something like absolute value that will construe the results? If it helps, I'm loading in a new paragraph and computing similarity but I thought that using Doc2Vec would capture more meaning.</p>

答: You can normalize all the values, to be between 0 and 1, for instance, if you have a vector X, you can obtain a normalized version Z:


问:
ngIf in angular 2 not working
```<code><div *ngFor="let message of messages">
  <div *ngIf="message.user===user">

  </div>

 <input [(ngModel)]="message"  />
<button (click)="sendMessage()">Send</button>
</code>```

Here user is the variable that I have assigned in the component. That is a string value 'user1'. If message.user === user1 then I need to show something but its not working.

答: Sorry guys that error was just because i missed out closing one div thanks for your responses</p>

Title: ngIf in angular 2 not working

Body:
 <input [(ngModel)]="message"  />
<button (click)="sendMessage()">Send</button>

Here user is the variable that I have assigned in the component. That is a string value 'user1'. If message.user === user1 then I need to show something but its not working.


问:
What does UserA committed with UserB 13 days ago on github mean?
I am interested in knowing which one of the two users made the file changes when github lists both. The git record contains only UserA however.</p>

答:
Another one of possible reasons behind this happening is by using $GIT_AUTHOR_NAME and $GIT_AUTHOR_EMAIL env variables.

When these variables are set, they override the author part of every onward commit no matter what user.name and user.email config values are set locally. In this case, when you hit git cat-file -p HEAD, author shows value of $GIT_AUTHOR_NAME and committer shows value of local user.name configuration.

So you'll need to remove lines that export these variables in .bashrc or .zshrc, or if you want to preserve those lines but just don't want this thing happen, insert unset GIT_AUTHOR_NAME && unset GIT_AUTHOR_EMAIL before running git commit.


问:
neural talk2 error : can not open eval.lua
I am getting the following output on trying to run neuraltalk2

What is going wrong here?  Do I need to run this code in Torch?

答: The path of eval.lua cannot be found,so I add the path as follows:enter image description here</p>


问:
Not able to display select box as ajax response in wordpress
I have two drop-down box one with custom taxonomy and other with it custom post under the current selected taxonomy. For that i have wrote an on-change function. i have some problem with displaying out put
it's showing output like this

```<code>8Associate<select class="form-control" name="upload_designation" id="upload_designation" >

<option value="">Select Designation</option><option value=""></option></select>
</code>```

instead of

```<code><select class="form-control" name="upload_designation" id="upload_designation" >

<option value="">Select Designation</option>
<option value="8">Associate</option></select>
</code>```

i am posting my on change function here
kindly help me to figure out the problem

```<code>function change_desgination() {
$post_val=explode("_",$_POST['id']);
$id=$post_val[0];
$taxonomy_name=$post_val[1];

$out='<select class="form-control" name="upload_designation" id="upload_designation" >
<option value="">Select Designation</option>';

    $args = array(
    'post_type' => 'designation',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'domain',
            'field' => 'slug',
            'terms' => $taxonomy_name
        )
    )
);
$the_query = new WP_Query( $args );

while ( $the_query->have_posts() ) : $the_query->the_post();
$theid=the_ID();
$thetitle=the_title();

  $out.='<option value="'.$theid.'">'.$thetitle.'</option>';

endwhile;
  $out.='</select>';
  die($out);
 }
</code>```

may be the problem is with the quotes. Any one please help me to find the the problem. Thanks in advance.

答:
The problem was with

```<code>$theid=the_ID();
$thetitle=the_title();
</code>```

the_ID() and the_title() will echo the values
where as  get_the_ID(); and get_the_title(); will return the values as string.
so i used

```<code>$theid=get_the_ID();
$thetitle=get_the_title();
</code>```

refer the links

https://wordpress.stackexchange.com/questions/48523/get-title-of-post-without-using-the-title

And

https://developer.wordpress.org/reference/functions/get_the_id/

Body:
I have two drop-down box one with custom taxonomy and other with it custom post under the current selected taxonomy. For that i have wrote an on-change function. i have some problem with displaying out put
it's showing output like this

8Associate<select class="form-control" name="upload_designation" id="upload_designation" >

<option value="">Select Designation</option><option value=""></option></select>

instead of

<select class="form-control" name="upload_designation" id="upload_designation" >

<option value="">Select Designation</option>
<option value="8">Associate</option></select>

i am posting my on change function here
kindly help me to figure out the problem

function change_desgination() {
$post_val=explode("_",$_POST['id']);
$id=$post_val[0];
$taxonomy_name=$post_val[1];

$out='<select class="form-control" name="upload_designation" id="upload_designation" >
<option value="">Select Designation</option>';

    $args = array(
    'post_type' => 'designation',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'domain',
            'field' => 'slug',
            'terms' => $taxonomy_name
        )
    )
);
$the_query = new WP_Query( $args );

while ( $the_query->have_posts() ) : $the_query->the_post();
$theid=the_ID();
$thetitle=the_title();

  $out.='<option value="'.$theid.'">'.$thetitle.'</option>';

endwhile;
  $out.='</select>';
  die($out);
 }

may be the problem is with the quotes. Any one please help me to find the the problem. Thanks in advance.

Body:
The problem was with

$theid=the_ID();
$thetitle=the_title();

the_ID() and the_title() will echo the values
where as  get_the_ID(); and get_the_title(); will return the values as string.
so i used

$theid=get_the_ID();
$thetitle=get_the_title();

refer the links

https://wordpress.stackexchange.com/questions/48523/get-title-of-post-without-using-the-title

And

https://developer.wordpress.org/reference/functions/get_the_id/


问:
How do you use srgbClr in openpyxl ColorChoices
How can I use colors that are not represented by the colornames like RGB.
Sorry, I don't understand the documents but there are no examples. Here is my code:</p>

```<code>series4Total = chart1.series[3]
fill4Total =  PatternFillProperties(prst="pct5")
fill4Total.foreground = ColorChoice(srgbClr='30,144,255') # dodgerBlue: R:30 G: 144 B: 255
fill4Total.background = ColorChoice(srgbClr='30,144,255')
series4Total.graphicalProperties.pattFill = fill4Total
</code>```

答:
Strictly srgbClr has this definition but I tried to simplify the API a bit where possible. </p>

<p>

</p>

Body:
How can I use colors that are not represented by the colornames like RGB.
Sorry, I don't understand the documents but there are no examples. Here is my code:

series4Total = chart1.series[3]
fill4Total =  PatternFillProperties(prst="pct5")
fill4Total.foreground = ColorChoice(srgbClr='30,144,255') # dodgerBlue: R:30 G: 144 B: 255
fill4Total.background = ColorChoice(srgbClr='30,144,255')
series4Total.graphicalProperties.pattFill = fill4Total


问:
How are 3D games so efficient?
There is something I have never understood. How can a great big PC game like GTA IV use 50% of my CPU and run at 60fps while a DX demo of a rotating Teapot @ 60fps uses a whopping 30% ? </p>

答:
How can a great big PC game like GTA IV use 50% of my CPU and run at 60fps while a DX demo of a rotating Teapot @ 60fps uses a whopping 30% ?

While GTA is quite likely to be more efficient than DX demo, measuring CPU efficiency this way is essentially broken. Efficiency could be defined e.g. by how much work you do per given time. A simple counterexample: spawn one thread per a logical CPU and let a simple infinite loop run on it. You will get CPU usage of 100 %, but it is not efficient, as no useful work is done.

This also leads to an answer: how can a game be efficient? When programming "great big games", a huge effort is dedicated to optimize the game in all aspects (which nowadays usually also includes multi-core optimizations). As for the DX demo, its point is not running fast, but rather demonstrating concepts.

Title: How are 3D games so efficient?


问:
BadMethodCallException in Macroable.php line 74: Method specialization does not exist
I am getting this small issue. Below is the source code

Doctor Model:

```<code>class Doctor extends Model {
......
....
     public function specialization() {
        return $this->HasMany('App\Specialization');
    }
}
</code>```

Specialization Model:

```<code>class Specialization extends Model {
......
....
     public function doctor () {
        return $this->belongsTo('App\Doctor', 'id');
     }
}
</code>```

Specialization Model:

Here the spec_id is a foreign key

```<code>class DoctorController extends Controller
{
......
....
 //Create a Doctor
    public function createDoctor(Request $request) {
    $doctor = new Doctor();
    $doctor->doctor_id = $request->input('doctor_id');
    // $doctor->spec_id = $request->input('spec_id');
    $doctor->spec_id = $request->specialization()->id;
    $doctor->dob = $request->input('dob');
    $doctor->age = $request->input('age');
    $doctor->gender = $request->input('gender');
    $doctor->qualification = $request->input('qualification');
    $doctor->experience = $request->input('experience');
    $doctor->phone_number = $request->input('phone_number');
    // $doctor->email = $request->user()->email;
    $doctor->email = $request->input('email');
    // $doctor->user_id = $request->user()->user_id;
    $doctor->user_id = $request->input('user_id');
    $doctor->save();
    return response()->json(['doctor' => $doctor], 201);
    }
}
</code>```

Please let me know how do I fix it.

答:
The error is most probably from ... = $request->specialization()->id; where the specialization() method doesn't exist. The error message also mentions Macroable, which makes me believe that you are type-hinting the Request facade in the method signature, not the correct Illuminate\Http\Request type.

Check your use-statements at the top of the file.

Body:
I am getting this small issue. Below is the source code

Doctor Model:

class Doctor extends Model {
......
....
     public function specialization() {
        return $this->HasMany('App\Specialization');
    }
}

Specialization Model:

class Specialization extends Model {
......
....
     public function doctor () {
        return $this->belongsTo('App\Doctor', 'id');
     }
}

Specialization Model:

Here the spec_id is a foreign key

class DoctorController extends Controller
{
......
....
 //Create a Doctor
    public function createDoctor(Request $request) {
    $doctor = new Doctor();
    $doctor->doctor_id = $request->input('doctor_id');
    // $doctor->spec_id = $request->input('spec_id');
    $doctor->spec_id = $request->specialization()->id;
    $doctor->dob = $request->input('dob');
    $doctor->age = $request->input('age');
    $doctor->gender = $request->input('gender');
    $doctor->qualification = $request->input('qualification');
    $doctor->experience = $request->input('experience');
    $doctor->phone_number = $request->input('phone_number');
    // $doctor->email = $request->user()->email;
    $doctor->email = $request->input('email');
    // $doctor->user_id = $request->user()->user_id;
    $doctor->user_id = $request->input('user_id');
    $doctor->save();
    return response()->json(['doctor' => $doctor], 201);
    }
}

Please let me know how do I fix it.


问:
check duplicate rand function value in database and generate it again
i create rand funtion for generating random value and concatenate with other value and show in the text field through ajax before insert this value. but here how can i check this random generating value is exists or not in database before inserting this value in database.if value is exists then again generate rand function value and again concatenate this and show the value in textbox. how can i do this? my code is below
    index.php</p>

```<code>    <html>
<head>
    <title>Untitled Document</title>
    <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
    </script>
    <script>
    $( document ).ready(function() {});
    function my_validate_func() {
    var name = $('#name').val();
    var year = $('#year').val();
    var course = $('#course').val();
    var branch_name = $('#branch_name').val();
        if ($('#name').val() != "" && $('#year').val() != "" &&
            $('#course').val() != "" && $('#branch_name').val() != "") {
            $.ajax({
                type: "POST",
                url: 'roll.php',
                data: { name: name, year: year, branch_name: branch_name, course: course },
                success: function(response) {
                    $('#roll').val(response);
                }
            });
        }
    }
</script>
</head>

<body>
    <form method="post" action="">
        <input type="text" name="name" id="name" onChange="my_validate_func()">
        <input type="text" name="phone" id="phone" onChange="my_validate_func()">
        <input type="text" name="course" id="course" onChange="my_validate_func()">
        <input type="text" name="center" id="center" onChange="my_validate_func()">
        <input type="text" name="roll" id="roll" value="">
    </form>
</body>

</html>

roll.php

    <?php
function calculateRoll()
{
    $name1        = $_POST['name'];
    $year1        = $_POST['year'];
    $course1      = $_POST['course'];
    $branch_name1 = $_POST['branch_name'];
    $name2        = substr($name1,0,3);
    $name         = strtoupper($name2);
    $year         = substr($year1,-2);
    $branch_name  = strtoupper(substr($branch_name1,0,3));
    $course2      = substr($course1,0,3);
    $course       = strtoupper($course2);
    $rand         = rand(100000,999999);
    $roll         =$branch_name.$name.$course.$year.$rand;
    //return $roll;
    echo $roll;
}

function isValidRoll($roll) {
    mysql_connect("localhost","root","");
    mysql_select_db("sigma");
    $sql="SELECT count(*) as total FROM student WHERE roll = '$roll'";
    $result = mysql_query($sql);

    $data = mysql_fetch_assoc($result);
    return $data['total'] == 0;
}

$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
    if (isValidRoll($roll)) {
        $validRoll = true;
    } else {
        $roll = calculateRoll();
    }
}
?>
</code>```

答: when ever you save the data of the form store rand function value too means in second time you can retrieve the rand function value and compare with current rand function generating value.  </p>

Body:
i create rand funtion for generating random value and concatenate with other value and show in the text field through ajax before insert this value. but here how can i check this random generating value is exists or not in database before inserting this value in database.if value is exists then again generate rand function value and again concatenate this and show the value in textbox. how can i do this? my code is below
    index.php

    <title>Untitled Document</title>

    <form method="post" action="">
        <input type="text" name="name" id="name" onChange="my_validate_func()">
        <input type="text" name="phone" id="phone" onChange="my_validate_func()">
        <input type="text" name="course" id="course" onChange="my_validate_func()">
        <input type="text" name="center" id="center" onChange="my_validate_func()">
        <input type="text" name="roll" id="roll" value="">
    </form>

roll.php

    <?php
function calculateRoll()
{
    $name1        = $_POST['name'];
    $year1        = $_POST['year'];
    $course1      = $_POST['course'];
    $branch_name1 = $_POST['branch_name'];
    $name2        = substr($name1,0,3);
    $name         = strtoupper($name2);
    $year         = substr($year1,-2);
    $branch_name  = strtoupper(substr($branch_name1,0,3));
    $course2      = substr($course1,0,3);
    $course       = strtoupper($course2);
    $rand         = rand(100000,999999);
    $roll         =$branch_name.$name.$course.$year.$rand;
    //return $roll;
    echo $roll;
}

function isValidRoll($roll) {
    mysql_connect("localhost","root","");
    mysql_select_db("sigma");
    $sql="SELECT count(*) as total FROM student WHERE roll = '$roll'";
    $result = mysql_query($sql);

    $data = mysql_fetch_assoc($result);
    return $data['total'] == 0;
}

$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
    if (isValidRoll($roll)) {
        $validRoll = true;
    } else {
        $roll = calculateRoll();
    }
}
?>


问:
AngularJS file upload with form data using PHP and MySql
I am creating a form which have lots of fields. My concern is I want to upload 10kb jpg file along with other HTML form data.

As per my search I have not seen any post which is explaining AngulaJS file upload along with other data as well. Please help me to do the same. While creating object in Angular controller, I am not able to get fileUpload path. that is why its showing undefine. Code is as under :-

PS - due to lack of time I used table tag.

HTML Code

```<code><div id="wrapper">
<form>
<table>
    <thead>
        <tr>
            <td>Add Record</td>
            <td style="text-align:right"><a href="#/list" style="color:#000;">Back</a></td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Name</td>
            <td><input type="text" value="" id="name" tabindex="1" placeholder="Enter Name" ng-model="person.name" name="name"  /> </td>
        </tr>
        <tr>
            <td>Extn</td>
            <td><input type="text" value="" id="extn" tabindex="2" placeholder="Enter Extn" ng-model="person.extn" name="extn"   /> </td>
        </tr>
        <tr>
            <td>Designation</td>
            <td><input type="text" value="" id="designation" tabindex="3" placeholder="Enter Designation" ng-model="person.designation" name="designation"   /> </td>
        </tr>
        <tr>
            <td>mobile</td>
            <td><input type="text" value="" id="mobile" tabindex="4" placeholder="Enter Mobile" ng-model="person.mobile" name="mobile"   /> </td>
        </tr>
        <tr>
            <td>email</td>
            <td><input type="text" value="" id="email" tabindex="5" placeholder="Enter Email" ng-model="person.email" name="email"   /> </td>
        </tr>
        <tr>
            <td>upload file</td>
            <td><input  type="file" id="uploadFile" name="uploadFile" tabindex="6" ng-mode="person.fileUpload"   /> </td>
        </tr>
        <tr>
            <td></td>
            <td><input type="button" value="Submit" id="submitbtn" tabindex="7" ng-click="save(person)"/> </td>
        </tr>
    </tbody>
</table>
</form>
</code>```

AngularJS

```<code>angular
.module("addressBook",['ngRoute'])
.controller('addController', ['$scope','$location','$rootScope','$http', function(scope,location,rootScope,http){

    scope.save = function (item){
        var personData = {
            'name' : scope.person.name,
            'extn' : scope.person.extn,
            'designation' : scope.person.designation,
            'mobile' : scope.person.mobile,
            'email' : scope.person.email,
            'fileUpload' : scope.person.fileUpload
        };

        if(typeof rootScope.crew === 'undefined'){
            rootScope.crew = [];
        }
        debugger;
        console.log(personData);
        http.post("server/insert.php",personData).success(function(data, status, headers, config){
            scope.person = personData;
            //rootScope.crew.push(scope.person);
            location.path("/admin");
        })

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

PHP Code

```<code><?php
    include 'conn.php';
    $data = json_decode(file_get_contents("php://input"));

    $name = mysql_real_escape_string($data->name);
    $extn = mysql_real_escape_string($data->extn);
    $designation = mysql_real_escape_string($data->designation);
    $mobile = mysql_real_escape_string($data->mobile);
    $email = mysql_real_escape_string($data->email);

    echo $query = "INSERT INTO employee (`name`,`extn`,`designation`,`mobile`,`email`) VALUES ('$name', '$extn', '$designation', '$mobile' , '$email')";
    mysql_query($query);
    Print "Your information has been successfully added to the database.";
?>
</code>```

答:
you can use Lightweight Angular directive to upload files with input fields
https://github.com/danialfarid/ng-file-upload </p>

Body:
I am creating a form which have lots of fields. My concern is I want to upload 10kb jpg file along with other HTML form data.

As per my search I have not seen any post which is explaining AngulaJS file upload along with other data as well. Please help me to do the same. While creating object in Angular controller, I am not able to get fileUpload path. that is why its showing undefine. Code is as under :-

PS - due to lack of time I used table tag.

HTML Code

<form>

            Add Record
            Back

            Name
            <input type="text" value="" id="name" tabindex="1" placeholder="Enter Name" ng-model="person.name" name="name"  />

            Extn
            <input type="text" value="" id="extn" tabindex="2" placeholder="Enter Extn" ng-model="person.extn" name="extn"   />

            Designation
            <input type="text" value="" id="designation" tabindex="3" placeholder="Enter Designation" ng-model="person.designation" name="designation"   />

            mobile
            <input type="text" value="" id="mobile" tabindex="4" placeholder="Enter Mobile" ng-model="person.mobile" name="mobile"   />

            email
            <input type="text" value="" id="email" tabindex="5" placeholder="Enter Email" ng-model="person.email" name="email"   />

            upload file
            <input  type="file" id="uploadFile" name="uploadFile" tabindex="6" ng-mode="person.fileUpload"   />

            <input type="button" value="Submit" id="submitbtn" tabindex="7" ng-click="save(person)"/>

</form>

AngularJS

angular
.module("addressBook",['ngRoute'])
.controller('addController', ['$scope','$location','$rootScope','$http', function(scope,location,rootScope,http){

    scope.save = function (item){
        var personData = {
            'name' : scope.person.name,
            'extn' : scope.person.extn,
            'designation' : scope.person.designation,
            'mobile' : scope.person.mobile,
            'email' : scope.person.email,
            'fileUpload' : scope.person.fileUpload
        };

        if(typeof rootScope.crew === 'undefined'){
            rootScope.crew = [];
        }
        debugger;
        console.log(personData);
        http.post("server/insert.php",personData).success(function(data, status, headers, config){
            scope.person = personData;
            //rootScope.crew.push(scope.person);
            location.path("/admin");
        })

    }
}]);

PHP Code

<?php
    include 'conn.php';
    $data = json_decode(file_get_contents("php://input"));

    $name = mysql_real_escape_string($data->name);
    $extn = mysql_real_escape_string($data->extn);
    $designation = mysql_real_escape_string($data->designation);
    $mobile = mysql_real_escape_string($data->mobile);
    $email = mysql_real_escape_string($data->email);

    echo $query = "INSERT INTO employee (`name`,`extn`,`designation`,`mobile`,`email`) VALUES ('$name', '$extn', '$designation', '$mobile' , '$email')";
    mysql_query($query);
    Print "Your information has been successfully added to the database.";
?>


问:
How to combine two byte arrays
I have two byte arrays and I am wondering how I would go about adding one to the other or combining them to form a new byte array. </p>

答:
I think it is best approach,</p>

```<code>public static byte[] addAll(final byte[] array1, byte[] array2) {
    byte[] joinedArray = Arrays.copyOf(array1, array1.length + array2.length);
    System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
    return joinedArray;
}
</code>```

Title: How to combine two byte arrays

Body:
I think it is best approach,

public static byte[] addAll(final byte[] array1, byte[] array2) {
    byte[] joinedArray = Arrays.copyOf(array1, array1.length + array2.length);
    System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
    return joinedArray;
}


问:
measuring the elapsed time between code segments in PHP
From time time to time, I'd like to be able to measure the elapsed time between two segments of code. This is solely to be able to detect the bottlenecks within the code and improve what can be improved.

I'd like to design a function like that where the function should work with a global variable which  echoes out the elapsed time between the current call and the last time it was called.

This way, you can use it many times one after the other.

And the function should be able to be calculate the differences in fractions of seconds such as 0.1 sec or 0.3 sec etc.

An example would probably explain it much better.

```<code>echo time_elapsed();

     // This echo outputs nothing cause this is the starting case.
     // There is nothing to compare against.

//
// 1st code section here
//

echo time_elapsed();

      // This echo outputs 0.5 seconds.
      // ...which means there has been 0.5 seconds passed
      // ...since the last time time_elapsed() was fired

//
// 2nd code section here
//

echo time_elapsed()

      // This echo outputs 0.2 seconds

//
// 3rd code section here
//

echo time_elapsed()

      // This echo outputs 0.1 seconds etc
</code>```

My question is what PHP utilities ( built-in functions ) do I need to use to achieve this kind of output?

答:
```<code><?php
$time_start = microtime(true);

// Sleep for a while (or your code which you want to measure)
usleep(100);

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
</code>```

Source: http://php.net/manual/en/function.microtime.php#example-2568

Body:
From time time to time, I'd like to be able to measure the elapsed time between two segments of code. This is solely to be able to detect the bottlenecks within the code and improve what can be improved.

I'd like to design a function like that where the function should work with a global variable which  echoes out the elapsed time between the current call and the last time it was called.

This way, you can use it many times one after the other.

And the function should be able to be calculate the differences in fractions of seconds such as 0.1 sec or 0.3 sec etc.

An example would probably explain it much better.

echo time_elapsed();

     // This echo outputs nothing cause this is the starting case.
     // There is nothing to compare against.

//
// 1st code section here
//

echo time_elapsed();

      // This echo outputs 0.5 seconds.
      // ...which means there has been 0.5 seconds passed
      // ...since the last time time_elapsed() was fired

//
// 2nd code section here
//

echo time_elapsed()

      // This echo outputs 0.2 seconds

//
// 3rd code section here
//

echo time_elapsed()

      // This echo outputs 0.1 seconds etc

My question is what PHP utilities ( built-in functions ) do I need to use to achieve this kind of output?

Body:
<?php
$time_start = microtime(true);

// Sleep for a while (or your code which you want to measure)
usleep(100);

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";

Source: http://php.net/manual/en/function.microtime.php#example-2568


问:
Why doesn't the following regex work when input through Spring
Here is the spring configuration:

<bean id="wrapInMarginalMarkup" class="com.a.ChangeContentAction">
        <property name="regEx">
            <bean class="java.util.regex.Pattern" factory-method="compile">
                <constructor-arg value="(.*)(<m>)(.*)(<xm>)(.*)" />
            </bean>
        </property>
        <property name="replaceExpression" value="$1<marginal\.markup>$3</marginal\.markup>$5" />
    </bean>
```

<p>The class accepts parameters in java like:</p>

```   private Pattern regEx;
    private String replaceExpression;

    /**
     * {@inheritDoc}
     */
    @Override
    public int execute(final BuilderContext context, final Paragraph paragraph)
    {
        String content = paragraph.getContent();
        paragraph.setContent(regEx.matcher(content).replaceAll(replaceExpression));
    }
```

<p>This is what the string looks like that will be matched on the pattern: </p>

```"Be it enacted by the Senate and House of Representatives of the United States of America in Congress assembled,,<m>Surface Transportation Extension Act of 2012.,<xm>"
```

<p>It doesn't seem to actually replace the markup here, what is the issue ? </p>

<p>I want the output string to look like:</p>

```"Be it enacted by the Senate and House of Representatives of the United States of America in Congress assembled,,<marginal.markup>Surface Transportation Extension Act of 2012.,</marginal.markup>"
```

答:
Try to parse the Reg Ex via a property file and then create pattern object. I sorted out the same issue I faced while injecting Reg Ex via XML beans.

Ex :- I needed to parse the Reg Ex (.*)(D[0-9]{7}\.D[0-9]{9}\.D[A-Z]{3}[0-9]{4})(.*) by injecting in Spring. But it didn't work. Then I tried to use the same Reg Ex hard coded in a Java class and it worked.

```<code>Pattern pattern = Pattern.compile("(.*)(D[0-9]{7}\\.D[0-9]{9}\\.D[A-Z]{2}[0-9]{4})(.*)");
Matcher matcher = pattern.matcher(file.getName().trim());
</code>```

Next I tried to load that Reg Ex via property file while injecting it. It worked fine.

```<code>p:remoteDirectory="${rawDailyReport.remote.download.dir}"
p:localDirectory="${rawDailyReport.local.valid.dir}"
p:redEx="${rawDailyReport.download.regex}"
</code>```

And in the property file the property is defined as follows.

```<code>(.*)(D[0-9]{7}\\.D[0-9]{9}\\.D[A-Z]{2}[0-9]{4})(.*)
</code>```

This is because the values with place holders are loaded through org.springframework.beans.factory.config.PropertyPlaceholderConfigurer and it handles these XML sensitive characters internally.

Body:
Here is the spring configuration:

<bean id="wrapInMarginalMarkup" class="com.a.ChangeContentAction">
        <property name="regEx">
            <bean class="java.util.regex.Pattern" factory-method="compile">
                <constructor-arg value="(.*)(<m>)(.*)(<xm>)(.*)" />
            </bean>
        </property>
        <property name="replaceExpression" value="$1<marginal\.markup>$3</marginal\.markup>$5" />
    </bean>

The class accepts parameters in java like:

   private Pattern regEx;
    private String replaceExpression;

    /**
     * {@inheritDoc}
     */
    @Override
    public int execute(final BuilderContext context, final Paragraph paragraph)
    {
        String content = paragraph.getContent();
        paragraph.setContent(regEx.matcher(content).replaceAll(replaceExpression));
    }

This is what the string looks like that will be matched on the pattern:

"Be it enacted by the Senate and House of Representatives of the United States of America in Congress assembled,,<m>Surface Transportation Extension Act of 2012.,<xm>"

It doesn't seem to actually replace the markup here, what is the issue ?

I want the output string to look like:

"Be it enacted by the Senate and House of Representatives of the United States of America in Congress assembled,,<marginal.markup>Surface Transportation Extension Act of 2012.,</marginal.markup>"

Body:
Try to parse the Reg Ex via a property file and then create pattern object. I sorted out the same issue I faced while injecting Reg Ex via XML beans.

Ex :- I needed to parse the Reg Ex (.*)(D[0-9]{7}\.D[0-9]{9}\.D[A-Z]{3}[0-9]{4})(.*) by injecting in Spring. But it didn't work. Then I tried to use the same Reg Ex hard coded in a Java class and it worked.

Pattern pattern = Pattern.compile("(.*)(D[0-9]{7}\\.D[0-9]{9}\\.D[A-Z]{2}[0-9]{4})(.*)");
Matcher matcher = pattern.matcher(file.getName().trim());

Next I tried to load that Reg Ex via property file while injecting it. It worked fine.

p:remoteDirectory="${rawDailyReport.remote.download.dir}"
p:localDirectory="${rawDailyReport.local.valid.dir}"
p:redEx="${rawDailyReport.download.regex}"

And in the property file the property is defined as follows.

(.*)(D[0-9]{7}\\.D[0-9]{9}\\.D[A-Z]{2}[0-9]{4})(.*)

This is because the values with place holders are loaded through org.springframework.beans.factory.config.PropertyPlaceholderConfigurer and it handles these XML sensitive characters internally.


问:
SwipeRefreshLayout with Webview not working
This is my webview app code with SwipeRefreshLayout. But SwipeRefresh not working please check it. But all other things are working correctly. Like webview, menu button.

Below is my activity_main.xml file

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

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:id="@+id/webView"
        />
    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
</code>```

And this is my MainActivity.java file

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

    WebView webView;
    SwipeRefreshLayout swipe;

    @Override
    public boolean onCreateOptionsMenu (Menu manu){
        getMenuInflater().inflate(R.menu.main, manu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected (MenuItem item){
        int id=item.getItemId();
        if(id==R.id.id_about){
            Intent intentabout=new Intent(MainActivity.this, About.class);
            startActivity(intentabout);

            return true;
        }
        if(id==R.id.id_terms){

            return true;
        }
        if(id==R.id.id_privacy){

            return true;
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        if(webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }

    }

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

        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                LoadWeb();
            }
        });

        LoadWeb();

    }

    public void LoadWeb(){
        webView = (WebView) findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webView.loadUrl("https://google.com");
        swipe.setRefreshing(true);
        webView.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                webView.loadUrl("file:///android_asset/error.html");

            }

            public void onPagefinished(WebView view, String url){
                swipe.setRefreshing(false);
            }
        });
    }

}
</code>```

答:
You gotta put your WebView inside SwipeRefreshLayout:

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

    WebView webView;
    SwipeRefreshLayout swipeRefreshLayout;
    String currentUrl = "https://www.google.co.in/";

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

        webView = (WebView) findViewById(R.id.webView);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);

        webView.loadUrl(currentUrl);
        webView.setWebViewClient(new MyWebViewClient());

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                webView.loadUrl(currentUrl);
            }
        });
    }

    public class MyWebViewClient extends WebViewClient{

        @Override
        public void onPageFinished(WebView view, String url) {
            swipeRefreshLayout.setRefreshing(false);
            currentUrl = url;
            super.onPageFinished(view, url);
        }
    }
}
</code>```

swipeRefreshLayout.setRefreshing(false) stops the animation.

Body:
This is my webview app code with SwipeRefreshLayout. But SwipeRefresh not working please check it. But all other things are working correctly. Like webview, menu button.

Below is my activity_main.xml file

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout>

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:id="@+id/webView"
        />
    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>

And this is my MainActivity.java file

    public class MainActivity extends AppCompatActivity {

    WebView webView;
    SwipeRefreshLayout swipe;

    @Override
    public boolean onCreateOptionsMenu (Menu manu){
        getMenuInflater().inflate(R.menu.main, manu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected (MenuItem item){
        int id=item.getItemId();
        if(id==R.id.id_about){
            Intent intentabout=new Intent(MainActivity.this, About.class);
            startActivity(intentabout);

            return true;
        }
        if(id==R.id.id_terms){

            return true;
        }
        if(id==R.id.id_privacy){

            return true;
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        if(webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }

    }

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

        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                LoadWeb();
            }
        });

        LoadWeb();

    }

    public void LoadWeb(){
        webView = (WebView) findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webView.loadUrl("https://google.com");
        swipe.setRefreshing(true);
        webView.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                webView.loadUrl("file:///android_asset/error.html");

            }

            public void onPagefinished(WebView view, String url){
                swipe.setRefreshing(false);
            }
        });
    }

}

Body:
You gotta put your WebView inside SwipeRefreshLayout:

public class MainActivity extends AppCompatActivity {

    WebView webView;
    SwipeRefreshLayout swipeRefreshLayout;
    String currentUrl = "https://www.google.co.in/";

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

        webView = (WebView) findViewById(R.id.webView);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);

        webView.loadUrl(currentUrl);
        webView.setWebViewClient(new MyWebViewClient());

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                webView.loadUrl(currentUrl);
            }
        });
    }

    public class MyWebViewClient extends WebViewClient{

        @Override
        public void onPageFinished(WebView view, String url) {
            swipeRefreshLayout.setRefreshing(false);
            currentUrl = url;
            super.onPageFinished(view, url);
        }
    }
}

swipeRefreshLayout.setRefreshing(false) stops the animation.


问:
iOS 11 Core NFC - any sample code?
I just installed the first iOS 11 beta to an iPhone 7 and am interested in trying the NFC. There's nothing about it in settings.  I am wondering if there's any sample code out there showing how to read a tag. Can anyone show how to use the Core NFC SDK, in a code snippet?</p>

答:
In the Apple Developer site, create a new App ID and make sure that NFC Tag Reading is enabled.

Add the following lines to your .plist file:

```<code><key>NFCReaderUsageDescription</key>
<string>NFC Tag!</string>
</code>```

and these to the entitlements file:

```<code><key>com.apple.developer.nfc.readersession.formats</key>
    <array>
        <string>NDEF</string>
    </array>
</code>```

It should look something like this in the corresponding files:

Also Core NFC can be enabled via the Capabilities tab in Xcode.

Objective-c

Import CoreNFC

```<code>#import <CoreNFC/CoreNFC.h>
</code>```

and set the delegate:

```<code>@interface YourViewController : UIViewController <NFCNDEFReaderSessionDelegate>
</code>```

In viewDidLoad:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NFCNDEFReaderSession *session = [[NFCNDEFReaderSession alloc] initWithDelegate:self queue:dispatch_queue_create(NULL, DISPATCH_QUEUE_CONCURRENT) invalidateAfterFirstRead:NO];
    [session beginSession];
}
</code>```

In the delegate callback:

```<code>- (void) readerSession:(nonnull NFCNDEFReaderSession *)session didDetectNDEFs:(nonnull NSArray<NFCNDEFMessage *> *)messages {

    for (NFCNDEFMessage *message in messages) {
        for (NFCNDEFPayload *payload in message.records) {
            NSLog(@"Payload data:%@",payload.payload);
        }
    }
}
</code>```

You must also add the didInvalidateWithError delegate callback or you'll not conform with protocol:

```<code>- (void)readerSession:(nonnull NFCNDEFReaderSession *)session didInvalidateWithError:(nonnull NSError *)error {

}
</code>```

You can stop the reader with:

```<code>[session invalidateSession];
</code>```

Swift 3/4

Import CoreNFC

```<code>import CoreNFC
</code>```

and set the delegate:

```<code>class YourViewController: UIViewController, NFCNDEFReaderSessionDelegate
</code>```

In viewDidLoad:

```<code><key>com.apple.developer.nfc.readersession.formats</key>
    <array>
        <string>NDEF</string>
    </array>
</code>```0

In the delegate callback:

```<code><key>com.apple.developer.nfc.readersession.formats</key>
    <array>
        <string>NDEF</string>
    </array>
</code>```1

You can stop the reader with:

```<code><key>com.apple.developer.nfc.readersession.formats</key>
    <array>
        <string>NDEF</string>
    </array>
</code>```2

Usage

After launching the view you should immediately see the iOS NFC reader dialog like so:

Once this dialog appears you have about a second to place the iPhone near the NFC tag you want to read. Otherwise, the field is deactivated (this seems to be a bug on Apple's end). I often needed to cancel and retry to get consistent readings. More details here.

Title: iOS 11 Core NFC - any sample code?

Body:
In the Apple Developer site, create a new App ID and make sure that NFC Tag Reading is enabled.

Add the following lines to your .plist file:

<key>NFCReaderUsageDescription</key>
<string>NFC Tag!</string>

and these to the entitlements file:

<key>com.apple.developer.nfc.readersession.formats</key>
    <array>
        <string>NDEF</string>
    </array>

It should look something like this in the corresponding files:

Also Core NFC can be enabled via the Capabilities tab in Xcode.

Objective-c

Import CoreNFC

#import <CoreNFC/CoreNFC.h>

and set the delegate:

@interface YourViewController : UIViewController <NFCNDEFReaderSessionDelegate>

In viewDidLoad:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NFCNDEFReaderSession *session = [[NFCNDEFReaderSession alloc] initWithDelegate:self queue:dispatch_queue_create(NULL, DISPATCH_QUEUE_CONCURRENT) invalidateAfterFirstRead:NO];
    [session beginSession];
}

In the delegate callback:

- (void) readerSession:(nonnull NFCNDEFReaderSession *)session didDetectNDEFs:(nonnull NSArray<NFCNDEFMessage *> *)messages {

    for (NFCNDEFMessage *message in messages) {
        for (NFCNDEFPayload *payload in message.records) {
            NSLog(@"Payload data:%@",payload.payload);
        }
    }
}

You must also add the didInvalidateWithError delegate callback or you'll not conform with protocol:

- (void)readerSession:(nonnull NFCNDEFReaderSession *)session didInvalidateWithError:(nonnull NSError *)error {

}

You can stop the reader with:

[session invalidateSession];

Swift 3/4

Import CoreNFC

import CoreNFC

and set the delegate:

class YourViewController: UIViewController, NFCNDEFReaderSessionDelegate

In viewDidLoad:

override func viewDidLoad() {
        super.viewDidLoad()

        let session = NFCNDEFReaderSession(delegate: self,
                      queue: DispatchQueue(label: "queueName", attributes: .concurrent), invalidateAfterFirstRead: false)
        session?.begin()
    }

In the delegate callback:

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
  for message in messages {
    for record in message.records {
      print(record.payload)
    }
  }
}

You can stop the reader with:

session.invalidateSession

Usage

After launching the view you should immediately see the iOS NFC reader dialog like so:

Once this dialog appears you have about a second to place the iPhone near the NFC tag you want to read. Otherwise, the field is deactivated (this seems to be a bug on Apple's end). I often needed to cancel and retry to get consistent readings. More details here.


问:
SVG to Android Shape
I'm wondering how vector drawing in Android with the Shape class may resemble another vector drawing standard.

Since Shape is a Drawable, and Drawables are usually defined as XML, it sounds a lot like the vector drawing commands in SVG.

My question is this: Has anybody created an XSLT transformation, or other mechanism, for converting an SVG drawing description into Android Shapes?

答:
Currently some people including me work on it independently.

You may find working solution in these articles:

  Android. ImageView with SVG Support.

  Android ImageView and Drawable with SVG support

Title: SVG to Android Shape


问:
Display DICOM monochrome2 having bits stored less than bits allocated
I want to display DICOM file having photometric interpretation MONOCHROME2.

some of the specifications of image are-

```<code>Rows:           1024
Columns:        1024
No of Frames:   622
Bits Allocated: 16
Bits Stored:    10
High Bit:       9
Pixel Representation: 0
Sample per pixel: 1
</code>```

I am using gdcmRegionReader to extract single frames byte array in the following way.

```<code> gdcm.ImageRegionReader _regionReader = new gdcm.ImageRegionReader();
 _regionReader.SetRegion(_boxRegion);  // _boxRegion is some region
 _regionReader.ReadIntoBuffer(Result, (uint)Result.Length);
 Marshal.Copy(Result.ToArray(), 0, _imageData.GetScalarPointer(),
 Result.ToArray().Length);
 _viewer.SetInput(_imageData);  // _viewer = vtkImageViewer
</code>```

But when i display that file it is displaying like this..

but the original image is like this..

So can someone help me on how to load and display MONOCHROME2 dicom images.

答:
You should really use vtkGDCMImageReader2 instead in your code. vtkGDCMImageReader2 precisely encapsulate gdcm::RegionReader for binding with VTK.

If for some reason you cannot use directly this class, simply copy/paste the C++ code from within the main function, into your C# code.

See:

http://gdcm.sourceforge.net/2.6/html/classvtkGDCMImageReader2.xhtml

http://gdcm.sourceforge.net/2.6/html/classgdcm_1_1ImageRegionReader.xhtml

Body:
I want to display DICOM file having photometric interpretation MONOCHROME2.

some of the specifications of image are-

Rows:           1024
Columns:        1024
No of Frames:   622
Bits Allocated: 16
Bits Stored:    10
High Bit:       9
Pixel Representation: 0
Sample per pixel: 1

I am using gdcmRegionReader to extract single frames byte array in the following way.

 gdcm.ImageRegionReader _regionReader = new gdcm.ImageRegionReader();
 _regionReader.SetRegion(_boxRegion);  // _boxRegion is some region
 _regionReader.ReadIntoBuffer(Result, (uint)Result.Length);
 Marshal.Copy(Result.ToArray(), 0, _imageData.GetScalarPointer(),
 Result.ToArray().Length);
 _viewer.SetInput(_imageData);  // _viewer = vtkImageViewer

But when i display that file it is displaying like this..

but the original image is like this..

So can someone help me on how to load and display MONOCHROME2 dicom images.


问:
Filter only parameters that are present in the request
There are lots of articles that are about Java 8 lambda operations however I couldn't find what I need until now. I tried to convert them to my approach unfortunately I couldn't succeed

Imagine that you have request that comes in POJO such as ;

```<code>public class DummyRequest {

    private String name;
    private String surname;
    private String country;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country= country;
    }

}
</code>```

During REST/SOAP request surname variable will be assigned as null.

```<code>List<Person> persons = Arrays.asList(
                new Person("maria", "gambert", "italy"),
                new Person("jack", "johson", "usa"),
                new Person("johnson", "jack", "usa"),
                new Person("kate", "julia", "spain"),
                new Person("jack","bob","uk");

DummyRequest dr = new DummyRequest();
dr.setName("jack");
dr.setCountry("usa");
</code>```

If I knew in advance that the surname field would be null, I could manage to filter the list like this, ignoring that field:

```<code>List<Person> result4 = persons.stream().
filter(x -> dummyRequest.getName().equals(x.getName())).
filter( x-> dummyRequest.getCountry().equals(x.getCountry())).
collect(Collectors.toList());
</code>```

However I don't know which fields will be null and which will not. How could I instead filter my data according to non-null request parameters only?

答:
If you want to filter only by the non-null properties of dummyRequest, you can simply add a null check to each Predicate:

```<code>List<Person> result4 =
    persons.stream()
           .filter(x -> dummyRequest.getSurname() == null || dummyRequest.getSurname().equals(x.getSurname()))
           .filter(x -> dummyRequest.getName() == null || dummyRequest.getName().equals(x.getName()))
           .filter(x -> dummyRequest.getCountry() == null || dummyRequest.getCountry().equals(x.getCountry()))
           .collect(Collectors.toList());
</code>```

Body:
There are lots of articles that are about Java 8 lambda operations however I couldn't find what I need until now. I tried to convert them to my approach unfortunately I couldn't succeed

Imagine that you have request that comes in POJO such as ;

public class DummyRequest {

    private String name;
    private String surname;
    private String country;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country= country;
    }

}

During REST/SOAP request surname variable will be assigned as null.

List<Person> persons = Arrays.asList(
                new Person("maria", "gambert", "italy"),
                new Person("jack", "johson", "usa"),
                new Person("johnson", "jack", "usa"),
                new Person("kate", "julia", "spain"),
                new Person("jack","bob","uk");

DummyRequest dr = new DummyRequest();
dr.setName("jack");
dr.setCountry("usa");

If I knew in advance that the surname field would be null, I could manage to filter the list like this, ignoring that field:

List<Person> result4 = persons.stream().
filter(x -> dummyRequest.getName().equals(x.getName())).
filter( x-> dummyRequest.getCountry().equals(x.getCountry())).
collect(Collectors.toList());

However I don't know which fields will be null and which will not. How could I instead filter my data according to non-null request parameters only?

Body:
If you want to filter only by the non-null properties of dummyRequest, you can simply add a null check to each Predicate:

List<Person> result4 =
    persons.stream()
           .filter(x -> dummyRequest.getSurname() == null || dummyRequest.getSurname().equals(x.getSurname()))
           .filter(x -> dummyRequest.getName() == null || dummyRequest.getName().equals(x.getName()))
           .filter(x -> dummyRequest.getCountry() == null || dummyRequest.getCountry().equals(x.getCountry()))
           .collect(Collectors.toList());


问:
bash scripting - how to loop through results called within a function
I have a function that gives me a list of IPs and for each IP in my list, I want to run a query. The problem I'm having is its only looping through (1) of the results and not the rest.

```<code>getPartition ()
{
    _knife=$(which knife);
    _grep=$(which grep);
    _awk=$(which awk);
    cd ~/home/foo/.chef
    local result=$(${_knife} search "chef_environment:dev AND role:myapp AND ec2_region:us-east-1" | ${_grep} IP | ${_awk} '{ print $2 }');
   read -a servers <<< $result;
   echo "Checking ${#servers[@]} servers";
   for i in ${servers[@]};
   do
       local host='10.1.2.123'
       local db='mystate'
       _mongo=$(which mongo);
       echo -n "$i";
       local exp="db.foobarcluster_servers.find(
       {\"node_host\":\"${i}\",\"node_type\":\"PROCESS\",\"region\":\"us-east-1\",\"status\":\"ACTIVE\"},{\"partition_range_start\":1,\"partition_range_end\":1, _id:0}).pretty();";
       ${_mongo} ${host}/${db} --eval "$exp" | grep -o -e "{[^}]*}";
  done
}
</code>```

So, I tried using for, but its only running the query for (1) of the (5) hosts listed.

I can see in my output for result that the list of IPs look like this:

```<code>+ local 'result=10.8.3.34
10.8.2.161
10.8.3.514
10.8.4.130
10.8.2.173'
</code>```

So, I'm just returning results for (1) of the IPs it should be (5) of them because I have 5 IPs:

```<code>+ read -a servers
+ echo 'Checking 1 servers'
Checking 1 servers
+ for i in ${servers[@]}
+ local host=10.1.2.130
+ local db=mystate
++ which mongo
+ _mongo=/usr/local/bin/mongo
+ echo -n 10.8.3.34
10.8.3.34+ local 'exp=db.foobarcluster_servers.find(
       {"node_host":"10.8.3.34","node_type":"PROCESS","region":"us-east-1","status":"ACTIVE"},{"partition_range_start":1,"partition_range_end":1, _id:0}).pretty();'
+ /usr/local/bin/mongo 10.8.3.34/mystate --eval 'db.foobarcluster_servers.find(
       {"node_host":"10.8.3.34","node_type":"PROCESS","region":"us-east-1","status":"ACTIVE"},{"partition_range_start":1,"partition_range_end":1, _id:0}).pretty();'
+ grep -o -e '{[^}]*}'
{ "partition_range_start" : 31, "partition_range_end" : 31 }
+ set +x
</code>```

Results:

```<code>{ "partition_range_start" : 31, "partition_range_end" : 31 }
</code>```

I'm expecting:

```<code>{ "partition_range_start" : 31, "partition_range_end" : 31 }
{ "partition_range_start" : 32, "partition_range_end" : 32 }
{ "partition_range_start" : 33, "partition_range_end" : 33 }
{ "partition_range_start" : 34, "partition_range_end" : 34 }
{ "partition_range_start" : 35, "partition_range_end" : 35 }
</code>```

How do I effectively loop through my IPs? Did I set up result properly as a variable to hold that list of IPs?

答:
The problem is that…

```<code>read -a servers <<< $result
</code>```

is only reading the first line into the array

Change that line to…

```<code>servers=( $result )
</code>```

This converts every whitespace-delimited value in $result into an array element. Effectively servers=( <ip> <ip> <ip> <ip> <ip> )

Body:
I have a function that gives me a list of IPs and for each IP in my list, I want to run a query. The problem I'm having is its only looping through (1) of the results and not the rest.

getPartition ()
{
    _knife=$(which knife);
    _grep=$(which grep);
    _awk=$(which awk);
    cd ~/home/foo/.chef
    local result=$(${_knife} search "chef_environment:dev AND role:myapp AND ec2_region:us-east-1" | ${_grep} IP | ${_awk} '{ print $2 }');
   read -a servers <<< $result;
   echo "Checking ${#servers[@]} servers";
   for i in ${servers[@]};
   do
       local host='10.1.2.123'
       local db='mystate'
       _mongo=$(which mongo);
       echo -n "$i";
       local exp="db.foobarcluster_servers.find(
       {\"node_host\":\"${i}\",\"node_type\":\"PROCESS\",\"region\":\"us-east-1\",\"status\":\"ACTIVE\"},{\"partition_range_start\":1,\"partition_range_end\":1, _id:0}).pretty();";
       ${_mongo} ${host}/${db} --eval "$exp" | grep -o -e "{[^}]*}";
  done
}

So, I tried using for, but its only running the query for (1) of the (5) hosts listed.

I can see in my output for result that the list of IPs look like this:

+ local 'result=10.8.3.34
10.8.2.161
10.8.3.514
10.8.4.130
10.8.2.173'

So, I'm just returning results for (1) of the IPs it should be (5) of them because I have 5 IPs:

+ read -a servers
+ echo 'Checking 1 servers'
Checking 1 servers
+ for i in ${servers[@]}
+ local host=10.1.2.130
+ local db=mystate
++ which mongo
+ _mongo=/usr/local/bin/mongo
+ echo -n 10.8.3.34
10.8.3.34+ local 'exp=db.foobarcluster_servers.find(
       {"node_host":"10.8.3.34","node_type":"PROCESS","region":"us-east-1","status":"ACTIVE"},{"partition_range_start":1,"partition_range_end":1, _id:0}).pretty();'
+ /usr/local/bin/mongo 10.8.3.34/mystate --eval 'db.foobarcluster_servers.find(
       {"node_host":"10.8.3.34","node_type":"PROCESS","region":"us-east-1","status":"ACTIVE"},{"partition_range_start":1,"partition_range_end":1, _id:0}).pretty();'
+ grep -o -e '{[^}]*}'
{ "partition_range_start" : 31, "partition_range_end" : 31 }
+ set +x

Results:

{ "partition_range_start" : 31, "partition_range_end" : 31 }

I'm expecting:

{ "partition_range_start" : 31, "partition_range_end" : 31 }
{ "partition_range_start" : 32, "partition_range_end" : 32 }
{ "partition_range_start" : 33, "partition_range_end" : 33 }
{ "partition_range_start" : 34, "partition_range_end" : 34 }
{ "partition_range_start" : 35, "partition_range_end" : 35 }

How do I effectively loop through my IPs? Did I set up result properly as a variable to hold that list of IPs?

Body:
The problem is that…

read -a servers <<< $result

is only reading the first line into the array

Change that line to…

servers=( $result )

This converts every whitespace-delimited value in $result into an array element. Effectively servers=( <ip> <ip> <ip> <ip> <ip> )


问:
Stylesheet does not apply to HTML?
I am adding a Google Places autocomplete box on my web site.

```<code>#pac-card.pac-card
  div
    #pac-title
      | Autocomplete search
    #type-selector.pac-controls
      input#changetype-all(type='radio', name='type', checked='checked')
      label(for='changetype-all') All
      input#changetype-establishment(type='radio', name='type')
      label(for='changetype-establishment') Establishments
      input#changetype-address(type='radio', name='type')
      label(for='changetype-address') Addresses
      input#changetype-geocode(type='radio', name='type')
      label(for='changetype-geocode') Geocodes
    #strict-bounds-selector.pac-controls
      input#use-strict-bounds(type='checkbox', value='')
      label(for='use-strict-bounds') Strict Bounds
  #pac-container
    input#pac-input(type='text', placeholder='Enter a location')
</code>```

and have a stylesheet defined:

```<code>.pac-card {
  margin: 10px 10px 0 0;
  border-radius: 2px 0 0 2px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
}

#pac-container {
  padding-bottom: 12px;
  margin-right: 12px;
}
</code>```

I do include the stylesheet on the page. What might be a possible reason the stylesheet does not apply to the HTML?

The code is correct as I tried it out on jsfiddle.

答:
your code is not HTML (maybe a template code that generate HTML ?).
I took a look a Place Autocomplete documentation (https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete?hl=fr), and the HTML should look like that :

```<code><input id="pac-input" class="controls" type="text"
        placeholder="Enter a location">
    <div id="type-selector" class="controls">
      <input type="radio" name="type" id="changetype-all" checked="checked">
      <label for="changetype-all">All</label>

      <input type="radio" name="type" id="changetype-establishment">
      <label for="changetype-establishment">Establishments</label>

      <input type="radio" name="type" id="changetype-address">
      <label for="changetype-address">Addresses</label>

      <input type="radio" name="type" id="changetype-geocode">
      <label for="changetype-geocode">Geocodes</label>
    </div>
    <div id="map"></div>
</code>```

In this code for example, I cant see a #pac-container id for any div.

So first thing, make sure your generated HTML has the correct CSS selector corresponding to your styles.

Title: Stylesheet does not apply to HTML?

Body:
I am adding a Google Places autocomplete box on my web site.

#pac-card.pac-card
  div
    #pac-title
      | Autocomplete search
    #type-selector.pac-controls
      input#changetype-all(type='radio', name='type', checked='checked')
      label(for='changetype-all') All
      input#changetype-establishment(type='radio', name='type')
      label(for='changetype-establishment') Establishments
      input#changetype-address(type='radio', name='type')
      label(for='changetype-address') Addresses
      input#changetype-geocode(type='radio', name='type')
      label(for='changetype-geocode') Geocodes
    #strict-bounds-selector.pac-controls
      input#use-strict-bounds(type='checkbox', value='')
      label(for='use-strict-bounds') Strict Bounds
  #pac-container
    input#pac-input(type='text', placeholder='Enter a location')

and have a stylesheet defined:

.pac-card {
  margin: 10px 10px 0 0;
  border-radius: 2px 0 0 2px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
}

#pac-container {
  padding-bottom: 12px;
  margin-right: 12px;
}

I do include the stylesheet on the page. What might be a possible reason the stylesheet does not apply to the HTML?

The code is correct as I tried it out on jsfiddle.

Body:
your code is not HTML (maybe a template code that generate HTML ?).
I took a look a Place Autocomplete documentation (https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete?hl=fr), and the HTML should look like that :

<input id="pac-input" class="controls" type="text"
        placeholder="Enter a location">
    <div id="type-selector" class="controls">
      <input type="radio" name="type" id="changetype-all" checked="checked">
      <label for="changetype-all">All</label>

      <input type="radio" name="type" id="changetype-establishment">
      <label for="changetype-establishment">Establishments</label>

      <input type="radio" name="type" id="changetype-address">
      <label for="changetype-address">Addresses</label>

      <input type="radio" name="type" id="changetype-geocode">
      <label for="changetype-geocode">Geocodes</label>
    </div>
    <div id="map"></div>

In this code for example, I cant see a #pac-container id for any div.

So first thing, make sure your generated HTML has the correct CSS selector corresponding to your styles.


问:
Replace array value with new one
I have array of array, where i want to change date format. I am trying to get it as below

```<code>foreach ($toReturn as $value) {

    $start_date = new DateTime($value['start_date']);
    $value['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $value['end_date'] = $end_date->format('m-d-Y');
}
</code>```

here format gets changed but it is not replacing array value with new one?? Why??

答:
If your want to change the value in the foreach, you need to access it by reference.

change foreach ($toReturn as $value) to foreach ($toReturn as &$value)

Title: Replace array value with new one

Body:
I have array of array, where i want to change date format. I am trying to get it as below

foreach ($toReturn as $value) {

    $start_date = new DateTime($value['start_date']);
    $value['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $value['end_date'] = $end_date->format('m-d-Y');
}

here format gets changed but it is not replacing array value with new one?? Why??


问:
what interval does this cron run?
What interval does this CRON run?</p>

```<code>*/5 0 * * * /command
</code>```

答: You cron runs every 5 minutes between midnight and 01h00 - not included.</p>

Title: what interval does this cron run?

Body:
What interval does this CRON run?

*/5 0 * * * /command


问:
Where does the Wakanda Enterprise Server license file go, on a Mac OS Sierra system?
Where should the Wakanda Enterprise Server license file be located in a Mac OS Sierra system? I signed up for the 30-day trial, and the instructions said /Document/Wakanda/License, but when I created that path and started the server, it said

"License not found. Server running in Community mode"

I also tried ~/Documents/Wakanda/ and ~/Documents/Wakanda/License/ to no effect.  I can’t seem to find it in the documentation either, can someone point me in the right direction?

答:
For Mac user, you need to add your license file here :

/Users/<user>/Documents/Wakanda/license/license.key
or
~/Documents/Wakanda/license/license.key

There is not uppercase to license.