问:
I am unable to get over the java.lang.NullPointerException in android studio when using file provider class
This is my Manifest file code

```<code><activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
    </activity>
</code>```

And the code for my new resource xml file is

```<code>  <?xml version="1.0" encoding="utf-8"?>
  <paths xmlns:android="http://schemas.android.com/apk/res/android">
     <external-path name="external_files" path="."/>
  </paths>
</code>```

My main activity code is

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

    private ImageView image;
    private final int CameraKey = 1;
    Context context = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button click_button = (Button) findViewById(R.id.button);
        image = (ImageView) findViewById(R.id.imageView3);

        click_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = getFile();
                Uri apkURI = FileProvider.getUriForFile(
                        context,
                        context.getApplicationContext()
                                .getPackageName() + ".provider", file);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, apkURI);
                startActivityForResult(intent, CameraKey);

            }
        });
    }

    private File getFile(){
        File store = new File("sdcard/Digiwrite");
        if(store.exists()){
            store.mkdir();
        }

        File image = new File(store,"Images.jpg");
        return image;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == CameraKey && resultCode == RESULT_OK){
            String path = "sdcard/Digiwrite/Images.jpg";

            image.setImageDrawable(Drawable.createFromPath(path));

        }
    }
</code>```

I keep getting this error:

FATAL EXCEPTION: main
                                                                                Process: com.mukesh.android.digiwrite, PID: 30365
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method
  'android.content.res.XmlResourceParser
  android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager,
  java.lang.String)' on a null object reference
                                                                                at
  android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:583)
                                                                                at
  android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:557)
                                                                                at
  android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:399)
                                                                                at
  com.mukesh.android.digiwrite.MainActivity$1.onClick(MainActivity.java:37)
                                                                                at android.view.View.performClick(View.java:5637)
                                                                                at android.view.View$PerformClick.run(View.java:22433)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

I am completely new to Android studio. I have tried various methods available but I don't get how to make file provider work. May I know where I went wrong?

I tried running this code on lower versions using file.getUri() method and it was working fine. So as to make it run on higher versions I have been trying to convert this to use file provider. But I am stuck. Pls help me out.

答:
The path specifying XML needs to contain path not paths. Change it to:

```<code><?xml version="1.0" encoding="utf-8"?>
<path xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</path>
</code>```

Body:
This is my Manifest file code

<activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
    </activity>

And the code for my new resource xml file is

  <?xml version="1.0" encoding="utf-8"?>
  <paths xmlns:android="http://schemas.android.com/apk/res/android">
     <external-path name="external_files" path="."/>
  </paths>

My main activity code is

public class MainActivity extends Activity {

    private ImageView image;
    private final int CameraKey = 1;
    Context context = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button click_button = (Button) findViewById(R.id.button);
        image = (ImageView) findViewById(R.id.imageView3);

        click_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = getFile();
                Uri apkURI = FileProvider.getUriForFile(
                        context,
                        context.getApplicationContext()
                                .getPackageName() + ".provider", file);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, apkURI);
                startActivityForResult(intent, CameraKey);

            }
        });
    }

    private File getFile(){
        File store = new File("sdcard/Digiwrite");
        if(store.exists()){
            store.mkdir();
        }

        File image = new File(store,"Images.jpg");
        return image;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == CameraKey && resultCode == RESULT_OK){
            String path = "sdcard/Digiwrite/Images.jpg";

            image.setImageDrawable(Drawable.createFromPath(path));

        }
    }

I keep getting this error:

FATAL EXCEPTION: main
                                                                                Process: com.mukesh.android.digiwrite, PID: 30365
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method
  'android.content.res.XmlResourceParser
  android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager,
  java.lang.String)' on a null object reference
                                                                                at
  android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:583)
                                                                                at
  android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:557)
                                                                                at
  android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:399)
                                                                                at
  com.mukesh.android.digiwrite.MainActivity$1.onClick(MainActivity.java:37)
                                                                                at android.view.View.performClick(View.java:5637)
                                                                                at android.view.View$PerformClick.run(View.java:22433)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

I am completely new to Android studio. I have tried various methods available but I don't get how to make file provider work. May I know where I went wrong?

I tried running this code on lower versions using file.getUri() method and it was working fine. So as to make it run on higher versions I have been trying to convert this to use file provider. But I am stuck. Pls help me out.

Body:
The path specifying XML needs to contain path not paths. Change it to:

<?xml version="1.0" encoding="utf-8"?>
<path xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</path>


来源: stackexchange

问:
How can I convert a native (NT) pathname into a Win32 path name?
I'm working on reporting some information gleaned from native system APIs. (I know this is bad.... but I'm getting information that I can't get otherwise, and I have little issue with having to update my app if/when that time comes around.)

The native API returns native pathnames, as seen by ob, i.e. \SystemRoot\System32\Ntoskrnl.exe, or \??\C:\Program Files\VMWare Workstation\vstor-ws60.sys.

I can replace common prefixes, i.e.

```<code>std::wstring NtPathToWin32Path( std::wstring ntPath )
{
    if (boost::starts_with(ntPath, L"\\\\?\\"))
    {
        ntPath.erase(ntPath.begin(), ntPath.begin() + 4);
        return ntPath;
    }
    if (boost::starts_with(ntPath, L"\\??\\"))
    {
        ntPath.erase(ntPath.begin(), ntPath.begin() + 4);
    }
    if (boost::starts_with(ntPath, L"\\"))
    {
        ntPath.erase(ntPath.begin(), ntPath.begin() + 1);
    }
    if (boost::istarts_with(ntPath, L"globalroot\\"))
    {
        ntPath.erase(ntPath.begin(), ntPath.begin() + 11);
    }
    if (boost::istarts_with(ntPath, L"systemroot"))
    {
        ntPath.replace(ntPath.begin(), ntPath.begin() + 10, GetWindowsPath());
    }
    if (boost::istarts_with(ntPath, L"windows"))
    {
        ntPath.replace(ntPath.begin(), ntPath.begin() + 7, GetWindowsPath());
    }
    return ntPath;
}

TEST(Win32Path, NtPathDoubleQuestions)
{
    ASSERT_EQ(L"C:\\Example", NtPathToWin32Path(L"\\??\\C:\\Example"));
}

TEST(Win32Path, NtPathUncBegin)
{
    ASSERT_EQ(L"C:\\Example", NtPathToWin32Path(L"\\\\?\\C:\\Example"));
}

TEST(Win32Path, NtPathWindowsStart)
{
    ASSERT_EQ(GetCombinedPath(GetWindowsPath(), L"Hello\\World"), NtPathToWin32Path(L"\\Windows\\Hello\\World"));
}

TEST(Win32Path, NtPathSystemrootStart)
{
    ASSERT_EQ(GetCombinedPath(GetWindowsPath(), L"Hello\\World"), NtPathToWin32Path(L"\\SystemRoot\\Hello\\World"));
}

