问:
Blank screen on Activity start even with correct onCreate() and setContentView()
I am getting a blank screen whenever I try to launch PlayListActivity.java from Bacon1.java on clicking a button which is button4 or button_audio . I think there is nothing wrong  with onCreate() and setContentView(). But I cant't understand still why I am getting a blank screen every time that activity launches.How to resolve this ?

This is the launcher Activity : Bacon1.java

```<code>package com.example.dell_1.myapp3;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Toast;
import java.io.File;

public class Bacon1 extends Activity {

    private static int RESULT_LOAD_IMAGE = 1;
    private static int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;

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

                    public void onClick3(View v) {
                        buttonClicked(v);

                        Intent o = new Intent(this,PlayListActivity.class);
                        startActivity(o);
    }

    private void buttonClicked(View view) {

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            Snackbar.make(view, "Permission not Granted, Requesting permission.", Snackbar.LENGTH_LONG).show();
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {

                Snackbar.make(view, "We need permission to internal storage for displaying songs", Snackbar.LENGTH_LONG).show();

            } else {

                Snackbar.make(view, "Allow myapp3 to access this device's internal storage", Snackbar.LENGTH_LONG).show();

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }
    }

    public void onClick2(View view) {

        Intent i = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(i, RESULT_LOAD_IMAGE);
    }

    public void onClick4(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "video/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    public void onClick5(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "zip/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    public void onClick6(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "text/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    public void onClick7(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "application/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(Bacon1.this, "WRITE_CONTACTS granted", Toast.LENGTH_SHORT)
                            .show();

                } else {

                    Toast.makeText(Bacon1.this, "WRITE_CONTACTS Denied", Toast.LENGTH_SHORT)
                            .show();

                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    }
</code>```

This is the corresponding xml : activity_bacon1.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.dell_1.myapp3.Bacon1">

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">
    </ImageView>

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="134dp"
        android:layout_marginStart="134dp"
        android:layout_marginTop="63dp"
        android:onClick="onClick2"
        android:text="@string/button_images" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button3"
        android:layout_alignStart="@+id/button3"
        android:layout_below="@+id/button3"
        android:layout_marginTop="22dp"
        android:onClick="onClick3"
        android:text="@string/button_audio" />

    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button4"
        android:layout_alignStart="@+id/button4"
        android:layout_below="@+id/button4"
        android:layout_marginTop="20dp"
        android:onClick="onClick4"
        android:text="@string/button_videos" />

    <Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button5"
        android:layout_alignStart="@+id/button5"
        android:layout_below="@+id/button5"
        android:layout_marginTop="16dp"
        android:onClick="onClick5"
        android:text="@string/button_zip" />

    <Button
        android:id="@+id/button7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button6"
        android:layout_alignStart="@+id/button6"
        android:layout_below="@+id/button6"
        android:layout_marginTop="19dp"
        android:onClick="onClick7"
        android:text="@string/button_apps" />

    <Button
        android:id="@+id/button8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="26dp"
        android:text="@string/button_documents"
        android:layout_below="@+id/button7"
        android:layout_alignLeft="@+id/button7"
        android:onClick="onClick6"
        android:layout_alignStart="@+id/button7" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="@string/text_internal"
        android:textAppearance="@android:style/TextAppearance.Large"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="99dp"
        android:layout_marginStart="99dp" />
</RelativeLayout>
</code>```

This is the launched Activity : PlayListActivity.java

```<code>package com.example.dell_1.myapp3;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;

public class PlayListActivity extends ListActivity {
    // Songs list
    public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_list);

        ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();

        SongsManager plm = new SongsManager();
        // get all songs from sdcard
        this.songsList = plm.getPlayList();

        // looping through playlist
        for (int i = 0; i < songsList.size(); i++) {
            // creating new HashMap
            HashMap<String, String> song = songsList.get(i);

            // adding HashList to ArrayList
            songsListData.add(song);
        }

        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(this, songsListData,
                R.layout.playlist_item, new String[]{"songTitle"}, new int[]{
                R.id.songTitle});

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();
        // listening to single listitem click
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // getting listitem index
                int songIndex = position;

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        AndroidBuildingMusicPlayerActivity.class);
                // Sending songIndex to PlayerActivity
                in.putExtra("songIndex", songIndex);
                setResult(100, in);
                // Closing PlayListView
                finish();
            }
        });
    }

}
</code>```

This is the corresponding xml file :   activity_play_list

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

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="#242424"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector" />

</LinearLayout>
</code>```

答:
Change you Bacon1 class to like this

```<code>package com.example.dell_1.myapp3;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Toast;
import java.io.File;

public class Bacon1 extends Activity {

    private static int RESULT_LOAD_IMAGE = 1;
    private static int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;

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

                    public void onClick3(View v) {
                        buttonClicked(v);
//We are going to call from buttonClicked method and onRequestPermissionsResult
                       // Intent o = new Intent(this,PlayListActivity.class);
                        //startActivity(o);
    }

    private void buttonClicked(View view) {

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            Snackbar.make(view, "Permission not Granted, Requesting permission.", Snackbar.LENGTH_LONG).show();
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {

                Snackbar.make(view, "We need permission to internal storage for displaying songs", Snackbar.LENGTH_LONG).show();

            } else {

                Snackbar.make(view, "Allow myapp3 to access this device's internal storage", Snackbar.LENGTH_LONG).show();

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }
else
{
 Intent o = new Intent(this,PlayListActivity.class);
                        startActivity(o);
}
    }

    public void onClick2(View view) {

        Intent i = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(i, RESULT_LOAD_IMAGE);
    }

    public void onClick4(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "video/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    public void onClick5(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "zip/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    public void onClick6(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "text/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    public void onClick7(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "application/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(Bacon1.this, "WRITE_CONTACTS granted", Toast.LENGTH_SHORT)
                            .show();
 Intent o = new Intent(this,PlayListActivity.class);
                        startActivity(o);

                } else {

                    Toast.makeText(Bacon1.this, "WRITE_CONTACTS Denied Please give permission from Settings->Apps->YourAppName>", Toast.LENGTH_SHORT)
                            .show();
//Or here you can call setting screen programmatically
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    }
</code>```

Hope it will help You..

Body:
I am getting a blank screen whenever I try to launch PlayListActivity.java from Bacon1.java on clicking a button which is button4 or button_audio . I think there is nothing wrong  with onCreate() and setContentView(). But I cant't understand still why I am getting a blank screen every time that activity launches.How to resolve this ?

This is the launcher Activity : Bacon1.java

package com.example.dell_1.myapp3;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Toast;
import java.io.File;

public class Bacon1 extends Activity {

    private static int RESULT_LOAD_IMAGE = 1;
    private static int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;

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

                    public void onClick3(View v) {
                        buttonClicked(v);

                        Intent o = new Intent(this,PlayListActivity.class);
                        startActivity(o);
    }

    private void buttonClicked(View view) {

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            Snackbar.make(view, "Permission not Granted, Requesting permission.", Snackbar.LENGTH_LONG).show();
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {

                Snackbar.make(view, "We need permission to internal storage for displaying songs", Snackbar.LENGTH_LONG).show();

            } else {

                Snackbar.make(view, "Allow myapp3 to access this device's internal storage", Snackbar.LENGTH_LONG).show();

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }
    }

    public void onClick2(View view) {

        Intent i = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(i, RESULT_LOAD_IMAGE);
    }

