问:
Unable to run app in emulator with API 29 android studio
I have an app run normally in the emulator with API 28. But when I run the app in the emulator with API 29 it shows

It does not only show keeps stopping in the emulator. I tried to install it on mobile and it also shows the same error.

The log shows this error like this:

```<code>2020-02-14 19:48:12.922 20370-20370/? E/stickerappmake: Unknown bits set in runtime_flags: 0x8000
2020-02-14 19:48:15.326 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:15.326 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:15.385 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:15.385 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.138 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.139 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.243 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.243 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:19.984 20370-20464/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:19.984 20370-20464/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.048 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.048 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.059 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.063 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:22.727 20370-20370/com.testdev.appname E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.testdev.appname, PID: 20370
    java.lang.NullPointerException: Attempt to get length of null array
        at com.testdev.appname.activities.CreateFragment.loadStickersCreated(CreateFragment.java:52)
        at com.testdev.appname.activities.CreateFragment.onCreateView(CreateFragment.java:88)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
        at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3273)
        at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3229)
        at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
        at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:620)
        at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1425)
        at android.app.Activity.performStart(Activity.java:7825)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3294)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
</code>```

I see there some problems with the java code in CreateFragment.java. And the java code is like below:
The CreateFragment.java code:

package com.devname.appname.activities;

```<code>import android.app.Activity;
import android.app.AlertDialog;
import android.support.v4.app.Fragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.devname.appname.helpers.Admob;
import com.sangcomz.fishbun.FishBun;
import com.sangcomz.fishbun.adapter.image.impl.GlideAdapter;
import com.sangcomz.fishbun.define.Define;
import com.devname.appname.R;
import com.devname.appname.backgroundRemover.CutOut;
import com.devname.appname.helpers.Constants;
import com.devname.appname.utils.FileUtils;
import com.devname.appname.utils.StickerPacksManager;

import java.io.File;
import java.util.ArrayList;

public class CreateFragment extends Fragment {
    ImagesGridAdapter imagesGridAdapter;
    View view;

    public CreateFragment() {
        // Required empty public constructor
    }

    public static ArrayList<Uri> loadStickersCreated() {
        String directoryPath = Constants.STICKERS_CREATED_DIRECTORY_PATH;
        File directory = new File(directoryPath);
        ArrayList<Uri> images = new ArrayList<>();
        if (directory.exists()) {
            File[] stickersImages = directory.listFiles();
            for (File f : stickersImages) {
                if (f.isFile() && (f.getName().contains(".png") || f.getName().contains(".PNG"))) {
                    images.add(Uri.fromFile((f)));
                }
            }
        } else {
            directory.mkdir();
        }
       // verifyStickersCount();
        return images;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_create, container, false);
        Admob.createLoadBanner(getContext(), view);
        view.findViewById(R.id.create_sticker).setOnClickListener(v -> FishBun.with(getActivity())
                .setImageAdapter(new GlideAdapter())
                .setMaxCount(1)
                .exceptGif(true)
                .setMinCount(1)
                .setActionBarColor(getResources().getColor(R.color.colorPrimaryDark), getResources().getColor(R.color.colorPrimary), false)
                .setActionBarTitleColor(Color.parseColor("#ffffff"))
                .startAlbum());

        RecyclerView gridview = view.findViewById(R.id.stickers_created_grid);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(view.getContext(), 3);
        gridview.setLayoutManager(gridLayoutManager);
        imagesGridAdapter = new ImagesGridAdapter(view.getContext(), loadStickersCreated());
        gridview.setAdapter(imagesGridAdapter);
        verifyStickersCount();
        return view;
    }

    public void verifyStickersCount() {
        View linearLayout = view.findViewById(R.id.no_stickers_icon);
        if (imagesGridAdapter == null || imagesGridAdapter.getItemCount() == 0) {
            linearLayout.setVisibility(View.VISIBLE);
        } else {
            linearLayout.setVisibility(View.GONE);
        }
    }

    public static void addImageToGallery(final String filePath, final Context context) {

        ContentValues values = new ContentValues();

        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.MediaColumns.DATA, filePath);

        context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("TESTTTTTT",requestCode+"");
        if (requestCode == CutOut.CUTOUT_ACTIVITY_REQUEST_CODE) {
            Log.d("TESTTTTTT :::::",requestCode+"");
            switch (resultCode) {
                case Activity.RESULT_OK:
                    String imagePath_intent = data.getStringExtra("imagePath");
                    Uri imageUri = Uri.fromFile(new File(imagePath_intent));

                    Log.d("TESTTTTTT ::::: He",imageUri+"");
                    String stickerName = FileUtils.generateRandomIdentifier();
                    Uri imagePath = Uri.parse(Constants.STICKERS_CREATED_DIRECTORY_PATH + stickerName + ".PNG");
                    StickerPacksManager.createStickerImageFile(imageUri, imagePath, getActivity(), Bitmap.CompressFormat.PNG);
                    addImageToGallery(imagePath.getPath(), getActivity());
                    imagesGridAdapter.uries = loadStickersCreated();
                    imagesGridAdapter.notifyDataSetChanged();
                    Toast.makeText(getActivity(), "Sticker created", Toast.LENGTH_LONG).show();
                    verifyStickersCount();
                    break;
                case CutOut.CUTOUT_ACTIVITY_RESULT_ERROR_CODE:
                    Exception ex = CutOut.getError(data);
                    Log.d("TESTTTTTT :::::",ex+"::DDD");
                    break;
                default:
                    System.out.print("User cancelled the CutOut screen");
            }
        } else if (requestCode == Define.ALBUM_REQUEST_CODE) {
            ArrayList<Uri> uries;
            if (resultCode == Activity.RESULT_OK) {
                uries = data.getParcelableArrayListExtra(Define.INTENT_PATH);
                CutOut.activity().src(uries.get(0)).intro().start(getActivity());
            }
        }
    }

    public class ImagesGridAdapter extends RecyclerView.Adapter<ImageViewHolder> {
        public ArrayList<Uri> uries = new ArrayList<>();
        Context context;

        public ImagesGridAdapter(Context context, ArrayList<Uri> uries) {
            this.uries = uries;
            this.context = context;
        }

        @NonNull
        @Override
        public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            final Context context = viewGroup.getContext();
            final LayoutInflater layoutInflater = LayoutInflater.from(context);
            final View view = layoutInflater.inflate(R.layout.sticker_created_item, viewGroup, false);
            return new ImageViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ImageViewHolder imageAdapter, int index) {
            imageAdapter.imageView.setImageURI(uries.get(index));
            imageAdapter.imageView.setPadding(8, 8, 8, 8);
            imageAdapter.imageView.setOnLongClickListener(v -> {
                PopupMenu popupMenu = new PopupMenu(context, imageAdapter.imageView);
                popupMenu.inflate(R.menu.sticker_menu);
                popupMenu.setOnMenuItemClickListener(item -> {
                    switch (item.getItemId()) {
                     /*  case R.id.add_to_exist_stickerpack:
                            addToStickerPack(index);
                            break;*/
                        case R.id.delete_sticker:
                            this.deleteSticker(index);
                            break;
                        default:
                            break;
                    }
                    return false;
                });
                popupMenu.show();
                return false;
            });
        }

        void deleteSticker(int index) {
            new AlertDialog.Builder(context)
                    .setTitle("Deleting")
                    .setMessage("Are you sure you want to delete this sticker?")
                    .setPositiveButton("Yes", (dialog, which) -> {
                        Uri uri = uries.get(index);
                        FileUtils.deleteFile(uri.getPath(),context);
                        uries.remove(index);
                        notifyItemRemoved(index);
                        notifyDataSetChanged();
                        Toast.makeText(context, "Deleted", Toast.LENGTH_SHORT).show();
                        verifyStickersCount();
                    })
                    .setNegativeButton("No", null)
                    .show();
        }

         void addToStickerPack(int index) {
            Intent intent = new Intent(context, AddToStickerPackActivity.class);
            intent.setData(uries.get(index));
            startActivity(intent);
        }

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

    class ImageViewHolder extends RecyclerView.ViewHolder {
        SimpleDraweeView imageView;

        public ImageViewHolder(@NonNull View itemView) {
            super(itemView);
            this.imageView = itemView.findViewById(R.id.sticker_created_image);
        }

    }
}
</code>```

答:
As per your comments these are your app permissions in your manifest :

```<code><uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</code>```

you need to add read permissions to in order to get the files from directory so apply below permission to your manifest :

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

Also you should check this permission in run-time too because the user might deny it and this error will show again, you can do the check as below :

```<code>public boolean readExtertalStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int result = context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
            return result == PackageManager.PERMISSION_GRANTED;
        }
        return false;
    }
</code>```

For more details you can check here

Body:
I have an app run normally in the emulator with API 28. But when I run the app in the emulator with API 29 it shows

It does not only show keeps stopping in the emulator. I tried to install it on mobile and it also shows the same error.

The log shows this error like this:

2020-02-14 19:48:12.922 20370-20370/? E/stickerappmake: Unknown bits set in runtime_flags: 0x8000
2020-02-14 19:48:15.326 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:15.326 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:15.385 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:15.385 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.138 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.139 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.243 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.243 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:19.984 20370-20464/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:19.984 20370-20464/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.048 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.048 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.059 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.063 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:22.727 20370-20370/com.testdev.appname E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.testdev.appname, PID: 20370
    java.lang.NullPointerException: Attempt to get length of null array
        at com.testdev.appname.activities.CreateFragment.loadStickersCreated(CreateFragment.java:52)
        at com.testdev.appname.activities.CreateFragment.onCreateView(CreateFragment.java:88)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
        at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3273)
        at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3229)
        at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
        at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:620)
        at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1425)
        at android.app.Activity.performStart(Activity.java:7825)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3294)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

I see there some problems with the java code in CreateFragment.java. And the java code is like below:
The CreateFragment.java code:

package com.devname.appname.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.support.v4.app.Fragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.devname.appname.helpers.Admob;
import com.sangcomz.fishbun.FishBun;
import com.sangcomz.fishbun.adapter.image.impl.GlideAdapter;
import com.sangcomz.fishbun.define.Define;
import com.devname.appname.R;
import com.devname.appname.backgroundRemover.CutOut;
import com.devname.appname.helpers.Constants;
import com.devname.appname.utils.FileUtils;
import com.devname.appname.utils.StickerPacksManager;

