text:
Q: SecurityException: Permission Denial API 19 I am a very new in android developing.
In my app I have a contact class that shown in a list view.for my contact i have an image that i got from gallery and images uri is stored on database.
In my last Post
my problem fixed by this post
fore while my app in genymotion and api 19 correctly worked but suddenly I got this error:
FATAL EXCEPTION: main
                                                                             Process: com.example.sayres.myapplication7, PID: 3865
                                                                             java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{5296e638 3865:com.example.sayres.myapplication7/u0a98} (pid=3865, uid=10098) requires android.permission.MANAGE_DOCUMENTS or android.permission.MANAGE_DOCUMENTS
                                                                                at android.os.Parcel.readException(Parcel.java:1465)
                                                                                at android.os.Parcel.readException(Parcel.java:1419)
                                                                                at android.app.ActivityManagerProxy.getContentProvider(ActivityManagerNative.java:2848)
                                                                                at android.app.ActivityThread.acquireProvider(ActivityThread.java:4399)
                                                                                at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2208)
                                                                                at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1425)
                                                                                at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1047)
                                                                                at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:904)
                                                                                at android.content.ContentResolver.openInputStream(ContentResolver.java:629)
                                                                                at android.provider.MediaStore$Images$Media.getBitmap(MediaStore.java:803)
                                                                                at com.example.sayres.myapplication7.mvp.view.adapter.ContactAdapter.getView(ContactAdapter.java:54)
                                                                                at android.widget.AbsListView.obtainView(AbsListView.java:2255)
                                                                                at android.widget.ListView.makeAndAddView(ListView.java:1790)
                                                                                at android.widget.ListView.fillDown(ListView.java:691)
                                                                                at android.widget.ListView.fillFromTop(ListView.java:752)
                                                                                at android.widget.ListView.layoutChildren(ListView.java:1616)
                                                                                at android.widget.AbsListView.onLayout(AbsListView.java:2087)
                                                                                at android.view.View.layout(View.java:14817)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4631)
                                                                                at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:122)
                                                                                at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
                                                                                at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1170)
                                                                                at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:814)
                                                                                at android.view.View.layout(View.java:14817)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4631)
                                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
                                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
                                                                                at android.view.View.layout(View.java:14817)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4631)
                                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
                                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
                                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
                                                                                at android.view.View.layout(View.java:14817)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4631)
                                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
                                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
                                                                                at android.view.View.layout(View.java:14817)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4631)
                                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
                                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
                                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
                                                                                at android.view.View.layout(View.java:14817)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4631)
                                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
                                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
                                                                                at android.view.View.layout(View.java:14817)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4631)
                                                                                at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1983)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1740)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:574)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:544)
                                                                                at android.view.Choreograph

according to my last post I have added some code  and my fragment code is:
package com.example.sayres.myapplication7.mvp.view.profile;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.example.sayres.myapplication7.App;
import com.example.sayres.myapplication7.R;
import com.example.sayres.myapplication7.entity.Contact;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import de.hdodenhof.circleimageview.CircleImageView;
public class EditProfileFragment extends Fragment {

private static final int GALLERY_KITKAT_INTENT_CALLED = 1;
private EditFragmentCallBack editFragmentCallBack;
private EditText fragmentEditEditTextName;
private EditText fragmentEditEditTextFamily;
private EditText fragmentEditEditTextPhoneNumber;
private static final int SELECT_FILE = 0;
public static final String TAG = "====>";
private AlertDialog.Builder builder;
private Uri selectedImageUri;
private CircleImageView fragmentEditPicture;
private Bitmap bm;
private Button fragmentEditBtUpdate;
private int id;
private int rowUpdate;
private String name;
private String family;
private String phoneNumber;
private Contact contact;

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

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    Log.d(TAG, "onAttach: is running");

    editFragmentCallBack = (EditFragmentCallBack) context;
    Log.d(TAG, "onAttach: editFragmentCallBack was initialized");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    Log.d(TAG, "onCreateView- EditFragment: is running");
    View fragmentView = inflater.inflate(R.layout.fragment_edit_profile, container, false);
    initFragment(fragmentView);
    return fragmentView;
}

private void initFragment(View parent) {

    /**
     * referencing of  fragment_edit_profile
     */
    fragmentEditPicture = (CircleImageView) parent.findViewById(R.id.fragment_edit_picture);
    fragmentEditEditTextName = (EditText) parent.findViewById(R.id.fragment_edit_editText_name);
    fragmentEditEditTextFamily = (EditText) parent.findViewById(R.id.fragment_edit_editText_family);
    fragmentEditEditTextPhoneNumber = (EditText) parent.findViewById(R.id.fragment_edit_editText_phone);
    fragmentEditBtUpdate = (Button) parent.findViewById(R.id.fragment_edit_btn_save);

    fragmentEditBtUpdate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Log.d(TAG, "onClick: yess");
            id = contact.get_id();
            name = fragmentEditEditTextName.getText().toString();
            family = fragmentEditEditTextFamily.getText().toString();
            phoneNumber = fragmentEditEditTextPhoneNumber.getText().toString();

            Log.d(TAG, "onClick: name " + name);
            Log.d(TAG, "onClick: family " + family);

            contact = new Contact(id, name, family, phoneNumber, selectedImageUri.toString());
            rowUpdate = App.getInstanceImplementation().updateContact(contact);

            Log.i("==>", "btnUpdateContact: " + rowUpdate);

        }
    });
    /**
     * get contact by invoke from CallBack on ProfileActivity
     */
    contact = editFragmentCallBack.getContact();

    fragmentEditEditTextName.setText(contact.getName());
    fragmentEditEditTextFamily.setText(contact.getFamily());
    fragmentEditEditTextPhoneNumber.setText(contact.getPhonNumber());

}

public void selectImage() {
    final CharSequence[] items = {"Choose from Library", "Cancel"};
    builder = new AlertDialog.Builder(getActivity());

    builder.setTitle("Add Photo ");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Choose from Library")) {

                if (Build.VERSION.SDK_INT <19) {
                    Log.d(TAG, "Build.VERSION.SDK_INT <19");

                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);

                    startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);

                }else {

                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
//                        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("image/*");
                    startActivityForResult(intent, GALLERY_KITKAT_INTENT_CALLED);
                }
            } else if (items[item].equals("Cancel")) {

            }
        }
    });
    builder.show();

}

@SuppressLint("NewApi")
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_FILE) {
            onSelectFromGalleryResult(data);

        } else if (requestCode == GALLERY_KITKAT_INTENT_CALLED) {
            selectedImageUri = data.getData();
            final int takeFlags = data.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            getActivity().getContentResolver().takePersistableUriPermission(selectedImageUri, takeFlags);

            bm = null;

            try {
                selectedImageUri = data.getData();

                bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
            } catch (IOException e) {
                e.printStackTrace();
            }

            Log.d(TAG, "selectedImageUri " + selectedImageUri);
            fragmentEditPicture.setImageBitmap(bm);
        }

    }
}

public void onSelectFromGalleryResult(Intent data) {
    if (data != null) {
        bm = null;

        try {
            selectedImageUri = data.getData();

            bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.d(TAG, "selectedImageUri " + selectedImageUri);
        fragmentEditPicture.setImageBitmap(bm);
    }

}

public interface EditFragmentCallBack {
    Contact getContact();

    void finishProfile();

}

}

I added uses-permission android:name="android.permission.MANAGE_DOCUMENTS" to manifest file but I still got the error.I have a list view that shows contact information.
my contactAdapter
package com.example.sayres.myapplication7.mvp.view.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.sayres.myapplication7.R;
import com.example.sayres.myapplication7.entity.Contact;

import java.io.IOException;
import java.util.List;

public class ContactAdapter extends ArrayAdapter<Contact> {
private Bitmap bm;
private Context context;
private List<Contact> contacts;

public ContactAdapter(Context context, List<Contact> contacts) {
    super(context, 0, contacts);
    this.context = context;
    this.contacts = contacts;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View rootView = View.inflate(getContext(), R.layout.item_contact_list, null);

    /**
     * get reference from item_contact_list Layout
     */
    ImageView imageViewAvatar = (ImageView) rootView.findViewById(R.id.imageView_avatar);
    TextView textViewName = (TextView) rootView.findViewById(R.id.textView_name);
    TextView textViewFamily = (TextView) rootView.findViewById(R.id.textView_family);

    Contact contact = contacts.get(position);

    if (contact.getImageSrc() =="") {
        Log.d("===>", "getImageSrc() == null");
        imageViewAvatar.setImageResource(R.mipmap.ic_launcher);
    } else {

        try {
            bm = MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.parse(contact.getImageSrc()));
            imageViewAvatar.setImageBitmap(bm);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    Log.d("===>", "getView from DB: " + Uri.parse(contact.getImageSrc()));
    Log.d("===>", "getView: " + contact.getImageSrc());
    textViewName.setText(contact.getName());
    textViewFamily.setText(contact.getFamily());

    return rootView;

}

}
this error is for this line : bm = MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.parse(contact.getImageSrc()));
what is the the error?how can i fix this?
Edit:
this is my Contact class:
package com.example.sayres.myapplication7.entity;

import java.io.Serializable;

public class Contact implements Serializable{
private int _id;
private String name, lastName, phoneNumber,imageSrc;

public Contact(int _id, String name, String family, String phoneNumber, String imageSrc) {
    this._id = _id;
    this.name = name;
    this.lastName = family;
    this.phoneNumber = phoneNumber;
    this.imageSrc = imageSrc;
}

public int get_id() {
    return _id;
}

public Contact set_id(int _id) {
    this._id = _id;
    return this;
}

public String getName() {
    return name;
}

public Contact setName(String name) {
    this.name = name;
    return this;
}

public String getFamily() {
    return lastName;
}

public Contact setFamily(String lastName) {
    this.lastName = lastName;
    return this;
}

public String getPhonNumber() {
    return phoneNumber;
}

public Contact setPhonNumber(String phonNumber) {
    this.phoneNumber = phonNumber;
    return this;
}

public String getImageSrc() {
    return imageSrc;
}

public Contact setImageSrc(String imageSrc) {
    this.imageSrc = imageSrc;
    return this;
}
}

