问:
Check if value equals 0 regardless of decimal values?
I'm balancing the sigma of a Gaussian kernel. I desire to break the while loop once the first index of the array is equal to 0.(any decimal value).

I found that simply trying to match 0 won't match if the value also contains any decimals like 0.000013301.

```<code>var gaussianKernel1d = (function() {
    var sqr2pi = Math.sqrt(2 * Math.PI);

    return function gaussianKernel1d(size, sigma) {
        'use strict';

        // ensure size is even and prepare variables
        var width = (size / 2) | 0,
            kernel = new Array(width * 2 + 1),
            norm = 1.0 / (sqr2pi * sigma),
            coefficient = 2 * sigma * sigma,
            total = 0,
            x;

        // set values and increment total
        for (x = -width; x <= width; x++) {
            total += kernel[width + x] = norm * Math.exp((-x * x) / coefficient);
        }

        // divide by total to make sure the sum of all the values is equal to 1
        for (x = 0; x < kernel.length; x++) {
            kernel[x] /= total;
        }

        return kernel;
    };
})();

let i = 0.01;
let kernelArray = gaussianKernel1d(512, i);
while (kernelArray[0] === 0) {
    i = i + 0.01;
    kernelArray = gaussianKernel1d(512, i);
</code>```

Same is also true when using Array[0] !== 0.0)

How can I match any values in the dataset that equal 0 regardless of the decimal values? And without converting the array to integers.

答:
Try following

$b = 0;

while ( (string) Array[0] !== (string) $b) {
  // code that just regenerates the random values
}

Body:
I'm balancing the sigma of a Gaussian kernel. I desire to break the while loop once the first index of the array is equal to 0.(any decimal value).

I found that simply trying to match 0 won't match if the value also contains any decimals like 0.000013301.

var gaussianKernel1d = (function() {
    var sqr2pi = Math.sqrt(2 * Math.PI);

    return function gaussianKernel1d(size, sigma) {
        'use strict';

        // ensure size is even and prepare variables
        var width = (size / 2) | 0,
            kernel = new Array(width * 2 + 1),
            norm = 1.0 / (sqr2pi * sigma),
            coefficient = 2 * sigma * sigma,
            total = 0,
            x;

        // set values and increment total
        for (x = -width; x <= width; x++) {
            total += kernel[width + x] = norm * Math.exp((-x * x) / coefficient);
        }

        // divide by total to make sure the sum of all the values is equal to 1
        for (x = 0; x < kernel.length; x++) {
            kernel[x] /= total;
        }

        return kernel;
    };
})();

let i = 0.01;
let kernelArray = gaussianKernel1d(512, i);
while (kernelArray[0] === 0) {
    i = i + 0.01;
    kernelArray = gaussianKernel1d(512, i);

Same is also true when using Array[0] !== 0.0)

How can I match any values in the dataset that equal 0 regardless of the decimal values? And without converting the array to integers.


来源: stackexchange

问:
Bigtable replication guidance
As per the Bigtable documentation:

Bigtable allows read/write operations to be performed on the basis of shortest distance.

Hence, it should always write to or read from nearest available cluster, in order to validate this, I had set up a GCE instance in "us-east1-d" zone and created a Bigtable instance with two clusters where one was in "us-east1-d" zone and other was in "us-west1-a"zone.

I expected my writes from GCE instance to follow "us-east1-d" only but I noticed a few writes going into "us-west1-a" and then replicating into "us-east1-d". I tracked this behaviour from Bigtable replication monitoring console only. Keeping in mind that zonal unavailability/disruption might be the reason of this behaviour, I deleted and recreated the Bigtable instance with clusters in different regions and zones. I still see some varience from "shortest distance" read/write theory of Bigtable.

So, my question, is there any way which can help me verify that read/writes from east region will always go to east region provided there is no zonal failure? Reliability of this feature is extremely critical to my applications in order to facilitate lowest possible latency.

答:
You could use Cloud Monitoring for BigTable to check each instance specifically, is not exactly what you want, since it's not per region and/or zone, but could be helpful to analize incoming requests to figure out what is happening with your particular instance.

One metric that is available and could really be helpful in your case is the Automatic failovers metric which shows the number of requests that were automatically rerouted from one cluster to another due to a failover scenario, such as a brief outage or delay.

You can see more details on how to set it up in this documentation.

Hope this helps.

ContentLicense: CC BY-SA 4.0

Title: Bigtable replication guidance


问:
Start C# script when image is detected for Vuforia+Unity
I have written a script, say like spiraling a sphere to the center in C#. However, the script starts even before the image target is detected and when I place the image target in front of camera the script is already executed.

I read that the DefaultTrackableBehaviour script needs to be modified for this. I saw some videos which show how to start audio when the image target is detected, however how do I start a script when the image target is detected.

This is the hierarchy of the objects

This is the script I want to execute for the sphere only when the image target is detected. On execution the sphere will spiral to the center (0,0,0)

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class spiralanti : MonoBehaviour
{
    float angles;
    float radiuss;
    float angleSpeed;
    float rSpeed;
    // Start is called before the first frame update
    void Start()
    {
        angles = 0;
        radiuss = 1f;
        angleSpeed = 250f;
        rSpeed = 0.05f;
        angles = Mathf.Max(0, Mathf.PI);
        radiuss = Mathf.Max(0, radiuss);

        //float x = 0;
        // float y = 0;
        // float z = 0;
    }

    // Update is called once per frame
    void Update()
    {
        angles += Time.deltaTime * angleSpeed;
        radiuss -= Time.deltaTime * rSpeed;
        if (radiuss <= 0)
        {
            float x = 0;
            float y = 1;
            float z = 0;

            transform.localPosition = new Vector3(x, y, z);
        }

        else
        {
            float x = radiuss * Mathf.Cos(Mathf.Deg2Rad * angles);
            float z = radiuss * Mathf.Sin(Mathf.Deg2Rad * angles);
            float y = 1;

            transform.localPosition = new Vector3(x, y, z);
        }

        }

 }
</code>```

Please help.

答:
In DefaultTrackableBehaviour script, make a bool variable targetFound.

Copy everything from your script's Start() method and add to DefaultTrackableBehaviour script's start() method.

Copy and add Update() method from your script to DefaultTrackableBehaviour script

Add an if condition in Update() method to check if targetFound is true or false, execute Update() code on if targetFound is true.

Set targetFound value to be true in onTrackingFound() method.

```<code>public bool targetFound = false;
</code>```

```<code>void onTrackingFound() {
          targetFound = true;
        }
</code>```

```<code>void Update() {
         if (targetFound){
          // your code here
       }
}
</code>```

Body:
I have written a script, say like spiraling a sphere to the center in C#. However, the script starts even before the image target is detected and when I place the image target in front of camera the script is already executed.

I read that the DefaultTrackableBehaviour script needs to be modified for this. I saw some videos which show how to start audio when the image target is detected, however how do I start a script when the image target is detected.

This is the hierarchy of the objects

This is the script I want to execute for the sphere only when the image target is detected. On execution the sphere will spiral to the center (0,0,0)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class spiralanti : MonoBehaviour
{
    float angles;
    float radiuss;
    float angleSpeed;
    float rSpeed;
    // Start is called before the first frame update
    void Start()
    {
        angles = 0;
        radiuss = 1f;
        angleSpeed = 250f;
        rSpeed = 0.05f;
        angles = Mathf.Max(0, Mathf.PI);
        radiuss = Mathf.Max(0, radiuss);

        //float x = 0;
        // float y = 0;
        // float z = 0;
    }

    // Update is called once per frame
    void Update()
    {
        angles += Time.deltaTime * angleSpeed;
        radiuss -= Time.deltaTime * rSpeed;
        if (radiuss <= 0)
        {
            float x = 0;
            float y = 1;
            float z = 0;

            transform.localPosition = new Vector3(x, y, z);
        }

        else
        {
            float x = radiuss * Mathf.Cos(Mathf.Deg2Rad * angles);
            float z = radiuss * Mathf.Sin(Mathf.Deg2Rad * angles);
            float y = 1;

            transform.localPosition = new Vector3(x, y, z);
        }

        }

 }

Please help.

Body:
In DefaultTrackableBehaviour script, make a bool variable targetFound.

Copy everything from your script's Start() method and add to DefaultTrackableBehaviour script's start() method.

Copy and add Update() method from your script to DefaultTrackableBehaviour script

Add an if condition in Update() method to check if targetFound is true or false, execute Update() code on if targetFound is true.

Set targetFound value to be true in onTrackingFound() method.

public bool targetFound = false;

void onTrackingFound() {
          targetFound = true;
        }

void Update() {
         if (targetFound){
          // your code here
       }
}


问:
Download an image with AsyncTask, I need help if there's no network connection
I'm new to programming so bear with me, this is a big learning experience for me, and it's been a lot of fun so far.

What I'm trying to do is to load an image into my app that I change and upload to my server on a regular basis. Right now, it loads a placement image until the proper image is finished downloading in the background, then shows the new image that it's downloaded.

My problem is that if there is no network connection, it ends up showing nothing at all. I'm assuming that there's something I can do in PostExecute that would show a drawable from within the app if it fails to load the image from the net, I'm just not sure how to do it!

Any help would be greatly appreciated!

EDIT: Am I on the right track to displaying an alternate image?

```<code>import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import android.widget.Toast;

