问:
How to get alert dialog with four images with selection
I want to create dialog button like attached image .
In this dialog four images will appear for selection .

```<code>String[] image = new String[]{R.mipmap.ic_launcher1, R.mipmap.ic_launcher2,R.mipmap.ic_launcher3, R.mipmap.ic_launcher4};
 AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose a container size");
        builder.setItems(image, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // the user clicked on colors[which]
            }
        });
        builder.show();
</code>```

答:
You have to use android.App.Dialog

for example

```<code>  final Dialog dialog = new Dialog(this, R.style.cust_dialog);
    dialog.setContentView(R.layout.your_xml);
    dialog.setTitle("Your title");
    dialog.setCancelable(false);
    dialog.show();
   Button d_btn_ok = (Button) dialog.findViewById(R.id.btnOk);
   Button d_btn_cancel = (Button) dialog.findViewById(R.id.btnCancel);

   ImageView image1 = (ImageView) dialog.findViewById(R.id.image1);
   image1.setImageDrawable(getResources().getDrawable(R.drawable.address));

   ImageView image2 = (ImageView) dialog.findViewById(R.id.image2);

   ImageView image3 = (ImageView) dialog.findViewById(R.id.image3);

   ImageView image4 = (ImageView) dialog.findViewById(R.id.image4);
</code>```

Make xml having ImageViews and what you want

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
android:background="@color/lightest_grey"
android:theme="@style/AppTheme">

<TextView
    android:id="@+id/tvMsg"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textSize="18sp"
    android:gravity="center"
    android:text="Msg" />

<LinearLayout
    android:id="@+id/linearImage1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="20dp"
    android:layout_below="@+id/tvMsg"
    android:weightSum="2">

    <ImageView
        android:id="@+id/image1"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/image2"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />

</LinearLayout>

<LinearLayout
    android:id="@+id/linearImag2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="20dp"
    android:layout_below="@+id/linearImage1"
    android:weightSum="2">

    <ImageView
        android:id="@+id/image3"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/image4"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="20dp"
    android:layout_below="@+id/linearImag2"
    android:weightSum="2">

    <Button
        android:id="@+id/btnOk"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@color/colorAccent"
        style="?android:attr/buttonBarButtonStyle"
        android:text="Yes"
        android:textColor="@color/white" />

    <Button
        android:id="@+id/btnCancel"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_marginLeft="2dp"
        android:layout_marginStart="2dp"
        style="?android:attr/buttonBarButtonStyle"
        android:background="@color/colorAccent"
        android:text="No"
        android:textColor="@color/white" />

</LinearLayout>
</code>```

Body:
I want to create dialog button like attached image .
In this dialog four images will appear for selection .

String[] image = new String[]{R.mipmap.ic_launcher1, R.mipmap.ic_launcher2,R.mipmap.ic_launcher3, R.mipmap.ic_launcher4};
 AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose a container size");
        builder.setItems(image, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // the user clicked on colors[which]
            }
        });
        builder.show();

Body:
You have to use android.App.Dialog

for example

  final Dialog dialog = new Dialog(this, R.style.cust_dialog);
    dialog.setContentView(R.layout.your_xml);
    dialog.setTitle("Your title");
    dialog.setCancelable(false);
    dialog.show();
   Button d_btn_ok = (Button) dialog.findViewById(R.id.btnOk);
   Button d_btn_cancel = (Button) dialog.findViewById(R.id.btnCancel);

   ImageView image1 = (ImageView) dialog.findViewById(R.id.image1);
   image1.setImageDrawable(getResources().getDrawable(R.drawable.address));

   ImageView image2 = (ImageView) dialog.findViewById(R.id.image2);

   ImageView image3 = (ImageView) dialog.findViewById(R.id.image3);

   ImageView image4 = (ImageView) dialog.findViewById(R.id.image4);

Make xml having ImageViews and what you want

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
android:background="@color/lightest_grey"
android:theme="@style/AppTheme">

<TextView
    android:id="@+id/tvMsg"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textSize="18sp"
    android:gravity="center"
    android:text="Msg" />

<LinearLayout
    android:id="@+id/linearImage1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="20dp"
    android:layout_below="@+id/tvMsg"
    android:weightSum="2">

    <ImageView
        android:id="@+id/image1"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/image2"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />

</LinearLayout>

<LinearLayout
    android:id="@+id/linearImag2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="20dp"
    android:layout_below="@+id/linearImage1"
    android:weightSum="2">

    <ImageView
        android:id="@+id/image3"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/image4"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="20dp"
    android:layout_below="@+id/linearImag2"
    android:weightSum="2">

    <Button
        android:id="@+id/btnOk"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@color/colorAccent"
        style="?android:attr/buttonBarButtonStyle"
        android:text="Yes"
        android:textColor="@color/white" />

    <Button
        android:id="@+id/btnCancel"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_marginLeft="2dp"
        android:layout_marginStart="2dp"
        style="?android:attr/buttonBarButtonStyle"
        android:background="@color/colorAccent"
        android:text="No"
        android:textColor="@color/white" />

</LinearLayout>


来源: stackexchange

问:
Bundle.main.path(forResource:ofType:inDirectory:) returns nil
Try not to laugh or cry -- I'm just getting back into coding after 20 years out...

I've spent more than 4 hours looking at references and trying code snippets to get Bundle.main.path to open my text file so I can read in data for my app (my next step is to appropriately parse it).

```<code>if let filepath = Bundle.main.path(forResource: "newTest", ofType: "txt")
{
    do
    {
        let contents = try String(contentsOfFile: filepath)
        print(contents)

    }
    catch
    {
        print("Contents could not be loaded.")
    }
}
else
{
    print("newTest.txt not found.")
}
</code>```

The result is: "newTest.txt not found." regardless of how I try to drag&drop the file into the project, create the file inside Xcode or use the File -> Add Files to ... menu item.

答:
Ah, so just found myself dealing with the exact same problem as the OP.

The problem is that the solutions given here and here do not work when the code is being executed in a playground, since the Options menu of add files looks different for it does not show the Add to targets field:

When inside a .playground file, instead press the Hide or show the Navigator button on the top-right of your Xcode window (visual impression)-->

Then, once the Navigator folds open on the left-side of the Xcode window, simply drag & drop your file to the Resources directory of your playground.

If your setup looks anything like the following you should be ok:

ContentLicense: CC BY-SA 3.0

Body:
Try not to laugh or cry -- I'm just getting back into coding after 20 years out...

I've spent more than 4 hours looking at references and trying code snippets to get Bundle.main.path to open my text file so I can read in data for my app (my next step is to appropriately parse it).

if let filepath = Bundle.main.path(forResource: "newTest", ofType: "txt")
{
    do
    {
        let contents = try String(contentsOfFile: filepath)
        print(contents)

    }
    catch
    {
        print("Contents could not be loaded.")
    }
}
else
{
    print("newTest.txt not found.")
}

The result is: "newTest.txt not found." regardless of how I try to drag&drop the file into the project, create the file inside Xcode or use the File -> Add Files to ... menu item.


问:
JavaScript function gets 100x slower for no obvious reason
I have this function:

```<code>function drawRect(rect, color, filled) {
    const width = this.width;
    const x = rect.x;
    const y = rect.y;
    const w = rect.w;
    const h = rect.h;

    console.time('drawRect');
    for (let _y = y; _y < y + h; _y++) {
      for (let _x = x; _x < x + w; _x++) {
         this.data[(_x + this.width * _y) * 4 + 0] = color.red;
         this.data[(_x + this.width * _y) * 4 + 1] = color.green;
         this.data[(_x + this.width * _y) * 4 + 2] = color.blue;
         this.data[(_x + this.width * _y) * 4 + 3] = color.alpha * 255;
      }
    }
    console.timeEnd('drawRect');
}
</code>```

Essentially what I'm trying to do is write my own Canvas-like wrapper around a big ImageData blob. (That's what this.data is.)

I wrote this function in a self-contained environment and tested it. It ran very quickly (less than 1ms generally).

I then copied it over to the app that I intended to use it in. Suddenly, although the function continues to work, it runs at least 100x slower. The output from console.time has gone from ~1ms to over 100ms.

I have tested it with the exact same arguments in both the small app and the large app. The exact same invocation of this function runs 100x slower in the larger app.

I looked in the Chrome profiling tools, and the function does not show an icon saying that it is unoptimized.

What could possibly cause a function to run 100x slower when put in a larger codebase?

I'm sorry, but I cannot provide a MCVE. I simply cannot narrow down my huge app to see which part of it is causing the slowdown. In fact, that's exactly what I'd like to know, because I have no clue where to even begin looking.

答:
Aha! I figured it out. Maybe this will help someone in the future with the same issue, who knows.

It turned out that I was accessing the Uint8Array (this.data) at a negative index, due to a coding error. It was this access that caused Chrome's profiler to catastrophically explode.

A single negative access will cause the function to be deoptimized forever.

If you run into optimization issues with Canvas stuff, make sure you're not indexing out of bounds!

Body:
I have this function:

function drawRect(rect, color, filled) {
    const width = this.width;
    const x = rect.x;
    const y = rect.y;
    const w = rect.w;
    const h = rect.h;

    console.time('drawRect');
    for (let _y = y; _y < y + h; _y++) {
      for (let _x = x; _x < x + w; _x++) {
         this.data[(_x + this.width * _y) * 4 + 0] = color.red;
         this.data[(_x + this.width * _y) * 4 + 1] = color.green;
         this.data[(_x + this.width * _y) * 4 + 2] = color.blue;
         this.data[(_x + this.width * _y) * 4 + 3] = color.alpha * 255;
      }
    }
    console.timeEnd('drawRect');
}

Essentially what I'm trying to do is write my own Canvas-like wrapper around a big ImageData blob. (That's what this.data is.)

I wrote this function in a self-contained environment and tested it. It ran very quickly (less than 1ms generally).

I then copied it over to the app that I intended to use it in. Suddenly, although the function continues to work, it runs at least 100x slower. The output from console.time has gone from ~1ms to over 100ms.

I have tested it with the exact same arguments in both the small app and the large app. The exact same invocation of this function runs 100x slower in the larger app.

I looked in the Chrome profiling tools, and the function does not show an icon saying that it is unoptimized.

What could possibly cause a function to run 100x slower when put in a larger codebase?

I'm sorry, but I cannot provide a MCVE. I simply cannot narrow down my huge app to see which part of it is causing the slowdown. In fact, that's exactly what I'd like to know, because I have no clue where to even begin looking.


问:
Failed to find configured root that contains /storage/emulated/0/Android/data/com.example
I know that there are a lot of questions of this problem but I cannot resolve my problem with the other posts.

I don't understand why I see this message.

MainActivity

```<code>alert = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

