问:
How to Update Progressbar in GridView Adapter using BroadcastReceiver?
I want to perform have scenario,

I am using Custom TouchyGridView
Everything was working fine.

But now I want to add new functionality.

I want to download APK file in the background. So When downloading start, I want to show new icon in grid view and progress bar upon new grade item.

*I know How to download from the server.

And ProgressBar should be updating using progressbar.setProgress(progress);

How can I do this?

I tried BroadCastReceiver, but didn't get success, because my broadcast is in MainActivity and View is in the adapter, So How can I update view of Adapter class using BroadCastReceiver?

grid_item.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dp">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/grid_app_image"
            android:layout_width="@dimen/icon_width"
            android:layout_height="@dimen/icon_height"
            android:layout_gravity="center_horizontal"
            android:src="@drawable/ic_launcher" />

        <ProgressBar
            android:id="@+id/progressBar"
            style="@style/Widget.AppCompat.ProgressBar.Horizontal"
            android:layout_width="@dimen/icon_width"
            android:layout_height="@dimen/icon_height"
            android:progressDrawable="@drawable/circular" />
    </RelativeLayout>

    <TextView
        android:id="@+id/grid_app_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="5px"
        android:gravity="center_horizontal"
        android:text="app"
        android:textColor="@color/content"
        android:textSize="18sp" />

</LinearLayout>
</code>```

HomeScreenAppGridAdapter.java

```<code>public class HomeScreenAppGridAdapter extends BaseAdapter implements
        OnClickListener {

    private Context mContext;
    private List<KioskAppDetail> mAppList;

    private PackageManager mPackageManager;
    private String tag = "GridAdapter";

    // Constructor to initialize values
    public HomeScreenAppGridAdapter(Context context,
                                    List<KioskAppDetail> appList) {
        mContext = context;
        mAppList = appList;

        mPackageManager = mContext.getPackageManager();
    }

    @Override
    public int getCount() {
        // Number of times getView method call depends upon gridValues.length
        return mAppList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    // Number of times getView method call depends upon gridValues.length
    public View getView(final int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View gridView;

//         if (convertView == null) {

        gridView = inflater.inflate(R.layout.grid_item, null);
        final TextView textView = (TextView) gridView
                .findViewById(R.id.grid_app_label);
        final ImageView imageView = (ImageView) gridView
                .findViewById(R.id.grid_app_image);
        ProgressBar progressBar = (ProgressBar) gridView
                .findViewById(R.id.progressBar);
        if (!mAppList.get(position).getAppLable().toString()
                .equalsIgnoreCase("Peripheral Settings")) {

            /*int color = Color.parseColor(Util.getStringDefaultPrefValue(
                    mContext, Util.TEXT_COLOR, Util.TEXT_COLOR_DEFAULT));*/

            progressBar.setVisibility(View.GONE);
            String iconSizePer = Util.getStringDefaultPrefValue(mContext, Util.ICON_SIZE_DP, Util.DEF_ICON_SIZE_DP);
            if(iconSizePer != null) {
                if(!iconSizePer.trim().isEmpty()) {
                    int originalIconSize = 60; // This is 100% Icon Size
                    int iconSize = (Integer.parseInt(iconSizePer) * originalIconSize) / 100;
                    int pixel = dpToPx(iconSize);
                    imageView.getLayoutParams().height = pixel;
                    imageView.getLayoutParams().width = pixel;
                    imageView.requestLayout();
                }
            }

            String textSizePer = Util.getStringDefaultPrefValue(mContext, Util.TEXT_SIZE_SP, Util.DEF_TEXT_SIZE_SP);
            if(textSizePer != null) {
                if(!textSizePer.trim().isEmpty()) {
                    int originalTextSize = 18; // This is 100% text Size
                    int textSize = (Integer.parseInt(textSizePer) * originalTextSize) / 100;
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
                } else {
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                }
            }

            int color;
            /*= Color.parseColor(Util.getStringDefaultPrefValue(
                    mContext, Util.TEXT_COLOR, Util.TEXT_COLOR_DEFAULT));
*/
            String selectedColor = Util.getStringDefaultPrefValue(mContext, Util.TEXT_COLOR, Util.TEXT_COLOR_DEFAULT);
            if(selectedColor.equalsIgnoreCase("")) {
                color = Color.parseColor(mContext.getString(R.string.black));
            } else if (selectedColor.equalsIgnoreCase("Black")) {
                color = Color.parseColor(mContext.getString(R.string.black));
            } else if (selectedColor.equalsIgnoreCase("Blue")) {
                color = Color.parseColor(mContext.getString(R.string.blue));
            } else if (selectedColor.equalsIgnoreCase("Cyan")) {
                color = Color.parseColor(mContext.getString(R.string.cyan));
            } else if (selectedColor.equalsIgnoreCase("Dark Grey")) {
                color = Color.parseColor(mContext.getString(R.string.dark_grey));
            } else if (selectedColor.equalsIgnoreCase("Grey")) {
                color = Color.parseColor(mContext.getString(R.string.grey));
            } else if (selectedColor.equalsIgnoreCase("Light Grey")) {
                color = Color.parseColor(mContext.getString(R.string.light_grey_text));
            } else if (selectedColor.equalsIgnoreCase("Green")) {
                color = Color.parseColor(mContext.getString(R.string.green));
            } else if (selectedColor.equalsIgnoreCase("Magenta")) {
                color = Color.parseColor(mContext.getString(R.string.magenta));
            } else if (selectedColor.equalsIgnoreCase("Red")) {
                color = Color.parseColor(mContext.getString(R.string.red));
            } else if (selectedColor.equalsIgnoreCase("White")) {
                color = Color.parseColor(mContext.getString(R.string.white));
            } else if (selectedColor.equalsIgnoreCase("Yellow")) {
                color = Color.parseColor(mContext.getString(R.string.yellow));
            } else {
                color = Color.parseColor(mContext.getString(R.string.black));
            }

            textView.setTextColor(color);
            textView.setText(mAppList.get(position).getAppLable());
            // Log.d(tag, mAppList.get(position).getAppLable() + "App lable"
            // + mAppList.size() + "App list size" + position);

            // if (TextUtils.isEmpty(mAppList.get(position).getAppIcon())) {
            // no custom icon, use app's icon
            imageView.setImageDrawable(mAppList.get(position).getDefaultAppIcon());
            // }

            final OnClickListener onClickListener = new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(tag, "app icon clicked ["
                            + mAppList.get(position).getPackageName());

                    Intent i = mPackageManager
                            .getLaunchIntentForPackage(mAppList.get(position)
                                    .getPackageName());
                    mContext.startActivity(i);

                }
            };
            imageView.setOnClickListener(onClickListener);

        } else {

            Log.d(tag, "In If Home Screen Adapter");

            int color;
            /*= Color.parseColor(Util.getStringDefaultPrefValue(
                    mContext, Util.TEXT_COLOR, Util.TEXT_COLOR_DEFAULT));
*/
            String selectedColor = Util.getStringDefaultPrefValue(mContext, Util.TEXT_COLOR, Util.TEXT_COLOR_DEFAULT);
            if(selectedColor.equalsIgnoreCase("")) {
                color = Color.parseColor(mContext.getString(R.string.black));
            } else if (selectedColor.equalsIgnoreCase("Black")) {
                color = Color.parseColor(mContext.getString(R.string.black));
            } else if (selectedColor.equalsIgnoreCase("Blue")) {
                color = Color.parseColor(mContext.getString(R.string.blue));
            } else if (selectedColor.equalsIgnoreCase("Cyan")) {
                color = Color.parseColor(mContext.getString(R.string.cyan));
            } else if (selectedColor.equalsIgnoreCase("Dark Grey")) {
                color = Color.parseColor(mContext.getString(R.string.dark_grey));
            } else if (selectedColor.equalsIgnoreCase("Grey")) {
                color = Color.parseColor(mContext.getString(R.string.grey));
            } else if (selectedColor.equalsIgnoreCase("Light Grey")) {
                color = Color.parseColor(mContext.getString(R.string.light_grey_text));
            } else if (selectedColor.equalsIgnoreCase("Green")) {
                color = Color.parseColor(mContext.getString(R.string.green));
            } else if (selectedColor.equalsIgnoreCase("Magenta")) {
                color = Color.parseColor(mContext.getString(R.string.magenta));
            } else if (selectedColor.equalsIgnoreCase("Red")) {
                color = Color.parseColor(mContext.getString(R.string.red));
            } else if (selectedColor.equalsIgnoreCase("White")) {
                color = Color.parseColor(mContext.getString(R.string.white));
            } else if (selectedColor.equalsIgnoreCase("Yellow")) {
                color = Color.parseColor(mContext.getString(R.string.yellow));
            } else {
                color = Color.parseColor(mContext.getString(R.string.black));
            }
            textView.setTextColor(color);
            textView.setText(mAppList.get(position).getAppLable());

            // if
            // (TextUtils.isEmpty(mAppList.get(position).getAppIcon()))
            // {
            // no custom icon, use app's icon
            imageView.setImageResource(R.drawable.icon_settings);
            // }

            final OnClickListener onClickListenerr = new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(tag, "app icon clicked ["
                            + mAppList.get(position).getPackageName());
                    // Intent i =
                    // mPackageManager.getLaunchIntentForPackage(mAppList
                    // .get(position).getPackageName());
                    // mContext.startActivity(i);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        boolean status_for_useage_access_on_app_click = Util
                                .systemSettingsOnUsage(mContext);
                        if (status_for_useage_access_on_app_click == true) {
                            // Intent i = mPackageManager
                            // .getLaunchIntentForPackage(mAppList
                            // .get(position)
                            // .getPackageName());
                            // mContext.startActivity(i);
                            Intent intent = new Intent(
                                    mContext,
                                    net.intricare.allowedsettings.PeripheralSettingsActivity.class);
                            mContext.startActivity(intent);
                        } else {
                            Util.launchUsageAccessDialog(mContext);
                        }
                    } else {
                        Intent intent = new Intent(
                                mContext,
                                net.intricare.allowedsettings.PeripheralSettingsActivity.class);
                        mContext.startActivity(intent);
                    }
                }
            };
            // --------------------------------------------- //
            imageView.setOnClickListener(onClickListenerr);

        }

        // } else {
        // gridView = (View) convertView;
        // }
        /**
         * duplicate code
         */
        // --------------------------------------------- //

        /*if (!mAppList.get(position).getAppLable().toString()
                .equalsIgnoreCase("Peripheral Settings")) {
            int color = Color.parseColor(Util.getStringDefaultPrefValue(
                    mContext, "text_color", "black"));

            textView.setTextColor(color);
            textView.setText(mAppList.get(position).getAppLable());
            // Log.d(tag, mAppList.get(position).getAppLable() + "App lable"
            // + mAppList.size() + "App list size duplicate code"
            // + position);

            // if (TextUtils.isEmpty(mAppList.get(position).getAppIcon())) {
            // no custom icon, use app's icon
            imageView.setImageDrawable(mAppList.get(position)
                    .getDefaultAppIcon());
            // }

            final OnClickListener onClickListener = new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(tag, "app icon clicked ["
                            + mAppList.get(position).getPackageName());
                    try {
                        Intent i = mPackageManager
                                .getLaunchIntentForPackage(mAppList.get(position)
                                        .getPackageName());
                        mContext.startActivity(i);
                    } catch (NullPointerException ex) {
                        ex.printStackTrace();
                    }

                }
            };
            imageView.setOnClickListener(onClickListener);
        } else {

            TextView textVieww = (TextView) gridView
                    .findViewById(R.id.grid_app_label);

            int color = Color.parseColor(Util.getStringDefaultPrefValue(
                    mContext, "text_color", "black"));
            textVieww.setTextColor(color);
            textVieww.setText(mAppList.get(position).getAppLable());

            ImageView imageVieww = (ImageView) gridView
                    .findViewById(R.id.grid_app_image);

            imageVieww.setImageResource(R.drawable.icon_settings);

            final OnClickListener onClickListenerr = new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(tag, "app icon clicked ["
                            + mAppList.get(position).getPackageName());

                    if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                        boolean status_for_useage_access_on_app_click = Util
                                .systemSettingsOnUsage(mContext);
                        if (status_for_useage_access_on_app_click == true) {

                            Intent intent = new Intent(
                                    mContext,
                                    net.intricare.allowedsettings.PeripheralSettingsActivity.class);
                            mContext.startActivity(intent);
                        } else {
                            Util.launchUsageAccessDialog(mContext);
                        }
                    } else {
                        Intent intent = new Intent(
                                mContext,
                                net.intricare.allowedsettings.PeripheralSettingsActivity.class);
                        mContext.startActivity(intent);
                    }
                }
            };
            // --------------------------------------------- //
            imageVieww.setOnClickListener(onClickListenerr);

        }*/

        return gridView;
    }

    public static int pxToDp(int px) {
        return (int) (px / Resources.getSystem().getDisplayMetrics().density);
    }

    public static int dpToPx(int dp) {
        return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
    }

    @Override
    public void onClick(View v) {
        Log.i(tag, "touch event");
    }
}
</code>```

HomeActivity.java

```<code>TouchyGridView mGridView;
 mGridView = (TouchyGridView) findViewById(R.id.apps_grid);

 LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MESSAGE_PROGRESS);
        bManager.registerReceiver(broadcastReceiver, intentFilter);

 mGridView.setAdapter(new HomeScreenAppGridAdapter(HomeActivity.this, mKioskAppsList));
        mGridView.setOnNoItemClickListener(this);
        mGridView.setOnItemClickListener(this);

        private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if(intent.getAction().equals(MESSAGE_PROGRESS)){
                //initHomeScreenUI(true);

                /*if(download.getProgress() == 100){
                    mProgressText.setText("File Download Complete");

                } else {
                    mProgressText.setText(String.format("Downloaded (%d/%d) MB",download.getCurrentFileSize(),download.getTotalFileSize()));
                }*/
            }
        }
    };

    // When Download Start, I am sending broadcast using below code

    Intent intent = new Intent(HomeActivity.MESSAGE_PROGRESS);
        intent.putExtra("download",download);
        LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);
