问:
Angularjs: How to get value of input without ng-model
I need to make some inputs by ng-repeat, and in my json file I have in object where is a property called name, like this:

```<code>"url":"find_company",
    "values":[
      {
        "name":"company name",
        "type":"input_search"
      },{
        "name":"company_phone",
        "type":"input_search"
      }
    ]
</code>```

I want to make search in DB, in search you can find by any field or by two or more field. Field called the same as property of object. So by ng-keyup I need to send to my function

```<code>search(field, value)
</code>```

two arguments. I want to do something like this

```<code><div ng-repeat="value in param.values">
    <input ng-if="value.type == 'input_search'"
           ng-keyup="search(value.name, this.text)"
           type="text">
</code>```

How can a send to function text of this input without using ng-model? Where this.text is value of input.

答:
This is how you do it with ngModel:

```<code><div ng-repeat="value in param.values">
    <input ng-if="value.type == 'input_search'" ng-model="value.val" ng-keyup="search(value)" type="text">
</code>```

And in your controller:

```<code>$scope.search = function( item ) {
    console.log( item.val ); // Here you have the value using ngModel
    console.log( item.name ); // Here you have the "name" property of the element inside the loop
}
</code>```

As you can see, you CAN use ngModel and by passing the object itself to the function you can access its properties from the function in the controller.

Note that there's that this.text in the view - I don't know what it is exactly so I dropped it from the example to make things clearer, but you can use it in your code of course.

Body:
I need to make some inputs by ng-repeat, and in my json file I have in object where is a property called name, like this:

"url":"find_company",
    "values":[
      {
        "name":"company name",
        "type":"input_search"
      },{
        "name":"company_phone",
        "type":"input_search"
      }
    ]

I want to make search in DB, in search you can find by any field or by two or more field. Field called the same as property of object. So by ng-keyup I need to send to my function

search(field, value)

two arguments. I want to do something like this

    <input ng-if="value.type == 'input_search'"
           ng-keyup="search(value.name, this.text)"
           type="text">

How can a send to function text of this input without using ng-model? Where this.text is value of input.

Body:
This is how you do it with ngModel:

<div ng-repeat="value in param.values">
    <input ng-if="value.type == 'input_search'" ng-model="value.val" ng-keyup="search(value)" type="text">

And in your controller:

$scope.search = function( item ) {
    console.log( item.val ); // Here you have the value using ngModel
    console.log( item.name ); // Here you have the "name" property of the element inside the loop
}

As you can see, you CAN use ngModel and by passing the object itself to the function you can access its properties from the function in the controller.

Note that there's that this.text in the view - I don't know what it is exactly so I dropped it from the example to make things clearer, but you can use it in your code of course.


来源: stackexchange

问:
Why app crashes when i set image to ImageView and run it on android 7.1.1
I am new to Android. I want to know why my app crashes on Android 7.1.1 while setting the image to imageView using explicit intent, as it totally runs fine on other versions of Android. I have tried to understand and solve the issue but unable to do.

Can anyone please help me to understand why this is happening and what's the reason behind this?

Thanks.

This is what it showing :

```<code>eAnimators on 0x97c5ee80 (RippleDrawable) with handle 0x9affd880
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.himanshu.imageviewintent, PID: 5049
                  java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/41 }} to activity {com.example.himanshu.imageviewintent/com.example.himanshu.imageviewintent.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/41 from pid=5049, uid=10073 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4089)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                      at android.app.ActivityThread.-wrap20(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                   Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/41 from pid=5049, uid=10073 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                      at android.os.Parcel.readException(Parcel.java:1684)
                      at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
                      at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:146)
                      at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:692)
                      at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1147)
                      at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:984)
                      at android.content.ContentResolver.openInputStream(ContentResolver.java:704)
                      at com.example.himanshu.imageviewintent.MainActivity.onActivityResult(MainActivity.java:44)
                      at android.app.Activity.dispatchActivityResult(Activity.java:6932)
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                      at android.app.ActivityThread.-wrap20(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Application terminated.
</code>```

And this is my code :

Java :

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

    final static int ImageIntentRequest = 1;

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

    public void setImage(View view) {

        Intent intent = new Intent(Intent.ACTION_PICK);
        File imageViewPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        String path =  imageViewPath.getPath();
        intent.setDataAndType(Uri.parse(path),"image/*");
        startActivityForResult(intent,ImageIntentRequest);
    }

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

        if(resultCode == RESULT_OK && requestCode == ImageIntentRequest) {

            InputStream stream;
            ImageView imageView = (ImageView)findViewById(R.id.imageView);
            try {
             stream = getContentResolver().openInputStream(data.getData());
                Bitmap bitmap = BitmapFactory.decodeStream(stream);
                imageView.setImageBitmap(bitmap);

            } catch (FileNotFoundException e) {
                Toast.makeText(this,"There is no File Present",Toast.LENGTH_SHORT).show();;
                e.printStackTrace();
            }
        }
    }
}
</code>```

XML :

```<code>   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.himanshu.imageviewintent.MainActivity"
>

<Button
    android:text="@string/set_image_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn_set_image"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:onClick="setImage"
    />

<ImageView
    android:src="@mipmap/ic_launcher"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/imageView"
    android:contentDescription="@null"
    android:layout_above="@+id/btn_set_image"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="10dp"
    />
</RelativeLayout>
</code>```

I found an easy fix for this :

I just replaced,

```<code>Intent.ACTION_PICK by -

Intent intent = Intent(Intent.ACTION_GET_CONTENT);
</code>```

and now the app runs totally fine on old and latest releases of Android.

But still have doubts:

Why ACTION_PICK works on old versions of Android but not on new Releases?
Why ACTION_GET_CONTENT works on all releases?

I will be thankful if someone clarify this?

答:
You need to take runtime permission from the user to read external storage.

You can use following code for asking permission from user.

Hope it will help you.

```<code>if(ActivityCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
        requestStoragePermission();
    } else {
        loadImageInImageview();
    }

    private void requestStoragePermission() {
        final String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
        if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            ActivityCompat.requestPermissions(this, permissions, 1000);
            return;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1000) {
            if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                loadImageInImageview();
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Allow permission.")
                        .setMessage("Please....")
                        .setCancelable(false)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                Intent intent = new Intent();
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            }
                        })
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        }).show();
            }
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to Android. I want to know why my app crashes on Android 7.1.1 while setting the image to imageView using explicit intent, as it totally runs fine on other versions of Android. I have tried to understand and solve the issue but unable to do.

Can anyone please help me to understand why this is happening and what's the reason behind this?

Thanks.

This is what it showing :

eAnimators on 0x97c5ee80 (RippleDrawable) with handle 0x9affd880
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.himanshu.imageviewintent, PID: 5049
                  java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/41 }} to activity {com.example.himanshu.imageviewintent/com.example.himanshu.imageviewintent.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/41 from pid=5049, uid=10073 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4089)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                      at android.app.ActivityThread.-wrap20(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                   Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/41 from pid=5049, uid=10073 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                      at android.os.Parcel.readException(Parcel.java:1684)
                      at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
                      at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:146)
                      at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:692)
                      at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1147)
                      at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:984)
                      at android.content.ContentResolver.openInputStream(ContentResolver.java:704)
                      at com.example.himanshu.imageviewintent.MainActivity.onActivityResult(MainActivity.java:44)
                      at android.app.Activity.dispatchActivityResult(Activity.java:6932)
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                      at android.app.ActivityThread.-wrap20(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Application terminated.

And this is my code :

Java :

public class MainActivity extends Activity {

    final static int ImageIntentRequest = 1;

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

    public void setImage(View view) {

        Intent intent = new Intent(Intent.ACTION_PICK);
        File imageViewPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        String path =  imageViewPath.getPath();
        intent.setDataAndType(Uri.parse(path),"image/*");
        startActivityForResult(intent,ImageIntentRequest);
    }

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

        if(resultCode == RESULT_OK && requestCode == ImageIntentRequest) {

            InputStream stream;
            ImageView imageView = (ImageView)findViewById(R.id.imageView);
            try {
             stream = getContentResolver().openInputStream(data.getData());
                Bitmap bitmap = BitmapFactory.decodeStream(stream);
                imageView.setImageBitmap(bitmap);

            } catch (FileNotFoundException e) {
                Toast.makeText(this,"There is no File Present",Toast.LENGTH_SHORT).show();;
                e.printStackTrace();
            }
        }
    }
}

XML :

   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.himanshu.imageviewintent.MainActivity"
>

<Button
    android:text="@string/set_image_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn_set_image"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:onClick="setImage"
    />

<ImageView
    android:src="@mipmap/ic_launcher"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/imageView"
    android:contentDescription="@null"
    android:layout_above="@+id/btn_set_image"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="10dp"
    />
</RelativeLayout>

I found an easy fix for this :

I just replaced,

Intent.ACTION_PICK by -

Intent intent = Intent(Intent.ACTION_GET_CONTENT);

and now the app runs totally fine on old and latest releases of Android.

But still have doubts:

Why ACTION_PICK works on old versions of Android but not on new Releases?
Why ACTION_GET_CONTENT works on all releases?

I will be thankful if someone clarify this?

Body:
You need to take runtime permission from the user to read external storage.

You can use following code for asking permission from user.

Hope it will help you.

if(ActivityCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
        requestStoragePermission();
    } else {
        loadImageInImageview();
    }

    private void requestStoragePermission() {
        final String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
        if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            ActivityCompat.requestPermissions(this, permissions, 1000);
            return;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1000) {
            if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                loadImageInImageview();
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Allow permission.")
                        .setMessage("Please....")
                        .setCancelable(false)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                Intent intent = new Intent();
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            }
                        })
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        }).show();
            }
        }
    }


问:
File / Folder monitoring
What is the best way to monitor disks against file activities. I mean that getting the full file name (c:\temp\abc.txt), action(created/deleted/modified/renamed), and also the user (user1) and process name (notepad.exe) causing the file (multiple delete) activities.