public class MainActivity extends AppCompatActivity {

    ImageView iv_foto;
    static final int REQUEST_TAKE_PHOTO = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv_foto = (ImageView) findViewById(R.id.iv_foto);

    }

    public void sacarFoto(View v){
        dispatchTakePictureIntent();
    }
    String mCurrentPhotoPath;

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.josemiguelrodriguez.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_TAKE_PHOTO){
            iv_foto.setImageURI(Uri.parse(mCurrentPhotoPath));
        }
    }
}
</code>```

AndroidManifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.josemiguelrodriguez.pruebacamara">

    <uses-feature android:name="android.hardware.camera"
        android:required="true"
        />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.josemiguelrodriguez.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

file_paths.xml

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

Error:

```<code>03-31 13:39:14.292 30787-30787/com.example.josemiguelrodriguez.pruebacamara E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.josemiguelrodriguez.pruebacamara, PID: 30787
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.example.josemiguelrodriguez.pruebacamara/files/Pictures/JPEG_20170331_133914_-2001489715.jpg
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:711)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:400)
at com.example.josemiguelrodriguez.pruebacamara.MainActivity.dispatchTakePictureIntent(MainActivity.java:67)
at com.example.josemiguelrodriguez.pruebacamara.MainActivity.sacarFoto(MainActivity.java:33)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
</code>```

Many Thanks!! :D

UPDATE
The error is solved with the first response of @CommonsWare but now I have the following error:

Error

```<code>resolveUri failed on bad bitmap uri: /storage/emulated/0/Android/data/com.example.josemiguelrodriguez.pruebacamara/files/Pictures/JPEG_20170331_140455_-2001489715.png
</code>```

答:
```<code>File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
</code>```

Change to

```<code>File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
</code>```

And/Or change path="Pictures" to path=".".

ContentLicense: CC BY-SA 4.0

Body:
I know that there are a lot of questions of this problem but I cannot resolve my problem with the other posts.

I don't understand why I see this message.

MainActivity

alert = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

public class MainActivity extends AppCompatActivity {

    ImageView iv_foto;
    static final int REQUEST_TAKE_PHOTO = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv_foto = (ImageView) findViewById(R.id.iv_foto);

    }

    public void sacarFoto(View v){
        dispatchTakePictureIntent();
    }
    String mCurrentPhotoPath;

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.josemiguelrodriguez.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_TAKE_PHOTO){
            iv_foto.setImageURI(Uri.parse(mCurrentPhotoPath));
        }
    }
}

AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.josemiguelrodriguez.pruebacamara">

    <uses-feature android:name="android.hardware.camera"
        android:required="true"
        />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.josemiguelrodriguez.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

file_paths.xml

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

Error:

03-31 13:39:14.292 30787-30787/com.example.josemiguelrodriguez.pruebacamara E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.josemiguelrodriguez.pruebacamara, PID: 30787
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.example.josemiguelrodriguez.pruebacamara/files/Pictures/JPEG_20170331_133914_-2001489715.jpg
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:711)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:400)
at com.example.josemiguelrodriguez.pruebacamara.MainActivity.dispatchTakePictureIntent(MainActivity.java:67)
at com.example.josemiguelrodriguez.pruebacamara.MainActivity.sacarFoto(MainActivity.java:33)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)

Many Thanks!! :D

UPDATE
The error is solved with the first response of @CommonsWare but now I have the following error:

Error

resolveUri failed on bad bitmap uri: /storage/emulated/0/Android/data/com.example.josemiguelrodriguez.pruebacamara/files/Pictures/JPEG_20170331_140455_-2001489715.png

Body:
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);

Change to

File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

And/Or change path="Pictures" to path=".".


问:
FileUpload to FileStream
I am in process of sending the file along with HttpWebRequest. My file will be from FileUpload UI. Here I need to convert the File Upload to filestream to send the stream along with HttpWebRequest. How do I convert the FileUpload to a filestream?</p>

答:
You can put a FileUpload file directly into a MemoryStream by using FileBytes (simplified answer from Tech Jerk)

```<code>using (MemoryStream ms = new MemoryStream(FileUpload1.FileBytes))
{
    //do stuff
}
</code>```

Or if you do not need a memoryStream

```<code>byte[] bin = FileUpload1.FileBytes;
</code>```

Title: FileUpload to FileStream

Body:
You can put a FileUpload file directly into a MemoryStream by using FileBytes (simplified answer from Tech Jerk)

using (MemoryStream ms = new MemoryStream(FileUpload1.FileBytes))
{
    //do stuff
}

Or if you do not need a memoryStream

byte[] bin = FileUpload1.FileBytes;


问:
Can I underline text in an Android layout?
How can I define underlined text in an Android layout xml file?

答:
A simple and flexible solution in xml:</p>

```<code><View
  android:layout_width="match_parent"
  android:layout_height="3sp"
  android:layout_alignLeft="@+id/your_text_view_need_underline"
  android:layout_alignRight="@+id/your_text_view_need_underline"
  android:layout_below="@+id/your_text_view_need_underline"
  android:background="@color/your_color" />
</code>```

Body:
A simple and flexible solution in xml:

<View
  android:layout_width="match_parent"
  android:layout_height="3sp"
  android:layout_alignLeft="@+id/your_text_view_need_underline"
  android:layout_alignRight="@+id/your_text_view_need_underline"
  android:layout_below="@+id/your_text_view_need_underline"
  android:background="@color/your_color" />


问:
Can select but not write/update to SQL server
as the title say I can read from the database but not insert nor update. I've checked in SQL Management and my user can read, write and is also DB owner. (dbo)

Im using MyBatis with JDBC towards Microsoft SQL Management Studio

```<code>sqlFunctions.InsertIntoUserDatabase(3, "Kar", "LEEE");

    public void InsertIntoUserDatabase(int id, String firsname, String lastname) {
    session = sqlConnection.GetSqlSessionFactory().openSession();
    if(CheckIfSessionIsOpen(session)) {
        Employee employee = new Employee();
        employee.setFirstName(firsname); employee.setLastName(lastname);
        mapper.InsertInUsers(employee);
    }
}

@Insert("INSERT INTO company(firstname,lastname) VALUES(#{firstName}, #{lastName})")
void InsertInUsers(Employee employee);
</code>```

Employee is a normal getter and setter (int id, String firstname, String lastname)

```<code>    @Results({
        @Result(property = "firstName", column = "firstname"),
        @Result(property = "lastName", column = "lastname")
})
</code>```

My SQL connection is opened as it should be, and no errors is being shown.

答:
It seems your transaction is read only which is default behavior.

You need to make it writable also e.g.

```<code>@Transactional(propagation=Propagation.REQUIRED, readOnly=false, rollbackFor=Exception.class)
</code>```

Regards,
Krishan

Body:
as the title say I can read from the database but not insert nor update. I've checked in SQL Management and my user can read, write and is also DB owner. (dbo)

Im using MyBatis with JDBC towards Microsoft SQL Management Studio

sqlFunctions.InsertIntoUserDatabase(3, "Kar", "LEEE");

    public void InsertIntoUserDatabase(int id, String firsname, String lastname) {
    session = sqlConnection.GetSqlSessionFactory().openSession();
    if(CheckIfSessionIsOpen(session)) {
        Employee employee = new Employee();
        employee.setFirstName(firsname); employee.setLastName(lastname);
        mapper.InsertInUsers(employee);
    }
}

@Insert("INSERT INTO company(firstname,lastname) VALUES(#{firstName}, #{lastName})")
void InsertInUsers(Employee employee);

Employee is a normal getter and setter (int id, String firstname, String lastname)

    @Results({
        @Result(property = "firstName", column = "firstname"),
        @Result(property = "lastName", column = "lastname")
})

My SQL connection is opened as it should be, and no errors is being shown.

Body:
It seems your transaction is read only which is default behavior.

You need to make it writable also e.g.

@Transactional(propagation=Propagation.REQUIRED, readOnly=false, rollbackFor=Exception.class)

Regards,
Krishan


问:
Using Renderer in Angular 4
I understand why it's better to use renderer instead of directly manipulating the DOM in Angular2 projects. However, I have uninstalled, clear cache, reinstalled Node, Typescript and the Angular-CLI several times and I still get an error when trying to inject the Renderer.

```<code>import { Injectable, Renderer2 } from '@angular/core';
constructor(private renderer: Renderer2) {}
</code>```

__zone_symbol__message: "No provider for Renderer2!"

__zone_symbol__stack:"Error↵    at Error.ZoneAwareError

Does anyone have any ideas what I am doing wrong?

答:
Update:

@Injectable()
class MyService {
  private renderer: Renderer2;

  constructor(rendererFactory: RendererFactory2) {
    this.renderer = rendererFactory.createRenderer(null, null);
  }
}
```

<p>See more on this here:
https://github.com/angular/angular/issues/17824#issuecomment-351961146</p>