TEST(Win32Path, NtPathGlobalRootSystemRoot)
{
    ASSERT_EQ(GetCombinedPath(GetWindowsPath(), L"Hello\\World"), NtPathToWin32Path(L"\\globalroot\\SystemRoot\\Hello\\World"));
}
</code>```

but I'd be strongly surprised if there's not some API, native or otherwise, which will convert these into Win32 path names. Does such an API exist?

答:
Check this out for getting the canonical pathname in Win32.  It may be helpful for you:

http://pdh11.blogspot.com/2009/05/pathcanonicalize-versus-what-it-says-on.html

ContentLicense: CC BY-SA 2.5

Body:
I'm working on reporting some information gleaned from native system APIs. (I know this is bad.... but I'm getting information that I can't get otherwise, and I have little issue with having to update my app if/when that time comes around.)

The native API returns native pathnames, as seen by ob, i.e. \SystemRoot\System32\Ntoskrnl.exe, or \??\C:\Program Files\VMWare Workstation\vstor-ws60.sys.

I can replace common prefixes, i.e.

std::wstring NtPathToWin32Path( std::wstring ntPath )
{
    if (boost::starts_with(ntPath, L"\\\\?\\"))
    {
        ntPath.erase(ntPath.begin(), ntPath.begin() + 4);
        return ntPath;
    }
    if (boost::starts_with(ntPath, L"\\??\\"))
    {
        ntPath.erase(ntPath.begin(), ntPath.begin() + 4);
    }
    if (boost::starts_with(ntPath, L"\\"))
    {
        ntPath.erase(ntPath.begin(), ntPath.begin() + 1);
    }
    if (boost::istarts_with(ntPath, L"globalroot\\"))
    {
        ntPath.erase(ntPath.begin(), ntPath.begin() + 11);
    }
    if (boost::istarts_with(ntPath, L"systemroot"))
    {
        ntPath.replace(ntPath.begin(), ntPath.begin() + 10, GetWindowsPath());
    }
    if (boost::istarts_with(ntPath, L"windows"))
    {
        ntPath.replace(ntPath.begin(), ntPath.begin() + 7, GetWindowsPath());
    }
    return ntPath;
}

TEST(Win32Path, NtPathDoubleQuestions)
{
    ASSERT_EQ(L"C:\\Example", NtPathToWin32Path(L"\\??\\C:\\Example"));
}

TEST(Win32Path, NtPathUncBegin)
{
    ASSERT_EQ(L"C:\\Example", NtPathToWin32Path(L"\\\\?\\C:\\Example"));
}

TEST(Win32Path, NtPathWindowsStart)
{
    ASSERT_EQ(GetCombinedPath(GetWindowsPath(), L"Hello\\World"), NtPathToWin32Path(L"\\Windows\\Hello\\World"));
}

TEST(Win32Path, NtPathSystemrootStart)
{
    ASSERT_EQ(GetCombinedPath(GetWindowsPath(), L"Hello\\World"), NtPathToWin32Path(L"\\SystemRoot\\Hello\\World"));
}

TEST(Win32Path, NtPathGlobalRootSystemRoot)
{
    ASSERT_EQ(GetCombinedPath(GetWindowsPath(), L"Hello\\World"), NtPathToWin32Path(L"\\globalroot\\SystemRoot\\Hello\\World"));
}

but I'd be strongly surprised if there's not some API, native or otherwise, which will convert these into Win32 path names. Does such an API exist?


问:
How to make all the attributions in the css selector into one line with vim?
Here is my css part of css file.

```<code>body{
    width:1100px;
    height:800px;
}
div.main{
    margin:20px auto 0 auto;
    background-color:#f7f7f7;
}
</code>```

I want to rewrite it as below.

```<code>body{width:1100px;height:800px;}
div.main{margin:20px auto 0 auto;background-color:#f7f7f7;}
</code>```

All attritutions and values rewritten as only one line,is there a smarty vim command to do the job?

答:
One option would be

```<code>g/{/,/}/j
</code>```

which breaks down as

```<code>g        start a global command
{        search for {
,/}/    for each match, set a range up until the }
j       join the range
</code>```

Note that this might be to naïve as-is. This doesn't take into account nested brackets. You might first want to set a visual range to the textblock you like to change.

ContentLicense: CC BY-SA 3.0

Body:
Here is my css part of css file.

body{
    width:1100px;
    height:800px;
}
div.main{
    margin:20px auto 0 auto;
    background-color:#f7f7f7;
}

I want to rewrite it as below.

body{width:1100px;height:800px;}
div.main{margin:20px auto 0 auto;background-color:#f7f7f7;}

All attritutions and values rewritten as only one line,is there a smarty vim command to do the job?

Body:
One option would be

g/{/,/}/j

which breaks down as

g        start a global command
{        search for {
,/}/    for each match, set a range up until the }
j       join the range

Note that this might be to naïve as-is. This doesn't take into account nested brackets. You might first want to set a visual range to the textblock you like to change.


问:
Date time type in postgresql
I need storage 2 colums with date_time in my postgresql DB table.

```<code>date_time            date_time_human
676484556463346      09.06.2017 9:38:00
</code>```

date_time - like oracle timestamp( this date in seconds)
date_time_human - date in normal form

What type of field should be?

```<code>INSERT INTO tabl (date_time, date_time_human) VALUES(now(), now())
</code>```

答:
It seems to me that if you have the same value in these fields, then there is no sense in starting it twice.
Create one field of type timestamp. And in seconds you can output and record using functions.
Data Type Formatting Functions</p>

Title: Date time type in postgresql

Body:
I need storage 2 colums with date_time in my postgresql DB table.

date_time            date_time_human
676484556463346      09.06.2017 9:38:00

date_time - like oracle timestamp( this date in seconds)
date_time_human - date in normal form

What type of field should be?

INSERT INTO tabl (date_time, date_time_human) VALUES(now(), now())


问:
Android Studio 2.3 - Cannot lock System Folders
I'm new to Android App Development and am using Android Studio 2.3 to learn it. I've been working on it for a week now but now I'm getting the following error:

port lock error

Currently I'm working on a project so I need this error to be resolved.
Please help.

答:
its problem with androidstudio.exe download from here its official site to download studio.

if any query after install new studio ask me.


问:
Duplicate Record display in Table
I'm working on software everything work perfectly, but when I print its record from multiple table is show duplicate entry for each row

I have no idea why this thing happened.

Here is my Query which gets data from table and display using PHP

```<code>Select item_id,item_name,rci.item_shape,
remaing_quantity,rci.child_date from rads_childrenitem rci ,
add_itemchildren aic where aic.id = rci.item_id group by
rci.id,item_name,rci.item_shape, remaing_quantity order by rci.id desc
</code>```

Image attached for better understanding.

答:
Add DISTINCT in your query.

```<code>Select DISTINCT (item_id)
     , item_name
     , rci.item_shape
     , remaing_quantity
     , rci.child_date
  from rads_childrenitem rci
     , add_itemchildren aic
 where aic.id = rci.item_id
 group
    by item_name
     ,rci.id
     , item_name
     , rci.item_shape
     , remaing_quantity
 order
    by rci.id desc
</code>```

Read more about it from here : https://dev.mysql.com/doc/refman/5.7/en/distinct-optimization.html

Title: Duplicate Record display in Table

Body:
I'm working on software everything work perfectly, but when I print its record from multiple table is show duplicate entry for each row

I have no idea why this thing happened.

Here is my Query which gets data from table and display using PHP

Select item_id,item_name,rci.item_shape,
remaing_quantity,rci.child_date from rads_childrenitem rci ,
add_itemchildren aic where aic.id = rci.item_id group by
rci.id,item_name,rci.item_shape, remaing_quantity order by rci.id desc

Image attached for better understanding.

Body:
Add DISTINCT in your query.

Select DISTINCT (item_id)
     , item_name
     , rci.item_shape
     , remaing_quantity
     , rci.child_date
  from rads_childrenitem rci
     , add_itemchildren aic
 where aic.id = rci.item_id
 group
    by item_name
     ,rci.id
     , item_name
     , rci.item_shape
     , remaing_quantity
 order
    by rci.id desc

Read more about it from here : https://dev.mysql.com/doc/refman/5.7/en/distinct-optimization.html


问:
Facebook login give me already authorized this app everytime ios
My app should implement login with facebook but I have noticed that every time I want to login the facebook tell me you are already authorize this app , the question if I already authorized the app the facebook should return automatically without pressing the okey button as I saw in other applications ?

see link :http://dugars.com/images/t13_7_authorize.jpg

答:
You should check if there is a current session before logging in with FBSDKLoginManager. Do not use [loginManager logout] before logging in.

```<code>if ([FBSDKAccessToken currentAccessToken])
 {
      NSLog(@"Token is available : %@",[[FBSDKAccessToken currentAccessToken]tokenString]);
      // Now get details using graphpath.
 } else {
     // login with permissions using FBSDKLoginManager and get details using graphpath in completion

 }
</code>```

Body:
You should check if there is a current session before logging in with FBSDKLoginManager. Do not use [loginManager logout] before logging in.

if ([FBSDKAccessToken currentAccessToken])
 {
      NSLog(@"Token is available : %@",[[FBSDKAccessToken currentAccessToken]tokenString]);
      // Now get details using graphpath.
 } else {
     // login with permissions using FBSDKLoginManager and get details using graphpath in completion

 }


问:
Android - How can I upload multiple files in one request
I wanted to upload multiple files in one request. I can upload file to server, but I cann't upload more then one file. here is my code

```<code>try {
        String uploadId = UUID.randomUUID().toString();
        uploadReceiver.setDelegate((SingleUploadBroadcastReceiver.Delegate) this);
        uploadReceiver.setUploadID(uploadId);

        //Creating a multi part request
        new MultipartUploadRequest(this, uploadId, UPLOAD_URL)
                .addFileToUpload(path, "p_url[]")
                .addParameter("phone_number", phone_number)
                .addHeader("Authorization", "Bearer " + token) //Adding token
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .startUpload(); //Starting the upload

    } catch (Exception exc) {
        Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
    }
</code>```

I try to upload image files. This is start image picker

```<code> ImagePicker.create(this)
                .folderMode(true) // set folder mode (false by default)
                .folderTitle("Folder") // folder selection title
                .imageTitle("Tap to select") // image selection title
                .single() // single mode
                .multi() // multi mode (default mode)
                .limit(10) // max images can be selected (999 by default)
                .showCamera(true) // show camera or not (true by default)
                .imageDirectory("Camera")   // captured image directory name ("Camera" folder by default)
                .origin(images) // original selected images, used in multi mode
                .start(PICK_FILE_REQUEST); // start image picker activity with request code
</code>```

And Activity result

```<code>if (requestCode == PICK_FILE_REQUEST && resultCode == RESULT_OK && data != null) {

        filePath = data.getData();
        images = data.getParcelableArrayListExtra(ImagePickerActivity.INTENT_EXTRA_SELECTED_IMAGES);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < images.size(); i++) {
            Log.d("____IMAGES_____", images.get(i).getPath());
            }
        }
</code>```

Log show this information

```<code>D/____IMAGES_____: /storage/emulated/0/DCIM/ios-logo1.png
D/____IMAGES_____: /storage/emulated/0/DCIM/Screenshot_1491908860.png
D/____IMAGES_____: /storage/emulated/0/DCIM/product_4.png
</code>```

And I try to send multiple file like this

```<code>try {
        String uploadId = UUID.randomUUID().toString();
        uploadReceiver.setDelegate((SingleUploadBroadcastReceiver.Delegate) this);
        uploadReceiver.setUploadID(uploadId);

        //Creating a multi part request
        new MultipartUploadRequest(this, uploadId, UPLOAD_URL)
                .addFileToUpload(path1, "p_url[]")
                .addFileToUpload(path2, "p_url[]")
                .addParameter("phone_number", phone_number)
                .addHeader("Authorization", "Bearer " + token) //Adding token
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .startUpload(); //Starting the upload

    } catch (Exception exc) {
        Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
    }
</code>```

It is work fine, but I choose files with file chooser. And files count will be dynamical. Above code I get files count static. User selected files, and my programm must to upload all of them

答:
What you can do is make the object of MultipartUploadRequest and looping through your files to upload you can add the files to that object.</p>

```<code>MultipartUploadRequest request = new MultipartUploadRequest(this, uploadId, UPLOAD_URL);

    for(int i=0; i<filesToUploadCount; i++){
        //change path and data according to your files
        request.addFileToUpload(pathForFile, "p_url[i]");
    }
    request.addParameter("phone_number", phone_number);
    request.addHeader("Authorization", "Bearer " + token); //Adding token
    request.setNotificationConfig(new UploadNotificationConfig());
    request.setMaxRetries(2);
    request.startUpload();