</code>```

答:
Please follow below steps to solve the issue.

First Make sure that Adapter class and activity code is in same class.

When You start download send one broadcast receiver for Update UI and manage flag according to that.

And Set Visibility true for the Progressbar.

Now update a progress bar.

Hide Progressbar when download finish.

Body:
I want to perform have scenario,

I am using Custom TouchyGridView
Everything was working fine.

But now I want to add new functionality.

I want to download APK file in the background. So When downloading start, I want to show new icon in grid view and progress bar upon new grade item.

*I know How to download from the server.

And ProgressBar should be updating using progressbar.setProgress(progress);

How can I do this?

I tried BroadCastReceiver, but didn't get success, because my broadcast is in MainActivity and View is in the adapter, So How can I update view of Adapter class using BroadCastReceiver?

grid_item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dp">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/grid_app_image"
            android:layout_width="@dimen/icon_width"
            android:layout_height="@dimen/icon_height"
            android:layout_gravity="center_horizontal"
            android:src="@drawable/ic_launcher" />

        <ProgressBar
            android:id="@+id/progressBar"
            style="@style/Widget.AppCompat.ProgressBar.Horizontal"
            android:layout_width="@dimen/icon_width"
            android:layout_height="@dimen/icon_height"
            android:progressDrawable="@drawable/circular" />
    </RelativeLayout>

    <TextView
        android:id="@+id/grid_app_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="5px"
        android:gravity="center_horizontal"
        android:text="app"
        android:textColor="@color/content"
        android:textSize="18sp" />

</LinearLayout>

HomeScreenAppGridAdapter.java

public class HomeScreenAppGridAdapter extends BaseAdapter implements
        OnClickListener {

    private Context mContext;
    private List<KioskAppDetail> mAppList;

    private PackageManager mPackageManager;
    private String tag = "GridAdapter";

    // Constructor to initialize values
    public HomeScreenAppGridAdapter(Context context,
                                    List<KioskAppDetail> appList) {
        mContext = context;
        mAppList = appList;

        mPackageManager = mContext.getPackageManager();
    }

    @Override
    public int getCount() {
        // Number of times getView method call depends upon gridValues.length
        return mAppList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    // Number of times getView method call depends upon gridValues.length
    public View getView(final int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View gridView;

//         if (convertView == null) {

        gridView = inflater.inflate(R.layout.grid_item, null);
        final TextView textView = (TextView) gridView
                .findViewById(R.id.grid_app_label);
        final ImageView imageView = (ImageView) gridView
                .findViewById(R.id.grid_app_image);
        ProgressBar progressBar = (ProgressBar) gridView
                .findViewById(R.id.progressBar);
        if (!mAppList.get(position).getAppLable().toString()
                .equalsIgnoreCase("Peripheral Settings")) {

            /*int color = Color.parseColor(Util.getStringDefaultPrefValue(
                    mContext, Util.TEXT_COLOR, Util.TEXT_COLOR_DEFAULT));*/

            progressBar.setVisibility(View.GONE);
            String iconSizePer = Util.getStringDefaultPrefValue(mContext, Util.ICON_SIZE_DP, Util.DEF_ICON_SIZE_DP);
            if(iconSizePer != null) {
                if(!iconSizePer.trim().isEmpty()) {
                    int originalIconSize = 60; // This is 100% Icon Size
                    int iconSize = (Integer.parseInt(iconSizePer) * originalIconSize) / 100;
                    int pixel = dpToPx(iconSize);
                    imageView.getLayoutParams().height = pixel;
                    imageView.getLayoutParams().width = pixel;
                    imageView.requestLayout();
                }
            }

            String textSizePer = Util.getStringDefaultPrefValue(mContext, Util.TEXT_SIZE_SP, Util.DEF_TEXT_SIZE_SP);
            if(textSizePer != null) {
                if(!textSizePer.trim().isEmpty()) {
                    int originalTextSize = 18; // This is 100% text Size
                    int textSize = (Integer.parseInt(textSizePer) * originalTextSize) / 100;
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
                } else {
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                }
            }

            int color;
            /*= Color.parseColor(Util.getStringDefaultPrefValue(
                    mContext, Util.TEXT_COLOR, Util.TEXT_COLOR_DEFAULT));
*/
            String selectedColor = Util.getStringDefaultPrefValue(mContext, Util.TEXT_COLOR, Util.TEXT_COLOR_DEFAULT);
            if(selectedColor.equalsIgnoreCase("")) {
                color = Color.parseColor(mContext.getString(R.string.black));
            } else if (selectedColor.equalsIgnoreCase("Black")) {
                color = Color.parseColor(mContext.getString(R.string.black));
            } else if (selectedColor.equalsIgnoreCase("Blue")) {
                color = Color.parseColor(mContext.getString(R.string.blue));
            } else if (selectedColor.equalsIgnoreCase("Cyan")) {
                color = Color.parseColor(mContext.getString(R.string.cyan));
            } else if (selectedColor.equalsIgnoreCase("Dark Grey")) {
                color = Color.parseColor(mContext.getString(R.string.dark_grey));
            } else if (selectedColor.equalsIgnoreCase("Grey")) {
                color = Color.parseColor(mContext.getString(R.string.grey));
            } else if (selectedColor.equalsIgnoreCase("Light Grey")) {
                color = Color.parseColor(mContext.getString(R.string.light_grey_text));
            } else if (selectedColor.equalsIgnoreCase("Green")) {
                color = Color.parseColor(mContext.getString(R.string.green));
            } else if (selectedColor.equalsIgnoreCase("Magenta")) {
                color = Color.parseColor(mContext.getString(R.string.magenta));
            } else if (selectedColor.equalsIgnoreCase("Red")) {
                color = Color.parseColor(mContext.getString(R.string.red));
            } else if (selectedColor.equalsIgnoreCase("White")) {
                color = Color.parseColor(mContext.getString(R.string.white));
            } else if (selectedColor.equalsIgnoreCase("Yellow")) {
                color = Color.parseColor(mContext.getString(R.string.yellow));
            } else {
                color = Color.parseColor(mContext.getString(R.string.black));
            }

            textView.setTextColor(color);
            textView.setText(mAppList.get(position).getAppLable());
            // Log.d(tag, mAppList.get(position).getAppLable() + "App lable"
            // + mAppList.size() + "App list size" + position);

            // if (TextUtils.isEmpty(mAppList.get(position).getAppIcon())) {
            // no custom icon, use app's icon
            imageView.setImageDrawable(mAppList.get(position).getDefaultAppIcon());
            // }

            final OnClickListener onClickListener = new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(tag, "app icon clicked ["
                            + mAppList.get(position).getPackageName());

                    Intent i = mPackageManager
                            .getLaunchIntentForPackage(mAppList.get(position)
                                    .getPackageName());
                    mContext.startActivity(i);

                }
            };
            imageView.setOnClickListener(onClickListener);

        } else {

            Log.d(tag, "In If Home Screen Adapter");

            int color;
            /*= Color.parseColor(Util.getStringDefaultPrefValue(
                    mContext, Util.TEXT_COLOR, Util.TEXT_COLOR_DEFAULT));
*/
            String selectedColor = Util.getStringDefaultPrefValue(mContext, Util.TEXT_COLOR, Util.TEXT_COLOR_DEFAULT);
            if(selectedColor.equalsIgnoreCase("")) {
                color = Color.parseColor(mContext.getString(R.string.black));
            } else if (selectedColor.equalsIgnoreCase("Black")) {
                color = Color.parseColor(mContext.getString(R.string.black));
            } else if (selectedColor.equalsIgnoreCase("Blue")) {
                color = Color.parseColor(mContext.getString(R.string.blue));
            } else if (selectedColor.equalsIgnoreCase("Cyan")) {
                color = Color.parseColor(mContext.getString(R.string.cyan));
            } else if (selectedColor.equalsIgnoreCase("Dark Grey")) {
                color = Color.parseColor(mContext.getString(R.string.dark_grey));
            } else if (selectedColor.equalsIgnoreCase("Grey")) {
                color = Color.parseColor(mContext.getString(R.string.grey));
            } else if (selectedColor.equalsIgnoreCase("Light Grey")) {
                color = Color.parseColor(mContext.getString(R.string.light_grey_text));
            } else if (selectedColor.equalsIgnoreCase("Green")) {
                color = Color.parseColor(mContext.getString(R.string.green));
            } else if (selectedColor.equalsIgnoreCase("Magenta")) {
                color = Color.parseColor(mContext.getString(R.string.magenta));
            } else if (selectedColor.equalsIgnoreCase("Red")) {
                color = Color.parseColor(mContext.getString(R.string.red));
            } else if (selectedColor.equalsIgnoreCase("White")) {
                color = Color.parseColor(mContext.getString(R.string.white));
            } else if (selectedColor.equalsIgnoreCase("Yellow")) {
                color = Color.parseColor(mContext.getString(R.string.yellow));
            } else {
                color = Color.parseColor(mContext.getString(R.string.black));
            }
            textView.setTextColor(color);
            textView.setText(mAppList.get(position).getAppLable());

            // if
            // (TextUtils.isEmpty(mAppList.get(position).getAppIcon()))
            // {
            // no custom icon, use app's icon
            imageView.setImageResource(R.drawable.icon_settings);
            // }

            final OnClickListener onClickListenerr = new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(tag, "app icon clicked ["
                            + mAppList.get(position).getPackageName());
                    // Intent i =
                    // mPackageManager.getLaunchIntentForPackage(mAppList
                    // .get(position).getPackageName());
                    // mContext.startActivity(i);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        boolean status_for_useage_access_on_app_click = Util
                                .systemSettingsOnUsage(mContext);
                        if (status_for_useage_access_on_app_click == true) {
                            // Intent i = mPackageManager
                            // .getLaunchIntentForPackage(mAppList
                            // .get(position)
                            // .getPackageName());
                            // mContext.startActivity(i);
                            Intent intent = new Intent(
                                    mContext,
                                    net.intricare.allowedsettings.PeripheralSettingsActivity.class);
                            mContext.startActivity(intent);
                        } else {
                            Util.launchUsageAccessDialog(mContext);
                        }
                    } else {
                        Intent intent = new Intent(
                                mContext,
                                net.intricare.allowedsettings.PeripheralSettingsActivity.class);
                        mContext.startActivity(intent);
                    }
                }
            };
            // --------------------------------------------- //
            imageView.setOnClickListener(onClickListenerr);

        }

        // } else {
        // gridView = (View) convertView;
        // }
        /**
         * duplicate code
         */
        // --------------------------------------------- //

        /*if (!mAppList.get(position).getAppLable().toString()
                .equalsIgnoreCase("Peripheral Settings")) {
            int color = Color.parseColor(Util.getStringDefaultPrefValue(
                    mContext, "text_color", "black"));

            textView.setTextColor(color);
            textView.setText(mAppList.get(position).getAppLable());
            // Log.d(tag, mAppList.get(position).getAppLable() + "App lable"
            // + mAppList.size() + "App list size duplicate code"
            // + position);

            // if (TextUtils.isEmpty(mAppList.get(position).getAppIcon())) {
            // no custom icon, use app's icon
            imageView.setImageDrawable(mAppList.get(position)
                    .getDefaultAppIcon());
            // }

            final OnClickListener onClickListener = new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(tag, "app icon clicked ["
                            + mAppList.get(position).getPackageName());
                    try {
                        Intent i = mPackageManager
                                .getLaunchIntentForPackage(mAppList.get(position)
                                        .getPackageName());
                        mContext.startActivity(i);
                    } catch (NullPointerException ex) {
                        ex.printStackTrace();
                    }

                }
            };
            imageView.setOnClickListener(onClickListener);
        } else {

            TextView textVieww = (TextView) gridView
                    .findViewById(R.id.grid_app_label);

            int color = Color.parseColor(Util.getStringDefaultPrefValue(
                    mContext, "text_color", "black"));
            textVieww.setTextColor(color);
            textVieww.setText(mAppList.get(position).getAppLable());

            ImageView imageVieww = (ImageView) gridView
                    .findViewById(R.id.grid_app_image);

            imageVieww.setImageResource(R.drawable.icon_settings);

            final OnClickListener onClickListenerr = new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(tag, "app icon clicked ["
                            + mAppList.get(position).getPackageName());

                    if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                        boolean status_for_useage_access_on_app_click = Util
                                .systemSettingsOnUsage(mContext);
                        if (status_for_useage_access_on_app_click == true) {

                            Intent intent = new Intent(
                                    mContext,
                                    net.intricare.allowedsettings.PeripheralSettingsActivity.class);
                            mContext.startActivity(intent);
                        } else {
                            Util.launchUsageAccessDialog(mContext);
                        }
                    } else {
                        Intent intent = new Intent(
                                mContext,
                                net.intricare.allowedsettings.PeripheralSettingsActivity.class);
                        mContext.startActivity(intent);
                    }
                }
            };
            // --------------------------------------------- //
            imageVieww.setOnClickListener(onClickListenerr);

        }*/

        return gridView;
    }

    public static int pxToDp(int px) {
        return (int) (px / Resources.getSystem().getDisplayMetrics().density);
    }

    public static int dpToPx(int dp) {
        return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
    }

    @Override
    public void onClick(View v) {
        Log.i(tag, "touch event");
    }
}

HomeActivity.java

TouchyGridView mGridView;
 mGridView = (TouchyGridView) findViewById(R.id.apps_grid);

 LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MESSAGE_PROGRESS);
        bManager.registerReceiver(broadcastReceiver, intentFilter);

 mGridView.setAdapter(new HomeScreenAppGridAdapter(HomeActivity.this, mKioskAppsList));
        mGridView.setOnNoItemClickListener(this);
        mGridView.setOnItemClickListener(this);

        private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if(intent.getAction().equals(MESSAGE_PROGRESS)){
                //initHomeScreenUI(true);

                /*if(download.getProgress() == 100){
                    mProgressText.setText("File Download Complete");

                } else {
                    mProgressText.setText(String.format("Downloaded (%d/%d) MB",download.getCurrentFileSize(),download.getTotalFileSize()));
                }*/
            }
        }
    };

    // When Download Start, I am sending broadcast using below code

    Intent intent = new Intent(HomeActivity.MESSAGE_PROGRESS);
        intent.putExtra("download",download);
        LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);


来源: stackexchange

问:
Scalamock 3. Mock overloaded method without parameter
I couldn't find any documentation that explains how to mock overloaded methods that take no arguments in scalamock e.g

```<code>public boolean isInfoEnabled(Marker marker);
public boolean isInfoEnabled();
</code>```

To mock the function that takes the Marker, one can simply use

```<code>(loggerMock.isInfoEnabled(_: Marker)).expects(*).returning(true)
</code>```

But how to mock the other method that takes no parameters? Any help is appreciated.

答:
In scala 2.12 this also works (no inspection for Intellij):</p>

```<code>//noinspection ConvertibleToMethodValue
(tailer.run _: () => Unit) expects()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I couldn't find any documentation that explains how to mock overloaded methods that take no arguments in scalamock e.g