I heard about Some APIs and ShellNotifications but could not use them for the whole needs above.

Best regards.

答:
I have something in Python for Windows which you might be interested
to port from if you like: http://github.com/gorakhargosh/watchdog</p>

ContentLicense: CC BY-SA 2.5

Title: File / Folder monitoring


问:
C# 6.0 Features Not Working with Visual Studio 2015
I am testing Visual Studio 2015 with C# 6.0 but the language features are not working. In an MVC web application, the following code does compile:

```<code>if (!string.IsNullOrWhiteSpace(Model.Profile?.TypeName))
{
    // More logic here...
}
</code>```

However, when I run the application via Debug and IIS Express, I get the following error:

CS1525: Invalid expression term '.'

How do I enable these features?

答:
```<code><compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:7 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:15 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</code>```

Body:
I am testing Visual Studio 2015 with C# 6.0 but the language features are not working. In an MVC web application, the following code does compile:

if (!string.IsNullOrWhiteSpace(Model.Profile?.TypeName))
{
    // More logic here...
}

However, when I run the application via Debug and IIS Express, I get the following error:

CS1525: Invalid expression term '.'

How do I enable these features?

Body:
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:7 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:15 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />


问:
best approach using cfthread
im looking at processing a query within a cfthread as the original data could be thousands of requests. Im looking at using cfthread
so i can make it process in the background. I know there is alot of info on cfthread, but getting my head around it has been difficult.

what this all comes down to is a number of remote calls using cfhttp and whether they are in a single thread or should be on their own.

The remote calls could take between 5 - 10 seconds each, and the database updates are very minor, simply updating a true false value on the query
processing them.

```<code><cfthread action="run" name="myThreadName" priority="high">
    <!--- do a query --->
    <cfloop query="myQuery">
        <!--- do a remote call --->
        <!--- process remote call response --->
        <!--- update local dbtables to indicate process is complete --->
        <!--- sleep using <cfset sleep(5000)> --->
    </cfloop>
</cfthread>
</code>```

Or is this the more ideal basic use of cfthread for this basic process

```<code><cfloop from="1" to="1000" index="idx">
    <cfthread action="run" name="myThreadName" priority="high">
        <!--- do a query --->
        <!--- do a remote call --->
        <!--- process remote call response --->
        <!--- update local dbtables to indicate process is complete --->
        <!--- sleep using <cfset sleep(5000)> --->
    </cfthread>
</cfloop>
</code>```

Im trying to find the best balance so i dont crash my servers, but am also able to handle alot of these requests to fetch information from the external service, but im struggling to find which is the best direction, or if there is a better process all together to handle the remote requests on mass

thanks in advance

答:
You can't just spawn n threads and hope for the best. Too many threads will cause the CPU scheduler to switch context way too often and thus cause an overall slowdown. I also don't see why you would want the thread(s) to run in high(er) priority, given that there are other things on the machine that need CPU time. It would simply cause delay on other threads while the many high priority threads would still contest for CPU time among each other. There's also no need for a thread pause (sleep) then.

You need to make the best out of the two approaches. Consider something like this:

```<code><cfset numberOfThreads              = 8>
<cfset numberOfRemoteCallsPerThread = 4>

<cfloop from="1" to="#numberOfThreads#" index="threadIndex">

    <!--- do a query and split the number of records to process by dividing/offsetting --->

    <cfthread name="myThread_#threadIndex#">
        <!--- do a remote call --->
        <!--- process remote call response --->
        <!--- update local dbtables to indicate process is complete --->
    </cfthread>

</cfloop>
</code>```

This will parallel your processing efficiently. Each thread will process a pre-determined set of records. To split the records, you could do something along the lines of:

```<code>SELECT
    <data to send>

WHERE
    <filter records to process>

LIMIT
    #((threadIndex - 1) * numberOfRemoteCallsPerThread)#, #numberOfRemoteCallsPerThread#
</code>```

Whatever works best here depends on how you acquire the records that need processing. You might need to calculate the records before starting to loop etc.

Title: best approach using cfthread

Body:
im looking at processing a query within a cfthread as the original data could be thousands of requests. Im looking at using cfthread
so i can make it process in the background. I know there is alot of info on cfthread, but getting my head around it has been difficult.

what this all comes down to is a number of remote calls using cfhttp and whether they are in a single thread or should be on their own.

The remote calls could take between 5 - 10 seconds each, and the database updates are very minor, simply updating a true false value on the query
processing them.

<cfthread action="run" name="myThreadName" priority="high">

    <cfloop query="myQuery">

    </cfloop>
</cfthread>

Or is this the more ideal basic use of cfthread for this basic process

<cfloop from="1" to="1000" index="idx">
    <cfthread action="run" name="myThreadName" priority="high">

    </cfthread>
</cfloop>

Im trying to find the best balance so i dont crash my servers, but am also able to handle alot of these requests to fetch information from the external service, but im struggling to find which is the best direction, or if there is a better process all together to handle the remote requests on mass

thanks in advance

Body:
You can't just spawn n threads and hope for the best. Too many threads will cause the CPU scheduler to switch context way too often and thus cause an overall slowdown. I also don't see why you would want the thread(s) to run in high(er) priority, given that there are other things on the machine that need CPU time. It would simply cause delay on other threads while the many high priority threads would still contest for CPU time among each other. There's also no need for a thread pause (sleep) then.

You need to make the best out of the two approaches. Consider something like this:

<cfset numberOfThreads              = 8>
<cfset numberOfRemoteCallsPerThread = 4>

<cfloop from="1" to="#numberOfThreads#" index="threadIndex">

    <!--- do a query and split the number of records to process by dividing/offsetting --->

    <cfthread name="myThread_#threadIndex#">
        <!--- do a remote call --->
        <!--- process remote call response --->
        <!--- update local dbtables to indicate process is complete --->
    </cfthread>

</cfloop>

This will parallel your processing efficiently. Each thread will process a pre-determined set of records. To split the records, you could do something along the lines of:

SELECT
    <data to send>

WHERE
    <filter records to process>

LIMIT
    #((threadIndex - 1) * numberOfRemoteCallsPerThread)#, #numberOfRemoteCallsPerThread#

Whatever works best here depends on how you acquire the records that need processing. You might need to calculate the records before starting to loop etc.


问:
Prolog Family tree
I did it but its not showing answers When i ask about the brothers,sisters,uncles,aunts

This is what I wrote, what's wrong ?

```<code>/*uncle(X, Y) :– male(X), sibling(X, Z), parent(Z, Y).*/
/*uncle(X, Y) :– male(X), spouse(X, W), sibling(W, Z), parent(Z, Y).*/

uncle(X,Y) :-
  parent(Z,Y), brother(X,Z).

aunt(X,Y) :-
  parent(Z,Y), sister(X,Z).

sibling(X, Y) :-
      parent(Z, X),
      parent(Z, Y),
      X \= Y.

sister(X, Y) :-
      sibling(X, Y),
      female(X).

brother(X, Y) :-
      sibling(X, Y),
      male(X).

parent(Z,Y) :- father(Z,Y).
parent(Z,Y) :- mother(Z,Y).

grandparent(C,D) :- parent(C,E), parent(E,D).

aunt(X, Y) :– female(X), sibling(X, Z), parent(Z, Y).
aunt(X, Y) :– female(X), spouse(X, W), sibling(W, Z), parent(Z, Y).

male(john).
male(bob).
male(bill).
male(ron).
male(jeff).

female(mary).
female(sue).
female(nancy).

mother(mary, sue).
mother(mary, bill).
mother(sue, nancy).
mother(sue, jeff).
mother(jane, ron).

father(john, sue).
father(john, bill).
father(bob, nancy).
father(bob, jeff).
father(bill, ron).

sibling(bob,bill).
sibling(sue,bill).
sibling(nancy,jeff).
sibling(nancy,ron).
sibling(jell,ron).
</code>```

And one more thing, how do I optimize the rule of the brother so that X is not brother to itself.

答:
first:

put your facts at the beginning of your code!

and for brother:

```<code>equal(X,Y) :-
   X=Y.

different(X,Y):-
   not(equal(X,Y)).

brother(X, Y) :-
  sibling(X, Y),
  male(X),
  different(X,Y).
</code>```

OwnerDisplayName: Tania

LastEditorDisplayName: Josh

Title: Prolog Family tree

Body:
I did it but its not showing answers When i ask about the brothers,sisters,uncles,aunts

This is what I wrote, what's wrong ?

/*uncle(X, Y) :– male(X), sibling(X, Z), parent(Z, Y).*/
/*uncle(X, Y) :– male(X), spouse(X, W), sibling(W, Z), parent(Z, Y).*/

uncle(X,Y) :-
  parent(Z,Y), brother(X,Z).

aunt(X,Y) :-
  parent(Z,Y), sister(X,Z).

sibling(X, Y) :-
      parent(Z, X),
      parent(Z, Y),
      X \= Y.

sister(X, Y) :-
      sibling(X, Y),
      female(X).

brother(X, Y) :-
      sibling(X, Y),
      male(X).

parent(Z,Y) :- father(Z,Y).
parent(Z,Y) :- mother(Z,Y).

grandparent(C,D) :- parent(C,E), parent(E,D).

aunt(X, Y) :– female(X), sibling(X, Z), parent(Z, Y).
aunt(X, Y) :– female(X), spouse(X, W), sibling(W, Z), parent(Z, Y).

male(john).
male(bob).
male(bill).
male(ron).
male(jeff).

female(mary).
female(sue).
female(nancy).

mother(mary, sue).
mother(mary, bill).
mother(sue, nancy).
mother(sue, jeff).
mother(jane, ron).

father(john, sue).
father(john, bill).
father(bob, nancy).
father(bob, jeff).
father(bill, ron).