public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {

private String url;
private final WeakReference<ImageView> imageViewReference;
private Resources res;

public ImageDownloader(ImageView imageView) {
    imageViewReference = new WeakReference<ImageView>(imageView);
}

@Override
protected Bitmap doInBackground(String... params) {
    url = params[0];
    try {
        return BitmapFactory.decodeStream(new URL(url).openConnection()
                .getInputStream());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {

      return BitmapFactory.decodeResource(res, R.drawable.displayThis);

        }
}

@Override
protected void onPostExecute(Bitmap result) {
    if (isCancelled()) {
        result = null;
    }
    if (imageViewReference != null) {
        ImageView imageView = imageViewReference.get();
        if (imageView != null) {
            imageView.setImageBitmap(result);
        }
    }
}

@Override
protected void onPreExecute() {
    if (imageViewReference != null) {
        ImageView imageView = imageViewReference.get();
        if (imageView != null) {
            imageView.setImageResource(R.drawable.uboxback);
        }
    }
}
}
</code>```

答:
In case of internet failed during data getting from internet in doInBackground() , Exception would come in the catch block. Here u can do the trick.

Take one global variable. If internet is failed then assign the "Failed" value to that variable in the catch block. Then in the onPostExecute() u can check do with the help of if and else depends on this variable.

Hope it helps....

ContentLicense: CC BY-SA 3.0

Body:
I'm new to programming so bear with me, this is a big learning experience for me, and it's been a lot of fun so far.

What I'm trying to do is to load an image into my app that I change and upload to my server on a regular basis. Right now, it loads a placement image until the proper image is finished downloading in the background, then shows the new image that it's downloaded.

My problem is that if there is no network connection, it ends up showing nothing at all. I'm assuming that there's something I can do in PostExecute that would show a drawable from within the app if it fails to load the image from the net, I'm just not sure how to do it!

Any help would be greatly appreciated!

EDIT: Am I on the right track to displaying an alternate image?

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import android.widget.Toast;

public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {

private String url;
private final WeakReference<ImageView> imageViewReference;
private Resources res;

public ImageDownloader(ImageView imageView) {
    imageViewReference = new WeakReference<ImageView>(imageView);
}

@Override
protected Bitmap doInBackground(String... params) {
    url = params[0];
    try {
        return BitmapFactory.decodeStream(new URL(url).openConnection()
                .getInputStream());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {

      return BitmapFactory.decodeResource(res, R.drawable.displayThis);

        }
}

@Override
protected void onPostExecute(Bitmap result) {
    if (isCancelled()) {
        result = null;
    }
    if (imageViewReference != null) {
        ImageView imageView = imageViewReference.get();
        if (imageView != null) {
            imageView.setImageBitmap(result);
        }
    }
}

@Override
protected void onPreExecute() {
    if (imageViewReference != null) {
        ImageView imageView = imageViewReference.get();
        if (imageView != null) {
            imageView.setImageResource(R.drawable.uboxback);
        }
    }
}
}


问:
onIonChange is triggering more than one input on Ionic 5 React
I have multiple inputs, each in it's own IonItem. I'm using onIonChange to set the value of the input to the value typed by the user. But when I click in one input other inputs activate, as if the onIonChange is triggering them. Below is a sample of my component:

```<code>const ReservationForm: React.FC = () => {

 const [name, setName] = useState<string>();
 const [email, setEmail] = useState<string>();
 const [phone, setPhone] = useState<number>();

return (
  <IonList>
     <IonItemDivider className="backgroundPrimary">Guest</IonItemDivider>
     <IonItem>
        <IonLabel position="stacked">Name</IonLabel>
        <IonInput value={name} onIonChange={e => setName(e.detail.value!)}></IonInput>
     </IonItem>
     <IonItem>
        <IonLabel position="stacked">Email</IonLabel>
        <IonInput value={email} onIonChange={e => setEmail(e.detail.value!)}></IonInput>
     </IonItem>
     <IonItem>
        <IonLabel position="stacked">Phone Number</IonLabel>
        <IonInput type="number" value={phone} onIonChange={e => setPhone(parseInt(e.detail.value!, 10))}></IonInput>
    </IonItem>
 </IonList>
);
};
export default ReservationForm;
</code>```

Here is an image of the problem:

as you can see I typed a letter in email but the floating label on phone number was trigger as well. Am I doing something wrong with useState or is this something wrong with the binding?
Any help appreciated.

I'm using Ionic 5 with React

答:
There seems to be an issue with onIonChange event due to which on first input it gets triggered on every IonInput and returns an undefined value for each element which is not a target. Now if we set the value to parseInt(e.detail.value!, 10) in state, each time onIonChange is triggered on the number input

To fix it you can add a conditional check for undefined

```<code><IonItem>
    <IonLabel position="floating">Phone Number</IonLabel>
    <IonInput
      type="number"
      value={phone}
      onIonChange={e => {
        if (e.detail.value === undefined) return;
        setPhone(parseInt(e.detail.value!, 10));
      }}
    />
</IonItem>
</code>```

The above solution will temporarily work for you but I will suggest you raise a Issue about this on github.

Working demo with the above solution

Body:
I have multiple inputs, each in it's own IonItem. I'm using onIonChange to set the value of the input to the value typed by the user. But when I click in one input other inputs activate, as if the onIonChange is triggering them. Below is a sample of my component:

const ReservationForm: React.FC = () => {

 const [name, setName] = useState<string>();
 const [email, setEmail] = useState<string>();
 const [phone, setPhone] = useState<number>();

return (
  <IonList>
     <IonItemDivider className="backgroundPrimary">Guest</IonItemDivider>
     <IonItem>
        <IonLabel position="stacked">Name</IonLabel>
        <IonInput value={name} onIonChange={e => setName(e.detail.value!)}></IonInput>
     </IonItem>
     <IonItem>
        <IonLabel position="stacked">Email</IonLabel>
        <IonInput value={email} onIonChange={e => setEmail(e.detail.value!)}></IonInput>
     </IonItem>
     <IonItem>
        <IonLabel position="stacked">Phone Number</IonLabel>
        <IonInput type="number" value={phone} onIonChange={e => setPhone(parseInt(e.detail.value!, 10))}></IonInput>
    </IonItem>
 </IonList>
);
};
export default ReservationForm;

Here is an image of the problem:

as you can see I typed a letter in email but the floating label on phone number was trigger as well. Am I doing something wrong with useState or is this something wrong with the binding?
Any help appreciated.

I'm using Ionic 5 with React

Body:
There seems to be an issue with onIonChange event due to which on first input it gets triggered on every IonInput and returns an undefined value for each element which is not a target. Now if we set the value to parseInt(e.detail.value!, 10) in state, each time onIonChange is triggered on the number input

To fix it you can add a conditional check for undefined

<IonItem>
    <IonLabel position="floating">Phone Number</IonLabel>
    <IonInput
      type="number"
      value={phone}
      onIonChange={e => {
        if (e.detail.value === undefined) return;
        setPhone(parseInt(e.detail.value!, 10));
      }}
    />
</IonItem>

The above solution will temporarily work for you but I will suggest you raise a Issue about this on github.

Working demo with the above solution


问:
select "all columns" with "group by" in hibernate criteria queries
I want to write a criteria query using "group by" and want to return all the columns.

Plane sql is like this:

```<code>select * from Tab group by client_name order by creation_time;
</code>```

I understand that it will have count(distinct client_name) number of rows.

My current query which doesn't seem to give proper result is as follows:

```<code>Criteria criteria = getSession(requestType).createCriteria(Tab.class);
        criteria.setProjection(Projections.projectionList().add(Projections.groupProperty("client_name")));
        criteria.addOrder(Order.asc("creationTime"));
</code>```

This query returns "client_name" only. I don't want to manually put all column names. There must be some way, what could be done?

答:
It is not possible to get all columns of the database by using a group based on a single column. Instead, you can use all columns in the group by clause and in the select as well which you want. To get the result in hibernate like below

```<code>    Criteria criteria = getSession(requestType).createCriteria(Tab.class);
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.property("client_name"));
    projectionList.add(Projections.property("column2"));
    projectionList.add(Projections.property("column3"));
    projectionList.add(Projections.groupProperty("client_name"));
    projectionList.add(Projections.groupProperty("column2"));
    projectionList.add(Projections.groupProperty("column3"));
    criteria.setProjection(projectionList);
    criteria.addOrder(Order.asc("creationTime"));