<p><strong>Previous version:</strong></p>

<p>According to your imports</p>

<pre class="lang-typescript prettyprint-override"><code>import { Injectable, Renderer2 } from '@angular/core'
</code>```

i suspect that you're trying to inject Renderer2 in your service class. It won't work. You can't inject Renderer2 in service. It should work for components and services that are provided within component.

We can take a look at source code https://github.com/angular/angular/blob/4.0.1/packages/core/src/view/provider.ts#L363-L373

while (view) {
  if (elDef) {
    switch (tokenKey) {
      case RendererV1TokenKey: {
        const compView = findCompView(view, elDef, allowPrivateServices);
        return createRendererV1(compView);
      }
      case Renderer2TokenKey: {
        const compView = findCompView(view, elDef, allowPrivateServices);
        return compView.renderer;
      }
```

<p>it checks only within element injector tree. And there are no other places when this token can be provided</p>

<p>So you have to pass <code>Renderer2</code> from component to service when you're calling some service method https://github.com/angular/angular/issues/17824#issuecomment-311986129</p>

<p>or you can provide service within component</p>

<pre class="lang-typescript prettyprint-override"><code>@Injectable()
export class Service {
  constructor(private r: Renderer2) {}
}
@Component({
  selector: 'my-app',
  templateUrl: `./app.component.html`,
  providers: [Service]
})
export class AppComponent {
  constructor(private service: Service) {}
}
</code>```

Title: Using Renderer in Angular 4

Body:
I understand why it's better to use renderer instead of directly manipulating the DOM in Angular2 projects. However, I have uninstalled, clear cache, reinstalled Node, Typescript and the Angular-CLI several times and I still get an error when trying to inject the Renderer.

import { Injectable, Renderer2 } from '@angular/core';
constructor(private renderer: Renderer2) {}

__zone_symbol__message: "No provider for Renderer2!"

__zone_symbol__stack:"Error↵    at Error.ZoneAwareError

Does anyone have any ideas what I am doing wrong?

Body:
Update:

@Injectable()
class MyService {
  private renderer: Renderer2;

  constructor(rendererFactory: RendererFactory2) {
    this.renderer = rendererFactory.createRenderer(null, null);
  }
}

See more on this here:
https://github.com/angular/angular/issues/17824#issuecomment-351961146

Previous version:

According to your imports

import { Injectable, Renderer2 } from '@angular/core'

i suspect that you're trying to inject Renderer2 in your service class. It won't work. You can't inject Renderer2 in service. It should work for components and services that are provided within component.

We can take a look at source code https://github.com/angular/angular/blob/4.0.1/packages/core/src/view/provider.ts#L363-L373

while (view) {
  if (elDef) {
    switch (tokenKey) {
      case RendererV1TokenKey: {
        const compView = findCompView(view, elDef, allowPrivateServices);
        return createRendererV1(compView);
      }
      case Renderer2TokenKey: {
        const compView = findCompView(view, elDef, allowPrivateServices);
        return compView.renderer;
      }

it checks only within element injector tree. And there are no other places when this token can be provided

So you have to pass Renderer2 from component to service when you're calling some service method https://github.com/angular/angular/issues/17824#issuecomment-311986129

or you can provide service within component

@Injectable()
export class Service {
  constructor(private r: Renderer2) {}
}
@Component({
  selector: 'my-app',
  templateUrl: `./app.component.html`,
  providers: [Service]
})
export class AppComponent {
  constructor(private service: Service) {}
}


问:
'Invoke-Webrequest' works fine on prompt but fails when executed through Jenkins
I am using a PowerShell script to get a dynamic file name from a web page.

When I run below code on a PowerShell prompt it returns output of the filename, e.g. abcxyz.jpeg.

```<code>((Invoke-WebRequest -Uri ‘http://myurl.x.y/abc/pqr/’).Links | Where innerHTML -like “abc*.jpeg”).href
</code>```

Then I copied the code to a Jenkins job executing PowerShell script.

Here instead of returning the filename, I see below error:

Invoke-WebRequest : The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer’s first-launch configuration is not complete....

I have tried replacing Invoke-WebRequest with wget, using -useBasicParsing, etc. Some sites recommended to open and configure Internet Explorer, which was already done,  Nevertheless I tried those too.

Jenkins Job runs with user Administrator. All other PowerShell commands such as reading a file, updating a file works fine, but I get error only in above command.

So if Invoke-WebRequest works fine from a PowerShell command prompt then why doesn't it work through a Jenkins Job? The PowerShell script was executed on the same slave machine where I'm executing the job.

I assume this is more to do with Jenkins environment, please advice.

答:
I had similar issue few days back and I resolved it by applying the proxy settings in the "Invoke-WebRequest" call.

Something like this;

```<code>Invoke-WebRequest -URI $url -Proxy 'http://10.10.7.11:80' -ProxyCredential $creds
</code>```

Body:
I am using a PowerShell script to get a dynamic file name from a web page.

When I run below code on a PowerShell prompt it returns output of the filename, e.g. abcxyz.jpeg.

((Invoke-WebRequest -Uri ‘http://myurl.x.y/abc/pqr/’).Links | Where innerHTML -like “abc*.jpeg”).href

Then I copied the code to a Jenkins job executing PowerShell script.

Here instead of returning the filename, I see below error:

Invoke-WebRequest : The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer’s first-launch configuration is not complete....

I have tried replacing Invoke-WebRequest with wget, using -useBasicParsing, etc. Some sites recommended to open and configure Internet Explorer, which was already done,  Nevertheless I tried those too.

Jenkins Job runs with user Administrator. All other PowerShell commands such as reading a file, updating a file works fine, but I get error only in above command.

So if Invoke-WebRequest works fine from a PowerShell command prompt then why doesn't it work through a Jenkins Job? The PowerShell script was executed on the same slave machine where I'm executing the job.

I assume this is more to do with Jenkins environment, please advice.

Body:
I had similar issue few days back and I resolved it by applying the proxy settings in the "Invoke-WebRequest" call.

Something like this;

Invoke-WebRequest -URI $url -Proxy 'http://10.10.7.11:80' -ProxyCredential $creds


问:
Expection in thread "main" java.lang.UnsatisfiedLinkError: JNItest2.helloworld()V
I made libcc.so from my test.cpp in ubuntu, and used the instruction ldd to check it linking no problem with opencv2.4.2, ffmpeg0.11.1, and others.

But when I tried to use eclipse to load libcc.so, I get the error:

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: JNItest2.helloworld()V
at JNItest2.helloworld(Native Method)
at JNItest2.main(JNItest2.java:28)
</code>```

Java code:

```<code>public class JNItest2 {
  public native void helloworld();
  static{
      String libPath= "/home/sun/workspace/JNItest2/src";
      System.setProperty("java.library.path",libPath);
      String Path = System.getProperty("java.library.path");
      System.out.println("java.library.path=" + Path);
      System.loadLibrary("cc");
  }
  public static void main(String[] args){
     new JNItest2().helloworld();
  }
}
</code>```

.h code:

```<code>/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JNItest2 */

#ifndef _Included_JNItest2
#define _Included_JNItest2
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     JNItest2
 * Method:    helloworld
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_JNItest2_helloworld
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif
</code>```

test.cpp

```<code>#include <jni.h>
#include "JNItest2.h"
#include <stdio.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <ctype.h>
#include <unistd.h>
#include <signal.h>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <fstream>
#include <iostream>
#include <vector>
#include <list>
#include <string>
IplImage* image = 0;
IplImage* prev_image = 0;
CvCapture* capture = 0;
JNIEXPORT void JNICALL
Java_JNItest2_helloworld(JNIEnv *env,jobject object,int argc,char ** argv)
{
    signal(SIGSEGV,sighandler);
    int frameNum = 0;
    char* video=null;
    char* video = argv[1];
    capture = cvCreateFileCapture(video);
    if( !capture ) {
        printf( "Could not initialize capturing..\n" );
        return ;
    }
    while(true)
    {
        frameNum += 1;
        IplImage* frame = 0;
        int i, j, c;

        frame = cvQueryFrame( capture );
        if( !frame )
            break;

        if( !image ) {
            image =  cvCreateImage( cvSize(frame->width,frame->height), 8, 3);
            image->origin = frame->origin;
        }

        cvCopy( frame, image, 0 );
        std::cerr << "The " << frameNum << "-th frame" << std::endl;
        frameNum++;
    }

    return;
}
</code>```

I am searching for a long time on net. But I can't solve my problem. Please help or try to give me some ideas.

答:
You have this function declared:

```<code>JNIEXPORT void JNICALL Java_JNItest2_helloworld
  (JNIEnv *, jobject);
</code>```

but you implement this one:

```<code>JNIEXPORT void JNICALL
Java_JNItest2_helloworld(JNIEnv *env,jobject object,int argc,char ** argv)
</code>```

Make sure to have:

```<code>JNIEXPORT void JNICALL
Java_JNItest2_helloworld(JNIEnv *env,jobject object)
</code>```

in your cpp code.

Body:
I made libcc.so from my test.cpp in ubuntu, and used the instruction ldd to check it linking no problem with opencv2.4.2, ffmpeg0.11.1, and others.

But when I tried to use eclipse to load libcc.so, I get the error:

Exception in thread "main" java.lang.UnsatisfiedLinkError: JNItest2.helloworld()V
at JNItest2.helloworld(Native Method)
at JNItest2.main(JNItest2.java:28)

Java code:

public class JNItest2 {
  public native void helloworld();
  static{
      String libPath= "/home/sun/workspace/JNItest2/src";
      System.setProperty("java.library.path",libPath);
      String Path = System.getProperty("java.library.path");
      System.out.println("java.library.path=" + Path);
      System.loadLibrary("cc");
  }
  public static void main(String[] args){
     new JNItest2().helloworld();
  }
}

.h code:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JNItest2 */

#ifndef _Included_JNItest2
#define _Included_JNItest2
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     JNItest2
 * Method:    helloworld
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_JNItest2_helloworld
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

test.cpp

#include <jni.h>
#include "JNItest2.h"
#include <stdio.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <ctype.h>
#include <unistd.h>
#include <signal.h>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <fstream>
#include <iostream>
#include <vector>
#include <list>
#include <string>
IplImage* image = 0;
IplImage* prev_image = 0;
CvCapture* capture = 0;
JNIEXPORT void JNICALL
Java_JNItest2_helloworld(JNIEnv *env,jobject object,int argc,char ** argv)
{
    signal(SIGSEGV,sighandler);
    int frameNum = 0;
    char* video=null;
    char* video = argv[1];
    capture = cvCreateFileCapture(video);
    if( !capture ) {
        printf( "Could not initialize capturing..\n" );
        return ;
    }
    while(true)
    {
        frameNum += 1;
        IplImage* frame = 0;
        int i, j, c;

        frame = cvQueryFrame( capture );
        if( !frame )
            break;

        if( !image ) {
            image =  cvCreateImage( cvSize(frame->width,frame->height), 8, 3);
            image->origin = frame->origin;
        }

        cvCopy( frame, image, 0 );
        std::cerr << "The " << frameNum << "-th frame" << std::endl;
        frameNum++;
    }

    return;
}

I am searching for a long time on net. But I can't solve my problem. Please help or try to give me some ideas.

Body:
You have this function declared:

JNIEXPORT void JNICALL Java_JNItest2_helloworld
  (JNIEnv *, jobject);

but you implement this one:

JNIEXPORT void JNICALL
Java_JNItest2_helloworld(JNIEnv *env,jobject object,int argc,char ** argv)

Make sure to have:

JNIEXPORT void JNICALL
Java_JNItest2_helloworld(JNIEnv *env,jobject object)

in your cpp code.


问:
Android Maps NullPointerException ItemizedOverlay
This does not refer to anywhere in my code at all.  How do I go about getting to the bottom of it?

```<code>java.lang.NullPointerException
at com.google.android.maps.OverlayBundle.draw(OverlayBundle.java:42)
at com.google.android.maps.MapView.onDraw(MapView.java:494)
at android.view.View.draw(View.java:6739)
at android.view.ViewGroup.drawChild(ViewGroup.java:1648)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1375)
at android.view.ViewGroup.drawChild(ViewGroup.java:1646)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1375)
at android.view.View.draw(View.java:6742)
at android.widget.FrameLayout.draw(FrameLayout.java:352)
at android.view.ViewGroup.drawChild(ViewGroup.java:1648)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1375)
at android.view.View.draw(View.java:6742)
at android.widget.FrameLayout.draw(FrameLayout.java:352)
at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1872)
at android.view.ViewRoot.draw(ViewRoot.java:1422)
at android.view.ViewRoot.performTraversals(ViewRoot.java:1167)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1744)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:144)
at android.app.ActivityThread.main(ActivityThread.java:4937)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
</code>```

Here is the draw method of the ItemizedOverlay

```<code>public void draw(Canvas canvas, MapView mapView, boolean shadow) {

            try {
            super.draw(canvas, mapView, false);

            if (getMainOverlayArray().size() != 0){

            pfOverlayItem tempOver = null;
            for (int i = 0; i < getMainOverlayArray().size(); i++) {

                tempOver = getMainOverlayArray().get(i);

            boolean isMatch = false;

            if (tempOver.getTitle().equals(selectedName))
            {
                isMatch = true;
            }

            if (isMatch){

            Projection projection = mapView.getProjection();
            Point point = new Point();
            projection.toPixels(tempOver.getPoint(), point);

            Paint background = new Paint();
            background.setColor(Color.WHITE);
            background.setAlpha(150);
            RectF rect = new RectF();
            rect.set(point.x - 55, point.y +15,
                    point.x + 100, point.y + 65);
            canvas.drawRoundRect(rect, 5, 5, background);

            Paint text = new Paint();
            text.setAntiAlias(true);
            text.setColor(Color.BLUE);
            text.setTextSize(14);
            text.setTypeface(Typeface.MONOSPACE);

            canvas.drawText(tempOver.getTitle() , point.x -50 , point.y + 30, text);
            canvas.drawText(tempOver.getTypeTextOut(), point.x -50 , point.y + 45, text);
            canvas.drawText(tempOver.getdestination(), point.x -50 , point.y + 60, text);
            }
            }
            }
            }catch (Exception e){
                Log.e("Error", "Problem drawing view", e);
                e.printStackTrace();
            }
        }
</code>```

I now print out the stacktrace and no difference! :-(

Does anyone have any ideas that could help get to the bottom of this?

EDIT - Latest code 28/11 FULL CLASS

```<code>    private class SitesOverlay extends ItemizedOverlay<pfOverlayItem> {
        private List<pfOverlayItem> items = new ArrayList<pfOverlayItem>();

        private PopupPanel panel=new PopupPanel(R.layout.popup);
        private MapLocation selectedMapLocation;
        private static final int CIRCLERADIUS = 2;
        private ArrayList<pfOverlayItem> mOverlays = new ArrayList<pfOverlayItem>();

        public SitesOverlay() {

            super(null);
            //super(boundCenter(defaultMarker));
            //items = getMainOverlayArray();
            //items = mOverlays;
            populate();

        }

public void finishedLoading(){

    populate();

}

        @Override
        protected pfOverlayItem createItem(int i) {
            // Log.i("CREATE","MARKER");
            return (items.get(i));

        }

        public void addItem(OverlayItem overlay) {
            overlay.setMarker(boundCenter(overlay.getMarker(0)));
            items.add((pfOverlayItem) overlay);
            //populate();
        }

        public void clearItems(){
            runOnUiThread(new Runnable() {
                public void run() {
                    items.clear();
                    myMapView.invalidate();
                }
            });

        }

        public void clear() {
            mOverlays.clear();
            myMapView.removeAllViews();
            //numItems = 0;
            // Workaround for another bug with this class:
            // http://groups.google.com/group/android-developers/browse_thread/thread/38b11314e34714c3
            setLastFocusedIndex(-1);
            populate();
        }

        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {
            super.draw(canvas, mapView, false);

            try {

            if (getMainOverlayArray().size() != 0){

            pfOverlayItem tempOver = null;
            for (int i = 0; i < getMainOverlayArray().size(); i++) {

                tempOver = getMainOverlayArray().get(i);

            boolean isMatch = false;

            //Log.i("Selected Name",selectedName);

            if (tempOver.getTitle().equals(selectedName))
            {
                isMatch = true;
            }

            if (isMatch){

            Projection projection = mapView.getProjection();
            Point point = new Point();
            projection.toPixels(tempOver.getPoint(), point);

            Paint background = new Paint();
            background.setColor(Color.WHITE);
            background.setAlpha(150);
            RectF rect = new RectF();
            rect.set(point.x - 50, point.y +15,
                    point.x + 90, point.y + 50);
            canvas.drawRoundRect(rect, 5, 5, background);

            Paint text = new Paint();
            text.setAntiAlias(true);
            text.setColor(Color.BLUE);
            text.setTextSize(14);
            text.setTypeface(Typeface.MONOSPACE);

            //canvas.drawRoundRect(rect, 2, 2, background);
            canvas.drawText(tempOver.getTitle() + " " + tempOver.getcallsign(), point.x -50 , point.y + 30, text);
            canvas.drawText(tempOver.getdestination() + " " + tempOver.getdraft(), point.x -50 , point.y + 45, text);
            }
            }
            }
            }catch (Exception e){
                Log.e("Error", "Problem drawing view", e);
                 e.printStackTrace();

            }
        }

        @Override
        protected boolean onTap(int i) {

            pfOverlayItem item = getItem(i);

            if (selectedName.equals(item.getTitle())){

                //Toast.makeText(PlaneFinderMain.this, "SECOND MOFO PRESS", 3000).show();
                try{
                Intent myIntent = new Intent(PlaneFinderMain.this, DetailActivity.class);
                myIntent.putExtra( "int", i);
                myIntent.putExtra( "string", selectedName );
                PlaneFinderMain.this.startActivity(myIntent);
                }catch (Exception e){
                    Log.e("Error", "Cannot launch", e);
                }
            }

            currentadshex = item.getmmsi();
            new GetRouteTask(item.getmmsi()).execute();

            selectedItem = i;
            selectedName = item.getTitle();
            selectedPlanePoint = item.getPoint();

            GeoPoint geo=item.getPoint();
            Point pt=myMapView.getProjection().toPixels(geo, null);

            View view=panel.getView();

            ((TextView)view.findViewById(R.id.reg)).setText(item.getTitle());
            ((TextView)view.findViewById(R.id.flightno)).setText(item.getcallsign());
            ((TextView)view.findViewById(R.id.route)).setText(item.getdestination());
            ((TextView)view.findViewById(R.id.height)).setText(item.getdraft());

            return (true);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event, MapView mapView) {

             if (event.getAction() == MotionEvent.ACTION_DOWN){

                 if (selectedPlanePoint != null){
                     Projection projection = mapView.getProjection();
                     Point point = new Point();
                     projection.toPixels(selectedPlanePoint, point);

                     Point pointHit = new Point();
                     pointHit.x=(int)event.getX();
                     pointHit.y=(int)event.getY();

                     if ((point.x - pointHit.x) >-100 && (point.x - pointHit.x) <70  && (point.y - pointHit.y) < -25  && (point.y - pointHit.y) > -95){

                            try{
                                 Intent myIntent = new Intent(PlaneFinderMain.this, DetailActivity.class);

                                    myIntent.putExtra( "int", selectedItem);
                                    myIntent.putExtra( "string", selectedName );
                                    PlaneFinderMain.this.startActivity(myIntent);

                                }catch (Exception e){
                                    Log.e("Error", "Cannot launch", e);
                                }

                     }else{

                     }

                 }

             }

            return false;

        }

        @Override
        public int size() {
            return (items.size());
        }

        public void addOverlay(OverlayItem o){
            setLastFocusedIndex(-1);
            populate();
        }

    }
</code>```

答:
Actually the problem is not in the implementation of your ItemizedOverlay, but in the implementation of your MapActivity. As you can see from a similar stack trace here at line 42 the OverlayBundle is calling the draw() method of an Overlay. This points to a null Overlay that you added to your mapView somewhere.

Some helpful hints:
You should definitely pass a drawable to your super constructor (used of hit-testing) by uncommenting the first line of code you already have in there:

```<code>     public SitesOverlay() {

        //super(null);
        super(boundCenter(defaultMarker));
        //items = getMainOverlayArray();
        //items = mOverlays;
        populate();

    }
</code>```

and potentially not call super.draw() in your draw() method.

```<code>    @Override
    public void draw(Canvas canvas, MapView mapView, boolean shadow) {
        // why do you do this if you paint it yourself later on.
        super.draw(canvas, mapView, false
</code>```

Most likely you will have to actually do both.

Edit: Come to think of it you should definitely pass a drawable to your super constructor as it is used for hit-testing. Amended the text above to reflect that.

ContentLicense: CC BY-SA 2.5

Body:
This does not refer to anywhere in my code at all.  How do I go about getting to the bottom of it?

java.lang.NullPointerException
at com.google.android.maps.OverlayBundle.draw(OverlayBundle.java:42)
at com.google.android.maps.MapView.onDraw(MapView.java:494)
at android.view.View.draw(View.java:6739)
at android.view.ViewGroup.drawChild(ViewGroup.java:1648)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1375)
at android.view.ViewGroup.drawChild(ViewGroup.java:1646)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1375)
at android.view.View.draw(View.java:6742)
at android.widget.FrameLayout.draw(FrameLayout.java:352)
at android.view.ViewGroup.drawChild(ViewGroup.java:1648)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1375)
at android.view.View.draw(View.java:6742)
at android.widget.FrameLayout.draw(FrameLayout.java:352)
at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1872)
at android.view.ViewRoot.draw(ViewRoot.java:1422)
at android.view.ViewRoot.performTraversals(ViewRoot.java:1167)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1744)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:144)
at android.app.ActivityThread.main(ActivityThread.java:4937)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)