sibling(bob,bill).
sibling(sue,bill).
sibling(nancy,jeff).
sibling(nancy,ron).
sibling(jell,ron).

And one more thing, how do I optimize the rule of the brother so that X is not brother to itself.

Body:
first:

put your facts at the beginning of your code!

and for brother:

equal(X,Y) :-
   X=Y.

different(X,Y):-
   not(equal(X,Y)).

brother(X, Y) :-
  sibling(X, Y),
  male(X),
  different(X,Y).


问:
Golang:xml unmarshall not working as expected
response getting in xml format:

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">
<id>https://sites.google.com/feeds/activity/site/siteName</id>
<updated>2009-09-10T05:24:23.120Z</updated>
<title>Activity</title>
<link rel="alternate" type="text/html" href="http://sites.google.com/site/siteName/system/app/pages/recentChanges"/>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"
  href="https://sites.google.com/feeds/activity/site/siteName"/>
<link rel="self" type="application/atom+xml"
  href="https://sites.google.com/feeds/activity/site/siteName"/>
<generator version="1" uri="http://sites.google.com">Google Sites</generator>
<openSearch:startIndex>1</openSearch:startIndex>
<entry xmlns:gd="http://schemas.google.com/g/2005" gd:etag="W/"CU4GQ3szfSl7ImA9WxNRFUg."">
<id>https://sites.google.com/feeds/activity/site/siteName/940375996952876062</id>
<updated>2009-09-10T03:38:42.585Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/sites/2008#deletion" label="deletion"/>
<title>home</title>

User deleted home

<link rel="http://schemas.google.com/sites/2008#revision" type="application/atom+xml"
  href="https://sites.google.com/feeds/revision/site/siteName/5409745539831916487"/>
<link rel="http://schemas.google.com/sites/2008#current" type="application/atom+xml"
  href="https://sites.google.com/feeds/content/site/siteName/5409745539831916487"/>
<link rel="self" type="application/atom+xml"
  href="https://sites.google.com/feeds/activity/site/siteName/940375996952876062"/>
<author>
  <name>User</name>
  <email>user@gmail.com</email>
</author>
</entry>
<entry xmlns:gd="http://schemas.google.com/g/2005" gd:etag="W/"CU8DQn45fyl7ImA9WxNRFUg."">
  <id>https://sites.google.com/feeds/activity/site/siteName/7165439066235480082</id>
  <updated>2009-09-10T03:37:53.027Z</updated>
  <category scheme="http://schemas.google.com/g/2005#kind"
    term="http://schemas.google.com/sites/2008#edit" label="edit"/>
  <title>home</title>

User2 edited home

  <link rel="http://schemas.google.com/sites/2008#revision" type="application/atom+xml"
    href="https://sites.google.com/feeds/revision/site/siteName/5409745539831916487"/>
  <link rel="http://schemas.google.com/sites/2008#current" type="application/atom+xml"
    href="https://sites.google.com/feeds/content/site/siteName/5409745539831916487"/>
  <link rel="self" type="application/atom+xml"
    href="https://sites.google.com/feeds/activity/site/siteName/7165439066235480082"/>
  <author>
    <name>User</name>
    <email>user@gmail.com</email>
  </author>
</entry>
<entry xmlns:gd="http://schemas.google.com/g/2005" gd:etag="W/"CU8AR3s4cSl7ImA9WxNRFUg."">
  <id>https://sites.google.com/feeds/activity/site/siteName/127448462987345884</id>
  <updated>2009-09-10T03:37:26.539Z</updated>
  <category scheme="http://schemas.google.com/g/2005#kind"
    term="http://schemas.google.com/sites/2008#creation" label="creation"/>
  <title>home</title>

User3 created home

  <link rel="http://schemas.google.com/sites/2008#revision" type="application/atom+xml"
    href="https://sites.google.com/feeds/revision/site/siteName/5409745539831916487"/>
  <link rel="http://schemas.google.com/sites/2008#current" type="application/atom+xml"
    href="https://sites.google.com/feeds/content/site/siteName/5409745539831916487"/>
  <link rel="self" type="application/atom+xml"
    href="https://sites.google.com/feeds/activity/site/siteName/127448462987345884"/>
  <author>
    <name>User3</name>
    <email>user3@gmail.com</email>
  </author>
</entry>
</feed>```
</div>
</div>
</p>

<p>In GO i using following structure and code to decode</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>type XMLLink struct {
 XMLName xml.Name `xml:"link"`
 Rel     string   `xml:"rel,attr"`
 Href    string   `xml:"rel,href"`
}
type XMLEntry struct {
 XMLName xml.Name  `xml:"entry"`
 Link    []XMLLink `xml:"link,attr"`
}
type XMLFeed struct {
 XMLName xml.Name   `xml:"feed"`
 Entry   []XMLEntry `xml:"entry,attr"`
}</code>```

here i want to decode only link tag under entry tag.
following is the code i using to decode the xml into necessary values

var feed XMLFeed
//response got from http request is expected xml here which is already men tioned above
bodyBytes, _ := ioutil.ReadAll(response.Body)
   err := xml.Unmarshal(bodyBytes, &feed)
   if err != nil {
    log.Fatalf("Unable to unmarshall", err)
   }
   fmt.Println("number of entries:", feed)```

but here output is only
 number of entries: {{http://www.w3.org/2005/Atom feed} []}
dont know what is going wrong here please suggest any changes to make this work fine

答:
The problem here is that you are using attr where you shouldn't.

You are treating the XMLEntry and XMLLink tags as attributes.

Body:
response getting in xml format:

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">
<id>https://sites.google.com/feeds/activity/site/siteName</id>
<updated>2009-09-10T05:24:23.120Z</updated>
<title>Activity</title>
<link rel="alternate" type="text/html" href="http://sites.google.com/site/siteName/system/app/pages/recentChanges"/>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"
  href="https://sites.google.com/feeds/activity/site/siteName"/>
<link rel="self" type="application/atom+xml"
  href="https://sites.google.com/feeds/activity/site/siteName"/>
<generator version="1" uri="http://sites.google.com">Google Sites</generator>
<openSearch:startIndex>1</openSearch:startIndex>
<entry xmlns:gd="http://schemas.google.com/g/2005" gd:etag="W/"CU4GQ3szfSl7ImA9WxNRFUg."">
<id>https://sites.google.com/feeds/activity/site/siteName/940375996952876062</id>
<updated>2009-09-10T03:38:42.585Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/sites/2008#deletion" label="deletion"/>
<title>home</title>

User deleted home

<link rel="http://schemas.google.com/sites/2008#revision" type="application/atom+xml"
  href="https://sites.google.com/feeds/revision/site/siteName/5409745539831916487"/>
<link rel="http://schemas.google.com/sites/2008#current" type="application/atom+xml"
  href="https://sites.google.com/feeds/content/site/siteName/5409745539831916487"/>
<link rel="self" type="application/atom+xml"
  href="https://sites.google.com/feeds/activity/site/siteName/940375996952876062"/>
<author>
  <name>User</name>
  <email>user@gmail.com</email>
</author>
</entry>
<entry xmlns:gd="http://schemas.google.com/g/2005" gd:etag="W/"CU8DQn45fyl7ImA9WxNRFUg."">
  <id>https://sites.google.com/feeds/activity/site/siteName/7165439066235480082</id>
  <updated>2009-09-10T03:37:53.027Z</updated>
  <category scheme="http://schemas.google.com/g/2005#kind"
    term="http://schemas.google.com/sites/2008#edit" label="edit"/>
  <title>home</title>

User2 edited home

  <link rel="http://schemas.google.com/sites/2008#revision" type="application/atom+xml"
    href="https://sites.google.com/feeds/revision/site/siteName/5409745539831916487"/>
  <link rel="http://schemas.google.com/sites/2008#current" type="application/atom+xml"
    href="https://sites.google.com/feeds/content/site/siteName/5409745539831916487"/>
  <link rel="self" type="application/atom+xml"
    href="https://sites.google.com/feeds/activity/site/siteName/7165439066235480082"/>
  <author>
    <name>User</name>
    <email>user@gmail.com</email>
  </author>
</entry>
<entry xmlns:gd="http://schemas.google.com/g/2005" gd:etag="W/"CU8AR3s4cSl7ImA9WxNRFUg."">
  <id>https://sites.google.com/feeds/activity/site/siteName/127448462987345884</id>
  <updated>2009-09-10T03:37:26.539Z</updated>
  <category scheme="http://schemas.google.com/g/2005#kind"
    term="http://schemas.google.com/sites/2008#creation" label="creation"/>
  <title>home</title>

User3 created home

  <link rel="http://schemas.google.com/sites/2008#revision" type="application/atom+xml"
    href="https://sites.google.com/feeds/revision/site/siteName/5409745539831916487"/>
  <link rel="http://schemas.google.com/sites/2008#current" type="application/atom+xml"
    href="https://sites.google.com/feeds/content/site/siteName/5409745539831916487"/>
  <link rel="self" type="application/atom+xml"
    href="https://sites.google.com/feeds/activity/site/siteName/127448462987345884"/>
  <author>
    <name>User3</name>
    <email>user3@gmail.com</email>
  </author>
</entry>
</feed>

In GO i using following structure and code to decode

type XMLLink struct {
 XMLName xml.Name `xml:"link"`
 Rel     string   `xml:"rel,attr"`
 Href    string   `xml:"rel,href"`
}
type XMLEntry struct {
 XMLName xml.Name  `xml:"entry"`
 Link    []XMLLink `xml:"link,attr"`
}
type XMLFeed struct {
 XMLName xml.Name   `xml:"feed"`
 Entry   []XMLEntry `xml:"entry,attr"`
}

here i want to decode only link tag under entry tag.
following is the code i using to decode the xml into necessary values

var feed XMLFeed
//response got from http request is expected xml here which is already men tioned above
bodyBytes, _ := ioutil.ReadAll(response.Body)
   err := xml.Unmarshal(bodyBytes, &feed)
   if err != nil {
    log.Fatalf("Unable to unmarshall", err)
   }
   fmt.Println("number of entries:", feed)

but here output is only
 number of entries: {{http://www.w3.org/2005/Atom feed} []}
dont know what is going wrong here please suggest any changes to make this work fine


问:
Spring boot + GRPC Http2Exception
I am trying to set up GRPC server with spring boot. My VIP is pointing to server on port 8443. I am trying to connect to the GRPC server on my vip from my local GRPC client.

Is there anything that I am missing while following the approach GRPC with spring boot ?

```<code>2017-05-29 10:11:30.549  INFO 12796 --- [           main] n.d.s.a.grpc.server.GrpcServerLifecycle  : gRPC Server started, listening on address: 0.0.0.0, port: 8443
2017-05-29 10:11:30.971  INFO 12796 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (https)
2017-05-29 10:11:30.979  INFO 12796 --- [           main] c.a.IntentProcessorGroup1Application     : Started IntentProcessorGroup1Application in 26.45 seconds (JVM running for 27.737)
2017-05-29 10:11:41.736  WARN 12796 --- [-worker-ELG-3-1] io.grpc.netty.NettyServerHandler         : Connection Error