    public void onClick4(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "video/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    public void onClick5(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "zip/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    public void onClick6(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "text/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    public void onClick7(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "application/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(Bacon1.this, "WRITE_CONTACTS granted", Toast.LENGTH_SHORT)
                            .show();

                } else {

                    Toast.makeText(Bacon1.this, "WRITE_CONTACTS Denied", Toast.LENGTH_SHORT)
                            .show();

                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    }

This is the corresponding xml : activity_bacon1.xml

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

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">
    </ImageView>

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="134dp"
        android:layout_marginStart="134dp"
        android:layout_marginTop="63dp"
        android:onClick="onClick2"
        android:text="@string/button_images" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button3"
        android:layout_alignStart="@+id/button3"
        android:layout_below="@+id/button3"
        android:layout_marginTop="22dp"
        android:onClick="onClick3"
        android:text="@string/button_audio" />

    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button4"
        android:layout_alignStart="@+id/button4"
        android:layout_below="@+id/button4"
        android:layout_marginTop="20dp"
        android:onClick="onClick4"
        android:text="@string/button_videos" />

    <Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button5"
        android:layout_alignStart="@+id/button5"
        android:layout_below="@+id/button5"
        android:layout_marginTop="16dp"
        android:onClick="onClick5"
        android:text="@string/button_zip" />

    <Button
        android:id="@+id/button7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button6"
        android:layout_alignStart="@+id/button6"
        android:layout_below="@+id/button6"
        android:layout_marginTop="19dp"
        android:onClick="onClick7"
        android:text="@string/button_apps" />

    <Button
        android:id="@+id/button8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="26dp"
        android:text="@string/button_documents"
        android:layout_below="@+id/button7"
        android:layout_alignLeft="@+id/button7"
        android:onClick="onClick6"
        android:layout_alignStart="@+id/button7" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="@string/text_internal"
        android:textAppearance="@android:style/TextAppearance.Large"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="99dp"
        android:layout_marginStart="99dp" />
</RelativeLayout>

This is the launched Activity : PlayListActivity.java

package com.example.dell_1.myapp3;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;

public class PlayListActivity extends ListActivity {
    // Songs list
    public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_list);

        ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();

        SongsManager plm = new SongsManager();
        // get all songs from sdcard
        this.songsList = plm.getPlayList();

        // looping through playlist
        for (int i = 0; i < songsList.size(); i++) {
            // creating new HashMap
            HashMap<String, String> song = songsList.get(i);

            // adding HashList to ArrayList
            songsListData.add(song);
        }

        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(this, songsListData,
                R.layout.playlist_item, new String[]{"songTitle"}, new int[]{
                R.id.songTitle});

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();
        // listening to single listitem click
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // getting listitem index
                int songIndex = position;

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        AndroidBuildingMusicPlayerActivity.class);
                // Sending songIndex to PlayerActivity
                in.putExtra("songIndex", songIndex);
                setResult(100, in);
                // Closing PlayListView
                finish();
            }
        });
    }

}

This is the corresponding xml file :   activity_play_list

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

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="#242424"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector" />

</LinearLayout>

Body:
Change you Bacon1 class to like this

package com.example.dell_1.myapp3;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Toast;
import java.io.File;

public class Bacon1 extends Activity {

    private static int RESULT_LOAD_IMAGE = 1;
    private static int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;

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

                    public void onClick3(View v) {
                        buttonClicked(v);
//We are going to call from buttonClicked method and onRequestPermissionsResult
                       // Intent o = new Intent(this,PlayListActivity.class);
                        //startActivity(o);
    }

    private void buttonClicked(View view) {

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            Snackbar.make(view, "Permission not Granted, Requesting permission.", Snackbar.LENGTH_LONG).show();
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {

                Snackbar.make(view, "We need permission to internal storage for displaying songs", Snackbar.LENGTH_LONG).show();

            } else {

                Snackbar.make(view, "Allow myapp3 to access this device's internal storage", Snackbar.LENGTH_LONG).show();

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }
else
{
 Intent o = new Intent(this,PlayListActivity.class);
                        startActivity(o);
}
    }

    public void onClick2(View view) {

        Intent i = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(i, RESULT_LOAD_IMAGE);
    }