</code>```

Body:
I want to write a criteria query using "group by" and want to return all the columns.

Plane sql is like this:

select * from Tab group by client_name order by creation_time;

I understand that it will have count(distinct client_name) number of rows.

My current query which doesn't seem to give proper result is as follows:

Criteria criteria = getSession(requestType).createCriteria(Tab.class);
        criteria.setProjection(Projections.projectionList().add(Projections.groupProperty("client_name")));
        criteria.addOrder(Order.asc("creationTime"));

This query returns "client_name" only. I don't want to manually put all column names. There must be some way, what could be done?

Body:
It is not possible to get all columns of the database by using a group based on a single column. Instead, you can use all columns in the group by clause and in the select as well which you want. To get the result in hibernate like below

    Criteria criteria = getSession(requestType).createCriteria(Tab.class);
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.property("client_name"));
    projectionList.add(Projections.property("column2"));
    projectionList.add(Projections.property("column3"));
    projectionList.add(Projections.groupProperty("client_name"));
    projectionList.add(Projections.groupProperty("column2"));
    projectionList.add(Projections.groupProperty("column3"));
    criteria.setProjection(projectionList);
    criteria.addOrder(Order.asc("creationTime"));


问:
How should i do from notification back to activity without new intent
from Android Development, i implement a simple notification by the sample code, but in my app, i don't want to new intent and create the activity again, i just want to back to my last activity(it's a mediaplayer UI). if i use the sample code, it will create a new activity by

```<code>Intent resultIntent = new Intent(this, ResultActivity.class);
</code>```

i comment relative code about new intent and got a notification, but didn't have idea how to back to my last activity...

back to my app from long press home key and touch my app is OK.
what i want is just like this behavior.

bleow is the sample code from Android Development, i comment the new intent portion.

```<code>NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!");
/*Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
    stackBuilder.getPendingIntent(
        0,
        PendingIntent.FLAG_UPDATE_CURRENT
    );
mBuilder.setContentIntent(resultPendingIntent);*/
NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, mBuilder.build());
</code>```

[UPDATE]

i thought i need to set flag for intent and properity for activity.
therefore, for the activity i want to back to i set

```<code>android:launchMode="singleInstance"
</code>```

and because, i don't want a new activity from intent, i just want my last activity, so i add

```<code>Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
</code>```

from documentation i got that using Pendingintent.contentIntent it must include the FLAG_ACTIVITY_NEW_TASK flag and When using this flag, if a task is already running for the activity you are now starting, then a new activity will not be started; instead, the current task will simply be brought to the front of the screen with the state it was last in. so i also add

```<code>Intent.FLAG_ACTIVITY_NEW_TASK
</code>```

but from logCat, i still saw that when i touch the notification for back to activity, the pendingintent still called onCreate() function rather than just show the last activity which still "alive".

答:
Code hear</p>
```<code>        Intent resultIntent = new
 Intent(getApplicationContext(),MainActivity.class);

        resultIntent.putExtra("splash",2);
        resultIntent.putExtra("message","test");
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addNextIntentWithParentStack(resultIntent);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent notifyPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        notificationCompatBuilder.setContentIntent(notifyPendingIntent);

    Intent intent = this.getIntent();
    Bundle extras = intent.getExtras();

    if (extras != null) {
        String extraValue = extras.getString("notificationType");

        if(extraValue !=null){
            int value = Integer.parseInt(extraValue);
            if (value == 1) {
                intent = new Intent(SplashActivity.this,MainActivity.class);
                intent.putExtra("splash",value);
                intent.putExtra("message", "fromsplash");
                startActivity(intent);
                finish();
            } else
             if (value == 2){
                 intent = new Intent(SplashActivity.this,MainActivity.class);
                 intent.putExtra("swip","2");
                 intent.putExtra("message", "test");
                startActivity(intent);
                finish();
            }
        }

    }
}
</code>```

Body:
from Android Development, i implement a simple notification by the sample code, but in my app, i don't want to new intent and create the activity again, i just want to back to my last activity(it's a mediaplayer UI). if i use the sample code, it will create a new activity by

Intent resultIntent = new Intent(this, ResultActivity.class);

i comment relative code about new intent and got a notification, but didn't have idea how to back to my last activity...

back to my app from long press home key and touch my app is OK.
what i want is just like this behavior.

bleow is the sample code from Android Development, i comment the new intent portion.

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!");
/*Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
    stackBuilder.getPendingIntent(
        0,
        PendingIntent.FLAG_UPDATE_CURRENT
    );
mBuilder.setContentIntent(resultPendingIntent);*/
NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, mBuilder.build());

[UPDATE]

i thought i need to set flag for intent and properity for activity.
therefore, for the activity i want to back to i set

android:launchMode="singleInstance"

and because, i don't want a new activity from intent, i just want my last activity, so i add

Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY

from documentation i got that using Pendingintent.contentIntent it must include the FLAG_ACTIVITY_NEW_TASK flag and When using this flag, if a task is already running for the activity you are now starting, then a new activity will not be started; instead, the current task will simply be brought to the front of the screen with the state it was last in. so i also add

Intent.FLAG_ACTIVITY_NEW_TASK

but from logCat, i still saw that when i touch the notification for back to activity, the pendingintent still called onCreate() function rather than just show the last activity which still "alive".

Body:
Code hear

        Intent resultIntent = new
 Intent(getApplicationContext(),MainActivity.class);

        resultIntent.putExtra("splash",2);
        resultIntent.putExtra("message","test");
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addNextIntentWithParentStack(resultIntent);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent notifyPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        notificationCompatBuilder.setContentIntent(notifyPendingIntent);

    Intent intent = this.getIntent();
    Bundle extras = intent.getExtras();

    if (extras != null) {
        String extraValue = extras.getString("notificationType");

        if(extraValue !=null){
            int value = Integer.parseInt(extraValue);
            if (value == 1) {
                intent = new Intent(SplashActivity.this,MainActivity.class);
                intent.putExtra("splash",value);
                intent.putExtra("message", "fromsplash");
                startActivity(intent);
                finish();
            } else
             if (value == 2){
                 intent = new Intent(SplashActivity.this,MainActivity.class);
                 intent.putExtra("swip","2");
                 intent.putExtra("message", "test");
                startActivity(intent);
                finish();
            }
        }

    }
}


问:
How to control the for loop with a if condition in it not to give output till the loop completes
I have a method which is having a Map with a set of rules which I am trying to apply on input with an if condition.

When the condition is matched then the if will break the loop and return the matched value. If none of the conditions is matched, I need to return a null output that the input didn't satisfy any given condition.

My current code as below

```<code>public static String matching(String input){

    HashMap<String, String> hm =  new HashMap<String, String>();

    //Key,Value pair in Hashmap represents Name of condition(Key) and Condition(value)
    for (Map.Entry mapElement : hm.entrySet()) {
        String value = mapElement.getValue();
        if(input.equals(condition)){
            return input;
            break;
        }
    }
    return null;
}
</code>```

Let's say the map has 5 entries and the condition which will satisfy the current input is present at the 5th position. The first four tests return null and when the condition at 5th position is matched it will return that matched condition. But I want to return the output only after evaluating all conditions in the map.
I tried putting else if after the if in the loop with a continue;, but it's giving the same result.

Please, how can I solve the issue ?

答:
First of all, since you are using HashMap - you cant be sure about the order.

Secondly - it depends, if you want to record all conditions that fits the input then just make separate collection and add them there within your loop. If the collection is empty - you simply return null.

Look at this sample code:

```<code>   final String input = "testValue2";
   Map<String, String> conditions = new HashMap<>();
   conditions.put("testKey1", "testValue1");
   conditions.put("testKey2", "testValue2");

   Set<Map.Entry> entrySetThatMatches = conditions.entrySet().stream().filter(m -> input.equals(m.getValue())).collect(Collectors.toSet());
   System.out.println(entrySetThatMatches.iterator().next().getValue()); //prints testValue2
</code>```

Body:
I have a method which is having a Map with a set of rules which I am trying to apply on input with an if condition.

When the condition is matched then the if will break the loop and return the matched value. If none of the conditions is matched, I need to return a null output that the input didn't satisfy any given condition.

My current code as below

public static String matching(String input){

    HashMap<String, String> hm =  new HashMap<String, String>();

    //Key,Value pair in Hashmap represents Name of condition(Key) and Condition(value)
    for (Map.Entry mapElement : hm.entrySet()) {
        String value = mapElement.getValue();
        if(input.equals(condition)){
            return input;
            break;
        }
    }
    return null;
}

Let's say the map has 5 entries and the condition which will satisfy the current input is present at the 5th position. The first four tests return null and when the condition at 5th position is matched it will return that matched condition. But I want to return the output only after evaluating all conditions in the map.
I tried putting else if after the if in the loop with a continue;, but it's giving the same result.

Please, how can I solve the issue ?

Body:
First of all, since you are using HashMap - you cant be sure about the order.

Secondly - it depends, if you want to record all conditions that fits the input then just make separate collection and add them there within your loop. If the collection is empty - you simply return null.

Look at this sample code:

   final String input = "testValue2";
   Map<String, String> conditions = new HashMap<>();
   conditions.put("testKey1", "testValue1");
   conditions.put("testKey2", "testValue2");

   Set<Map.Entry> entrySetThatMatches = conditions.entrySet().stream().filter(m -> input.equals(m.getValue())).collect(Collectors.toSet());
   System.out.println(entrySetThatMatches.iterator().next().getValue()); //prints testValue2


问:
Can someone help me to install the netflix's VMAF library in Ubuntu
First of all, I have to say that I am not very experienced in ubuntu.
I would like to install this library to use with FFMPEG.

I am following these steps, but I can manage to install it well...

https://github.com/Netflix/vmaf/blob/master/resource/doc/VMAF_Python_library.md

Could someone tell me what are the exact steps (commands) that I have to follow.

On the other hand, someone knows if there are other metrics that can ffmpeg calculates directly (apart from PSNR or SSIM)?

Many thanks

答:
The link you provided is just to install the VMAF python library. To use VMAF with ffmpeg you need to install  libvmaf first and then compile ffmpeg with libvmaf filter enabled. However, as one user suggests, you can use already compiled ffmpeg packages https://www.johnvansickle.com/ffmpeg/

Moving to your questions. These are the step by step I followed to install FFmpeg+VMAF over an Ubuntu 20.04:

Installing dependencies:

```<code>apt update -qq
apt install pkg-config -y
apt-get install --no-install-recommends\
    ninja-build \
    python3 \
    python3-pip \
    python3-setuptools \
    python3-wheel \
    ninja-build \
    wget \
    doxygen \
    autoconf \
    automake \
    cmake \
    g++ \
    gcc \
    pkg-config \
    make \
    nasm \
    yasm -y
pip3 install --user meson
</code>```

Installing libvmaf:

```<code>export PATH="$PATH:$HOME/.local/bin"
wget https://github.com/Netflix/vmaf/archive/v1.5.1.tar.gz
tar -xzf  v1.5.1.tar.gz
cd vmaf-1.5.1/libvmaf/
meson build --buildtype release
ninja -vC build
ninja -vC build test
ninja -vC build install
</code>```

Installing ffmpeg:

```<code>wget https://ffmpeg.org/releases/ffmpeg-4.2.2.tar.bz2 && tar xjf ffmpeg-4.2.2.tar.bz2
cd ffmpeg-4.2.2
./configure --enable-libvmaf --enable-version3
make
make install
</code>```

Sometimes, depending on your OS, you also need to setup your $PATH, $LD_LIBRARY_PATH, $PKG_CONFIG_PATH.

Body:
The link you provided is just to install the VMAF python library. To use VMAF with ffmpeg you need to install  libvmaf first and then compile ffmpeg with libvmaf filter enabled. However, as one user suggests, you can use already compiled ffmpeg packages https://www.johnvansickle.com/ffmpeg/

Moving to your questions. These are the step by step I followed to install FFmpeg+VMAF over an Ubuntu 20.04:

Installing dependencies:

apt update -qq
apt install pkg-config -y
apt-get install --no-install-recommends\
    ninja-build \
    python3 \
    python3-pip \
    python3-setuptools \
    python3-wheel \
    ninja-build \
    wget \
    doxygen \
    autoconf \
    automake \
    cmake \
    g++ \
    gcc \
    pkg-config \
    make \
    nasm \
    yasm -y
pip3 install --user meson

Installing libvmaf:

export PATH="$PATH:$HOME/.local/bin"
wget https://github.com/Netflix/vmaf/archive/v1.5.1.tar.gz
tar -xzf  v1.5.1.tar.gz
cd vmaf-1.5.1/libvmaf/
meson build --buildtype release
ninja -vC build
ninja -vC build test
ninja -vC build install

Installing ffmpeg:

wget https://ffmpeg.org/releases/ffmpeg-4.2.2.tar.bz2 && tar xjf ffmpeg-4.2.2.tar.bz2
cd ffmpeg-4.2.2
./configure --enable-libvmaf --enable-version3
make
make install

Sometimes, depending on your OS, you also need to setup your $PATH, $LD_LIBRARY_PATH, $PKG_CONFIG_PATH.


问:
How to get this values form this data
```<code>envelope:'{"to":["reply-to-501-4455@email.ashishbhangade.com"],"from":"Tway"}'
</code>```

<p>here my object data and i want find values only 501 and 4455 (every time this values are dynamic not static values) so how to get please give me suggestion. </p>

答:
This is way to dynamic values

const split = '{"to":["reply-to-501-4455@email.ashishbhangade.com"],"from":"Tway"}'.split('-')

const code1 = split[2]
const arrWithCode2 = split[3].split('@')
const code2 = arrWithCode2[0]

console.log(code1, code2)```
</div>
</div>
</p>