io.netty.handler.codec.http2.Http2Exception: HTTP/2 client preface string missing or corrupt. Hex dump for received bytes: 160301008e0100008a03039bda7533eee4bee56f87bd4a42
    at io.netty.handler.codec.http2.Http2Exception.connectionError(Http2Exception.java:85) ~[netty-codec-http2-4.1.8.Final.jar:4.1.8.Final]
</code>```

答:
The reason I was getting this error is because I was not starting my grpc server on TLS configuration correctly.
The issue is resolved now and details can be found here : https://github.com/yidongnan/grpc-spring-boot-starter/issues/44</p>

Title: Spring boot + GRPC Http2Exception

Body:
I am trying to set up GRPC server with spring boot. My VIP is pointing to server on port 8443. I am trying to connect to the GRPC server on my vip from my local GRPC client.

Is there anything that I am missing while following the approach GRPC with spring boot ?

2017-05-29 10:11:30.549  INFO 12796 --- [           main] n.d.s.a.grpc.server.GrpcServerLifecycle  : gRPC Server started, listening on address: 0.0.0.0, port: 8443
2017-05-29 10:11:30.971  INFO 12796 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (https)
2017-05-29 10:11:30.979  INFO 12796 --- [           main] c.a.IntentProcessorGroup1Application     : Started IntentProcessorGroup1Application in 26.45 seconds (JVM running for 27.737)
2017-05-29 10:11:41.736  WARN 12796 --- [-worker-ELG-3-1] io.grpc.netty.NettyServerHandler         : Connection Error

io.netty.handler.codec.http2.Http2Exception: HTTP/2 client preface string missing or corrupt. Hex dump for received bytes: 160301008e0100008a03039bda7533eee4bee56f87bd4a42
    at io.netty.handler.codec.http2.Http2Exception.connectionError(Http2Exception.java:85) ~[netty-codec-http2-4.1.8.Final.jar:4.1.8.Final]


问:
Is it possible to Git merge / push using Jenkins pipeline
I am trying to create a Jenkins workflow using a Jenkinsfile. All I want it to do is monitor the 'develop' branch for changes. When a change occurs, I want it to git tag and merge to master. I am using the GitSCM Step but the only thing that it appears to support is git clone. I don't want to have to shell out to do the tag / merge but I see no way around it. Does anyone know if this is possible? I am using BitBucket (on-prem) for my Git server.</p>

答:
If what you're after are the git credentials you can use the SSH Agent plugin like in this link: https://issues.jenkins-ci.org/browse/JENKINS-28335?focusedCommentId=260925&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-260925</p>

```<code>sshagent(['git-credentials-id']) {
  sh "git push origin master"
}
</code>```

Body:
If what you're after are the git credentials you can use the SSH Agent plugin like in this link: https://issues.jenkins-ci.org/browse/JENKINS-28335?focusedCommentId=260925&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-260925

sshagent(['git-credentials-id']) {
  sh "git push origin master"
}


问:
for loop inside for loop
I am trying to insert data to multidementional array, but 'for loop' inside for loop(inner 'for loop') not running (when i run the code inner loop not runnig only other 'for loop')you can clearly see that at result i attached with this quection.

Some code:

```<code>for(int s=0;s<=y;s++){  //y mean number of arrays, user can input any number for y in here y>=2
     int w=s+1;
     System.out.println("number of data for array"+" "+w+':');
     int night[][]=new int[s][x.nextInt()];
     for(int counter=0;counter<night.length;counter++){
         int m=counter+1;
         System.out.println("insert the number"+m+":");
         night[s][counter]=x.nextInt();

     }
}
</code>```

I am still learning Java please tell me why this not working

This is the result when i run that code

```<code>how much Arrays:
4
number of data for array 1:
6
number of data for array 2:
7
insert the number1:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at practice.Multi_array_data_input.main(Multi_array_data_input.java:42)
</code>```

答:
The problem is that you call a index in an array, which does not exists, because arrays in Java and JavaScript are zero-based. When you define an array with int[] array = new int[3] does this mean, that the indexes 0, 1, 2 are available. The index 3 is not part of the array. So to solve the problem you have to minimise the variable s by 1, when you call your night array.

```<code>for(int s=0;s<=y;s++){ // y mean number of arrays, user can input any number for y in here y>=2
    int w=s+1;
    System.out.println("number of data for array "+w+':');
    int night[][]=new int[s][x.nextInt()];
    for(int counter=0;counter<night.length;counter++){
        int m=counter+1;
        System.out.println("insert the number "+m+":");
        night[s - 1][counter]=x.nextInt();
    }
}
</code>```

Title: for loop inside for loop

Body:
I am trying to insert data to multidementional array, but 'for loop' inside for loop(inner 'for loop') not running (when i run the code inner loop not runnig only other 'for loop')you can clearly see that at result i attached with this quection.

Some code:

for(int s=0;s<=y;s++){  //y mean number of arrays, user can input any number for y in here y>=2
     int w=s+1;
     System.out.println("number of data for array"+" "+w+':');
     int night[][]=new int[s][x.nextInt()];
     for(int counter=0;counter<night.length;counter++){
         int m=counter+1;
         System.out.println("insert the number"+m+":");
         night[s][counter]=x.nextInt();

     }
}

I am still learning Java please tell me why this not working

This is the result when i run that code

how much Arrays:
4
number of data for array 1:
6
number of data for array 2:
7
insert the number1:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at practice.Multi_array_data_input.main(Multi_array_data_input.java:42)

Body:
The problem is that you call a index in an array, which does not exists, because arrays in Java and JavaScript are zero-based. When you define an array with int[] array = new int[3] does this mean, that the indexes 0, 1, 2 are available. The index 3 is not part of the array. So to solve the problem you have to minimise the variable s by 1, when you call your night array.

for(int s=0;s<=y;s++){ // y mean number of arrays, user can input any number for y in here y>=2
    int w=s+1;
    System.out.println("number of data for array "+w+':');
    int night[][]=new int[s][x.nextInt()];
    for(int counter=0;counter<night.length;counter++){
        int m=counter+1;
        System.out.println("insert the number "+m+":");
        night[s - 1][counter]=x.nextInt();
    }
}


问:
No enrollment ID or enrollment secret has been provided
I'm using the RESTful API to communicate to the ledger. I've added some protection to the API by using Passport.

Now I'd like to issue an identity to a specific participant in the network. The CLI command works just fine.

composer identity issue -n 'epd' -i admin -s adminpw -u "myid" -a "nl.epd.blockchain.Patient#myid"

But whenever I try to use the RESTful API call it keeps saying:

No enrollment ID or enrollment secret has been provided

The payload I am sending looks like the following

```<code>{
  "participant": "nl.epd.blockchain.Patient#myid",
  "userID": "myid",
  "options": {
    "enrollmentID" : "admin",
    "enrollmentSecret" : "adminpw"
   }
}
</code>```

To startup the REST server I use the following code:

```<code>composer-rest-server -n epd -p defaultProfile -i admin -s adminpw -N never -P 3000 -S true
</code>```

So I guess my payload is incorrect because it can't find the enrollmentid and secret. So what's the correct format for the payload?

答:
You don't need to put the enrollmentID and enrollmentSecret as part of the payload. Those get passed in via the composer-rest-server.

Here are some instructions on enabling REST authentication for a business network. https://hyperledger.github.io/composer/integrating/enabling-rest-authentication.html

I think the step you are missing is Adding a Blockchain identity to the default wallet

Body:
I'm using the RESTful API to communicate to the ledger. I've added some protection to the API by using Passport.

Now I'd like to issue an identity to a specific participant in the network. The CLI command works just fine.

composer identity issue -n 'epd' -i admin -s adminpw -u "myid" -a "nl.epd.blockchain.Patient#myid"

But whenever I try to use the RESTful API call it keeps saying:

No enrollment ID or enrollment secret has been provided

The payload I am sending looks like the following

{
  "participant": "nl.epd.blockchain.Patient#myid",
  "userID": "myid",
  "options": {
    "enrollmentID" : "admin",
    "enrollmentSecret" : "adminpw"
   }
}

To startup the REST server I use the following code:

composer-rest-server -n epd -p defaultProfile -i admin -s adminpw -N never -P 3000 -S true

So I guess my payload is incorrect because it can't find the enrollmentid and secret. So what's the correct format for the payload?


问:
Spring Data REST - RepositoryEventHandler methods not getting invoked for POST method?
I have the following domain object and DTO defined.

Country.java

```<code>@Data
@Entity
public class Country extends ResourceSupport {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long countryID;