import java.io.File;
import java.util.ArrayList;

public class CreateFragment extends Fragment {
    ImagesGridAdapter imagesGridAdapter;
    View view;

    public CreateFragment() {
        // Required empty public constructor
    }

    public static ArrayList<Uri> loadStickersCreated() {
        String directoryPath = Constants.STICKERS_CREATED_DIRECTORY_PATH;
        File directory = new File(directoryPath);
        ArrayList<Uri> images = new ArrayList<>();
        if (directory.exists()) {
            File[] stickersImages = directory.listFiles();
            for (File f : stickersImages) {
                if (f.isFile() && (f.getName().contains(".png") || f.getName().contains(".PNG"))) {
                    images.add(Uri.fromFile((f)));
                }
            }
        } else {
            directory.mkdir();
        }
       // verifyStickersCount();
        return images;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_create, container, false);
        Admob.createLoadBanner(getContext(), view);
        view.findViewById(R.id.create_sticker).setOnClickListener(v -> FishBun.with(getActivity())
                .setImageAdapter(new GlideAdapter())
                .setMaxCount(1)
                .exceptGif(true)
                .setMinCount(1)
                .setActionBarColor(getResources().getColor(R.color.colorPrimaryDark), getResources().getColor(R.color.colorPrimary), false)
                .setActionBarTitleColor(Color.parseColor("#ffffff"))
                .startAlbum());

        RecyclerView gridview = view.findViewById(R.id.stickers_created_grid);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(view.getContext(), 3);
        gridview.setLayoutManager(gridLayoutManager);
        imagesGridAdapter = new ImagesGridAdapter(view.getContext(), loadStickersCreated());
        gridview.setAdapter(imagesGridAdapter);
        verifyStickersCount();
        return view;
    }

    public void verifyStickersCount() {
        View linearLayout = view.findViewById(R.id.no_stickers_icon);
        if (imagesGridAdapter == null || imagesGridAdapter.getItemCount() == 0) {
            linearLayout.setVisibility(View.VISIBLE);
        } else {
            linearLayout.setVisibility(View.GONE);
        }
    }

    public static void addImageToGallery(final String filePath, final Context context) {

        ContentValues values = new ContentValues();

        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.MediaColumns.DATA, filePath);

        context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("TESTTTTTT",requestCode+"");
        if (requestCode == CutOut.CUTOUT_ACTIVITY_REQUEST_CODE) {
            Log.d("TESTTTTTT :::::",requestCode+"");
            switch (resultCode) {
                case Activity.RESULT_OK:
                    String imagePath_intent = data.getStringExtra("imagePath");
                    Uri imageUri = Uri.fromFile(new File(imagePath_intent));

                    Log.d("TESTTTTTT ::::: He",imageUri+"");
                    String stickerName = FileUtils.generateRandomIdentifier();
                    Uri imagePath = Uri.parse(Constants.STICKERS_CREATED_DIRECTORY_PATH + stickerName + ".PNG");
                    StickerPacksManager.createStickerImageFile(imageUri, imagePath, getActivity(), Bitmap.CompressFormat.PNG);
                    addImageToGallery(imagePath.getPath(), getActivity());
                    imagesGridAdapter.uries = loadStickersCreated();
                    imagesGridAdapter.notifyDataSetChanged();
                    Toast.makeText(getActivity(), "Sticker created", Toast.LENGTH_LONG).show();
                    verifyStickersCount();
                    break;
                case CutOut.CUTOUT_ACTIVITY_RESULT_ERROR_CODE:
                    Exception ex = CutOut.getError(data);
                    Log.d("TESTTTTTT :::::",ex+"::DDD");
                    break;
                default:
                    System.out.print("User cancelled the CutOut screen");
            }
        } else if (requestCode == Define.ALBUM_REQUEST_CODE) {
            ArrayList<Uri> uries;
            if (resultCode == Activity.RESULT_OK) {
                uries = data.getParcelableArrayListExtra(Define.INTENT_PATH);
                CutOut.activity().src(uries.get(0)).intro().start(getActivity());
            }
        }
    }

    public class ImagesGridAdapter extends RecyclerView.Adapter<ImageViewHolder> {
        public ArrayList<Uri> uries = new ArrayList<>();
        Context context;

        public ImagesGridAdapter(Context context, ArrayList<Uri> uries) {
            this.uries = uries;
            this.context = context;
        }

        @NonNull
        @Override
        public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            final Context context = viewGroup.getContext();
            final LayoutInflater layoutInflater = LayoutInflater.from(context);
            final View view = layoutInflater.inflate(R.layout.sticker_created_item, viewGroup, false);
            return new ImageViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ImageViewHolder imageAdapter, int index) {
            imageAdapter.imageView.setImageURI(uries.get(index));
            imageAdapter.imageView.setPadding(8, 8, 8, 8);
            imageAdapter.imageView.setOnLongClickListener(v -> {
                PopupMenu popupMenu = new PopupMenu(context, imageAdapter.imageView);
                popupMenu.inflate(R.menu.sticker_menu);
                popupMenu.setOnMenuItemClickListener(item -> {
                    switch (item.getItemId()) {
                     /*  case R.id.add_to_exist_stickerpack:
                            addToStickerPack(index);
                            break;*/
                        case R.id.delete_sticker:
                            this.deleteSticker(index);
                            break;
                        default:
                            break;
                    }
                    return false;
                });
                popupMenu.show();
                return false;
            });
        }

        void deleteSticker(int index) {
            new AlertDialog.Builder(context)
                    .setTitle("Deleting")
                    .setMessage("Are you sure you want to delete this sticker?")
                    .setPositiveButton("Yes", (dialog, which) -> {
                        Uri uri = uries.get(index);
                        FileUtils.deleteFile(uri.getPath(),context);
                        uries.remove(index);
                        notifyItemRemoved(index);
                        notifyDataSetChanged();
                        Toast.makeText(context, "Deleted", Toast.LENGTH_SHORT).show();
                        verifyStickersCount();
                    })
                    .setNegativeButton("No", null)
                    .show();
        }

         void addToStickerPack(int index) {
            Intent intent = new Intent(context, AddToStickerPackActivity.class);
            intent.setData(uries.get(index));
            startActivity(intent);
        }

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

    class ImageViewHolder extends RecyclerView.ViewHolder {
        SimpleDraweeView imageView;

        public ImageViewHolder(@NonNull View itemView) {
            super(itemView);
            this.imageView = itemView.findViewById(R.id.sticker_created_image);
        }

    }
}

Body:
As per your comments these are your app permissions in your manifest :

<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

you need to add read permissions to in order to get the files from directory so apply below permission to your manifest :

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Also you should check this permission in run-time too because the user might deny it and this error will show again, you can do the check as below :

public boolean readExtertalStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int result = context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
            return result == PackageManager.PERMISSION_GRANTED;
        }
        return false;
    }

For more details you can check here


来源: stackexchange

问:
Background different than XML preview
I have a drawable that creates a gradient in the background:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="radial"
        android:gradientRadius="75%p"
        android:startColor="#252A32"
        android:endColor="#0C0D10"
        />
</shape>
</code>```

However it looks completely off when running on an emulator:

XML preview:

On emulator:

Why is it showing that ugly circle display?

答: it may be because of different screen density. Emulator and AS showing differently best you can do is trying on an actual device.</p>

ContentLicense: CC BY-SA 4.0

Title: Background different than XML preview

Body:
I have a drawable that creates a gradient in the background:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="radial"
        android:gradientRadius="75%p"
        android:startColor="#252A32"
        android:endColor="#0C0D10"
        />
</shape>

However it looks completely off when running on an emulator:

XML preview:

On emulator:

Why is it showing that ugly circle display?


问:
How to handle string pattern categories

The problem

I have a column in dataframe that has 4 different string patterns like:

```<code>COLUMN |
'NE=123'
'NE=123, FR=4'
'NE=123, FR=4, S=5, CP=6'
'NE=123, FR=4, S=5, CP=6, SC=78, PP=99'
</code>```

I want to create column to encode patterns so that the output will be like:

```<code>COLUMN                                |  CATEGORY
AA=123                                | A
AA=123, BB=4                          | AB
AA=123, BB=4, CC=5, DD=6              | ABCD
AA=123, BB=4, CC=5, DD=6, EE=78, FF=99| ABCDEF
</code>```

I tried to see if that worked smth like

```<code>A = 'AA'
B = 'BB'
C = ['CC', 'DD']
D = ['EE', 'FF']
df[df['COLUMNS'].str.contains(A, B, '|'.join(C)==False, '|'.join(D)==False)]
</code>```

But I also get the rows with C and D included.

答:
Try this way:

DataFrame:

```<code>d={'COLUMN':
['AA=123' ,
'AA=123, BB=4',
'AA=123, BB=4, CC=5, DD=6 ',
'AA=123, BB=4, CC=5, DD=6, EE=78, FF=99']}

df=pd.DataFrame(d)
</code>```

Function to find pattern:

```<code>def f(s):
  m=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']

  p = []
  r=''

  for x in s:
    if x in m and x not in p:
      p.append(x)
      r+=str(x)

  return r