<p>If "reply-to-"  and codes length don`t change</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-js lang-js prettyprint-override"><code>const msg = '{"to":["reply-to-501-4455@email.ashishbhangade.com"],"from":"Tway"}'

const code1 = msg.substring(17, 20)
const code2 = msg.substring(21, 25)

console.log(code1, code2)</code>```

Title: How to get this values form this data

Body:
envelope:'{"to":["reply-to-501-4455@email.ashishbhangade.com"],"from":"Tway"}'

here my object data and i want find values only 501 and 4455 (every time this values are dynamic not static values) so how to get please give me suggestion.

Body:
This is way to dynamic values

const split = '{"to":["reply-to-501-4455@email.ashishbhangade.com"],"from":"Tway"}'.split('-')

const code1 = split[2]
const arrWithCode2 = split[3].split('@')
const code2 = arrWithCode2[0]

console.log(code1, code2)

If "reply-to-"  and codes length don`t change

const msg = '{"to":["reply-to-501-4455@email.ashishbhangade.com"],"from":"Tway"}'

const code1 = msg.substring(17, 20)
const code2 = msg.substring(21, 25)

console.log(code1, code2)


问:
Reading image in matlab in a format acceptable to mex
Hi I use imread function in matlab to read an image. But now if i want to use this image in a mex file what should I do?
I used im2double function to the image and then passed it to the mex file but the results i get are not acceptable.

so is there any other function which can be used

答: Convert to double and divided by 255. In Mex file Matlab double array is used to represent the image</p>


问:
Understanding variables and functions in while loops
I have a function thar uses a while loop that goes like this

```<code>def fun_rightamount(monthly_salary,down_payment,semi_annual_rise,r,errore=False):
    epsilon = 100
    num_guesses = 0
    low = 0
    high = 100
    portion_saved = (high + low)/2.0
    while abs(fun_thirtysix(portion_saved,monthly_salary,down_payment,semi_annual_rise,r) - down_payment ) >= epsilon :
        if fun_thirtysix(portion_saved,monthly_salary,down_payment,semi_annual_rise,r)  < down_payment  :
            low = portion_saved
        else:
            high = portion_saved
        portion_saved = (high + low)/2.0
        num_guesses += 1
        if portion_saved > 99.9999:
            print('attenzione ERRORE !!!!!!!!!!!!!!!!!!!!!!!!!!')
            errore=True
            break
    return portion_saved,num_guesses,errore
</code>```

I can change the while statment using another function   'pippo'

```<code>def pippo(portion_saved,monthly_salary,down_payment,semi_annual_rise,r):
    yy=(fun_thirtysix(portion_saved,monthly_salary,down_payment,semi_annual_rise,r) - down_payment)
    return yy

def fun_rightamount(monthly_salary,down_payment,semi_annual_rise,r,errore=False):
    epsilon = 100
    num_guesses = 0
    low = 0
    high = 100
    portion_saved = (high + low)/2.0
    while abs(pippo(portion_saved,monthly_salary,down_payment,semi_annual_rise,r)) >= epsilon :  #
        if pippo(portion_saved,monthly_salary,down_payment,semi_annual_rise,r)  < 0  :           #
            low = portion_saved                                                                  #
        else:
            high = portion_saved
        portion_saved = (high + low)/2.0
        num_guesses += 1
        if portion_saved > 99.9999:
            print('attenzione ERRORE !!!!!!!!!!!!!!!!!!!!!!!!!!')
            errore=True
            break
    return portion_saved,num_guesses,errore
</code>```

and everything works as expected,the two constructs works exavctly the same, but if I try to use a variable ('yy') in my while statement instead of a function my program enters an infinite loop:

```<code>def fun_rightamount(monthly_salary,down_payment,semi_annual_rise,r,errore=False):
    epsilon = 100
    num_guesses = 0
    low = 0
    high = 100
    portion_saved = (high + low)/2.0
    yy=(fun_thirtysix(portion_saved,monthly_salary,down_payment,semi_annual_rise,r) - down_payment) #
    while abs(yy) >= epsilon :                                                                      #
        if yy  < 0  :                                                                               #
            low = portion_saved
        else:
            high = portion_saved
        portion_saved = (high + low)/2.0
        num_guesses += 1
        if portion_saved > 99.9999:
            print('attenzione ERRORE !!!!!!!!!!!!!!!!!!!!!!!!!!')
            errore=True
            break
    return portion_saved,num_guesses,errore
</code>```

the while loop, loops but the num_guesses  incraeses, the abs(yy) values doesnt change and the portion_saved stays as '0' while at least in the first loop shoulb be '50'. Any idea ?

答:
Green Cloak Guy answered my question

yy gets set once, when you assign it, and then never changes. Even if portion_saved would change, you'd need to run the function again and assign it to yy again. In your earlier example, you call the function on every iteration, so it terminates correctly – Green Cloak Guy Apr 29 at 19:07

Body:
I have a function thar uses a while loop that goes like this

def fun_rightamount(monthly_salary,down_payment,semi_annual_rise,r,errore=False):
    epsilon = 100
    num_guesses = 0
    low = 0
    high = 100
    portion_saved = (high + low)/2.0
    while abs(fun_thirtysix(portion_saved,monthly_salary,down_payment,semi_annual_rise,r) - down_payment ) >= epsilon :
        if fun_thirtysix(portion_saved,monthly_salary,down_payment,semi_annual_rise,r)  < down_payment  :
            low = portion_saved
        else:
            high = portion_saved
        portion_saved = (high + low)/2.0
        num_guesses += 1
        if portion_saved > 99.9999:
            print('attenzione ERRORE !!!!!!!!!!!!!!!!!!!!!!!!!!')
            errore=True
            break
    return portion_saved,num_guesses,errore

I can change the while statment using another function   'pippo'

def pippo(portion_saved,monthly_salary,down_payment,semi_annual_rise,r):
    yy=(fun_thirtysix(portion_saved,monthly_salary,down_payment,semi_annual_rise,r) - down_payment)
    return yy

def fun_rightamount(monthly_salary,down_payment,semi_annual_rise,r,errore=False):
    epsilon = 100
    num_guesses = 0
    low = 0
    high = 100
    portion_saved = (high + low)/2.0
    while abs(pippo(portion_saved,monthly_salary,down_payment,semi_annual_rise,r)) >= epsilon :  #
        if pippo(portion_saved,monthly_salary,down_payment,semi_annual_rise,r)  < 0  :           #
            low = portion_saved                                                                  #
        else:
            high = portion_saved
        portion_saved = (high + low)/2.0
        num_guesses += 1
        if portion_saved > 99.9999:
            print('attenzione ERRORE !!!!!!!!!!!!!!!!!!!!!!!!!!')
            errore=True
            break
    return portion_saved,num_guesses,errore

and everything works as expected,the two constructs works exavctly the same, but if I try to use a variable ('yy') in my while statement instead of a function my program enters an infinite loop:

def fun_rightamount(monthly_salary,down_payment,semi_annual_rise,r,errore=False):
    epsilon = 100
    num_guesses = 0
    low = 0
    high = 100
    portion_saved = (high + low)/2.0
    yy=(fun_thirtysix(portion_saved,monthly_salary,down_payment,semi_annual_rise,r) - down_payment) #
    while abs(yy) >= epsilon :                                                                      #
        if yy  < 0  :                                                                               #
            low = portion_saved
        else:
            high = portion_saved
        portion_saved = (high + low)/2.0
        num_guesses += 1
        if portion_saved > 99.9999:
            print('attenzione ERRORE !!!!!!!!!!!!!!!!!!!!!!!!!!')
            errore=True
            break
    return portion_saved,num_guesses,errore

the while loop, loops but the num_guesses  incraeses, the abs(yy) values doesnt change and the portion_saved stays as '0' while at least in the first loop shoulb be '50'. Any idea ?


问:
Google Script For Loop Issues
So this question seems to be beaten to death on the boards, but with all my reading and googling, I just can't figure out what I'm doing wrong.

I'm trying to adapt the code from this link
How to loop a google spreadsheet column values and set result in column B?

Below is what I've adapted it to

```<code>function EquationIterationTest(){
  var s = SpreadsheetApp.getActiveSpreadsheet();
  var sht = s.getSheetByName('Heath, OH')
  var drng = sht.getDataRange();
  var rng = sht.getRange(13, 2, 111, 1)
  //.getRange(13, 2, drng.getLastRow()-1, drng.getLastColumn())
  var rngA = rng.getValues();//Array of input values

  Logger.log(rngA);

  for(var i = 0; i < rngA.length; i++) {
    if(rngA[i][0] === 'subtotal'){
    rng.offset(0,3).setFormula('=iferror(sum(filter(Invoices!$E:$E,Invoices!$F:$F=$B14,Invoices!$A:$A=$C$2)))');
    }
   else{
     rng.offset(0,3).setValue('Dumb');
   }
   }
 }
</code>```

When I run this, rngA does get the first column of values (which in this instance starts at B13) however, it will not input the formula in the third column of values. Instead it moves right through the first if statement and executes the else statement. The only thing I can think is there's something wrong either with my if statement or my array.

I tried setting if(rngA[i][0] === 'subtotal') to if(rngA[i][1] === 'subtotal'), but that still returned "dumb" on every line.

Any help would be appreciated so I can stop being "dumb"!

Here's the link to my sheet.

https://docs.google.com/spreadsheets/d/1cDkwWThXDTssH89gJX7W1zKzsW86oLXO-FPfAIJvc-g/edit?usp=sharing

Thanks

答:
The problem is not in your if condition, although if you use three equal signs you are making a strict comparison, so subtotal in your case should start with capital letter.

That said, your problem is happening when you assign a value or formula to rng.offset(0,3), because the result of that expression is a range with the same size as rng but offset 3 columns to the right. You can verify this by using: Logger.log(rng.offset(0,3).getA1Notation());, thus whenever you assign a value or formula there you are assigning it to the whole offset rng. Not what you want right?

You should use offset() from a single cell in your case, not a whole range.

Your function could be simplified to something like the following:

function EquationIterationTest(){
  var s = SpreadsheetApp.getActiveSpreadsheet();
  var sht = s.getSheetByName('Heath, OH')
  var rng = sht.getRange(13, 2, 111, 1)

  for(var i = 1; i <= rng.getNumRows(); i++) {
    var cell = rng.getCell(i,1);
    if(cell.getValue() === 'Subtotal'){
      cell.offset(0,3).setFormula(
        '=iferror(sum(filter(Invoices!$E:$E,Invoices!$F:$F=$B14,Invoices!$A:$A=$C$2)))'
      );
    }
    else{
      cell.offset(0,3).setValue('Dummy');
    }
  }
}
```