    @NotBlank(message = "Country name is a required field")
    private String countryName;

    private String countryNationality;
}
</code>```

CountryDTO.java

```<code>@Data

public class CountryDTO {

    private List<Country> countries;
}
</code>```

I have overridden the POST method in the RepositoryRestController for the country class.

```<code>@RepositoryRestController
public class CountryController {

    @Autowired
    private CountryRepository repo;

    @RequestMapping(method = POST, value = "countries")
    public @ResponseBody ResponseEntity<?> createCountry(@RequestBody Resource<CountryDTO> dto,
            Pageable page, PersistentEntityResourceAssembler resourceAssembler) {

        Country savedCountry = repo.save(dto.getContent().getCountries());
        return new ResponseEntity<>(resourceAssembler.toResource(savedCountry), HttpStatus.OK);
    }

}
</code>```

Now I have defined a RepositoryEventHandler to handle validations.

```<code>@Component
@RepositoryEventHandler
public class CountryHandler {

    @HandleBeforeCreate
    public void handleBeforeCreate(Country country) {

        System.out.println("testing");

}
</code>```

But when I send a POST request to the endpoint http://localhost:8080/countries, the eventhandler does not get invoked. Is there anything I am doing wrong?

UPDATE 1:
I am sending the following JSON to the endpoint using Postman.

```<code>"countries":[{
    "countryName":"Australia",
    "countryNationality":"Australian"

}]
</code>```

答:
It is difficult to give you an exact solution not knowing how you are invoking the request. But possible reason is that you are missing the slash symbol @RequestMapping value attribute:

```<code>@RequestMapping(method = POST, value = "countries")
</code>```

Should be:

```<code>@RequestMapping(method = POST, value = "/countries")
</code>```

Body:
I have the following domain object and DTO defined.

Country.java

@Data
@Entity
public class Country extends ResourceSupport {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long countryID;

    @NotBlank(message = "Country name is a required field")
    private String countryName;

    private String countryNationality;
}

CountryDTO.java

@Data

public class CountryDTO {

    private List<Country> countries;
}

I have overridden the POST method in the RepositoryRestController for the country class.

@RepositoryRestController
public class CountryController {

    @Autowired
    private CountryRepository repo;

    @RequestMapping(method = POST, value = "countries")
    public @ResponseBody ResponseEntity<?> createCountry(@RequestBody Resource<CountryDTO> dto,
            Pageable page, PersistentEntityResourceAssembler resourceAssembler) {

        Country savedCountry = repo.save(dto.getContent().getCountries());
        return new ResponseEntity<>(resourceAssembler.toResource(savedCountry), HttpStatus.OK);
    }

}

Now I have defined a RepositoryEventHandler to handle validations.

@Component
@RepositoryEventHandler
public class CountryHandler {

    @HandleBeforeCreate
    public void handleBeforeCreate(Country country) {

        System.out.println("testing");

}

But when I send a POST request to the endpoint http://localhost:8080/countries, the eventhandler does not get invoked. Is there anything I am doing wrong?

UPDATE 1:
I am sending the following JSON to the endpoint using Postman.

"countries":[{
    "countryName":"Australia",
    "countryNationality":"Australian"

}]

Body:
It is difficult to give you an exact solution not knowing how you are invoking the request. But possible reason is that you are missing the slash symbol @RequestMapping value attribute:

@RequestMapping(method = POST, value = "countries")

Should be:

@RequestMapping(method = POST, value = "/countries")


问:
How to find a set of three or more number?
Can you please help me find a set of three numbers og more with a sum of X in a given list.

Fx a set of tree numbers with a sum of 6 in the list 1,2,3,4,5,6,7,8,9 would be 1+2+3

I can do this with a set of two numbers se VBA code below

```<code>Function Set(list As Range, x As Integer)
  k = 0
  j = 0
  For Each i In list
    If x = list(1 + k) + list(list.Rows.Count - j) Then
      Set = k & ", " & j
    ElseIf list(1 + k) + list(list.Rows.Count - j) > x Then
      j = j + 1
    ElseIf list(1 + k) + list(list.Rows.Count - j) < x Then
      k = k + 1
    End If
  Next i
End Function
</code>```

Best regards
Kresten

答:
Maybe,</p>

```<code>Function myPair(list As Range, x As Integer)
    Dim vDB, vR(1 To 3)
    Dim i As Long, n As Long, k As Long
    vDB = list
    n = UBound(vDB, 1)
    For i = 1 To n
        For j = i + 1 To n
            For k = j + 1 To n
                If vDB(i, 1) + vDB(j, 1) + vDB(k, 1) = x Then
                    vR(1) = vDB(i, 1): vR(2) = vDB(j, 1): vR(3) = vDB(k, 1)
                    myPair = Join(vR, ",")
                End If
            Next k
        Next j
    Next i

End Function
</code>```

Body:
Can you please help me find a set of three numbers og more with a sum of X in a given list.

Fx a set of tree numbers with a sum of 6 in the list 1,2,3,4,5,6,7,8,9 would be 1+2+3

I can do this with a set of two numbers se VBA code below

Function Set(list As Range, x As Integer)
  k = 0
  j = 0
  For Each i In list
    If x = list(1 + k) + list(list.Rows.Count - j) Then
      Set = k & ", " & j
    ElseIf list(1 + k) + list(list.Rows.Count - j) > x Then
      j = j + 1
    ElseIf list(1 + k) + list(list.Rows.Count - j) < x Then
      k = k + 1
    End If
  Next i
End Function

Best regards
Kresten

Body:
Maybe,

Function myPair(list As Range, x As Integer)
    Dim vDB, vR(1 To 3)
    Dim i As Long, n As Long, k As Long
    vDB = list
    n = UBound(vDB, 1)
    For i = 1 To n
        For j = i + 1 To n
            For k = j + 1 To n
                If vDB(i, 1) + vDB(j, 1) + vDB(k, 1) = x Then
                    vR(1) = vDB(i, 1): vR(2) = vDB(j, 1): vR(3) = vDB(k, 1)
                    myPair = Join(vR, ",")
                End If
            Next k
        Next j
    Next i

End Function


问:
Imageview not following finger touch
I want to build an app that has an imageview and it simply follows the finger touch. In other words, the imageview follows the touch of the finger. I have partially achieved this, in the sense that the imageview is following the touch of the finger but the problem is that it is at some offset. The imageview is about an inch down the actual touch.

Below is my code:

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

ImageView img;

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

    img = (ImageView)findViewById(R.id.img1);
    img.setImageResource(R.drawable.ic_remove_circle_black_24dp);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
    img.setX(event.getX());
    img.setY(event.getY());
    return false;
}
</code>```

}

What could be the reason behind the offset?

Edit: Solution

Following code does what I need:

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

    ImageView img;
    int[] viewCoords = new int[2];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView)findViewById(R.id.img1);
        img.setImageResource(R.drawable.ic_remove_circle_black_24dp);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event){
        img.getLocationOnScreen(viewCoords);
        img.setX(event.getX()-(viewCoords[0]-img.getX()));
        img.setY(event.getY()-(viewCoords[1]-img.getY()));
        return true;

    }
}
</code>```

Thanks to Doomsknight for the direction.

答:
From what I can see, you are using the X and Y coordinates of the touch event of the Screen.

And then drawing this coordinates on the X and Y of the ImageView.

This will cause the offset you are seeing, as they do not match up, as the imageview probably isnt at the very top of your screen.

What I think you are trying to do is get the X and Y, of the actual image.
You will therefore need to offset the coordinates accordingly.

There is a good example of this already of getting the offset, and removing it: see link below.

https://stackoverflow.com/a/11312423/940834

You can get the top left corner of your view as follows:

```<code> int[] viewCoords = new int[2];
 imageView.getLocationOnScreen(viewCoords);
</code>```

From this and the touch
     coordinates you can calculate the point inside the ImageView:

```<code> int touchX = (int) event.getX();
 int touchY = (int) event.getY();

 int imageX = touchX - viewCoords[0]; // viewCoords[0] is the X coordinate
 int imageY = touchY - viewCoords[1]; // viewCoords[1] is the y coordinate