</code>```

Create category column:

```<code>df['Category']=df['COLUMN'].apply(lambda x :  f(x))
</code>```

Output:

```<code>    COLUMN                                  Cateory
0   AA=123                                  A
1   AA=123, BB=4                            AB
2   AA=123, BB=4, CC=5, DD=6                ABCD
3   AA=123, BB=4, CC=5, DD=6, EE=78, FF=99  ABCDEF
</code>```

Title: How to handle string pattern categories

Body:
The problem

I have a column in dataframe that has 4 different string patterns like:

COLUMN |
'NE=123'
'NE=123, FR=4'
'NE=123, FR=4, S=5, CP=6'
'NE=123, FR=4, S=5, CP=6, SC=78, PP=99'

I want to create column to encode patterns so that the output will be like:

COLUMN                                |  CATEGORY
AA=123                                | A
AA=123, BB=4                          | AB
AA=123, BB=4, CC=5, DD=6              | ABCD
AA=123, BB=4, CC=5, DD=6, EE=78, FF=99| ABCDEF

I tried to see if that worked smth like

A = 'AA'
B = 'BB'
C = ['CC', 'DD']
D = ['EE', 'FF']
df[df['COLUMNS'].str.contains(A, B, '|'.join(C)==False, '|'.join(D)==False)]

But I also get the rows with C and D included.

Body:
Try this way:

DataFrame:

d={'COLUMN':
['AA=123' ,
'AA=123, BB=4',
'AA=123, BB=4, CC=5, DD=6 ',
'AA=123, BB=4, CC=5, DD=6, EE=78, FF=99']}

df=pd.DataFrame(d)

Function to find pattern:

def f(s):
  m=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']

  p = []
  r=''

  for x in s:
    if x in m and x not in p:
      p.append(x)
      r+=str(x)

  return r

Create category column:

df['Category']=df['COLUMN'].apply(lambda x :  f(x))

Output:

    COLUMN                                  Cateory
0   AA=123                                  A
1   AA=123, BB=4                            AB
2   AA=123, BB=4, CC=5, DD=6                ABCD
3   AA=123, BB=4, CC=5, DD=6, EE=78, FF=99  ABCDEF


问:
Please help me why am I getting a negative value when using russian peasant algorithm when there is a negative input
I've tried using Russian peasant using recursion. Below is the code

```<code>public static int russianPeasantForMultiply(int a, int b){
    if(b == 1) return a;
    if(a == 0 || b == 0) return 0;
    int res = 0;
    if((b & 1) != 0){
        res += a;
    }

    return res + russianPeasantForMultiply(a << 1, b >> 1);
}
</code>```

It is working correctly for all inputs. However, I am unable to understand why is it working with negative inputs. Let's say a = 8, b = -4. The value of "a" overflows and then becomes a negative value. And later somehow I have the output -32 on the screen. Tried debugging the code using print statements, and here's the output for each stack call of the recursion.

```<code>>
C:\Users\s\Documents\A_Work_space>java RussianPeasant
8
-4
a = 32
b = -1
res = 32 ,
a = 64
b = -1
res = 64 ,
a = 128
b = -1
res = 128 ,
a = 256
b = -1
res = 256 ,
a = 512
b = -1
res = 512 ,
a = 1024
b = -1
res = 1024 ,
a = 2048
b = -1
res = 2048 ,
a = 4096
b = -1
res = 4096 ,
a = 8192
b = -1
res = 8192 ,
a = 16384
b = -1
res = 16384 ,
a = 32768
b = -1
res = 32768 ,
a = 65536
b = -1
res = 65536 ,
a = 131072
b = -1
res = 131072 ,
a = 262144
b = -1
res = 262144 ,
a = 524288
b = -1
res = 524288 ,
a = 1048576
b = -1
res = 1048576 ,
a = 2097152
b = -1
res = 2097152 ,
a = 4194304
b = -1
res = 4194304 ,
a = 8388608
b = -1
res = 8388608 ,
a = 16777216
b = -1
res = 16777216 ,
a = 33554432
b = -1
res = 33554432 ,
a = 67108864
b = -1
res = 67108864 ,
a = 134217728
b = -1
res = 134217728 ,
a = 268435456
b = -1
res = 268435456 ,
a = 536870912
b = -1
res = 536870912 ,
a = 1073741824
b = -1
res = 1073741824 ,
a = -2147483648
b = -1
res = -2147483648 ,
-32
</code>```

Please help me understand why is this happening.

答:
the shifting produces quite high values.

For potential values

higher than 2,147,483,647 or

below -2,147,483,648,

which are the biggest numbers that can be represented by an int, better use longs:

```<code>public static long russianPeasantForMultiply(long a, long b){
    if(b == 1) return a;
    if(a == 0 || b == 0) return 0;
    int res = 0;
    if((b & 1) != 0){
        res += a;
    }

    return res + russianPeasantForMultiply(a << 1, b >> 1);
}
</code>```

Note: a long ranges

from -9,223,372,036,854,775,808

to 9,223,372,036,854,775,807

Body:
I've tried using Russian peasant using recursion. Below is the code

public static int russianPeasantForMultiply(int a, int b){
    if(b == 1) return a;
    if(a == 0 || b == 0) return 0;
    int res = 0;
    if((b & 1) != 0){
        res += a;
    }

    return res + russianPeasantForMultiply(a << 1, b >> 1);
}

It is working correctly for all inputs. However, I am unable to understand why is it working with negative inputs. Let's say a = 8, b = -4. The value of "a" overflows and then becomes a negative value. And later somehow I have the output -32 on the screen. Tried debugging the code using print statements, and here's the output for each stack call of the recursion.

>
C:\Users\s\Documents\A_Work_space>java RussianPeasant
8
-4
a = 32
b = -1
res = 32 ,
a = 64
b = -1
res = 64 ,
a = 128
b = -1
res = 128 ,
a = 256
b = -1
res = 256 ,
a = 512
b = -1
res = 512 ,
a = 1024
b = -1
res = 1024 ,
a = 2048
b = -1
res = 2048 ,
a = 4096
b = -1
res = 4096 ,
a = 8192
b = -1
res = 8192 ,
a = 16384
b = -1
res = 16384 ,
a = 32768
b = -1
res = 32768 ,
a = 65536
b = -1
res = 65536 ,
a = 131072
b = -1
res = 131072 ,
a = 262144
b = -1
res = 262144 ,
a = 524288
b = -1
res = 524288 ,
a = 1048576
b = -1
res = 1048576 ,
a = 2097152
b = -1
res = 2097152 ,
a = 4194304
b = -1
res = 4194304 ,
a = 8388608
b = -1
res = 8388608 ,
a = 16777216
b = -1
res = 16777216 ,
a = 33554432
b = -1
res = 33554432 ,
a = 67108864
b = -1
res = 67108864 ,
a = 134217728
b = -1
res = 134217728 ,
a = 268435456
b = -1
res = 268435456 ,
a = 536870912
b = -1
res = 536870912 ,
a = 1073741824
b = -1
res = 1073741824 ,
a = -2147483648
b = -1
res = -2147483648 ,
-32

Please help me understand why is this happening.

Body:
the shifting produces quite high values.

For potential values

higher than 2,147,483,647 or

below -2,147,483,648,

which are the biggest numbers that can be represented by an int, better use longs:

public static long russianPeasantForMultiply(long a, long b){
    if(b == 1) return a;
    if(a == 0 || b == 0) return 0;
    int res = 0;
    if((b & 1) != 0){
        res += a;
    }

    return res + russianPeasantForMultiply(a << 1, b >> 1);
}

Note: a long ranges

from -9,223,372,036,854,775,808

to 9,223,372,036,854,775,807


问:
does DateTime keep itself updated in C#?
I am trying to create a folder based off of the current month/day using DateTime. After i initialize a new DateTime( 2011, 5, 16, 1, 1, 30); will this keep itself updated or reset every time the program is ran?</p>

答: No, DateTime is not a Clock object of any kind, it's just an object that represents a moment in time. Use DateTime.Now if you always need to get the current moment in time.

ContentLicense: CC BY-SA 3.0


问:
Swift - Integer conversion to Hours/Minutes/Seconds
I have a (somewhat?) basic question regarding time conversions in Swift.

I have an integer that I would like converted into Hours / Minutes / Seconds.

Example: Int = 27005 would give me:

```<code>7 Hours  30 Minutes 5 Seconds
</code>```

I know how to do this in PHP, but alas, swift isn't PHP.

答:
Swift 5 & String Response, In presentable format

```<code>public static func secondsToHoursMinutesSecondsStr (seconds : Int) -> String {
      let (hours, minutes, seconds) = secondsToHoursMinutesSeconds(seconds: seconds);
      var str = hours > 0 ? "\(hours) h" : ""
      str = minutes > 0 ? str + " \(minutes) min" : str
      str = seconds > 0 ? str + " \(seconds) sec" : str
      return str
  }

public static func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
        return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
 }
</code>```

Usage:

```<code>print(secondsToHoursMinutesSecondsStr(seconds: 20000)) // Result = "5 h 33 min 20 sec"
</code>```

Body:
I have a (somewhat?) basic question regarding time conversions in Swift.

I have an integer that I would like converted into Hours / Minutes / Seconds.

Example: Int = 27005 would give me:

7 Hours  30 Minutes 5 Seconds

I know how to do this in PHP, but alas, swift isn't PHP.

Body:
Swift 5 & String Response, In presentable format

public static func secondsToHoursMinutesSecondsStr (seconds : Int) -> String {
      let (hours, minutes, seconds) = secondsToHoursMinutesSeconds(seconds: seconds);
      var str = hours > 0 ? "\(hours) h" : ""
      str = minutes > 0 ? str + " \(minutes) min" : str
      str = seconds > 0 ? str + " \(seconds) sec" : str
      return str
  }

public static func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
        return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
 }

Usage:

print(secondsToHoursMinutesSecondsStr(seconds: 20000)) // Result = "5 h 33 min 20 sec"


问:
Set title size in seaborn
I´m working with several types of plots in seaborn reason for which I have to change the font sizes contantly in order to keep it readable. I´m using the plt.rcParams parameter to do it so for most of the options:

```<code>plt.rcParams['figure.figsize'] = 12, 6
plt.rcParams["legend.fontsize"] = 12
plt.rcParams["xtick.labelsize"] = 12
plt.rcParams["ytick.labelsize"] = 12
</code>```

But I have not found which is the alias for the title there, the equivalent of "ytick.labelsize"
I have tried several combinations like:

```<code>plt.rcParams["title.labelsize"] = 12
</code>```

But have not found the right one.

答:
You can see a sample rc file showing all possible options here.

I think you are looking for figure.titlesize

Title: Set title size in seaborn

Body:
I´m working with several types of plots in seaborn reason for which I have to change the font sizes contantly in order to keep it readable. I´m using the plt.rcParams parameter to do it so for most of the options:

plt.rcParams['figure.figsize'] = 12, 6
plt.rcParams["legend.fontsize"] = 12
plt.rcParams["xtick.labelsize"] = 12
plt.rcParams["ytick.labelsize"] = 12

But I have not found which is the alias for the title there, the equivalent of "ytick.labelsize"
I have tried several combinations like:

plt.rcParams["title.labelsize"] = 12

But have not found the right one.


问:
How to configure source compatbility level for xtend-maven-plugin?
Follow-up of Is there a P2 repository with an up-to-date javassist?

The issue I have is related to Java lambdas. I am also using xtend, and xtend lambdas are generated as Java lambdas if source level compatibility is set to Java 8+, but as anonymous classes.

I know how to set the source compatibility level in Eclipse, but how do I configure it for xtend-maven-plugin? I did not find documentation.

答:
The accepted answer did not work for me. I had to use

```<code><configuration>
    <javaSourceVersion>1.8</javaSourceVersion>