public boolean isInfoEnabled(Marker marker);
public boolean isInfoEnabled();

To mock the function that takes the Marker, one can simply use

(loggerMock.isInfoEnabled(_: Marker)).expects(*).returning(true)

But how to mock the other method that takes no parameters? Any help is appreciated.

Body:
In scala 2.12 this also works (no inspection for Intellij):

//noinspection ConvertibleToMethodValue
(tailer.run _: () => Unit) expects()


问:
How did my trigger get deleted?
If you can figure out this one you are a true SQL guru! It's one of the weirdest things I've ever seen.

I've added a trigger to a table in our database. The server is SQL 2008. The trigger doesn't do anything particularly tricky. Just changes a LastUpdated field in the table when certain fields are changed. It's a "After Update" trigger.

There is a large C++ legacy app that runs all kind of huge queries against this database. Somehow (I've got absolutely no idea how) it is deleting this trigger. It doesn't delete any other triggers and I'm certain that it's not explicitly dropping the trigger or table. The developers of this app don't even know anything about my triggers.

How is this possible??

I've tried running a trace using SQL Server Profiler and I've gone through each command that it's sending and run them using SQL Management Studio but my trigger is not affected. It only seems to happen when I run the app. WTF :(

UPDATE:

Sorry I don't want to waste your time. I just realised that if I change the name of the trigger then it doesn't get deleted. Furthermore if I modify the trigger so it doesn't do anything at all then it still gets deleted. From this I can only guess that the other devs are explicitly deleting it but I've searched the trace for the trigger name and it's not there. I'll hassle them and see what they say. Thanks for the suggestions.

UPDATE 2:

The other devs reckon that they are not deleting it explicitly. It doesn't exist in sys.objects or sys.triggers so it's not a glitch with SSMS. So confused :(  Guess I'll just rename it and hope for the best? Can't think of anything else to try. A few comments below have asked if the trigger is being deleted or just disabled or not working. As I stated, it's being deleted completely. Also, the problem is not related to the actual contents of the trigger. As I stated, it I remove the contents and replace with some extremely simple code that doesn't do anything then it is still deleted.

Cheers

Mark

答:
I had an identical issue which I tracked down to a creation script missing a final GO statement.

Script 1

```<code>IF EXISTS (....)
    DROP PROC MyProc
GO

CREATE PROC MyProc
.....
/* GO statement is missing */
</code>```

Script 2

```<code>IF EXISTS (....)
    DROP TRIGGER MyDisappearingTrigger
GO

CREATE TRIGGER MyDisappearingTrigger
.....
GO
</code>```

When I inspected MyProc in the object explorer it looked like this:

```<code>CREATE PROC MyProc
AS
...

IF EXISTS (....)
    DROP TRIGGER MyDisappearingTrigger
GO
</code>```

So this meant that every time the stored proc was called the trigger was also deleted.

Title: How did my trigger get deleted?

Body:
I had an identical issue which I tracked down to a creation script missing a final GO statement.

Script 1

IF EXISTS (....)
    DROP PROC MyProc
GO

CREATE PROC MyProc
.....
/* GO statement is missing */

Script 2

IF EXISTS (....)
    DROP TRIGGER MyDisappearingTrigger
GO

CREATE TRIGGER MyDisappearingTrigger
.....
GO

When I inspected MyProc in the object explorer it looked like this:

CREATE PROC MyProc
AS
...

IF EXISTS (....)
    DROP TRIGGER MyDisappearingTrigger
GO

So this meant that every time the stored proc was called the trigger was also deleted.


问:
gson.toJson() throws StackOverflowError
I would like to generate a JSON String from my object:

```<code>Gson gson = new Gson();
String json = gson.toJson(item);
</code>```

Everytime I try to do this, I get this error:

```<code>14:46:40,236 ERROR [[BomItemToJSON]] Servlet.service() for servlet BomItemToJSON threw exception
java.lang.StackOverflowError
    at com.google.gson.stream.JsonWriter.string(JsonWriter.java:473)
    at com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:347)
    at com.google.gson.stream.JsonWriter.value(JsonWriter.java:440)
    at com.google.gson.internal.bind.TypeAdapters$7.write(TypeAdapters.java:235)
    at com.google.gson.internal.bind.TypeAdapters$7.write(TypeAdapters.java:220)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:200)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:60)
    at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:843)
</code>```

These are the attributes of my BomItem class:

```<code>private int itemId;
private Collection<BomModule> modules;
private boolean deprecated;
private String partNumber;
private String description; //LOB
private int quantity;
private String unitPriceDollar;
private String unitPriceEuro;
private String discount;
private String totalDollar;
private String totalEuro;
private String itemClass;
private String itemType;
private String vendor;
private Calendar listPriceDate;
private String unitWeight;
private String unitAveragePower;
private String unitMaxHeatDissipation;
private String unitRackSpace;
</code>```

Attributes of my referenced BomModule class:

```<code>private int moduleId;
private String moduleName;
private boolean isRootModule;
private Collection<BomModule> parentModules;
private Collection<BomModule> subModules;
private Collection<BomItem> items;
private int quantity;
</code>```

Any idea what causes this error? How can I fix it?

答:
My answer is a little bit late, but I think this question doesn't have a good solution yet. I found it originally here.

With Gson you can mark the fields you do want to be included in json with @Expose like this:

```<code>@Expose
String myString;  // will be serialized as myString
</code>```

and create the gson object with:

```<code>Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
</code>```

Circular references you just do not expose. That did the trick for me!

Title: gson.toJson() throws StackOverflowError

Body:
I would like to generate a JSON String from my object:

Gson gson = new Gson();
String json = gson.toJson(item);

Everytime I try to do this, I get this error:

14:46:40,236 ERROR [[BomItemToJSON]] Servlet.service() for servlet BomItemToJSON threw exception
java.lang.StackOverflowError
    at com.google.gson.stream.JsonWriter.string(JsonWriter.java:473)
    at com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:347)
    at com.google.gson.stream.JsonWriter.value(JsonWriter.java:440)
    at com.google.gson.internal.bind.TypeAdapters$7.write(TypeAdapters.java:235)
    at com.google.gson.internal.bind.TypeAdapters$7.write(TypeAdapters.java:220)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:200)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:60)
    at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:843)