A: When you get a Uri from another app, you have temporary rights to the content identified by that Uri.
If you got the Uri via ACTION_OPEN_DOCUMENT, you can try to use takePersistableUriPermission() to get durable access to that content. You have code for this already.
However, if you got the Uri via ACTION_GET_CONTENT, there is no means to get long-term access to the content. You have to use the content immediately (i.e., while your process is still running). Your only real option is to copy the content to some file that you control. You can get an InputStream on the content identified by the Uri via a ContentResolver and openInputStream(), and you can then use standard Java I/O to copy from that stream to some file. Then, use the file going forward.


text:
Q: Sender in signal-to-signal connection There is a function QObject::sender(), than, when invoked in a slot, provides the QObject* pointer to the sending object.
It's behaviour is far less useful if you have the following structure.
class A : public QObject { Q_OBJECT
    ...
    signals:
        void foo();
};

class B : public QObject { Q_OBJECT
    ...
    signals:
        void foo();
};

class C : public QObject { Q_OBJECT
    ...
    public slots:
        void bar() { qDebug() << sender(); }
};

A a;
B b;
C c;

connect(&A, SIGNAL(foo()), &B, SIGNAL(foo()));
connect(&B, SIGNAL(foo()), &C, SLOT(bar()));

A::whatever() { emit foo(); }

C::bar() indicates B as the emitter. How can I get the original emitting object, without dealing with all the relays?
Unfortunately QObject::sender() is protected so this naive approach in C::bar() wouldn't compile (not sure if it ever could work, but that's my only idea to traverse the sender() backwards):
QObject *ptr = this;
while ((ptr = ptr->sender()) != NULL)
    qDebug() << ptr->objectName();

To answer some of the questions raised in comments:

*

*A - custom widget (lots of dynamically created ones) (holding some data, pointers, whatnot)

*B - custom top-level UI element (member of the QStackedWidget, handles some UI responsibilities)

*C - (in practice, C1, C2, C3) - work that needs to be performed (using common state, such as DSP queue) on data stored in As.