</configuration>
</code>```

in my pom file to force the xtend maven plugin to produce Java 8 code instead of the default, which is Java 1.6.
This is with xtend 2.20.

Body:
The accepted answer did not work for me. I had to use

<configuration>
    <javaSourceVersion>1.8</javaSourceVersion>
</configuration>

in my pom file to force the xtend maven plugin to produce Java 8 code instead of the default, which is Java 1.6.
This is with xtend 2.20.


问:
Dissecting Number Ranges
I'm trying to figure out the most efficient way to generate a WHERE query. I asked another question earlier, which was similar, but I will get right to the point on this one.

Given a collection of number ranges, ie 1-1000, 1500-1600 it is quite simple to create a mysql where condition to select records which are between these values.

ie, you would just do:

WHERE (lft BETWEEN 1 and 1000) OR (lft BETWEEN 1500-1600). However, what if you wanted to incorporate a NOT BETWEEN as well.

For example, if you define several rules, like...

ALLOW BETWEEN 1 - 1000

ALLOW BETWEEN 1500 - 1600

ALLOW BETWEEN 1250 - 1300

DENY BETWEEN 25 - 50

How can I merge these rules in order to efficiently generate a WHERE condition.
I would like the WHERE to dissect the ALLOW BETWEEN 1 - 1000 in order to create a gap in it. So that it would become 1-24 and 51-1000. Because the DENY rule is defined after the first rule, it "overwrites" the previous rules.

As another example,
Say that you have

ALLOW BETWEEN 5 - 15

DENY BETWEEN 10 - 50

ALLOW BETWEEN 45 - 60

Then I would like to generate a WHERE condition which would allow me to do:

WHERE (lft BETWEEN 5 and 9) OR (lft BETWEEN 45 and 60).

Notes (Edits)

Also, the maximum range that would ever allowed is 1 - 5600000. (Which would be 'Earth') ie. Allow everything on Earth.

The number ranges are actually the LEFT values in a NESTED SET MODEL. These aren't unique keys.
You can read why I want to do this in this question I asked earlier.
https://stackoverflow.com/questions/6020553/generating-a-mysql-between-where-condition-based-on-an-access-ruleset

Possible important note on my number ranges I maybe shouldn't have used the sample example which I did, but one important note about the nature of the number ranges is that, the ranges should actually always entirely consume or be consumed by a previous rule. For example, I used the example above, 10-50 allow, and deny 45-60. This wouldn't actually ever happen in my data set. It would actually be, allow 10-50, then the DENY would have to either be entirely consumed by that range, ie, 34-38. OR, entirely consume the previous rule. 9-51. This is because the ranges actually represent lft and rgt values in a nested set model and you cannot have overlaps like I presented.

I didn't think to mention that when asking the question, but after seeing the working sample code below, I can see that this note is actually important.

(Edited example mysql to include OR instead of AND as per comment below)

答:
I spent a little time trying to solve this (it's a neat problem), and came up with this. It's not optimal, nor am I guaranteeing it's perfect, but it might get you started:

```<code><?php

/*$cond = array(
    array('a', 5, 15),
    array('d', 9, 50),
    array('a', 45, 60)
);*/

$cond = array(
    array('a', 1, 1000),
    array('a', 1500, 1600),
    array('a', 1250, 1300),
    array('d', 25, 50)
);

$allow = array();

function merge_and_sort(&$allow)
{
    usort($allow, function($arr1, $arr2)
    {
        if ($arr1[0] > $arr2[0])
        {
            return 1;
        }
        else
        {
            return -1;
        }
    });

    $prev = false;

    for ($i = 0; $i < count($allow); $i++)
    {
        $c = $allow[$i];
        if ($i > 0 && $allow[$i][0] < $allow[$i - 1][1])
        {
            if ($allow[$i][1] <= $allow[$i - 1][1])
            {
                unset($allow[$i]);
            }
            else
            {
                $allow[$i - 1][1] = $allow[$i][1];
                unset($allow[$i]);
            }
        }
    }

    usort($allow, function($arr1, $arr2)
    {
        if ($arr1[0] > $arr2[0])
        {
            return 1;
        }
        else
        {
            return -1;
        }
    });
}

function remove_cond(&$allow, $start, $end)
{
    for ($i = 0; $i < count($allow); $i++)
    {
        if ($start > $allow[$i][0])
        {
            if ($end <= $allow[$i][1])
            {
                $temp = $allow[$i][1];
                $allow[$i][1] = $start;
                $allow []= array($end, $temp);
            }
            else
            {
                $found = false;
                for ($j = $i + 1; $j < count($allow); $j++)
                {
                    if ($end >= $allow[$j][0] && $end < $allow[$j][1])
                    {
                        $found = true;
                        $allow[$j][0] = $end;
                    }
                    else
                    {
                        unset($allow[$j]);
                    }
                }

                if (!$found)
                {
                    $allow[$i][1] = $start;
                }
            }
        }
    }
}

foreach ($cond as $c)
{
    if ($c[0] == "a")
    {
        $allow []= array($c[1], $c[2]);

        merge_and_sort($allow);
    }
    else
    {
        remove_cond($allow, $c[1], $c[2]);
        merge_and_sort($allow);
    }
}