Title: Google Script For Loop Issues

Body:
So this question seems to be beaten to death on the boards, but with all my reading and googling, I just can't figure out what I'm doing wrong.

I'm trying to adapt the code from this link
How to loop a google spreadsheet column values and set result in column B?

Below is what I've adapted it to

function EquationIterationTest(){
  var s = SpreadsheetApp.getActiveSpreadsheet();
  var sht = s.getSheetByName('Heath, OH')
  var drng = sht.getDataRange();
  var rng = sht.getRange(13, 2, 111, 1)
  //.getRange(13, 2, drng.getLastRow()-1, drng.getLastColumn())
  var rngA = rng.getValues();//Array of input values

  Logger.log(rngA);

  for(var i = 0; i < rngA.length; i++) {
    if(rngA[i][0] === 'subtotal'){
    rng.offset(0,3).setFormula('=iferror(sum(filter(Invoices!$E:$E,Invoices!$F:$F=$B14,Invoices!$A:$A=$C$2)))');
    }
   else{
     rng.offset(0,3).setValue('Dumb');
   }
   }
 }

When I run this, rngA does get the first column of values (which in this instance starts at B13) however, it will not input the formula in the third column of values. Instead it moves right through the first if statement and executes the else statement. The only thing I can think is there's something wrong either with my if statement or my array.

I tried setting if(rngA[i][0] === 'subtotal') to if(rngA[i][1] === 'subtotal'), but that still returned "dumb" on every line.

Any help would be appreciated so I can stop being "dumb"!

Here's the link to my sheet.

https://docs.google.com/spreadsheets/d/1cDkwWThXDTssH89gJX7W1zKzsW86oLXO-FPfAIJvc-g/edit?usp=sharing

Thanks


问:
How to get JSON data by POST method with Secret code in android studio
I need to get json data response based on SECRET CODE with POST method, would you please solve my issue, thanks in advance.

I have been facing  with many problems with this POST method of Secret Code to get the JSON Response

```<code> public class MainActivity extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.listViewHeroes);

    getQuestions();
}

private void getQuestions() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ApiInterface.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
            .build();

    ApiInterface api = retrofit.create(ApiInterface.class);

    RequestModel requestModel = new RequestModel();
    requestModel.setSecretCode("341977082");

    Call<List<ModelObjects>> call = api.getQuestions();

   call.enqueue(new Callback<List<ModelObjects>>() {
       @Override
       public void onResponse(Call<List<ModelObjects>> call, Response<List<ModelObjects>> response) {
           List<ModelObjects> questionsList = response.body();

           String[] questions = new String[questionsList.size()];

           for (int i = 0; i < questionsList.size(); i++) {
               questions[i] = questionsList.get(i).getQues_No();
           }

           listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, questions));
       }

       @Override
       public void onFailure(Call<List<ModelObjects>> call, Throwable t) {
           Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
       }
   });}}
</code>```

Here is the interface and where I am passing the URL that contains parent and extension

```<code>public interface ApiInterface {

String BASE_URL = "";

@POST("QuestionsList")
Call<List<ModelObjects>> getQuestions();}
</code>```

Here is the response Model

```<code> public class ModelObjects {
@SerializedName("Ques_No")
private String Ques_No;

public ModelObjects(String ques_No) {
    Ques_No = ques_No;
}

public String getQues_No() {
    return Ques_No;
}

public void setQues_No(String ques_No) {
    Ques_No = ques_No;
}}
</code>```

Here is the Request Model

```<code> public class RequestModel {
private String SecretCode;

public RequestModel(String secretCode) {
    SecretCode = secretCode;
}

public RequestModel() {

}

public String getSecretCode() {
    return SecretCode;
}

public void setSecretCode(String secretCode) {
    SecretCode = secretCode;
}}
</code>```

答:
What can i see it, you are creating object of RequestModel class, but you are not passing it anywhere. If you want to send the secretCode along with the post network call, then you'll have to pass this requestModel instance to the call.

```<code>    public interface ApiInterface {
    String BASE_URL = "";
    @POST("QuestionsList")
    Call<List<ModelObjects>> getQuestions(@Body RequestModel requestModel);
    }
</code>```

then you can call this method and can pass this requestModel Object by

```<code>    Call<List<ModelObjects>> call = api.getQuestions(requestModel);
</code>```

If you want to access the first object you can do it by

```<code>   List<ModelObjects> questionsList = response.body();
   ModelObject obj = questionList.get(0);
   String question = obj.getQues_No();
</code>```

This question is going to be the first question.

Body:
I need to get json data response based on SECRET CODE with POST method, would you please solve my issue, thanks in advance.

I have been facing  with many problems with this POST method of Secret Code to get the JSON Response

 public class MainActivity extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.listViewHeroes);

    getQuestions();
}

private void getQuestions() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ApiInterface.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
            .build();

    ApiInterface api = retrofit.create(ApiInterface.class);

    RequestModel requestModel = new RequestModel();
    requestModel.setSecretCode("341977082");

    Call<List<ModelObjects>> call = api.getQuestions();

   call.enqueue(new Callback<List<ModelObjects>>() {
       @Override
       public void onResponse(Call<List<ModelObjects>> call, Response<List<ModelObjects>> response) {
           List<ModelObjects> questionsList = response.body();

           String[] questions = new String[questionsList.size()];

           for (int i = 0; i < questionsList.size(); i++) {
               questions[i] = questionsList.get(i).getQues_No();
           }

           listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, questions));
       }

       @Override
       public void onFailure(Call<List<ModelObjects>> call, Throwable t) {
           Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
       }
   });}}

Here is the interface and where I am passing the URL that contains parent and extension

public interface ApiInterface {

String BASE_URL = "";

@POST("QuestionsList")
Call<List<ModelObjects>> getQuestions();}

Here is the response Model

 public class ModelObjects {
@SerializedName("Ques_No")
private String Ques_No;

public ModelObjects(String ques_No) {
    Ques_No = ques_No;
}

public String getQues_No() {
    return Ques_No;
}

public void setQues_No(String ques_No) {
    Ques_No = ques_No;
}}

Here is the Request Model

 public class RequestModel {
private String SecretCode;

public RequestModel(String secretCode) {
    SecretCode = secretCode;
}

public RequestModel() {

}

public String getSecretCode() {
    return SecretCode;
}

public void setSecretCode(String secretCode) {
    SecretCode = secretCode;
}}

Body:
What can i see it, you are creating object of RequestModel class, but you are not passing it anywhere. If you want to send the secretCode along with the post network call, then you'll have to pass this requestModel instance to the call.

    public interface ApiInterface {
    String BASE_URL = "";
    @POST("QuestionsList")
    Call<List<ModelObjects>> getQuestions(@Body RequestModel requestModel);
    }

then you can call this method and can pass this requestModel Object by

    Call<List<ModelObjects>> call = api.getQuestions(requestModel);

If you want to access the first object you can do it by

   List<ModelObjects> questionsList = response.body();
   ModelObject obj = questionList.get(0);
   String question = obj.getQues_No();

This question is going to be the first question.


问:
ROR: Trying to trigger update route using 'put' but for some reason deleting instead
I have a rails application I'm working on, and I'm using devise for authentication. I'm having an issue where when I try to update the user details instead up updating the user the user just gets deleted.

In registrations/edit.html.erb I have:

```<code><%= form_for(resource, as: resource_name, url: registration_path(resource_name), method: :put) do |f| %>

  ... input tags and styling

<% end %>

</code>```

Which generates the html:

```<code><form class="edit_user" id="edit_user" enctype="multipart/form-data" action="/users" accept-charset="UTF-8" method="post">
<input type="hidden" name="_method" value="put" />
<input type="hidden" name="authenticity_token" value="Q2U4gEBfaIwCo2Vwi2fwXgwYLjzE4HpoDC8KN52m2GGqEdb94jd/c3TyFhEJtQEziHat9zFQs+e+fRJp4/j2WA==" />

... rest of the input tags

</form>

</code>```

The key thing here being <input type="hidden" name="_method" value="put" /> in rails this should trigger the PUT route but for some reason when I submit the form it's triggering the delete route:

```<code>Started DELETE "/users" for 127.0.0.1 at 2020-06-01 16:15:48 +0100
   (0.6ms)  SET NAMES utf8mb4 COLLATE utf8mb4_bin,  @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'),  @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
   (0.2ms)  SELECT `schema_migrations`.`version` FROM `schema_migrations` ORDER BY `schema_migrations`.`version` ASC

</code>```

Has anyone come across this before and know what could be causing it?

EDIT

my config/routes.rb

```<code># frozen_string_literal: true

Rails.application.routes.draw do
  resources :posts
  namespace :admin do
      resources :users

      root to: "users#index"
    end
  devise_for :users, module: 'users'
  get 'profile', to: 'profile#index'
  root to: "home#index"
end

</code>```

答:
Turns out I was just being silly. amongst the input fields there was a ERB button_to helper for canceling the account (or rather deleting the user) this helper was rendering a form inside the update form and that inner form was what was being submitted when hitting the submit button on the outer form, causing the delete action to be triggered

EDIT: To be clear the way to avoid this is to make sure the button_to helper is outside the form you're wanting to submit or on a separate page.

Body:
I have a rails application I'm working on, and I'm using devise for authentication. I'm having an issue where when I try to update the user details instead up updating the user the user just gets deleted.

In registrations/edit.html.erb I have:

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), method: :put) do |f| %>

  ... input tags and styling

<% end %>

Which generates the html:

<form class="edit_user" id="edit_user" enctype="multipart/form-data" action="/users" accept-charset="UTF-8" method="post">
<input type="hidden" name="_method" value="put" />
<input type="hidden" name="authenticity_token" value="Q2U4gEBfaIwCo2Vwi2fwXgwYLjzE4HpoDC8KN52m2GGqEdb94jd/c3TyFhEJtQEziHat9zFQs+e+fRJp4/j2WA==" />

... rest of the input tags

</form>

The key thing here being <input type="hidden" name="_method" value="put" /> in rails this should trigger the PUT route but for some reason when I submit the form it's triggering the delete route:

Started DELETE "/users" for 127.0.0.1 at 2020-06-01 16:15:48 +0100
   (0.6ms)  SET NAMES utf8mb4 COLLATE utf8mb4_bin,  @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'),  @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
   (0.2ms)  SELECT `schema_migrations`.`version` FROM `schema_migrations` ORDER BY `schema_migrations`.`version` ASC

Has anyone come across this before and know what could be causing it?

EDIT

my config/routes.rb