Ultimately, A needs to know very little about Cs (or even if anything cares about it's signals). B is where the UI aggregation takes place (also the top-level UI calls Cs to set DSP parameters etc). Cs need to know if sender() is qobject_cast'able to IA interface.
It can be reworked to something along the lines of:
class A : public QObject { Q_OBJECT
    ...
    signals:
        void foo(QObject*);
};

class B : public QObject { Q_OBJECT
    ...
    signals:
        void foo(QObject*);
};

class C : public QObject { Q_OBJECT
    ...
    public slots:
        void bar(QObject* mySender) { qDebug() << mySender; }
};

A a;
B b;
C c;

connect(&A, SIGNAL(foo(QObject*)), &B, SIGNAL(foo(QObject*)));
connect(&B, SIGNAL(foo(QObject*)), &C, SLOT(bar(QObject*)));

A::whatever() { emit foo(this); }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I find my IP address when inside a Server I have a Linux server is hosting in a host company.  I don't know what is the public IP address of the server.  I can only ssh to the server using their Cloud access.  I'm wondering if there's any tools that I can use to tell what is the public IP address of the Server I'm inside.

A: This cyberciti.biz article Expline how to find your public IP address.
To show IP address of server use this command: ifconfig -a.

A: I found this website service that you can create a link URL then send a request to that URL to reveal your IP Address and header details which is cool.
https://www.requestheader.com/


text:
Q: Access Application using same ip within office network I've deployed one application developed using Java-Struts on one of my client's office. Application is web-based - So we hosted it on one the machine available in client's office - using static ip. The application runs fine(well I had couple of issues to deal with honestly). But when we were testing the application within client's environment - we came across odd issue.
If client needs to access the application inside their network - they need to use local ip address, something like this -
http://192.168.1.12:8080/CTS
Outside the network - they need to use following url -
http://99.99.999.999:8080/CTS
How I can make sure client does not have to use 2 different urls to access this application?
I went through few forums and got to know about host mapping and NAT forwarding, etc. I'm not a networking expert, So I really need some guidance of how to achieve this with right method.
Thank you very much in advance.

A: For security reason the intranet IP(http://192.168.1.12:8080/CTS) is not exposed publicly.Have to check with the network team of Client whether the IP is publicly exposed if not then map local IP with domain/Static IP and that should be exposed publicly.If it is publicly exposed then within the network too the client can access intranet IP/domain.


text:
Q: asyncData with apollo query returns an object but not an array I am using apollo to get my data in a Nuxt.js project, using asyncData
import homeQuery from '~/apollo/queries/home'

export default {
  async asyncData({app}) {
    const homeresult = await app.apolloProvider.defaultClient.query({
    query: homeQuery
  })
  return { home: homeresult.data.home }
},
data () {
  return {
    home: {}
  }
}

this works fine when the result of the query is an object, for example the above is:
 {
   "data": {
     "home": {
       title": "Home"
     }
   }
}

However, if the query result is an array:
{
  "data": {
    "home": [
      {
        "id": "1"
      },
      {
        "id": "2"
      },
      {
        "id": "3"
      }
    ]
  }
}

nothing gets returned. (I also tested data () { return { home: [] } } )
Do I have to treat arrays differently, and how should I correctly write the asyncData?

A: I have absolutely no idea what changed... but when I tried again that code, I had no more problems with arrays as results.


text:
Q: SURF only works outside but not inside of my Anaconda environment I build OpenCV 4.5.5 from source in windows and I activated OPENCV_ENABLE_NONFREE with the help of CMAKE. As I tried 'surf = cv.xfeatures2d.SURF_create(400)' outside of my anaconda environment I am getting no error and it works perfetly...but when I try the same thing inside of my anaconda environment I am getting error module 'cv2' has no attribute 'xfeatures2d'

A: Instructions how to build open-cv with GPU support on windows on an anaconda environment (also fix for autocomplete not available):
"""
    opencv cuda installation on WINDOWS 10:
    youtube https://www.youtube.com/watch?v=YsmhKar8oOc&ab_channel=TheCodingBug
    ** all links for download in the link
    ** in brackets: my specific installation
    * install anaconda
    * vs studio 19 with "desktop development C++" and "python development"
    * Cuda toolkit (cuda toolkit 10.2)
    * cuDNN - version that match the cuda toolkit above (cuDnn v7.6.5 for Cuda 10.2)
        * archive: https://developer.nvidia.com/rdp/cudnn-archive
        * copy all to cuda (bin to bin, lib to lib, include to include)
        * minimum 7.5
    * CMake
    * openCV source (4.5.2)
    * openCV contrib - same version as openCV above (4.5.2)
        * place openCV and openCV contrib in the same folder and extract both

    1 build a new python env anywhere(conda(base or custom), normal py, venv...)
    2 set 4 system environment variables:
        let PY_PATH be you python dir (conda env, normal py, venv...)
        go to PATH and add the next 4:
            * PY_PATH # for the python.exe
            * PY_PATH/Scripts # for pip...
            * PY_PATH/libs  # for python36.lib file
            * PY_PATH/include # h files
    2b pip install numpy (if you want tf, 1.19.5)
    3 open CMake gui
    * source code: location of openCV source
    * create 2 new dirs in the level of openCV source called build and install
    * where to build: location of build folder created above
    * configure, set generator x64 and finish
    * click grouped checkbox and look in PYTHON3
        should have EXECUTABLE, INCLUDE_DIR, LIBRARY, NUMPY_INCLUDE, PACKAGES paths filled according to PY_PATH
        look at the output and search for OpenCV modules. if python3 in Unavailable - don't continue. it should be
        in the "To be built"
    * extra round of flags:
        WITH_CUDA
        BUILD_opencv_dnn
        OPENCV_DNN_CUDA
        ENABLE_FAST_MATH
        BUILD_opencv_world
        BUILD_opencv_python3 # should already be on
        OPENCV_EXTRA_MODULES_PATH -> set to openCV contrib on modules folder
    * hit configure - in the output you should see your CUDA and cuDNN details
        CUDA detected: x.y (10.2)
        Found CUDNN path ...
    * extra round of flags:
        CUDA_FAST_MATH
        CUDA_ARCH_BIN -> go to https://en.wikipedia.org/wiki/CUDA and look for your GPU. find it's Compute
            capability (version). (my GPU is gtx 1050. version 6.1)
            remove all versions other than you GPU version. (i left only 6.1)
        CMAKE_INSTALL_PREFIX -> place install path from above (you create this dir with build above)
        CMAKE_CONFIGURATION_TYPES -> remove Debug and keep only Release
    * hit configure
    * hit generate
    close CMAKE gui
    4 go to build folder and look for OpenCV.sln
    * goto solution explorer->CMakeTargets-> right click ALL_BUILD and hit build # should take 10-30 mins
    * if done with no errors, right click INSTALL and build.
    * if no errors, openCV cuda is ready
    5 validation: open terminal and write python (should work due to step 2)
    import cv2
    print(cv2.__version__)
    print(cv2.cuda.getCudaEnabledDeviceCount())  # should be >=1
    run this:
        pip install wizzi_utils
        import wizzi_utils as wu
        wu.cvt.test.cuda_on_gpu_test()
    6 cleanup
    * delete all build folder except build/lib # maybe for future use ?
    * delete both zips and extracted open cv and open cv contrib
    7 after checking on pycharm, open cv with GPU support should work but no autocomplete.
    pip install mypy
    stubgen -m cv2 -o ENV_PATH\Lib\site-packages\cv2
    # if the stubgen fails, run as administrator
    # rename cv2.pyi created to __init__.pyi
    # all done
    e.g:
    stubgen -m cv2 -o C:\\Users\\GiladEiniKbyLake\\.conda\\envs\\cv_cuda\\Lib\\site-packages\\cv2
    # a file was created at C:\\Users\\GiladEiniKbyLake\\.conda\\envs\\temp\\Lib\\site-packages\\cv2\\cv2.pyi
    # rename cv2.pyi to __init__.pyi and have the file:
        C:\\Users\\GiladEiniKbyLake\\.conda\\envs\\temp\\Lib\\site-packages\\cv2\\__init__.pyi
    :return:
    """


text:
Q: As a response to "I'm glad ...", what does "you're glad" imply? The conversation occurs after A did B a favor:
A: I'm glad I was able to help you out!
B: You're glad!

What does B imply?

A: It depends on how much stress was put on each word.

YOU're glad(?)

Would imply that person B thinks he/she is the one who should be thankful, not person A. As in "Why are YOU thanking me! It surprises me to see YOU thanking me! I'm the one who should be thanking!"

you're GLAD(?)

Implies that person B didn't think that person A would thank them, because he/she thinks what they did was not worthy of being thanked for, or they think what they did was rather destructive than helpful and thus, it surprises them to see person A thankful. "You're GLAD? I thought you would be mad at me!"/"you're GLAD? But I messed up!"


text:
Q: Execution failed: 'app:compileDebugJavaWithJavac FAILED' -ReactNative I have installed react-native-navigation locally inside the project, even then it is displaying an error app:compileDebugJavaWithJavac FAILED. I then tried cd android and then ran gradlew clean, however the error persists
 Please check the Full error:
 Task :app:compileDebugJavaWithJavac FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/4.10.1/userguide/command_line_interface.html#sec:command_line_warnings
302 actionable tasks: 1 executed, 301 up-to-date
C:\Users\User\Baaz\android\app\src\main\java\com\baaz\MainActivity.java:2: error: package com.reactnativenavigation does not exist
import com.reactnativenavigation.NavigationActivity;
                                ^
C:\Users\User\Baaz\android\app\src\main\java\com\baaz\MainActivity.java:8: error: cannot find symbol
public class MainActivity extends NavigationActivity {
                                  ^
  symbol: class NavigationActivity
C:\Users\User\Baaz\android\app\src\main\java\com\baaz\MainActivity.java:15: error: method does not override or implement a method from a supertype
    @Override
    ^
C:\Users\User\Baaz\android\app\src\main\java\com\baaz\MainActivity.java:17: error: cannot find symbol
        return new ReactActivityDelegate(this, getMainComponentName()) {
                                               ^
  symbol:   method getMainComponentName()
  location: class MainActivity
C:\Users\User\Baaz\android\app\src\main\java\com\baaz\MainActivity.java:20: error: incompatible types: MainActivity cannot be converted to Context
                return new RNGestureHandlerEnabledRootView(MainActivity.this);
                                                                       ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
5 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 8s

error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
C:\Users\User\Baaz\android\app\src\main\java\com\baaz\MainActivity.java:2: error: package com.reactnativenavigation does not exist
import com.reactnativenavigation.NavigationActivity;
                                ^
C:\Users\User\Baaz\android\app\src\main\java\com\baaz\MainActivity.java:8: error: cannot find symbol
public class MainActivity extends NavigationActivity {
                                  ^
  symbol: class NavigationActivity
C:\Users\User\Baaz\android\app\src\main\java\com\baaz\MainActivity.java:15: error: method does not override or implement a method from a supertype
    @Override
    ^
C:\Users\User\Baaz\android\app\src\main\java\com\baaz\MainActivity.java:17: error: cannot find symbol
        return new ReactActivityDelegate(this, getMainComponentName()) {
                                               ^
  symbol:   method getMainComponentName()
  location: class MainActivity
C:\Users\User\Baaz\android\app\src\main\java\com\baaz\MainActivity.java:20: error: incompatible types: MainActivity cannot be converted to Context
                return new RNGestureHandlerEnabledRootView(MainActivity.this);
                                                                       ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
5 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 8s

    at checkExecSyncError (child_process.js:621:11)
    at execFileSync (child_process.js:639:15)
    at runOnAllDevices (C:\Users\User\Baaz\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:94:39)
    at buildAndRun (C:\Users\User\Baaz\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:158:41)
    at C:\Users\User\Baaz\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:125:12
    at processTicksAndRejections (internal/process/task_queues.js:94:5)
    at async Command.handleAction (C:\Users\User\Baaz\node_modules\react-native\node_modules\@react-native-community\cli\build\index.js:164:9)

The following is the main mainactivvity.java file
MainActivity.java
package com.baaz;
import com.reactnativenavigation.NavigationActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;

public class MainActivity extends NavigationActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */

    @Override
    protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
            @Override
            protected ReactRootView createRootView() {
                return new RNGestureHandlerEnabledRootView(MainActivity.this);
            }
        };
    }
}

MainApplication.java
package com.baaz;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.baaz.generated.BasePackageList;
import com.swmansion.reanimated.ReanimatedPackage;
import com.swmansion.rnscreens.RNScreensPackage;
import com.swmansion.gesturehandler.react.RNGestureHandlerPackage;

import org.unimodules.adapters.react.ReactAdapterPackage;
import org.unimodules.adapters.react.ModuleRegistryAdapter;
import org.unimodules.adapters.react.ReactModuleRegistryProvider;
import org.unimodules.core.interfaces.Package;
import org.unimodules.core.interfaces.SingletonModule;
import expo.modules.constants.ConstantsPackage;
import expo.modules.permissions.PermissionsPackage;
import expo.modules.filesystem.FileSystemPackage;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {
  private final ReactModuleRegistryProvider mModuleRegistryProvider = new ReactModuleRegistryProvider(
    new BasePackageList().getPackageList(),
    Arrays.<SingletonModule>asList()
  );

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new ReanimatedPackage(),
          new RNGestureHandlerPackage(),
          new RNScreensPackage(),
          new ModuleRegistryAdapter(mModuleRegistryProvider)
      );
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

package.json
{
  "scripts": {
    "start": "react-native start",
    "android": "cd ./android && ./gradlew app:assembleDebug && ./gradlew installDebug",
    "ios": "react-native run-ios",
    "web": "expo start --web",
    "postinstall": "jetify"
  },
  "dependencies": {
    "expo": "~36.0.0",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "~0.61.4",
    "react-native-gesture-handler": "~1.5.0",
    "react-native-navigation": "^4.5.4",
    "react-native-reanimated": "~1.4.0",
    "react-native-screens": "~2.0.0-alpha.12",
    "react-native-unimodules": "~0.7.0",
    "react-native-web": "~0.11.7"
  },
  "devDependencies": {
    "@babel/core": "^7.0.0",
    "babel-jest": "~24.9.0",
    "jest": "~24.9.0",
    "jetifier": "~1.6.4",
    "metro-react-native-babel-preset": "~0.56.0",
    "react-test-renderer": "~16.9.0",
    "babel-preset-expo": "~8.0.0"
  },
  "private": true
}

Kindly, answer and do let me know if anything else is equired to solve this error

A: You can fix this by running:
sudo apt install openjdk-8-jdk

A: SOLVED at the same issue:
My solution was at /android/build.gradle file.
Somehow, the buildscript versions were wrong.
Follow the exact same step of RN documentation and make a totally new & clean project.
And compate the /android/build.gradle file > buildscript & dependencies part.
There should be some version differences.
It matters by your own local env settings.
After changing buildToolsVersion, ndkVersion, classpath, it worked fine again!!


text:
Q: Every time I run a meteor command, I get an error Every time I run a meteor command, I get the error:
C:\Users\brand\AppData\Local\.meteor\packages\meteor-tool\1.6.0\mt-os.windows.x86_64\tools\isobuild\meteor-npm.js:265
  versions: _extends({}, process.versions)

I think it has something to do with the new meteor update, but I am not sure. I am running windows 10. If anyone has any suggestions, that would be great.


text:
Q: Emacs workflow to edit Bash scripts while they run Bash can give unexpected results if one edits a script while the script is running. But it would often be very convenient to be able to edit a temporary copy of a script that I run within a shell, but make sure it is back in the original location before I run it again. Does anyone have suggestions for a workflow or customizations to Emacs to facilitate this?

A: M-x delete-file, press down to insert obtain the path to the file you're editing, and RET to delete the file. When you next save your buffer, this will create a new file. Bash will keep executing the old, deleted file.
By the way, in most cases, you don't even need to take this precaution. Emacs usually saves to a temporary file, then renames that temporary file to the proper file name (which deletes the old file, unless it's being kept as a backup). Emacs only overwrites the file in place if it detects that it can't recreate the file properly: if the file has hard links, or if you don't have write permission on the directory. (I'm simplifying a little; the details are in the basic-save-buffer-2 function in files.el.) As long as the file has a single directory entry and you have write permissions on the directory containing the script, just press C-x C-s.

A: [edit] The best workaround is done in shell script side, not in Emacs. In short, _put all in a brace, and put "exit" before the closing brace. Read the linked answer well to avoid pitfalls.
In this reply, I supplement Gilles's answer with theory.
The reason deletion is safe but modification is not is that in Unix, a deleted file gets inaccessible from the file system, but the processes that had opened the file (here, /bin/bash) can still read it, as explained here. It's not that bash does something special, like buffering the entire file, but it simply reads. (Even after the deletion, you can recover the script while it's running, as explained here. In bash, the script seems to be always opened as 255, /proc/<pid>/fd/255.)
[edit] My old answer included Emacs solution and co, as per OP's request. But after years of experience, I'm sure that the above pointer is the best, far better than any other attempts.)

A: i already had a function for renaming the current buffer's file.  was a short jump to a function which made it easy to toggle to a temp version of a file and then back again.  basically, if you run this function when visiting a normal file "foo.txt", it will copy the file to a new file in the same dir with the name "tmp.foo.txt".  edit as desired.  when ready to switch back, run the function again and it will move the temp file back over the original file.  i used the prefix "tmp." instead of a suffix because most mode recognition in emacs is based on the suffix (you could probably do something fancier with remembering all the buffer modes and re-applying...).
(defun toggle-temp-file ()
  (interactive)
  (let* ((cur-buf (current-buffer))
         (cur-file (buffer-file-name cur-buf))
         (cur-file-dir (file-name-directory cur-file))
         (cur-file-name (file-name-nondirectory cur-file))
         new-file)
    (if (string-match "^tmp\\.\\(.+\\)\\'" cur-file-name)
        ;; temp file -> orig file
        (progn
          (setq new-file
                (concat cur-file-dir (match-string 1 cur-file-name)))
          (rename-file cur-file new-file t))
      ;; orig file -> temp file
      (setq new-file (concat cur-file-dir "tmp." cur-file-name))
      (copy-file cur-file new-file nil nil t))
    (kill-buffer cur-buf)
    (find-file new-file)))

A: Just adding this solution as an easy and clean way to protect running BASH scripts from being changed:
#! /bin/bash
{
your_code;
exit;
}


text:
Q: NameError: Uninitialized constant Twitter When I try to run any command that uses the Twitter API in the ruby console, I get the error NameError: uninitialized constant Twitter.
I have named this twitterFeed.rb because I read that it should not be named twitter.rb. This file is placed in my config/initializers folder. I have ran bundle install already, and the line gem 'twitter', '~> 6.2' is in my gem file.
require 'rubygems'
require 'bundler/setup'

require 'twitter'
require 'json'

client = Twitter::REST::Client.new do |config|
 config.consumer_key = ENV['TWITTER_CONSUMER_KEY']
 config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET']
 config.access_token = ENV['TWITTER_ACCESS_TOKEN']
 config.access_token_secret = ENV['TWITTER_ACCESS_TOKEN_SECRET']
end

A: It looks like you're trying to use irb instead of the Rails console to run your code. When you run through irb (or pry), you aren't actually loading the Rails environment, so none of the gems will be available. You can manually require them, but you still won't have access to the Rails environment.
What you want to do instead is use rails console (or rails c for short).
For example with irb, Twitter isn't loaded:
rails_dir » irb
2.2.4 :001 > Twitter
NameError: uninitialized constant Twitter
    from (irb):1
    from /Users/bbugh/.rvm/rubies/ruby-2.2.4/bin/irb:11:in `<top (required)>'

With rails c, it works just fine:
rails_dir » rails c
Loading development environment (Rails 5.0.1)
2.2.4 :001 > Twitter
=> Twitter

You can take all of those requires out of your initializer - Rails will require the gems automatically by that point. You just need to use rails console when you're doing console work with Rails.


text:
Q: Text shows up dim (initially) when trying to make a gallery of layouts I am trying to make a gallery that functions similar to the android market where you can scroll (left/right) to view free or paid apps and etc... Also be able to scroll up and down through a layout.
So far I just have it loading two layouts that have a simple "Hello World!" text view and a "Hey! how are you?" text view.
They load fine, except initially the text at position 0 of the gallery shows up dim until I scroll away and back to it. Is there something that I'm missing?
public class HelloGallery extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Gallery gallery = (Gallery)findViewById(R.id.gallery);
        gallery.setAdapter(new ViewAdapter(this));

        gallery.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id)
            {
                Toast.makeText(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

public class ViewAdapter extends BaseAdapter
{
    public Context mContext;
    public static final Integer[] viewId = { R.layout.helloworld, R.layout.heyhowareyou };
    public int mGalleryItemBackground;

    public ViewAdapter(Context context)
    {
        this.mContext = context;
        TypedArray attr = context.obtainStyledAttributes(R.styleable.HelloGallery);
        mGalleryItemBackground = attr.getResourceId(R.styleable.HelloGallery_android_galleryItemBackground, 0);
        attr.recycle();
    }

    @Override
    public int getCount()
    {
        return viewId.length;
    }

    public Object getItem(int position)
    {
        return position;
    }

    public long getItemId(int position)
    {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        convertView = LayoutInflater.from(mContext).inflate(viewId[position], null);
        convertView.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        convertView.setBackgroundResource(mGalleryItemBackground);
        return convertView;
    }
}

I also referenced this a little bit. What Aavon in this thread is doing is exactly what I'm trying to get at...
Thread Link: Get button to work in gallery with inflated layouts
Any help?
Thanks in advance.

A: In my layout xml, I found that I wasn't setting the color for the text that was appearing on the screen. When I set that color, the text no longer dims out when loading the layout.


text:
Q: Authentication only for Admin prefix CakePHP 4 Hy guys!
I haven't been using Cake from gen 2 so i am a bit stuck with all the new stuff. I added the Authentication Component to my project and it works fine (login/out/pass hash etc) but i can't seem to find how to make only the "Admin" prefix to require Authentication.
In the old times was something "simple" like:
if($this->params['prefix'] == 'admin'){
    $this->Auth->deny('*');
}

A: While you could do something similar with the authentication plugin's authentication component, authentication is now performed at middleware level, that is before a controller is being invoked, hence it is probably best to avoid trying to authenticate a user in the first place when it's not actually needed.
Scope the middleware
With the authentication plugin there's a few way to handle this, the easiest way would probably be to apply the authentication middleware on routing level, so that it is scoped to your prefixed routes.
You'd just remove adding the middleware in your Application::middleware() method (src/Application.php), and instead add it in either your config/routes.php file, or your Application::routes() method, depending on where you're connecting your prefix route:
$routes->prefix('Admin', function (RouteBuilder $routes) {
    $routes->registerMiddleware(
        'auth',
        new \Authentication\Middleware\AuthenticationMiddleware($this)
    );
    $routes->applyMiddleware('auth');

    // ...
});

This way only the routes connected in that prefix are going have authentication applied.
Conditionally require an authenticated user
As a second step you'd still need to handle checking for the possibly authenticated user, so that your endpoints are actually protected. By default the authentication component will do automatically, so one way would be to load the authentication component only for the Admin prefix, for example in your AppController::initialize() method:
if ($this->request->getParam('prefix') === 'Admin') {
    $this->loadComponent('Authentication.Authentication');
}

Note the capital A in Admin! In CakePHP 4.x prefixes on are now camel cased, while the generated URLs are lower cased and dash separated!
See also

*

*Cookbook > Routing > Connecting Scoped Middleware

*Cookbook > Routing > Prefix Routing

*Cookbook > Request & Response Objects > Request > Request Parameters

A: I don't know if this is a conventional method, but it works.
In the callback method beforeFilter, in my global Appcontroller.php, I had this code:
public function beforeFilter(\Cake\Event\EventInterface $event)
    {
        if($this->request->getParam('prefix') == 'Api') {
            $this->Authentication->allowUnauthenticated([$this->request->getParam('action')]);
        }

    }
}

It allows access to all methods of my prefix API.


text:
Q: Magento 1.9 turns 503 error on Stripe Webhook request Please help to clarify which side Magento1.9 or Server turns 503 error to stripe webhook in such cases:

*

*Case 1: Successful payment -- web hook fails to create magento
  orderes,

*Case 2: cancelled subscription -- web hook is not
  processed.  503 Error

*Case 3: Successful payment - web hook
  fails with 503

The access.log contains such lines (ip at the begining of line was changed for example):
-11.111.111.111 - - [26/Feb/2018:09:40:24 +0000] "POST
/subscription/stripe/webhook HTTP/1.1" 503 7319 "-" "Stripe/1.0
(+https://stripe.com/docs/webhooks)"
-22.222.222.222 - - [26/Feb/2018:17:30:01 +0000] "GET /cron.php HTTP/1.1" 20 +0000] "POST /subscription/stripe/webhook HTTP/1.1" 200 3907 "-" "Stripe/1.0 (+https://stripe.com/docs/webhooks)"0 3444 "-" "Wget/1.15 (linux-gnu)"
-33.333.333.333 - - [26/Feb/2018:17:48:26 +0000] "POST /subscription/stripe/webhook HTTP/1.1" 200 3907 "-" "Stripe/1.0 (+https://stripe.com/docs/webhooks)"
-22.222.222.222 - - [26/Feb/2018:18:07:58 +0000] "POST /subscription/stripe/webhook HTTP/1.1" 503 7321 "-" "Stripe/1.0 (+https://stripe.com/docs/webhooks)"
So as you see sometimes it turns 200 sometimes 503.
There is no maintenance.flag file. Site is working fine except named cases.
How to define what cause of such cases?
Also i got this error page
Customer email is required
Trace:
0 - /var/www/html/app/code/core/Mage/Customer/Model/Resource/Customer.php(76): Mage::exception('Mage_Customer', 'Customer email ...')
1 - /var/www/html/app/code/core/Mage/Eav/Model/Entity/Abstract.php(1122): Mage_Customer_Model_Resource_Customer->_beforeSave(Object(Mage_Customer_Model_Customer))
2 - /var/www/html/app/code/core/Mage/Core/Model/Abstract.php(318): Mage_Eav_Model_Entity_Abstract->save(Object(Mage_Customer_Model_Customer))
3 - /var/www/html/app/code/local/Blackbox/Subscription/controllers/StripeController.php(123): Mage_Core_Model_Abstract->save()
4 -  /var/www/html/app/code/local/Blackbox/Subscription/controllers/StripeController.php(18): Blackbox_Subscription_StripeController->paymentSucceeded(Array)
5 -  /var/www/html/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Blackbox_Subscription_StripeController->webhookAction()
6 -  /var/www/html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(254): Mage_Core_Controller_Varien_Action->dispatch('webhook')
7 -  /var/www/html/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
8 -  /var/www/html/app/code/core/Mage/Core/Model/App.php(365): Mage_Core_Controller_Varien_Front->dispatch()
9 -  /var/www/html/app/Mage.php(684): Mage_Core_Model_App->run(Array)
10 -  /var/www/html/index.php(83): Mage::run('', 'store')
11 -  {main}


text:
Q: upload to document library subfolder in client object model I'm using the Client Object Model to upload files from a network drive to a SharePoint document library. Here is how I would specify the upload location if I were uploading to the document library's root folder:
Microsoft.SharePoint.Client.File uploadFile = docLibrary.RootFolder.Files.Add(newFile);

How can I upload to a specific subfolder by name?

A: I think the simplest code is this:
ClientContext context = new ClientContext("http://MySiteUrl");
using (FileStream fs = new FileStream(@"x:\MyFile.docx", FileMode.Open))
{
   Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, "/MyLibName/MyFolderName/MyFile.docx", fs, true);
}

So you just need to provide sub-folder url.
References:
File.SaveBinaryDirect Method
Uploading files using Client Object Model in SharePoint 2010
ADDITION:
The The remote server returned an error: (409) Conflict. when running above code will occur if target folder doesn't exist.
To check if folder exist one can use:
ClientContext context = new ClientContext("http://MySiteUrl");
Folder f = web.GetFolderByServerRelativeUrl(listUrl + "/" + newDocSetName);
context .Load(f);
bool alreadyExists = false;
try
{
    clientContext.ExecuteQuery();
    alreadyExists = true;
}
catch { }

Code borrowed from Matt Rankin blog post:
SharePoint 2010 : Using The Client Object Model To Move Files And Folders Across Site Collections And Subsites Check it out!

A: The accepted answer here may work but it is not proper user of the API.  The two main problems with this kind of approach are (a) exceptions are being thrown around for common cases (e.g. a folder that may not exist, actually doesn't) and (b) you often won't be able to give fine grained explanations to the user about why the operation failed because most of the API is being bypassed.
The proper way to do what you're trying to do is the following:
var subFolders = docLibrary.RootFolder.Folders.Where(folder => folder.Name == "My Subfolder");

_context.ExecuteQuery();

var spFolder = subFolders.FirstOrDefault();

If spFolder is null, the sub folder does not exist (note: if you wanted to make a method for checking the existence of sub folders you could return subFolders.Any()).  If it is not null then this is the folder and you can do all the same operations on it as you can on RootFolder.


text:
Q: Int64 as result from double times 10^x? I have a variable representing a quantity in some given unit:
enum Unit
{
  Single,
  Thousand,
  Million,
  Billion,
  Trillion
}

public class Quantity()
{

  public double number;
  public Unit numberUnit;

  public Int64 GetNumberInSingleUnits()
  {
    // ???
  }

}

For example, imagine
var GDP_Of_America = new Quantiy { number = 16.66, numberUnit = Unit.Trillion };
Int64 gdp = GDP_Of_America.GetNumberinSingleUnits();  // should return 16,660,000,000,000

My question is basically - how can I implement the "GetNumberInSingleUnits" function?
I can't just multiply with some UInt64 factor, e.g.
        double num = 0.5;
        UInt64 factor = 1000000000000;

        var result = num * factor; // won't work! results in double

As the regular numeric operations reslt in a double, but the result may be larger than the range of valid doubles.
How could I do this conversion?
ps, I know the class "Quantity" is not a great way to store information - but this is bound by the input data of my application, which is in non-single (e.g. millions, billions etc) units.

A: Like I said, decimals can help you here:
public enum Unit
{
    Micro = -6, Milli = -3, Centi = -2, Deci = -1,
    One /* Don't really like this name */, Deca, Hecto, Kilo, Mega = 6, Giga = 9
}

public struct Quantity
{
    public decimal Value { get; private set; }

    public Unit Unit { get; private set; }

    public Quantity(decimal value, Unit unit) :
        this()
    {
        Value = value;
        Unit = unit;
    }

    public decimal OneValue /* This one either */
    {
        get
        {
            return Value * (decimal)Math.Pow(10, (int)Unit);
        }
    }
}

With decimals you won't lose a lot of precision until after you decide to convert them to long (and beware of over/underflows).

A: Anton's answer seems like a good solution.
Just for the sake of discussion, another potential way.
I don't like this one at all as it seems very messy; However I think this might avoid imprecisions, if these ever turned out to be an issue with decimals.
public Int64 GetAsInt64(double number)
{
    // Returns 1 for single units, 3 for thousands, 6 for millions, etc.
    uint e = GetFactorExponent();

    // Converts to scientific notation
    // e.g. number = -1.2345, unit millions to "-1.2345e6"
    string str = String.Format("{0:#,0.###########################}", number) + "e" + e;

    // Parses scientific notation into Int64
    Int64 result = Int64.Parse(str, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent | NumberStyles.AllowThousands);
    return result;
}


text:
Q: Sql para contagem de parcelas Tenho uma tabela de boletos de clientes.
Os campos significantes são os seguintes:
| vencimento | data_pagamento | valor_pago |

Preciso fazer uma consulta que me retorne:

*

*A quantidade de parcelas vencidas não pagas;

*A quantidade de parcelas pagas;

*A quantidade de parcelas não pagas que ainda não venceram;

Estou tentando dessa forma:
SELECT
COUNT(CASE WHEN vencimento < NOW() AND data_pagamento IS NULL THEN 1 ELSE 0 END) as 'VENCIDAS',
COUNT(CASE WHEN data_pagamento IS NOT NULL THEN 1 ELSE 0 END) as 'PAGAS',
COUNT(CASE WHEN vencimento >= NOW() AND data_pagamento IS NULL THEN 1 ELSE 0 END) as 'A VENCER'
FROM boletos WHERE cliente = 12345;

Porém não me retorna os valores corretos.
Existe algum meio melhor ?
O que estou fazendo de errado ao utilizar CASE WHEN ?

A: O COUNT que está a utilizar vai sempre devolver 1, seja COUNT(1) ou COUNT(0) ou mesmo COUNT(1000), por isso é que não está a dar os resultados esperados.
A solução passa por utilizar o SUM, para que seja somado 1 sempre que a condição se verificar e 0 em caso contrário:
SELECT      cliente
        ,   SUM(CASE WHEN vencimento < NOW() AND data_pagamento IS NULL     THEN 1 ELSE 0 END)  AS 'VENCIDAS'
        ,   SUM(CASE WHEN data_pagamento IS NOT NULL                        THEN 1 ELSE 0 END)  AS 'PAGAS'
        ,   SUM(CASE WHEN vencimento >= NOW() AND data_pagamento IS NULL    THEN 1 ELSE 0 END)  AS 'A VENCER'
FROM        boletos
GROUP BY    cliente
ORDER BY    cliente

Se pretender filtrar por cliente basta adicionar a cláusula WHERE:
SELECT      cliente
        ,   SUM(CASE WHEN vencimento < NOW() AND data_pagamento IS NULL     THEN 1 ELSE 0 END)  AS 'VENCIDAS'
        ,   SUM(CASE WHEN data_pagamento IS NOT NULL                        THEN 1 ELSE 0 END)  AS 'PAGAS'
        ,   SUM(CASE WHEN vencimento >= NOW() AND data_pagamento IS NULL    THEN 1 ELSE 0 END)  AS 'A VENCER'
FROM        boletos
WHERE       cliente = 12345
GROUP BY    cliente

A: Deve ter um jeito melhor de fazer, eu faria com CTE no Oracle (que é o que eu uso) mas no MySQL eu tentaria algo assim:
select (select count('X') from boletos where vencimento < '2019-01-23' AND data_pagamento IS NULL and cliente = 12345),
   (select count('X') from boletos where data_pagamento IS NOT NULL and cliente = 12345),
   (select count('X') from boletos where vencimento >= '2019-01-23' AND data_pagamento IS NULL and cliente = 12345) from dual


text:
Q: Importing tabular data that has been exported from Evernote In Evernote you can embed HTML tables in the note. You can then export them to an xml format with the extension enex. I am trying to get the data from the table imported into Mathematica. Here is the data from a small test note I made and exported as test.enex:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE en-export SYSTEM "http://xml.evernote.com/pub/evernote-export.dtd">
<en-export export-date="20120812T214410Z" application="Evernote/Windows" version="4.x">
<note><title>test</title><content><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">

<en-note style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;">

heading 1	heading 2	heading 3

text 1	12.34	5

text 2
	9

text 3	13.33	10

</en-note>]]></content><created>20120812T144746Z</created><updated>20120812T214402Z</updated><tag>testtag</tag></note></en-export>

I am not really sure how to get this imported into Mathematica and then get the data extracted from the embedded HTML table. Any help would be appreciated.
EDIT: Slightly changed the test data so that there is a missing data point, which it turns out happens in my real dataset.

A: Below I use ImportString as a proxy for Import so that we don't need external files for the demonstration, but Import should work similarly.
imp = ImportString["<- paste your XML code between the double quotes ->", {"XML", "CDATA"}]

(* ==>
{"test", "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <!DOCTYPE \
en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\"> <en-note \
style=\"word-wrap: break-word; -webkit-nbsp-mode: space; \
-webkit-line-break: after-white-space;\">

heading 1	heading \
2	heading 3

text 1	12.34	5

text 2	12.1	9

text 3	13.33	10

</en-note>", \
"20120812T144746Z", "20120812T144859Z", "testtag"}
*)

Apparently we need the second element here. We'll try to import that as HTML and get the data out of it:
ImportString[imp[[2]], {"HTML", "Data"}]

{{"heading 1", "heading 2", "heading 3"}, {"text 1", 12.34,    5},
  {"text 2", 12.1, 9}, {"text 3", 13.33, 10}}


text:
Q: PreAuthorize not getting honored over ResourceServerConfigurerAdaptor I have a Spring Resource Server with Spring Security enabled. In Resource Server, i am extending the ResourceServerConfigurerAdaptor, some like the following.
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .anonymous().disable().requestMatcher(new OAuthRequestedMatcher()).authorizeRequests()
            .antMatchers(HttpMethod.POST, "/api/admin/**").hasAnyRole("ADMIN")
            .anyRequest().authenticated();
    }

    private static class OAuthRequestedMatcher implements RequestMatcher {
        public boolean matches(HttpServletRequest request) {
            String auth = request.getHeader("Authorization");
            boolean haveOauth2Token = (auth != null) && auth.toLowerCase().startsWith("bearer");
            boolean haveAccessToken = request.getParameter("access_token") != null;
            return haveOauth2Token || haveAccessToken;
        }
    }
}

Here i am expecting /api/admin/** to be accessible to ADMIN Role only.
Everything works fine till now.
But now i am trying to override this behavior at the method level using @PreAuthorize method level annotation.
Following is the RestController
@RestController
@RequestMapping("/api/admin/event")
public class ShunyaEventResource {

    @Autowired
    private ShunyaEventService eventService;

    @PreAuthorize("hasRole('ADMIN') or #oauth2.hasScope('write')")
    @PostMapping
    public void createEvent(@RequestBody ShunyaEvent event, Principal user) {
        eventService.create(event);
    }

}

So, i want to allow /api/admin/event to be accessible to #oauth2 write scope as well. But this does not work, unless either i remove /api/admin/** from antmatcher altogether or i add #oauth2.hasScope('write') in antmatcher itself.
I have already defined the below configuration
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        return new OAuth2MethodSecurityExpressionHandler();
    }
}

Here my question is why Method Level security not working for an endpoint that is already covered by ResourceServerConfigurerAdapter? What is precedence of security filter when same endpoint is covered by MethodLevel Security (using PreAuthorize) and HttpSecurity antMatcher?
Really appreciate any help on this.


text:
Q: Communicate with a subprocess using pyzmq I'm trying to communicate with a subprocess which I start using multiprocessing.Process via a ZeroMQ socket.  I know that there exist solutions to communicate with subprocesses within the multiprocessing module but I want to ultimately communicate with a function from a shared library written in C++.  Without further ado, here is the self-contained code:
import time
import zmq
import multiprocessing

def perform(nseconds, endpoint):
    context = zmq.Context()
    publisher = context.socket(zmq.PUB)
    publisher.connect(endpoint)

    for i in range(5):
        time.sleep(nseconds)
        publisher.send_string("{}".format(i))
    publisher.send_string(">>END")

if __name__ == "__main__":
    multiprocessing.freeze_support()
    context = zmq.Context()
    socket = context.socket(zmq.SUB)
    socket.bind("tcp://*:*")
    socket.setsockopt_string(zmq.SUBSCRIBE, u"")
    endpoint = socket.getsockopt_string(zmq.LAST_ENDPOINT)

    print("Binding via {}".format(endpoint))

    t = multiprocessing.Process(target=perform, args=(1,endpoint))
    t.start()

    string = ""
    while not ">>END" in string:
        string = socket.recv_string()
        print(string)

    t.join()

This code runs perfectly fine on GNU/Linux with the expected output:
Binding via tcp://0.0.0.0:34149
0
1
2
3
4
>>END

But running this on Windows with Python from Anaconda and pyzmq version 16.0.2 installed with conda install pyzmq it crashes with the following error:
Binding via tcp://0.0.0.0:52019
Assertion failed: Can't assign requested address (bundled\zeromq\src\tcp_connect
er.cpp:341)

How do I fix this?  Or am I doing it wrong?  And if I am doing it wrong, why is it platform dependent?

A: Remove the wildcard in socket.bind( "tcp://*:*" )
First,
this is very platform specific, one ought never rely on how the wildcard expansion will get handled on unknown ecosystem details in production. Be explicit.
Next,
this is on the very contrary to the concise, state-of-art resources management practice in Distributed-systems design and there could be hardly a worse idea from the architecture point of view, than to .bind() straight on all ports on all localhost available addresses. Just imagine what this causes inside the Context()-instance, to manage all that herd of endpoints and their associated resources' pools ready and sniffing for a potentially incoming connection request ( just in case one such may appear ). No.
Never do this.

Performance sins and other aspects  - ref. my criticism on Amdahl's Law v/s costs
Well, having seen your publications, I will not expand this a lot, but yet have to add, the Distributed-computing realm requires a lot of care spent on details -- never expect a few SLOCs to perform any good for HPC computations.
The worst sins come from a good will to improve some process. If a code spins-off a process ( what the multiprocessing is exactly designed to do ), not many people also associate with such a SLOC the actual costs, that have to be paid, before the departed code gets it's first chance to start processing ( replica of the complete python execution environment ( so as to escape from the original local-GIL etc ) -- so your code has to pay in both [TIME] and [SPACE] for a huge memory-to-memory transfer, next your proposed code instantiates another "remote"-process Context()-engine. While this may look smart, your code has to pay for it again all costs - and spend just a few SLOCs to process. Next, always use rather a .setsockopt(  zmq.LINGER, 0 ), so as not to leave your resources infinitely blocking a graceful termination. While this seems as a "nice-to-have" preventive step, it is rather a "must-do" lifesaver, before hunting "what went wrong this time?" on a big and expensive computing infrastructure...
Many other performance tweaking deserves to be done before shelling out multiprocessing.Process( ... ), which goes way beyond the scope of this post. But worth mastering, definitely before running many-times inefficient code.


text:
Q: PassportJS rename "user" object I am using PassportJS for my login functionalIs there a way to change the "user" object name in the request?
This is how it works now, by default (req.user):
function (req, res, next) {
    if (!req.user) {
        req.flash('error', 'Please sign in to access this page.');
        res.redirect('/login');
    } else {
        next();
    }
}

I would like to use the following instead (req.candidate):
function (req, res, next) {
    if (!req.candidate) {
        req.flash('error', 'Please sign in to access this page.');
        res.redirect('/login');
    } else {
        next();
    }
}

A: You can change it in initialization:
 passport.initialize( {
      userProperty: 'student' // defaults to 'user' if omitted
     })

This code set: req.student
What you will do next depends on you and the used framework.
Look at source code:
Passport source code


text:
Q: Sequelize delete request with payload works with Postman but not with Vue Frontend implementation I am trying to send PUT and DELETE requests with my express backend to a sqlite database. Put request works fine but DELETE request always fails.
I already checked the headers within the network tab, it seems to be the right one for both (application/json)
With postman, I can easily delete entries, but with my frontend the body does not seem to be set correctly.
       const countryToPush = {title: countryName}
       try{
        await CountryService.post(countryToPush)
        console.log(countryName + ' added!')
       } catch(err)
       {
        console.log(err)
       }
       },
       removeFromDb: async function(countryName){
       const countryToDelete = {title: countryName}
       try{
        await CountryService.delete(countryToDelete)
        console.log(countryName + ' deleted!')
       } catch(err)
       {
        console.log(err)
       }
      }

This is within my vue file where I get the 'countryName' from an on click function.
    try {
      const country = await Country.create(req.body)
      res.send(country)
    } catch (err) {
      res.status(500).send({
        error: 'an error has occurred trying to create the country'
      })
    }
  },
  async delete (req, res) {
    try {
      const toDelete = await Country.findOne({
        where: {
          title: req.body.title
        }
      })
      await toDelete.destroy()
      res.send(req.body.title + ' was deleted')
    } catch (err) {
      res.status(500).send({
        error: 'an error has occurred trying to delete the country'
      })
    }
  }

Whereas this is the example from my sqlite calls
Unfortunately, the DELETE request from my vue frontend always fails and gives me the defined error 500 an error has occurred trying to delete the country.
Any ideas what else I could try to get it working?

A: Model.delete() is not a Sequelize function, you want to use Model.destroy().
await CountryService.destroy(countryToDelete)

Right now you are swallowing the actual error - add console.log(err) to your catch to see that it is probably saying CountryService.destroy is undefined.


text:
Q: Is String Builder or ""+someNumb more efficient/correct for small cases? II've been in the habit of doing:
int num = 12;
String text = ""+12;

for a long time, but I've found that to be a very inefficient mechanism for the large number of additions.
For those cases I generally do something like:
// this is psuedo code here..
FileInputStream fis = new FileInputStream(fis);
StringBuilder builder = new StringBuilder();
while(input.hasNext()) {
   builder.append(input.nextString());
}

My question is:  When coding for Android (vs the General Java case) Is the performance trade off at the small case worth using String Builder, or are there any other reasons to prefer String Builder in these small cases?  It seems like it's a lot of extra typing int he simple case presented above.  I also suspect (though I have not confirmed) that the memory allocations in the simple case are probably not worth it.
Edit:  Suppose that the values being appended aren't known at compile time, I.E. they aren't constants.
Also the example above of ""+12 is a poorly chosen example..  Suppose it was
String userGeneratedText  = textInput.getText().toString();
int someVal = intInput.getInt();

String finalVal = userGeneratedText+someVal;

A: If your code is short as you shown here:
String text = "foo" + 12;

The compiler will automatically replace the concatenation to use StringBuilder:
String text = new StringBuilder().append("foo").append(12).toString();

So don't worry about the inefficiency of this code, because it will work better than you expect.
For cases when you need to append very large Strings or you don't know how many objects (Strings, ints, booleans, etc) will you concatenate, use a StringBuilder as you do in your second code sample.
Here's a more in depth explanation about how the String concatenation works: http://blog.eyallupu.com/2010/09/under-hood-of-java-strings.html

A: As far as I know! string is immutable object. It means that its state cannot be changed, when ever you append value to string type then what happened is compiler deletes old one create new one with apended value.
But this is not the case with StringBuilder. StringBuilder is mutable which means its old value won't be destroyed. Any change/append will be taken place with existing object.
I know I am not covering in depth but this might cause major performance difference.


text:
Q: How to get "error" message from @commands.has_role() I recently made a discord bot using discord.py. I tried making permissions for some commands. I have this test command function:
@client.command()
@commands.has_role('Moderator')
async def cool(ctx):
    await ctx.send("You are cool indeed!")

How can I return a message(error) when a user does not have the 'Moderator' role?
I've already tried this:
async def on_command_error(ctx, error):
    if isinstance(error, commands.NoPrivateMessage):
        await ctx.send("*Private messages.* ")
    elif isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("*Command is missing an argument:* ")
    elif isinstance(error, commands.DisabledCommand):
        await ctx.send("*This command is currenlty disabled. Please try again later.* ")
    elif isinstance(error, commands.CheckFailure):
        await ctx.send("*You do not have the permissions to do this.* ")
    elif isinstance(error, commands.CommandNotFound):
        await ctx.send("*This command is not listed in my dictionary.*")

But I'm not getting anything back from that.

A: In the on_command_error function, check against commands.MissingRole or commands.MissingAnyRole.
if isinstance(error, (commands.MissingRole, commands.MissingAnyRole)):
    ...


text:
Q: Swipe support with bootstrap carousel SOLVED Reference https://github.com/avinoamr/bootstrap-carousel-swipe
Hey guys i'm trying to design a website for my small business.. My primary goal is to add swipe support to my bootstrap custom carousel. I have found several answers to this but I cant seem to get it to work on my carousel. After a hour of trial and error I seek some advice...
What am I missing? Thank you in advance for your help!
update Im still trying to get this to work. Ive tried using the jquery cdn instead of local file.. Ive always tried using the hammer.js method. I got to thinking maybe the div overlay was stopping it, so I removed those for testing purpose without success.. I also tried removing data interval with no success.... Again any help would be appreciated thank you.
/* My Carousel HTML */

Shingle Roofing

"Get the Estimate You Deserve!"

        Call Now (217) 820-7597

Metal Roofing

"Get the Estimate You Deserve!"

        Call Now (217) 820-7597

Rubber Roofing

"Get the Estimate You Deserve!"

        Call Now (217) 820-7597

/* Slide Support Script */

A: I haven't tried this one yet but looks like it would work
http://www.jqueryscript.net/slider/Mobile-friendly-Carousel-Slideshow-Plugin-With-jQuery-Bootstrap.html
DEMO:
http://www.jqueryscript.net/demo/Mobile-friendly-Carousel-Slideshow-Plugin-With-jQuery-Bootstrap/


text:
Q: Using Multiple threads to access a Single Jedis client I am trying to access a jedis client with multiple threads where one thread can simple read and write to the database while the other thread can subscribe and a listen to a channel . Is this possible in jedis . Or if it is possible to write variables to one client by any other client that would also work.
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
public class Testing1 {
public static void main(String args[])
{
   final Jedis jedis = new Jedis("localhost");
    Runnable runnable =()->
    {
        System.out.println(jedis.clientId());
        jedis.set("acd","acg");
        String str=jedis.get("acd");
        System.out.println(str);

    };
    Runnable runnable2 =()->
    {
        System.out.println(jedis.clientId());
        JedisPubSub jedisPubSub = new JedisPubSub()
        {
            @Override
            public void onMessage(String channel, String message) {
                System.out.println("Channel " + channel + " has sent a message : " + message );
                if(channel.equals("C1")) {
                    /* Unsubscribe from channel C1 after first message is received. */
                    unsubscribe(channel);
                }
            }

            @Override
            public void onSubscribe(String channel, int subscribedChannels) {
                System.out.println("Client is Subscribed to channel : "+ channel);
                System.out.println("Client is Subscribed to "+ subscribedChannels + " no. of channels");
            }

            @Override
            public void onUnsubscribe(String channel, int subscribedChannels) {
                System.out.println("Client is Unsubscribed from channel : "+ channel);
                System.out.println("Client is Subscribed to "+ subscribedChannels + " no. of channels");
            }

        };
        jedis.subscribe(jedisPubSub, "__redis__:invalidate");
    };

  / Thread thread= new Thread(runnable);
    Thread thread1= new Thread(runnable2);
    thread.start();
    thread1.start();
    jedis.set("harry","veer");
    System.out.println(jedis.get("harry"));
}

}
Here is what I am trying basically please help me with this


text:
Q: Recursively filter nested json data using javascript or rxjs I am looking to find elegant solution to filter nested json data structure so that filter functionality can be applied.
pre-condtions:

*

*Depth is unknown (needs to be recursive Solution)

*if value doesn't matched and have childrens than all children should be attached to parent
and it should be recursive.

*Filter should work more than one By What i mean is if select filter By Y and by Z than
results of Y and Z should be shown in Tree Structure. But currently displayed example below
for filter by kind property and value to filter applied is Y .

Thanks!!
e.g
   var dataToFilter = {
        "children": [{
            "tagPath": "/../../tagPath-1",
            "children": [{
                "tagPath": "/../../tagPath-1-1",
                "children": [{
                        "tagPath": "/../../tagPath-1-2",
                        "kind": "Y",
                        "children": [{
                                "tagPath": "/../../tagPath-1-3.1",
                                "kind": "X",
                                "children": []
                            },
                            {
                                "tagPath": "/../../tagPath-1.3.2",
                                "kind": "X",
                                "children": [{
                                    "tagPath": "/../../tagPath-1.3",
                                    "kind": "Y",
                                    "children": []
                                }]
                            }
                        ]
                    },
                    {
                        "kind": "Y",
                        "children": []
                    }
                ],
                "kind": "X",
            }],
            "kind": "Y",
        }]

Desired Output on kind property when value is e.g Y :
var desiredOutput = {
        "children": [{
            "tagPath": "/../../tagPath-1",
            "children": [{
                    "tagPath": "/../../tagPath-1-2",
                    "kind": "Y",
                    "children": [{
                        "tagPath": "/../../tagPath-1.3",
                        "kind": "Y",
                        "children": []
                    }]
                },
                {
                    "kind": "Y",
                    "children": []
                }
            ],
            "kind": "Y",
        }]
    ```

A: You can use the following function:
const restructure = (nodes, filter) => nodes.reduce(
    (acc, node) => {
        const children = restructure(node.children, filter);

        return acc.concat(
            filter(node)
                ? {...node, children}
                : children
        );
    },
    []
);

Which accepts filter as a function. This allows you to decide how to filter, e.g.:
const yOnly = restructure(dataToFilter, node => 'Y' === node.kind);

Or:
const yAndX = restructure(dataToFilter, node => ['Y', 'X'].includes(node.kind));

The only difference to your code above is that dataToFilter must already be an array of nodes (see the full code snippet below).

const restructure = (nodes, filter) => nodes.reduce(
    (acc, node) => {
        const children = restructure(node.children, filter);

        return acc.concat(
            filter(node)
                ? {...node, children}
                : children
        );
    },
    []
);

const dataToFilter = [{
    'tagPath':  '/../../tagPath-1',
    'children': [{
        'tagPath':  '/../../tagPath-1-1',
        'children': [{
            'tagPath':  '/../../tagPath-1-2',
            'kind':     'Y',
            'children': [{
                'tagPath':  '/../../tagPath-1-3.1',
                'kind':     'X',
                'children': []
            }, {
                'tagPath':  '/../../tagPath-1.3.2',
                'kind':     'X',
                'children': [{
                    'tagPath':  '/../../tagPath-1.3',
                    'kind':     'Y',
                    'children': []
                }]
            }]
        }, {
            'kind':     'Y',
            'children': []
        }],
        'kind':     'X',
    }],
    'kind':     'Y',
}];

const yOnly = restructure(dataToFilter, node => 'Y' === node.kind);
const xOnly = restructure(dataToFilter, node => 'X' === node.kind);
const yAndX = restructure(dataToFilter, node => ['Y', 'X'].includes(node.kind));

console.log(yOnly);
console.log(xOnly);
console.log(yAndX);


text:
Q: Getting Outlook::_MailItem from Outlook::Attachment (embedded email) I'm writing an Outlook Addin using VC/ATL. This particular addin takes selected email messages and writes them to disk. It also writes all of the associated attachments to disk. We then read everything in to our application outside of Outlook.
Using the Outlook object model, this is pretty straightforward as both _MailItem and Attachment have SaveAs methods. The problem comes when an attachment is an embedded email itself, which we also want to break apart and save as individual files.
In an ideal world, I could query the attachment for the _MailItem interface and just handle it like a normal part of the selection. But QueryInterface returns "no interface".
I need a solution that works with Outlook XP (2002) through Outlook 2010. I know that in Outlook 2007 there is a method (CreateItemFromTemplate) on the application object which allows me to get a MailItem  back from a saved message on disk, but that won't work for Outlook XP / 2003. I also need sender / recipient info intact.
I also know that the 3rd party Redemption library can do this using Extended MAPI. However, we are trying to avoid using 3rd party libraries.

A: If you don't want to use third party libraries then you will probably have to write your own MSG-file parser to extract the embedded mail items.
Apart from that, if you really are serious about developing Outlook addins then you will end up using Redemption sooner or later anyway, so why wait? It definitely is worth more than its author's weight in gold.


text:
Q: Create a column of random integers, where the min and max integer for each row come from adjacent columns I have a data frame:
letter <- c("A", "B", "C")
min <- c(1, 2, 3)
max <- c(4, 5, 6)
df <- data.frame(letter, min, max)

I want to add a 4th column to df which generates a random number for each row, where the lower and upper limits from which the random integers are sampled from are the min and max values of that row, respectively.
I have an inkling that I should use sample(), but when I do it returns a column of values drawn randomly from the referenced column:
df$random <- sample(df$max)

Could I also use runif?

A: Assuming your dataframe df as
   letter min max
1      A   1   4
2      B   2   5
3      C   3   6

I have a feeling there should be a better base R solution than this. However, for now we can try with apply and select (sample) any random number between the two columns.
df$third_column <- apply(df, 1, function(x) sample(x[2]:x[3], 1))
df

#  letter min max third_column
#1      A   1   4            1
#2      B   2   5            4
#3      C   3   6            4

A: You can go the dplyr way:
df %<>%
  rowwise() %>%
  dplyr::mutate(x = sample(min:max, 1))


text:
Q: Why changing canvas size resets its parameters? When I change the canvas size, I notice the parameter 'mozImageSmoothingEnabled' is being reset.
HTML
<canvas id='canv'>Your browser don't support canvas.</canvas>

Javascript
var cnv = document.getElementById('canv');
var ctx = cnv.getContext('2d');
console.log(ctx.mozImageSmoothingEnabled); // default 'true'
ctx.mozImageSmoothingEnabled = false;
console.log(ctx.mozImageSmoothingEnabled); // shows 'false'
cnv.width = 100;
console.log(ctx.mozImageSmoothingEnabled); // shows 'true'

JSFiddle: https://jsfiddle.net/epvtuz37/
Is this a bug, or expected behavior?

A: Because when you change the canvas width or height parameters, every properties of the attached context are reset to their default.
From specs

When the canvas element is created, and subsequently whenever the width and height attributes are set (whether to a new value or to the previous value), the bitmap and any associated contexts must be cleared back to their initial state and reinitialized with the newly specified coordinate space dimensions.


text:
Q: Array of uniformly spaced numbers I wanted to create a grid of equally spaced numbers. So far I obtained this:
m = Table[{i, j}, {i, 0.0, 1.0, 0.5}, {j, 0.0, 1.0, 0.5}]

Now when I am trying to cast them as vectors I obtained:
{ {{0., 0.}, {0., 0.5}, {0., 1.}},
  {{0.5, 0.}, {0.5, 0.5},{0.5, 1.}},
  {{1., 0.}, {1., 0.5}, {1., 1.}} }

Which, instead, I would like to be something like:
{{0., 0.},
 {0., 0.5},
 {0., 1.},
 {0.5, 0.},
 {0.5, 0.5},
 {0.5, 1.},
 ...., }

A: I'd use Outer, and then Flatten to get the desired level:
Flatten[Outer[List, Range[0, 1, 0.5], Range[0, 1, 0.5]], 1]

{{0., 0.}, {0., 0.5}, {0., 1.}, {0.5, 0.}, {0.5, 0.5},
 {0.5, 1.}, {1., 0.}, {1., 0.5}, {1., 1.}}

A: A variation on the method given by bill s:
Range[0, 1, 0.5] // Distribute[{#, #}, List] &

% // MatrixForm

$$\left(
\begin{array}{cc}
 0. & 0. \\
 0. & 0.5 \\
 0. & 1. \\
 0.5 & 0. \\
 0.5 & 0.5 \\
 0.5 & 1. \\
 1. & 0. \\
 1. & 0.5 \\
 1. & 1. \\
\end{array}
\right)$$

A: You can convert the full array into a list of pairs using Join, Catenate, or Flatten:
Join @@ m
Catenate[m]     (* version 10 or later *)
Flatten[m, 1]

(@@ is shorthand for Apply.  See also Partition and ArrayReshape.)
However there are arguably better ways to approach this problem from the outset than using Table.  Knowing that you want a "flat" output of pairs I would turn to Tuples.  The uniformly spaced numbers can be generated with Range, which is Listable, allowing this for your example:
Tuples @ Range[0, {1, 1}, .5]

{{0., 0.}, {0., 0.5}, {0., 1.}, {0.5, 0.}, {0.5, 0.5},
 {0.5, 1.}, {1., 0.}, {1., 0.5}, {1., 1.}}

Generalized to ranges that do not share common values, in two equivalent forms
Tuples @ Range[{0, 7}, {1, 8}, {.5, 1}]

Tuples[{Range[0, 1, .5], Range[7, 8, 1]}]

{{0., 7}, {0., 8}, {0.5, 7}, {0.5, 8}, {1., 7}, {1., 8}}

{{0., 7}, {0., 8}, {0.5, 7}, {0.5, 8}, {1., 7}, {1., 8}}

If you did want a full array instead of a flat list of pairs then look at Array and CoordinateBoundsArray:
Array[List, {3, 3}, {{0`, 1}}]

CoordinateBoundsArray[{{0, 1}, {0, 1}}, 0.5]

The syntax of Array is unlike the others in that the number of steps is specified rather than the size of the steps; this is sometimes more convenient.
Each of these generalized to the second example given for Tuples:
Array[List, {3, 2}, {{0`, 1}, {7, 8}}]

CoordinateBoundsArray[{{0, 1}, {7, 8}}, {0.5, 1}]

{{{0., 7}, {0., 8}}, {{0.5, 7}, {0.5, 8}}, {{1., 7}, {1., 8}}}

{{{0., 7}, {0., 8}}, {{0.5, 7}, {0.5, 8}}, {{1., 7}, {1., 8}}}


text:
Q: Exponential Search alternative to std::lower_bound Does the STL include an implementation of exponential search, already?
std::lower_bound states complexity logarithmic in the differences between the iterators (begin and end, so often the size of the array), whereas exponential search is logarithmic in the (expected) index of the element to search for.
While it's not hard to implement, I want to avoid an unnecessary re-implementation with it's already tehre and I just cannot find it.


text:
Q: Persisting form data on view after file upload post from same view I have a view to edit some document details and upload two related images. I want this view to post to two different actions on my controller, one for saving all the form fields and one to do the file upload.
I have one form around the main form and a multipart form around the file uplaod input
   <% using (Html.BeginForm("Edit", "Document", FormMethod.Post,
                                 new { enctype = "multipart/form-data" })) { %>

    <% =Html.TextBoxFor(model => model.Document.Title) %>
     <%= Html.TextBoxFor(model => model.Document.Description) %>

    //and then another multipart form around the file upload part like this
     <% using(Html.BeginForm("FileUpload", "Document", FormMethod.Post, new { enctype = "multipart/form-data" }))
                <input type="file" id="fileUpload" name="iamge" size="30" />
                <input type="submit" value="Upload" />
                  <% { %>

<input type="submit" value="Save" />
<% } %>

The file upload is happening correctly on posting the inner form but I want the controller to return the compelte model to the main view again with all the form fields persisited. The view is strongly typed so I thought I would post the whole model to the file upload action using the inner form. Can I get away with having just one multipart form that will post the files and the form data regardless of what input element is clicked? Is this good practice. At the end of the day all I want is to make sure all my form data is persisted on the Edit form after my file upload.
How can I pass the model data to the file upload action from the inner form?

A: You don't need the inner form I don't think. You can just have the outer form, which should parse in your model if you set up the action arguments. You could then have a different logic path in terms of, for instance, persisting other model elements depending on whether any files had been posted.
You would then be able to pass the model that had been posted back, back into the view.


text:
Q: Interlacing a single number into a long list This seems like it should be a simple question, but I am running into some difficulty in doing this with Mathematica. Right now, I have a list like this:
data1={0, 0, 0, 0, 0, 0, 3, 1, 10, 3, 11, 1, 0, 0, 32, 0, 1, 0, 5, 0, 2, 0, 25, 0, 1, 0, 1,
       0, 0, 0, 0, 7, 0, 0, 0, 0, 13, 4, 0, 5, 0, 0, 2, 3, 4, 0, 0, 95, 4, 16, 11, 2, 0, 0,
       81, 35, 0, 0, 0, 33, 0, 0, 0, 0, 0, 5, 42, 0, 0, 0};

I want to insert "1997" into the list after each element and transpose it, so that it will look like so: {{1997,0},{1997,0},{1997,0}...}. So far so good.
Unfortunately, the only way I know how to do this is to manually create a list of equal length to data1 (70 "1997"s in a row). I also do not know how to create a list that is just 70 "1997"s in a row. I've plumbed the documentation and tried every command I can think of, but the closest I can get are either functions or a list that resembles {{1997,0,1997,0,1997,0...} etc.

A: As always, there are several ways to skin the cat. Here's yet another one:
data1 /. x_Integer :> {1997, x}

Use x_Real or x_?NumericQ as necessary, if your list is not exactly made of integers as in the example.

A: One more:
ArrayFlatten@{{1997, List /@ data1}}

A: Absolutely unbeatable :
Tuples[{{1997}, data1}]

All other methods are much slower even Verbeia's {1997,#}&/@ data1 or dws' Thread[{1997, data1}]
Tuples[{{1997}, data1}] === ({1997, #} & /@ data1) ===  Thread[{1997, data1}]

True

We compare the most efficient methods for a long list :
 list = RandomChoice[data1, 10^7];

and results :
Thread[{1997, list}]; // AbsoluteTiming // First
{1997, #} & /@ list; // AbsoluteTiming // First
Tuples[{{1997}, list}]; // AbsoluteTiming // First

1.6000000
0.8470000
0.1960000

Other methods just for  completeness:
Inner[List, Table[1997, {Length @ data1}], data1, List]

Outer[List, {1997}, data1] // Flatten[#, 1] &

Transpose@{Table[1997, {Length @ data1}], data1}

A: Another possibility:
Thread[{1997,data1}]

A: The following works and is the way I would recommend:
{1997,#}&/@ data1

There is no need to create a list of 1997s of the same length as your original data.
I can think of a few other ways but they are more roundabout.
This version uses the optional third argument of Riffle.
Partition[Riffle[data1, 1997, {1, 2 Length[data1] - 1, 2}], 2]

There is no point using FoldList if you aren't using the intermediate values of the lists in your calculations, but the following works if what you really want is something more complicated than just joining 1997.
FoldList[{1997, #2} &, {1997, First[data1]}, Rest@data1]


text:
Q: Which button was clicked without using Javascript? There is a html code
<form>
  <button type="submit" name="button-name" value="btn1">button1</button>
  <button type="submit" name="button-name" value="btn2">button2</button>
</form>

Is there any way to determine which button was clicked on a server side? I'd like not to use javascript and not to replace them with input.
That's funny but I have nil in params["button-name"]

A: You should be able to check the value of the button-name parameter on the server side to determine which button was clicked.  In decent browsers it will be the value of the value attribute, but in IE you will receive the inner html of each button.
So for example, if I clicked the first button and was using Java on the server side:
In IE
String param = reqeust.getParameter("button-name");
System.out.println(param); // Prints button1

In Firefox
String param = reqeust.getParameter("button-name");
System.out.println(param); // Prints btn1

A: This would work if you are working with PHP on the server side.
if(isset($_GET['button-name']))
    echo $_GET['button-name'];

A: If you were to use PHP, this would work (assuming you use GET instead of POST):
if((isset($_GET['button-name'])) && ($_GET['button-name'] === 'btn1' ||  $_GET['button-name'] === 'btn2')){
}