var_dump($allow);
</code>```

The last var_dump outputs:

```<code>array(4) {
  [0]=>
  array(2) {
    [0]=>
    int(1)
    [1]=>
    int(25)
  }
  [1]=>
  array(2) {
    [0]=>
    int(50)
    [1]=>
    int(1000)
  }
  [2]=>
  array(2) {
    [0]=>
    int(1250)
    [1]=>
    int(1300)
  }
  [3]=>
  array(2) {
    [0]=>
    int(1500)
    [1]=>
    int(1600)
  }
}
</code>```

Edited to use the first example instead of the second.

Title: Dissecting Number Ranges

Body:
I spent a little time trying to solve this (it's a neat problem), and came up with this. It's not optimal, nor am I guaranteeing it's perfect, but it might get you started:

<?php

/*$cond = array(
    array('a', 5, 15),
    array('d', 9, 50),
    array('a', 45, 60)
);*/

$cond = array(
    array('a', 1, 1000),
    array('a', 1500, 1600),
    array('a', 1250, 1300),
    array('d', 25, 50)
);

$allow = array();

function merge_and_sort(&$allow)
{
    usort($allow, function($arr1, $arr2)
    {
        if ($arr1[0] > $arr2[0])
        {
            return 1;
        }
        else
        {
            return -1;
        }
    });

    $prev = false;

    for ($i = 0; $i < count($allow); $i++)
    {
        $c = $allow[$i];
        if ($i > 0 && $allow[$i][0] < $allow[$i - 1][1])
        {
            if ($allow[$i][1] <= $allow[$i - 1][1])
            {
                unset($allow[$i]);
            }
            else
            {
                $allow[$i - 1][1] = $allow[$i][1];
                unset($allow[$i]);
            }
        }
    }

    usort($allow, function($arr1, $arr2)
    {
        if ($arr1[0] > $arr2[0])
        {
            return 1;
        }
        else
        {
            return -1;
        }
    });
}

function remove_cond(&$allow, $start, $end)
{
    for ($i = 0; $i < count($allow); $i++)
    {
        if ($start > $allow[$i][0])
        {
            if ($end <= $allow[$i][1])
            {
                $temp = $allow[$i][1];
                $allow[$i][1] = $start;
                $allow []= array($end, $temp);
            }
            else
            {
                $found = false;
                for ($j = $i + 1; $j < count($allow); $j++)
                {
                    if ($end >= $allow[$j][0] && $end < $allow[$j][1])
                    {
                        $found = true;
                        $allow[$j][0] = $end;
                    }
                    else
                    {
                        unset($allow[$j]);
                    }
                }

                if (!$found)
                {
                    $allow[$i][1] = $start;
                }
            }
        }
    }
}

foreach ($cond as $c)
{
    if ($c[0] == "a")
    {
        $allow []= array($c[1], $c[2]);

        merge_and_sort($allow);
    }
    else
    {
        remove_cond($allow, $c[1], $c[2]);
        merge_and_sort($allow);
    }
}

var_dump($allow);

The last var_dump outputs:

array(4) {
  [0]=>
  array(2) {
    [0]=>
    int(1)
    [1]=>
    int(25)
  }
  [1]=>
  array(2) {
    [0]=>
    int(50)
    [1]=>
    int(1000)
  }
  [2]=>
  array(2) {
    [0]=>
    int(1250)
    [1]=>
    int(1300)
  }
  [3]=>
  array(2) {
    [0]=>
    int(1500)
    [1]=>
    int(1600)
  }
}

Edited to use the first example instead of the second.


问:
Can't get element SELENIUM PYTHON
I need to get element from page and then print it out
But it always print out this:

```<code>[<selenium.webdriver.remote.webelement.WebElement (session="636e500d9db221d6b7b10b8d7849e1b5",
    element="4f0ccc3b-44b0-4cf2-abd4-95a70278bf77")>...
</code>```

My code:

```<code>film_player = free_filmy_url + filmPlayerPart
dr = webdriver.Chrome()
dr.get(film_player)
captcha_button = dr.find_element_by_xpath('/html/body/form/div/input[1]')
captcha_items = dr.find_elements_by_class_name('captchaMyImg')
print(captcha_items)
</code>```

答:
You can iterate through the captcha_items and print each of them.</p>

```<code>for captcha_item in captcha_items:
    # you can access each item here as "captcha_item"
    print(captcha_item.text()) # if you are trying to print the text

</code>```

Title: Can't get element SELENIUM PYTHON

Body:
I need to get element from page and then print it out
But it always print out this:

[<selenium.webdriver.remote.webelement.WebElement (session="636e500d9db221d6b7b10b8d7849e1b5",
    element="4f0ccc3b-44b0-4cf2-abd4-95a70278bf77")>...

My code:

film_player = free_filmy_url + filmPlayerPart
dr = webdriver.Chrome()
dr.get(film_player)
captcha_button = dr.find_element_by_xpath('/html/body/form/div/input[1]')
captcha_items = dr.find_elements_by_class_name('captchaMyImg')
print(captcha_items)

Body:
You can iterate through the captcha_items and print each of them.

for captcha_item in captcha_items:
    # you can access each item here as "captcha_item"
    print(captcha_item.text()) # if you are trying to print the text


问:
If one checkbox is checked, set the other to unchecked
I have two checkboxes on my form; chkBuried and chkAboveGround. I want to set it up so if one is checked, the other is unchecked. How can I do this?

I have tried the CheckChanged property:

```<code>private void chkBuried_CheckedChanged(object sender, EventArgs e)
{
    chkAboveGround.Checked = false;
}
private void chkAboveGround_CheckedChanged(object sender, EventArgs e)
{
    chkBuried.Checked = false;
}
</code>```

And it works, just not as well as I hoped. That is, when I check chkBuried, then check chkAboveGround, both boxes become unchecked before I can check another one again.

答:
I needed to show or not show a table when activating the CheckBox, how they were two, if I activated both, everything was fine, but if I tried to deactivate one later, the other was also deactivated. PD: The default value for the tables that I used was Visible=false. The solution I got was the following:</p>

```<code> protected void YourNameOfMethodForBothCheckBox(object sender, EventArgs e)
    {
        if (CheckBox_1.Checked == true)
        {
            Table_1.Visible = true;

            if (CheckBox_2.Checked == true)
            {
                Table_2.Visible = true;
            }
            else { Table_2.Visible = false; }

        }
        else
        {
            Table_1.Visible = false;

            if (CheckBox_2.Checked == false)
            {
                Table_2.Visible = false;
            }
            else
            {
                Table_2.Visible = true;

            }
        }

    }
</code>```

Body:
I have two checkboxes on my form; chkBuried and chkAboveGround. I want to set it up so if one is checked, the other is unchecked. How can I do this?

I have tried the CheckChanged property:

private void chkBuried_CheckedChanged(object sender, EventArgs e)
{
    chkAboveGround.Checked = false;
}
private void chkAboveGround_CheckedChanged(object sender, EventArgs e)
{
    chkBuried.Checked = false;
}

And it works, just not as well as I hoped. That is, when I check chkBuried, then check chkAboveGround, both boxes become unchecked before I can check another one again.

Body:
I needed to show or not show a table when activating the CheckBox, how they were two, if I activated both, everything was fine, but if I tried to deactivate one later, the other was also deactivated. PD: The default value for the tables that I used was Visible=false. The solution I got was the following:

 protected void YourNameOfMethodForBothCheckBox(object sender, EventArgs e)
    {
        if (CheckBox_1.Checked == true)
        {
            Table_1.Visible = true;

            if (CheckBox_2.Checked == true)
            {
                Table_2.Visible = true;
            }
            else { Table_2.Visible = false; }

        }
        else
        {
            Table_1.Visible = false;

            if (CheckBox_2.Checked == false)
            {
                Table_2.Visible = false;
            }
            else
            {
                Table_2.Visible = true;

            }
        }

    }


问:
How can i validate a serializer field with ModelSerializer. Does the validate() method get called on create or do i have to call the method
I have a serializer (ModelSerializer) where i need to validate a field which will be passed to the validate method.

CompanySerializer

```<code>class CompanySerializer(serializers.ModelSerializer):

    def validate_vat_number(self, vat_no):

        vatlayer = "http://apilayer.net/api/validate?access_key={api_key}&vat_number={VAT_NUMBER}".format(api_key=settings.VATLAYER, VAT_NUMBER=vat_no)

        vatlayer = json.loads(vatlayer)

        if vatlayer['valid'] is not True:
            raise serializers.ValidationError("VAT number not valid")

        return vat_no

    class Meta:
        model = Company
        fields = ('profile', 'name', 'address', 'currency', 'id_number', 'vat_number', 'vat_company_name', 'email', 'phone', 'fixed_phone')

</code>```

My question is, does the validate_vat_number method get called when the create method is triggered, and if so, how do i pass the vat_no parameter? If not, where do i call this method? And is it possible to do it without overwriting the create method?

My view

```<code>class CompanyAPI(viewsets.ModelViewSet):

    queryset = Company.objects.all()
    serializer_class = CompanySerializer

</code>```

It would be perfect if i could somehow validate without using @action in the view since that makes another endpoint. My goal is to validate and save the object with one post request

答:
Here is the validation order:

Field deserialization (serializer.to_internal_value and field.run_validators)

serializer.validate_[field] is called for each field

Serializer-level validators are called (serializer.run_validation)

serializer.validate

create method is called after all validations completed.

So in your case, since it's not an actually field error but rather a verification error, you should use object level validation (step 4):

```<code>def validate(self, data):
    vatlayer = "http://apilayer.net/api/validate?access_key={api_key}&vat_number={VAT_NUMBER}".format(api_key=settings.VATLAYER, VAT_NUMBER=data[vat_no])

    vatlayer = json.loads(vatlayer)

    if vatlayer['valid'] is not True:
        raise serializers.ValidationError("VAT number not valid")

    return data
</code>```

Body:
I have a serializer (ModelSerializer) where i need to validate a field which will be passed to the validate method.

CompanySerializer

class CompanySerializer(serializers.ModelSerializer):

    def validate_vat_number(self, vat_no):

        vatlayer = "http://apilayer.net/api/validate?access_key={api_key}&vat_number={VAT_NUMBER}".format(api_key=settings.VATLAYER, VAT_NUMBER=vat_no)

        vatlayer = json.loads(vatlayer)

        if vatlayer['valid'] is not True:
            raise serializers.ValidationError("VAT number not valid")

        return vat_no

    class Meta:
        model = Company
        fields = ('profile', 'name', 'address', 'currency', 'id_number', 'vat_number', 'vat_company_name', 'email', 'phone', 'fixed_phone')

My question is, does the validate_vat_number method get called when the create method is triggered, and if so, how do i pass the vat_no parameter? If not, where do i call this method? And is it possible to do it without overwriting the create method?

My view

class CompanyAPI(viewsets.ModelViewSet):

    queryset = Company.objects.all()
    serializer_class = CompanySerializer

It would be perfect if i could somehow validate without using @action in the view since that makes another endpoint. My goal is to validate and save the object with one post request

Body:
Here is the validation order:

Field deserialization (serializer.to_internal_value and field.run_validators)

serializer.validate_[field] is called for each field

Serializer-level validators are called (serializer.run_validation)

serializer.validate

create method is called after all validations completed.

So in your case, since it's not an actually field error but rather a verification error, you should use object level validation (step 4):

def validate(self, data):
    vatlayer = "http://apilayer.net/api/validate?access_key={api_key}&vat_number={VAT_NUMBER}".format(api_key=settings.VATLAYER, VAT_NUMBER=data[vat_no])

    vatlayer = json.loads(vatlayer)

    if vatlayer['valid'] is not True:
        raise serializers.ValidationError("VAT number not valid")

    return data


问:
how to disable a button and change text when clicked
I'm setting a text in a button when clicked, but it makes it so quick. In fact it changes it for half seconds and returns it to the old message....it doesn't disable it

I'm using this in my html

```<code>
 <button mat-flat-button color="accent"
   (click)="cancelBuildingImage(element.buildId); setSaving($event.target, 'Canceling...')">
            Cancel Build
    </button>

</code>```

and this in ts:

```<code>
setSaving(element, text) {
    element.textContent = text;
    element.disabled = true;
  }

</code>```

Thanks in advance for your help

答:
You could store the text in a property or in your element variable.

Something like this:

<button mat-flat-button color="accent" (click)="cancelBuildingImage(element.buildId); text = 'Cancelling...'">
     {{ text }}
</button>
```

<pre class="lang-js prettyprint-override"><code>export class MyComponent {
    text = 'Cancel Build';
}
</code>```

Body:
I'm setting a text in a button when clicked, but it makes it so quick. In fact it changes it for half seconds and returns it to the old message....it doesn't disable it

I'm using this in my html

 <button mat-flat-button color="accent"
   (click)="cancelBuildingImage(element.buildId); setSaving($event.target, 'Canceling...')">
            Cancel Build
    </button>

and this in ts:

setSaving(element, text) {
    element.textContent = text;
    element.disabled = true;
  }

Thanks in advance for your help

Body:
You could store the text in a property or in your element variable.

Something like this:

<button mat-flat-button color="accent" (click)="cancelBuildingImage(element.buildId); text = 'Cancelling...'">
     {{ text }}
</button>

export class MyComponent {
    text = 'Cancel Build';
}


问:
How to exclude an anonyomous class from jacoco?
I am seeing class CacheConfig.new CacheLoader() {...} in my jacoco report. Is there a way to exclude it?

答: Adding <code>**/*$*.*</code> in excluded list ignores all anonymous binders and classes in your classes </p>

Body: Adding **/*$*.* in excluded list ignores all anonymous binders and classes in your classes


问:
How to use a delegate between a Winforms Form and a WPF Usercontrol hosted by an elementhost in the Winforms form?
I have a Winforms app (class named Form_WinForms for the example) and I want to add an elementhost control to it in order to host a WPF Usercontrol (named Form_WPF).

But I don't know how to handle the delegates between them: I want to exchange with the Form_WPF controls from the Form_WinForms and vice versa. How could I do ? Thanks

In the example, I just want to modify the text of the control textbox (WPF technologie) by clicking inside a Winforms button.

In Winforms class:

```<code>// In Form_WinForms (my main form)

private void btn_Debug_Click(object sender, EventArgs e)
{
    // Form_WPF.GetInstance().Invoke(new ChangeTextBox_WPF(Form_WPF._ChangeTextBox_WPF), Form_WPF.GetInstance().TextBoxDebug, "test"); // what I would have done if Form_WPF was a WinForms form
    Form_WPF.GetInstance().Dispatcher.Invoke(new ChangeTextBox_WPF(Form_WPF._ChangeTextBox_WPF), Form_WPF.GetInstance().TextBoxDebug, "test");
}
</code>```

In WPF class:

```<code>// In the Usercontrol Form_WPF (which is hosted by an elementhost in Winforms)

private delegate void ChangeTextBox_WPF(System.Windows.Controls.TextBox TextBox, String texte);
public static void _ChangeTextBox_WPF(System.Windows.Controls.TextBox TextBox, String texte) { TextBox.Text = texte; TextBox.Tag = texte; }

private static Form_WPF _Form_WPF;

public static Form_WPF GetInstance()
{
    if (_Form_WPF == null)
    {
        _Form_WPF = new Form_WPF();
    }
    return _Form_WPF;
}
</code>```

答:
Cast the Child property of the ElementHost to your WPF control type, e.g.:

```<code>Form_WPF wpfControl = elementHost.Host as Form_WPF;
</code>```

Then you can access any members of the hosted instance as usual.

Body:
I have a Winforms app (class named Form_WinForms for the example) and I want to add an elementhost control to it in order to host a WPF Usercontrol (named Form_WPF).

But I don't know how to handle the delegates between them: I want to exchange with the Form_WPF controls from the Form_WinForms and vice versa. How could I do ? Thanks

In the example, I just want to modify the text of the control textbox (WPF technologie) by clicking inside a Winforms button.

In Winforms class:

// In Form_WinForms (my main form)

private void btn_Debug_Click(object sender, EventArgs e)
{
    // Form_WPF.GetInstance().Invoke(new ChangeTextBox_WPF(Form_WPF._ChangeTextBox_WPF), Form_WPF.GetInstance().TextBoxDebug, "test"); // what I would have done if Form_WPF was a WinForms form
    Form_WPF.GetInstance().Dispatcher.Invoke(new ChangeTextBox_WPF(Form_WPF._ChangeTextBox_WPF), Form_WPF.GetInstance().TextBoxDebug, "test");
}

In WPF class:

// In the Usercontrol Form_WPF (which is hosted by an elementhost in Winforms)

private delegate void ChangeTextBox_WPF(System.Windows.Controls.TextBox TextBox, String texte);
public static void _ChangeTextBox_WPF(System.Windows.Controls.TextBox TextBox, String texte) { TextBox.Text = texte; TextBox.Tag = texte; }

private static Form_WPF _Form_WPF;

public static Form_WPF GetInstance()
{
    if (_Form_WPF == null)
    {
        _Form_WPF = new Form_WPF();
    }
    return _Form_WPF;
}

Body:
Cast the Child property of the ElementHost to your WPF control type, e.g.:

Form_WPF wpfControl = elementHost.Host as Form_WPF;

Then you can access any members of the hosted instance as usual.


问:
What is the best way to create file folder for specifi user in laravel?
I have a simple dashboard in which users can register and do some stuff, now I would like to generate a file with username and his id; something like widget/obama2030.js in Laravel when a user is registered

my app structure:

myapp

```<code>-app
-bootstrap
-database
-resource
 .....
-widget
 -------
</code>```

in my user registration controller, I have the following.

```<code>protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        ]);

    File::makeDirectory('/widget/'.$user->name.Auth::user()->id, 0755, true);

    return $user;
}
</code>```

Now when user click the button register I am getting the following error

```<code>ErrorException (E_NOTICE)
Trying to get property of non-object
</code>```

what is wrong with my code????

答:
You've created a user, but you haven't logged them in as that newly created user.

As such, Auth::user() is null, and (null)->id won't work.

After creating your user, log them in:

```<code>Auth::login($user)
</code>```

and your code should work.

That said, it's typically not necessary (and it's quite messy) to actually create files for each user - you can almost certainly handle this via a Laravel route, instead.

Body:
I have a simple dashboard in which users can register and do some stuff, now I would like to generate a file with username and his id; something like widget/obama2030.js in Laravel when a user is registered

my app structure:

myapp

-app
-bootstrap
-database
-resource
 .....
-widget
 -------

in my user registration controller, I have the following.

protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        ]);

    File::makeDirectory('/widget/'.$user->name.Auth::user()->id, 0755, true);

    return $user;
}

Now when user click the button register I am getting the following error

ErrorException (E_NOTICE)
Trying to get property of non-object

what is wrong with my code????

Body:
You've created a user, but you haven't logged them in as that newly created user.

As such, Auth::user() is null, and (null)->id won't work.

After creating your user, log them in:

Auth::login($user)

and your code should work.

That said, it's typically not necessary (and it's quite messy) to actually create files for each user - you can almost certainly handle this via a Laravel route, instead.


问:
Apache / ColdFusion: Replicated Websites?
So I've done this before a number of different ways, but I wanted to get the opinion of the community.

What needs to be accomplished is essentially dynamic URLs that pull in content depending on what exists in the URL. Example:

http://www.domain.com/userA/

This URL would pull in userA's content and populate the website. The idea is so multiple people can have their own custom spot on the website. It's the same website for everyone, but the user specific information changes per the URL request.

Taking this a step further, to be able to call example.com/userA/mediaID and display a video from userA.

Like I said, I've done this before, but I want to do it with best practices in mind... perhaps a combination of htaccess and CGI?

Thoughts?

答:
Use the Apache rewrite module to send the request through a front controller. So your httpd.conf would have an entry that looks something like this:

```<code># QSA preserves original query string
# PT Sends the new URI to ColdFusion
# NS (No [internal] Subrequests) is necessary because expandPath() will not work otherwise
RewriteRule ^/(.*) /frontcontroller.cfm [E=ORIGINAL_URI:%{REQUEST_URI},QSA,PT,NS]
</code>```

This makes CGI.ORIGINAL_URI available to ColdFusion code this allows for dynamically generating the response and securing it relative to the user session.

Body:
Use the Apache rewrite module to send the request through a front controller. So your httpd.conf would have an entry that looks something like this:

# QSA preserves original query string
# PT Sends the new URI to ColdFusion
# NS (No [internal] Subrequests) is necessary because expandPath() will not work otherwise
RewriteRule ^/(.*) /frontcontroller.cfm [E=ORIGINAL_URI:%{REQUEST_URI},QSA,PT,NS]

This makes CGI.ORIGINAL_URI available to ColdFusion code this allows for dynamically generating the response and securing it relative to the user session.


答:
I would do it with a combination of functions in a lambda:

```<code>import pandas as pd
import re
df = pd.DataFrame({'column_1':['NE=123','NE=123, FR=4' ,'NE=123, FR=4, S=5, CP=6',
                               'NE=123, FR=4, S=5, CP=6, SC=78, PP=99'],
                    'index':[0,1,2,3]})