These are the attributes of my BomItem class:

private int itemId;
private Collection<BomModule> modules;
private boolean deprecated;
private String partNumber;
private String description; //LOB
private int quantity;
private String unitPriceDollar;
private String unitPriceEuro;
private String discount;
private String totalDollar;
private String totalEuro;
private String itemClass;
private String itemType;
private String vendor;
private Calendar listPriceDate;
private String unitWeight;
private String unitAveragePower;
private String unitMaxHeatDissipation;
private String unitRackSpace;

Attributes of my referenced BomModule class:

private int moduleId;
private String moduleName;
private boolean isRootModule;
private Collection<BomModule> parentModules;
private Collection<BomModule> subModules;
private Collection<BomItem> items;
private int quantity;

Any idea what causes this error? How can I fix it?

Body:
My answer is a little bit late, but I think this question doesn't have a good solution yet. I found it originally here.

With Gson you can mark the fields you do want to be included in json with @Expose like this:

@Expose
String myString;  // will be serialized as myString

and create the gson object with:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

Circular references you just do not expose. That did the trick for me!


问:
Reading the first 10 bytes of a file in Java
```<code>    for (String name : filenames) {
FileInputStream in = new FileInputStream(input.readUTF());
    int byteCounter = 0;
    int rowCounter = 0;
    long bufferCounter = 0;
    byte[] b = new byte[8];
    int read;

    //in.skip(10);
    //while((read = in.read()) != -1){
    while((read = in.read(b, 0, 10)) != -1){
        byteCounter ++;
        if (byteCounter != 1000){
            if (rowCounter == 16){
                System.out.println("\n");
                rowCounter = 0;
            }
        System.out.print(Integer.toHexString(read) + "\t");
            bufferCounter ++;
            rowCounter ++;
        }else{
                byteCounter = 0;
                try{
                    Thread.sleep(200);
                }catch(InterruptedException e) {
                }
        }
    }
    System.out.println("\n"+"================"+"\n");
}
</code>```

Hi there, I was hoping someone might be able to help me with an issue I've been having. I'm trying to get my program to read in the first 10 bytes of a specified file. I can get it to work with the skip() but obviously this does the opposite of what I want (it removes the first 10 instead)
I've looked all over to no avail, if you can help me out, that'd be great.
You can probably see that I've tried to enter the read(b, off, len) into the code already but this just produces random characters as an output rather than the actual hex characters I want 74 65 71 etc (Edit: These random characters seem to be the hex code for the number of bytes read. So for a text file that has 23 hex chars in it, it produces a a 3 (or in other words: 10,10,3 = 23)

答:
the problem is here

```<code>System.out.print(Integer.toHexString(read) + "\t");
</code>```

read contains the number of bytes effectively read from stream. Teh bytes are in array b.

By the way: your array has a size of 8. you should increas it to 10 if you want to read 10 bytes!

ContentLicense: CC BY-SA 2.5

Body:
    for (String name : filenames) {
FileInputStream in = new FileInputStream(input.readUTF());
    int byteCounter = 0;
    int rowCounter = 0;
    long bufferCounter = 0;
    byte[] b = new byte[8];
    int read;

    //in.skip(10);
    //while((read = in.read()) != -1){
    while((read = in.read(b, 0, 10)) != -1){
        byteCounter ++;
        if (byteCounter != 1000){
            if (rowCounter == 16){
                System.out.println("\n");
                rowCounter = 0;
            }
        System.out.print(Integer.toHexString(read) + "\t");
            bufferCounter ++;
            rowCounter ++;
        }else{
                byteCounter = 0;
                try{
                    Thread.sleep(200);
                }catch(InterruptedException e) {
                }
        }
    }
    System.out.println("\n"+"================"+"\n");
}