Here is the draw method of the ItemizedOverlay

public void draw(Canvas canvas, MapView mapView, boolean shadow) {

            try {
            super.draw(canvas, mapView, false);

            if (getMainOverlayArray().size() != 0){

            pfOverlayItem tempOver = null;
            for (int i = 0; i < getMainOverlayArray().size(); i++) {

                tempOver = getMainOverlayArray().get(i);

            boolean isMatch = false;

            if (tempOver.getTitle().equals(selectedName))
            {
                isMatch = true;
            }

            if (isMatch){

            Projection projection = mapView.getProjection();
            Point point = new Point();
            projection.toPixels(tempOver.getPoint(), point);

            Paint background = new Paint();
            background.setColor(Color.WHITE);
            background.setAlpha(150);
            RectF rect = new RectF();
            rect.set(point.x - 55, point.y +15,
                    point.x + 100, point.y + 65);
            canvas.drawRoundRect(rect, 5, 5, background);

            Paint text = new Paint();
            text.setAntiAlias(true);
            text.setColor(Color.BLUE);
            text.setTextSize(14);
            text.setTypeface(Typeface.MONOSPACE);

            canvas.drawText(tempOver.getTitle() , point.x -50 , point.y + 30, text);
            canvas.drawText(tempOver.getTypeTextOut(), point.x -50 , point.y + 45, text);
            canvas.drawText(tempOver.getdestination(), point.x -50 , point.y + 60, text);
            }
            }
            }
            }catch (Exception e){
                Log.e("Error", "Problem drawing view", e);
                e.printStackTrace();
            }
        }