</code>```

Body:
I wanted to upload multiple files in one request. I can upload file to server, but I cann't upload more then one file. here is my code

try {
        String uploadId = UUID.randomUUID().toString();
        uploadReceiver.setDelegate((SingleUploadBroadcastReceiver.Delegate) this);
        uploadReceiver.setUploadID(uploadId);

        //Creating a multi part request
        new MultipartUploadRequest(this, uploadId, UPLOAD_URL)
                .addFileToUpload(path, "p_url[]")
                .addParameter("phone_number", phone_number)
                .addHeader("Authorization", "Bearer " + token) //Adding token
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .startUpload(); //Starting the upload

    } catch (Exception exc) {
        Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
    }

I try to upload image files. This is start image picker

 ImagePicker.create(this)
                .folderMode(true) // set folder mode (false by default)
                .folderTitle("Folder") // folder selection title
                .imageTitle("Tap to select") // image selection title
                .single() // single mode
                .multi() // multi mode (default mode)
                .limit(10) // max images can be selected (999 by default)
                .showCamera(true) // show camera or not (true by default)
                .imageDirectory("Camera")   // captured image directory name ("Camera" folder by default)
                .origin(images) // original selected images, used in multi mode
                .start(PICK_FILE_REQUEST); // start image picker activity with request code

And Activity result

if (requestCode == PICK_FILE_REQUEST && resultCode == RESULT_OK && data != null) {

        filePath = data.getData();
        images = data.getParcelableArrayListExtra(ImagePickerActivity.INTENT_EXTRA_SELECTED_IMAGES);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < images.size(); i++) {
            Log.d("____IMAGES_____", images.get(i).getPath());
            }
        }

Log show this information

D/____IMAGES_____: /storage/emulated/0/DCIM/ios-logo1.png
D/____IMAGES_____: /storage/emulated/0/DCIM/Screenshot_1491908860.png
D/____IMAGES_____: /storage/emulated/0/DCIM/product_4.png

And I try to send multiple file like this

try {
        String uploadId = UUID.randomUUID().toString();
        uploadReceiver.setDelegate((SingleUploadBroadcastReceiver.Delegate) this);
        uploadReceiver.setUploadID(uploadId);

        //Creating a multi part request
        new MultipartUploadRequest(this, uploadId, UPLOAD_URL)
                .addFileToUpload(path1, "p_url[]")
                .addFileToUpload(path2, "p_url[]")
                .addParameter("phone_number", phone_number)
                .addHeader("Authorization", "Bearer " + token) //Adding token
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .startUpload(); //Starting the upload

    } catch (Exception exc) {
        Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
    }

It is work fine, but I choose files with file chooser. And files count will be dynamical. Above code I get files count static. User selected files, and my programm must to upload all of them

Body:
What you can do is make the object of MultipartUploadRequest and looping through your files to upload you can add the files to that object.

MultipartUploadRequest request = new MultipartUploadRequest(this, uploadId, UPLOAD_URL);

    for(int i=0; i<filesToUploadCount; i++){
        //change path and data according to your files
        request.addFileToUpload(pathForFile, "p_url[i]");
    }
    request.addParameter("phone_number", phone_number);
    request.addHeader("Authorization", "Bearer " + token); //Adding token
    request.setNotificationConfig(new UploadNotificationConfig());
    request.setMaxRetries(2);
    request.startUpload();


答:
Use Common table expression :</p>

```<code>   DECLARE @StartDT DATETIME = '2017-01-01'
   DECLARE @EndDT DATETIME = '2017-01-05'
   DECLARE @Id INT = 1

   ;WITH CTE (_id , _Date)AS
   (
     SELECT @Id , @StartDT
     UNION ALL
     SELECT @Id , DATEADD(DAY,1,_Date)
     FROM CTE
     WHERE _Date < @EndDT
    )

   SELECT  * FROM CTE