Hi there, I was hoping someone might be able to help me with an issue I've been having. I'm trying to get my program to read in the first 10 bytes of a specified file. I can get it to work with the skip() but obviously this does the opposite of what I want (it removes the first 10 instead)
I've looked all over to no avail, if you can help me out, that'd be great.
You can probably see that I've tried to enter the read(b, off, len) into the code already but this just produces random characters as an output rather than the actual hex characters I want 74 65 71 etc (Edit: These random characters seem to be the hex code for the number of bytes read. So for a text file that has 23 hex chars in it, it produces a a 3 (or in other words: 10,10,3 = 23)

Body:
the problem is here

System.out.print(Integer.toHexString(read) + "\t");

read contains the number of bytes effectively read from stream. Teh bytes are in array b.

By the way: your array has a size of 8. you should increas it to 10 if you want to read 10 bytes!


问:
Optimize calculation of a large set of binary predicate based rules
I have a known and limited set of binary predicates: A, B, C, ...

And a large set of rules, containing the predicates with OR, AND, NOT operators. i.e

```<code>R1 = A AND B
R2 = NOT(C) OR B
R3 = ((A OR B) AND C) OR NOT(C)
</code>```

When getting a binary assignment for all the predicates, I want to optimize the calculation of the rules.

For that, I can modify the rule definition however I wish, as long as the logic won't change (same predicate assignment will give same calculated result on each rule).

I was thinking of creating some sort of a joint decision tree, but couldn't see how I can tell what is the optimized arrangement.

Note: I don't care about the complexity of building the calculating algorithm, only the calculation complexity.

答:
For a small number of predicates you can calculate all results in advance to create a cache. Note that you will have 2 ^ (the number of predicates) entries in your cache.

For a large number of predicates you can't do this. I'd say this sounds like dynamic programming, as the rules may have overlapping components. To increase this overlap you could rewrite all rules to use a single type of operation, e.g. NAND. From this you can then create a graph where the predicates are the input and the rules are the output.

So your rules would look like:

```<code>R1 = (A NAND B) NAND (A NAND B)
R2 = (B NAND B) NAND C
R3 = (A NAND A) NAND (B NAND B) NAND C
</code>```

You can already see some overlap. This will increase with the number of rules. Your graph would look like this:

Once you get the binary assignment, you can compute the graph from left to right. Or in dynamic programming style, you start with R1 and cache all intermediate results for later use, then do the same for R2 and R3.

Body:
I have a known and limited set of binary predicates: A, B, C, ...

And a large set of rules, containing the predicates with OR, AND, NOT operators. i.e

R1 = A AND B
R2 = NOT(C) OR B
R3 = ((A OR B) AND C) OR NOT(C)

When getting a binary assignment for all the predicates, I want to optimize the calculation of the rules.

For that, I can modify the rule definition however I wish, as long as the logic won't change (same predicate assignment will give same calculated result on each rule).

I was thinking of creating some sort of a joint decision tree, but couldn't see how I can tell what is the optimized arrangement.

Note: I don't care about the complexity of building the calculating algorithm, only the calculation complexity.

Body:
For a small number of predicates you can calculate all results in advance to create a cache. Note that you will have 2 ^ (the number of predicates) entries in your cache.

For a large number of predicates you can't do this. I'd say this sounds like dynamic programming, as the rules may have overlapping components. To increase this overlap you could rewrite all rules to use a single type of operation, e.g. NAND. From this you can then create a graph where the predicates are the input and the rules are the output.

So your rules would look like:

R1 = (A NAND B) NAND (A NAND B)
R2 = (B NAND B) NAND C
R3 = (A NAND A) NAND (B NAND B) NAND C

You can already see some overlap. This will increase with the number of rules. Your graph would look like this:

Once you get the binary assignment, you can compute the graph from left to right. Or in dynamic programming style, you start with R1 and cache all intermediate results for later use, then do the same for R2 and R3.


问:
JDI UI Test Automation Framework Simple Java example project - run test
I am download Simple Java example project
Run SimpleTest
I see error

Error:(12, 17) java: cannot find symbol   symbol:   method domain()

  location: @interface
  com.epam.jdi.uitests.web.selenium.elements.pageobjects.annotations.JSite

Error:(12, 1) java: annotation
  @com.epam.jdi.uitests.web.selenium.elements.pageobjects.annotations.JSite
  is missing a default value for the element 'value'

I'm changing @JSite(**domain** = "https://epam.github.io/JDI/") to @JSite(**value** = "https://epam.github.io/JDI/")

In the end, I got an error

"ERROR: Can't download latest driver for CHROME. Exception null"

I changed the value driver=${driver} to driver=chrome in file test.properties,
commented on the line chrome in pom.xml
I see the same mistake
I saw the answers on the query

"ERROR: Can't download latest driver for CHROME. Exception null"

But I can not imagine where you can still specify the property of the path to the driver

```<code>System.setProperty("webdriver.chrome.driver", System.getProperty("C:\\Users\\xxxxxx\\chromedriver_win32_2.1"));
ChromeDriver d1 = new ChromeDriver();
</code>```

答:
I found the answer.

In file JDIExampleSite changing @JSite(value = "https://epam.github.io/JDI") (Remove the last slash)

In file HomePage changing @JPage(url = "/index.html", title = "Index Page") (We add "L" to htm and we get html)

In file test.properties remove the comment "drivers.folder=C:\" (I have a root chrome driver, If you are different, specify your path)

I also removed the comment from "drivers.version=2.23" in file test.properties and changed "driver=chrome" here

Body:
I am download Simple Java example project
Run SimpleTest
I see error

Error:(12, 17) java: cannot find symbol   symbol:   method domain()

  location: @interface
  com.epam.jdi.uitests.web.selenium.elements.pageobjects.annotations.JSite

Error:(12, 1) java: annotation
  @com.epam.jdi.uitests.web.selenium.elements.pageobjects.annotations.JSite
  is missing a default value for the element 'value'

I'm changing @JSite(**domain** = "https://epam.github.io/JDI/") to @JSite(**value** = "https://epam.github.io/JDI/")

In the end, I got an error

"ERROR: Can't download latest driver for CHROME. Exception null"

I changed the value driver=${driver} to driver=chrome in file test.properties,
commented on the line chrome in pom.xml
I see the same mistake
I saw the answers on the query

"ERROR: Can't download latest driver for CHROME. Exception null"

But I can not imagine where you can still specify the property of the path to the driver

System.setProperty("webdriver.chrome.driver", System.getProperty("C:\\Users\\xxxxxx\\chromedriver_win32_2.1"));
ChromeDriver d1 = new ChromeDriver();