    public void onClick4(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "video/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    public void onClick5(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "zip/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    public void onClick6(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "text/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    public void onClick7(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "application/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(Bacon1.this, "WRITE_CONTACTS granted", Toast.LENGTH_SHORT)
                            .show();
 Intent o = new Intent(this,PlayListActivity.class);
                        startActivity(o);

                } else {

                    Toast.makeText(Bacon1.this, "WRITE_CONTACTS Denied Please give permission from Settings->Apps->YourAppName>", Toast.LENGTH_SHORT)
                            .show();
//Or here you can call setting screen programmatically
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    }

Hope it will help You..


来源: stackexchange

问:
Issues with Updating EF 4 Proc in Model Browser
I'm having issues with updating a select stored procedure in the model browser.  Deleting the function import and proc isn't updating the object correctly.  What's happening is that when I remap it, it says the function returns no columns.  I execute it in SQL, and it returns data with the associated columns just fine.

I don't understand why EF is having problems; I was able to map originally the correct way.  When deleting the complex object

Found this similar issue, but I am not using dynamic SQL.  I am using a function though: Entity Framework 4: The selected stored procedure returns no columns

Any ideas?

答: I'm assuming that you are allowing the entity modeler to generate the complex type for you based on the results of the stored procedure.  In your stored procedure, try adding SET FMTONLY OFF before you do the final select of your result set.  Then, at the end of the procedure, SET FMTONLY ON.  You can remove both statements once the entity modeler has generated your complex type.  More information in this question.

ContentLicense: CC BY-SA 2.5


问:
Inequalities on pandas column
I have a pandas dataframe, and I would like to create a new column based on an existing column and certain inequalities. For example, let

```<code>df=pd.DataFrame({'a':[1,2,3,4,5,6,7],'b':[3,6,4,2,7,7,1]})
</code>```

so df looks like

```<code>    a   b
0   1   3
1   2   6
2   3   4
3   4   2
4   5   7
5   6   7
6   7   1
</code>```

I would like to add a new column, res, that equals 0 if the corresponding value in a is smaller than 2, 1 if the corresponding value in a is at least 2 and smaller than 4, and 2 otherwise. So I would like to get

```<code>    a   b   res
0   1   3   0
1   2   6   1
2   3   4   1
3   4   2   2
4   5   7   2
5   6   7   2
6   7   1   2
</code>```

So far I have been doing this by using apply as follows:

```<code>def f(x):
    if x['a']<2:
        return 0
    elif x['a']>=2 and x['a']<4:
        return 1
    else:
        return 2
df['res']=df.apply(f,axis=1)
</code>```

but I was wondering if there is a more direct way, or some specific pandas method that can enable me to do that.

答:
For just a few values, you can also use numpy.where as a vectorized solution:

```<code>df['res'] = pd.np.where(df.a < 2, 0, pd.np.where((df.a >= 2) & (df.a < 4), 1, 2))
df
#   a   b   res
#0  1   3   0
#1  2   6   1
#2  3   4   1
#3  4   2   2
#4  5   7   2
#5  6   7   2
#6  7   1   2
</code>```

ContentLicense: CC BY-SA 3.0

Title: Inequalities on pandas column

Body:
I have a pandas dataframe, and I would like to create a new column based on an existing column and certain inequalities. For example, let

df=pd.DataFrame({'a':[1,2,3,4,5,6,7],'b':[3,6,4,2,7,7,1]})

so df looks like

    a   b
0   1   3
1   2   6
2   3   4
3   4   2
4   5   7
5   6   7
6   7   1

I would like to add a new column, res, that equals 0 if the corresponding value in a is smaller than 2, 1 if the corresponding value in a is at least 2 and smaller than 4, and 2 otherwise. So I would like to get

    a   b   res
0   1   3   0
1   2   6   1
2   3   4   1
3   4   2   2
4   5   7   2
5   6   7   2
6   7   1   2

So far I have been doing this by using apply as follows:

def f(x):
    if x['a']<2:
        return 0
    elif x['a']>=2 and x['a']<4:
        return 1
    else:
        return 2
df['res']=df.apply(f,axis=1)

but I was wondering if there is a more direct way, or some specific pandas method that can enable me to do that.

Body:
For just a few values, you can also use numpy.where as a vectorized solution:

df['res'] = pd.np.where(df.a < 2, 0, pd.np.where((df.a >= 2) & (df.a < 4), 1, 2))
df
#   a   b   res
#0  1   3   0
#1  2   6   1
#2  3   4   1
#3  4   2   2
#4  5   7   2
#5  6   7   2
#6  7   1   2


问:
PHP MySQL Query Where x = $variable from function
Why is this not working:

```<code>function listOrderComments ($factnr){
global $connection;

//$factnr = 123; //or $factnr = "123"; (Both work)

$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);
</code>```

When I echo $factnr I get "123" back.

When I uncommented //$factnr = 123; my function is working.

Looked everywhere for a solution. check the type $factnr is (string).

答:
Well if you're using a variable in your query you're opening yourself up to an injection attack for one.

If you're going to be using that variable I would recommend you use bind_param for your query

Read the PHP manual link below and you will be able to figure out the issue

http://php.net/manual/en/mysqli-stmt.bind-param.php

If you're passing in a variable to your function it should already be set so I don't understand why you're setting it to 123 anyway. So execute the sql statement and bind the parameter following the first example on the PHP docs page.

```<code>public function listOrderComments ($factnr)
{
   global $connection;
   $query = "SELECT * FROM orderstatus WHERE factuurnummer = ?";
   $sql->prepare($query);
   $sql->bind_param("s", $factnr);
   $sql->execute();
   $result = $sql->get_result();
   $data = mysqli_fetch_all($result, MYSQLI_ASSOC);

   foreach ($data as $row) {
        print_r($row);
   }
}
</code>```

Then do what you want with the result

Body:
Why is this not working:

function listOrderComments ($factnr){
global $connection;

//$factnr = 123; //or $factnr = "123"; (Both work)

$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);

When I echo $factnr I get "123" back.

When I uncommented //$factnr = 123; my function is working.

Looked everywhere for a solution. check the type $factnr is (string).

Body:
Well if you're using a variable in your query you're opening yourself up to an injection attack for one.

If you're going to be using that variable I would recommend you use bind_param for your query

Read the PHP manual link below and you will be able to figure out the issue

http://php.net/manual/en/mysqli-stmt.bind-param.php

If you're passing in a variable to your function it should already be set so I don't understand why you're setting it to 123 anyway. So execute the sql statement and bind the parameter following the first example on the PHP docs page.

public function listOrderComments ($factnr)
{
   global $connection;
   $query = "SELECT * FROM orderstatus WHERE factuurnummer = ?";
   $sql->prepare($query);
   $sql->bind_param("s", $factnr);
   $sql->execute();
   $result = $sql->get_result();
   $data = mysqli_fetch_all($result, MYSQLI_ASSOC);

   foreach ($data as $row) {
        print_r($row);
   }
}

Then do what you want with the result

ContentLicense: CC BY-SA 4.0


问:
Diagonal Background Structure [CSS]
Currently working on a web design project for a client where I designed a multi-layered diagonal background. I solved a single diagonal with;

```<code>background-color: #dbebde;
background-image: -webkit-linear-gradient(120deg, #dbebde 50%, #f8f8f8 45%);
min-height: 400px;
</code>```

However, as seen in the image below, I need to add a smaller diagonal on the left side.

Does anyone have an idea on how to solve this specific issue?

答:
I suggest you using 2 DIVs and give one of them a gradient with transparent color.
HTML :

```<code><div class="outer">
  <div class="inner"></div>
</div>
</code>```

CSS:

```<code>.outer,.inner{
  position:fixed;
  top:0;
  bottom:0;
  left:0;
  right:0;
}
.outer {
  background-color: #dbebde;
  background-image: -webkit-linear-gradient(50deg, red 70%, #f8f8f8 65%);
  background-image: -moz-linear-gradient(50deg, red 70%, #f8f8f8 65%);
  background-image: -o-linear-gradient(50deg, red 70%, #f8f8f8 65%);
  background-image: -ms-linear-gradient(50deg, red 70%, #f8f8f8 65%);
}
.inner{
  background-color:  transparent;
  background-image: -webkit-linear-gradient(120deg, #dbebde 60%, transparent 55%);
  background-image: -moz-linear-gradient(120deg, #dbebde 60%, transparent 55%);
  background-image: -o-linear-gradient(120deg, #dbebde 60%, transparent 55%);
  background-image: -ms-linear-gradient(120deg, #dbebde 60%, transparent 55%);
}
</code>```

You can see it in action:
https://codepen.io/FaridNaderi/pen/LLBVqw

Hope at least it helps you.

Title: Diagonal Background Structure [CSS]

Body:
Currently working on a web design project for a client where I designed a multi-layered diagonal background. I solved a single diagonal with;

background-color: #dbebde;
background-image: -webkit-linear-gradient(120deg, #dbebde 50%, #f8f8f8 45%);
min-height: 400px;

However, as seen in the image below, I need to add a smaller diagonal on the left side.

Does anyone have an idea on how to solve this specific issue?

Body:
I suggest you using 2 DIVs and give one of them a gradient with transparent color.
HTML :

<div class="outer">
  <div class="inner"></div>
</div>

CSS:

.outer,.inner{
  position:fixed;
  top:0;
  bottom:0;
  left:0;
  right:0;
}
.outer {
  background-color: #dbebde;
  background-image: -webkit-linear-gradient(50deg, red 70%, #f8f8f8 65%);
  background-image: -moz-linear-gradient(50deg, red 70%, #f8f8f8 65%);
  background-image: -o-linear-gradient(50deg, red 70%, #f8f8f8 65%);
  background-image: -ms-linear-gradient(50deg, red 70%, #f8f8f8 65%);
}
.inner{
  background-color:  transparent;
  background-image: -webkit-linear-gradient(120deg, #dbebde 60%, transparent 55%);
  background-image: -moz-linear-gradient(120deg, #dbebde 60%, transparent 55%);
  background-image: -o-linear-gradient(120deg, #dbebde 60%, transparent 55%);
  background-image: -ms-linear-gradient(120deg, #dbebde 60%, transparent 55%);
}

You can see it in action:
https://codepen.io/FaridNaderi/pen/LLBVqw

Hope at least it helps you.


问:
Chef vault adding nodes
I would like to add nodes to a certain vault before creating them, for example:

All vagrant machines that I provision with vagrant up that has the patter vagrant-dev-* could acces the chef vault secrets.

If i try to do this, I've got a warning that no one machine is on chef with that pattern.

WARNING: No clients were returned from search, you may not have got what you expected!!

If I try the command after the machine is provisioned it works, but then the provision fails because the machine does not have acces to the vault for configure the sensitive information.

knife vault create secrets root -M client -S "name:vagrant-dev-*"

How can I make the machines have access to the vaul before provisioning them?

答: Unfortunately this is not possible. For something to be added to a vault it needs to have an RSA public key available on the Chef Server. This is generally done as part of the node bootstrap and client creation. This is a structural limitation of this whole category of asymmetric pre-encryption systems, the keys for all secrets consumers must be known at the time of the pre-encryption process.</p>

Title: Chef vault adding nodes


问:
A few questions about ray tracing with opengl
I need to do a limited form of ray tracing. I do not need reflections. I only need to change the color of a pixel, depending on how it passes by an object, and refraction. I also only need to test for intersections between the ray and spheres and disks, nothing else.

This is the main function in my shader:

```<code>void main(void)
{
    Ray ray;
    ray.origin=vec3(0.5,0.5,.75);

    ray.direction=vec3(gl_FragCoord.x/width,gl_FragCoord.y/height,-gl_FragCoord.z)-ray.origin;
    ray.direction=normalize(ray.direction);

    gl_FragColor=trace(ray);
}
</code>```

My first question is regarding the origin of the ray. How do I get its location? Right now, I just fiddle around until it looks right, but if I change the width or height of the screen I have to play around until it looks right.

My second question is about the intersection between a ray and a disk. I do this by first checking to see if the ray intersects a plane and then if the intersection point is within the radius of the disk.
My code looks like this

```<code>float intersectPlane(Ray ray,vec3 point,vec3 normal)
{
    return dot(point-ray.origin,normal)/dot(ray.direction,normal);
}
...

det=intersectPlane(ray,bodies[count].position,vec3(0,0,1));
if(det>0)
{
        if(distance(det*ray.direction,bodies[count].position)<=bodies[count].radius)
        {
            return vec4(1.0,0.0,0.0,1.0);
        }
}
</code>```

The problem is that if bodies[count].radius is less than or equal to the z-position of the ray's origin then nothing shows up. So

```<code>if(det>0)
{
        if(distance(det*ray.direction,bodies[count].position)<=.76)
        {
            return vec4(1.0,0.0,0.0,1.0);
        }
}
</code>```

results in visible disks, while using the actual radius results in nothing.

答:
The intersection point of a ray and a plane is calculated as follows:

```<code>dist = dot( plane_origin - ray.origin, plane_NV ) / dot( ray.direction, plane_NV );
plane_isect = ray.origin + ray.direction * dist;
</code>```

Your function intersectPlane calculates the distance from the origin of the ray to the intersection point at the plane correctly, but you do not calculate the intersection point before you compare it to the center of the disks.

To test if the intersection point is within the radius you have to do the following:

```<code>vec3 plane_isect = ray.origin + det * ray.direction;
if ( distance( plane_isect, bodies[count].position ) <= bodies[count].radius )
</code>```

Adapt your code like this:

```<code>det = intersectPlane( ray, bodies[count].position, vec3(0,0,1) );
if ( det>0 )
{
    vec3 plane_isect = ray.origin + det * ray.direction;
    if ( distance( plane_isect, bodies[count].position ) <= bodies[count].radius )
    {
        return vec4(1.0,0.0,0.0,1.0);
    }
}
</code>```

Body:
I need to do a limited form of ray tracing. I do not need reflections. I only need to change the color of a pixel, depending on how it passes by an object, and refraction. I also only need to test for intersections between the ray and spheres and disks, nothing else.

This is the main function in my shader:

void main(void)
{
    Ray ray;
    ray.origin=vec3(0.5,0.5,.75);

    ray.direction=vec3(gl_FragCoord.x/width,gl_FragCoord.y/height,-gl_FragCoord.z)-ray.origin;
    ray.direction=normalize(ray.direction);

    gl_FragColor=trace(ray);
}

My first question is regarding the origin of the ray. How do I get its location? Right now, I just fiddle around until it looks right, but if I change the width or height of the screen I have to play around until it looks right.

My second question is about the intersection between a ray and a disk. I do this by first checking to see if the ray intersects a plane and then if the intersection point is within the radius of the disk.
My code looks like this

float intersectPlane(Ray ray,vec3 point,vec3 normal)
{
    return dot(point-ray.origin,normal)/dot(ray.direction,normal);
}
...

det=intersectPlane(ray,bodies[count].position,vec3(0,0,1));
if(det>0)
{
        if(distance(det*ray.direction,bodies[count].position)<=bodies[count].radius)
        {
            return vec4(1.0,0.0,0.0,1.0);
        }
}

The problem is that if bodies[count].radius is less than or equal to the z-position of the ray's origin then nothing shows up. So

if(det>0)
{
        if(distance(det*ray.direction,bodies[count].position)<=.76)
        {
            return vec4(1.0,0.0,0.0,1.0);
        }
}

results in visible disks, while using the actual radius results in nothing.

Body:
The intersection point of a ray and a plane is calculated as follows:

dist = dot( plane_origin - ray.origin, plane_NV ) / dot( ray.direction, plane_NV );
plane_isect = ray.origin + ray.direction * dist;

Your function intersectPlane calculates the distance from the origin of the ray to the intersection point at the plane correctly, but you do not calculate the intersection point before you compare it to the center of the disks.

To test if the intersection point is within the radius you have to do the following:

vec3 plane_isect = ray.origin + det * ray.direction;
if ( distance( plane_isect, bodies[count].position ) <= bodies[count].radius )

Adapt your code like this:

det = intersectPlane( ray, bodies[count].position, vec3(0,0,1) );
if ( det>0 )
{
    vec3 plane_isect = ray.origin + det * ray.direction;
    if ( distance( plane_isect, bodies[count].position ) <= bodies[count].radius )
    {
        return vec4(1.0,0.0,0.0,1.0);
    }
}


问:
Transfer of Websocket communication from server to client in Streaming
I'm new websocket streaming application.
I'm trying to evaluate kaazing and solace streaming vendor products.
I'm trying to put a layer or interface application infornt of kaazing publisher before it creates the socket connection.
The client would make request to the interface for the socket connection , the interface plays the role to authenticate and authorize and do some business changes before the creation of socket.
The interface establish the secured socket connection with kazzing or streaming application and transfer the connection object to the client in response.
The client use the established connection from the reponse and retains the connection for streaming the data to client from the streaming server.

The objective is to hide the topic info and connection established from the client side for secured process.
So the infterace creates the secured connection and transfers the connection to authorized client which continue the streaming from the streaming server until the session expires.
Please let me designing such an application is possible.

The client receives data but it doesn't establish connection of its own, its created from server side and transfered to client side after all necessary validation.

Guide me to proceed further with the design and I'm inneed of expert's valuable suggestion.
Thanks in advance and appriciated for directing me to the right path in designing the streaming appliation.

My aim is not to introduce a new layer between the gateway and client. Altimate aim is to customize the gateway for my product, For example the user(client) connects to gateway and tries to access the topic say stock(eligible to subscribe) then he will be able to get the data streaming. If he needs share he would register is some place and after approval only he will be eligible to view, So authorization would play a role and maintaince a session and loads the customized data and allows to stream.
Typically am trying to have a dashboard of data streaming. So only authorized streaming is allowed for user. Also he will be able to see all the topic name. whether its possible to use proxy name , example 1, or 2 might be the value he would use from client side, when it reaches the gateway it verify the authorization and replace the value with real topic name and establish the data.
Please let me know whether I've my question clear. Your valuable suggestions and guidance will be more helpful to continue with my research.

Thanks
Krish

答:
in case you wonder how the world has changed over the last five year to address this kind of need, now you could give a try to streamdata.io, a proxy which uses SSE protocol (unidirectional) and is available in minutes. It would perfectly fit what's needed in the example given, because Im not sure WebSocket is the ideal answer here. Tho it should work, it's basically like buying a harvester to go get your kids at school.

As a disclaimer, I need to say that I work for Streamdata, and we see this kind of thing every day.

WebSocket is great if you need bidirectional streams of data, like in chats or games. Most of the time, when the clients mainly expect updated data from the server, instead of polling AF or deploying WebSocket, SSE is the best alternative as it's easier to deploy (http, etc.). The rest of the settings (for security) can be done through the proxy interface.

Boom: it's available before you even realize it, it's secure, easy to maintain and more efficient than before. You have more time available to answer questions from the community over here; your team is happy; your boss loves you more than before and might even give you a raise. Life can be so simple sometimes!


问:
Postgres COPY invalid syntax for integer
My table,

```<code>       Table "public.product_status"
 Column |         Type          | Modifiers
--------+-----------------------+-----------
 id     | integer               | not null
 code   | character varying(10) |
 notes  | text                  |
</code>```

First line of my CSV file,

```<code>1,S,blah blah blah
</code>```

Copy command,

```<code>=# copy product_status from 'status_table.csv' with csv;
ERROR:  invalid input syntax for integer: "1"
CONTEXT:  COPY product_status, line 1, column id: "1"
</code>```

Really don't understand how that's invalid syntax for an integer!
Even postgres seems to agree with me,

```<code>=# insert into product_status values (1,'S','blah blah blah');
=# copy product_status to STDOUT with csv;
1,S,blah blah blah
</code>```

Any ideas? Other questions I found on the site didn't seem applicable to whatever I've done wrong here.

答:
I had this same issue, and my answer was the same as above, a "useless byte order mark at the beginning of the file."  Here is how I removed it.

1) Open the file in vim

```<code>vim file_with_bom.txt
</code>```

2) Set the 'nobomb' option

```<code>:set nobomb
</code>```

3) Save the file and exit

```<code>:wq
</code>```

Hope this helps!

Body:
My table,

       Table "public.product_status"
 Column |         Type          | Modifiers
--------+-----------------------+-----------
 id     | integer               | not null
 code   | character varying(10) |
 notes  | text                  |

First line of my CSV file,

1,S,blah blah blah

Copy command,

=# copy product_status from 'status_table.csv' with csv;
ERROR:  invalid input syntax for integer: "1"
CONTEXT:  COPY product_status, line 1, column id: "1"

Really don't understand how that's invalid syntax for an integer!
Even postgres seems to agree with me,

=# insert into product_status values (1,'S','blah blah blah');
=# copy product_status to STDOUT with csv;
1,S,blah blah blah

Any ideas? Other questions I found on the site didn't seem applicable to whatever I've done wrong here.

Body:
I had this same issue, and my answer was the same as above, a "useless byte order mark at the beginning of the file."  Here is how I removed it.

1) Open the file in vim

vim file_with_bom.txt

2) Set the 'nobomb' option

:set nobomb

3) Save the file and exit

:wq

Hope this helps!


问:
Get database connection from a connection pool
I am refactoring others code.  The one thing I notice is that of the manner on how the system is getting a connection from the connection pool.

Sample is like this. On every call of the service method, the system is making a context lookup on the JNDI for the datasource.

```<code>public class CheckinServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            //Obtain Connection
            InitialContext initialContext = new InitialContext();
            javax.sql.DataSource ds = (javax.sql.DataSource) initialContext
                    .lookup("jdbc/mysqldb");
            java.sql.Connection conn = ds.getConnection();
            //business logic
            //redirect
        } finally {
            conn.close();
        }
    }
}
</code>```

I do think that there is a performance hit on doing this every time.  I am thinking of another way around these on how to retrieve a connection from a connection pool.

I am thinking about using the servlet's init() method but I think that is not optimal.

答:
Adding to what's said, there's a design pattern called Service Locator, which is a basically a singleton containing a registry called "service" that holds your JNDI objects.

Basically, if the object isn't found in the registry, the service is taken from the JNDI pool and registered in the registry. The next call will simply pull the object from registry.

Hope this helps.

Body:
I am refactoring others code.  The one thing I notice is that of the manner on how the system is getting a connection from the connection pool.

Sample is like this. On every call of the service method, the system is making a context lookup on the JNDI for the datasource.

public class CheckinServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            //Obtain Connection
            InitialContext initialContext = new InitialContext();
            javax.sql.DataSource ds = (javax.sql.DataSource) initialContext
                    .lookup("jdbc/mysqldb");
            java.sql.Connection conn = ds.getConnection();
            //business logic
            //redirect
        } finally {
            conn.close();
        }
    }
}

I do think that there is a performance hit on doing this every time.  I am thinking of another way around these on how to retrieve a connection from a connection pool.

I am thinking about using the servlet's init() method but I think that is not optimal.


问:
Amazon Alexa: Testing my skill, convert a text to Lambda Request
I have defined my intent schema and sample utterances and it works fine. I can also test it with Service Simulator and Amazon dot.

I want to write a code which gets a text and create the IntentRequest based on it (knowing the intentSchema). I can see that Service Simulator is doing something similar: it receives the text, make the IntentRequest and show it in the left box named Lambda Request.

How can do the same? receive the text and recognize the intent and slots and convert it to IntentRequest (obviously, not manually).

example:
input: "How is the weather in Austin?"
output: a IntentRequest object similar to this:

```<code>{
  "session": {
    "sessionId": "....",
    "application": {
      "applicationId": "... "
    },
    "attributes": {},
    "user": {...},
    "new": true
  },
  "request": {
    "type": "IntentRequest",
    "requestId": "reqid",
    "locale": "en-US",
    "timestamp": "...",
    "intent": {
      "name": "WeatherIntent",
      "slots": {...},
    }
  },
  "version": "1.0"
}
</code>```

答:
You should use a dedicated dialog service such as Lex, API.AI, or Watson

They will get text and return the intent

Body:
I have defined my intent schema and sample utterances and it works fine. I can also test it with Service Simulator and Amazon dot.

I want to write a code which gets a text and create the IntentRequest based on it (knowing the intentSchema). I can see that Service Simulator is doing something similar: it receives the text, make the IntentRequest and show it in the left box named Lambda Request.

How can do the same? receive the text and recognize the intent and slots and convert it to IntentRequest (obviously, not manually).

example:
input: "How is the weather in Austin?"
output: a IntentRequest object similar to this:

{
  "session": {
    "sessionId": "....",
    "application": {
      "applicationId": "... "
    },
    "attributes": {},
    "user": {...},
    "new": true
  },
  "request": {
    "type": "IntentRequest",
    "requestId": "reqid",
    "locale": "en-US",
    "timestamp": "...",
    "intent": {
      "name": "WeatherIntent",
      "slots": {...},
    }
  },
  "version": "1.0"
}


问:
In Node JS (Hapijs) how to globally access the Server variable
It must be simple but I can not find a good solution.

In a node module for example I want to log if something goes wrong. So I need want to use the Hapi function  server.log(...). An example:

In the server.js:

```<code>const server = new Hapi.Server({...});
server.connection({port:3000});
server.start((err) => {
  if (err) { throw err }
}
</code>```

In the file test.js, I want to use the server variable created in the server.js. It should be usable in any module, because of logging and loading other plugins.

```<code>class Test {
  logInfo(text) {
    server.log(['info'], text);  // this will not work.
  }
}
module.exports = new Test();
</code>```

I can ofcause add the server to every call for the module, but that would be an overkill.

How do I get a reference to the server variable outside the module it was created?

答:
If you want to log a message during a request, you can use request.log(...).

Alternatively, you can use server.log(...) by accessing the server object on the request object in a handler.

```<code>{
    method: 'GET',
    path: '/do/stuff',
    handler: function (request, reply) {
        request.server.log('server.log() method');

        request.log('request.log() method');

        const test = new Test(request.server);

        test.logInfo('some text here');
    }
}
</code>```

Check out my answer on logging in hapi, too.

In your case, you'd need to pass a reference to the server object to your module if you specifically wanted to log a message a hapi server event.

```<code>class Test {
    private server;

    constructor(server) {
        this.server = server;
    }

    logInfo(text) {
        this.server.log(['info'], text);  // this will work.
    }
}
</code>```

But the commenter on your question is likely right. You should avoid this pattern if you want to avoid tight coupling of your modules.

Body:
It must be simple but I can not find a good solution.

In a node module for example I want to log if something goes wrong. So I need want to use the Hapi function  server.log(...). An example:

In the server.js:

const server = new Hapi.Server({...});
server.connection({port:3000});
server.start((err) => {
  if (err) { throw err }
}

In the file test.js, I want to use the server variable created in the server.js. It should be usable in any module, because of logging and loading other plugins.

class Test {
  logInfo(text) {
    server.log(['info'], text);  // this will not work.
  }
}
module.exports = new Test();

I can ofcause add the server to every call for the module, but that would be an overkill.

How do I get a reference to the server variable outside the module it was created?

Body:
If you want to log a message during a request, you can use request.log(...).

Alternatively, you can use server.log(...) by accessing the server object on the request object in a handler.

{
    method: 'GET',
    path: '/do/stuff',
    handler: function (request, reply) {
        request.server.log('server.log() method');

        request.log('request.log() method');

        const test = new Test(request.server);

        test.logInfo('some text here');
    }
}

Check out my answer on logging in hapi, too.

In your case, you'd need to pass a reference to the server object to your module if you specifically wanted to log a message a hapi server event.

class Test {
    private server;

    constructor(server) {
        this.server = server;
    }

    logInfo(text) {
        this.server.log(['info'], text);  // this will work.
    }
}

But the commenter on your question is likely right. You should avoid this pattern if you want to avoid tight coupling of your modules.


问:
Android Studio - how to make R.string show text in the editor
Sometimes in the activity or xml, Android studio editor directly shows the text that is mapped for the particular R.string and When I click on that text, it changes to R.string.<>.

Few times, I see activity or xml editor shows R.string.<>, now  from the editor is there a short-cut to see what is the string in that reference without opening strings.xml?

答:
You need to enable it under Preferences -> Editor -> General -> Code Folding.

It’s (as far as I can remember) the “Android String References”.

Note, you have to close/re-open the XML for this setting to “show”.

You can see how it looks (some code has been “red taped” for “corporate reasons” but you can see how even the @dimen/xxx and the @string/xxx in the contentDescription has been expanded.


问:
What is the use case of noop [:] in bash?
I searched for noop in bash (:), but was not able to find any good information. What is the exact purpose or use case of this operator?

I tried following and it's working like this for me:

```<code>[mandy@root]$ a=11
[mandy@root]$ b=20
[mandy@root]$ c=30
[mandy@root]$ echo $a; : echo $b ; echo $c
10
30
</code>```

Please let me know, any use case of this operator in real time or any place where it is mandatory to use it.

答:
Ignoring alias arguments

Some times you want to have an alias that doesn't take any argument. You can do it using ::

```<code>> alias alert_with_args='echo hello there'

> alias alert='echo hello there;:'

> alert_with_args blabla
hello there blabla

> alert blabla
hello there
</code>```

Body:
I searched for noop in bash (:), but was not able to find any good information. What is the exact purpose or use case of this operator?

I tried following and it's working like this for me:

[mandy@root]$ a=11
[mandy@root]$ b=20
[mandy@root]$ c=30
[mandy@root]$ echo $a; : echo $b ; echo $c
10
30

Please let me know, any use case of this operator in real time or any place where it is mandatory to use it.

Body:
Ignoring alias arguments

Some times you want to have an alias that doesn't take any argument. You can do it using ::

> alias alert_with_args='echo hello there'

> alias alert='echo hello there;:'

> alert_with_args blabla
hello there blabla

> alert blabla
hello there


问:
Problems reading binary file
I'm trying to read the first 6 bytes of a file, but it's giving me weird results, and I can't seem to figure out what I'm doing wrong.

My code:

```<code>struct Block {
    char fileSize[3];
    char initialDataBlockId[3];
};

int main(int c, char **a) {

    ifstream file("C\\main_file_cache.idx0", ios::binary);

    Block block;

    file.get((char*)&block, sizeof(block));

    printf("File Size: %i\n", block.fileSize);
    printf("Initial Data Block ID: %i\n", block.initialDataBlockId);

    file.close();

    system("pause");
    return 0;
}
</code>```

Before I ran the code, I opened the file in a binary editor,
and it showed me this hex code:

```<code>    00 00 00 00-00 00 05 af-4b 00 00 01-26 df cd 00
    00 6f 03 3f-ed 00 03 61-05 08 35 00-04 8b 01 61
    59 00 08 39-03 23 0a 00-05 6c 00 35-d0 00 06 fe
    03 69 d8 00-07 19
</code>```

There are a total of 54 bytes. The first 6 bytes are just zero.

So, I expected my program to produce the following output:

```<code>File Size: 0
Initial Data Block ID: 0
</code>```

Instead, the outputs is as follows:

```<code>File Size: 10419128
Initial Data Block ID: 10419131
</code>```

This result makes no sense. Maybe there is something wrong with my code?

答:
If you want to read a binary data you can use a read method from ifstream and also write method from ofstream.

```<code>istream & ifstream::read (char * s, streamsize n);
ostream & ofstream::write (const char * s, streamsize n);
</code>```

You have to know that binary mode is useless for UNIX systems and text mode is only useful.

Title: Problems reading binary file

Body:
I'm trying to read the first 6 bytes of a file, but it's giving me weird results, and I can't seem to figure out what I'm doing wrong.

My code:

struct Block {
    char fileSize[3];
    char initialDataBlockId[3];
};

int main(int c, char **a) {

    ifstream file("C\\main_file_cache.idx0", ios::binary);

    Block block;

    file.get((char*)&block, sizeof(block));

    printf("File Size: %i\n", block.fileSize);
    printf("Initial Data Block ID: %i\n", block.initialDataBlockId);

    file.close();

    system("pause");
    return 0;
}

Before I ran the code, I opened the file in a binary editor,
and it showed me this hex code:

    00 00 00 00-00 00 05 af-4b 00 00 01-26 df cd 00
    00 6f 03 3f-ed 00 03 61-05 08 35 00-04 8b 01 61
    59 00 08 39-03 23 0a 00-05 6c 00 35-d0 00 06 fe
    03 69 d8 00-07 19

There are a total of 54 bytes. The first 6 bytes are just zero.

So, I expected my program to produce the following output:

File Size: 0
Initial Data Block ID: 0

Instead, the outputs is as follows:

File Size: 10419128
Initial Data Block ID: 10419131

This result makes no sense. Maybe there is something wrong with my code?

Body:
If you want to read a binary data you can use a read method from ifstream and also write method from ofstream.

istream & ifstream::read (char * s, streamsize n);
ostream & ofstream::write (const char * s, streamsize n);

You have to know that binary mode is useless for UNIX systems and text mode is only useful.


问:
MySQL - How Can I Automate a View Query That Subtracts Metrics From the Most Recent Date To The Previous Day & Date Stamps The Most Recent Data
I have a daily API call that gives me LIFETIME data for a unique ID and date stamps the data batch every day at midnight. This data is appended to a database in MySQL, but I need to transform it in a way where I can get daily data for that unique id for every metric.

My Table in MySQL:

Desired Output:

For id 3 I took the previous day (7/3/2017) and most recent date (7/4/2017) difference for it's respective metrics (Impressions, Clicks) and time stamped that line item as 7/4/2017. I need to process this type of transformation by id for multiple ids and metrics. Thank you!

UPDATE of My Query Based on Jacob's Feedback:

```<code>CREATE VIEW `facebook_insights` AS
SELECT
  t1.id
, t1.timestamp
, t1.message
, t1.posted
, t1.permalink_url
, t1.caption
, t1.link
, t1.type
, t1.post_impressions - t2.post_impressions as Impressions
, t1.post_impressions_organic - t2.post_impressions_organic as Post_Impressions_Organic
, t1.post_impressions_paid - t2.post_impressions_paid as Post_Impressions_Paid
, t1.post_engaged_users - t2.post_engaged_users as Post_Engaged_Users
, t1.post_consumptions - t2.post_consumptions as Post_Consumptions
, t1.post_negative_feedback - t2.post_negative_feedback as
Post_Negative_Feedback
, t1.post_negative_feedback_unique - t2.Post_Negative_Feedback_Unique as
Post_Negative_Feedback_Unique
, t1.post_impressions_fan - t2.post_impressions_fan as Post_Impressions_Fan
, t1.post_impressions_fan_paid - t2.post_impressions_fan_paid as
Post_Impressions_Fan_Paid
, t1.post_engaged_fan - t2.Post_Engaged_Fan as Post_Engaged_Fan
, t1.post_video_complete_views_organic -
t2.post_video_complete_views_organic as Post_Video_Complete_Views_Organic
, t1.post_video_complete_views_paid - t2.post_video_complete_views_paid as
Post_Video_Complete_Views_Paid
, t1.post_video_views_10s - t2.post_video_views_10s as Post_Video_Views_10s
, t1.post_video_views_10s_unique - t2.post_video_views_10s_unique as
Post_Video_Views_10s_Unique
, t1.post_video_views_organic - t2.post_video_views_organic as
Post_Video_Views_Organic
, t1.post_video_views_paid - t2.post_video_views_paid as
Post_Video_Views_Paid
, t1.post_video_views_clicked_to_play - t2.post_video_views_clicked_to_play
as Post_Video_Views_Clicked_to_Play

FROM
unpaid_media.facebook_insight t1
JOIN unpaid_media.facebook_insight t2
ON t1.id = t2.id
and t1.timestamp  = t2.timestamp + INTERVAL 1 DAY
</code>```

答:
The key here is to rejoin the table to itself. In the query below, I'm rejoining your table, but setting it up so that the timestamp is a qualifier on the join. This will join the previous day's records and allow you to simply subtract them.

select
  t1.id
  , t1.timestamp
  , t1.impressions - t2.impressions as impressions
  , t1.clicks - t2.clicks as clicks
from
  table t1
  join table t2
    on t1.id         = t2.id
    and t1.timestamp = t2.timestamp + INTERVAL 1 DAY
```

Body:
I have a daily API call that gives me LIFETIME data for a unique ID and date stamps the data batch every day at midnight. This data is appended to a database in MySQL, but I need to transform it in a way where I can get daily data for that unique id for every metric.

My Table in MySQL:

Desired Output:

For id 3 I took the previous day (7/3/2017) and most recent date (7/4/2017) difference for it's respective metrics (Impressions, Clicks) and time stamped that line item as 7/4/2017. I need to process this type of transformation by id for multiple ids and metrics. Thank you!

UPDATE of My Query Based on Jacob's Feedback:

CREATE VIEW `facebook_insights` AS
SELECT
  t1.id
, t1.timestamp
, t1.message
, t1.posted
, t1.permalink_url
, t1.caption
, t1.link
, t1.type
, t1.post_impressions - t2.post_impressions as Impressions
, t1.post_impressions_organic - t2.post_impressions_organic as Post_Impressions_Organic
, t1.post_impressions_paid - t2.post_impressions_paid as Post_Impressions_Paid
, t1.post_engaged_users - t2.post_engaged_users as Post_Engaged_Users
, t1.post_consumptions - t2.post_consumptions as Post_Consumptions
, t1.post_negative_feedback - t2.post_negative_feedback as
Post_Negative_Feedback
, t1.post_negative_feedback_unique - t2.Post_Negative_Feedback_Unique as
Post_Negative_Feedback_Unique
, t1.post_impressions_fan - t2.post_impressions_fan as Post_Impressions_Fan
, t1.post_impressions_fan_paid - t2.post_impressions_fan_paid as
Post_Impressions_Fan_Paid
, t1.post_engaged_fan - t2.Post_Engaged_Fan as Post_Engaged_Fan
, t1.post_video_complete_views_organic -
t2.post_video_complete_views_organic as Post_Video_Complete_Views_Organic
, t1.post_video_complete_views_paid - t2.post_video_complete_views_paid as
Post_Video_Complete_Views_Paid
, t1.post_video_views_10s - t2.post_video_views_10s as Post_Video_Views_10s
, t1.post_video_views_10s_unique - t2.post_video_views_10s_unique as
Post_Video_Views_10s_Unique
, t1.post_video_views_organic - t2.post_video_views_organic as
Post_Video_Views_Organic
, t1.post_video_views_paid - t2.post_video_views_paid as
Post_Video_Views_Paid
, t1.post_video_views_clicked_to_play - t2.post_video_views_clicked_to_play
as Post_Video_Views_Clicked_to_Play

FROM
unpaid_media.facebook_insight t1
JOIN unpaid_media.facebook_insight t2
ON t1.id = t2.id
and t1.timestamp  = t2.timestamp + INTERVAL 1 DAY


问:
Google Maps Javascript API shows only a few markers out of 500+
I'm currently working with the Google Maps Javascript API to display all locations for the customers. It has worked well with PHP only, but now I'm working with the $.ajax() function.

```<code>function init() {
    map = new google.maps.Map(document.getElementById('googleMap'), {
            zoom: 6,
            center: {lng:  10.1293945, lat: 51.1793430}
          });
    var markers = addMarkers('', '', 'POST');
    return map;
}

function addMarkers(f, s, method) {
    console.log("Filter: " + f);
    $.ajax({
        url:      'user-load.php' + "?echo=1&method=" + method + "&filter=" + f + "&search=" + s,

        dataType: 'json',
        success: function(data) {
            var count = data['length'];
            console.log(count + " found");
            var displayed = 0;
            for(var i = 0; i < count;  i++) {
                if(data[i]['lat'] != 0 && data[i]['lat'] != 0) {
                    displayed++;
                    var name = data[i]['first'] + " " + data[i]['last'];
                    var url = '';
                    if(data[i]['url'] != '') {
                        url = "<p>Website: <a target=\x22_blank\x22 href=\x22" + data[i]['url'] + "\x22>" + data[i]['url'] + "</a></p>";
                    }
                    var mail = '';
                    if(data[i]['mail'] != '') {
                        url = "<p>E-Mail: " + data[i]['mail'] + "</p>";
                    }
                    var marker = new google.maps.Marker({
                        position:{lng: parseInt(data[i]['lng']), lat: parseInt(data[i]['lat'])},
                        map: map,
                        title: name + ", " + data[i]['title'],
                        animation: google.maps.Animation.DROP
                    });
                    var c = '<h1>' + name + '</h1>' +
                                  '<h4>' + data[i]['title'] + '</h4>' +
                                  '<p>' + data[i]['Land'] + ", " + data[i]['PLZ'] + " " + data[i]['Ort'] + '</p>' +
                                  '<p>' + data[i]['Strasse'] + '</p>' +
                                  mail +
                                  url;
                    var window = new google.maps.InfoWindow({
                                    content: c
                                });
                    marker.addListener('click', (function(map,marker, window){
                        return function() {
                            window.open(map, marker);
                        };
                    })(map, marker, window));
                    markers.push(marker);
                } else {
                    console.log("Not valid: " + data[i]);
                }
            }
            console.log(displayed + " displayed");
        },
        error: function(data) {
            console.log("ERROR!");
        }
    });
}
</code>```

So here is my whole code. The output array of my user-load.php has no errors. It works well, the result->num_rows is equals to the markers array length, but there are only like ~50 markers out of 557. What is the problem? I'm a beginner of JS and it's a bit confusing at the start.

答:
FIXED it.
Such a dumb mistake, searched it for like 5 hours.
Instead of

```<code>parseInt(data[i]['lng'])
</code>```

this:

```<code>parseFloat(data[i]['lng'])
</code>```

Now everything works well. Maybe I can help someone :)

Body:
I'm currently working with the Google Maps Javascript API to display all locations for the customers. It has worked well with PHP only, but now I'm working with the $.ajax() function.

function init() {
    map = new google.maps.Map(document.getElementById('googleMap'), {
            zoom: 6,
            center: {lng:  10.1293945, lat: 51.1793430}
          });
    var markers = addMarkers('', '', 'POST');
    return map;
}

function addMarkers(f, s, method) {
    console.log("Filter: " + f);
    $.ajax({
        url:      'user-load.php' + "?echo=1&method=" + method + "&filter=" + f + "&search=" + s,

        dataType: 'json',
        success: function(data) {
            var count = data['length'];
            console.log(count + " found");
            var displayed = 0;
            for(var i = 0; i < count;  i++) {
                if(data[i]['lat'] != 0 && data[i]['lat'] != 0) {
                    displayed++;
                    var name = data[i]['first'] + " " + data[i]['last'];
                    var url = '';
                    if(data[i]['url'] != '') {
                        url = "
Website: " + data[i]['url'] + "
";
                    }
                    var mail = '';
                    if(data[i]['mail'] != '') {
                        url = "
E-Mail: " + data[i]['mail'] + "
";
                    }
                    var marker = new google.maps.Marker({
                        position:{lng: parseInt(data[i]['lng']), lat: parseInt(data[i]['lat'])},
                        map: map,
                        title: name + ", " + data[i]['title'],
                        animation: google.maps.Animation.DROP
                    });
                    var c = '
' + name + '
' +
                                  '
' + data[i]['title'] + '
' +
                                  '
' + data[i]['Land'] + ", " + data[i]['PLZ'] + " " + data[i]['Ort'] + '
' +
                                  '
' + data[i]['Strasse'] + '
' +
                                  mail +
                                  url;
                    var window = new google.maps.InfoWindow({
                                    content: c
                                });
                    marker.addListener('click', (function(map,marker, window){
                        return function() {
                            window.open(map, marker);
                        };
                    })(map, marker, window));
                    markers.push(marker);
                } else {
                    console.log("Not valid: " + data[i]);
                }
            }
            console.log(displayed + " displayed");
        },
        error: function(data) {
            console.log("ERROR!");
        }
    });
}

So here is my whole code. The output array of my user-load.php has no errors. It works well, the result->num_rows is equals to the markers array length, but there are only like ~50 markers out of 557. What is the problem? I'm a beginner of JS and it's a bit confusing at the start.

Body:
FIXED it.
Such a dumb mistake, searched it for like 5 hours.
Instead of

parseInt(data[i]['lng'])

this:

parseFloat(data[i]['lng'])

Now everything works well. Maybe I can help someone :)


问:
Code challenge: finding the divisible in a list
I am playing a code challenge. Simply speaking, the problem is:

Given a list L (max length is of the order of 1000) containing positive integers.
  Find the number of "Lucky Triples", which is L[i] divides L[j], and L[j] divides L[k].

for example, [1,2,3,4,5,6] should give the answer 3 because [1,2,4], [1,2,6],[1,3,6]

My attempt:

Sort the list. (let say there are n elements)

3 For loops: i, j, k (i from 1 to n-2), (j from i+1 to n-1), (k from j+1 to n)

only if L[j] % L[i] == 0, the k for loop will be executed

The algorithm seems to give the correct answer. But the challenge said that my code exceeded the time limit. I tried on my computer for the list [1,2,3,...,2000], count = 40888(I guess it is correct). The time is around 5 second.

Is there any faster way to do that?

This is the code I have written in python.

```<code>def answer(l):
    l.sort()
    cnt = 0
    if len(l) == 2:
        return cnt
    for i in range(len(l)-2):
        for j in range(1,len(l)-1-i):
            if (l[i+j]%l[i] == 0):
                for k in range(1,len(l)-j-i):
                    if (l[i+j+k]%l[i+j] == 0):
                        cnt += 1

    return cnt
</code>```

答:
I'll give you just an idea, the implementation should be up to you:

Initialize the global counter to zero.

Sort the list, starting with smallest number.

Create a list of integers (one entry per number with same index).

Iterate through each number (index i), and do the following:

Check for dividers at positions 0 to i-1.

Store the number of dividers in the list at the position i.

Fetch the number of dividers from the list for each divider, and add each number to the global counter.

Unless you finished, go to 3rd.

Your result should be in the global counter.

Body:
I am playing a code challenge. Simply speaking, the problem is:

Given a list L (max length is of the order of 1000) containing positive integers.
  Find the number of "Lucky Triples", which is L[i] divides L[j], and L[j] divides L[k].

for example, [1,2,3,4,5,6] should give the answer 3 because [1,2,4], [1,2,6],[1,3,6]

My attempt:

Sort the list. (let say there are n elements)

3 For loops: i, j, k (i from 1 to n-2), (j from i+1 to n-1), (k from j+1 to n)

only if L[j] % L[i] == 0, the k for loop will be executed

The algorithm seems to give the correct answer. But the challenge said that my code exceeded the time limit. I tried on my computer for the list [1,2,3,...,2000], count = 40888(I guess it is correct). The time is around 5 second.

Is there any faster way to do that?

This is the code I have written in python.

def answer(l):
    l.sort()
    cnt = 0
    if len(l) == 2:
        return cnt
    for i in range(len(l)-2):
        for j in range(1,len(l)-1-i):
            if (l[i+j]%l[i] == 0):
                for k in range(1,len(l)-j-i):
                    if (l[i+j+k]%l[i+j] == 0):
                        cnt += 1

    return cnt


问:
Issue defining traefik labelselector in traefik.toml vs. container arg
I have a traefik.toml file defined as part of my traefik configmap. The snippet below is the kubernetes endpoint configuration with a labelselector defined:

```<code>[kubernetes]
  labelselector = "expose=internal"
</code>```

When I check the traefik status page in this configuration, I see all ingresses listed, not just those with the label "expose: internal" defined.

If I set the kubernetes.labelselector as a container argument to my deployment, however, only the ingresses with the matching label are displayed on the traefik status page as expected:

```<code>- --kubernetes.labelselector=expose=internal
</code>```

According to the Kubernetes Ingress Backend documentation, any label selector format valid in the label selector section of the Labels and Selectors should be valid in the traefik.toml file. I have experimented with both the equality baed (as shown above) and the set-based (to determine if the "expose" label is present, only), neither of which have worked in the toml. The set-based does not seem to work in the container args, but the equality statements do.

I'm assuming there is some issue related to how I've formatted the kubernetes endpoint within the traefik.toml file. Before reporting this issue to github I was hoping someone could clarify the documentation and/or correct any mistakes I've made in the toml file format.

答:
As you have already found out, not passing --kubernetes makes things work for you. The reason is that this parameter not only enables the Kubernetes provider but also sets all defaults. As documented, the command-line arguments take precedence over the configuration file; thus, any non-default Kubernetes parameters specified in the TOML file will be overridden by the default values implied through --kubernetes. This is intended (albeit not ideally documented) behavior.

You can still mix and match both command-line and TOML configuration parameters for Kubernetes (or any other provider, for that matter) by omitting --kubernetes. For instance, you could have your example TOML file

```<code>[kubernetes]
  labelselector = "expose=internal"
</code>```

and then invoke Traefik like

```<code>./traefik --configfile=config.yaml --kubernetes.namespaces=other
</code>```

which will cause Traefik to use both the custom label selector expose=internal and watch the namespace other.

I have submitted a PR to clarify the behavior of the command-line provider-enabling parameters with regards to the provider default values.

Body:
I have a traefik.toml file defined as part of my traefik configmap. The snippet below is the kubernetes endpoint configuration with a labelselector defined:

[kubernetes]
  labelselector = "expose=internal"

When I check the traefik status page in this configuration, I see all ingresses listed, not just those with the label "expose: internal" defined.

If I set the kubernetes.labelselector as a container argument to my deployment, however, only the ingresses with the matching label are displayed on the traefik status page as expected:

- --kubernetes.labelselector=expose=internal

According to the Kubernetes Ingress Backend documentation, any label selector format valid in the label selector section of the Labels and Selectors should be valid in the traefik.toml file. I have experimented with both the equality baed (as shown above) and the set-based (to determine if the "expose" label is present, only), neither of which have worked in the toml. The set-based does not seem to work in the container args, but the equality statements do.

I'm assuming there is some issue related to how I've formatted the kubernetes endpoint within the traefik.toml file. Before reporting this issue to github I was hoping someone could clarify the documentation and/or correct any mistakes I've made in the toml file format.

Body:
As you have already found out, not passing --kubernetes makes things work for you. The reason is that this parameter not only enables the Kubernetes provider but also sets all defaults. As documented, the command-line arguments take precedence over the configuration file; thus, any non-default Kubernetes parameters specified in the TOML file will be overridden by the default values implied through --kubernetes. This is intended (albeit not ideally documented) behavior.

You can still mix and match both command-line and TOML configuration parameters for Kubernetes (or any other provider, for that matter) by omitting --kubernetes. For instance, you could have your example TOML file

[kubernetes]
  labelselector = "expose=internal"

and then invoke Traefik like

./traefik --configfile=config.yaml --kubernetes.namespaces=other

which will cause Traefik to use both the custom label selector expose=internal and watch the namespace other.

I have submitted a PR to clarify the behavior of the command-line provider-enabling parameters with regards to the provider default values.


问:
Does .net core dependency injection support Lazy<T>
I am trying to use the generic Lazy class to instantiate a costly class with .net core dependency injection extension. I have registered the IRepo type, but I'm not sure what the registration of the Lazy class would look like or if it is even supported. As a workaround I have used this method http://mark-dot-net.blogspot.com/2009/08/lazy-loading-of-dependencies-in-unity.html

config:

```<code>public void ConfigureService(IServiceCollection services)
{
    services.AddTransient<IRepo, Repo>();
    //register lazy
}
</code>```

controller:

```<code>public class ValuesController : Controller
{
    private Lazy<IRepo> _repo;

    public ValuesController (Lazy<IRepo> repo)
    {
        _repo = repo;
    }

    [HttpGet()]
    public IActionResult Get()
    {
         //Do something cheap
         if(something)
             return Ok(something);
         else
             return Ok(repo.Value.Get());
    }
}
</code>```

答:
You only need to add a registration for a factory method that creates the Lazy<IRepo> object.

```<code>public void ConfigureService(IServiceCollection services)
{
    services.AddTransient<IRepo, Repo>();
    services.AddTransient<Lazy<IRepo>>(provider => new Lazy<IRepo>(provider.GetService<IRepo>));
}
</code>```

Body:
I am trying to use the generic Lazy class to instantiate a costly class with .net core dependency injection extension. I have registered the IRepo type, but I'm not sure what the registration of the Lazy class would look like or if it is even supported. As a workaround I have used this method http://mark-dot-net.blogspot.com/2009/08/lazy-loading-of-dependencies-in-unity.html

config:

public void ConfigureService(IServiceCollection services)
{
    services.AddTransient<IRepo, Repo>();
    //register lazy
}

controller:

public class ValuesController : Controller
{
    private Lazy<IRepo> _repo;

    public ValuesController (Lazy<IRepo> repo)
    {
        _repo = repo;
    }

    [HttpGet()]
    public IActionResult Get()
    {
         //Do something cheap
         if(something)
             return Ok(something);
         else
             return Ok(repo.Value.Get());
    }
}

Body:
You only need to add a registration for a factory method that creates the Lazy<IRepo> object.

public void ConfigureService(IServiceCollection services)
{
    services.AddTransient<IRepo, Repo>();
    services.AddTransient<Lazy<IRepo>>(provider => new Lazy<IRepo>(provider.GetService<IRepo>));
}


问:
Webpack not reading @ symbol - Unexpected character '@' (4:0)
Why am I receiving this error? I also have bootstrap files being imported into the main custom.scss file.  Not sure if this is creating any issues?

I'm receiving this error when attempting to use the scss loader in
            webpack:

```<code>        Unexpected character '@' (4:0)
        You may need an appropriate loader to handle this file type.
        |
        |
        | @import "_bootstrap";
        | @import "spinner";
        | @import "navigations";
         @ ./js/app.js 5:0-30

        Here is my webpack.config.js script:

        var path = require('path');
        var webpack = require('webpack');

        module.exports = {
            entry: './js/app.js',
            output: {
                path: __dirname,
                filename: 'js/bundle.js'
            },

            watch: true,
            module: {
                rules: [
                    {
                        test: /\.(jpe?g|png|gif|svg)$/i,
                        //test: /\.(png|jpg)$/,
                        use: 'file-loader'
                    }
                ],
                loaders: [
                    {
                    test: /.jsx?$/,
                    loader: 'babel-loader',
                    exclude: /node_modules/,
                    query: {
                    presets: ['es2015', 'react']
                    }
                  },
                  {
                  test: /.scss?$/,
                  loader: 'style-loader!css-loader!sass-loader'

                  }

                ]
            },
        };

        Here is my require script located in my app.js file:

        require('../scss/custom.scss');
</code>```

答:
I believe you need to move the loader rule into module:

```<code>module.exports = {
  entry: './js/app.js',
  output: {
    path: __dirname,
    filename: 'js/bundle.js'
  },

  watch: true,
  module: {
    rules: [
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        //test: /\.(png|jpg)$/,
        use: 'file-loader'
      },
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      },
      {
        test: /\.scss?$/,
        loader: 'style-loader!css-loader!sass-loader'

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

If that doesn't work, you can try the use to specify the loaders:

```<code>module.exports = {
  module: {
    rules: [
      {
        test: /\.scss?$/,
        use: [
          { loader: 'style-loader' },
          { loader: 'css-loader' },
          { loader: 'sass-loader' },
        ]
      }
    ]
  }
};
</code>```

Body:
Why am I receiving this error? I also have bootstrap files being imported into the main custom.scss file.  Not sure if this is creating any issues?

I'm receiving this error when attempting to use the scss loader in
            webpack:

        Unexpected character '@' (4:0)
        You may need an appropriate loader to handle this file type.
        |
        |
        | @import "_bootstrap";
        | @import "spinner";
        | @import "navigations";
         @ ./js/app.js 5:0-30

        Here is my webpack.config.js script:

        var path = require('path');
        var webpack = require('webpack');

        module.exports = {
            entry: './js/app.js',
            output: {
                path: __dirname,
                filename: 'js/bundle.js'
            },

            watch: true,
            module: {
                rules: [
                    {
                        test: /\.(jpe?g|png|gif|svg)$/i,
                        //test: /\.(png|jpg)$/,
                        use: 'file-loader'
                    }
                ],
                loaders: [
                    {
                    test: /.jsx?$/,
                    loader: 'babel-loader',
                    exclude: /node_modules/,
                    query: {
                    presets: ['es2015', 'react']
                    }
                  },
                  {
                  test: /.scss?$/,
                  loader: 'style-loader!css-loader!sass-loader'

                  }

                ]
            },
        };

        Here is my require script located in my app.js file:

        require('../scss/custom.scss');

Body:
I believe you need to move the loader rule into module:

module.exports = {
  entry: './js/app.js',
  output: {
    path: __dirname,
    filename: 'js/bundle.js'
  },

  watch: true,
  module: {
    rules: [
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        //test: /\.(png|jpg)$/,
        use: 'file-loader'
      },
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      },
      {
        test: /\.scss?$/,
        loader: 'style-loader!css-loader!sass-loader'

      }
    ]
  }
};

If that doesn't work, you can try the use to specify the loaders:

module.exports = {
  module: {
    rules: [
      {
        test: /\.scss?$/,
        use: [
          { loader: 'style-loader' },
          { loader: 'css-loader' },
          { loader: 'sass-loader' },
        ]
      }
    ]
  }
};