print(df)
df['category'] = df['column_1'].apply(lambda x: ''.join(sorted(list(set(re.findall(r'[A-Z]+',x))))))
print(df)
</code>```

Output:

```<code>                                column_1  index     category
0                                 NE=123      0           NE
1                           NE=123, FR=4      1         FRNE
2                NE=123, FR=4, S=5, CP=6      2      CPFRNES
3  NE=123, FR=4, S=5, CP=6, SC=78, PP=99      3  CPFRNEPPSSC
</code>```

Title: How to handle string pattern categories

Body:
The problem

I have a column in dataframe that has 4 different string patterns like:

COLUMN |
'NE=123'
'NE=123, FR=4'
'NE=123, FR=4, S=5, CP=6'
'NE=123, FR=4, S=5, CP=6, SC=78, PP=99'

I want to create column to encode patterns so that the output will be like:

COLUMN                                |  CATEGORY
AA=123                                | A
AA=123, BB=4                          | AB
AA=123, BB=4, CC=5, DD=6              | ABCD
AA=123, BB=4, CC=5, DD=6, EE=78, FF=99| ABCDEF

I tried to see if that worked smth like

A = 'AA'
B = 'BB'
C = ['CC', 'DD']
D = ['EE', 'FF']
df[df['COLUMNS'].str.contains(A, B, '|'.join(C)==False, '|'.join(D)==False)]

But I also get the rows with C and D included.

Body:
I would do it with a combination of functions in a lambda:

import pandas as pd
import re
df = pd.DataFrame({'column_1':['NE=123','NE=123, FR=4' ,'NE=123, FR=4, S=5, CP=6',
                               'NE=123, FR=4, S=5, CP=6, SC=78, PP=99'],
                    'index':[0,1,2,3]})
print(df)
df['category'] = df['column_1'].apply(lambda x: ''.join(sorted(list(set(re.findall(r'[A-Z]+',x))))))
print(df)

Output:

                                column_1  index     category
0                                 NE=123      0           NE
1                           NE=123, FR=4      1         FRNE
2                NE=123, FR=4, S=5, CP=6      2      CPFRNES
3  NE=123, FR=4, S=5, CP=6, SC=78, PP=99      3  CPFRNEPPSSC


问:
Map sharing between different ebpf program types
Is it possible to share ebpf maps between different program types. I need to share a map between a tc-bpf program and a cgroup bpf program. This should be possible if the map is pinned to file system that act as global namespace. But, I haven't got this working.

The map is created by tc-bpf program and pinned to global namespace. Since it is tc-bpf program, the map is of type  struct bpf_elf_map. This bpf program is loaded via iproute2.

Now, I have a cgroup bpf program that should be accessing this map, but since it is loaded via a user.c (libbpf) or bpftool and not iproute, the map that is defined here cannot be ‘bpf_elf_map’, but it is struct bpf_map_def. So in the cgroup bpf program, the same map is defined as struct bpf_map_def and not struct bpf_elf_map.

Probably because of this the cgroup program gets a new map_id when I dump the maps (and does not share the intended map), ideally when the same map is shared across bpf programs, these bpf programs would be having the same map_id associated with their unique prog_ids.

答:
It is possible to share access to eBPF maps between programs of different types.

First, you can forget about those differences between struct bpf_elf_map and struct bpf_map_def. They are structs used in user space to build the objects to pass to the kernel. Iproute2 and libbpf may not use the same struct/attribute names, but they both end up passing the map metadata to the bpf() system call in the same format, or the kernel would not understand what map is to be created.

When they are loaded to the kernel, eBPF programs refer to a given map through file descriptors to this map. This means that the process calling the bpf() system call to load the program first has to retrieve file descriptors to the map to use. So the two following cases may happen:

User space application (ip, tc, bpftool...) parses the ELF object file and collects map-related metadata. It does not identify (and possibly did not even try to identify) any existing map that should be reused for the program. So it creates a new map with the bpf() syscall, which returns a file descriptor to this newly-created map. This file descriptor is used in the program instructions referring to map access (once the program is loaded in the kernel, those file descriptors will be replaced by the map address), and the program is then loaded with the bpf() syscall. This is what happens with your tc program, and in your case it seems, with your cgroup program which is creating a second map.

Or user application parses the ELF object file, and finds somehow that there is already an existing map that the program should use. For example, it finds a map of id 1337, or a pinned map under /sys/fs/bpf/. In that case it retrieves a file descriptor to that map (from the id with bpf() syscall, from a pinned path with open()). Then as in the first case, it uses this file descriptor to prepare and then load the program.

Libbpf provides a way to reuse a file descriptor for a given map to use with a program. See for example bpf_map__reuse_fd(). Bpftool uses it to support reusing existing maps, with the map argument for bpftool prog load (see man bpftool-prog). For example, load a program from foo.o and tell it to reuse map of id 27 for the first map found in the object file, then the map pinned at /sys/fs/bpf/foomap for the map named foomap in the object file:

```<code># bpftool prog load foo.o /sys/fs/bpf/foo_prog \
        map idx 0 id 27 \
        map foomap stats pinned /sys/fs/bpf/foomap