# frozen_string_literal: true

Rails.application.routes.draw do
  resources :posts
  namespace :admin do
      resources :users

      root to: "users#index"
    end
  devise_for :users, module: 'users'
  get 'profile', to: 'profile#index'
  root to: "home#index"
end


问:
Call Directory Extension - no extension found
I have an app using the Call Directory Extension. I log analytics on all the errors my users receive from the extension and out of around 260 users receiving errors this month, 7 users received an error that the extension was not found.

I know that is a really small percentage of users, but I'm curious why anyone would ever not have the extension installed with my app.

Is it possible that sometimes there is just a corrupted app download that fails to install the extension along with the app? Or is there anything I can do on my end to resolve this error?

答:
This seems to be an OS issue / installation error:

I had the same issue with an app that was distributed with an enterprise distribution certificate to >1000 Users. One single user reported the issue (we have an error message in the app). When checking his mobile phone, the Caller Identification / Blocking settings were indeed missing.

After deinstallation of our app and installation of a separate app with Caller Identification / Blocking from the App Store, the setting appeared. After that and re-installing our app the error was gone.


问:
Spring Kafka can not deserialize JSON
My consumer, which is a Spring Boot application, uses Spring Kafka. It is supposed to read messages from a topic in JSON format. When the messages are "small", everything goes without problems.

However, when the message is "big" (which is not actually that big - 6,7kB), my application throws the following exception. The input JSON is valid:

```<code>org.apache.kafka.common.errors.SerializationException: Error deserializing key/value for partition input-topic-0 at offset 0. If needed, please seek past the record to continue consumption.
Caused by: org.apache.kafka.common.errors.SerializationException: Can't deserialize data [[31, 58, 55,...]]
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Unexpected end-of-input in VALUE_STRING
</code>```

Please, be aware, that [[INT1, INT2, INT3,...]] denotes just a beginning of a long sequence of integers.

Example of a "small" JSON, that is processed without any problems (138 characters):

```<code>{"attr1":"value","timestamp":1589880366240,"encoding":"UTF-8aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}
</code>```

Example of a "big" JSON, that throws exception (4648 characters, 6,7kB):

```<code>{"attr1":"value","timestamp":1589880366240,"encoding":"[encoded data, 4600 characters]"}
</code>```

When I consumed the input topic, which the JSON was produced to, the "big" consumed JSON were cut to first 4087 characters. Therefore, I suspect, that the problem is in Kafka config.

答:
What version are you using (spring-kafka and Jackson)?

I just ran a test with your JSON and it worked just fine.

JsonDeserializer<Map<?, ?>> de = new JsonDeserializer<>(Map.class);
byte[] bytes = "{\"attr1\":\"value\",\"timestamp\":1589880366240,\"encoding\":\"[encoded data, 4600 characters]\"}".getBytes();
System.out.println(de.deserialize("foo", new RecordHeaders(), bytes));

```

{attr1=value, timestamp=1589880366240, [encoded data, 4609 characters]}

Title: Spring Kafka can not deserialize JSON

Body:
My consumer, which is a Spring Boot application, uses Spring Kafka. It is supposed to read messages from a topic in JSON format. When the messages are "small", everything goes without problems.

However, when the message is "big" (which is not actually that big - 6,7kB), my application throws the following exception. The input JSON is valid:

org.apache.kafka.common.errors.SerializationException: Error deserializing key/value for partition input-topic-0 at offset 0. If needed, please seek past the record to continue consumption.
Caused by: org.apache.kafka.common.errors.SerializationException: Can't deserialize data [[31, 58, 55,...]]
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Unexpected end-of-input in VALUE_STRING

Please, be aware, that [[INT1, INT2, INT3,...]] denotes just a beginning of a long sequence of integers.

Example of a "small" JSON, that is processed without any problems (138 characters):

{"attr1":"value","timestamp":1589880366240,"encoding":"UTF-8aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}

Example of a "big" JSON, that throws exception (4648 characters, 6,7kB):

{"attr1":"value","timestamp":1589880366240,"encoding":"[encoded data, 4600 characters]"}

When I consumed the input topic, which the JSON was produced to, the "big" consumed JSON were cut to first 4087 characters. Therefore, I suspect, that the problem is in Kafka config.

Body:
What version are you using (spring-kafka and Jackson)?

I just ran a test with your JSON and it worked just fine.

JsonDeserializer<Map<?, ?>> de = new JsonDeserializer<>(Map.class);
byte[] bytes = "{\"attr1\":\"value\",\"timestamp\":1589880366240,\"encoding\":\"[encoded data, 4600 characters]\"}".getBytes();
System.out.println(de.deserialize("foo", new RecordHeaders(), bytes));

{attr1=value, timestamp=1589880366240, [encoded data, 4609 characters]}


问:
Rest API Design - Image tagging application
I am working on a tagging application to explore REST and Dropwizard.

Images can be uploaded and associated with tags. CRUD operation on those resources.
Here the 2 resources are - image and tag.  I am following the collections pattern in designing the rest endpoints . The DB schema of the mini application are as follows -

```<code>create table images(
   id BIGINT NOT NULL AUTO_INCREMENT,
   url VARCHAR(100) NOT NULL,
   isActive BOOLEAN default true,
   description BLOB NOT NULL,
   creation_time TIMESTAMP default now(),
   updation_time TIMESTAMP default now(),
   PRIMARY KEY ( id )
);

create table tags(
    id BIGINT NOT NULL AUTO_INCREMENT,
    description BLOB NOT NULL,
    is_active BOOLEAN default true,
    creation_time TIMESTAMP default now(),
    updation_time TIMESTAMP default now(),
    PRIMARY KEY( id )
);

create table images_tags(
    id BIGINT NOT NULL AUTO_INCREMENT,
    image_id BIGINT NOT NULL,
    tag_id BIGINT NOT NULL,
    is_active BOOLEAN default true,
    association_time TIMESTAMP default now(),
    PRIMARY KEY( id ),
    CONSTRAINT images_tags_uc UNIQUE (image_id,tag_id,is_active),
    FOREIGN KEY (image_id) REFERENCES images(id),
    FOREIGN KEY (tag_id) REFERENCES tags(id)
)
</code>```

The endpoints designed are as follows -

```<code>GET /images
GET /images/{id}
GET /tags
GET /tags/{id}

POST /images - creation of a new image- body will contain the tags associated at image upload/creation in the system.
POST /tags - creation of a new tag

PUT /tags/{id} - update a tag
PUT /images/{id} - update a image

DELETE /tags/{id}
DELETE /images/{id}

GET /search/tags?query="ab*"&startIndex=0&limit=20 - search tags starting with ab
</code>```

Now the use-case where I am stuck about the endpoint design.

A uploaded image can change the tag association . lets say image I1 at creation time got
associated with tags t1,t2. Later user wants to remove t2 tag and add tag - t3,t4 from available tags to the image. How should this action/use-case be supported by API following REST principles.

My design -

```<code>PUT /images/{id}/tags/associate
{
"addedTags" :[t3,t4],
"removeTags" : [t2]
}

</code>```

*My question is that is the above endpoint a good way of REST api design. If not what should the endpoint look like ? *

答:
Forget about your REST API - think about how you would achieve the outcome you want with a collection of web pages, and forms that the operator can fill in and submit.

That will give you important insights into how your REST API should be designed.

The important element here is that a REST API doesn't expose your data model to the web, it exposes your affordance model to the web; we're defining families of resources (documents) that allow the consumer to use general purpose tools to interact with our business.

Now, if you aren't happy with web forms, a reasonable alternative is to define your API in terms of edits to the documents themselves.  All of the interaction would look something like

```<code>GET /e61954b9-a6a5-4a19-a7aa-0d2ca436dc82
</code>```

```<code>200 OK

{original contents}
</code>```

Client makes edits to its local copy of the document, then...

```<code>PUT /e61954b9-a6a5-4a19-a7aa-0d2ca436dc82

{updated contents}
</code>```

```<code>200 OK
</code>```

So for the use case you describe, we might GET a copy of a document that describes the image and the list of tags associated with it, then modify our local copy to remove the unwanted tags and add new tags as necessary, the PUT a copy of our local representation back to the server.

Depending on how many different kinds of use cases we needed to support, there might be many resources available for interacting with a single image in your system.

Body:
I am working on a tagging application to explore REST and Dropwizard.

Images can be uploaded and associated with tags. CRUD operation on those resources.
Here the 2 resources are - image and tag.  I am following the collections pattern in designing the rest endpoints . The DB schema of the mini application are as follows -

create table images(
   id BIGINT NOT NULL AUTO_INCREMENT,
   url VARCHAR(100) NOT NULL,
   isActive BOOLEAN default true,
   description BLOB NOT NULL,
   creation_time TIMESTAMP default now(),
   updation_time TIMESTAMP default now(),
   PRIMARY KEY ( id )
);

create table tags(
    id BIGINT NOT NULL AUTO_INCREMENT,
    description BLOB NOT NULL,
    is_active BOOLEAN default true,
    creation_time TIMESTAMP default now(),
    updation_time TIMESTAMP default now(),
    PRIMARY KEY( id )
);

create table images_tags(
    id BIGINT NOT NULL AUTO_INCREMENT,
    image_id BIGINT NOT NULL,
    tag_id BIGINT NOT NULL,
    is_active BOOLEAN default true,
    association_time TIMESTAMP default now(),
    PRIMARY KEY( id ),
    CONSTRAINT images_tags_uc UNIQUE (image_id,tag_id,is_active),
    FOREIGN KEY (image_id) REFERENCES images(id),
    FOREIGN KEY (tag_id) REFERENCES tags(id)
)

The endpoints designed are as follows -

GET /images
GET /images/{id}
GET /tags
GET /tags/{id}

POST /images - creation of a new image- body will contain the tags associated at image upload/creation in the system.
POST /tags - creation of a new tag

PUT /tags/{id} - update a tag
PUT /images/{id} - update a image

DELETE /tags/{id}
DELETE /images/{id}

GET /search/tags?query="ab*"&startIndex=0&limit=20 - search tags starting with ab

Now the use-case where I am stuck about the endpoint design.

A uploaded image can change the tag association . lets say image I1 at creation time got
associated with tags t1,t2. Later user wants to remove t2 tag and add tag - t3,t4 from available tags to the image. How should this action/use-case be supported by API following REST principles.

My design -

PUT /images/{id}/tags/associate
{
"addedTags" :[t3,t4],
"removeTags" : [t2]
}

*My question is that is the above endpoint a good way of REST api design. If not what should the endpoint look like ? *

Body:
Forget about your REST API - think about how you would achieve the outcome you want with a collection of web pages, and forms that the operator can fill in and submit.

That will give you important insights into how your REST API should be designed.

The important element here is that a REST API doesn't expose your data model to the web, it exposes your affordance model to the web; we're defining families of resources (documents) that allow the consumer to use general purpose tools to interact with our business.

Now, if you aren't happy with web forms, a reasonable alternative is to define your API in terms of edits to the documents themselves.  All of the interaction would look something like

GET /e61954b9-a6a5-4a19-a7aa-0d2ca436dc82

200 OK

{original contents}

Client makes edits to its local copy of the document, then...

PUT /e61954b9-a6a5-4a19-a7aa-0d2ca436dc82

{updated contents}

200 OK

So for the use case you describe, we might GET a copy of a document that describes the image and the list of tags associated with it, then modify our local copy to remove the unwanted tags and add new tags as necessary, the PUT a copy of our local representation back to the server.

Depending on how many different kinds of use cases we needed to support, there might be many resources available for interacting with a single image in your system.


问:
How to take n spaced input for multiple lines in java?
11 22 33

44 54 63

73 53 24

I am unable to take input in this format in java.
I am comfortable with n spaced input for single line but am unable to take n spaced multiple line input used in competitive coding.
Can anyone provide me an easy solution to it.

答:
You can use a Scanner for this purpose:

```<code>import java.util.Scanner;
public class GetInput {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int[][] numbers = new int[3][3];