</code>```

Title: Imageview not following finger touch

Body:
I want to build an app that has an imageview and it simply follows the finger touch. In other words, the imageview follows the touch of the finger. I have partially achieved this, in the sense that the imageview is following the touch of the finger but the problem is that it is at some offset. The imageview is about an inch down the actual touch.

Below is my code:

public class MainActivity extends AppCompatActivity {

ImageView img;

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

    img = (ImageView)findViewById(R.id.img1);
    img.setImageResource(R.drawable.ic_remove_circle_black_24dp);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
    img.setX(event.getX());
    img.setY(event.getY());
    return false;
}

}

What could be the reason behind the offset?

Edit: Solution

Following code does what I need:

public class MainActivity extends AppCompatActivity {

    ImageView img;
    int[] viewCoords = new int[2];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView)findViewById(R.id.img1);
        img.setImageResource(R.drawable.ic_remove_circle_black_24dp);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event){
        img.getLocationOnScreen(viewCoords);
        img.setX(event.getX()-(viewCoords[0]-img.getX()));
        img.setY(event.getY()-(viewCoords[1]-img.getY()));
        return true;

    }
}

Thanks to Doomsknight for the direction.

Body:
From what I can see, you are using the X and Y coordinates of the touch event of the Screen.

And then drawing this coordinates on the X and Y of the ImageView.

This will cause the offset you are seeing, as they do not match up, as the imageview probably isnt at the very top of your screen.

What I think you are trying to do is get the X and Y, of the actual image.
You will therefore need to offset the coordinates accordingly.

There is a good example of this already of getting the offset, and removing it: see link below.

https://stackoverflow.com/a/11312423/940834

You can get the top left corner of your view as follows:

 int[] viewCoords = new int[2];
 imageView.getLocationOnScreen(viewCoords);

From this and the touch
     coordinates you can calculate the point inside the ImageView:

 int touchX = (int) event.getX();
 int touchY = (int) event.getY();

 int imageX = touchX - viewCoords[0]; // viewCoords[0] is the X coordinate
 int imageY = touchY - viewCoords[1]; // viewCoords[1] is the y coordinate


问:
How to change property of more than one qlineedit at once
I have done some coding for L00 (name of my first QLineEdit).

I want to do the same for other 99 widgets (up to L99). I don't wanna copy paste it 100 hundred times.

```<code>void MainWindow::on_L00_returnPressed(){
    QString c = ui->L00->text();
    char d = QString(c).at(0).toLatin1();
    if(d>=65&&d<=90||d>=97&&d<=122)
    {
        square[0]=d;
        ui->MessageBox->setText("Alphabet succesfully entered");
        ui->L00->setReadOnly(true);
        ui->L00->setStyleSheet("QLineEdit { background: rgb(0, 255, 255);}");
    }
    else
    {
        ui->MessageBox->setText("Enter Alphabets Only");
        ui->L00->setText("");
    }
}
</code>```

答:
Problem starts with:

I have done some coding for L00 (name of my first QLineEdit) … 99 widgets (up to L99).

This means that you designed your application incorrectly.

I'm almost sure that you should use QTableView or QTableWidget with QAbstractTableModel or QStandartItemModel.

Also setStyleSheet should be applied on QApplication or at least on top level widget. This is how stylesheet is supposed to be used.

Body:
I have done some coding for L00 (name of my first QLineEdit).

I want to do the same for other 99 widgets (up to L99). I don't wanna copy paste it 100 hundred times.

void MainWindow::on_L00_returnPressed(){
    QString c = ui->L00->text();
    char d = QString(c).at(0).toLatin1();
    if(d>=65&&d<=90||d>=97&&d<=122)
    {
        square[0]=d;
        ui->MessageBox->setText("Alphabet succesfully entered");
        ui->L00->setReadOnly(true);
        ui->L00->setStyleSheet("QLineEdit { background: rgb(0, 255, 255);}");
    }
    else
    {
        ui->MessageBox->setText("Enter Alphabets Only");
        ui->L00->setText("");
    }
}


问:
C++ Array out of strings
I have a new class assignment where i need to make Hangman in c++. I got everything set but I can't figure out how to make an array from a string that a user has already entered. Here is what i got.

```<code>#include <iostream>
using namespace std;

int main(){
    string stringToGuess;
    cout << "Hello user, please enter a word to play hangman" << endl;
    cin >> stringToGuess;
    int arrLength = stringToGuess.length();
    cout << arrLength << endl;
    char arr_To_Guess[arrLength] = {atoi(stringToGuess.c_str())};
    for (int i = 0; i < arrLength; i++){
        cout << arr_To_Guess << " ";
    }
}
</code>```

I realize that i can accomplish this without making an array from the string but it is required to do so in the assignment.                                                      .                                                                                Instructions from your teacher:
We are going to do this one step at a time.
Here is the first step:
Ask the user to enter a word, save it to a string called
stringToGuess
Then, create 2 arrays of chars called
arrToGuess, arrCurrGuess
The first array will contain all of the letters in the word the user entered, the second array will contain all of the letters the player has guess correctly so far.
If the user enter the word
programming
The values of the variables would be:
stringToGuess: "PROGRAMMING"
arrToGuess: [P, R, O, G, R, A, M, M, I, N, G]
arrCurGuess:[_, _, _, _, _, _, _, _, _, _, _]
Your job is to make this work.
Look at this program first: https://repl.it/IZQd/0
Some things to pay attention to:
1) Make all of the letters capital.

答:
You know, a string is an array of char, which means you can do this.

```<code>string stringToGuess;
cout << "Hello user, please enter a word to play hangman" << endl;
cin >> stringToGuess;
for(int  i = 0; i < stringToGuess.length(); i++)
{
    cout << stringToGuess[i];
}
</code>```

Title: C++ Array out of strings

Body:
I have a new class assignment where i need to make Hangman in c++. I got everything set but I can't figure out how to make an array from a string that a user has already entered. Here is what i got.

#include <iostream>
using namespace std;

int main(){
    string stringToGuess;
    cout << "Hello user, please enter a word to play hangman" << endl;
    cin >> stringToGuess;
    int arrLength = stringToGuess.length();
    cout << arrLength << endl;
    char arr_To_Guess[arrLength] = {atoi(stringToGuess.c_str())};
    for (int i = 0; i < arrLength; i++){
        cout << arr_To_Guess << " ";
    }
}

I realize that i can accomplish this without making an array from the string but it is required to do so in the assignment.                                                      .                                                                                Instructions from your teacher:
We are going to do this one step at a time.
Here is the first step:
Ask the user to enter a word, save it to a string called
stringToGuess
Then, create 2 arrays of chars called
arrToGuess, arrCurrGuess
The first array will contain all of the letters in the word the user entered, the second array will contain all of the letters the player has guess correctly so far.
If the user enter the word
programming
The values of the variables would be:
stringToGuess: "PROGRAMMING"
arrToGuess: [P, R, O, G, R, A, M, M, I, N, G]
arrCurGuess:[_, _, _, _, _, _, _, _, _, _, _]
Your job is to make this work.
Look at this program first: https://repl.it/IZQd/0
Some things to pay attention to:
1) Make all of the letters capital.

Body:
You know, a string is an array of char, which means you can do this.

string stringToGuess;
cout << "Hello user, please enter a word to play hangman" << endl;
cin >> stringToGuess;
for(int  i = 0; i < stringToGuess.length(); i++)
{
    cout << stringToGuess[i];
}

ContentLicense: CC BY-SA 4.0


问:
How to remove "+00:00" from end of datetime.datetime object. (not remove time)
I'm calling a database, and returning a datetime.datetime object as the 3rd item in a tuple.

The SQL statement is: SELECT name,name_text,time_received FROM {}.{} WHERE DATE(time_received)=CURRENT_DATE LIMIT 1

If I do print(mytuple[2]) it returns something like: 2017-05-31 17:21:19+00:00 but always with that "+00:00" at the end for every value. How do I remove that trailing "+00:00" from the datetime.datetime object?

I've tried different string-stripping methods like print(mytuple[2][:-6]) but it gives me an error saying that datetime.datetime object is not subscriptable. Thanks for any help!

答:
Docs:

to_char(timestamp, 'YYYY-MM-DD HH24:MM:SS') would be one way.

For your specific case:

```<code>SELECT name,name_text,to_char(time_Received, 'YYYY-MM-DD HH24:MM:SS')
</code>```

Time received (mytuple[2]) would then be formatted as character data instead of time.

So if your program is handling it as a date, we'd have to convert it back to a date datatype

Body:
Docs:

to_char(timestamp, 'YYYY-MM-DD HH24:MM:SS') would be one way.

For your specific case:

SELECT name,name_text,to_char(time_Received, 'YYYY-MM-DD HH24:MM:SS')

Time received (mytuple[2]) would then be formatted as character data instead of time.

So if your program is handling it as a date, we'd have to convert it back to a date datatype


问:
Add extra keys to responses in dingo/api Laravel package
I'm using dingo/api laravel package to create an API.

I want to add success key response to every API call. If we have an error, success: false and if all is OK, then success: true.

Final response must looks like this:

```<code>{
"success":true,
"data": [{}, {}]
}
</code>```

I know that there is a ->setMeta($meta); method to add extra keys like this :

```<code>$meta = array(
    'success' => 'true',
    'status_code' => 200
);

return $this->response->collection($users, new UserTransformer)->setMeta($meta);
</code>```

that creates bellow response :

```<code>{
    "data": [{}, {}],
    "meta": {
        "success": true,
        "status_code": 200
    },
}
</code>```

As you can see ,setMeta adds extra keys under a meta key that I do not want that.

I readed it's Responses documentations but I could not find any solution.

How to do that?

答:
This will help you

```<code>$api->get('book/{id}', function ($id){
    $book = Book::FindOrFail($id);
    $_res['success'] = true;
    $_res['book'] = $book;
    return $_res;
});
</code>```

and edit config/api.php

```<code>'errorFormat' => [
    'success' => false,
    'message' => ':message',
    'errors' => ':errors',
    'code' => ':code',
    'status_code' => ':status_code',
    'debug' => ':debug',
],
</code>```

Body:
I'm using dingo/api laravel package to create an API.

I want to add success key response to every API call. If we have an error, success: false and if all is OK, then success: true.

Final response must looks like this:

{
"success":true,
"data": [{}, {}]
}

I know that there is a ->setMeta($meta); method to add extra keys like this :

$meta = array(
    'success' => 'true',
    'status_code' => 200
);

return $this->response->collection($users, new UserTransformer)->setMeta($meta);

that creates bellow response :

{
    "data": [{}, {}],
    "meta": {
        "success": true,
        "status_code": 200
    },
}

As you can see ,setMeta adds extra keys under a meta key that I do not want that.

I readed it's Responses documentations but I could not find any solution.

How to do that?

Body:
This will help you

$api->get('book/{id}', function ($id){
    $book = Book::FindOrFail($id);
    $_res['success'] = true;
    $_res['book'] = $book;
    return $_res;
});

and edit config/api.php

'errorFormat' => [
    'success' => false,
    'message' => ':message',
    'errors' => ':errors',
    'code' => ':code',
    'status_code' => ':status_code',
    'debug' => ':debug',
],


问:
How to increase slider values in whole numbers when starting value is 2 decimals
I have a price slider that submits and works as it should. The only thing it doesn't do is increase the values of the slider in whole numbers when the starting value is a 2 decimal number.
It also doesn't display the initial 2 decimal number. Just to show what I mean here is the code:

```<code> $Deposit= '12.85';
<script>
   Deposit_increase = <?php echo (isset($_GET['Deposit_increase'])) ?
   $_GET['Deposit_increase'] : 0 ?>;

   $(document).ready(function() {
   $( "#slider-range-min" ).slider({
      range: "min",
      value: <?php echo $Deposit ?>,
      min: <?php echo $Deposit ?>,
      max: 3000,

      values : [Deposit_increase],
                slide : function(event, ui) {
                    $("#Deposit_increase").val(ui.values[0]);
                },
        change: function() {
            $("#increase_form").submit();
        }
    });
    $("#Deposit_increase").val($("#slider-range-min").slider("values", 0));
});
  </script>