I now print out the stacktrace and no difference! :-(

Does anyone have any ideas that could help get to the bottom of this?

EDIT - Latest code 28/11 FULL CLASS

    private class SitesOverlay extends ItemizedOverlay<pfOverlayItem> {
        private List<pfOverlayItem> items = new ArrayList<pfOverlayItem>();

        private PopupPanel panel=new PopupPanel(R.layout.popup);
        private MapLocation selectedMapLocation;
        private static final int CIRCLERADIUS = 2;
        private ArrayList<pfOverlayItem> mOverlays = new ArrayList<pfOverlayItem>();

        public SitesOverlay() {

            super(null);
            //super(boundCenter(defaultMarker));
            //items = getMainOverlayArray();
            //items = mOverlays;
            populate();

        }

public void finishedLoading(){

    populate();

}

        @Override
        protected pfOverlayItem createItem(int i) {
            // Log.i("CREATE","MARKER");
            return (items.get(i));

        }

        public void addItem(OverlayItem overlay) {
            overlay.setMarker(boundCenter(overlay.getMarker(0)));
            items.add((pfOverlayItem) overlay);
            //populate();
        }

        public void clearItems(){
            runOnUiThread(new Runnable() {
                public void run() {
                    items.clear();
                    myMapView.invalidate();
                }
            });

        }

        public void clear() {
            mOverlays.clear();
            myMapView.removeAllViews();
            //numItems = 0;
            // Workaround for another bug with this class:
            // http://groups.google.com/group/android-developers/browse_thread/thread/38b11314e34714c3
            setLastFocusedIndex(-1);
            populate();
        }

        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {
            super.draw(canvas, mapView, false);

            try {

            if (getMainOverlayArray().size() != 0){

            pfOverlayItem tempOver = null;
            for (int i = 0; i < getMainOverlayArray().size(); i++) {

                tempOver = getMainOverlayArray().get(i);

            boolean isMatch = false;

            //Log.i("Selected Name",selectedName);

            if (tempOver.getTitle().equals(selectedName))
            {
                isMatch = true;
            }

            if (isMatch){

            Projection projection = mapView.getProjection();
            Point point = new Point();
            projection.toPixels(tempOver.getPoint(), point);

            Paint background = new Paint();
            background.setColor(Color.WHITE);
            background.setAlpha(150);
            RectF rect = new RectF();
            rect.set(point.x - 50, point.y +15,
                    point.x + 90, point.y + 50);
            canvas.drawRoundRect(rect, 5, 5, background);

            Paint text = new Paint();
            text.setAntiAlias(true);
            text.setColor(Color.BLUE);
            text.setTextSize(14);
            text.setTypeface(Typeface.MONOSPACE);

            //canvas.drawRoundRect(rect, 2, 2, background);
            canvas.drawText(tempOver.getTitle() + " " + tempOver.getcallsign(), point.x -50 , point.y + 30, text);
            canvas.drawText(tempOver.getdestination() + " " + tempOver.getdraft(), point.x -50 , point.y + 45, text);
            }
            }
            }
            }catch (Exception e){
                Log.e("Error", "Problem drawing view", e);
                 e.printStackTrace();

            }
        }

        @Override
        protected boolean onTap(int i) {

            pfOverlayItem item = getItem(i);

            if (selectedName.equals(item.getTitle())){

                //Toast.makeText(PlaneFinderMain.this, "SECOND MOFO PRESS", 3000).show();
                try{
                Intent myIntent = new Intent(PlaneFinderMain.this, DetailActivity.class);
                myIntent.putExtra( "int", i);
                myIntent.putExtra( "string", selectedName );
                PlaneFinderMain.this.startActivity(myIntent);
                }catch (Exception e){
                    Log.e("Error", "Cannot launch", e);
                }
            }

            currentadshex = item.getmmsi();
            new GetRouteTask(item.getmmsi()).execute();

            selectedItem = i;
            selectedName = item.getTitle();
            selectedPlanePoint = item.getPoint();

            GeoPoint geo=item.getPoint();
            Point pt=myMapView.getProjection().toPixels(geo, null);

            View view=panel.getView();

            ((TextView)view.findViewById(R.id.reg)).setText(item.getTitle());
            ((TextView)view.findViewById(R.id.flightno)).setText(item.getcallsign());
            ((TextView)view.findViewById(R.id.route)).setText(item.getdestination());
            ((TextView)view.findViewById(R.id.height)).setText(item.getdraft());

            return (true);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event, MapView mapView) {

             if (event.getAction() == MotionEvent.ACTION_DOWN){

                 if (selectedPlanePoint != null){
                     Projection projection = mapView.getProjection();
                     Point point = new Point();
                     projection.toPixels(selectedPlanePoint, point);

                     Point pointHit = new Point();
                     pointHit.x=(int)event.getX();
                     pointHit.y=(int)event.getY();

                     if ((point.x - pointHit.x) >-100 && (point.x - pointHit.x) <70  && (point.y - pointHit.y) < -25  && (point.y - pointHit.y) > -95){

                            try{
                                 Intent myIntent = new Intent(PlaneFinderMain.this, DetailActivity.class);

                                    myIntent.putExtra( "int", selectedItem);
                                    myIntent.putExtra( "string", selectedName );
                                    PlaneFinderMain.this.startActivity(myIntent);

                                }catch (Exception e){
                                    Log.e("Error", "Cannot launch", e);
                                }

                     }else{

                     }

                 }

             }

            return false;

        }

        @Override
        public int size() {
            return (items.size());
        }

        public void addOverlay(OverlayItem o){
            setLastFocusedIndex(-1);
            populate();
        }

    }

Body:
Actually the problem is not in the implementation of your ItemizedOverlay, but in the implementation of your MapActivity. As you can see from a similar stack trace here at line 42 the OverlayBundle is calling the draw() method of an Overlay. This points to a null Overlay that you added to your mapView somewhere.

Some helpful hints:
You should definitely pass a drawable to your super constructor (used of hit-testing) by uncommenting the first line of code you already have in there:

     public SitesOverlay() {

        //super(null);
        super(boundCenter(defaultMarker));
        //items = getMainOverlayArray();
        //items = mOverlays;
        populate();

    }

and potentially not call super.draw() in your draw() method.

    @Override
    public void draw(Canvas canvas, MapView mapView, boolean shadow) {
        // why do you do this if you paint it yourself later on.
        super.draw(canvas, mapView, false

Most likely you will have to actually do both.

Edit: Come to think of it you should definitely pass a drawable to your super constructor as it is used for hit-testing. Amended the text above to reflect that.


问:
CodeIgniter URL Query String Manipulation
I have a E-Commerce Website build using CodeIgniter 2.3.

Please suggest how can I manipulate the URLs in the given sequence:-

Say a Person Searches for "Mobile Phones".
URL must be xyz.com/search/mobile-phone, which displays all the Mobile Phones from our Database.
I am already aware of the Search controller and use Routing to exclude the function name from the URL

Next the Person uses filtering by name of Mobile Phone Companies. Suppose he chooses "Apple". The URL must become xyz.com/search/mobile-phones/apple

Next the Person again filters by Condition ie "New" or "Refurbished". The URL must become xyz.com/search/mobile-phones/apples/new

The URLs need to be Functional URLs so that, if I pass the URL xyz.com/search/mobile-phones/apples/new to someone externally, he/she should be able to see the same result set as the person who came after Search & Filtering.

I am non-technical so may be I couldnt explain my problem very technically, but be assured, my Tech Person would be reading your suggestions.

Further Details

We are already using URI Segmentation, Routing & Post Method. But that way we are facing issues wrt Point #4 mentioned above

答:
I am going to do this answer with script, from client side.

1. Say a Person Searches for "Mobile Phones". URL must be xyz.com/search/mobile-phone, which displays all the Mobile Phones from our Database. I am already aware of the Search controller and use Routing to exclude the function name from the URL

simply get the input value and pass it to script.

```<code><script>

$('#search').keyup(function (e) {

if(e.keyCode==13)
{
    var search=$('#search').val();

    window.location.href = 'xyz.com/search/'+search;
}
});

</script>
</code>```

2. Next the Person uses filtering by name of Mobile Phone Companies. Suppose he chooses "Apple". The URL must become xyz.com/search/mobile-phones/apple

when the person clicks apple, you are going to write.

onclick="javascript:window.location.href='xyz.com/search/<?php echo $this->uri->segment(3).'/Apple'; ?>';"

3. Next the Person again filters by Condition ie "New" or "Refurbished". The URL must become xyz.com/search/mobile-phones/apples/new

assuming selection box for new or refurbished.

```<code>$('#select').change(function(e) {

        var select=$('#select').val();

        window.location.href = 'xyz.com/search/<?php echo $this->uri->segment(3)."/".$this->uri->segment(4); ?>'+select;

 });
</code>```

4. The URLs need to be Functional URLs so that, if I pass the URL xyz.com/search/mobile-phones/apples/new to someone externally, he/she should be able to see the same result set as the person who came after Search & Filtering.

and in controller, you can get the values with the uri segment.

```<code>$this->uri->segment(3)
$this->uri->segment(4)
$this->uri->segment(5)
</code>```

and make the query a your wish and return the result.

the above url works for all, if you make the query result with the parameters.

i have not write any validation, so make the validations and pass it to the url whether user input is empty or not.

Hope this helps :)

Body:
I am going to do this answer with script, from client side.

1. Say a Person Searches for "Mobile Phones". URL must be xyz.com/search/mobile-phone, which displays all the Mobile Phones from our Database. I am already aware of the Search controller and use Routing to exclude the function name from the URL

simply get the input value and pass it to script.

<script>

$('#search').keyup(function (e) {

if(e.keyCode==13)
{
    var search=$('#search').val();

    window.location.href = 'xyz.com/search/'+search;
}
});

</script>

2. Next the Person uses filtering by name of Mobile Phone Companies. Suppose he chooses "Apple". The URL must become xyz.com/search/mobile-phones/apple

when the person clicks apple, you are going to write.

onclick="javascript:window.location.href='xyz.com/search/<?php echo $this->uri->segment(3).'/Apple'; ?>';"

3. Next the Person again filters by Condition ie "New" or "Refurbished". The URL must become xyz.com/search/mobile-phones/apples/new

assuming selection box for new or refurbished.

$('#select').change(function(e) {

        var select=$('#select').val();

        window.location.href = 'xyz.com/search/<?php echo $this->uri->segment(3)."/".$this->uri->segment(4); ?>'+select;

 });

4. The URLs need to be Functional URLs so that, if I pass the URL xyz.com/search/mobile-phones/apples/new to someone externally, he/she should be able to see the same result set as the person who came after Search & Filtering.

and in controller, you can get the values with the uri segment.

$this->uri->segment(3)
$this->uri->segment(4)
$this->uri->segment(5)

and make the query a your wish and return the result.

the above url works for all, if you make the query result with the parameters.

i have not write any validation, so make the validations and pass it to the url whether user input is empty or not.

Hope this helps :)


答:
I would count the number of records in a subquery that matches the original where criteria and if that count is 3, then do the selection only:

```<code>SELECT * FROM sku
WHERE sellerID = 1
    AND id IN (3,4,10)
    AND 3 = (SELECT count(*) FROM sku WHERE sellerID = 1 AND id IN (3,4,10));
</code>```

Title: 'AND' condition for (id array) in mysql

Body:
I have an mysql table like this.

+----+----------+----------+---------------------------------------------------------------------------+------+---------------------+
| id | sku      | sellerID | name                                                                      | mode | created             |
+----+----------+----------+---------------------------------------------------------------------------+------+---------------------+
|  1 | Sample   |        1 | SampleItem                                                                |    1 | 2016-05-20 12:04:33 |
|  2 | Sample   |        2 | Sample1                                                                   |    1 | 2016-06-14 12:23:24 |
|  3 | SDGS046  |        1 | Shivaprasad                                                               |    2 | 2016-06-18 05:26:27 |
|  4 | PAWA006  |        1 | Panda Baby Walker Music                                                   |    2 | 2016-06-18 06:19:10 |
|  5 | PAWA005  |        1 | WonderKart Panda Walker for Kids (colour may vary)                        |    2 | 2016-06-18 06:24:23 |
|  6 | WKBR1301 |        1 | Planet of Toys New Born Toddler Protable Rocker                           |    2 | 2016-06-18 06:26:30 |
|  7 | PAKS001  |        1 | Panda Baby Musical Swing With Multiple Age Settings | 4 Stages | (Orange) |    2 | 2016-06-18 06:28:19 |
|  8 | WKGS046  |        1 | The Flyers Bay Flyer's Bay Ultra Durable Big Wheel Scooter (Silver)       |    2 | 2016-06-18 06:57:25 |
|  9 | MABS001  |        1 | Mastela Booster to Toddler 6M+ Seat (DarkGray)                            |    2 | 2016-06-20 06:25:00 |
| 10 | WKGS546  |        1 | Saffire Kids Scooter with Tractor Wheels Green                            |    2 | 2016-06-20 06:26:50 |
+----+----------+----------+---------------------------------------------------------------------------+------+---------------------+

I want get data by query like.

SELECT * FROM `sku` WHERE `sellerID` = 1 AND id = 3 AND id = 4 AND id = 10;

but m trying this like

SELECT * FROM sku WHERE sellerID = 1 AND id IN (3,4,10);

it returns rows, if id(3,4,10) any available in table, but i want return row, if every id(3 and 4 and 10) available in table.

I want to pass an array to check AND Condition. Please suggest me if there is any solution available.

Body:
I would count the number of records in a subquery that matches the original where criteria and if that count is 3, then do the selection only:

SELECT * FROM sku
WHERE sellerID = 1
    AND id IN (3,4,10)
    AND 3 = (SELECT count(*) FROM sku WHERE sellerID = 1 AND id IN (3,4,10));


问:
How can realize border radius like egg
Can I realize this style of image with css3?

I have set this style of border in

```<code>.image img {border-radius: 40% 60% 60% 40%/50%; }
</code>```

, but I think that isn't right one.

答:
I will give you a little code for egg . It is created by border-radius

#egg {
       display:block;
       width: 126px;
       height: 180px;
       background-color: red;
       -webkit-border-radius: 63px 63px 63px 63px / 108px 108px 72px 72px;
       border-radius:         50%  50%  50%  50%  / 60%   60%   40%  40%;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="egg"></div></code>```

Title: How can realize border radius like egg

Body:
Can I realize this style of image with css3?

I have set this style of border in

.image img {border-radius: 40% 60% 60% 40%/50%; }

, but I think that isn't right one.

Body:
I will give you a little code for egg . It is created by border-radius

#egg {
       display:block;
       width: 126px;
       height: 180px;
       background-color: red;
       -webkit-border-radius: 63px 63px 63px 63px / 108px 108px 72px 72px;
       border-radius:         50%  50%  50%  50%  / 60%   60%   40%  40%;
    }

<div id="egg"></div>


问:
Hide element based on attribute value jquery
How can I hide child div based on the attribute value of parent div. I have following markup:

```<code><div class="offerContainer">
    <div class="Offers" producttype="CIP">
        <div class="buttons_wrap"></div>
    </div>
    <div class="Offers" producttype="P">
        <div class="buttons_wrap"></div>
    </div>
    <div class="Offers" producttype="CIP">
        <div class="buttons_wrap"></div>
    </div>
</div>
</code>```

And I want to hide buttons_wrap only when  atrribute value of producttype is "CIP".

Something like:

```<code>if($(obj).parents(".offersContainer").find('.Offers').attr('producttype').value == "CIP")
    $('.buttons_wrap').hide();
</code>```

答:
Try This custom method

$(function() {
var $offers = $('.Offers');
$offers.each(function() {
var productType = $(this).attr('producttype');
if(productType != "CIP")
{
   $(this).children().hide();
}
});
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="offerContainer">
    <div class="Offers" producttype="CIP">
        <div class="buttons_wrap"><button>First</button></div>
    </div>
    <div class="Offers" producttype="P">
        <div class="buttons_wrap"><button>Second</button></div>
    </div>
    <div class="Offers" producttype="CIP">
        <div class="buttons_wrap"><button>Third</button></div>
    </div>
</div></code>```

Body:
How can I hide child div based on the attribute value of parent div. I have following markup:

And I want to hide buttons_wrap only when  atrribute value of producttype is "CIP".

Something like:

if($(obj).parents(".offersContainer").find('.Offers').attr('producttype').value == "CIP")
    $('.buttons_wrap').hide();

Body:
Try This custom method

$(function() {
var $offers = $('.Offers');
$offers.each(function() {
var productType = $(this).attr('producttype');
if(productType != "CIP")
{
   $(this).children().hide();
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="offerContainer">
    <div class="Offers" producttype="CIP">
        <div class="buttons_wrap"><button>First</button></div>
    </div>
    <div class="Offers" producttype="P">
        <div class="buttons_wrap"><button>Second</button></div>
    </div>
    <div class="Offers" producttype="CIP">
        <div class="buttons_wrap"><button>Third</button></div>
    </div>
</div>


问:
Error : No provider for ValidateService
I'm using @angular/cli . to validate the form I used validate service by creating a folder called services and then ran ng g service validate.
two files created and inside validate.service, I wrote some validation functions. then I imported it to my another file and created an instance inside the constructor to call it using this key word like below.

```<code> constructor(private vd : ValidateService) { }
</code>```

then I check with ng serve. so it give the following error

```<code>ERROR Error: Uncaught (in promise): Error: No provider for ValidateService!
</code>```

some says, this bundle are broken, it will fix soon and instead of it use dev bundle. what is this. I have no idea

答:
Use Provider in app.module.ts file like</p>

```<code>@NgModule({
    imports: [],
 providers: [ValidateService]
})
</code>```

Title: Error : No provider for ValidateService

Body:
I'm using @angular/cli . to validate the form I used validate service by creating a folder called services and then ran ng g service validate.
two files created and inside validate.service, I wrote some validation functions. then I imported it to my another file and created an instance inside the constructor to call it using this key word like below.

 constructor(private vd : ValidateService) { }

then I check with ng serve. so it give the following error

ERROR Error: Uncaught (in promise): Error: No provider for ValidateService!

some says, this bundle are broken, it will fix soon and instead of it use dev bundle. what is this. I have no idea

Body:
Use Provider in app.module.ts file like

@NgModule({
    imports: [],
 providers: [ValidateService]
})


问:
I want only all cities of "INDIA" to show through ngAutocomplete..??? which changes I have to make in ngAutocomplete..?
I just want to give all cities of India in options through ngAutocomplete.js...well below code of ngAutocomplete.js           </p>

```<code>    var opts;
    var initOpts = function() {
      opts = {}
      if (scope.options) {
        if (scope.options.types) {
          opts.types = []
          opts.types.push(scope.options.types)
        }
        if (scope.options.bounds) {
          opts.bounds = scope.options.bounds
        }
        if (scope.options.country) {
          opts.componentRestrictions = {
            country: 'IN'
          }
        }
      }
    }
</code>```

答:
```<code>            $scope.getOnlyINDIA = {
                      country: 'in',
                      types: '(cities)'
                       };
</code>```

add this into controller then on auto-complete textbox add...

```<code>           options="getOnlyINDIA"
</code>```

Body:
I just want to give all cities of India in options through ngAutocomplete.js...well below code of ngAutocomplete.js

    var opts;
    var initOpts = function() {
      opts = {}
      if (scope.options) {
        if (scope.options.types) {
          opts.types = []
          opts.types.push(scope.options.types)
        }
        if (scope.options.bounds) {
          opts.bounds = scope.options.bounds
        }
        if (scope.options.country) {
          opts.componentRestrictions = {
            country: 'IN'
          }
        }
      }
    }

Body:
            $scope.getOnlyINDIA = {
                      country: 'in',
                      types: '(cities)'
                       };

add this into controller then on auto-complete textbox add...

           options="getOnlyINDIA"


问:
Prolog why the following term doesn't unify?
In prolog = is used for unification, as far as I understand if the two terms can be matched maybe with the help if variable instantiation, they are unified.

So why the following query fails

```<code>?- 2+2 = 4.
</code>```

Although 2+2 yields into 4 which is the same number as the other term.

答:
The expression on the left-hand side is not evaluated by itself. You are instead comparing the unification of strings. To compare the unification of the expression's evaluation with the right-hand side, you need to use the is/2 operator.

```<code>?- 4 is 2+2.
</code>```

Compare with:

```<code>?- 2+2 = 2+2.
</code>```

and

```<code>?- X is 2+2.
</code>```

Body:
In prolog = is used for unification, as far as I understand if the two terms can be matched maybe with the help if variable instantiation, they are unified.

So why the following query fails

?- 2+2 = 4.

Although 2+2 yields into 4 which is the same number as the other term.

Body:
The expression on the left-hand side is not evaluated by itself. You are instead comparing the unification of strings. To compare the unification of the expression's evaluation with the right-hand side, you need to use the is/2 operator.

?- 4 is 2+2.

Compare with:

?- 2+2 = 2+2.

and

?- X is 2+2.


问:
Python Skips Numbers
I'm writing a program that's supposed to determine the square root of a number by brute force. However, certain numbers(same every time).

Here is the code:

```<code>toCalc = 3

guess = toCalc
toCalc = round(toCalc, 2)
while 1+1==2:

        print "Trying ", guess, "..."
        calc = guess * guess
        calc = round(calc, 2)
        print calc
        guess = guess - 0.01
        if calc == toCalc:
                break
</code>```

And here is the output:

```<code>Trying  1.22 ...
1.49
Trying  1.21 ...
1.46
Trying  1.2 ...
1.44
Trying  1.19 ...
1.42
Trying  1.18 ...
1.39
Trying  1.17 ...
1.37
Trying  1.16 ...
1.35
Trying  1.15 ...
1.32
Trying  1.14 ...
1.3
Trying  1.13 ...
1.28
Trying  1.12 ...
1.25
Trying  1.11 ...
1.23
Trying  1.1 ...
1.21
Trying  1.09 ...
1.19
Trying  1.08 ...
1.17
Trying  1.07 ...
1.14
Trying  1.06 ...
1.12
Trying  1.05 ...
1.1
Trying  1.04 ...
1.08
Trying  1.03 ...
1.06
Trying  1.02 ...
1.04
Trying  1.01 ...
1.02
Trying  1.0 ...
1.0
Trying  0.99 ...
0.98
Trying  0.98 ...
0.96
Trying  0.97 ...
0.94
Trying  0.96 ...
0.92
Trying  0.95 ...
0.9
Trying  0.94 ...
0.88
Trying  0.93 ...
0.86
Trying  0.92 ...
0.85
Trying  0.91 ...
0.83
</code>```

The number under "Trying" is calc and the number after "Trying" is guess.

答:
When you take the next guess which is old guess - 0.01, and square that, the next square is approximately old square - 0.02 (using a binomic formula). This means the step in the guess squared column is about 0.02 and thus numbers are missing.

Is that what you meant?

A better algorithm might be to use bisection (google it).

Title: Python Skips Numbers

Body:
I'm writing a program that's supposed to determine the square root of a number by brute force. However, certain numbers(same every time).

Here is the code:

toCalc = 3

guess = toCalc
toCalc = round(toCalc, 2)
while 1+1==2:

        print "Trying ", guess, "..."
        calc = guess * guess
        calc = round(calc, 2)
        print calc
        guess = guess - 0.01
        if calc == toCalc:
                break

And here is the output:

Trying  1.22 ...
1.49
Trying  1.21 ...
1.46
Trying  1.2 ...
1.44
Trying  1.19 ...
1.42
Trying  1.18 ...
1.39
Trying  1.17 ...
1.37
Trying  1.16 ...
1.35
Trying  1.15 ...
1.32
Trying  1.14 ...
1.3
Trying  1.13 ...
1.28
Trying  1.12 ...
1.25
Trying  1.11 ...
1.23
Trying  1.1 ...
1.21
Trying  1.09 ...
1.19
Trying  1.08 ...
1.17
Trying  1.07 ...
1.14
Trying  1.06 ...
1.12
Trying  1.05 ...
1.1
Trying  1.04 ...
1.08
Trying  1.03 ...
1.06
Trying  1.02 ...
1.04
Trying  1.01 ...
1.02
Trying  1.0 ...
1.0
Trying  0.99 ...
0.98
Trying  0.98 ...
0.96
Trying  0.97 ...
0.94
Trying  0.96 ...
0.92
Trying  0.95 ...
0.9
Trying  0.94 ...
0.88
Trying  0.93 ...
0.86
Trying  0.92 ...
0.85
Trying  0.91 ...
0.83

The number under "Trying" is calc and the number after "Trying" is guess.


问:
how to remove characters using treplace
I have pulled in a JSON using the tRest stage, and some of my values appear like this: ["345"].  I need to convert this to a integer: 345.  I know I need to remove the extra characters, but I'm having the worst luck using EReplace and Integer in a tmap.  I was recommended to use tReplace.  Can someone please show me how to set it so I can remove the brackets and quotes?

Just for the record, here is the line that I tried in tMap:

```<code>Integer.parseInt(StringHandling.EREPLACE(StringHandling.EREPLACE(StringHandling.EREPLACE(row2.rank,"[",""),"]",""),"\"",""))
</code>```

Thanks.

答:
Instead of using treplace component, use the code like below in tMap component

```<code>Integer.parseInt(row2.rank.replaceAll("\"","").replaceAll("\\[","").replaceAll("\\]",""));
</code>```

The above will give you the expected result

Hope this would help you out.

Title: how to remove characters using treplace

Body:
I have pulled in a JSON using the tRest stage, and some of my values appear like this: ["345"].  I need to convert this to a integer: 345.  I know I need to remove the extra characters, but I'm having the worst luck using EReplace and Integer in a tmap.  I was recommended to use tReplace.  Can someone please show me how to set it so I can remove the brackets and quotes?

Just for the record, here is the line that I tried in tMap:

Integer.parseInt(StringHandling.EREPLACE(StringHandling.EREPLACE(StringHandling.EREPLACE(row2.rank,"[",""),"]",""),"\"",""))

Thanks.

Body:
Instead of using treplace component, use the code like below in tMap component

Integer.parseInt(row2.rank.replaceAll("\"","").replaceAll("\\[","").replaceAll("\\]",""));

The above will give you the expected result

Hope this would help you out.


问:
SonarQube 6.3 LDAP/SSO UTF-8 encoding
We‘re using LDAP/SSO in my company which provides the username in UTF-8 format to SonarQube.

However LDAP/SSO sends the username in UFT-8 but SonarQube requires Latin1/ISO-8859. There is no way to change the encoding on LDAP/SSO or SonarQube.

Result wrong umlauts:

Andrü Tingö = Andr«Ã Ting¼Ã OR äëüö = Ã¤Ã«Ã¼Ã

Is there any workaround?

答:
I wanted to post this as comment, but I need 50 reputations to write comments.

We are using simplesamlphp for SSO as IdP and SP. IdP takes cn, givenName and sn from LDAP, which has UTF-8 values. Loginnames/Usernames are us-ascii only.

If the user comes to Sonar, the non-us-ascii characters are incorrect - they were converted from ... to utf-8, even they already are in utf-8.

If I use the attributes from IDP in PHP which sends the page in UTF-8, then characters are correct.

I did just now one test. In our Apache Config we set the X-Forwarded-Name to MCAC_ATTR_CN attribute what SP get from IdP. Original configuration is:

```<code>RequestHeader set X-Forwarded-Name "expr=%{reqenv:MCAC_ATTR_CN}"
</code>```

Now I have added fixed string in UTF-8:

```<code>RequestHeader set X-Forwarded-Name "expr=%{reqenv:MCAC_ATTR_CN} cäëöüc"
</code>```

The "c" characters are only separators to see the encoded text better.

The hexdump of this configuration line is:

```<code>0000750:        09 0909 5265 7175 6573 7448 6561     ...RequestHea
0000760: 6465 7220 7365 7420 582d 466f 7277 6172  der set X-Forwar
0000770: 6465 642d 4e61 6d65 2022 6578 7072 3d25  ded-Name "expr=%
0000780: 7b72 6571 656e 763a 4d43 4143 5f41 5454  {reqenv:MCAC_ATT
0000790: 525f 434e 7d20 63c3 a4c3 abc3 b6c3 bc63  R_CN} c........c
00007a0: 220a                                     ".
</code>```

As you can see, there are fixed utf-8 characters "ä" c3a4 "ë" c3ab "ö" c3b6 "ü" c3bc.

From LDAP comes follwing name:

```<code>xxxxxx xxxxx xxxx äëüö
</code>```

In Apache config is appended " cäëöüc", therefore resulting name should be:

```<code>xxxxxx xxxxx xxxx äëüö cäëöüc
</code>```

But in Sonar, the name is displayed as

```<code>xxxxxx xxxxx xxxx Ã¤Ã«Ã¼Ã¶ cÃ¤Ã«Ã¶Ã¼c
</code>```

You get similar result if you convert follwing text:

```<code>xxxxxx xxxxx xxxx äëüö cäëöüc
</code>```

from ISO-8859-1 to UTF-8:

```<code>echo "xxxxxx xxxxx xxxx äëüö cäëöüc" | iconv -f iso-8859-2 -t utf-8
xxxxxx xxxxx xxxx Ă¤ĂŤĂźĂś cĂ¤ĂŤĂśĂźc
</code>```

The "¤" character is utf-8 char c2 a4:

```<code>00000000: c2a4 0a                                  ...
</code>```

I have made tcpdump on loopback to get communications from apache proxy module to sonarqube and even there you can see correct UTF-8 characters c3a4 c3ab c3bc c3b6 comming from IdP and then between "c"s you can see c3a4 c3ab c3b6 c3bc comming direct from apache.

```<code>00000000  47 45 54 20 2f 61 63 63  6f 75 6e 74 20 48 54 54   GET /acc ount HTT
...
00000390  58 2d 46 6f 72 77 61 72  64 65 64 2d 4e 61 6d 65   X-Forwar ded-Name
000003A0  3a 20 72 6f 62 65 72 74  20 74 65 73 74 32 20 77   : xxxxxx  xxxxx x
000003B0  6f 6c 66 20 c3 a4 c3 ab  c3 bc c3 b6 20 63 c3 a4   xxx .... .... c..
000003C0  c3 ab c3 b6 c3 bc 63 0d  0a                        ......c. .
...
</code>```

The system has locales set to en_US.UTF-8, if this matters.

So Sonar gets really UTF-8 Text from Apache (direct config or from IdP) but then something probably converts this utf-8 text as if it was iso-8859 text to utf-8 again and makes nonsense.

Do you have any idea now? Could this be something in sonar or in wrapper or somewhere some options set incorrectly?

Regards,

Robert.

Title: SonarQube 6.3 LDAP/SSO UTF-8 encoding

Body:
I wanted to post this as comment, but I need 50 reputations to write comments.

We are using simplesamlphp for SSO as IdP and SP. IdP takes cn, givenName and sn from LDAP, which has UTF-8 values. Loginnames/Usernames are us-ascii only.

If the user comes to Sonar, the non-us-ascii characters are incorrect - they were converted from ... to utf-8, even they already are in utf-8.

If I use the attributes from IDP in PHP which sends the page in UTF-8, then characters are correct.

I did just now one test. In our Apache Config we set the X-Forwarded-Name to MCAC_ATTR_CN attribute what SP get from IdP. Original configuration is:

RequestHeader set X-Forwarded-Name "expr=%{reqenv:MCAC_ATTR_CN}"

Now I have added fixed string in UTF-8:

RequestHeader set X-Forwarded-Name "expr=%{reqenv:MCAC_ATTR_CN} cäëöüc"

The "c" characters are only separators to see the encoded text better.

The hexdump of this configuration line is:

0000750:        09 0909 5265 7175 6573 7448 6561     ...RequestHea
0000760: 6465 7220 7365 7420 582d 466f 7277 6172  der set X-Forwar
0000770: 6465 642d 4e61 6d65 2022 6578 7072 3d25  ded-Name "expr=%
0000780: 7b72 6571 656e 763a 4d43 4143 5f41 5454  {reqenv:MCAC_ATT
0000790: 525f 434e 7d20 63c3 a4c3 abc3 b6c3 bc63  R_CN} c........c
00007a0: 220a                                     ".

As you can see, there are fixed utf-8 characters "ä" c3a4 "ë" c3ab "ö" c3b6 "ü" c3bc.

From LDAP comes follwing name:

xxxxxx xxxxx xxxx äëüö

In Apache config is appended " cäëöüc", therefore resulting name should be:

xxxxxx xxxxx xxxx äëüö cäëöüc

But in Sonar, the name is displayed as

xxxxxx xxxxx xxxx Ã¤Ã«Ã¼Ã¶ cÃ¤Ã«Ã¶Ã¼c

You get similar result if you convert follwing text:

xxxxxx xxxxx xxxx äëüö cäëöüc

from ISO-8859-1 to UTF-8:

echo "xxxxxx xxxxx xxxx äëüö cäëöüc" | iconv -f iso-8859-2 -t utf-8
xxxxxx xxxxx xxxx Ă¤ĂŤĂźĂś cĂ¤ĂŤĂśĂźc

The "¤" character is utf-8 char c2 a4:

00000000: c2a4 0a                                  ...

I have made tcpdump on loopback to get communications from apache proxy module to sonarqube and even there you can see correct UTF-8 characters c3a4 c3ab c3bc c3b6 comming from IdP and then between "c"s you can see c3a4 c3ab c3b6 c3bc comming direct from apache.

00000000  47 45 54 20 2f 61 63 63  6f 75 6e 74 20 48 54 54   GET /acc ount HTT
...
00000390  58 2d 46 6f 72 77 61 72  64 65 64 2d 4e 61 6d 65   X-Forwar ded-Name
000003A0  3a 20 72 6f 62 65 72 74  20 74 65 73 74 32 20 77   : xxxxxx  xxxxx x
000003B0  6f 6c 66 20 c3 a4 c3 ab  c3 bc c3 b6 20 63 c3 a4   xxx .... .... c..
000003C0  c3 ab c3 b6 c3 bc 63 0d  0a                        ......c. .
...

The system has locales set to en_US.UTF-8, if this matters.

So Sonar gets really UTF-8 Text from Apache (direct config or from IdP) but then something probably converts this utf-8 text as if it was iso-8859 text to utf-8 again and makes nonsense.

Do you have any idea now? Could this be something in sonar or in wrapper or somewhere some options set incorrectly?

Regards,

Robert.