        for(int i = 0; i < 3; i++) {    //Iterating over the lines - in this case the user has to enter 3 lines
            for(int j = 0; j < 3; j++) {    //User has to enter 3 numbers per line
                numbers[i][j] = scan.nextInt(); //Scans the next int. It is not a problem that you don't press enter after each number
            }
        }

        //Output - just to test if all went correct
        for(int i = 0; i < 3; i++) {
            for(int j = 0; j < 3; j++) {
                System.out.print(numbers[i][j] + " ");
            }
            System.out.println("");
        }

    }
}
</code>```

Body:
You can use a Scanner for this purpose:

import java.util.Scanner;
public class GetInput {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int[][] numbers = new int[3][3];

        for(int i = 0; i < 3; i++) {    //Iterating over the lines - in this case the user has to enter 3 lines
            for(int j = 0; j < 3; j++) {    //User has to enter 3 numbers per line
                numbers[i][j] = scan.nextInt(); //Scans the next int. It is not a problem that you don't press enter after each number
            }
        }

        //Output - just to test if all went correct
        for(int i = 0; i < 3; i++) {
            for(int j = 0; j < 3; j++) {
                System.out.print(numbers[i][j] + " ");
            }
            System.out.println("");
        }

    }
}


问:
Move child elements if parent is duplicate
Just staring to lean js here. Is it possible to move child elements from one parent under another parent if parent name is duplicate?

Example:

How to put Something else & Something like under a single Composition parent, and Someone else under one Content, and delete the duplicates.
Is this possible with javascript or jquery? Thank you!

```<code><li>
  <h4>Composition</h4>
  <p>Something</p>
</li>
<li>
  <h4>Composition</h4>
  <p>Something else</p>
</li>
<li>
  <h4>Composition</h4>
  <p>Something like</p>
</li>

<li>
  <h4>Content</h4>
  <p>Someone</p>
</li>
  <h4>Content</h4>
  <p>Someone else</p>
</li>
</code>```

here is the js I got so far, I'm stuck at moving p items to the first element that repeats, each under it's parent. thing is parent elements don't have certain id's or classes:

```<code>const $technicalProp = $("[data-surface-prop]");
const technicalVal = $("[data-surface-val]");
let duplicate = {};

$technicalProp.each(function() {
  let txt = $(this).text();

  if (duplicate[txt]) {
     $(this).remove(); // this only removes the dulicate names I also need to move chlidren
  }
  else {
    duplicate[txt] = true;
  }
});
</code>```

答:
With jQuery you can remove and add elements with detach(), append() and prepend()

Like here: https://stackoverflow.com/a/19802593/11265780 (but replace jQuery with $)

Body:
Just staring to lean js here. Is it possible to move child elements from one parent under another parent if parent name is duplicate?

Example:

How to put Something else & Something like under a single Composition parent, and Someone else under one Content, and delete the duplicates.
Is this possible with javascript or jquery? Thank you!

Composition

Something

Composition

Something else

Composition

Something like

Content

Someone

Content

Someone else

here is the js I got so far, I'm stuck at moving p items to the first element that repeats, each under it's parent. thing is parent elements don't have certain id's or classes:

const $technicalProp = $("[data-surface-prop]");
const technicalVal = $("[data-surface-val]");
let duplicate = {};

$technicalProp.each(function() {
  let txt = $(this).text();

  if (duplicate[txt]) {
     $(this).remove(); // this only removes the dulicate names I also need to move chlidren
  }
  else {
    duplicate[txt] = true;
  }
});


问:
Set transparency of background cover using css
Below is code for setting background cover, i want to set transparency of background cover, so that i can display some text over it. I got the solution as below, but its not working for me. I am not getting where am missing it. </p>

```<code> style="background: url(images/football_ground.jpg) no-repeat center center fixed;-webkit-
     background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;-moz-opacity:.30;
filter:alpha(opacity=30);
-khtml-opacity: 0.3;  ">
</code>```

答:
Reaching this now and our requirement was such that the image needed a darker cover, so that the white text placed on top of the image, could be more visible - in case of a whiter background image.

I always used elements to achieve this, but another solution might be to just add this to your parent element's css (or wherever you need it):

```<code>background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)), url("./your_image_url");
</code>```

There might even be a shorter way, but I've been using the above at some places.

Body:
Below is code for setting background cover, i want to set transparency of background cover, so that i can display some text over it. I got the solution as below, but its not working for me. I am not getting where am missing it.

 style="background: url(images/football_ground.jpg) no-repeat center center fixed;-webkit-
     background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;-moz-opacity:.30;
filter:alpha(opacity=30);
-khtml-opacity: 0.3;  ">

Body:
Reaching this now and our requirement was such that the image needed a darker cover, so that the white text placed on top of the image, could be more visible - in case of a whiter background image.

I always used elements to achieve this, but another solution might be to just add this to your parent element's css (or wherever you need it):

background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)), url("./your_image_url");

There might even be a shorter way, but I've been using the above at some places.


问:
How to pass Object in as string list in c# controller?
```<code>public class abcController : ApiController
{
    public IEnumerable<string> Get()
    {
        return new string[] { "A","B","C"};
    }

}
</code>```

I want to pass object containing name, id and image in string array..
How to accomplish this??
Please help me..
Also tell me how to access any specific element in this object..

答:
I think this is what you are looking for. I have put this in Console app. You can just copy the logic to your controller</p>

```<code>        public class ImageInformation
        {
            public ImageInformation(string name, string id, string image)
            {
                Name = name;
                Id = id;
                Image = image;
            }
            public string Name { get; private set; }
            public string Id { get; private set; }
            public string Image { get; private set; }
        }

        public static IEnumerable<ImageInformation> Get()
        {
            return new List<ImageInformation> {
               new ImageInformation("A", "1", "A.jpg"),
               new ImageInformation("B", "2", "B.jpg"),
               new ImageInformation("C", "3", "C.jpg"),
            };
        }

        public static void Main()
        {
            var images = Get();
            var imageA = images.First(x => x.Name == "A");
            var imageAName = imageA.Name;
            var imageAId = imageA.Id;
            var imageAImage = imageA.Image;

            Console.WriteLine(imageAName);
            Console.WriteLine(imageAId);
            Console.WriteLine(imageAImage);
        }
</code>```

Body:
public class abcController : ApiController
{
    public IEnumerable<string> Get()
    {
        return new string[] { "A","B","C"};
    }

}

I want to pass object containing name, id and image in string array..
How to accomplish this??
Please help me..
Also tell me how to access any specific element in this object..

Body:
I think this is what you are looking for. I have put this in Console app. You can just copy the logic to your controller

        public class ImageInformation
        {
            public ImageInformation(string name, string id, string image)
            {
                Name = name;
                Id = id;
                Image = image;
            }
            public string Name { get; private set; }
            public string Id { get; private set; }
            public string Image { get; private set; }
        }

        public static IEnumerable<ImageInformation> Get()
        {
            return new List<ImageInformation> {
               new ImageInformation("A", "1", "A.jpg"),
               new ImageInformation("B", "2", "B.jpg"),
               new ImageInformation("C", "3", "C.jpg"),
            };
        }

        public static void Main()
        {
            var images = Get();
            var imageA = images.First(x => x.Name == "A");
            var imageAName = imageA.Name;
            var imageAId = imageA.Id;
            var imageAImage = imageA.Image;

            Console.WriteLine(imageAName);
            Console.WriteLine(imageAId);
            Console.WriteLine(imageAImage);
        }


问:
Why does the sun jdk source code not contain the javax.servlet package?
I tried to find the source code of the javax.servlet package in the jdk source code, but it seems the jdk doesn't contains the package. Where can I download the package?</p>

答:
If you need a peek at what the source itself would look like here [1] are the sources for javax.servlet in Apache Geronimo and [2] for glass fish.

[1] http://svn.apache.org/viewvc/geronimo/specs/trunk/geronimo-servlet_2.5_spec/src/main/java/
[2] http://svn-mirror.glassfish.org/glassfish-svn/branches/BuildDeploymentTest/web/javax.servlet/


问:
How to join two CSV files by a temporary common column in awk?
I have two CSV files in the form of

file1

```<code>A,44
A,21
B,65
C,79
</code>```

file2

```<code>A,7
B,4
C,11
</code>```

I used awk as

```<code>awk -F, 'NR==FNR{a[$1]=$0;next} ($1 in a){print a[$1]","$2 }' file1.csv file2.csv
</code>```

producing

```<code>A,44,7
A,21,7
B,65,4
C,79,11
</code>```

a[$1] prints the entire line from file1. How can I omit the first columns in both files (the first column is only used to match the second columns) to produce:

```<code>44,7
21,7
65,4
79,11
</code>```

In other words, how can I pass the columns from the first file to the print block, as $2 does for the second file?

答:
You can join them using the join command and chose which fields you want to have in the output:</p>

```<code>kent$  join -t',' -o 1.2,2.2 file1 file2
44,7
21,7
65,4
79,11
</code>```

Body:
I have two CSV files in the form of

file1

A,44
A,21
B,65
C,79

file2

A,7
B,4
C,11

I used awk as

awk -F, 'NR==FNR{a[$1]=$0;next} ($1 in a){print a[$1]","$2 }' file1.csv file2.csv

producing

A,44,7
A,21,7
B,65,4
C,79,11

a[$1] prints the entire line from file1. How can I omit the first columns in both files (the first column is only used to match the second columns) to produce:

44,7
21,7
65,4
79,11

In other words, how can I pass the columns from the first file to the print block, as $2 does for the second file?

Body:
You can join them using the join command and chose which fields you want to have in the output:

kent$  join -t',' -o 1.2,2.2 file1 file2
44,7
21,7
65,4
79,11


问:
Does dividing float by int always give float? C++
I been programming on C and C++ for some time, and was always sure that double dividing int gives double, or double dividing int also give double (only int by int gives int) and same with adding. I was doing my assignment and was sure that 1 + (f*f + 10) / k, where f is double and k is int would always return double.
I was using g++ -std=gnu++11 command on mac (so it's clang compiler probably) and I got tests passed (I indeed got float number as a result), but my teacher says that it not for sure that it will be float (he is using windows). Is that behavior platform specific? Is there any C++ standard that describes double on int division? Thank you!
My code:

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

int main() {
    int  N;
    double f, P = 0;
    cin >> N >> f;
    for (double k = 1; k <= N; k++){
      P += 1 + (f*f + 10) / k;
    }
    cout << P;
    return 0;
}
</code>```