</code>```

Body:
It is possible to share access to eBPF maps between programs of different types.

First, you can forget about those differences between struct bpf_elf_map and struct bpf_map_def. They are structs used in user space to build the objects to pass to the kernel. Iproute2 and libbpf may not use the same struct/attribute names, but they both end up passing the map metadata to the bpf() system call in the same format, or the kernel would not understand what map is to be created.

When they are loaded to the kernel, eBPF programs refer to a given map through file descriptors to this map. This means that the process calling the bpf() system call to load the program first has to retrieve file descriptors to the map to use. So the two following cases may happen:

User space application (ip, tc, bpftool...) parses the ELF object file and collects map-related metadata. It does not identify (and possibly did not even try to identify) any existing map that should be reused for the program. So it creates a new map with the bpf() syscall, which returns a file descriptor to this newly-created map. This file descriptor is used in the program instructions referring to map access (once the program is loaded in the kernel, those file descriptors will be replaced by the map address), and the program is then loaded with the bpf() syscall. This is what happens with your tc program, and in your case it seems, with your cgroup program which is creating a second map.

Or user application parses the ELF object file, and finds somehow that there is already an existing map that the program should use. For example, it finds a map of id 1337, or a pinned map under /sys/fs/bpf/. In that case it retrieves a file descriptor to that map (from the id with bpf() syscall, from a pinned path with open()). Then as in the first case, it uses this file descriptor to prepare and then load the program.

Libbpf provides a way to reuse a file descriptor for a given map to use with a program. See for example bpf_map__reuse_fd(). Bpftool uses it to support reusing existing maps, with the map argument for bpftool prog load (see man bpftool-prog). For example, load a program from foo.o and tell it to reuse map of id 27 for the first map found in the object file, then the map pinned at /sys/fs/bpf/foomap for the map named foomap in the object file:

# bpftool prog load foo.o /sys/fs/bpf/foo_prog \
        map idx 0 id 27 \
        map foomap stats pinned /sys/fs/bpf/foomap


问:
How insert records into a table from another table with conditions
I'm working on a program which contains an Insert into statement, and I would like to add some conditions to it.

Let's say that the TARGET_TABLE has 2 primary key columns called A, B and 1 variable C (whose values are "NO" or "YES").

And same for the SOURCE_TABLE.

If the record in the SOURCE_TABLE does not exist in the TARGET_TABLE then insert it

If there is already a record present in the TARGET_TABLE with same values for the primary key columns, and with variable C = "NO", then update the record only if the new record has a variable C = "YES"

If there is already a record present in the TARGET_TABLE with same values for the primary key columns, and with variable C = "YES", then don't insert

Do you have some ideas? I was trying with the "where not exists" then I tried using "Case when" but I can't figure out how to mix the 3 cases in the same program...

答:
I think this merge covers all cases (Oracle solution):

```<code>merge into target_table t
using source_table s
on (t.a = s.a and t.b = s.b)
when matched then update set d = s.d, c = s.c where t.c = 'NO' and s.c = 'YES'
when not matched then insert values (s.a, s.b, s.c, s.d)
</code>```

So for these sample data:

```<code>create table target_table(a, b, c, d) as (
   select 1, 2, 'NO',  100 from dual union all
   select 1, 3, 'NO',  100 from dual union all
   select 1, 4, 'NO',  100 from dual union all
   select 1, 5, 'YES', 100 from dual );

create table source_table(a, b, c, d) as (
   select 1, 1, 'NO',  200  from dual union all
   select 1, 3, 'YES', 200  from dual union all
   select 1, 4, 'NO',  200  from dual union all
   select 1, 5, 'YES', 200  from dual );
</code>```

you get:

```<code>     A          B C            D
------ ---------- --- ----------
     1          1 NO         200
     1          2 NO         100
     1          3 YES        200
     1          4 NO         100
     1          5 YES        100
</code>```

dbfiddle

Body:
I think this merge covers all cases (Oracle solution):

merge into target_table t
using source_table s
on (t.a = s.a and t.b = s.b)
when matched then update set d = s.d, c = s.c where t.c = 'NO' and s.c = 'YES'
when not matched then insert values (s.a, s.b, s.c, s.d)

So for these sample data:

create table target_table(a, b, c, d) as (
   select 1, 2, 'NO',  100 from dual union all
   select 1, 3, 'NO',  100 from dual union all
   select 1, 4, 'NO',  100 from dual union all
   select 1, 5, 'YES', 100 from dual );

create table source_table(a, b, c, d) as (
   select 1, 1, 'NO',  200  from dual union all
   select 1, 3, 'YES', 200  from dual union all
   select 1, 4, 'NO',  200  from dual union all
   select 1, 5, 'YES', 200  from dual );

you get:

     A          B C            D
------ ---------- --- ----------
     1          1 NO         200
     1          2 NO         100
     1          3 YES        200
     1          4 NO         100
     1          5 YES        100

dbfiddle


问:
How to change repo with magit emacs?
I need to work with a few different git repositories. How to switch between them using magit? Magit allows me to choose a directory when I just start it.. But it is not clear for me how to switch to another repo if required. I've looked at magit cheatsheet and docs but haven't found an answer. Thanks.</p>

答:
Magit uses current working directory of your current buffer when you execute magit-status. If other answers fail, here is inefficient but always working alternative:

Close magit current buffers (if any) (q)

Change directory to the one with your repo (M-x cd)

Start magit again (M-x magit-status)

(Inefficient because magit will be restarted)

Title: How to change repo with magit emacs?


答:
Just add the following line to change the title size, Replace 40 by the size of your choice

```<code>plt.rcParams["axes.titlesize"] = 40
</code>```

For an exhaustive list of the allowed parameters, you can read how to Customize Matplotlib with style sheets and rcParams

Title: Set title size in seaborn

Body:
I´m working with several types of plots in seaborn reason for which I have to change the font sizes contantly in order to keep it readable. I´m using the plt.rcParams parameter to do it so for most of the options:

plt.rcParams['figure.figsize'] = 12, 6
plt.rcParams["legend.fontsize"] = 12
plt.rcParams["xtick.labelsize"] = 12
plt.rcParams["ytick.labelsize"] = 12

But I have not found which is the alias for the title there, the equivalent of "ytick.labelsize"
I have tried several combinations like:

plt.rcParams["title.labelsize"] = 12

But have not found the right one.

Body:
Just add the following line to change the title size, Replace 40 by the size of your choice

plt.rcParams["axes.titlesize"] = 40

For an exhaustive list of the allowed parameters, you can read how to Customize Matplotlib with style sheets and rcParams


问:
Deletes Headings when deleting rows with different criteria
I have an issue when deleting rows with certain conditions because it deletes my headers too, also ¿ is there a way to improving the deleting of rows with different criteria ?

```<code>Sub RO_FilterDelete()
Dim RowToTest As Long

For RowToTest = Cells(Rows.Count, 2).End(xlUp).row To 2 Step -1

With Cells(RowToTest, 1)
    If .Value <> "ONLINE" _
    Then _
    Rows(RowToTest).EntireRow.Delete
End With

Next RowToTest

Dim RowToTest2 As Long

For RowToTest2 = Cells(Rows.Count, 2).End(xlUp).row To 2 Step -1

With Cells(RowToTest2, 6)
    If .Value <> "CONFIRMACIÓN DE INFORMACIÓN DE CONTRATO" _
    And .Value <> "ACTUALIZACIÓN DE INFORMACIÓN DE CONTRATO" _
    Then _
    Rows(RowToTest2).EntireRow.Delete
End With

Next RowToTest2
End Sub
</code>```

The error comes from the macro that paste the data into the worksheet, it pastes it from A1 instead of A2, that's why the filter doesn't work.

```<code>Sub RechazosOnline()
Dim rsh As Worksheet, wb As Workbook
Dim wbCopyFrom As Workbook, wsCopyFrom As Worksheet

Set wb = Workbooks("2. Detalle_Transacciones_pendientes_rechazadas_MDM_27Ene20.xlsx")
Set wbCopyFrom = Workbooks("1. ReporteGeneral_TransaccionesDiariasMDM_20200115")
Set wsCopyFrom = wbCopyFrom.Worksheets("Detalle")
wsCopyFrom.Range("A2:I" & wsCopyFrom.Range("A" & Rows.Count).End(xlUp).row).Copy

For Each rsh In wb.Sheets
         rsh.Range("A2:I" & rsh.Range("A" & rsh.Cells.Rows.Count).End(xlUp).row).PasteSpecial xlPasteValues
     Next
End Sub
</code>```

答:
Using the union method is convenient and fast.</p>

```<code>Sub test()
    Dim rngU As Range, Rng As Range
    Dim rngDB As Range

    Set rngDB = Range("a2", Range("a" & Rows.Count).End(xlUp))

    For Each Rng In rngDB
        If Rng <> "ONLINE" Then
            If rngU Is Nothing Then
                Set rngU = Rng
            Else
                Set rngU = Union(Rng, rngU)
            End If
        End If
    Next Rng

    If Not rngU Is Nothing Then
        rngU.EntireRow.Delete
    End If

    Set rngU = Nothing
    Set rngDB = Range("b2", Range("b" & Rows.Count).End(xlUp))

    For Each Rng In rngDB
        If Not (Rng.Value = "CONFIRMACION DE INFORMACION DE CONTRATO" Or Rng.Value = "ACTUALIZACION DE INFORMACION DE CONTRATO") Then
            If rngU Is Nothing Then
                Set rngU = Rng
            Else
                Set rngU = Union(Rng, rngU)
            End If
        End If
    Next Rng

    If Not rngU Is Nothing Then
        rngU.EntireRow.Delete
    End If