</code>```

Title: sql server print all dates between two date columns

Body:
i have a table containing 3 columns. ID,Start_Date,End_Date.i want to print all the days between Start_Date and End_Date along with ID.
For Example i have table

+----+------------+------------+
| ID | Start_Date | End_Date   |
+----+------------+------------+
| 1  | 2017-01-01 | 2017-01-05 |
+----+------------+------------+

and i want result like

+----+------------+
| ID | Date       |
+----+------------+
| 1  | 2017-01-01 |
| 1  | 2017-01-02 |
| 1  | 2017-01-03 |
| 1  | 2017-01-04 |
| 1  | 2017-04-05 |
+----+------------+

Body:
Use Common table expression :

   DECLARE @StartDT DATETIME = '2017-01-01'
   DECLARE @EndDT DATETIME = '2017-01-05'
   DECLARE @Id INT = 1

   ;WITH CTE (_id , _Date)AS
   (
     SELECT @Id , @StartDT
     UNION ALL
     SELECT @Id , DATEADD(DAY,1,_Date)
     FROM CTE
     WHERE _Date < @EndDT
    )

   SELECT  * FROM CTE


问:
How to get JSON output as NSString
Working in Objective-C where I need to parse JSON. So after parsing successfully.

Below is my code :

```<code>-(instancetype)initWithDict:(NSDictionary *)dict {
    self = [super init];
    if (self) {

        if ([dict isKindOfClass:[NSDictionary class]]) {
            self.allKeysArray = [dict allKeys];

 if ([self.allKeysArray containsObject:@"nDetail"]) {

                if ([dict valueForKey:@"nDetail"]) {

 _tempNutrientArray = [[[dict valueForKey:@"nDetail"] valueForKey:@"nTypeCode"] valueForKey:@"value"];
         }
     }
 }

NSLog(@"N Array : @%@", _tempNutrientArray);

}
</code>```

I need to convert this in string format each an every value.

My output :

```<code>N Array : @(
    "ENER-",
    FAT,
    FASAT,
    CHOAVL,
    "SUGAR-",
    "PRO-",
    NACL
)
</code>```

Required Output :

```<code> N Array : @("ENER-","FAT","FASAT","CHOAVL","SUGAR-","PRO-","NACL")
</code>```

So how should I convert it to string format. Please help me.

答:
In your case you have create one variable that store your whole string from your response after that use my code.

```<code> NSString *tempstring = @"ENER- FAT FASAT CHOAVL SUGAR- PRO- NACL";
 NSArray *arr = [tempstring componentsSeparatedByString:@" "];
 NSLog(@"%@",arr);
 NSLog(@"First value : %@",[arr objectAtIndex:0]);
 NSLog(@"Second value : %@",[arr objectAtIndex:1]);
 NSLog(@"Third value : %@",[arr objectAtIndex:2]);
</code>```

now check arr value you got all string in array that you want .

Output :

```<code>(
    "ENER-",
    FAT,
    FASAT,
    CHOAVL,
    "SUGAR-",
    "PRO-",
    NACL
)

First value : ENER-
Second value : FAT
Third value : FASAT
</code>```

Title: How to get JSON output as NSString

Body:
Working in Objective-C where I need to parse JSON. So after parsing successfully.

Below is my code :

-(instancetype)initWithDict:(NSDictionary *)dict {
    self = [super init];
    if (self) {

        if ([dict isKindOfClass:[NSDictionary class]]) {
            self.allKeysArray = [dict allKeys];

 if ([self.allKeysArray containsObject:@"nDetail"]) {

                if ([dict valueForKey:@"nDetail"]) {

 _tempNutrientArray = [[[dict valueForKey:@"nDetail"] valueForKey:@"nTypeCode"] valueForKey:@"value"];
         }
     }
 }

NSLog(@"N Array : @%@", _tempNutrientArray);

}

I need to convert this in string format each an every value.

My output :

N Array : @(
    "ENER-",
    FAT,
    FASAT,
    CHOAVL,
    "SUGAR-",
    "PRO-",
    NACL
)

Required Output :

 N Array : @("ENER-","FAT","FASAT","CHOAVL","SUGAR-","PRO-","NACL")

So how should I convert it to string format. Please help me.

Body:
In your case you have create one variable that store your whole string from your response after that use my code.

 NSString *tempstring = @"ENER- FAT FASAT CHOAVL SUGAR- PRO- NACL";
 NSArray *arr = [tempstring componentsSeparatedByString:@" "];
 NSLog(@"%@",arr);
 NSLog(@"First value : %@",[arr objectAtIndex:0]);
 NSLog(@"Second value : %@",[arr objectAtIndex:1]);
 NSLog(@"Third value : %@",[arr objectAtIndex:2]);

now check arr value you got all string in array that you want .

Output :

(
    "ENER-",
    FAT,
    FASAT,
    CHOAVL,
    "SUGAR-",
    "PRO-",
    NACL
)

First value : ENER-
Second value : FAT
Third value : FASAT


问:
TFS 2010: Automating builds based on Labels?
I need to set up an automated CI build that executes in the following order:

1) Label all files in source control with new label.
2) Get only files that have the new label
3) Build + version + Test

I need to be certain that I am only building files that I have labeled.

All ideas will be appreciated.

Thanks

答:
If anyone is interested, TFS 2010 support this out-of-the-box.

Build process:

After the latest version has been taken (Changeset1), TFS "lable" the code in the "workspace". Now, if there had been another check-in (Changeset2) just before this label is applied, TFS will ONLY lable the previous changeset (Changeset1). - This I believe the correct behaviour. Changeset2 should go to the next build.

I initially thought TFS labels the second check-in even though the "Workspace" only has changeset1.


问:
how do i convert int to byte and back
given a 64bit int I need to split it into 4 x 2bytes int.

for example decimal 66309 is 0000 0000 0000 0001 0000 0011 0000 0101

I need to convert this into an array of 4 ints {0, 1, 3, 5}. How can I do it in lua?

答:
First, the conversion of 66309 into four 16 bit integers wouldn't be {0, 1, 3, 5}, but {0, 0, 1, 773}. In your example, you are splitting it into 8 bit integers. The below does 16 bit integers.

```<code>local int = 66309
local t = {}
for i = 0, 3 do
    t[i+1] = (int >> (i * 16)) & 0xFFFF
end
</code>```

If you want it to be 8 bit integers change the 3 in the loop to 7, the 16 in the shift expression to an 8, and the hex mask 0xFFFF to 0xFF.

And finally, this only works for Lua 5.3. You cannot accurately represent a 64 bit integer in Lua before this version without external libraries.

Title: how do i convert int to byte and back

Body:
First, the conversion of 66309 into four 16 bit integers wouldn't be {0, 1, 3, 5}, but {0, 0, 1, 773}. In your example, you are splitting it into 8 bit integers. The below does 16 bit integers.

local int = 66309
local t = {}
for i = 0, 3 do
    t[i+1] = (int >> (i * 16)) & 0xFFFF
end

If you want it to be 8 bit integers change the 3 in the loop to 7, the 16 in the shift expression to an 8, and the hex mask 0xFFFF to 0xFF.

And finally, this only works for Lua 5.3. You cannot accurately represent a 64 bit integer in Lua before this version without external libraries.


问:
Multiple "Error CS0234" causing MSBuild to fail in VSTS
I have an MVC5 web application, written in VS2017. It targets .NET 4.6.1. On my development machine it builds and runs without a problem. I can even use the Publish feature in VS to publish it to my server and it works perfectly.

I'm now trying to instantiate CI in VSTS, something I've done successfully plenty of times before with other projects. When the Build runs, the MSBuild task fails. The logs show many instances of basically the same CS0234 error, relating to missing references. For example:

I've done a lot of Googling on this and tried all sorts of things. I've removed and re-added NuGet packages. I've made sure that the Copy Local attriubute of all my references is True. I've tried manually specifying the C# Language Version in the project's advanced build settings (I'm clutching at straws!).

Initially I was trying to get this working with a locally-hosted agent (which builds other projects without problems), and so I've gone onto that machine, installed VS2017 and rebuilt and run the project in VS on it, again without a problem. In any case, I don't think the issue relates to the machine running the build agent because I get the same errors when I use an Azure-hosted build agent.

Most of the questions I've found on SO and elsewhere relate to a particular reference apparently being missing. As you can see, in my case it seems like just about ALL the referenced assemblies are missing!

I've shared the full Build task log here. You'll see the bulk of the errors begin on line 1059, but there are warnings of the problems to come on line 129 (amongst others), which says:

```<code>##[warning]C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(1964,5): Warning MSB3245: Could not resolve this reference. Could not locate the assembly "EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
</code>```

So obviously the necessary files are missing, but why? Why would they be missing even on the Azure-hosted agent machine? And, most importantly, how do I restore/install them where they need to be? As I say, the Solution builds fine on my own machine.

答:
Refer to these steps below to modify your build definition:

Add NuGet Installer task (Path to solution or packages.config: **\*.sln; Installation Type: Restore)

Change NuGet Version to 4.0 in Advanced section

Queue build with Hosted VS2017 agent.

Body:
I have an MVC5 web application, written in VS2017. It targets .NET 4.6.1. On my development machine it builds and runs without a problem. I can even use the Publish feature in VS to publish it to my server and it works perfectly.

I'm now trying to instantiate CI in VSTS, something I've done successfully plenty of times before with other projects. When the Build runs, the MSBuild task fails. The logs show many instances of basically the same CS0234 error, relating to missing references. For example:

I've done a lot of Googling on this and tried all sorts of things. I've removed and re-added NuGet packages. I've made sure that the Copy Local attriubute of all my references is True. I've tried manually specifying the C# Language Version in the project's advanced build settings (I'm clutching at straws!).

Initially I was trying to get this working with a locally-hosted agent (which builds other projects without problems), and so I've gone onto that machine, installed VS2017 and rebuilt and run the project in VS on it, again without a problem. In any case, I don't think the issue relates to the machine running the build agent because I get the same errors when I use an Azure-hosted build agent.

Most of the questions I've found on SO and elsewhere relate to a particular reference apparently being missing. As you can see, in my case it seems like just about ALL the referenced assemblies are missing!

I've shared the full Build task log here. You'll see the bulk of the errors begin on line 1059, but there are warnings of the problems to come on line 129 (amongst others), which says:

##[warning]C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(1964,5): Warning MSB3245: Could not resolve this reference. Could not locate the assembly "EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.

So obviously the necessary files are missing, but why? Why would they be missing even on the Azure-hosted agent machine? And, most importantly, how do I restore/install them where they need to be? As I say, the Solution builds fine on my own machine.


问:
Error in wordpress customizr theme
yesterday I installed  customizr theme and after turning it on my site crashed and i'm receiving error:

```<code>Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting ',' or ')' in /wp-content/themes/customizr/core/functions.php on line 3152
</code>```

Here's the mentioned line:

```<code>else if ( class_exists($cb[0]) && isset($cb[0]::$instance) && method_exists($cb[0]::$instance, $cb[1]) ) {
    $to_return = call_user_func( array( $cb[0]::$instance ,  $cb[1] ), $params );
</code>```

I will be really gratefull if someone could fix this error

答:
Few things I found disturbing in your code, I dont know what these are representing so I would go with my instance.

1) you are calling method_exists with static variable as first argurment, it should be class name, in your case only $cb[0].

2) while calling call_user_func you are again passing static variable. What should come here as first argument depends upon you class structure. Any way I think  call_user_func( array( $cb[0],  $cb[1] ), $params ); should work

Title: Error in wordpress customizr theme

Body:
yesterday I installed  customizr theme and after turning it on my site crashed and i'm receiving error:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting ',' or ')' in /wp-content/themes/customizr/core/functions.php on line 3152

Here's the mentioned line:

else if ( class_exists($cb[0]) && isset($cb[0]::$instance) && method_exists($cb[0]::$instance, $cb[1]) ) {
    $to_return = call_user_func( array( $cb[0]::$instance ,  $cb[1] ), $params );

I will be really gratefull if someone could fix this error


问:
Storing keys of inconsistent levels of dictionary
The structure of the code is like:

```<code>def foo(dicc, cases):
    if cases==1:
        return dicc['a']
    if cases==2:
        return dicc['b']['c']
</code>```

dicc is not changeable. I want to eliminate the switch-like usage of cases. I thought about creating a dictionary outside the function like info={1:'a',2:'b'} and call like dicc[info[cases]], but it won't work for case 2. Does this mean I have to create a class for each case? What is the common practice to deal with the problem?

答:
Not sure if this is what you want, but you can try this</p>

```<code>info=[['a'], ['b', 'c']]

def foo(dicc, cases):
    result = dicc
    for k in info[cases-1]:
        result = result[k]
    return result
</code>```

Body:
The structure of the code is like:

def foo(dicc, cases):
    if cases==1:
        return dicc['a']
    if cases==2:
        return dicc['b']['c']

dicc is not changeable. I want to eliminate the switch-like usage of cases. I thought about creating a dictionary outside the function like info={1:'a',2:'b'} and call like dicc[info[cases]], but it won't work for case 2. Does this mean I have to create a class for each case? What is the common practice to deal with the problem?

Body:
Not sure if this is what you want, but you can try this

info=[['a'], ['b', 'c']]

def foo(dicc, cases):
    result = dicc
    for k in info[cases-1]:
        result = result[k]
    return result


问:
Is there a way to normalize / zero point SVG path data?
I have a path that can plot it self anywhere on the page. So I will have a path that is in the middle of the container. The path data is something like:

```<code>M 100 100 L 100 200 L 200 200 L 200 100 z
</code>```

That creates a box at the coordinates x 100, y 100. But I want to normalize it or zero point it so that the coordinates will end up:

```<code>M 0 0 L 0 100 L 100 100 L 100 0 z
</code>```

And then I set the x to 100 and y to 100. In this example, I can do simple math because the path is a square but if it's not, for example, if it's a line going from right to left or a complex path, is there code that will zero point it?

Please ask for clarification if needed instead of downvoting.

Here is the source code of the Path class in Flex which uses AS3 (like JavaScript) looks like it has functions that may help get the bounds using the Path class.

FYI To inform readers of my tag selection Flex and FXG is the markup language that is a sibling of SVG (both created by Adobe). The path data is the same for both languages and the markup are almost 1 to 1. An answer that works in one may work in another. Also, the DOMParser can parse SVG and I can use that if it will help.

答: I think it is simple math, regardless of the complexity of your path. Just iterate over the points and identify the minimum x and y values. Et voilà! That is your "zero point" offset. You have already unconsciously applied the same algorithm to your square, where it's obvious.</p>

Body:
I have a path that can plot it self anywhere on the page. So I will have a path that is in the middle of the container. The path data is something like:

M 100 100 L 100 200 L 200 200 L 200 100 z

That creates a box at the coordinates x 100, y 100. But I want to normalize it or zero point it so that the coordinates will end up:

M 0 0 L 0 100 L 100 100 L 100 0 z

And then I set the x to 100 and y to 100. In this example, I can do simple math because the path is a square but if it's not, for example, if it's a line going from right to left or a complex path, is there code that will zero point it?

Please ask for clarification if needed instead of downvoting.

Here is the source code of the Path class in Flex which uses AS3 (like JavaScript) looks like it has functions that may help get the bounds using the Path class.

FYI To inform readers of my tag selection Flex and FXG is the markup language that is a sibling of SVG (both created by Adobe). The path data is the same for both languages and the markup are almost 1 to 1. An answer that works in one may work in another. Also, the DOMParser can parse SVG and I can use that if it will help.


问:
Is there any benefit of checking typeof a === "undefined" instead of a === undefined?
I have been using typeof operator to check if a variable is not defined like this:

```<code>if( typeof numLines === "undefined" ){
  // do something
}
</code>```

But the same can be achieved using:

```<code>if( numLines === undefined ){
  // do something
}
</code>```

As far as I remember, I had read somewhere that the typeof approach is better but now I think why should I use a slightly longer statement if there is no benefit at all in that.  So my questions are:

Is there really any benefit in sticking to typeof approach for such checks?

Can you provide some examples where one approach is better than the other?

Thanks.

答:
According to a related question undefined is not assured to be the thing you expect it to be:

```<code>var undefined = 'uh oh'

if (numLines === undefined) {
  // Seems safe but isn't
}
else if (typeof(numlines) == 'undefined') {
  // Actually gets it.
}
</code>```

It's very odd that undefined is not nailed down in JavaScript, but that's how it is with the ECMA standard.

Body:
I have been using typeof operator to check if a variable is not defined like this:

if( typeof numLines === "undefined" ){
  // do something
}

But the same can be achieved using:

if( numLines === undefined ){
  // do something
}

As far as I remember, I had read somewhere that the typeof approach is better but now I think why should I use a slightly longer statement if there is no benefit at all in that.  So my questions are:

Is there really any benefit in sticking to typeof approach for such checks?

Can you provide some examples where one approach is better than the other?

Thanks.

Body:
According to a related question undefined is not assured to be the thing you expect it to be:

var undefined = 'uh oh'

if (numLines === undefined) {
  // Seems safe but isn't
}
else if (typeof(numlines) == 'undefined') {
  // Actually gets it.
}

It's very odd that undefined is not nailed down in JavaScript, but that's how it is with the ECMA standard.


问:
Save last row number as variable after opening the workbook for the later use
I want to save the last row number used in a particular sheet at Workbook_Open() for the later use in other modules.
So far I have this code:

ThisWorkbook:

```<code>Public last_row as long

Private Sub Workbook_Open()
    last_row = Worksheets("Sheet1").Cells(Rows.count, 1).End(xlUp).Row
    MsgBox ("This is the last row number: " & last_row)
End Sub
</code>```

I get the pop-up message correctly, like "This is the last row number: 25", when I open the workbook. This is a desired output.

Module 1:

```<code>Sub ABC()
    MsgBox ("This is the last row number: " & last_row)
End Sub
</code>```

But when I run the Module 1, "This is the last row number: " message is what I get.

So, I am failing in storing the "last_row" variable as public. What am I doing wrong? Thanks in advance!

答:
To answer your question specifically, modify your code like this:

```<code>Sub ABC()
   MsgBox ("This is the last row number: " & ThisWorkbook.last_row)
End Sub
</code>```

To use a public variable declared in ThisWorkbook module you must qualify it with the module name.

Notes:

You should enable Option Explicit in your VBE. It would have told you that last_row is not declared. A good habit to have;

Although this solution will work, I 100% agree with @Siddharth Rout that this approach is a conceptually bad idea - you will end up with an unstable (unpredictable) code.

There are many better ways to solve your problem; the simpest is - save your last row number to a cell on a hidden sheet.

Body:
I want to save the last row number used in a particular sheet at Workbook_Open() for the later use in other modules.
So far I have this code:

ThisWorkbook:

Public last_row as long

Private Sub Workbook_Open()
    last_row = Worksheets("Sheet1").Cells(Rows.count, 1).End(xlUp).Row
    MsgBox ("This is the last row number: " & last_row)
End Sub

I get the pop-up message correctly, like "This is the last row number: 25", when I open the workbook. This is a desired output.

Module 1:

Sub ABC()
    MsgBox ("This is the last row number: " & last_row)
End Sub

But when I run the Module 1, "This is the last row number: " message is what I get.

So, I am failing in storing the "last_row" variable as public. What am I doing wrong? Thanks in advance!

Body:
To answer your question specifically, modify your code like this:

Sub ABC()
   MsgBox ("This is the last row number: " & ThisWorkbook.last_row)
End Sub

To use a public variable declared in ThisWorkbook module you must qualify it with the module name.

Notes:

You should enable Option Explicit in your VBE. It would have told you that last_row is not declared. A good habit to have;

Although this solution will work, I 100% agree with @Siddharth Rout that this approach is a conceptually bad idea - you will end up with an unstable (unpredictable) code.

There are many better ways to solve your problem; the simpest is - save your last row number to a cell on a hidden sheet.


问:
Trigger other Property from binding
I have two entries in a page in my Xamarin Forms app. The Text properties  of these two entries are binded with a realm object. Thats a two way binding, so whenever I type in a value in either of these fields, my realm object updates and vice versa. This works just fine.

But my requirement is, when the user changes value in one entry, the value in the other entry also need to be re-calculated and updated. It's like having two entries for a unit conversion (e.g mm-inch) - when you change the mm value, it updates the inch value in the other field, and vice versa. How can I achieve this behaviour?

```<code><Label Text="Speed" />
<Entry x:Name="SpeedEntry" Text="{Binding Speed, Mode=TwoWay}" />
<Label  Text="Depth" />
<Entry x:Name="DepthEntry" Text="{Binding Depth, Mode=TwoWay}" />
</code>```

答:
It sounds like you're following the MVVM pattern (incase you don't you should, because what you're doing is a prime example for how and why to use it)

I suggest putting the calculation in the ViewModel since it increases the opportunity for code reuse (across platforms and possible across projects)

One way of doing it is the following code snippet - there are plenty of others - including Fody.PropertyChanged (reducing the amount of plumbing code needed), Reactive.UI (for reactive programming - also reducing the plumbing) and similar libraries.

```<code>using System.ComponentModel;
using System.Runtime.CompilerServices;

public class ConversionViewModel : INotifyPropertyChanged
{

    private double depth;

    private double speed;

    public double Speed {
        get { return this.speed; }
        set {
            this.speed = value;
            this.OnPropertyChanged();
            this.Depth = this.CalculateDepth();
        }
    }

    public double Depth {
        get { return this.depth; }
        set {
            this.depth = value;
            this.OnPropertyChanged();
            this.Speed = this.CalculateSpeed();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private double CalculateSpeed()
    {
        // do your calculation
        return 0;
    }

    private double CalculateDepth()
    {
        // do your calculation
        return 0;
    }

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

}
</code>```

You could move the calculation to the properties getters to only execute it, when it's actually needed. If it's a relative CPU intensive calculation you'd probably want to cache the result in a field and invalidate it when some properties change.

Title: Trigger other Property from binding

Body:
I have two entries in a page in my Xamarin Forms app. The Text properties  of these two entries are binded with a realm object. Thats a two way binding, so whenever I type in a value in either of these fields, my realm object updates and vice versa. This works just fine.

But my requirement is, when the user changes value in one entry, the value in the other entry also need to be re-calculated and updated. It's like having two entries for a unit conversion (e.g mm-inch) - when you change the mm value, it updates the inch value in the other field, and vice versa. How can I achieve this behaviour?

<Entry x:Name="SpeedEntry" Text="{Binding Speed, Mode=TwoWay}" />

<Entry x:Name="DepthEntry" Text="{Binding Depth, Mode=TwoWay}" />

Body:
It sounds like you're following the MVVM pattern (incase you don't you should, because what you're doing is a prime example for how and why to use it)

I suggest putting the calculation in the ViewModel since it increases the opportunity for code reuse (across platforms and possible across projects)

One way of doing it is the following code snippet - there are plenty of others - including Fody.PropertyChanged (reducing the amount of plumbing code needed), Reactive.UI (for reactive programming - also reducing the plumbing) and similar libraries.

using System.ComponentModel;
using System.Runtime.CompilerServices;

public class ConversionViewModel : INotifyPropertyChanged
{

    private double depth;

    private double speed;

    public double Speed {
        get { return this.speed; }
        set {
            this.speed = value;
            this.OnPropertyChanged();
            this.Depth = this.CalculateDepth();
        }
    }

    public double Depth {
        get { return this.depth; }
        set {
            this.depth = value;
            this.OnPropertyChanged();
            this.Speed = this.CalculateSpeed();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private double CalculateSpeed()
    {
        // do your calculation
        return 0;
    }

    private double CalculateDepth()
    {
        // do your calculation
        return 0;
    }

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

}

You could move the calculation to the properties getters to only execute it, when it's actually needed. If it's a relative CPU intensive calculation you'd probably want to cache the result in a field and invalidate it when some properties change.


问:
How does Two way binding works in Angular 2?
I am trying to use two way binding between two of my components (Parent and Child component) and trying to detect the changes caused by this in ngOnChanges of both of the components. I am able to trigger ngOnChanges of Child component (Test Component) by changing input/output property of Parent component (App Component). However, I am not able to trigger ngOnChanges of Parent component by changing two way bound property in Child component.

Working Plunker can be found here: https://plnkr.co/edit/AGh6EM9l9ENMufb9JWPW?p=preview

```<code>import { Component, OnInit, OnChange, Output, Input, EventEmitter } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>
              <h3>Two Way Parent - {{twoWaySend}} </h3>

              <button (click) =  "oneWayButtonPressed()">Increase oneWay from Parent</button>
              <button (click) = "twoWayButtonPressed()">Increase TwoWay from Parent</button>
                <test-component [oneWayReceive] = 'oneWaySend'
              [(twoWayReceive)] = 'twoWaySend'></test-component>`
})
export class AppComponent implements OnChanges{
  name = 'Angular';
  oneWaySend = "You shall pass";
  twoWaySend = "You shall both ways";
  counter:int = 0;
  negativeCounter:int = 0;
  oneWayButtonPressed() {
    this.oneWaySend = `${this.oneWaySend} ${++this.counter}`;
  }
  twoWayButtonPressed() {
    this.twoWaySend = `${this.twoWaySend} ${--this.negativeCounter}`;
  }
  ngOnChanges() {
    console.log('ngOnchange Parent ' + this.twoWaySend);
  }
}

@Component({
  selector: 'test-component',
  template: `<h1>TestComponent {{name}}  {{oneWayReceive}}</h1>
            <h3>Two Way Child - {{twoWayReceive}}</h3>
            <button (click) = "twoWayButtonPressed()">Change Two Way from Child</button>`
})
export class TestComponent implements OnChange {
  @Input() oneWayReceive;
  @Input() twoWayReceive;
  @Output() twoWayReceiveChange: EventEmitter<string> = new EventEmitter<string>();
  name = 'Angular';
  negativeCounter = 0;
  ngOnChanges() {
    console.log(`OneWayReceive ${this.oneWayReceive}   TwoWayReceive ${this.twoWayReceive}`);
  }
  twoWayButtonPressed() {
    this.twoWayReceive = `${--this.negativeCounter}  ${this.twoWayReceive}`;
    this.twoWayReceiveChange.emit(this.twoWayReceive);
  }
}
</code>```

答: ngOnChanges is only called when a parent component passes a different value for an input of the component. You just shouldn't expect the parent component's ngOnChanges method to be called, since it doesn't have any input, nor any parent component.

Body:
I am trying to use two way binding between two of my components (Parent and Child component) and trying to detect the changes caused by this in ngOnChanges of both of the components. I am able to trigger ngOnChanges of Child component (Test Component) by changing input/output property of Parent component (App Component). However, I am not able to trigger ngOnChanges of Parent component by changing two way bound property in Child component.

Working Plunker can be found here: https://plnkr.co/edit/AGh6EM9l9ENMufb9JWPW?p=preview

import { Component, OnInit, OnChange, Output, Input, EventEmitter } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
Hello {{name}}

Two Way Parent - {{twoWaySend}}

              <button (click) =  "oneWayButtonPressed()">Increase oneWay from Parent</button>
              <button (click) = "twoWayButtonPressed()">Increase TwoWay from Parent</button>
                <test-component [oneWayReceive] = 'oneWaySend'
              [(twoWayReceive)] = 'twoWaySend'></test-component>`
})
export class AppComponent implements OnChanges{
  name = 'Angular';
  oneWaySend = "You shall pass";
  twoWaySend = "You shall both ways";
  counter:int = 0;
  negativeCounter:int = 0;
  oneWayButtonPressed() {
    this.oneWaySend = `${this.oneWaySend} ${++this.counter}`;
  }
  twoWayButtonPressed() {
    this.twoWaySend = `${this.twoWaySend} ${--this.negativeCounter}`;
  }
  ngOnChanges() {
    console.log('ngOnchange Parent ' + this.twoWaySend);
  }
}

@Component({
  selector: 'test-component',
  template: `
TestComponent {{name}}  {{oneWayReceive}}

Two Way Child - {{twoWayReceive}}

            <button (click) = "twoWayButtonPressed()">Change Two Way from Child</button>`
})
export class TestComponent implements OnChange {
  @Input() oneWayReceive;
  @Input() twoWayReceive;
  @Output() twoWayReceiveChange: EventEmitter<string> = new EventEmitter<string>();
  name = 'Angular';
  negativeCounter = 0;
  ngOnChanges() {
    console.log(`OneWayReceive ${this.oneWayReceive}   TwoWayReceive ${this.twoWayReceive}`);
  }
  twoWayButtonPressed() {
    this.twoWayReceive = `${--this.negativeCounter}  ${this.twoWayReceive}`;
    this.twoWayReceiveChange.emit(this.twoWayReceive);
  }
}


问:
Using WP Cli ib localhost
I use Openserver + WP + WP Cli (local).
And I want import all images (which I have uploaded in /wp-content/uploads) via WP Cli wp media import command.
How I must add the path to the media files if they in:
c:\OpenServer\domains\golf.loc\wp-content\uploads\
I use: wp media import ~/wp-content/uploads/**/*.jpg
and receive an Error: reason file doesn't exist. No images imported.
Thanks in advance.

答:
You have syntax error in the import,

check this ,

```<code>wp media import ~/wp-content/uploads/**\/*.jpg
</code>```

Title: Using WP Cli ib localhost

Body:
You have syntax error in the import,

check this ,

wp media import ~/wp-content/uploads/**\/*.jpg


问:
Does ACE+TAO/OpenDDS support a 64-bit GCC toolchain?
ACE+TAO: 6.3.2

OpenDDS: 3.11

Host compiler: GCC 5.4

As I cross-compile OpenDDS for Android, I'm looking at ACE_wrappers/build/arm/include/makeinclude/platform_android.GNU which appears to do the cross-compiling for ACE, and it appears to only build for ARM-v7a.

The reason why I say this is that I'm getting the following error when compiling the auto-generated files in my application ((which come from using opendds_idl on the *.idl), and after a bunch of "In file included from" lines, ends up with ...

```<code> [exec] /home/me/tools/crystax-ndk/sources/cxx-stl/gnu-libstdc++/5/include/limits:1601:7: internal compiler error: Illegal instruction
 [exec]        max() _GLIBCXX_USE_NOEXCEPT { return __FLT_MAX__; }
 [exec]        ^
</code>```

I've seen something like this before when I've compiled code which had some wrong flags for the CPU architecture. So my thinking is that maybe there's some incompatible toolchain settings on GCC which I use on my app and those settings used by ACE+TAO/OpenDDS? The CROSS_COMPILE variable in platform_android.GNU is arm-linux-androideabi- ... which as far as I know is a 32 bit toolchain, i.e., arm-v7a and I see no v8a references. And yet in my app I'm using aarch64-linux-android-5. Should these be compatible? Can the tool chain be changed?

What I'd like to do is build ACE+TAO/OpenDDS/my-application for the target architecture and ABI ... arm64: arm64-v8a and use the NDK toolchain and target ABI ... aarch64-linux-android-5:  arm64-v8a.

Thoughts?

答: This should be possible, but probably configuration files are outdated. First, update to ACE+TAO 6.3.4 which is the latest. Second, check the file include/makeinclude/platform_android.GNU and see if your target is there. It could be that some small updates are necessary, if so, please open a pull request at https://github.com/DOCGroup/ACE_TAO with the necessary changes. Search for arm-v7a and look if at that place a new check for arm-v8a is necessary.</p>

Body:
ACE+TAO: 6.3.2

OpenDDS: 3.11

Host compiler: GCC 5.4

As I cross-compile OpenDDS for Android, I'm looking at ACE_wrappers/build/arm/include/makeinclude/platform_android.GNU which appears to do the cross-compiling for ACE, and it appears to only build for ARM-v7a.

The reason why I say this is that I'm getting the following error when compiling the auto-generated files in my application ((which come from using opendds_idl on the *.idl), and after a bunch of "In file included from" lines, ends up with ...

 [exec] /home/me/tools/crystax-ndk/sources/cxx-stl/gnu-libstdc++/5/include/limits:1601:7: internal compiler error: Illegal instruction
 [exec]        max() _GLIBCXX_USE_NOEXCEPT { return __FLT_MAX__; }
 [exec]        ^

I've seen something like this before when I've compiled code which had some wrong flags for the CPU architecture. So my thinking is that maybe there's some incompatible toolchain settings on GCC which I use on my app and those settings used by ACE+TAO/OpenDDS? The CROSS_COMPILE variable in platform_android.GNU is arm-linux-androideabi- ... which as far as I know is a 32 bit toolchain, i.e., arm-v7a and I see no v8a references. And yet in my app I'm using aarch64-linux-android-5. Should these be compatible? Can the tool chain be changed?

What I'd like to do is build ACE+TAO/OpenDDS/my-application for the target architecture and ABI ... arm64: arm64-v8a and use the NDK toolchain and target ABI ... aarch64-linux-android-5:  arm64-v8a.

Thoughts?


问:
top two elements of an associative array in php
I've accomplished the end goal for this already, but maybe there is a more elegant way of accomplishing this.

If I have an array like such:

```<code>$data = array(
    'wood' => 2,
    'metal' => 5,
    'plastic' => 3,
);
</code>```

I want to get the top 2 key/value pairs from $data (ie metal:5 & plastic:3). Here's what I came up with:

```<code>arsort($data);       //put values in order
reset($data);           //set pointer to first element
$first = each($data);    //assign first element to $first
array_shift($data); //remove first element from array
reset($data);           //set pointer to the new first element
$second = each($data); //assign the new first element to $second
</code>```

答:
```<code>asort($data);
$first = array_pop($data);
$second = array_pop($data);
</code>```

Notice that instead of putting it in reverse order and grabbing the first items, I put it in order and grabbed the last items.

Body:
I've accomplished the end goal for this already, but maybe there is a more elegant way of accomplishing this.

If I have an array like such:

$data = array(
    'wood' => 2,
    'metal' => 5,
    'plastic' => 3,
);

I want to get the top 2 key/value pairs from $data (ie metal:5 & plastic:3). Here's what I came up with:

arsort($data);       //put values in order
reset($data);           //set pointer to first element
$first = each($data);    //assign first element to $first
array_shift($data); //remove first element from array
reset($data);           //set pointer to the new first element
$second = each($data); //assign the new first element to $second

Body:
asort($data);
$first = array_pop($data);
$second = array_pop($data);

Notice that instead of putting it in reverse order and grabbing the first items, I put it in order and grabbed the last items.


问:
Controller registration error while using ng-route
I am creating an angular application using v1.6.4. I am using ngRoute and have defined a solitary routing condition for now. I created an app.js file for angular module initialization and have a separate folder for other application js files.

app.js:

```<code>"use strict";

var appOtmReport = angular.module("appReport", ['ngRoute']);

appOtmReport.config(['$routeProvider',function($routeProvider) {

    $routeProvider.when('/home',{
        templateUrl: 'views/reportSample.html',
        controller: 'js/reportSampleController'
    })
    .otherwise({redirectTo:'/home'});
}]);
</code>```

index.html:

```<code><!DOCTYPE html>
<html lang="en"  id="ng-app">
<head>
<meta charset="ISO-8859-1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<title>OTM-DCPP Query Report</title>

<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">

</head>
<body>

<div  ng-app="appReport">
    <ng-view></ng-view>
</div>

<!-- JQuery stuff -->
<script src="lib/jquery.min.js"></script>
<script src="lib/highcharts.js"></script>

<!-- AngularJS framework stuff -->

<script src="lib/bootstrap.min.js"></script>
<script src="lib/angular.min.js"></script>
<script src="lib/angular-route.min.js"></script>

<!-- application specific js -->
<script src="app.js"></script>
<script src="js/reportSampleController.js"></script>

</body>
</html>
</code>```

Controller(separate file in different directory):

```<code>appOtmReport.controller('reportSampleController',function ($scope){
    $scope.name = "Vikash";
});
</code>```

When I run this, I get the below error:
[$controller:ctrlreg] http://errors.angularjs.org/1.6.4/$controller/ctrlreg?p0=js%2FreportSampleController(…)

As a result , I do not get the resolved expression but something like : Hi Name is :{{name}}

I have gone through other links similar to this , but none happen to help me. I would be thankful for any help.

答:
I found out the issue here. My app.js and controller file were in a different folder, hence the module was inaccessible inside the controller.  Once I moved the app.js file to the same directory as the controller, it worked.

Changed my index.html :

```<code><!-- application specific js -->
<script src="**js/app.js**"></script>
<script src="js/reportSampleController.js"></script>
</code>```

changed app.js:

"use strict";

var appOtmReport = angular.module("appOtmDcppQueryReport", ['ngRoute']);

```<code>appOtmReport.config(['$routeProvider',function($routeProvider) {

    $routeProvider.when('/home',{
        templateUrl: 'views/reportSample.html',
        **controller: 'reportSampleController'**
    })
    .otherwise({redirectTo:'/home'});
}]);
</code>```

Body:
I am creating an angular application using v1.6.4. I am using ngRoute and have defined a solitary routing condition for now. I created an app.js file for angular module initialization and have a separate folder for other application js files.

app.js:

"use strict";

var appOtmReport = angular.module("appReport", ['ngRoute']);

appOtmReport.config(['$routeProvider',function($routeProvider) {

    $routeProvider.when('/home',{
        templateUrl: 'views/reportSample.html',
        controller: 'js/reportSampleController'
    })
    .otherwise({redirectTo:'/home'});
}]);

index.html:

<!DOCTYPE html>

<meta charset="ISO-8859-1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<title>OTM-DCPP Query Report</title>

<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">

    <ng-view></ng-view>

Controller(separate file in different directory):

appOtmReport.controller('reportSampleController',function ($scope){
    $scope.name = "Vikash";
});

When I run this, I get the below error:
[$controller:ctrlreg] http://errors.angularjs.org/1.6.4/$controller/ctrlreg?p0=js%2FreportSampleController(…)

As a result , I do not get the resolved expression but something like : Hi Name is :{{name}}

I have gone through other links similar to this , but none happen to help me. I would be thankful for any help.

Body:
I found out the issue here. My app.js and controller file were in a different folder, hence the module was inaccessible inside the controller.  Once I moved the app.js file to the same directory as the controller, it worked.

Changed my index.html :

<!-- application specific js -->
<script src="**js/app.js**"></script>
<script src="js/reportSampleController.js"></script>

changed app.js:

"use strict";

var appOtmReport = angular.module("appOtmDcppQueryReport", ['ngRoute']);

appOtmReport.config(['$routeProvider',function($routeProvider) {

    $routeProvider.when('/home',{
        templateUrl: 'views/reportSample.html',
        **controller: 'reportSampleController'**
    })
    .otherwise({redirectTo:'/home'});
}]);


问:
Scaling filesystem on centos whm and nginx webservers
We have built a marketplace for our clients, we have hundreds thousands of companies in our database and they will add their products with many files (images,videos etc.). And also individual users are able to send photos.

We are using centos +whm (nginx+cassandra+mysql+redis+nodejs+php+java) for different parts of project according to their different content.

For main software we are using mysql and cassandra as database servers, there are restful java webservices between php7 code and database servers (which are already scaled).nodejs+redis+cassandra (for chat)

We have no problems for scaling information, but now we have to decide how to scale objects. The company which we work supplies 10TB bandwidth for each server that we get. If we consider to work with amazon or other cloud services, only for 10TB bandwidth they will charge a lot, on the other hand in this case we will have another server which will be used for other issues as well. So it seems better to have servers instead of cloud storage.

Now my question is how should we go ahead for statics files ? What is the best solution for this.

Creating nodes with subdomains like static1.domain.com, static2.domain.com for each new server. and add image location to database to show location of image. in this case for upload we always need to change target mounted disk after each server is full. We will also use CDN to decrease loads on servers.

What is the best architecture for our situation ? Thanks

答:
There is a one option in Amazon Web Services (s3). that is not a file system but you can store your static files in that s3 bucket. It will auto increase/decrease storage size based on data size and also data 99.99999999999% availability.

FYR,
AWS-s3


问:
How to train the network only on one output when there are multiple outputs?
I am using a multiple output model in Keras

```<code>model1 = Model(input=x, output=[y2, y3])

model1.compile((optimizer='sgd', loss=cutom_loss_function)
</code>```

my custom_loss function is

```<code>def custom_loss(y_true, y_pred):
   y2_pred = y_pred[0]
   y2_true = y_true[0]

   loss = K.mean(K.square(y2_true - y2_pred), axis=-1)
   return loss
</code>```

I only want to train the network on output y2.

What is the shape/structure of the y_pred and y_true argument in loss function when multiple outputs are used?
Can I access them as above? Is it y_pred[0] or y_pred[:,0]?

答:
I only want to train the network on output y2.

Based on Keras functional API guide you can achieve that with

```<code>model1 = Model(input=x, output=[y2,y3])
model1.compile(optimizer='sgd', loss=custom_loss_function,
                  loss_weights=[1., 0.0])
</code>```

What is the shape/structure of the y_pred and y_true argument in loss
  function when multiple outputs are used? Can I access them as above?
  Is it y_pred[0] or y_pred[:,0]

In keras multi-output models loss function is applied for each output separately. In pseudo-code:

```<code>loss = sum( [ loss_function( output_true, output_pred ) for ( output_true, output_pred ) in zip( outputs_data, outputs_model ) ] )
</code>```

The functionality to do loss function on multiple outputs seems unavailable to me. One probably could achieve that by incorporating the loss function as a layer of the network.

ContentLicense: CC BY-SA 4.0

Body:
I am using a multiple output model in Keras

model1 = Model(input=x, output=[y2, y3])

model1.compile((optimizer='sgd', loss=cutom_loss_function)

my custom_loss function is

def custom_loss(y_true, y_pred):
   y2_pred = y_pred[0]
   y2_true = y_true[0]

   loss = K.mean(K.square(y2_true - y2_pred), axis=-1)
   return loss

I only want to train the network on output y2.

What is the shape/structure of the y_pred and y_true argument in loss function when multiple outputs are used?
Can I access them as above? Is it y_pred[0] or y_pred[:,0]?

Body:
I only want to train the network on output y2.

Based on Keras functional API guide you can achieve that with

model1 = Model(input=x, output=[y2,y3])
model1.compile(optimizer='sgd', loss=custom_loss_function,
                  loss_weights=[1., 0.0])

What is the shape/structure of the y_pred and y_true argument in loss
  function when multiple outputs are used? Can I access them as above?
  Is it y_pred[0] or y_pred[:,0]

In keras multi-output models loss function is applied for each output separately. In pseudo-code:

loss = sum( [ loss_function( output_true, output_pred ) for ( output_true, output_pred ) in zip( outputs_data, outputs_model ) ] )

The functionality to do loss function on multiple outputs seems unavailable to me. One probably could achieve that by incorporating the loss function as a layer of the network.


问:
Using single vim instance with --remote-silent
I've always been a console vim user, but lately I've tried to use gvim.
I've made settings such that my console habits won't suffer, such as
opening an urxvt terminal at the current directory with .

However having multiple gvims and terminals open with my netbook is
horrible, quickly reducing my vim-space to a centimeter or two. At best,
the window width is halved, making it impossible to vertically split
screen (tiling wm).

I went around this problem by aliasing vim to gvim --remote-silent and it
worked fine for a couple of days, but today I needed to use -c '' and
realized that having any switches behind --remote-silent opens those
switches as files. So doing gvim --remote-silent --foo bar opens two
files, --foo and bar.

I put a new alias for alias vim=gvim, but I'm afraid this will make me a
console vim user again, sooner than I thought I would.

So the question is, what would be the preferred way to keep using gvim,
with minimal effort (setting up the system can be laborous) so that I can
still keep using vim with its full power. The solution does not need to use
remote vim, it should just minimize the gvim windows.

答:
I don't think having multiple gvim instances running is a decent solution.  Why not just have one alias to gvim --remote-silent that you use when you you don't need extra switches (presumably most of the time), and another alias to just gvim for when you want to add command-line switches?  Seems fine to me, not much extra to remember.

The main unpleasantness from having multiple gvim instances running, aside from getting many windows that are hard to keep track of, is that each gvim has its own runtime envioronment, harder to share and copy data between buffers in different gvim instances.

Derek Wyatt has interesting video on --remote-silent; I don't think it addresses your issue but you may be interested in watching it:
OneVimToRuleThemAll

Also, if problem is that window splits within gvim are taking screen estate away, make better use of the tab functionality (you can even disable the actual tab labels but keep metaphor of open tab pages) and/or alternatively just navigate between buffers while having only one buffer visible at a time.


问:
Can not find selenium WebElement twice
Working with selenium and InternetExplorer 11, I can navigate around this site.

I got a method that finds an input box on the page then inputs text. It works the first time, but when I go to another page it says that element does not exist and the page just refreshes randomly.

I a m just using a simple wait:

```<code>WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(), 'Enter Name')]")));
WebElement nameField = driver.findElement(By.xpath("//*[contains(text(), 'Enter Name')]"));
</code>```

It crashes and says the element can not be found during the wait.

I am not sure if this is just site specific or if I am doing something wrong.

If anyone has any idea I'd appreciate it :)

答:
Here is the Answer to your Question:

As you mentioned when I go to another page the entire HTML DOM gets changed and now if you try to locate or use findElement() with a previously found id/name/css/xpath Selenium will fail to do that.

So when we are on a new page we have to search for the element again using the current id/name/css/xpath in-order to use click() or sendKeys() methods.

Let me know if this Answers your Question.

Title: Can not find selenium WebElement twice

Body:
Working with selenium and InternetExplorer 11, I can navigate around this site.

I got a method that finds an input box on the page then inputs text. It works the first time, but when I go to another page it says that element does not exist and the page just refreshes randomly.

I a m just using a simple wait:

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(), 'Enter Name')]")));
WebElement nameField = driver.findElement(By.xpath("//*[contains(text(), 'Enter Name')]"));

It crashes and says the element can not be found during the wait.

I am not sure if this is just site specific or if I am doing something wrong.

If anyone has any idea I'd appreciate it :)


问:
Save program output to a (.txt) file
My program

```<code>namespace trim2
  {
     class Program
      {
        static void Main(string[] args)
          {
            //ask user to start, if yes then continue, else then close

            DataConversion()
          }

    public static void DataConversion()
    {
        string lines = File.ReadAllText(@"d:\trim1.txt");
        string result;
        result = lines.Replace("- - ", string.Empty).Replace("+", string.Empty).....

         \\process goes here
         \\process goes here
         \\process goes here
    }
  }
}
</code>```

What I expected is after the file goes thru the data conversion process it would save into a new text file (which is the processed one).. how can i achieve this?

Also, I tried this line, seems wont work

```<code> File.WriteAllText("C:\Users\Cleaned.txt", new string(ShiftLine));
</code>```

答:
The \ character is used to designate an escape sequence

Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences. An escape sequence is regarded as a single character and is therefore valid as a character constant.

To avoid that interpretation of the string you either you need to write it twice:

```<code>File.WriteAllText("C:\\Users\\Cleaned.txt", new string(ShiftLine));
</code>```

or you use the @ operator to tell the compiler to interpret the string literally:

```<code>File.WriteAllText(@"C:\Users\Cleaned.txt", new string(ShiftLine));
</code>```

@ is a verbatim string literal

A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim,

Title: Save program output to a (.txt) file

Body:
My program

namespace trim2
  {
     class Program
      {
        static void Main(string[] args)
          {
            //ask user to start, if yes then continue, else then close

            DataConversion()
          }

    public static void DataConversion()
    {
        string lines = File.ReadAllText(@"d:\trim1.txt");
        string result;
        result = lines.Replace("- - ", string.Empty).Replace("+", string.Empty).....

         \\process goes here
         \\process goes here
         \\process goes here
    }
  }
}

What I expected is after the file goes thru the data conversion process it would save into a new text file (which is the processed one).. how can i achieve this?

Also, I tried this line, seems wont work

 File.WriteAllText("C:\Users\Cleaned.txt", new string(ShiftLine));

Body:
The \ character is used to designate an escape sequence

Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences. An escape sequence is regarded as a single character and is therefore valid as a character constant.

To avoid that interpretation of the string you either you need to write it twice:

File.WriteAllText("C:\\Users\\Cleaned.txt", new string(ShiftLine));

or you use the @ operator to tell the compiler to interpret the string literally:

File.WriteAllText(@"C:\Users\Cleaned.txt", new string(ShiftLine));

@ is a verbatim string literal

A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim,


问:
How to get JSON output as NSString
Working in Objective-C where I need to parse JSON. So after parsing successfully.

Below is my code :

```<code>-(instancetype)initWithDict:(NSDictionary *)dict {
    self = [super init];
    if (self) {

        if ([dict isKindOfClass:[NSDictionary class]]) {
            self.allKeysArray = [dict allKeys];

 if ([self.allKeysArray containsObject:@"nDetail"]) {

                if ([dict valueForKey:@"nDetail"]) {

 _tempNutrientArray = [[[dict valueForKey:@"nDetail"] valueForKey:@"nTypeCode"] valueForKey:@"value"];
         }
     }
 }

NSLog(@"N Array : @%@", _tempNutrientArray);

}
</code>```

I need to convert this in string format each an every value.

My output :

```<code>N Array : @(
    "ENER-",
    FAT,
    FASAT,
    CHOAVL,
    "SUGAR-",
    "PRO-",
    NACL
)
</code>```

Required Output :

```<code> N Array : @("ENER-","FAT","FASAT","CHOAVL","SUGAR-","PRO-","NACL")
</code>```

So how should I convert it to string format. Please help me.

答:
You need to enumerate the whole array to make all object as a proper string. This may be fast operation.

you can use this code:

```<code>NSArray *arr = [NSArray arrayWithObjects:@"",@"", nil];
NSMutableArray *arrNew = [NSMutableArray new];

[arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSString *plainstr = [NSString stringWithFormat:@"%@",obj];
    [arrNew addObject:plainstr];
}];
</code>```

The arrNew will be the array with string..

Better you convert it to string when you are fetching it.

Title: How to get JSON output as NSString

Body:
Working in Objective-C where I need to parse JSON. So after parsing successfully.

Below is my code :

-(instancetype)initWithDict:(NSDictionary *)dict {
    self = [super init];
    if (self) {

        if ([dict isKindOfClass:[NSDictionary class]]) {
            self.allKeysArray = [dict allKeys];

 if ([self.allKeysArray containsObject:@"nDetail"]) {

                if ([dict valueForKey:@"nDetail"]) {

 _tempNutrientArray = [[[dict valueForKey:@"nDetail"] valueForKey:@"nTypeCode"] valueForKey:@"value"];
         }
     }
 }

NSLog(@"N Array : @%@", _tempNutrientArray);

}

I need to convert this in string format each an every value.

My output :

N Array : @(
    "ENER-",
    FAT,
    FASAT,
    CHOAVL,
    "SUGAR-",
    "PRO-",
    NACL
)

Required Output :

 N Array : @("ENER-","FAT","FASAT","CHOAVL","SUGAR-","PRO-","NACL")

So how should I convert it to string format. Please help me.

Body:
You need to enumerate the whole array to make all object as a proper string. This may be fast operation.

you can use this code:

NSArray *arr = [NSArray arrayWithObjects:@"",@"", nil];
NSMutableArray *arrNew = [NSMutableArray new];

[arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSString *plainstr = [NSString stringWithFormat:@"%@",obj];
    [arrNew addObject:plainstr];
}];

The arrNew will be the array with string..

Better you convert it to string when you are fetching it.


问:
How to use database procedure in fluent nhibernate mapping
I have this class

```<code>public class Bill : EntityBase
{
      public virtual decimal Value { get; set; }
}
</code>```

and in below mapping, I fill in the value of 'Value' using a procedure in a Formula()

```<code>public class MapBill : ClassMap<Bill>
{
    public MapBill()
    {
        Table("cabrec");
        Map(m => m.Value)
            .Formula(
"(select t.VALOR_IND from ret_vlorind(1,1,cast('02/06/1993' as Date)) as t)")
            .CustomType(typeof(decimal));
    }
}
</code>```

But it returns the error when executing:

```<code>{"Dynamic SQL Error\r\nSQL error code = -104\r\nToken unknown - line 1, column 279\r\n."}
</code>```

Is there any way to use procedure in fluent nhibernate?

答:
The formula mapping expression is later converted by NHibernate to statement like this

```<code>// source in code
(select t.VALOR_IND from ret_vlorind(1,1,cast('02/06/1993' as Date)) as t)
// sent SQL statement
(select t.VALOR_IND from ret_vlorind(1,1,cast('02/06/1993' as Date)) as this_.t)
</code>```

The this_. prefix is injected at places, where NHibernate thinks it should properly use MAIN table alias.

This is not what we want.. and the only way I found, is to introduce our own Dialect (I am working with SQL Server) and define some "CONSTANTS" to be treated as - I do not need prefix

```<code>public class CustomMsSql2012Dialect : MsSql2012Dialect
{
    public CustomMsSql2012Dialect()
    {
        RegisterKeyword("my_table_alias");
        ...
</code>```

This must be used for configuration

```<code><property name="dialect">MyNamespace.CustomMsSql2012Dialect,MyLib</property>
</code>```

And finally, we have to adjust our statement

```<code>// wrong t is not known keyword.. would be prefixed
(select t.VALOR_IND from ret_vlorind(1,1,cast('02/06/1993' as Date)) as t)
// into this
(select my_table_alias.VALOR_IND from ret_vlorind(1,1,cast('02/06/1993' as Date)) as my_table_alias)
</code>```

NOTE: keywords, my experience, must be just lower case

Body:
I have this class

public class Bill : EntityBase
{
      public virtual decimal Value { get; set; }
}

and in below mapping, I fill in the value of 'Value' using a procedure in a Formula()

public class MapBill : ClassMap<Bill>
{
    public MapBill()
    {
        Table("cabrec");
        Map(m => m.Value)
            .Formula(
"(select t.VALOR_IND from ret_vlorind(1,1,cast('02/06/1993' as Date)) as t)")
            .CustomType(typeof(decimal));
    }
}

But it returns the error when executing:

{"Dynamic SQL Error\r\nSQL error code = -104\r\nToken unknown - line 1, column 279\r\n."}

Is there any way to use procedure in fluent nhibernate?

Body:
The formula mapping expression is later converted by NHibernate to statement like this

// source in code
(select t.VALOR_IND from ret_vlorind(1,1,cast('02/06/1993' as Date)) as t)
// sent SQL statement
(select t.VALOR_IND from ret_vlorind(1,1,cast('02/06/1993' as Date)) as this_.t)

The this_. prefix is injected at places, where NHibernate thinks it should properly use MAIN table alias.

This is not what we want.. and the only way I found, is to introduce our own Dialect (I am working with SQL Server) and define some "CONSTANTS" to be treated as - I do not need prefix

public class CustomMsSql2012Dialect : MsSql2012Dialect
{
    public CustomMsSql2012Dialect()
    {
        RegisterKeyword("my_table_alias");
        ...

This must be used for configuration

<property name="dialect">MyNamespace.CustomMsSql2012Dialect,MyLib</property>

And finally, we have to adjust our statement

// wrong t is not known keyword.. would be prefixed
(select t.VALOR_IND from ret_vlorind(1,1,cast('02/06/1993' as Date)) as t)
// into this
(select my_table_alias.VALOR_IND from ret_vlorind(1,1,cast('02/06/1993' as Date)) as my_table_alias)

NOTE: keywords, my experience, must be just lower case