</code>```

The form:

```<code> <form action="" id="increase_form" method="get">

           <p  style="margin-left:12%; color:#2872bd; font-weight:bold; text-align:left">
  Change your Depost<br><br>
Deposit: £
  <input type="text" id="Deposit_increase" name="Deposit_increase"  style="border:0; color:#2872bd; font-weight:bold; text-align:left"  value="<?php echo $_GET['Deposit_increase']; ?>">

</p>
        <div id="slider-range-min"></div></form>
</code>```

Here it displays as follows:
Deposit: £12.9  (instead of £12.85)

The slider uses increments of 1 so all values will be shown as 13.9, 14.9. 15.9 etc.

What I want the slider to show is:
14, 15, 16 etc.

Is there a way to achieve this? Any help welcome

答:
I don't see the increment function in your code, but you should be able to raise the slider value using the Math library.

You can do this by listening the slider input value and transforming this value before it gets displayed again.

```<code>var newVal = Math.ceil(val);
</code>```

Body:
I have a price slider that submits and works as it should. The only thing it doesn't do is increase the values of the slider in whole numbers when the starting value is a 2 decimal number.
It also doesn't display the initial 2 decimal number. Just to show what I mean here is the code:

 $Deposit= '12.85';

The form:

 <form action="" id="increase_form" method="get">

  Change your Depost

Deposit: £
  <input type="text" id="Deposit_increase" name="Deposit_increase"  style="border:0; color:#2872bd; font-weight:bold; text-align:left"  value="<?php echo $_GET['Deposit_increase']; ?>">

</form>

Here it displays as follows:
Deposit: £12.9  (instead of £12.85)

The slider uses increments of 1 so all values will be shown as 13.9, 14.9. 15.9 etc.

What I want the slider to show is:
14, 15, 16 etc.

Is there a way to achieve this? Any help welcome

Body:
I don't see the increment function in your code, but you should be able to raise the slider value using the Math library.

You can do this by listening the slider input value and transforming this value before it gets displayed again.

var newVal = Math.ceil(val);


问:
Get open activity of the foreground app
I need to get the current Activity of the foreground App. I tried following this answer and later used this library(because the first solution only worked from Lollipop), and them indeed worked well telling the foreground app's package name, but I need to know what activity is open.</p>

答: You should not be able to do it due to security issues. You don't want another app to know your current open activity. So other apps don't want you to spy on them. This is an OS limitation.</p>

Title: Get open activity of the foreground app


问:
How to add custom shape in tableau?
There are many shape available but how to add our own custom shape ?

答:
Create .png format image with square fit image(height and width same).

Copy in My Tableau Repository, by default the repository in Document folder.

Refresh or restart your Tableau you custom logo will be there.

Title: How to add custom shape in tableau?


问:
Calculate two different value in different rows
I want to get total first row then if the value in second row in FirstValue column sum with upper Total,
but if the value in Second value the total upper value Sub with the Second value

```<code>Date        FirstValue   SecondValue     (New Column)
2017-06-01  312500.00     0.00            312,000
2017-06-03  0.00          300000.00       12,500
2017-06-04  400000.00     0.00            412,500
2017-06-04  1600000.00    0.00            2,012,500
2017-06-07  0.00          200000.00       1,812,500
2017-06-15  0.00          500000.00       1,312,500