End Sub
</code>```

Body:
I have an issue when deleting rows with certain conditions because it deletes my headers too, also ¿ is there a way to improving the deleting of rows with different criteria ?

Sub RO_FilterDelete()
Dim RowToTest As Long

For RowToTest = Cells(Rows.Count, 2).End(xlUp).row To 2 Step -1

With Cells(RowToTest, 1)
    If .Value <> "ONLINE" _
    Then _
    Rows(RowToTest).EntireRow.Delete
End With

Next RowToTest

Dim RowToTest2 As Long

For RowToTest2 = Cells(Rows.Count, 2).End(xlUp).row To 2 Step -1

With Cells(RowToTest2, 6)
    If .Value <> "CONFIRMACIÓN DE INFORMACIÓN DE CONTRATO" _
    And .Value <> "ACTUALIZACIÓN DE INFORMACIÓN DE CONTRATO" _
    Then _
    Rows(RowToTest2).EntireRow.Delete
End With

Next RowToTest2
End Sub

The error comes from the macro that paste the data into the worksheet, it pastes it from A1 instead of A2, that's why the filter doesn't work.

Sub RechazosOnline()
Dim rsh As Worksheet, wb As Workbook
Dim wbCopyFrom As Workbook, wsCopyFrom As Worksheet

Set wb = Workbooks("2. Detalle_Transacciones_pendientes_rechazadas_MDM_27Ene20.xlsx")
Set wbCopyFrom = Workbooks("1. ReporteGeneral_TransaccionesDiariasMDM_20200115")
Set wsCopyFrom = wbCopyFrom.Worksheets("Detalle")
wsCopyFrom.Range("A2:I" & wsCopyFrom.Range("A" & Rows.Count).End(xlUp).row).Copy

For Each rsh In wb.Sheets
         rsh.Range("A2:I" & rsh.Range("A" & rsh.Cells.Rows.Count).End(xlUp).row).PasteSpecial xlPasteValues
     Next
End Sub

Body:
Using the union method is convenient and fast.

Sub test()
    Dim rngU As Range, Rng As Range
    Dim rngDB As Range

    Set rngDB = Range("a2", Range("a" & Rows.Count).End(xlUp))

    For Each Rng In rngDB
        If Rng <> "ONLINE" Then
            If rngU Is Nothing Then
                Set rngU = Rng
            Else
                Set rngU = Union(Rng, rngU)
            End If
        End If
    Next Rng

    If Not rngU Is Nothing Then
        rngU.EntireRow.Delete
    End If

    Set rngU = Nothing
    Set rngDB = Range("b2", Range("b" & Rows.Count).End(xlUp))

    For Each Rng In rngDB
        If Not (Rng.Value = "CONFIRMACION DE INFORMACION DE CONTRATO" Or Rng.Value = "ACTUALIZACION DE INFORMACION DE CONTRATO") Then
            If rngU Is Nothing Then
                Set rngU = Rng
            Else
                Set rngU = Union(Rng, rngU)
            End If
        End If
    Next Rng

    If Not rngU Is Nothing Then
        rngU.EntireRow.Delete
    End If

End Sub


问:
Locate only the variable numeric data in filename in pandas column and place numbers in new column
I am using this code to pull in two CSVs of a similar naming convention, place their filenames in a "File" column and concatenate the dataframes into one dataframe called NatHrs.

```<code>import glob
from pathlib import Path

path = r'C:\Users\ThisUser\Desktop\AC Mbr Analysis'
all_files = glob.glob(path + '\\Natl_hours_YTD_OC_*.csv')

Nat_dfs = []
for file in all_files:
    df = pd.read_csv(file, index_col=None, encoding='windows-1252', header=1 )
    df['File'] = file
    Nat_dfs.append(df)

NatHrs = pd.concat(Nat_dfs)
</code>```

Now, I want to take the "File" column, which returns a filename object with entries looking like "C:\Users\ThisUser\Desktop\AC Mbr Analysis\Natl_hours_YTD_OC_2018-2019", extract ONLY the end of the filename--in this case "2018-2019"--and place those characters into a new colum "Program Year", reflecting the entry "2018-2019".  I am not having success with manipulating strings or series--should I be using path.replace?  I am lost.  When I describe the column I'm looking to parse...

```<code>NatHrs['File'].describe
</code>```

...I get this:

```<code>Name: File, dtype: object>
</code>```

答:
This ultimately ended up working.  Thank you much for helping me along!</p>

```<code>globbed_files = glob.glob("Natl_hours_YTD_OC_*.csv")
globbed_files

data = []
for csv in globbed_files:
    frame = pd.read_csv(csv, encoding='windows-1252', header=1)
    frame['filename'] = os.path.basename(csv)
    file = os.path.basename(csv)
#create a new column to store the portion of the file name that denotes the Program Year to which the data belongs
    frame['Program Year'] = re.search('\d+[-]*\d*',file).group()
    data.append(frame)

NatHrs = pd.concat(data, ignore_index=True) #dont want pandas to try an align row indexes
NatHrs.copy().head()
</code>```

Body:
I am using this code to pull in two CSVs of a similar naming convention, place their filenames in a "File" column and concatenate the dataframes into one dataframe called NatHrs.

import glob
from pathlib import Path

path = r'C:\Users\ThisUser\Desktop\AC Mbr Analysis'
all_files = glob.glob(path + '\\Natl_hours_YTD_OC_*.csv')

Nat_dfs = []
for file in all_files:
    df = pd.read_csv(file, index_col=None, encoding='windows-1252', header=1 )
    df['File'] = file
    Nat_dfs.append(df)

NatHrs = pd.concat(Nat_dfs)

Now, I want to take the "File" column, which returns a filename object with entries looking like "C:\Users\ThisUser\Desktop\AC Mbr Analysis\Natl_hours_YTD_OC_2018-2019", extract ONLY the end of the filename--in this case "2018-2019"--and place those characters into a new colum "Program Year", reflecting the entry "2018-2019".  I am not having success with manipulating strings or series--should I be using path.replace?  I am lost.  When I describe the column I'm looking to parse...

NatHrs['File'].describe

...I get this:

Name: File, dtype: object>

Body:
This ultimately ended up working.  Thank you much for helping me along!

globbed_files = glob.glob("Natl_hours_YTD_OC_*.csv")
globbed_files

data = []
for csv in globbed_files:
    frame = pd.read_csv(csv, encoding='windows-1252', header=1)
    frame['filename'] = os.path.basename(csv)
    file = os.path.basename(csv)
#create a new column to store the portion of the file name that denotes the Program Year to which the data belongs
    frame['Program Year'] = re.search('\d+[-]*\d*',file).group()
    data.append(frame)

NatHrs = pd.concat(data, ignore_index=True) #dont want pandas to try an align row indexes
NatHrs.copy().head()


答:
You definitely can sort array to timestamps with the given code below, but I would like to drag your attention to the format of time I have used to store.. There are different benefits of storing time in such format. Read more about this here https://stackoverflow.com/a/59912185/7997043</p>

```<code>function compareByTimeStamp($a, $b ) {
    return strtotime($b) - strtotime($a);
}
$arr = array("2020-02-11 00:00:00", "2020-02-13 00:00:00", "2020-02-08 00:00:00");
usort($arr, "compareByTimeStamp");
echo json_encode($arr);
</code>```

Title: How to sort date array in php?

Body:
I am new to php, I have php date array

[0] => 11-01-2012
[1] => 01-01-2014
[2] => 01-01-2015
[3] => 09-02-2013
[4] => 01-01-2013

I want to sort it like :

[0] => 11-01-2012
[1] => 01-01-2013
[2] => 09-02-2013
[3] => 01-01-2014
[4] => 01-01-2015

I use asort but not working.

Body:
You definitely can sort array to timestamps with the given code below, but I would like to drag your attention to the format of time I have used to store.. There are different benefits of storing time in such format. Read more about this here https://stackoverflow.com/a/59912185/7997043

function compareByTimeStamp($a, $b ) {
    return strtotime($b) - strtotime($a);
}
$arr = array("2020-02-11 00:00:00", "2020-02-13 00:00:00", "2020-02-08 00:00:00");
usort($arr, "compareByTimeStamp");
echo json_encode($arr);


问:
Custom NSMenuItem with right-aligned detail text label
What I want to implement

I am looking for a way to display a title label and a detail text label in a NSMenuItem.
Preferably it would look something like this:

The Title Label is left aligned with all the other NSMenuItem's
titles

The Detail Text Label is right-aligned

The Detail Text Label has a different text color than the title

Selection/Submenus etc. work as expected

What have I tried already

By reading the documentation I found the following possible implementations:

Create a custom NSView and set NSMenuItem.view

Use a default NSMenuItem and use a NSAttributedString

First I tried to use a custom NSView. However I could not get the NSMenuItem to size correctly in order to display all the available text. I guess some autoresizing masks do not work correctly but I am not sure. Also this way I would need to re-implement selection/arrow for the submenu, ...

Then I started to experiment with NSAttributedString. I calculate the title with the most characters and then pad the string with title += string.padding(toLength: maxTitleLength, withPad: " ", startingAt: 0). The NSAttributedString colors the title and the detail label differently. However this does not seem to work since the detail labels are not correctly aligned although the title is padded to the same length. I guess this makes sense since characters have different widths?

TL;DR - Question

So is there any other way to implement the desired design which I did not find? Do you have any advice for me on how to implement this?

答: Nevermind I found the answer myself. Actually it works for me now by using the view property of the NSMenuItem to set a custom view. This answer lead me to the right direction: Highlighting a NSMenuItem with a custom view?.


问:
How to add a group to multiple built-in Ribbon tabs (vsto)?
This is VS2010 + Office 2010 add-in. All I want is to add a button (or button group) to multiple built-in tabs. For example, my buttons should be available in both New Mail Message Ribbon and in New Appointment Ribbon. I have tried adding a new tab (in the Visual Designer) but that doesn't seem to work. The button group appears on the New Mail Message tab, but not on the Appointment tab. BTW, I'm using the following IDs: TabNewMailMessage and TabAppointment.

答:
The designated answer is now obsolete!

On the OfficeRibbon object, set the RibbonType for as many cases as necessary (e.g. Microsoft.Outlook.Explorer and Microsoft.Outlook.Mail.Read).

Add a first Tab and set the ControlId.OfficeId (e.g. TabMail)

Add another Tab and set the ControlId.OfficeId (e.g. TabReadMessage)

In each Tab add a Group and a Button within and set the Button.Click event to point to the same OnClick method