答:
From the C++20 standard draft [expr.arith.conv]:

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

(1.1)
  If either operand is of scoped enumeration type, no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.

(1.2)
  If either operand is of type long double, the other shall be converted to long double.

(1.3)
  Otherwise, if either operand is double, the other shall be converted to double.

(1.4)
  Otherwise, if either operand is float, the other shall be converted to float.

(1.5)
  Otherwise, the integral promotions ([conv.prom]) shall be performed on both operands.56 Then the following rules shall be applied to the promoted operands:
  ...

This paragraph has not changed in any fundmental way since at least C++11 (which was the oldest I checked), so your teacher has some explaining to do.

Body:
I been programming on C and C++ for some time, and was always sure that double dividing int gives double, or double dividing int also give double (only int by int gives int) and same with adding. I was doing my assignment and was sure that 1 + (f*f + 10) / k, where f is double and k is int would always return double.
I was using g++ -std=gnu++11 command on mac (so it's clang compiler probably) and I got tests passed (I indeed got float number as a result), but my teacher says that it not for sure that it will be float (he is using windows). Is that behavior platform specific? Is there any C++ standard that describes double on int division? Thank you!
My code:

#include <iostream>
using namespace std;

int main() {
    int  N;
    double f, P = 0;
    cin >> N >> f;
    for (double k = 1; k <= N; k++){
      P += 1 + (f*f + 10) / k;
    }
    cout << P;
    return 0;
}


问:
Automatically check for binary incompatibility between versions of a C# DLL?
I'm looking for any automatable way to check for binary incompatibility between versions of a C# DLL.

Something like Unix C++'s abi-compliance-checker but for .NET, and in particular for C#, would be great. This SO answer gives a screenshot of exactly the kind of info that I'd love to be able to get regarding two different versions of a C# API.

If there isn't any direct equivalent, then it would also be helpful to get any information at all about any automatable way to get some assurance that binary compatibility isn't broken between versions of a library.

This question seems to be the authoritative list on Stack Overflow of ways to break your API. There's also an article by Jon Skeet which discusses some of these issues. (And of course there are multiple other discussions of this issue on the internet; though there is a lot more of it focused on C++ than on C# and .NET, which is what I'm asking about here.)

Amongst other things, those articles help make clear that:

Binary and compilation compatibility and incompatibility are NOT trivial problems!

Binary (in)compatibility does not always entail compilation (in)compatibility nor vice versa

Even though (it might be worth noting here) at least one Microsoft article on the topic incorrectly/misleadingly states that it does in one direction

There are different levels of incompatibility: in particular, there are some obscure things, particularly to do with reflection, that users of a library can do which will make certain API changes binary incompatible, where they wouldn't have been otherwise

As a side note, this pretty much makes it seem like real world incompatibility isn't a yes/no question: there'll be certain theoretically incompatible changes which you might well be prepared to make within a major version of your API, if you don't expect normal users of the API to be doing these more obscure things with it

That fits with the different severities of incompatibility shown in the abi-compliance-checker screenshot in the SO answer linked above

So, given that everybody these days is supposed to be updating their APIs using semantic versioning, and also given that everybody is using test suites and probably devops as well, how on earth is everybody - or even anybody?! - automatically testing for binary incompatibility changes in .NET?

I can see that careful use of a test suite is enough to let you know if you've made compilation compatibility changes, and most projects already have this - hence why my question is about binary incompatibility changes, which don't seem to be automatically detected at all in any projects I've looked at or worked on.

Just reading the above articles and being careful probably isn't enough... (though of course it's some kind of start) but I can't find any documentation about any other approach.

答:
As a partial answer to my own question, and on the basis that something is better than nothing at all, it looks to me as if one possible pragmatic answer (i.e. it definitely won't catch all possible problems, but it should at least catch some...) would be to store compiled versions of old test suites and then to check whether these still run against compiled newer versions of the API.

In essentially all OSS projects I've worked on, the tests and the library are compiled at the same time. Anything which is a binary incompatibility but not a compilation incompatibility would never cause a failure when just running normal tests in the normal way, in such a project. But at least some such problems would show up with what I've suggested.

So I'm not just answering my question by saying 'have a test suite'! I'm suggesting something different from what I've seen normally done with test suites, that can (and does, I now use this approach) help with the problem my question is about.


问:
How to make Phonegap connect to localhost
I am working with phonegap for the first time to build hybrid mobile app with back-end(php, mysql). So i am doing a test on how phonegap can connect to php on localhost to send and retrieve data. But no data was retrieved, I have reduced my codes to the this and i see no errors in both ajax call and php code. So i guess it should be the way phonegap connects to backend that i am getting wrong, please help.

html form and ajax call:

```<code>        <form id="form1">
       <input  type="text" id="email"  />
         <input  type="password" id="password"  />
         <input type="submit" name="login" id="login" value="Login">
        </form>

      <script type="text/javascript">
      $("form").submit(function(){
         var data= ("#form1").serialize();
       $.post("http://localhost/securityapp/login.php",data,function(response){
     alert(response);
       });

        });

      </script>
</code>```

php file:

```<code>          <?php
           include 'db.php';
      session_start();
     if ($_POST ) {
     echo $_POST;

        }

           ?>
</code>```

Basically it is meant to alert to values sent to php script as the response but it is not doing so, network tab says 200 for status. what am i doing wrong? I feel phonegap isn't connecting to the url defined

答:
This is how I solved this issue:

created a table on a database that holds the current URL/IP of the server

Created a check-url.php file, this file runs a query on the database to see IP/URL of
the server

I created a connection.js file, this file basically makes a request to a check-url.php
to get current IP of the server to use in Cordova app

check-url.php

 header("Access-Control-Allow-Origin: *"); //to allow phonegap access it because of cross origin and domain restrictions
 require 'db.php';
 $query= "SELECT url  FROM settings";
 $query= mysqli_query($conn,$query);
 $row = mysqli_fetch_assoc($query);
 $row= $row['url'];
 echo $row; //current IP exmaple:http://127.0.0.1:80/
```

<p>connection.js</p>

<pre class="lang-js prettyprint-override"><code>  //check current server ip from database
export function check_url(callback) {
  var httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = function() {
      if (httpRequest.readyState === 4) { // request is done
          if (httpRequest.status === 200) { // successfully
              callback(httpRequest.responseText); // we're calling our method
          }
      }
  };
  httpRequest.open('GET', "http://127.0.0.1:80/projectname/check-url.php");
  httpRequest.send();
}
</code>```

So any time I want to connect to backend by Cordova I import the function check-url() from connection.js into my front-end ajax request url like this:

```

Note: The URL/IP in connection.js, database, and server IP should be the same, as this helps you not to repeat IP always and also to test when using PhoneGap mobile and also when you switch to live, change it to the current IP address of your project.

Body:
I am working with phonegap for the first time to build hybrid mobile app with back-end(php, mysql). So i am doing a test on how phonegap can connect to php on localhost to send and retrieve data. But no data was retrieved, I have reduced my codes to the this and i see no errors in both ajax call and php code. So i guess it should be the way phonegap connects to backend that i am getting wrong, please help.

html form and ajax call:

        <form id="form1">
       <input  type="text" id="email"  />
         <input  type="password" id="password"  />
         <input type="submit" name="login" id="login" value="Login">
        </form>

php file:

          <?php
           include 'db.php';
      session_start();
     if ($_POST ) {
     echo $_POST;

        }

           ?>

Basically it is meant to alert to values sent to php script as the response but it is not doing so, network tab says 200 for status. what am i doing wrong? I feel phonegap isn't connecting to the url defined

Body:
This is how I solved this issue:

created a table on a database that holds the current URL/IP of the server

Created a check-url.php file, this file runs a query on the database to see IP/URL of
the server

I created a connection.js file, this file basically makes a request to a check-url.php
to get current IP of the server to use in Cordova app

check-url.php

 header("Access-Control-Allow-Origin: *"); //to allow phonegap access it because of cross origin and domain restrictions
 require 'db.php';
 $query= "SELECT url  FROM settings";
 $query= mysqli_query($conn,$query);
 $row = mysqli_fetch_assoc($query);
 $row= $row['url'];
 echo $row; //current IP exmaple:http://127.0.0.1:80/

connection.js

  //check current server ip from database
export function check_url(callback) {
  var httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = function() {
      if (httpRequest.readyState === 4) { // request is done
          if (httpRequest.status === 200) { // successfully
              callback(httpRequest.responseText); // we're calling our method
          }
      }
  };
  httpRequest.open('GET', "http://127.0.0.1:80/projectname/check-url.php");
  httpRequest.send();
}

So any time I want to connect to backend by Cordova I import the function check-url() from connection.js into my front-end ajax request url like this:

<script type="module">
   import {check-url} from './connection.js';

check-url(function(result) {
var currentIP= result;
$.ajax({
type:"POST",
url: currentIP + "projectapp/login.php",
data:data,
success: function(data){
//do something
}
});
});
</script>

Note: The URL/IP in connection.js, database, and server IP should be the same, as this helps you not to repeat IP always and also to test when using PhoneGap mobile and also when you switch to live, change it to the current IP address of your project.