Last Value is   1,312,500
</code>```

as I mentioned in a picture

答: Add a new column which is the 0-SecondValue, then your desired answer is a runningtotal of firstValue+inverseSecondValue</p>

Body:
I want to get total first row then if the value in second row in FirstValue column sum with upper Total,
but if the value in Second value the total upper value Sub with the Second value

Date        FirstValue   SecondValue     (New Column)
2017-06-01  312500.00     0.00            312,000
2017-06-03  0.00          300000.00       12,500
2017-06-04  400000.00     0.00            412,500
2017-06-04  1600000.00    0.00            2,012,500
2017-06-07  0.00          200000.00       1,812,500
2017-06-15  0.00          500000.00       1,312,500

Last Value is   1,312,500

as I mentioned in a picture


问:
xargs with export is not working
I have a file which looks as below.

```<code>HOST=localhost
PORT=8080
</code>```

I want to export the above into environment. I am executing the following command to export the variables in file to environment.

cat <FileName> | xargs export

I am getting the following exception when trying to run the above command.

xargs: export: No such file or directory

答:
export is a built-in function, and xargs takes executable as an argument, not a function. Also, there is no sense in wrapping export into some script or subshell,  xargs won't fail in such case, but your vars won't be exported anyway.
So better to choose some another approach, w/o xargs, like showed in the previous comment.

Title: xargs with export is not working

Body:
I have a file which looks as below.

HOST=localhost
PORT=8080

I want to export the above into environment. I am executing the following command to export the variables in file to environment.

cat <FileName> | xargs export

I am getting the following exception when trying to run the above command.

xargs: export: No such file or directory


问:
string split based on char \
Got a bit of a mind freeze at the moment.
I have the following syntax:-

```<code>        string[] repname = Thread.CurrentPrincipal.Identity.ToString().Split('\');
</code>```

and I get an error on the split character. Can anyone advise on how I can do the split using the \ character as the delimiter?

Cheers

答:
```<code> string[] repname = Thread.CurrentPrincipal.Identity.ToString().Split(new string[]{"\\"}, StringSplitOptions.None);
</code>```

Title: string split based on char \

Body:
Got a bit of a mind freeze at the moment.
I have the following syntax:-

        string[] repname = Thread.CurrentPrincipal.Identity.ToString().Split('\');

and I get an error on the split character. Can anyone advise on how I can do the split using the \ character as the delimiter?

Cheers


问:
G++ math.h problem
I'm hoping someone has come across this problem before too.

I am trying to use visual studio to develop for Linux with G++.

I am trying to include math.h and use tanf()

If I compile with the g++ compiler, "arm-none-linux-gnueabi-g++", everything works

but if I add this include directory, which the docs say is the right one, and
"CodeSourcery\Sourcery G++ Lite\arm-none-linux-gnueabi\libc\usr\include\"
then include math.h,

visual studio does not recognize any of the math functions, namely tanf().

anyone have any idea why?

thanks for any help.

edit:
the same app successfully compiles with this command line:

arm-none-linux-gnueabi-g++ -o test main.cpp "-I%PALMPDK%\include" "-I%PALMPDK%\include\SDL" "-L%PALMPDK%\device\lib" -Wl,--allow-shlib-undefined -lSDL -lGLESv2 -lpdl

答:
I found a solution!

I downloaded and installed MinGW instead, and that works fine. I have all the function prototypes for extra stuff like gettimeofday(), and all the regular suff like tanf() is still working fine.

ps: visual studio even has a button for "Use Output Window" where it nicely dumps any errors that are generated by "arm-none-linux-gnueabi-g++"

Title: G++ math.h problem


问:
How to reinitialize socket after few hours in android?
The application is not receiving any messages from the server even if it is connected to a server after several ideal hours. How to reconnect them to a server?</p>

答: are you sure that your socket keeps the connection? you should use a timed task to check the connection status periodically.</p>


问:
Passing waypoint info to comgooglemaps (Google Maps URL Scheme)
I am in the process of creating an app using the Google Maps api to generate random biking routes (http://sutsurikeru.com/maps) and it works fine so far, but the issue I am having is passing the generated route, including the following info to the google maps app:

Start Destination

Way-point (randomly generated using https://gis.stackexchange.com/questions/25877/how-to-generate-random-locations-nearby-my-location)

End Destination (same as the start destination)

Once I've got all the lat/long information I pass it to a button that is created when the route is generated so that it can pass the route to the Google Maps App, but I am unsure how to pass the way-point as there is no mention of it in the docs - https://developers.google.com/maps/documentation/ios-sdk/urlscheme

```<code>$('#goRide').append('<a class="goridebtn" href="comgooglemaps://?saddr=' + address + '&daddr=' + address + '&directionsmode=bicycling">Go ride</a>');
</code>```

I guess my question is then, can I include the way-point information when I am passing it to the Google Maps App?

答:
i couldn't find the answer for that too , so i ended using:

"comgooglemapsurl" instead..

this way you can pass a full url (same onese used in the browser)
the format will be something like this:

```<code>comgooglemapsurl://www.google.com/maps/dir/STARTING_POINT/WAYPOINT_1/WAYPOINT_2/WAYPOINT_3/WAYPOINT_4/DESTINATION
</code>```

you can add as many points as u wish

```<code>comgooglemapsurl://www.google.com/maps/dir/24.848607,46.660478/24.748607,46.760478/24.778607,46.784478
</code>```

https://developers.google.com/maps/documentation/urls/ios-urlscheme

Body:
I am in the process of creating an app using the Google Maps api to generate random biking routes (http://sutsurikeru.com/maps) and it works fine so far, but the issue I am having is passing the generated route, including the following info to the google maps app:

Start Destination

Way-point (randomly generated using https://gis.stackexchange.com/questions/25877/how-to-generate-random-locations-nearby-my-location)

End Destination (same as the start destination)

Once I've got all the lat/long information I pass it to a button that is created when the route is generated so that it can pass the route to the Google Maps App, but I am unsure how to pass the way-point as there is no mention of it in the docs - https://developers.google.com/maps/documentation/ios-sdk/urlscheme

$('#goRide').append('Go ride');

I guess my question is then, can I include the way-point information when I am passing it to the Google Maps App?

Body:
i couldn't find the answer for that too , so i ended using:

"comgooglemapsurl" instead..

this way you can pass a full url (same onese used in the browser)
the format will be something like this:

comgooglemapsurl://www.google.com/maps/dir/STARTING_POINT/WAYPOINT_1/WAYPOINT_2/WAYPOINT_3/WAYPOINT_4/DESTINATION

you can add as many points as u wish

comgooglemapsurl://www.google.com/maps/dir/24.848607,46.660478/24.748607,46.760478/24.778607,46.784478

https://developers.google.com/maps/documentation/urls/ios-urlscheme


问:
How to run one update and commit in single command in ORACLE
I want to run a update query in ORACLE but to reflect the change of that query (means updating the value in database with receptive values) i have to run a commit; after that query (then only the value change will be updated in the database). So, how can i pass the update statement and the commit in same line through C#.

i am running the query like below,

```<code>UPDATE table_name
   SET columnname1 = 'N',
       columnname2 = 1
 WHERE columnname3 = '-2085371064';

COMMIT;
</code>```

答:
Usually, you don't want explicit commit since all the changes will be auto commited on the connection close. However, if you insist on COMMIT you can do it with a help of Oracle's anonymous block:

```<code> //TODO: put the right connection here
 using (OracleConnection con = new OracleConnection(ConnectionStringHere)) {
   con.Open();

   string sql =
     @"BEGIN -- Anonymous block: run these queries (update, commit) together
         UPDATE table_name
            SET columnname1 = 'N',
                columnname2 = 1
          WHERE columnname3 = '-2085371064'; -- Is it really a string?

         COMMIT; -- Not necessary, but possible
       END;";

   using (var q = con.CreateCommand()) {
     q.CommandText = sql;

     q.ExecuteNonQuery();
   }
 }
</code>```

Body:
I want to run a update query in ORACLE but to reflect the change of that query (means updating the value in database with receptive values) i have to run a commit; after that query (then only the value change will be updated in the database). So, how can i pass the update statement and the commit in same line through C#.

i am running the query like below,

UPDATE table_name
   SET columnname1 = 'N',
       columnname2 = 1
 WHERE columnname3 = '-2085371064';

COMMIT;

Body:
Usually, you don't want explicit commit since all the changes will be auto commited on the connection close. However, if you insist on COMMIT you can do it with a help of Oracle's anonymous block:

 //TODO: put the right connection here
 using (OracleConnection con = new OracleConnection(ConnectionStringHere)) {
   con.Open();

   string sql =
     @"BEGIN -- Anonymous block: run these queries (update, commit) together
         UPDATE table_name
            SET columnname1 = 'N',
                columnname2 = 1
          WHERE columnname3 = '-2085371064'; -- Is it really a string?

         COMMIT; -- Not necessary, but possible
       END;";

   using (var q = con.CreateCommand()) {
     q.CommandText = sql;

     q.ExecuteNonQuery();
   }
 }


问:
How to import js file in react component?
```<code>$( "#left_arrow" ).click(function() {
  if ($(".left_block").hasClass("w-0")) {
     $(".left_block" ).removeClass("w-0");
   }else{
     $(".left_block" ).addClass("w-0");
   }
 });
</code>```

In the custom.js I am having the script code above feature is not working when importing with below.

```<code> import * as script from '../js/custom.js';
</code>```

In the Html page when I load this file its working but when writing in react component its not working

答:
You should not mix with jquery with React, What you want to achieve can easily be implemented in React like

class App extends React.Component {
  state = {
    class: 'w-0'
  }
  handleClick=()=> {
    if(this.state.class === 'w-0') {
      this.setState({class: ''})
    } else{
      this.setState({class: 'w-0'})
    }
  }
  render() {
    return (

Arrow

Hello World

    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="app"></div></code>```

Body:
$( "#left_arrow" ).click(function() {
  if ($(".left_block").hasClass("w-0")) {
     $(".left_block" ).removeClass("w-0");
   }else{
     $(".left_block" ).addClass("w-0");
   }
 });

In the custom.js I am having the script code above feature is not working when importing with below.

 import * as script from '../js/custom.js';

In the Html page when I load this file its working but when writing in react component its not working

Body:
You should not mix with jquery with React, What you want to achieve can easily be implemented in React like

class App extends React.Component {
  state = {
    class: 'w-0'
  }
  handleClick=()=> {
    if(this.state.class === 'w-0') {
      this.setState({class: ''})
    } else{
      this.setState({class: 'w-0'})
    }
  }
  render() {
    return (
      <div>
          <div id="left_arrow" className="left_arrow" onClick={this.handleClick}><i className="fa fa-chevron-left" />Arrow</div>

          <div className={"left_block " + this.state.class}>Hello World</div>
      </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="app"></div>


问:
Why jenkins can not perform certain names of jmx?
1.It can't perform when my script name is lotteryOnline:

2.But changed to other names (such as game), BUILD SUCCESSFUL：

答:
Most likely your JMeter test execution for this lotteryOnline test plan has failed. The reason of failure you can see in the jmeter.log file. If you don't see the log file you can add jmeterlogfile parameter to jmeter Ant task like:

```<code><jmeter
     jmeterhome="${jmeter.home}"
     testplan ="${testpath}/${test}.jmx"
     resultlog="${testpath}/${test}.jtl"
     jmeterlogfile="/path/to/jmeter.log"> <!-- add this line to enable logging-->
</code>```

References:

JMeter Ant Task

Five Ways To Launch a JMeter Test without Using the JMeter GUI

Body:
Most likely your JMeter test execution for this lotteryOnline test plan has failed. The reason of failure you can see in the jmeter.log file. If you don't see the log file you can add jmeterlogfile parameter to jmeter Ant task like:

<jmeter
     jmeterhome="${jmeter.home}"
     testplan ="${testpath}/${test}.jmx"
     resultlog="${testpath}/${test}.jtl"
     jmeterlogfile="/path/to/jmeter.log"> <!-- add this line to enable logging-->

References:

JMeter Ant Task

Five Ways To Launch a JMeter Test without Using the JMeter GUI


问:
AutoFilter to find blank cells
I am trying to apply an autofilter in VBA for three different criterias in the same field. Once I have applied the filter I would like to find all those cells that are blank, can anyone advise?

```<code>    Sub ApplyAutoFiler()
    Dim ws As Worksheet
    Dim I, j, NumberOfErrors As Long
    IsErrors = False

    Set ws = Sheets("Assessments")

    NumberOfErrors = 0
    Dim Z As Range
    Set Z = Cells(4, 3).EntireColumn.Find("*", SearchDirection:=xlPrevious)
    If Not Z Is Nothing Then
        NumberOfRows = Z.Row
    End If

    For I = 4 To NumberOfRows

   With ws
   .AutoFilterMode = False
  .Range("W4:AA4").AutoFilter Field:=1, Criteria1:=Array("A", "B", "C"), Operator:=xlFilterValues
  .Cells.SpecialCells(xlCellTypeBlanks).Interior.Color = 65535
  .AutoFilterMode = False

   End With

   Next I

   End Sub
</code>```

I ended up doing this as a nested if statement

```<code>If Range("W" & i).Value = "A" Or Range("W" & i).Value = "B" Or Range("W" & i).Value = "C" Then
     If Range("AD" & i).Value = "" Then
        Range("AD" & CStr(i)).Interior.ColorIndex = 3
        NumberOfErrors = NumberOfErrors + 1
     End If
  End If
</code>```

答:
I know this treads had been quite long. But just want to share. To filter out blank cells, you could use autofilter using the following criteria:

```<code>Worksheets("sheet name").Range("A1").autoFilter Field:=18, Criteria1:=(Blanks)
</code>```

"Field" refers to the column numbers. As for "Criteria1", it can be either

```<code>Criteria1:=(Blanks)
</code>```

or

```<code>Criteria1:="="
</code>```

or

```<code>Criteria1:=""
</code>```

Title: AutoFilter to find blank cells

Body:
I am trying to apply an autofilter in VBA for three different criterias in the same field. Once I have applied the filter I would like to find all those cells that are blank, can anyone advise?

    Sub ApplyAutoFiler()
    Dim ws As Worksheet
    Dim I, j, NumberOfErrors As Long
    IsErrors = False

    Set ws = Sheets("Assessments")

    NumberOfErrors = 0
    Dim Z As Range
    Set Z = Cells(4, 3).EntireColumn.Find("*", SearchDirection:=xlPrevious)
    If Not Z Is Nothing Then
        NumberOfRows = Z.Row
    End If

    For I = 4 To NumberOfRows

   With ws
   .AutoFilterMode = False
  .Range("W4:AA4").AutoFilter Field:=1, Criteria1:=Array("A", "B", "C"), Operator:=xlFilterValues
  .Cells.SpecialCells(xlCellTypeBlanks).Interior.Color = 65535
  .AutoFilterMode = False

   End With

   Next I

   End Sub

I ended up doing this as a nested if statement

If Range("W" & i).Value = "A" Or Range("W" & i).Value = "B" Or Range("W" & i).Value = "C" Then
     If Range("AD" & i).Value = "" Then
        Range("AD" & CStr(i)).Interior.ColorIndex = 3
        NumberOfErrors = NumberOfErrors + 1
     End If
  End If

Body:
I know this treads had been quite long. But just want to share. To filter out blank cells, you could use autofilter using the following criteria:

Worksheets("sheet name").Range("A1").autoFilter Field:=18, Criteria1:=(Blanks)

"Field" refers to the column numbers. As for "Criteria1", it can be either

Criteria1:=(Blanks)

or

Criteria1:="="

or

Criteria1:=""