问:
Jax-rs convert to object Mule
I am using RAML for design api.
Then I convert raml to jaxrs and get java classes (https://github.com/mulesoft-labs/raml-for-jax-rs ).
It gives two classes: interface and *impl classes.
Then I Import them into my project In Anypoint Studio. I want to use them.

But JsonToObject Transfer cannot use convert classes.

org.mule.api.transformer.TransformerMessagingException: Failed to transform from "json" to "classImpl".

I try use without interface classes. It work correct.

How to use interface and *impl Classes for convert json to Object?

答: You should make sure your classImp support JSON binding using Jackson annotations. See the related Mule documentation on JSON Support for details.

Title: Jax-rs convert to object Mule


问:
Why does the accordion works just once?
I'm trying to get this effect:

When I open the dialog for the first time everything works fine.
But if I close the dialog and open it again this is what I see:

Does someone knows how to fix it?
This is the part of my code:

```<code>function showLicenses(cluster_id) {
    // get licenses from window object
  var licenses = window.licenses[cluster_id];
    $('#accordion-cluster').html('');
  // sort reverse timestamp
  licenses = licenses.sort(function(a, b){
    return new Date(b.date_created) - new Date(a.date_created);
  });

  $.each(licenses, function(index, license){
    console.log(license);
    var id = license.license_id;
    var licenseNo = index + 1;
    if(licenseNo !== 1){
      //$("#accordion-cluster").append('<hr><br>')
    }
    $("#accordion-cluster").append('<h2> LICENSE ' + licenseNo + '<a class="removeLicense" style="background:#c8212f;color:white;padding:5px;margin:15px;position:absolute;top: 0;right: 0;" data-license-id="' + license.license_id + '">remove</a></h2><div>' + license.key_contents + '</div>');
  });
  $("#dialog").dialog({
      height: 500,
      width: 800,
      modal: true,
      open: function(){
          var icons = {
              header: "ui-icon-triangle-1-s",    // custom icon class
              activeHeader: "ui-icon-triangle-1-n" // custom icon class
          };
          console.log($("#accordion-cluster"));
          $("#accordion-cluster").accordion({
              collapsible : true,
              active : 'none',
              icons: icons
          });
      }
  });
  $.LoadingOverlay("hide");
}
</code>```

And the HTML:

```<code><div id="dialog" title="License Key">
    <div style="white-space: pre-wrap;" id="license-key">
         <div id="accordion-cluster">

         </div>
    </div>
</div>
</code>```

To answer to the comments, this is the appearance of the opened accordion (just the first time i open the dialog box):

答:
You have to destroy the accordion before changing the data inside, the best timing to do this is when closing the dialog:

```<code>$("#dialog").dialog({
    height: 500,
    width: 800,
    modal: true,
    open: function () {
        var icons = {
            header: "ui-icon-triangle-1-s",    // custom icon class
            activeHeader: "ui-icon-triangle-1-n" // custom icon class
        };

        $("#accordion-cluster").accordion({
            collapsible : true,
            active : 'none',
            icons: icons
        });
    },
    close: function () {
        $('#accordion-cluster').accordion('destroy');
    }
});
</code>```

Related question that helped me: re-initialize jquery accordion on callback
Do note that the referenced question is not a duplicate, because of the fact this question involves a dialog.

Title: Why does the accordion works just once?

Body:
I'm trying to get this effect:

When I open the dialog for the first time everything works fine.
But if I close the dialog and open it again this is what I see:

Does someone knows how to fix it?
This is the part of my code:

function showLicenses(cluster_id) {
    // get licenses from window object
  var licenses = window.licenses[cluster_id];
    $('#accordion-cluster').html('');
  // sort reverse timestamp
  licenses = licenses.sort(function(a, b){
    return new Date(b.date_created) - new Date(a.date_created);
  });

  $.each(licenses, function(index, license){
    console.log(license);
    var id = license.license_id;
    var licenseNo = index + 1;
    if(licenseNo !== 1){
      //$("#accordion-cluster").append('

')
    }
    $("#accordion-cluster").append('
 LICENSE ' + licenseNo + 'remove

' + license.key_contents + '
');
  });
  $("#dialog").dialog({
      height: 500,
      width: 800,
      modal: true,
      open: function(){
          var icons = {
              header: "ui-icon-triangle-1-s",    // custom icon class
              activeHeader: "ui-icon-triangle-1-n" // custom icon class
          };
          console.log($("#accordion-cluster"));
          $("#accordion-cluster").accordion({
              collapsible : true,
              active : 'none',
              icons: icons
          });
      }
  });
  $.LoadingOverlay("hide");
}

And the HTML:

To answer to the comments, this is the appearance of the opened accordion (just the first time i open the dialog box):

Body:
You have to destroy the accordion before changing the data inside, the best timing to do this is when closing the dialog:

$("#dialog").dialog({
    height: 500,
    width: 800,
    modal: true,
    open: function () {
        var icons = {
            header: "ui-icon-triangle-1-s",    // custom icon class
            activeHeader: "ui-icon-triangle-1-n" // custom icon class
        };

        $("#accordion-cluster").accordion({
            collapsible : true,
            active : 'none',
            icons: icons
        });
    },
    close: function () {
        $('#accordion-cluster').accordion('destroy');
    }
});

Related question that helped me: re-initialize jquery accordion on callback
Do note that the referenced question is not a duplicate, because of the fact this question involves a dialog.


问:
On input focus make background look like modal
On my webpage, I have a footer which has a textarea box. When the user clicks in the textarea, I want the rest of the page to darken by 60%, kindof like they are in a modal. I am a noob when it comes to advanced css so I am unsure of the properties to apply.

I am using bootstrap 3, javascript and knockout. I know how to detect when the user is in the text area I just want to change the background so everything else is opaque.

A jsFiddle would be wonderful as well :)

答:
A good solution is to make a modal appear behind the input and not just making the background darker, this can be accomplished with css alone

```<code>...

<style>
textarea:focus{
  z-index: 901;
  position: relative;
}
textarea ~ .textarea-modal{
  position: fixed;
  background-color: transparent;
  margin: auto;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  z-index: 900;
  pointer-events: none;
  transition: background-color .5s ease;
}
textarea:focus ~ .textarea-modal{
  pointer-events: auto;
  background-color: rgba(0,0,0,0.3);
}
</style>

...

<div>
    <textarea></textarea>
    <div class="textarea-modal"></div>
</div>

...
</code>```

feel free to change the selectors to target specific elements, however at the moment when you focus on the textarea a modal would appear below it with other elements behind.

Body:
A good solution is to make a modal appear behind the input and not just making the background darker, this can be accomplished with css alone

...

<style>
textarea:focus{
  z-index: 901;
  position: relative;
}
textarea ~ .textarea-modal{
  position: fixed;
  background-color: transparent;
  margin: auto;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  z-index: 900;
  pointer-events: none;
  transition: background-color .5s ease;
}
textarea:focus ~ .textarea-modal{
  pointer-events: auto;
  background-color: rgba(0,0,0,0.3);
}
</style>

...

<div>
    <textarea></textarea>
    <div class="textarea-modal"></div>
</div>

...

feel free to change the selectors to target specific elements, however at the moment when you focus on the textarea a modal would appear below it with other elements behind.


问:
Option Strict Intellisense errors but compiles fine
I have just got a new work PC and am moving a solution from VS15 to 17.

When I edit existing source files, I get a bunch of errors relating to option strict, which include:

```<code>Option Strict On requires all variable declarations to have an 'As' clause
Option Strict On disallows implicit conversions from 'Object' to 'Integer'
Option Strict prohibits operands of type Object for operator '-'
Option Strict On disallows late binding
</code>```

In addition to this, I am getting errors about System classes not being found, for example Attribute, NotImplementedException, etc.

Option Strict is turned off for all solutions in the project.

The errors relating to Object to Integer are caused by i variables within loops, where the for line also has an error about late binding being disallowed.

I have tried deleting the vs folder within the solution but it made no difference.

The project compiles without issue. How can I fix the Intellisense errors?

答:
Probably it is the VS 2017 bug (v. 15.5.0) described here.

Occurred today with me after I updated VS from 15.4 to 15.5.

The workaround has already been posted in Drake's answer.

Uncheck option Allow parallel project initialization (Tools > Options > Projects and Solutions > General). Reopen the solution.

EDIT

This has been fixed with the latest update (v. 15.5.1).

Body:
I have just got a new work PC and am moving a solution from VS15 to 17.

When I edit existing source files, I get a bunch of errors relating to option strict, which include:

Option Strict On requires all variable declarations to have an 'As' clause
Option Strict On disallows implicit conversions from 'Object' to 'Integer'
Option Strict prohibits operands of type Object for operator '-'
Option Strict On disallows late binding

In addition to this, I am getting errors about System classes not being found, for example Attribute, NotImplementedException, etc.

Option Strict is turned off for all solutions in the project.

The errors relating to Object to Integer are caused by i variables within loops, where the for line also has an error about late binding being disallowed.

I have tried deleting the vs folder within the solution but it made no difference.

The project compiles without issue. How can I fix the Intellisense errors?


问:
How to import file into sqlite?
On a Mac, I have a txt file with two columns, one being an autoincrement in an sqlite table:

```<code>, "mytext1"
, "mytext2"
, "mytext3"
</code>```

When I try to import this file, I get a datatype mismatch error:

```<code>.separator ","
.import mytextfile.txt mytable
</code>```

How should the txt file be structured so that it uses the autoincrement?

Also, how do I enter in text that will have line breaks?  For example:

```<code>"this is a description of the code below.
The text might have some line breaks and indents.  Here's
the related code sample:

foreach (int i = 0; i < 5; i++){

  //do some stuff here

}

this is a little more follow up text."
</code>```

I need the above inserted into one row.  Is there anything special I need to do to the formatting?

For one particular table, I want each of my rows as a file and import them that way.  I'm guessing it is a matter of creating some sort of batch file that runs multiple imports.

Edit

That's exactly the syntax I posted, minus a tab since I'm using a comma. The missing line break in my post didn't make it as apparent. Anyways, that gives the mismatch error.

答:
I was looking on the same problem. Looks like I've found an answer on the first part of your question — about importing a file into a table with ID field.

So yes, create a temporary table without ID, import your file into it, then do insert..select to copy its data into your target table. (Remove leading commas from mytextfile.txt).

```<code>-- assuming your table is called Strings and
-- was created like this:
-- create table Strings( ID integer primary key, Code text )

create table StringsImport( Code text );
.import mytextfile.txt StringsImport
insert into Strings ( Code ) select * from StringsImport;
drop table StringsImport;
</code>```

Do not know what to do with newlines. I've read some mentions that importing in CSV mode will do the trick (.mode csv), but when I tried it did not seem to work.

Title: How to import file into sqlite?

Body:
On a Mac, I have a txt file with two columns, one being an autoincrement in an sqlite table:

, "mytext1"
, "mytext2"
, "mytext3"

When I try to import this file, I get a datatype mismatch error:

.separator ","
.import mytextfile.txt mytable

How should the txt file be structured so that it uses the autoincrement?

Also, how do I enter in text that will have line breaks?  For example:

"this is a description of the code below.
The text might have some line breaks and indents.  Here's
the related code sample:

foreach (int i = 0; i < 5; i++){

  //do some stuff here

}

this is a little more follow up text."

I need the above inserted into one row.  Is there anything special I need to do to the formatting?

For one particular table, I want each of my rows as a file and import them that way.  I'm guessing it is a matter of creating some sort of batch file that runs multiple imports.

Edit

That's exactly the syntax I posted, minus a tab since I'm using a comma. The missing line break in my post didn't make it as apparent. Anyways, that gives the mismatch error.

Body:
I was looking on the same problem. Looks like I've found an answer on the first part of your question — about importing a file into a table with ID field.

So yes, create a temporary table without ID, import your file into it, then do insert..select to copy its data into your target table. (Remove leading commas from mytextfile.txt).

-- assuming your table is called Strings and
-- was created like this:
-- create table Strings( ID integer primary key, Code text )

create table StringsImport( Code text );
.import mytextfile.txt StringsImport
insert into Strings ( Code ) select * from StringsImport;
drop table StringsImport;

Do not know what to do with newlines. I've read some mentions that importing in CSV mode will do the trick (.mode csv), but when I tried it did not seem to work.

OwnerDisplayName: alexandroid


问:
Linux command: How to 'find' only text files?
After a few searches from Google, what I come up with is:

```<code>find my_folder -type f -exec grep -l "needle text" {} \; -exec file {} \; | grep text
</code>```

which is very unhandy and outputs unneeded texts such as mime type information. Any better solutions? I have lots of images and other binary files in the same folder with a lot of text files that I need to search through.

答:
How about this:

```<code>$ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable'
</code>```

If you want the filenames without the file types, just add a final sed filter.

```<code>$ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'
</code>```

You can filter-out unneeded file types by adding more -e 'type' options to the last grep command.

EDIT:

If your xargs version supports the -d option, the commands above become simpler:

```<code>$ grep -rl "needle text" my_folder | xargs -d '\n' -r file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'
</code>```

Body:
After a few searches from Google, what I come up with is:

find my_folder -type f -exec grep -l "needle text" {} \; -exec file {} \; | grep text

which is very unhandy and outputs unneeded texts such as mime type information. Any better solutions? I have lots of images and other binary files in the same folder with a lot of text files that I need to search through.

Body:
How about this:

$ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable'

If you want the filenames without the file types, just add a final sed filter.

$ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'

You can filter-out unneeded file types by adding more -e 'type' options to the last grep command.

EDIT:

If your xargs version supports the -d option, the commands above become simpler:

$ grep -rl "needle text" my_folder | xargs -d '\n' -r file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'


问:
SPLIT URL in PHP
I have below URL in my code and i want to split it and get the number from it

For example from the below URL  need to fetch 123456

https://review-test.com/#/c/123456/

I have tried this and it is not working

```<code>$completeURL  = https://review-test.com/#/c/123456/  ;

  list($url, $number) = explode('#c', preg_replace('/^.*\/+/', '', $completeURL));
</code>```

答:
Simply:

```<code>$tmp = explode( '/', $completeUrl).end();
</code>```

It will explode the string by '/' and take the last element

Title: SPLIT URL in PHP

Body:
I have below URL in my code and i want to split it and get the number from it

For example from the below URL  need to fetch 123456

https://review-test.com/#/c/123456/

I have tried this and it is not working

$completeURL  = https://review-test.com/#/c/123456/  ;

  list($url, $number) = explode('#c', preg_replace('/^.*\/+/', '', $completeURL));

Body:
Simply:

$tmp = explode( '/', $completeUrl).end();

It will explode the string by '/' and take the last element


问:
Random Forest and Python
I have a Random Forest model for a dataset with 72 features: Objective is to find the feature importances and use it for feature selection.

```<code>rf = RandomForestRegressor(n_estimators=XXX)
rf.fit(X, y)
</code>```

I am not able to get the list of predictors with their feature values, it just provide 72 feature importance numbers, which is very diffficult to map with each feature name,
Is there a way to get the names and importance together
Like

A 0.55656

  B 0.4333

etc

答: The feature_importance_ method keeps the order of features the tree was trained upon. So you can use a zip function between the original feature list and the feature_importance_ return value to get per each features its importance. </p>

OwnerDisplayName: Amrita

Title: Random Forest and Python

Body:
I have a Random Forest model for a dataset with 72 features: Objective is to find the feature importances and use it for feature selection.

rf = RandomForestRegressor(n_estimators=XXX)
rf.fit(X, y)

I am not able to get the list of predictors with their feature values, it just provide 72 feature importance numbers, which is very diffficult to map with each feature name,
Is there a way to get the names and importance together
Like

A 0.55656

  B 0.4333

etc


问:
slot.value returns all utterances rather than just those from slot
I have an intent set up with a list of the planets in the solar system.

 {
      "intent": "PlanetIntent",
      "slots": [
        {
          "name": "Planet",
          "type": "LIST_OF_PLANETS"
        }
      ]
    },```
</div>
</div>
</p>

<p>I'm trying to set it up so that when a user names a planet my code simply returns the name of that planet back to them. If they say a planet not in the list then it'll return with an error (or go to unhandled which is what I initially assumed would happen).</p>

<p>But no matter what I try, from the most basic to the most complex code, my code will <em>always</em> return any word that is said, rather than just the relevant slot value.</p>

<p>So neither</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>'PlanetIntent': function () {
 var selection = this.event.request.intent.slots.Planet.value;

        this.response.speak(selection);
        this.emit(':responseReady');
}</code>```

nor this

'PlanetIntent': function () {
 var selection = '';

        if ( !this.event.request.intent.slots.Planet ||
        this.event.request.intent.slots.Planet.value == '') {
            this.emitWithState('AMAZON.HelpIntent');

        } else {
            selection = this.event.request.intent.slots.Planet.value;

        this.response.speak(selection);
        this.emit(':responseReady');
  }
},```

Seem to stop random values from getting through. If you say Mars, it returns Mars, if you say turnip, it returns turnip. Any ideas. I just want to limit it to return only responses from my list of planets!

答:
The list you provide for slots are just Hints, not a filter or restriction. You will definitely need to filter the list in your code.

Since you're only looking for the names of planets in our solar system, this shouldn't be too difficult: 7-9 values depending whether you want to count Pluto and/or include Earth also, a bit tougher if you start including their moons, and quite challenging if you include known planets of other stars :-)

Body:
I have an intent set up with a list of the planets in the solar system.

 {
      "intent": "PlanetIntent",
      "slots": [
        {
          "name": "Planet",
          "type": "LIST_OF_PLANETS"
        }
      ]
    },

I'm trying to set it up so that when a user names a planet my code simply returns the name of that planet back to them. If they say a planet not in the list then it'll return with an error (or go to unhandled which is what I initially assumed would happen).

But no matter what I try, from the most basic to the most complex code, my code will always return any word that is said, rather than just the relevant slot value.

So neither

'PlanetIntent': function () {
 var selection = this.event.request.intent.slots.Planet.value;

        this.response.speak(selection);
        this.emit(':responseReady');
}

nor this

'PlanetIntent': function () {
 var selection = '';

        if ( !this.event.request.intent.slots.Planet ||
        this.event.request.intent.slots.Planet.value == '') {
            this.emitWithState('AMAZON.HelpIntent');

        } else {
            selection = this.event.request.intent.slots.Planet.value;

        this.response.speak(selection);
        this.emit(':responseReady');
  }
},

Seem to stop random values from getting through. If you say Mars, it returns Mars, if you say turnip, it returns turnip. Any ideas. I just want to limit it to return only responses from my list of planets!


问:
Publishing and reading of non-volatile field
```<code>public class Factory {
    private Singleton instance;
    public Singleton getInstance() {
        Singleton res = instance;
        if (res == null) {
            synchronized (this) {
                res = instance;
                if (res == null) {
                    res = new Singleton();
                    instance = res;
                }
            }
        }
        return res;
    }
}
</code>```

It is almost correct implementation of thread-safe Singleton. The only problem I see is:

The thread #1 that is initializing the instance field can published before it will be initialized completely. Now, the second thread can read instance in a inconsistent state.

But, for my eye it is only problem here. Is it only problem here?
(And we can make instance volatile).

答:
EDIT I've written one more answer here that should clear all the confusion.

This is a good question, and I'll try to summarize my understanding here.

Suppose Thread1 is currently initializing Singleton instance and publishes the reference (unsafely obviously). Thread2 can see this un-safe published reference (meaning it sees a non-null reference), but that does not mean that the fields that it sees via that reference (Singleton fields that are initialized via the constructor) are initialized correctly too.

As far as I can see, this happens because there could be re-ordering of the stores of the fields happening inside the constructor. Since there is no "happens-before" rules (these are plain variables), this could be entirely possible.

But that is not the only problem here. Notice that you do two reads here:

```<code>if (res == null) { // read 1

return res // read 2
</code>```

These reads have no synchronization protection, thus these are racy reads. AFAIK this means that read 1 is allowed to read a non-null reference, while read 2 is allowed to read a null reference.

This btw is the same thing that the ALL mighty Shipilev explains (even if I read this article once 1/2 year I still find something new every time).

Indeed making instance volatile would fix things. When you make it volatile, this happens:

```<code> instance = res; // volatile write, thus [LoadStore][StoreStore] barriers
</code>```

All "other" actions (stores from within the constructor) can not pass this fence, there will be no re-orderings. It also means that when you read the volatile variable and see a non-null value, it means that every "write" that was done before writing the volatile itself has occurred for sure. This excellent post has the exact meaning of it

This also solves the second problem, since these operations can not be re-ordered, you are guaranteed to see the same value from read 1 and read 2.

No matter how much I read and try to understand these things are constantly complicated to me, there are very few people that I know that can write code like this and reason correctly about it too. When you can (I do!) please stick to the known and working examples of double check locking :)

ContentLicense: CC BY-SA 4.0

Body:
public class Factory {
    private Singleton instance;
    public Singleton getInstance() {
        Singleton res = instance;
        if (res == null) {
            synchronized (this) {
                res = instance;
                if (res == null) {
                    res = new Singleton();
                    instance = res;
                }
            }
        }
        return res;
    }
}

It is almost correct implementation of thread-safe Singleton. The only problem I see is:

The thread #1 that is initializing the instance field can published before it will be initialized completely. Now, the second thread can read instance in a inconsistent state.

But, for my eye it is only problem here. Is it only problem here?
(And we can make instance volatile).

Body:
EDIT I've written one more answer here that should clear all the confusion.

This is a good question, and I'll try to summarize my understanding here.

Suppose Thread1 is currently initializing Singleton instance and publishes the reference (unsafely obviously). Thread2 can see this un-safe published reference (meaning it sees a non-null reference), but that does not mean that the fields that it sees via that reference (Singleton fields that are initialized via the constructor) are initialized correctly too.

As far as I can see, this happens because there could be re-ordering of the stores of the fields happening inside the constructor. Since there is no "happens-before" rules (these are plain variables), this could be entirely possible.

But that is not the only problem here. Notice that you do two reads here:

if (res == null) { // read 1

return res // read 2

These reads have no synchronization protection, thus these are racy reads. AFAIK this means that read 1 is allowed to read a non-null reference, while read 2 is allowed to read a null reference.

This btw is the same thing that the ALL mighty Shipilev explains (even if I read this article once 1/2 year I still find something new every time).

Indeed making instance volatile would fix things. When you make it volatile, this happens:

 instance = res; // volatile write, thus [LoadStore][StoreStore] barriers

All "other" actions (stores from within the constructor) can not pass this fence, there will be no re-orderings. It also means that when you read the volatile variable and see a non-null value, it means that every "write" that was done before writing the volatile itself has occurred for sure. This excellent post has the exact meaning of it

This also solves the second problem, since these operations can not be re-ordered, you are guaranteed to see the same value from read 1 and read 2.

No matter how much I read and try to understand these things are constantly complicated to me, there are very few people that I know that can write code like this and reason correctly about it too. When you can (I do!) please stick to the known and working examples of double check locking :)


问:
How to add a blurred drop shadow to a button?
I need to add blurred drop shadow to my button:

I tried to create background with layer-list xml drawable, but it not looks like blur.

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

    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <corners android:radius="45dp" />
            <padding
                android:bottom="2dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />

            <stroke
                android:width="6dp"
                android:color="#007879E8" />

        </shape>
    </item>
    //////   10 more items
        <item>
        <shape>
            <corners android:radius="45dp" />
            <padding
                android:bottom="2dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />

            <stroke
                android:width="6dp"
                android:color="#177879E8" />

        </shape>
    </item>

    <!-- Background -->
    <item>
        <shape>
            <corners android:radius="45dp" />
            <stroke
                android:width="2dp"
                android:color="@color/main_purple_text_color" />
        </shape>
    </item>

</layer-list>
</code>```

Also i tried to use background element behind button with blured png but it uses to many resources and i cannot create selector to change background on hover or click.

I need to have single background file for button and use selector to change blur and gradient on hover/click.
Any ideas how to achieve such effect with Android SDK ?

UPDATE 1

Thanks everybody for answers, but I'm not asking how to create gradient. I've already done this. I need to create blurred drop-shadow.

答:
You can do it by Graident

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<gradient
    android:startColor="#6586F0"
    android:centerColor="#D6D6D6"
    android:endColor="#4B6CD6"
    android:angle="90"/>
<corners
    android:radius="0dp"/>
</code>```

Body:
I need to add blurred drop shadow to my button:

I tried to create background with layer-list xml drawable, but it not looks like blur.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape>
            <corners android:radius="45dp" />
            <padding
                android:bottom="2dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />

            <stroke
                android:width="6dp"
                android:color="#007879E8" />

        </shape>
    </item>
    //////   10 more items
        <item>
        <shape>
            <corners android:radius="45dp" />
            <padding
                android:bottom="2dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />

            <stroke
                android:width="6dp"
                android:color="#177879E8" />

        </shape>
    </item>

    <item>
        <shape>
            <corners android:radius="45dp" />
            <stroke
                android:width="2dp"
                android:color="@color/main_purple_text_color" />
        </shape>
    </item>

</layer-list>

Also i tried to use background element behind button with blured png but it uses to many resources and i cannot create selector to change background on hover or click.

I need to have single background file for button and use selector to change blur and gradient on hover/click.
Any ideas how to achieve such effect with Android SDK ?

UPDATE 1

Thanks everybody for answers, but I'm not asking how to create gradient. I've already done this. I need to create blurred drop-shadow.

Body:
You can do it by Graident

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<gradient
    android:startColor="#6586F0"
    android:centerColor="#D6D6D6"
    android:endColor="#4B6CD6"
    android:angle="90"/>
<corners
    android:radius="0dp"/>


问:
ngIf not working if value contains hyphen(-) between text
*ngIf not comparing value properly if value/data contains a hyphen(-) symbol i.e. 'Pick-list' in my example.

If I remove the hyphen(-) symbol then it's work.
So how to compare string which contains a hyphen(-) symbol?

not working:

<ng-container *ngIf="fieldInfo.FieldType=='Pick-list'">
       <select class="form-control" required="">
       <option></option>
       <option> Lorem ipsum dolor sit amet </option>
       <option> Donec imperdiet sit amet </option>
       </select>
</ng-container>```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>working:

<ng-container *ngIf="fieldInfo.FieldType=='Checklist'">
       <h1>Check list</h1>
</ng-container></code>```

答:
Seems like you are missing something in your code. Make sure fieldInfo.FieldType= has the proper value to check that you can print ((fieldInfo.FieldType}}

Here is the working example

Body:
*ngIf not comparing value properly if value/data contains a hyphen(-) symbol i.e. 'Pick-list' in my example.

If I remove the hyphen(-) symbol then it's work.
So how to compare string which contains a hyphen(-) symbol?

not working:

<ng-container *ngIf="fieldInfo.FieldType=='Pick-list'">
       <select class="form-control" required="">
       <option></option>
       <option> Lorem ipsum dolor sit amet </option>
       <option> Donec imperdiet sit amet </option>
       </select>
</ng-container>

working:

<ng-container *ngIf="fieldInfo.FieldType=='Checklist'">

Check list

</ng-container>


答:
If you have no other option than regex, for your example data you could use preg_match to split your url instead of preg_replace.

An approach could be to

Capture the first part as a group (.+\/)

Then capture your number as a group (\d+)

Followed by a forward slash at the end of the line \/$/

This will take the last number from the url followed by a forward slash.

Then you could use list and skip the first item of the $matches array because that will contain the text that matched the full pattern.

```<code>$completeURL  = "https://review-test.com/#/c/123456/";
preg_match('/(.+\/)(\d+)\/$/', $completeURL, $matches);
list(, $url, $number) = $matches;
</code>```

Title: SPLIT URL in PHP

Body:
If you have no other option than regex, for your example data you could use preg_match to split your url instead of preg_replace.

An approach could be to

Capture the first part as a group (.+\/)

Then capture your number as a group (\d+)

Followed by a forward slash at the end of the line \/$/

This will take the last number from the url followed by a forward slash.

Then you could use list and skip the first item of the $matches array because that will contain the text that matched the full pattern.

$completeURL  = "https://review-test.com/#/c/123456/";
preg_match('/(.+\/)(\d+)\/$/', $completeURL, $matches);
list(, $url, $number) = $matches;


问:
Select corresponding to row from the same table SQL Server
I want to get some column based on another column

Example table:

```<code>| BlilCode | BlilShortName | BatchWeigth | BillVersion | BlilMaxTime |
+----------+---------------+-------------+-------------+-------------+
| 5502     | aaa           | 1.00        | 1           | 360         |
| 5502     | aaa           | 2.00        | 2           | 240         |
| 5510     | bbb           | -32.94      | 2           | 360         |
| 5510     | bbb           | 1.00        | 1           | 360         |
| 5510     | bbb           | 36.37       | 3           | 3600        |
</code>```

but I want to get the rows where BillVersion is max for every BlilCode is max

Expected result

```<code>| BlilCode | BlilShortName | BatchWeigth | BillVersion | BlilMaxTime |
+----------+---------------+-------------+-------------+-------------+
| 5502     | aaa           | 2.00        | 2           | 240         |
| 5510     | bbb           | 36.37       | 3           | 3600        |
</code>```

My current query is:

```<code>SELECT
    [BlilCode], [BlilShortName],
    BatchWeigth, (BillVersion) AS BillVersion, [BlilMaxTime]
FROM
    [CVfeedDB].[dbo].[constants.Blil]
WHERE
    BlilActive = 1 AND BatchWeigth IS NOT NULL
ORDER BY
    BlilCode
</code>```

答:
Your results suggest that you want:

```<code>select db.*
from (select db.*,
             row_number() over (partition by shortname order by billversion desc) as seqnum
      from db
     ) db
where seqnum = 1;
</code>```

If you based this on blilcode, then the results would have three rows instead of two.

Note:  The question was edited after this, so the appropriate query would be:

```<code>select db.*
from (select db.*,
             row_number() over (partition by blilcode order by billversion desc) as seqnum
      from db
     ) db
where seqnum = 1;
</code>```

Body:
I want to get some column based on another column

Example table:

| BlilCode | BlilShortName | BatchWeigth | BillVersion | BlilMaxTime |
+----------+---------------+-------------+-------------+-------------+
| 5502     | aaa           | 1.00        | 1           | 360         |
| 5502     | aaa           | 2.00        | 2           | 240         |
| 5510     | bbb           | -32.94      | 2           | 360         |
| 5510     | bbb           | 1.00        | 1           | 360         |
| 5510     | bbb           | 36.37       | 3           | 3600        |

but I want to get the rows where BillVersion is max for every BlilCode is max

Expected result

| BlilCode | BlilShortName | BatchWeigth | BillVersion | BlilMaxTime |
+----------+---------------+-------------+-------------+-------------+
| 5502     | aaa           | 2.00        | 2           | 240         |
| 5510     | bbb           | 36.37       | 3           | 3600        |

My current query is:

SELECT
    [BlilCode], [BlilShortName],
    BatchWeigth, (BillVersion) AS BillVersion, [BlilMaxTime]
FROM
    [CVfeedDB].[dbo].[constants.Blil]
WHERE
    BlilActive = 1 AND BatchWeigth IS NOT NULL
ORDER BY
    BlilCode

Body:
Your results suggest that you want:

select db.*
from (select db.*,
             row_number() over (partition by shortname order by billversion desc) as seqnum
      from db
     ) db
where seqnum = 1;

If you based this on blilcode, then the results would have three rows instead of two.

Note:  The question was edited after this, so the appropriate query would be:

select db.*
from (select db.*,
             row_number() over (partition by blilcode order by billversion desc) as seqnum
      from db
     ) db
where seqnum = 1;