Programs & Examples On #Nsmenu

OS X API : A class that defines an object that manages an application’s menus

android: data binding error: cannot find symbol class

Your problem might actually be on this line:

<include layout="@layout/content_contact_list" />

Android Studio gets a little confused at time and takes the include layout for the layout tag. What's even more frustrating is that this could work the first time, fails to work with a modification on the Java/Kotlin code later, and then work again after a tweak that forces it to rebuild the binding. You may want to replace <include> tags with something that populates it dynamically.

In android how to set navigation drawer header image and name programmatically in class file?

Also you can use Kotlinx features

val hView = nav_view.getHeaderView(0)
hView.textViewName.text = "lorem ipsum"
hView.imageView.setImageResource(R.drawable.ic_menu_gallery)

How to filter a RecyclerView with a SearchView

Introduction

Since it is not really clear from your question what exactly you are having trouble with, I wrote up this quick walkthrough about how to implement this feature; if you still have questions feel free to ask.

I have a working example of everything I am talking about here in this GitHub Repository.
If you want to know more about the example project visit the project homepage.

In any case the result should looks something like this:

demo image

If you first want to play around with the demo app you can install it from the Play Store:

Get it on Google Play

Anyway lets get started.


Setting up the SearchView

In the folder res/menu create a new file called main_menu.xml. In it add an item and set the actionViewClass to android.support.v7.widget.SearchView. Since you are using the support library you have to use the namespace of the support library to set the actionViewClass attribute. Your xml file should look something like this:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/action_search"
          android:title="@string/action_search"
          app:actionViewClass="android.support.v7.widget.SearchView"
          app:showAsAction="always"/>

</menu>

In your Fragment or Activity you have to inflate this menu xml like usual, then you can look for the MenuItem which contains the SearchView and implement the OnQueryTextListener which we are going to use to listen for changes to the text entered into the SearchView:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    final MenuItem searchItem = menu.findItem(R.id.action_search);
    final SearchView searchView = (SearchView) searchItem.getActionView();
    searchView.setOnQueryTextListener(this);

    return true;
}

@Override
public boolean onQueryTextChange(String query) {
    // Here is where we are going to implement the filter logic
    return false;
}

@Override
public boolean onQueryTextSubmit(String query) {
    return false;
}

And now the SearchView is ready to be used. We will implement the filter logic later on in onQueryTextChange() once we are finished implementing the Adapter.


Setting up the Adapter

First and foremost this is the model class I am going to use for this example:

public class ExampleModel {

    private final long mId;
    private final String mText;

    public ExampleModel(long id, String text) {
        mId = id;
        mText = text;
    }

    public long getId() {
        return mId;
    }

    public String getText() {
        return mText;
    }
}

It's just your basic model which will display a text in the RecyclerView. This is the layout I am going to use to display the text:

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

    <data>

        <variable
            name="model"
            type="com.github.wrdlbrnft.searchablerecyclerviewdemo.ui.models.ExampleModel"/>

    </data>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/selectableItemBackground"
        android:clickable="true">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:text="@{model.text}"/>

    </FrameLayout>

</layout>

As you can see I use Data Binding. If you have never worked with data binding before don't be discouraged! It's very simple and powerful, however I can't explain how it works in the scope of this answer.

This is the ViewHolder for the ExampleModel class:

public class ExampleViewHolder extends RecyclerView.ViewHolder {

    private final ItemExampleBinding mBinding;

    public ExampleViewHolder(ItemExampleBinding binding) {
        super(binding.getRoot());
        mBinding = binding;
    }

    public void bind(ExampleModel item) {
        mBinding.setModel(item);
    }
}

Again nothing special. It just uses data binding to bind the model class to this layout as we have defined in the layout xml above.

Now we can finally come to the really interesting part: Writing the Adapter. I am going to skip over the basic implementation of the Adapter and am instead going to concentrate on the parts which are relevant for this answer.

But first there is one thing we have to talk about: The SortedList class.


SortedList

The SortedList is a completely amazing tool which is part of the RecyclerView library. It takes care of notifying the Adapter about changes to the data set and does so it a very efficient way. The only thing it requires you to do is specify an order of the elements. You need to do that by implementing a compare() method which compares two elements in the SortedList just like a Comparator. But instead of sorting a List it is used to sort the items in the RecyclerView!

The SortedList interacts with the Adapter through a Callback class which you have to implement:

private final SortedList.Callback<ExampleModel> mCallback = new SortedList.Callback<ExampleModel>() {

    @Override
    public void onInserted(int position, int count) {
         mAdapter.notifyItemRangeInserted(position, count);
    }

    @Override
    public void onRemoved(int position, int count) {
        mAdapter.notifyItemRangeRemoved(position, count);
    }

    @Override
    public void onMoved(int fromPosition, int toPosition) {
        mAdapter.notifyItemMoved(fromPosition, toPosition);
    }

    @Override
    public void onChanged(int position, int count) {
        mAdapter.notifyItemRangeChanged(position, count);
    }

    @Override
    public int compare(ExampleModel a, ExampleModel b) {
        return mComparator.compare(a, b);
    }

    @Override
    public boolean areContentsTheSame(ExampleModel oldItem, ExampleModel newItem) {
        return oldItem.equals(newItem);
    }

    @Override
    public boolean areItemsTheSame(ExampleModel item1, ExampleModel item2) {
        return item1.getId() == item2.getId();
    }
}

In the methods at the top of the callback like onMoved, onInserted, etc. you have to call the equivalent notify method of your Adapter. The three methods at the bottom compare, areContentsTheSame and areItemsTheSame you have to implement according to what kind of objects you want to display and in what order these objects should appear on the screen.

Let's go through these methods one by one:

@Override
public int compare(ExampleModel a, ExampleModel b) {
    return mComparator.compare(a, b);
}

This is the compare() method I talked about earlier. In this example I am just passing the call to a Comparator which compares the two models. If you want the items to appear in alphabetical order on the screen. This comparator might look like this:

private static final Comparator<ExampleModel> ALPHABETICAL_COMPARATOR = new Comparator<ExampleModel>() {
    @Override
    public int compare(ExampleModel a, ExampleModel b) {
        return a.getText().compareTo(b.getText());
    }
};

Now let's take a look at the next method:

@Override
public boolean areContentsTheSame(ExampleModel oldItem, ExampleModel newItem) {
    return oldItem.equals(newItem);
}

The purpose of this method is to determine if the content of a model has changed. The SortedList uses this to determine if a change event needs to be invoked - in other words if the RecyclerView should crossfade the old and new version. If you model classes have a correct equals() and hashCode() implementation you can usually just implement it like above. If we add an equals() and hashCode() implementation to the ExampleModel class it should look something like this:

public class ExampleModel implements SortedListAdapter.ViewModel {

    private final long mId;
    private final String mText;

    public ExampleModel(long id, String text) {
        mId = id;
        mText = text;
    }

    public long getId() {
        return mId;
    }

    public String getText() {
        return mText;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ExampleModel model = (ExampleModel) o;

        if (mId != model.mId) return false;
        return mText != null ? mText.equals(model.mText) : model.mText == null;

    }

    @Override
    public int hashCode() {
        int result = (int) (mId ^ (mId >>> 32));
        result = 31 * result + (mText != null ? mText.hashCode() : 0);
        return result;
    }
}

Quick side note: Most IDE's like Android Studio, IntelliJ and Eclipse have functionality to generate equals() and hashCode() implementations for you at the press of a button! So you don't have to implement them yourself. Look up on the internet how it works in your IDE!

Now let's take a look at the last method:

@Override
public boolean areItemsTheSame(ExampleModel item1, ExampleModel item2) {
    return item1.getId() == item2.getId();
}

The SortedList uses this method to check if two items refer to the same thing. In simplest terms (without explaining how the SortedList works) this is used to determine if an object is already contained in the List and if either an add, move or change animation needs to be played. If your models have an id you would usually compare just the id in this method. If they don't you need to figure out some other way to check this, but however you end up implementing this depends on your specific app. Usually it is the simplest option to give all models an id - that could for example be the primary key field if you are querying the data from a database.

With the SortedList.Callback correctly implemented we can create an instance of the SortedList:

final SortedList<ExampleModel> list = new SortedList<>(ExampleModel.class, mCallback);

As the first parameter in the constructor of the SortedList you need to pass the class of your models. The other parameter is just the SortedList.Callback we defined above.

Now let's get down to business: If we implement the Adapter with a SortedList it should look something like this:

public class ExampleAdapter extends RecyclerView.Adapter<ExampleViewHolder> {

    private final SortedList<ExampleModel> mSortedList = new SortedList<>(ExampleModel.class, new SortedList.Callback<ExampleModel>() {
        @Override
        public int compare(ExampleModel a, ExampleModel b) {
            return mComparator.compare(a, b);
        }

        @Override
        public void onInserted(int position, int count) {
            notifyItemRangeInserted(position, count);
        }

        @Override
        public void onRemoved(int position, int count) {
            notifyItemRangeRemoved(position, count);
        }

        @Override
        public void onMoved(int fromPosition, int toPosition) {
            notifyItemMoved(fromPosition, toPosition);
        }

        @Override
        public void onChanged(int position, int count) {
            notifyItemRangeChanged(position, count);
        }

        @Override
        public boolean areContentsTheSame(ExampleModel oldItem, ExampleModel newItem) {
            return oldItem.equals(newItem);
        }

        @Override
        public boolean areItemsTheSame(ExampleModel item1, ExampleModel item2) {
            return item1.getId() == item2.getId();
        }
    });

    private final LayoutInflater mInflater;
    private final Comparator<ExampleModel> mComparator;

    public ExampleAdapter(Context context, Comparator<ExampleModel> comparator) {
        mInflater = LayoutInflater.from(context);
        mComparator = comparator;
    }

    @Override
    public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final ItemExampleBinding binding = ItemExampleBinding.inflate(inflater, parent, false);
        return new ExampleViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(ExampleViewHolder holder, int position) {
        final ExampleModel model = mSortedList.get(position);
        holder.bind(model);
    }

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

The Comparator used to sort the item is passed in through the constructor so we can use the same Adapter even if the items are supposed to be displayed in a different order.

Now we are almost done! But we first need a way to add or remove items to the Adapter. For this purpose we can add methods to the Adapter which allow us to add and remove items to the SortedList:

public void add(ExampleModel model) {
    mSortedList.add(model);
}

public void remove(ExampleModel model) {
    mSortedList.remove(model);
}

public void add(List<ExampleModel> models) {
    mSortedList.addAll(models);
}

public void remove(List<ExampleModel> models) {
    mSortedList.beginBatchedUpdates();
    for (ExampleModel model : models) {
        mSortedList.remove(model);
    }
    mSortedList.endBatchedUpdates();
}

We don't need to call any notify methods here because the SortedList already does this for through the SortedList.Callback! Aside from that the implementation of these methods is pretty straight forward with one exception: the remove method which removes a List of models. Since the SortedList has only one remove method which can remove a single object we need to loop over the list and remove the models one by one. Calling beginBatchedUpdates() at the beginning batches all the changes we are going to make to the SortedList together and improves performance. When we call endBatchedUpdates() the RecyclerView is notified about all the changes at once.

Additionally what you have to understand is that if you add an object to the SortedList and it is already in the SortedList it won't be added again. Instead the SortedList uses the areContentsTheSame() method to figure out if the object has changed - and if it has the item in the RecyclerView will be updated.

Anyway, what I usually prefer is one method which allows me to replace all items in the RecyclerView at once. Remove everything which is not in the List and add all items which are missing from the SortedList:

public void replaceAll(List<ExampleModel> models) {
    mSortedList.beginBatchedUpdates();
    for (int i = mSortedList.size() - 1; i >= 0; i--) {
        final ExampleModel model = mSortedList.get(i);
        if (!models.contains(model)) {
            mSortedList.remove(model);
        }
    }
    mSortedList.addAll(models);
    mSortedList.endBatchedUpdates();
}

This method again batches all updates together to increase performance. The first loop is in reverse since removing an item at the start would mess up the indexes of all items that come up after it and this can lead in some instances to problems like data inconsistencies. After that we just add the List to the SortedList using addAll() to add all items which are not already in the SortedList and - just like I described above - update all items that are already in the SortedList but have changed.

And with that the Adapter is complete. The whole thing should look something like this:

public class ExampleAdapter extends RecyclerView.Adapter<ExampleViewHolder> {

    private final SortedList<ExampleModel> mSortedList = new SortedList<>(ExampleModel.class, new SortedList.Callback<ExampleModel>() {
        @Override
        public int compare(ExampleModel a, ExampleModel b) {
            return mComparator.compare(a, b);
        }

        @Override
        public void onInserted(int position, int count) {
            notifyItemRangeInserted(position, count);
        }

        @Override
        public void onRemoved(int position, int count) {
            notifyItemRangeRemoved(position, count);
        }

        @Override
        public void onMoved(int fromPosition, int toPosition) {
            notifyItemMoved(fromPosition, toPosition);
        }

        @Override
        public void onChanged(int position, int count) {
            notifyItemRangeChanged(position, count);
        }

        @Override
        public boolean areContentsTheSame(ExampleModel oldItem, ExampleModel newItem) {
            return oldItem.equals(newItem);
        }

        @Override
        public boolean areItemsTheSame(ExampleModel item1, ExampleModel item2) {
            return item1 == item2;
        }
    });

    private final Comparator<ExampleModel> mComparator;
    private final LayoutInflater mInflater;

    public ExampleAdapter(Context context, Comparator<ExampleModel> comparator) {
        mInflater = LayoutInflater.from(context);
        mComparator = comparator;
    }

    @Override
    public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final ItemExampleBinding binding = ItemExampleBinding.inflate(mInflater, parent, false);
        return new ExampleViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(ExampleViewHolder holder, int position) {
        final ExampleModel model = mSortedList.get(position);
        holder.bind(model);
    }

    public void add(ExampleModel model) {
        mSortedList.add(model);
    }

    public void remove(ExampleModel model) {
        mSortedList.remove(model);
    }

    public void add(List<ExampleModel> models) {
        mSortedList.addAll(models);
    }

    public void remove(List<ExampleModel> models) {
        mSortedList.beginBatchedUpdates();
        for (ExampleModel model : models) {
            mSortedList.remove(model);
        }
        mSortedList.endBatchedUpdates();
    }

    public void replaceAll(List<ExampleModel> models) {
        mSortedList.beginBatchedUpdates();
        for (int i = mSortedList.size() - 1; i >= 0; i--) {
            final ExampleModel model = mSortedList.get(i);
            if (!models.contains(model)) {
                mSortedList.remove(model);
            }
        }
        mSortedList.addAll(models);
        mSortedList.endBatchedUpdates();
    }

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

The only thing missing now is to implement the filtering!


Implementing the filter logic

To implement the filter logic we first have to define a List of all possible models. For this example I create a List of ExampleModel instances from an array of movies:

private static final String[] MOVIES = new String[]{
        ...
};

private static final Comparator<ExampleModel> ALPHABETICAL_COMPARATOR = new Comparator<ExampleModel>() {
    @Override
    public int compare(ExampleModel a, ExampleModel b) {
        return a.getText().compareTo(b.getText());
    }
};

private ExampleAdapter mAdapter;
private List<ExampleModel> mModels;
private RecyclerView mRecyclerView;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);

    mAdapter = new ExampleAdapter(this, ALPHABETICAL_COMPARATOR);

    mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
    mBinding.recyclerView.setAdapter(mAdapter);

    mModels = new ArrayList<>();
    for (String movie : MOVIES) {
        mModels.add(new ExampleModel(movie));
    }
    mAdapter.add(mModels);
}

Nothing special going on here, we just instantiate the Adapter and set it to the RecyclerView. After that we create a List of models from the movie names in the MOVIES array. Then we add all the models to the SortedList.

Now we can go back to onQueryTextChange() which we defined earlier and start implementing the filter logic:

@Override
public boolean onQueryTextChange(String query) {
    final List<ExampleModel> filteredModelList = filter(mModels, query);
    mAdapter.replaceAll(filteredModelList);
    mBinding.recyclerView.scrollToPosition(0);
    return true;
}

This is again pretty straight forward. We call the method filter() and pass in the List of ExampleModels as well as the query string. We then call replaceAll() on the Adapter and pass in the filtered List returned by filter(). We also have to call scrollToPosition(0) on the RecyclerView to ensure that the user can always see all items when searching for something. Otherwise the RecyclerView might stay in a scrolled down position while filtering and subsequently hide a few items. Scrolling to the top ensures a better user experience while searching.

The only thing left to do now is to implement filter() itself:

private static List<ExampleModel> filter(List<ExampleModel> models, String query) {
    final String lowerCaseQuery = query.toLowerCase();

    final List<ExampleModel> filteredModelList = new ArrayList<>();
    for (ExampleModel model : models) {
        final String text = model.getText().toLowerCase();
        if (text.contains(lowerCaseQuery)) {
            filteredModelList.add(model);
        }
    }
    return filteredModelList;
}

The first thing we do here is call toLowerCase() on the query string. We don't want our search function to be case sensitive and by calling toLowerCase() on all strings we compare we can ensure that we return the same results regardless of case. It then just iterates through all the models in the List we passed into it and checks if the query string is contained in the text of the model. If it is then the model is added to the filtered List.

And that's it! The above code will run on API level 7 and above and starting with API level 11 you get item animations for free!

I realize that this is a very detailed description which probably makes this whole thing seem more complicated than it really is, but there is a way we can generalize this whole problem and make implementing an Adapter based on a SortedList much simpler.


Generalizing the problem and simplifying the Adapter

In this section I am not going to go into much detail - partly because I am running up against the character limit for answers on Stack Overflow but also because most of it already explained above - but to summarize the changes: We can implemented a base Adapter class which already takes care of dealing with the SortedList as well as binding models to ViewHolder instances and provides a convenient way to implement an Adapter based on a SortedList. For that we have to do two things:

  • We need to create a ViewModel interface which all model classes have to implement
  • We need to create a ViewHolder subclass which defines a bind() method the Adapter can use to bind models automatically.

This allows us to just focus on the content which is supposed to be displayed in the RecyclerView by just implementing the models and there corresponding ViewHolder implementations. Using this base class we don't have to worry about the intricate details of the Adapter and its SortedList.

SortedListAdapter

Because of the character limit for answers on StackOverflow I can't go through each step of implementing this base class or even add the full source code here, but you can find the full source code of this base class - I called it SortedListAdapter - in this GitHub Gist.

To make your life simple I have published a library on jCenter which contains the SortedListAdapter! If you want to use it then all you need to do is add this dependency to your app's build.gradle file:

compile 'com.github.wrdlbrnft:sorted-list-adapter:0.2.0.1'

You can find more information about this library on the library homepage.

Using the SortedListAdapter

To use the SortedListAdapter we have to make two changes:

  • Change the ViewHolder so that it extends SortedListAdapter.ViewHolder. The type parameter should be the model which should be bound to this ViewHolder - in this case ExampleModel. You have to bind data to your models in performBind() instead of bind().

    public class ExampleViewHolder extends SortedListAdapter.ViewHolder<ExampleModel> {
    
        private final ItemExampleBinding mBinding;
    
        public ExampleViewHolder(ItemExampleBinding binding) {
            super(binding.getRoot());
            mBinding = binding;
        }
    
        @Override
        protected void performBind(ExampleModel item) {
            mBinding.setModel(item);
        }
    }
    
  • Make sure that all your models implement the ViewModel interface:

    public class ExampleModel implements SortedListAdapter.ViewModel {
        ...
    }
    

After that we just have to update the ExampleAdapter to extend SortedListAdapter and remove everything we don't need anymore. The type parameter should be the type of model you are working with - in this case ExampleModel. But if you are working with different types of models then set the type parameter to ViewModel.

public class ExampleAdapter extends SortedListAdapter<ExampleModel> {

    public ExampleAdapter(Context context, Comparator<ExampleModel> comparator) {
        super(context, ExampleModel.class, comparator);
    }

    @Override
    protected ViewHolder<? extends ExampleModel> onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int viewType) {
        final ItemExampleBinding binding = ItemExampleBinding.inflate(inflater, parent, false);
        return new ExampleViewHolder(binding);
    }

    @Override
    protected boolean areItemsTheSame(ExampleModel item1, ExampleModel item2) {
        return item1.getId() == item2.getId();
    }

    @Override
    protected boolean areItemContentsTheSame(ExampleModel oldItem, ExampleModel newItem) {
        return oldItem.equals(newItem);
    }
}

After that we are done! However one last thing to mention: The SortedListAdapter does not have the same add(), remove() or replaceAll() methods our original ExampleAdapter had. It uses a separate Editor object to modify the items in the list which can be accessed through the edit() method. So if you want to remove or add items you have to call edit() then add and remove the items on this Editor instance and once you are done, call commit() on it to apply the changes to the SortedList:

mAdapter.edit()
        .remove(modelToRemove)
        .add(listOfModelsToAdd)
        .commit();

All changes you make this way are batched together to increase performance. The replaceAll() method we implemented in the chapters above is also present on this Editor object:

mAdapter.edit()
        .replaceAll(mModels)
        .commit();

If you forget to call commit() then none of your changes will be applied!

Manage toolbar's navigation and back button from fragment in android

You can use Toolbar inside the fragment and it is easy to handle. First add Toolbar to layout of the fragment

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:background="?attr/colorPrimaryDark">
</android.support.v7.widget.Toolbar>

Inside the onCreateView Method in the fragment you can handle the toolbar like this.

 Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
 toolbar.setTitle("Title");
 toolbar.setNavigationIcon(R.drawable.ic_arrow_back);

IT will set the toolbar,title and the back arrow navigation to toolbar.You can set any icon to setNavigationIcon method.

If you need to trigger any event when click toolbar navigation icon you can use this.

 toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           //handle any click event
    });

If your activity have navigation drawer you may need to open that when click the navigation back button. you can open that drawer like this.

 toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DrawerLayout drawer = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
            drawer.openDrawer(Gravity.START);
        }
    });

Full code is here

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //inflate the layout to the fragement
    view = inflater.inflate(R.layout.layout_user,container,false);

    //initialize the toolbar
    Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
    toolbar.setTitle("Title");
    toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //open navigation drawer when click navigation back button
            DrawerLayout drawer = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
            drawer.openDrawer(Gravity.START);
        }
    });
    return view;
}

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

My silly mistake was this: change != to ==

if(convertView != null) { // <---- HERE 
                LayoutInflater layoutInflater = LayoutInflater.from(z_selBoardElectricity.this);
                convertView = layoutInflater.inflate(R.layout.listview_board_alert, null);

                TextView textView = convertView.findViewById(R.id.board_name_tv);
                ImageView imageView = convertView.findViewById(R.id.board_imageview);

                textView.setText(text_list.get(position));
                imageView.setImageDrawable(imageAddressList.get(position));

                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.putExtra("MESSAGE", text_list.get(pos));
                        setResult(98, intent);
                        finish();
                    }
                });
            }
return convertView;

How to use SearchView in Toolbar Android

You have to use Appcompat library for that. Which is used like below:

dashboard.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" 
      xmlns:tools="http://schemas.android.com/tools"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always|collapseActionView"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        android:title="Search"/>
</menu>

Activity file (in Java):

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.dashboard, menu);

     MenuItem searchItem = menu.findItem(R.id.action_search);

    SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);

    SearchView searchView = null;
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
    }
        return super.onCreateOptionsMenu(menu);
}

Activity file (in Kotlin):

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    menuInflater.inflate(R.menu.menu_search, menu)

    val searchItem: MenuItem? = menu?.findItem(R.id.action_search)
    val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
    val searchView: SearchView? = searchItem?.actionView as SearchView

    searchView?.setSearchableInfo(searchManager.getSearchableInfo(componentName))
    return super.onCreateOptionsMenu(menu)
}

manifest file:

<meta-data 
      android:name="android.app.default_searchable" 
      android:value="com.apkgetter.SearchResultsActivity" /> 

        <activity
            android:name="com.apkgetter.SearchResultsActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop" >
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
            </intent-filter>

            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>

searchable xml file:

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:hint="@string/search_hint"
    android:label="@string/app_name" />

And at last, your SearchResultsActivity class code. for showing result of your search.

How to add buttons like refresh and search in ToolBar in Android?

OK, I got the icons because I wrote in menu.xml android:showAsAction="ifRoom" instead of app:showAsAction="ifRoom" since i am using v7 library.

However the title is coming at center of extended toolbar. How to make it appear at the top?

Cannot catch toolbar home button click event

If you want to know when home is clicked is an AppCompatActivity then you should try it like this:

First tell Android you want to use your Toolbar as your ActionBar:

setSupportActionBar(toolbar);

Then set Home to be displayed via setDisplayShowHomeEnabled like this:

getSupportActionBar().setDisplayShowHomeEnabled(true);

Finally listen for click events on android.R.id.home like usual:

@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
    if (menuItem.getItemId() == android.R.id.home) {
        Timber.d("Home pressed");
    }
    return super.onOptionsItemSelected(menuItem);
}

If you want to know when the navigation button is clicked on a Toolbar in a class other than AppCompatActivity you can use these methods to set a navigation icon and listen for click events on it. The navigation icon will appear on the left side of your Toolbar where the the "home" button used to be.

toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_nav_back));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.d("cek", "home selected");
    }
});

If you want to know when the hamburger is clicked and when the drawer opens, you're already listening for these events via onDrawerOpened and onDrawerClosed so you'll want to see if those callbacks fit your requirements.

The following classes could not be instantiated: - android.support.v7.widget.Toolbar

I had the same problem for one of the activities in my app , one of the causes of this problem is that Theme in the theme editor might be different than the theme defined in the 'styles.xml'.change the Theme in the theme editor to your 'Apptheme' or your custom defined theme(if you have defined). Doing this fixed my issue.

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

you must use import android.support.v7.app.ActionBarDrawerToggle;

and use the constructor

public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout)
{
    super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
}

and if the drawer toggle button becomes dark then you must use the supportActionBar provided in the support library.

You can implement supportActionbar from this link: http://developer.android.com/training/basics/actionbar/setting-up.html

How to change option menu icon in the action bar?

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
            android:id="@+id/logout"
            android:icon="@drawable/logout"
            android:title="Log Out"
            app:showAsAction="always"
        />
</menu>

This did the trick for me!

How to implement OnFragmentInteractionListener

For those of you who visit this page looking for further clarification on this error, in my case the activity making the call to the fragment needed to have 2 implements in this case, like this:

public class MyActivity extends Activity implements 
    MyFragment.OnFragmentInteractionListener, 
    NavigationDrawerFragment.NaviationDrawerCallbacks {
    ...// rest of the code
}

Hide/Show Action Bar Option Menu Item for different fragments

Hello I got the best solution of this, suppose if u have to hide a particular item at on create Menu method and show that item in other fragment. I am taking an example of two menu item one is edit and other is delete. e.g menu xml is as given below:

sell_menu.xml

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

<item
    android:id="@+id/action_edit"
    android:icon="@drawable/ic_edit_white_shadow_24dp"
    app:showAsAction="always"
    android:title="Edit" />

<item
    android:id="@+id/action_delete"
    android:icon="@drawable/ic_delete_white_shadow_24dp"
    app:showAsAction="always"
    android:title="Delete" />

Now Override the two method in your activity & make a field variable mMenu as:

  private Menu mMenu;         //  field variable    


  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.sell_menu, menu);
    this.mMenu = menu;

    menu.findItem(R.id.action_delete).setVisible(false);
    return super.onCreateOptionsMenu(menu);
  }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_delete) {
       // do action
        return true;
    } else if (item.getItemId() == R.id.action_edit) {
      // do action
        return true;
    }

    return super.onOptionsItemSelected(item);
 }

Make two following method in your Activity & call them from fragment to hide and show your menu item. These method are as:

public void showDeleteImageOption(boolean status) {
    if (menu != null) {
        menu.findItem(R.id.action_delete).setVisible(status);
    }
}

public void showEditImageOption(boolean status) {
    if (menu != null) {
        menu.findItem(R.id.action_edit).setVisible(status);
    }
}

That's Solve from my side,I think this explanation will help you.

Button button = findViewById(R.id.button) always resolves to null in Android Studio

The button code should be moved to the PlaceholderFragment() class. There you will call the layout fragment_main.xml in the onCreateView method. Like so

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);
    Button buttonClick = (Button) view.findViewById(R.id.button);
    buttonClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onButtonClick((Button) view);
        }

    });

    return view;
}

Using Service to run background and create notification

The question is relatively old, but I hope this post still might be relevant for others.

TL;DR: use AlarmManager to schedule a task, use IntentService, see the sample code here;

What this test-application(and instruction) is about:

Simple helloworld app, which sends you notification every 2 hours. Clicking on notification - opens secondary Activity in the app; deleting notification tracks.

When should you use it:

Once you need to run some task on a scheduled basis. My own case: once a day, I want to fetch new content from server, compose a notification based on the content I got and show it to user.

What to do:

  1. First, let's create 2 activities: MainActivity, which starts notification-service and NotificationActivity, which will be started by clicking notification:

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp">
        <Button
            android:id="@+id/sendNotifications"
            android:onClick="onSendNotificationsButtonClick"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Start Sending Notifications Every 2 Hours!" />
    </RelativeLayout>
    

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        public void onSendNotificationsButtonClick(View view) {
            NotificationEventReceiver.setupAlarm(getApplicationContext());
        }   
    }
    

    and NotificationActivity is any random activity you can come up with. NB! Don't forget to add both activities into AndroidManifest.

  2. Then let's create WakefulBroadcastReceiver broadcast receiver, I called NotificationEventReceiver in code above.

    Here, we'll set up AlarmManager to fire PendingIntent every 2 hours (or with any other frequency), and specify the handled actions for this intent in onReceive() method. In our case - wakefully start IntentService, which we'll specify in the later steps. This IntentService would generate notifications for us.

    Also, this receiver would contain some helper-methods like creating PendintIntents, which we'll use later

    NB1! As I'm using WakefulBroadcastReceiver, I need to add extra-permission into my manifest: <uses-permission android:name="android.permission.WAKE_LOCK" />

    NB2! I use it wakeful version of broadcast receiver, as I want to ensure, that the device does not go back to sleep during my IntentService's operation. In the hello-world it's not that important (we have no long-running operation in our service, but imagine, if you have to fetch some relatively huge files from server during this operation). Read more about Device Awake here.

    NotificationEventReceiver.java

    public class NotificationEventReceiver extends WakefulBroadcastReceiver {
    
        private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
        private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
        private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
    
        public static void setupAlarm(Context context) {
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            PendingIntent alarmIntent = getStartPendingIntent(context);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    getTriggerAt(new Date()),
                    NOTIFICATIONS_INTERVAL_IN_HOURS * AlarmManager.INTERVAL_HOUR,
                    alarmIntent);
        }
    
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Intent serviceIntent = null;
            if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
                serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
            } else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
                serviceIntent = NotificationIntentService.createIntentDeleteNotification(context);
            }
    
            if (serviceIntent != null) {
                startWakefulService(context, serviceIntent);
            }
        }
    
        private static long getTriggerAt(Date now) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            //calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
            return calendar.getTimeInMillis();
        }
    
        private static PendingIntent getStartPendingIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    
        public static PendingIntent getDeleteIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_DELETE_NOTIFICATION);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    }
    
  3. Now let's create an IntentService to actually create notifications.

    There, we specify onHandleIntent() which is responses on NotificationEventReceiver's intent we passed in startWakefulService method.

    If it's Delete action - we can log it to our analytics, for example. If it's Start notification intent - then by using NotificationCompat.Builder we're composing new notification and showing it by NotificationManager.notify. While composing notification, we are also setting pending intents for click and remove actions. Fairly Easy.

    NotificationIntentService.java

    public class NotificationIntentService extends IntentService {
    
        private static final int NOTIFICATION_ID = 1;
        private static final String ACTION_START = "ACTION_START";
        private static final String ACTION_DELETE = "ACTION_DELETE";
    
        public NotificationIntentService() {
            super(NotificationIntentService.class.getSimpleName());
        }
    
        public static Intent createIntentStartNotificationService(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_START);
            return intent;
        }
    
        public static Intent createIntentDeleteNotification(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_DELETE);
            return intent;
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d(getClass().getSimpleName(), "onHandleIntent, started handling a notification event");
            try {
                String action = intent.getAction();
                if (ACTION_START.equals(action)) {
                    processStartNotification();
                }
                if (ACTION_DELETE.equals(action)) {
                    processDeleteNotification(intent);
                }
            } finally {
                WakefulBroadcastReceiver.completeWakefulIntent(intent);
            }
        }
    
        private void processDeleteNotification(Intent intent) {
            // Log something?
        }
    
        private void processStartNotification() {
            // Do something. For example, fetch fresh data from backend to create a rich notification?
    
            final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
            builder.setContentTitle("Scheduled Notification")
                    .setAutoCancel(true)
                    .setColor(getResources().getColor(R.color.colorAccent))
                    .setContentText("This notification has been triggered by Notification Service")
                    .setSmallIcon(R.drawable.notification_icon);
    
            PendingIntent pendingIntent = PendingIntent.getActivity(this,
                    NOTIFICATION_ID,
                    new Intent(this, NotificationActivity.class),
                    PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingIntent);
            builder.setDeleteIntent(NotificationEventReceiver.getDeleteIntent(this));
    
            final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(NOTIFICATION_ID, builder.build());
        }
    }
    
  4. Almost done. Now I also add broadcast receiver for BOOT_COMPLETED, TIMEZONE_CHANGED, and TIME_SET events to re-setup my AlarmManager, once device has been rebooted or timezone has changed (For example, user flown from USA to Europe and you don't want notification to pop up in the middle of the night, but was sticky to the local time :-) ).

    NotificationServiceStarterReceiver.java

    public final class NotificationServiceStarterReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            NotificationEventReceiver.setupAlarm(context);
        }
    }
    
  5. We need to also register all our services, broadcast receivers in AndroidManifest:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="klogi.com.notificationbyschedule">
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <service
                android:name=".notifications.NotificationIntentService"
                android:enabled="true"
                android:exported="false" />
    
            <receiver android:name=".broadcast_receivers.NotificationEventReceiver" />
            <receiver android:name=".broadcast_receivers.NotificationServiceStarterReceiver">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                    <action android:name="android.intent.action.TIMEZONE_CHANGED" />
                    <action android:name="android.intent.action.TIME_SET" />
                </intent-filter>
            </receiver>
    
            <activity
                android:name=".NotificationActivity"
                android:label="@string/title_activity_notification"
                android:theme="@style/AppTheme.NoActionBar"/>
        </application>
    
    </manifest>
    

That's it!

The source code for this project you can find here. I hope, you will find this post helpful.

How can I parse a local JSON file from assets folder into a ListView?

If you are using Kotlin in android then you can create Extension function.
Extension Functions are defined outside of any class - yet they reference the class name and can use this. In our case we use applicationContext.
So in Utility class you can define all extension functions.


Utility.kt

fun Context.loadJSONFromAssets(fileName: String): String {
    return applicationContext.assets.open(fileName).bufferedReader().use { reader ->
        reader.readText()
    }
}

MainActivity.kt

You can define private function for load JSON data from assert like this:

 lateinit var facilityModelList: ArrayList<FacilityModel>
 private fun bindJSONDataInFacilityList() {
    facilityModelList = ArrayList<FacilityModel>()
    val facilityJsonArray = JSONArray(loadJSONFromAsserts("NDoH_facility_list.json")) // Extension Function call here
    for (i in 0 until facilityJsonArray.length()){
        val facilityModel = FacilityModel()
        val facilityJSONObject = facilityJsonArray.getJSONObject(i)
        facilityModel.Facility = facilityJSONObject.getString("Facility")
        facilityModel.District = facilityJSONObject.getString("District")
        facilityModel.Province = facilityJSONObject.getString("Province")
        facilityModel.Subdistrict = facilityJSONObject.getString("Facility")
        facilityModel.code = facilityJSONObject.getInt("code")
        facilityModel.gps_latitude = facilityJSONObject.getDouble("gps_latitude")
        facilityModel.gps_longitude = facilityJSONObject.getDouble("gps_longitude")

        facilityModelList.add(facilityModel)
    }
}

You have to pass facilityModelList in your ListView


FacilityModel.kt

class FacilityModel: Serializable {
    var District: String = ""
    var Facility: String = ""
    var Province: String = ""
    var Subdistrict: String = ""
    var code: Int = 0
    var gps_latitude: Double= 0.0
    var gps_longitude: Double= 0.0
}

In my case JSON response start with JSONArray

[
  {
    "code": 875933,
    "Province": "Eastern Cape",
    "District": "Amathole DM",
    "Subdistrict": "Amahlathi LM",
    "Facility": "Amabele Clinic",
    "gps_latitude": -32.6634,
    "gps_longitude": 27.5239
  },

  {
    "code": 455242,
    "Province": "Eastern Cape",
    "District": "Amathole DM",
    "Subdistrict": "Amahlathi LM",
    "Facility": "Burnshill Clinic",
    "gps_latitude": -32.7686,
    "gps_longitude": 27.055
  }
]

How to change MenuItem icon in ActionBar programmatically

Kotlin version:

toolbar.menu.findItem(R.id.notification).icon =
                    ContextCompat.getDrawable(requireContext(), R.drawable.ic_notification)

toolbar.menu.findItem(R.id.notification).isVisible = true

How to change the background color of Action Bar's Option Menu in Android 4.2?

<style name="customTheme" parent="any_parent_theme">
    <item name="android:itemBackground">#424242</item>
    <item name="android:itemTextAppearance">@style/TextAppearance</item>
</style>

<style name="TextAppearance">
    <item name="android:textColor">#E9E2BF</item>
</style>

Add Items to ListView - Android

Try this one it will work

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
     liste = new ArrayList<String>();
     Collections.addAll(liste, values);
     adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, liste);
     setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
     liste.add("Nokia");
     adapter.notifyDataSetChanged();
  }
}

The specified child already has a parent. You must call removeView() on the child's parent first

I encountered this error whenever I omitted a parameter while inflating the view for a fragment in the onCreateView() method like so:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view=inflater.inflate(R.layout.fragment_reject, container);
    return view;
}

The solution is to change the view inflation line to:

View view=inflater.inflate(R.layout.fragment_reject, container,false);

The explanation can be found at the Android guide for fragments

Quoting from the guide, the final parameter in the view initialization statement is false because:

"the system is already inserting the inflated layout into the container—passing true would create a redundant view group in the final layout"

How to add Action bar options menu in Android Fragments

I am late for the answer but I think this is another solution which is not mentioned here so posting.

Step 1: Make a xml of menu which you want to add like I have to add a filter action on my action bar so I have created a xml filter.xml. The main line to notice is android:orderInCategory this will show the action icon at first or last wherever you want to show. One more thing to note down is the value, if the value is less then it will show at first and if value is greater then it will show at last.

filter.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" >


    <item
        android:id="@+id/action_filter"
        android:title="@string/filter"
        android:orderInCategory="10"
        android:icon="@drawable/filter"
        app:showAsAction="ifRoom" />


</menu>

Step 2: In onCreate() method of fragment just put the below line as mentioned, which is responsible for calling back onCreateOptionsMenu(Menu menu, MenuInflater inflater) method just like in an Activity.

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

Step 3: Now add the method onCreateOptionsMenu which will be override as:

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.filter, menu);  // Use filter.xml from step 1
    }

Step 4: Now add onOptionsItemSelected method by which you can implement logic whatever you want to do when you select the added action icon from actionBar:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.action_filter){
            //Do whatever you want to do 
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

Play sound on button click android

  • The audio must be placed in the raw folder, if it doesn't exists, create one.
  • The raw folder must be inside the res folder
  • The name mustn't have any - or special characters in it.

On your activity, you need to have a object MediaPlayer, inside the onCreate method or the onclick method, you have to initialize the MediaPlayer, like MediaPlayer.create(this, R.raw.name_of_your_audio_file), then your audio file ir ready to be played with the call for start(), in your case, since you want it to be placed in a button, you'll have to put it inside the onClick method.

Example:

private Button myButton;
private MediaPlayer mp;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myactivity);
        mp = MediaPlayer.create(this, R.raw.gunshot);

        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.start();
            }
        });
}
}

Slide a layout up from bottom of screen

Use this layout. If you want to animate the main view shrinking you'll need to add animation to the height of the hidden bar, buy it may be good enough to use the translate animation on the bar, and have the main view height jump instead of animate.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<RelativeLayout
    android:id="@+id/main_screen"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="@string/hello_world" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/hello_world" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:onClick="slideUpDown"
        android:text="Slide up / down" />
</RelativeLayout>

<RelativeLayout
    android:id="@+id/hidden_panel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="#fcc"
    android:visibility="visible" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name" />
</RelativeLayout>

</LinearLayout>

getSupportActionBar() The method getSupportActionBar() is undefined for the type TaskActivity. Why?

Your class needs to extend from ActionBarActivity, rather than a plain Activity in order to use the getSupport*() methods.

Update [2015/04/23]: With the release of Android Support Library 22.1, you should now extend AppCompatActivity. Also, you no longer have to extend ActionBarActivity or AppCompatActivity, as you can now incorporate an AppCompatDelegate instance in any activity.

How to get current location in Android

You need to write code in the OnLocationChanged method, because this method is called when the location has changed. I.e. you need to save the new location to return it if getLocation is called.

If you don't use the onLocationChanged it always will be the old location.

Moving from one activity to another Activity in Android

Below code is working fine with Android 4.3:

Intent i = new Intent(this,MainActivity2.class);
startActivity(i);

How to activate "Share" button in android app?

Share Any File as below ( Kotlin ) :
first create a folder named xml in the res folder and create a new XML Resource File named provider_paths.xml and put the below code inside it :

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

    <external-path
        name="external_files"
        path="."/>
</paths>

now go to the manifests folder and open the AndroidManifest.xml and then put the below code inside the <application> tag :

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/provider_paths" /> // provider_paths.xml file path in this example
</provider>

now you put the below code in the setOnLongClickListener :

share_btn.setOnClickListener {
    try {
        val file = File("pathOfFile")
        if(file.exists()) {
            val uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file)
            val intent = Intent(Intent.ACTION_SEND)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setType("*/*")
            intent.putExtra(Intent.EXTRA_STREAM, uri)
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent)
        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
        toast("Error")
    }
}

OnClickListener in Android Studio

you will need to button initilzation inside method instead of trying to initlzing View's at class level do it as:

 Button button;  //<< declare here..

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button= (Button) findViewById(R.id.standingsButton); //<< initialize here
         // set OnClickListener for Button here
        button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this,StandingsActivity.class));
        }
      });
    }

How to get Android GPS location

Excerpt:-

try 
        {
          cnt++;scnt++;now=System.currentTimeMillis();r=rand.nextInt(6);r++;
            loc=lm.getLastKnownLocation(best);
            if(loc!=null){lat=loc.getLatitude();lng=loc.getLongitude();}

            Thread.sleep(100);
            handler.sendMessage(handler.obtainMessage());
         } 
        catch (InterruptedException e) 
        {
            Toast.makeText(this, "Error="+e.toString(), Toast.LENGTH_LONG).show();
        }

As you can see above, a thread is running alongside main thread of user-interface activity which continuously displays GPS lat,long alongwith current time and a random dice throw.

IF you are curious then just check the full code: GPS Location with a randomized dice throw & current time in separate thread

How to pass values between Fragments

I´ve made something really easy for begginers like me. I made a textview in my activity_main.xml and put

id=index
visibility=invisible

then I get this textview from the first fragment

index= (Textview) getActivity().findviewbyid(R.id.index)
index.setText("fill me with the value")

and then in the second fragment I get the value

index= (Textview) getActivity().findviewbyid(R.id.index)
String get_the_value= index.getText().toString();

onCreateOptionsMenu inside Fragments

Set setHasMenuOptions(true) works if application has a theme with Actionbar such as Theme.MaterialComponents.DayNight.DarkActionBar or Activity has it's own Toolbar, otherwise onCreateOptionsMenu in fragment does not get called.

If you want to use standalone Toolbar you either need to get activity and set your Toolbar as support action bar with

(requireActivity() as? MainActivity)?.setSupportActionBar(toolbar)

which lets your fragment onCreateOptionsMenu to be called.

Other alternative is, you can inflate your Toolbar's own menu with toolbar.inflateMenu(R.menu.YOUR_MENU) and item listener with

toolbar.setOnMenuItemClickListener {
   // do something
   true
}

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

You are trying to set int value to TextView so you are getting this issue. To solve this try below one option

option 1:

tv.setText(no+"");

Option2:

tv.setText(String.valueOf(no));

Call fragment from fragment

This is my answer which solved the same problem. Fragment2.java is the fragment class which holds the layout of fragment2.xml.

public void onClick(View v) {
                    Fragment  fragment2 = new Fragement2();
                    FragmentManager fragmentManager = getFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.frame_container, fragment2);
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();   
                }

Android ListView not refreshing after notifyDataSetChanged

adapter.setNotifyDataChanged()

should do the trick.

Android Button click go to another xml page

Change your FirstyActivity to:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn_go=(Button)findViewById(R.id.YOUR_BUTTON_ID);
            btn_go.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                  Log.i("clicks","You Clicked B1");
              Intent i=new Intent(
                     MainActivity.this,
                     MainActivity2.class);
              startActivity(i);
            }
        }
    });

}

Hope it will help you.

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

There is one alternate solution (NOT the best solution) for this problem, but works. Using flag you can handle it, like below

/**
 * Flag to avoid "java.lang.IllegalStateException: Can not perform this action after
 * onSaveInstanceState". Avoid Fragment transaction until onRestoreInstanceState or onResume
 * gets called.
 */
private boolean isOnSaveInstanceStateCalled = false;


@Override
public void onRestoreInstanceState(final Bundle bundle) {
    .....
    isOnSaveInstanceStateCalled = false;
    .....
}

@Override
public void onSaveInstanceState(final Bundle outState) {
    .....
    isOnSaveInstanceStateCalled = true;
    .....
}

@Override
public void onResume() {
    super.onResume();
    isOnSaveInstanceStateCalled = false;
    .....
}

And you can check this boolean value while doing fragment transaction.

private void fragmentReplace(Fragment fragment, String fragmentTag){
    if (!isOnSaveInstanceStateCalled) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.layout_container, fragment, fragmentTag)
                .commit();
    }
}

This app won't run unless you update Google Play Services (via Bazaar)

This app won't run unless you update Google Play Services. I have tried it for such a long much time, but still I didn't get the map... Only a blank screen is appearing, even if I modified my Google Play Service given by the below comment..


Check your play services manifest file and check the version code for the APK file com.google.android.gms. In the below, it is "3136110". Download these APK files and install from a DOS prompt, but before installation run your target emulator.

package="com.google.android.gms"
android:versionCode="3136110"
android:versionName="3.1.36 (673201-10)

I got these APK files from this link.

How to open a second activity on click of button in android app

 <Button
            android:id="@+id/btnSignIn"
            android:layout_width="250dp"
            android:layout_height="40dp"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="16dp"
            android:background="@drawable/circal"
            android:text="Sign in"
            android:textColor="@color/white"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/etPasswordLogin" />

IN JAVA CODE

Button signIn= (Button) findViewById(R.id.btnSignIn);

signIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(SignInPage.this,MainActivity.class));
            }
        });

}

How to get the ActionBar height?

In XML, you should use this attribute:

android:paddingTop="?android:attr/actionBarSize"

How can I return to a parent activity correctly?

Although an old question, here is another (imho the cleanest and best) solution as all the previous answeres didn't work for me since I deeplinked Activity B from a Widget.

public void navigateUp() {
final Intent upIntent = NavUtils.getParentActivityIntent(this);
if (NavUtils.shouldUpRecreateTask(this, upIntent) || isTaskRoot()) {
    Log.v(logTag, "Recreate back stack");
        TaskStackBuilder.create(this).addNextIntentWithParentStack(upIntent).startActivities();
  } else {
    NavUtils.navigateUpTo(this, upIntent);
  }
}

[https://stackoverflow.com/a/31350642/570168 ]

But also see: https://speakerdeck.com/jgilfelt/this-way-up-implementing-effective-navigation-on-android

How do I hide a menu item in the actionbar?

use invalidateOptionsMenu()

in order to call onPrepareOptionsMenu(menu: Menu?)

you should use onCreateOptionsMenu() only to create the initial menu state and not to make changes during the activity lifecycle...

When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().

https://developer.android.com/guide/topics/ui/menus

support FragmentPagerAdapter holds reference to old fragments

I solved the problem by saving the fragments in SparceArray:

public abstract class SaveFragmentsPagerAdapter extends FragmentPagerAdapter {

    SparseArray<Fragment> fragments = new SparseArray<>();

    public SaveFragmentsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        fragments.append(position, fragment);
        return fragment;
    }

    @Nullable
    public Fragment getFragmentByPosition(int position){
        return fragments.get(position);
    }

}

switch case statement error: case expressions must be constant expression

Solution can be done be this way:

  1. Just assign the value to Integer
  2. Make variable to final

Example:

public static final int cameraRequestCode = 999;

Hope this will help you.

How to add Options Menu to Fragment in Android

If you want to add your menu custom

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

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_custom, menu);
}

Handling a Menu Item Click Event - Android

Menu items file looks like

res/menu/menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">
    <item
        android:id="@+id/settings"
        android:title="Setting"
        app:showAsAction="never" />
    <item
        android:id="@+id/my_activity"
        android:title="My Activity"
        app:showAsAction="always"
        android:icon="@android:drawable/btn_radio"/>
</menu>

Java code looks like

src/MainActivity.java

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

      if (id == R.id.my_activity) {
            Intent intent1 = new Intent(this,MyActivity.class);
            this.startActivity(intent1);
            return true;
        }

        if (id == R.id.settings) {
            Toast.makeText(this, "Setting", Toast.LENGTH_LONG).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

And add following code to your AndroidManifest.xml file

<activity
            android:name=".MyActivity"
            android:label="@string/app_name" >
        </activity>

I hope it will help you.

Android, How to create option Menu

Android UI programming is a little bit tricky. To enable the Options menu, in addition to the code you wrote, we also need to call setHasOptionsMenu(true) in your overriden method OnCreate(). Hope this will help you out.

How to style the menu items on an Android action bar

I did this way:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="android:actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="actionMenuTextColor">@color/colorAccent</item>
</style>

<style name="MenuTextAppearance" >
    <item name="android:textAppearance">@android:style/TextAppearance.Large</item>
    <item name="android:textSize">20sp</item>
    <item name="android:textStyle">bold</item>
</style>

How to update a menu item shown in the ActionBar?

To refresh menu from Fragment simply call:

getActivity().invalidateOptionsMenu();

Android: How to enable/disable option menu item on button click?

If visible menu

menu.findItem(R.id.id_name).setVisible(true);

If hide menu

menu.findItem(R.id.id_name).setVisible(false);

Changing Locale within the app itself

Through the original question is not exactly about the locale itself all other locale related questions are referencing to this one. That's why I wanted to clarify the issue here. I used this question as a starting point for my own locale switching code and found out that the method is not exactly correct. It works, but only until any configuration change (e.g. screen rotation) and only in that particular Activity. Playing with a code for a while I have ended up with the following approach:

I have extended android.app.Application and added the following code:

public class MyApplication extends Application
{
    private Locale locale = null;

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        if (locale != null)
        {
            newConfig.locale = locale;
            Locale.setDefault(locale);
            getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
        }
    }

    @Override
    public void onCreate()
    {
        super.onCreate();

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);

        Configuration config = getBaseContext().getResources().getConfiguration();

        String lang = settings.getString(getString(R.string.pref_locale), "");
        if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang))
        {
            locale = new Locale(lang);
            Locale.setDefault(locale);
            config.locale = locale;
            getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
        }
    }
}

This code ensures that every Activity will have custom locale set and it will not be reset on rotation and other events.

I have also spent a lot of time trying to make the preference change to be applied immediately but didn't succeed: the language changed correctly on Activity restart, but number formats and other locale properties were not applied until full application restart.

Changes to AndroidManifest.xml

Don't forget to add android:configChanges="layoutDirection|locale" to every activity at AndroidManifest, as well as the android:name=".MyApplication" to the <application> element.

How do you generate dynamic (parameterized) unit tests in Python?

I have found that this works well for my purposes, especially if I need to generate tests that do slightly difference processes on a collection of data.

import unittest

def rename(newName):
    def renamingFunc(func):
        func.__name__ == newName
        return func
    return renamingFunc

class TestGenerator(unittest.TestCase):

    TEST_DATA = {}

    @classmethod
    def generateTests(cls):
        for dataName, dataValue in TestGenerator.TEST_DATA:
            for func in cls.getTests(dataName, dataValue):
                setattr(cls, "test_{:s}_{:s}".format(func.__name__, dataName), func)

    @classmethod
    def getTests(cls):
        raise(NotImplementedError("This must be implemented"))

class TestCluster(TestGenerator):

    TEST_CASES = []

    @staticmethod
    def getTests(dataName, dataValue):

        def makeTest(case):

            @rename("{:s}".format(case["name"]))
            def test(self):
                # Do things with self, case, data
                pass

            return test

        return [makeTest(c) for c in TestCluster.TEST_CASES]

TestCluster.generateTests()

The TestGenerator class can be used to spawn different sets of test cases like TestCluster.

TestCluster can be thought of as an implementation of the TestGenerator interface.

React Js conditionally applying class attributes

The curly braces are inside the string, so it is being evaluated as string. They need to be outside, so this should work:

<div className={"btn-group pull-right " + (this.props.showBulkActions ? 'show' : 'hidden')}>

Note the space after "pull-right". You don't want to accidentally provide the class "pull-rightshow" instead of "pull-right show". Also the parentheses needs to be there.

Handling exceptions from Java ExecutorService tasks

If you want to monitor the execution of task, you could spin 1 or 2 threads (maybe more depending on the load) and use them to take tasks from an ExecutionCompletionService wrapper.

How should I read a file line-by-line in Python?

There is exactly one reason why the following is preferred:

with open('filename.txt') as fp:
    for line in fp:
        print line

We are all spoiled by CPython's relatively deterministic reference-counting scheme for garbage collection. Other, hypothetical implementations of Python will not necessarily close the file "quickly enough" without the with block if they use some other scheme to reclaim memory.

In such an implementation, you might get a "too many files open" error from the OS if your code opens files faster than the garbage collector calls finalizers on orphaned file handles. The usual workaround is to trigger the GC immediately, but this is a nasty hack and it has to be done by every function that could encounter the error, including those in libraries. What a nightmare.

Or you could just use the with block.

Bonus Question

(Stop reading now if are only interested in the objective aspects of the question.)

Why isn't that included in the iterator protocol for file objects?

This is a subjective question about API design, so I have a subjective answer in two parts.

On a gut level, this feels wrong, because it makes iterator protocol do two separate things—iterate over lines and close the file handle—and it's often a bad idea to make a simple-looking function do two actions. In this case, it feels especially bad because iterators relate in a quasi-functional, value-based way to the contents of a file, but managing file handles is a completely separate task. Squashing both, invisibly, into one action, is surprising to humans who read the code and makes it more difficult to reason about program behavior.

Other languages have essentially come to the same conclusion. Haskell briefly flirted with so-called "lazy IO" which allows you to iterate over a file and have it automatically closed when you get to the end of the stream, but it's almost universally discouraged to use lazy IO in Haskell these days, and Haskell users have mostly moved to more explicit resource management like Conduit which behaves more like the with block in Python.

On a technical level, there are some things you may want to do with a file handle in Python which would not work as well if iteration closed the file handle. For example, suppose I need to iterate over the file twice:

with open('filename.txt') as fp:
    for line in fp:
        ...
    fp.seek(0)
    for line in fp:
        ...

While this is a less common use case, consider the fact that I might have just added the three lines of code at the bottom to an existing code base which originally had the top three lines. If iteration closed the file, I wouldn't be able to do that. So keeping iteration and resource management separate makes it easier to compose chunks of code into a larger, working Python program.

Composability is one of the most important usability features of a language or API.

Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?

Hope this would help:

  1. Connect iPhone to your MAC(I didn't try this with windows)
  2. Click on Apple’s logo on the top left corner > select About This Mac
  3. In Overview tab > System Report
  4. Hardware in the left column > USB >
  5. then on right pane select iPhone
  6. in bottom pane -> "Serial number

-> And that serial number is UDID

"Repository does not have a release file" error

im use this code to and suggest you:

1) sudo sed -i -e 's|disco|eoan|g' /etc/apt/sources.list
2) sudo apt update

Efficient evaluation of a function at every cell of a NumPy array

A similar question is: Mapping a NumPy array in place. If you can find a ufunc for your f(), then you should use the out parameter.

Difference between save and saveAndFlush in Spring data jpa

Depending on the hibernate flush mode that you are using (AUTO is the default) save may or may not write your changes to the DB straight away. When you call saveAndFlush you are enforcing the synchronization of your model state with the DB.

If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between save() and saveAndFlush() because the select triggers a flush first. See the documention.

How can I assign an ID to a view programmatically?

Android id overview

An Android id is an integer commonly used to identify views; this id can be assigned via XML (when possible) and via code (programmatically.) The id is most useful for getting references for XML-defined Views generated by an Inflater (such as by using setContentView.)

Assign id via XML

  • Add an attribute of android:id="@+id/somename" to your view.
  • When your application is built, the android:id will be assigned a unique int for use in code.
  • Reference your android:id's int value in code using "R.id.somename" (effectively a constant.)
  • this int can change from build to build so never copy an id from gen/package.name/R.java, just use "R.id.somename".
  • (Also, an id assigned to a Preference in XML is not used when the Preference generates its View.)

Assign id via code (programmatically)

  • Manually set ids using someView.setId(int);
  • The int must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)
  • For example, if creating and numbering several views representing items, you could use their item number.

Uniqueness of ids

  • XML-assigned ids will be unique.
  • Code-assigned ids do not have to be unique
  • Code-assigned ids can (theoretically) conflict with XML-assigned ids.
  • These conflicting ids won't matter if queried correctly (keep reading).

When (and why) conflicting ids don't matter

  • findViewById(int) will iterate depth-first recursively through the view hierarchy from the View you specify and return the first View it finds with a matching id.
  • As long as there are no code-assigned ids assigned before an XML-defined id in the hierarchy, findViewById(R.id.somename) will always return the XML-defined View so id'd.

Dynamically Creating Views and Assigning IDs

  • In layout XML, define an empty ViewGroup with id.
  • Such as a LinearLayout with android:id="@+id/placeholder".
  • Use code to populate the placeholder ViewGroup with Views.
  • If you need or want, assign any ids that are convenient to each view.
  • Query these child views using placeholder.findViewById(convenientInt);

  • API 17 introduced View.generateViewId() which allows you to generate a unique ID.

If you choose to keep references to your views around, be sure to instantiate them with getApplicationContext() and be sure to set each reference to null in onDestroy. Apparently leaking the Activity (hanging onto it after is is destroyed) is wasteful.. :)

Reserve an XML android:id for use in code

API 17 introduced View.generateViewId() which generates a unique ID. (Thanks to take-chances-make-changes for pointing this out.)*

If your ViewGroup cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:

Here, values/ids.xml defines a custom id:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="reservedNamedId" type="id"/>
</resources>

Then once the ViewGroup or View has been created, you can attach the custom id

myViewGroup.setId(R.id.reservedNamedId);

Conflicting id example

For clarity by way of obfuscating example, lets examine what happens when there is an id conflict behind the scenes.

layout/mylayout.xml

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

To simulate a conflict, lets say our latest build assigned R.id.placeholder(@+id/placeholder) an int value of 12..

Next, MyActivity.java defines some adds views programmatically (via code):

int placeholderId = R.id.placeholder; // placeholderId==12
// returns *placeholder* which has id==12:
ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId);
for (int i=0; i<20; i++){
    TextView tv = new TextView(this.getApplicationContext());
    // One new TextView will also be assigned an id==12:
    tv.setId(i);
    placeholder.addView(tv);
}

So placeholder and one of our new TextViews both have an id of 12! But this isn't really a problem if we query placeholder's child views:

// Will return a generated TextView:
 placeholder.findViewById(12);

// Whereas this will return the ViewGroup *placeholder*;
// as long as its R.id remains 12: 
Activity.this.findViewById(12);

*Not so bad

How to quickly check if folder is empty (.NET)?

You will have to go the hard drive for this information in any case, and this alone will trump any object creation and array filling.

What is the largest possible heap size with a 64-bit JVM?

If you want to use 32-bit references, your heap is limited to 32 GB.

However, if you are willing to use 64-bit references, the size is likely to be limited by your OS, just as it is with 32-bit JVM. e.g. on Windows 32-bit this is 1.2 to 1.5 GB.

Note: you will want your JVM heap to fit into main memory, ideally inside one NUMA region. That's about 1 TB on the bigger machines. If your JVM spans NUMA regions the memory access and the GC in particular will take much longer. If your JVM heap start swapping it might take hours to GC, or even make your machine unusable as it thrashes the swap drive.

Note: You can access large direct memory and memory mapped sizes even if you use 32-bit references in your heap. i.e. use well above 32 GB.

Compressed oops in the Hotspot JVM

Compressed oops represent managed pointers (in many but not all places in the JVM) as 32-bit values which must be scaled by a factor of 8 and added to a 64-bit base address to find the object they refer to. This allows applications to address up to four billion objects (not bytes), or a heap size of up to about 32Gb. At the same time, data structure compactness is competitive with ILP32 mode.

Detecting IE11 using CSS Capability/Feature Detection

This seems to work:

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  
}

https://www.limecanvas.com/css-hacks-for-targeting-ie-10-and-above/

Force add despite the .gitignore file

Another way of achieving it would be to temporary edit the gitignore file, add the file and then revert back the gitignore. A bit hacky i feel

Using bootstrap with bower

You have install nodeJs on your system in order to execute npm commands. Once npm is properly working you can visit bower.io. There you will find complete documentation on this topic. You will find a command $ npm install bower. this will install bower on your machine. After installing bower you can install Bootstrap easily.

Here is a video tutorial on that

How do I join two lists in Java?

Slightly simpler:

List<String> newList = new ArrayList<String>(listOne);
newList.addAll(listTwo);

Check if a number has a decimal place/is a whole number

Here's an excerpt from my guard library (inspired by Effective JavaScript by David Herman):

var guard = {

    guard: function(x) {
        if (!this.test(x)) {
            throw new TypeError("expected " + this);
        }
    }

    // ...
};

// ...

var number = Object.create(guard);
number.test = function(x) {
    return typeof x === "number" || x instanceof Number;
};
number.toString = function() {
    return "number";
};


var uint32 = Object.create(guard);
uint32.test = function(x) {
    return typeof x === "number" && x === (x >>> 0);
};
uint32.toString = function() {
    return "uint32";
};


var decimal = Object.create(guard);
decimal.test = function(x) {
    return number.test(x) && !uint32.test(x);
};
decimal.toString = function() {
    return "decimal";
};


uint32.guard(1234);     // fine
uint32.guard(123.4);    // TypeError: expected uint32

decimal.guard(1234);    // TypeError: expected decimal
decimal.guard(123.4);   // fine

Is there a way to perform "if" in python's lambda

This snippet should help you:

x = lambda age: 'Older' if age > 30 else 'Younger'

print(x(40))

PHP array printing using a loop

Additionally, if you are debugging as Tom mentioned, you can use var_dump to see the array.

Explicitly select items from a list or tuple

I just want to point out, even syntax of itemgetter looks really neat, but it's kinda slow when perform on large list.

import timeit
from operator import itemgetter
start=timeit.default_timer()
for i in range(1000000):
    itemgetter(0,2,3)(myList)
print ("Itemgetter took ", (timeit.default_timer()-start))

Itemgetter took 1.065209062149279

start=timeit.default_timer()
for i in range(1000000):
    myList[0],myList[2],myList[3]
print ("Multiple slice took ", (timeit.default_timer()-start))

Multiple slice took 0.6225321444745759

Eloquent: find() and where() usage laravel

Your code looks fine, but there are a couple of things to be aware of:

Post::find($id); acts upon the primary key, if you have set your primary key in your model to something other than id by doing:

protected  $primaryKey = 'slug';

then find will search by that key instead.

Laravel also expects the id to be an integer, if you are using something other than an integer (such as a string) you need to set the incrementing property on your model to false:

public $incrementing = false;

How to remove an item from an array in Vue.js

Splice is the best to remove element from specific index. The given example is tested on console.

card = [1, 2, 3, 4];
card.splice(1,1);  // [2]
card   // (3) [1, 3, 4]
splice(startingIndex, totalNumberOfElements)

startingIndex start from 0.

var self = this?

Just adding to this that in ES6 because of arrow functions you shouldn't need to do this because they capture the this value.

Android - Spacing between CheckBox and text

Why not just extend the Android CheckBox to have better padding instead. That way instead of having to fix it in code every time you use the CheckBox you can just use the fixed CheckBox instead.

First Extend CheckBox:

package com.whatever;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.CheckBox;

/**
 * This extends the Android CheckBox to add some more padding so the text is not on top of the
 * CheckBox.
 */
public class CheckBoxWithPaddingFix extends CheckBox {

    public CheckBoxWithPaddingFix(Context context) {
        super(context);
    }

    public CheckBoxWithPaddingFix(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public CheckBoxWithPaddingFix(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public int getCompoundPaddingLeft() {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (super.getCompoundPaddingLeft() + (int) (10.0f * scale + 0.5f));
    }
}

Second in your xml instead of creating a normal CheckBox create your extended one

<com.whatever.CheckBoxWithPaddingFix
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello there" />

VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds

When the workbook first opens, execute this code:

alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"

Then just have a macro in the workbook called "EventMacro" that will repeat it.

Public Sub EventMacro()
    '... Execute your actions here'
    alertTime = Now + TimeValue("00:02:00")
    Application.OnTime alertTime, "EventMacro"
End Sub

No input file specified

In my case, there were an error in the php.ini open_basedir variable.

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

Finally I made it work thanks to the steps outlined in the Eclipse forum:

Set up the SSH key stuff

  1. Download and install mysys git according to the github instructions at http://help.github.com/win-git-installation/
  2. In C:/Users/you/ssh hide any existing keys (id_rsa and id_rsa.pub) in a subdirectory. If the ssh directory does not exist, create it. Of course, "you" is your username as the OS knows you.
  3. From the start menu, run Git-Bash command shell (a regular DOS command shell will not work).
  4. In the Git-Bash shell generate an rsa key based on your email (the one you registered at github): ssh-keygen -t rsa -C "[email protected]" and enter your pass phrase and confirm when asked.
  5. The previous step should have created C:/User/you/ssh/id_rsa.pub which you can now open in a text editor and copy. At github, go to account settings, SSH Keys, add a key and paste this in the key box.
  6. In Git-Bash again (notice the back-ticks in the next line): eval `ssh-agent` ssh-add C:/User/you/ssh/id_rsa ssh [email protected]

Here is what you just did: You ran the ssh-agent which is needed by ssh-add. Then you used ssh-add to make note of the location of your key. Then you tried to ssh to GitHub. The response to this last command should be that you have successfully authenticated at GitHub but that you don't have shell access. This is just an authentication test. If the authentication was not successful, you'll have to sort that out. Try the verbose version:

ssh -v [email protected]

Assuming this worked....

In Eclipse, configure the remote push

  1. Window > Show View > Git > Git Repositories will add a repository explorer window.
  2. In the repository window, select the repository and expand and right-click Remotes and choose Create Remote.
  3. Copy the GitHub repository URI from the GitHub repository page and paste it in the URI box.
  4. Select ssh as the protocol but then go back to the URI box and add "git+" at the beginning so it looks like this:

    git+ssh://[email protected]/UserName/ProjectName.git

  5. In the Repository Path box, remove the leading slash

  6. Hit Next and cross your fingers. If your get "auth fail", restart Eclipse and try step 5 again.
  7. When you get past the authentication, in the next dialog select "master" for source ref, click "Add all branches spec" and "Finish".

Instead of using SSH [email protected] I did it with SSH [email protected].

Now I can push and import without any problem.

If my interface must return Task what is the best way to have a no-operation implementation?

Recently encountered this and kept getting warnings/errors about the method being void.

We're in the business of placating the compiler and this clears it up:

    public async Task MyVoidAsyncMethod()
    {
        await Task.CompletedTask;
    }

This brings together the best of all the advice here so far. No return statement is necessary unless you're actually doing something in the method.

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

Round up value to nearest whole number in SQL UPDATE

For MS SQL CEILING(your number) will round it up. FLOOR(your number) will round it down

How do operator.itemgetter() and sort() work?

#sorting first by age then profession,you can change it in function "fun".
a = []

def fun(v):
    return (v[1],v[2])

# create the table (name, age, job)
a.append(["Nick", 30, "Doctor"])
a.append(["John",  8, "Student"])
a.append(["Paul",  8,"Car Dealer"])
a.append(["Mark", 66, "Retired"])

a.sort(key=fun)


print a

How to Convert the value in DataTable into a string array in c#

If you would like to use System.Data instead of System.LINQ, then you can do something like this.

 List<string> BrandsInDataTable = new List<string>();
 DataTable g = Access._ME_G_BrandsInPop(); 
        if (g.Rows.Count > 0)
        {
            for (int x = 0; x < g.Rows.Count; x++)
                BrandsInDataTable.Add(g.Rows[x]["Name"].ToString()); 
        }
        else return;

Connect Java to a MySQL database

Connection I was using some time ago, it was looking like the easiest way, but also there were recommendation to make there if statement- exactly

Connection con = DriverManager.getConnection(
                     "jdbc:myDriver:DatabaseName",
                     dBuserName,
                     dBuserPassword);
if (con != null){
 //..handle your code there 
}

Or something like in that way :)

Probably there's some case, while getConnection can return null :)

How to read user input into a variable in Bash?

Also you can try zenity !

user=$(zenity --entry --text 'Please enter the username:') || exit 1

Connect to external server by using phpMyAdmin

using PhpMyAdmin version 4.5.4.1deb2ubuntu2, you can set the variables in /etc/phpmyadmin/config-db.php

so set $dbserver to your server name, e.g. $dbserver='mysql.example.com';

<?php
##
## database access settings in php format
## automatically generated from /etc/dbconfig-common/phpmyadmin.conf
## by /usr/sbin/dbconfig-generate-include
##
## by default this file is managed via ucf, so you shouldn't have to
## worry about manual changes being silently discarded.  *however*,
## you'll probably also want to edit the configuration file mentioned
## above too.
##
$dbuser='phpmyadmin';
$dbpass='P@55w0rd';
$basepath='';
$dbname='phpmyadmin';
$dbserver='localhost';
$dbport='';
$dbtype='mysql';

Android 6.0 Marshmallow. Cannot write to SD Card

Maybe you cannot use manifest class from generated code in your project. So, you can use manifest class from android sdk "android.Manifest.permission.WRITE_EXTERNAL_STORAGE". But in Marsmallow version have 2 permission must grant are WRITE and READ EXTERNAL STORAGE in storage category. See my program, my program will request permission until user choose yes and do something after permissions is granted.

            if (Build.VERSION.SDK_INT >= 23) {
                if (ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(LoginActivity.this,
                            new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE},
                            1);
                } else {
                    //do something
                }
            } else {
                    //do something
            }

When to use @QueryParam vs @PathParam

REST may not be a standard as such, but reading up on general REST documentation and blog posts should give you some guidelines for a good way to structure API URLs. Most rest APIs tend to only have resource names and resource IDs in the path. Such as:

/departments/{dept}/employees/{id}

Some REST APIs use query strings for filtering, pagination and sorting, but Since REST isn't a strict standard I'd recommend checking some REST APIs out there such as github and stackoverflow and see what could work well for your use case.

I'd recommend putting any required parameters in the path, and any optional parameters should certainly be query string parameters. Putting optional parameters in the path will end up getting really messy when trying to write URL handlers that match different combinations.

Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

This should do the trick!

// convert object => json
$json = json_encode($myObject);

// convert json => object
$obj = json_decode($json);

Here's an example

$foo = new StdClass();
$foo->hello = "world";
$foo->bar = "baz";

$json = json_encode($foo);
echo $json;
//=> {"hello":"world","bar":"baz"}

print_r(json_decode($json));
// stdClass Object
// (
//   [hello] => world
//   [bar] => baz
// )

If you want the output as an Array instead of an Object, pass true to json_decode

print_r(json_decode($json, true));
// Array
// (
//   [hello] => world
//   [bar] => baz
// )    

More about json_encode()

See also: json_decode()

Use 'class' or 'typename' for template parameters?

It doesn't matter at all, but class makes it look like T can only be a class, while it can of course be any type. So typename is more accurate. On the other hand, most people use class, so that is probably easier to read generally.

With block equivalent in C#?

This is what Visual C# program manager has to say: Why doesn't C# have a 'with' statement?

Many people, including the C# language designers, believe that 'with' often harms readability, and is more of a curse than a blessing. It is clearer to declare a local variable with a meaningful name, and use that variable to perform multiple operations on a single object, than it is to have a block with a sort of implicit context.

checked = "checked" vs checked = true

checked attribute is a boolean value so "checked" value of other "string" except boolean false converts to true.

Any string value will be true. Also presence of attribute make it true:

<input type="checkbox" checked>

You can make it uncheked only making boolean change in DOM using JS.

So the answer is: they are equal.

w3c

what is Promotional and Feature graphic in Android Market/Play Store?

I know there were several perfect answers but I found this page useful as well !

from: https://support.google.com/googleplay/android-developer/answer/113469?hl=en

Quote from the site:

The Feature Graphic is used for promotions on Google Play. While this graphic is not required to save and publish your Store Listing, it is required in order to be featured on Google Play.

Commentary:

To be clear, these "promotions" are chosen at Google's discretion. Even though excellent the "This is a test" app demonstration (above) shows the Feature graphic used in common areas of the outdated "Android Market", this is no longer the case with today's "Play Store".

Quote from the site:

The Promo Graphic is used for promotions on older versions of the Android OS (earlier than 4.0). This image is not required to save and publish your Store Listing.

Commentary:

It appears that this is also at Google's discretion and not always used as the "This is a test" demo suggests. Even though an older device may not get an update to their Android version, the "Android Market" update bringing them to a modern version of "Play Store" should be available.

How do you round a float to 2 decimal places in JRuby?

sprintf('%.2f', number) is a cryptic, but very powerful way of formatting numbers. The result is always a string, but since you're rounding I assume you're doing it for presentation purposes anyway. sprintf can format any number almost any way you like, and lots more.

Full sprintf documentation: http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf

How to increase font size in NeatBeans IDE?

At Windows in the file C:\Program Files\NetBeans x.x\etc\netbeans.conf

Add "--fontsize [size]" at the end of line netbeans_default_options:

netbeans_default_options=".... --fontsize 16"

Formula to convert date to number

If you change the format of the cells to General then this will show the date value of a cell as behind the scenes Excel saves a date as the number of days since 01/01/1900

Screenprint 1

Screenprint 2

If your date is text and you need to convert it then DATEVALUE will do this:

Datevalue function

How to convert String object to Boolean Object?

Boolean b = Boolean.valueOf(string);

The value of b is true if the string is not a null and equal to true (ignoring case).

While variable is not defined - wait

Object.defineProperty(window, 'propertyName', {
    set: value => {
        this._value = value;
        // someAction();
    },
    get: () => this._value
});

or even if you just want this property to be passed as an argument to a function and don't need it to be defined on a global object:

Object.defineProperty(window, 'propertyName', { set: value => someAction(value) })

However, since in your example you seem to want to perform an action upon creation of a node, I would suggest you take a look at MutationObservers.

Why doesn't the height of a container element increase if it contains floated elements?

You need to add overflow:auto to your parent div for it to encompass the inner floated div:

<div style="margin:0 auto;width: 960px; min-height: 100px; background-color:orange;overflow:auto">
    <div style="width:500px; height:200px; background-color:black; float:right">
    </div>
</div>

jsFiddle example

Difference between git pull and git pull --rebase

Suppose you have two commits in local branch:

      D---E master
     /
A---B---C---F origin/master

After "git pull", will be:

      D--------E  
     /          \
A---B---C---F----G   master, origin/master

After "git pull --rebase", there will be no merge point G. Note that D and E become different commits:

A---B---C---F---D'---E'   master, origin/master

Get class list for element with jQuery

var classList = $(element).attr('class').split(/\s+/);
$(classList).each(function(index){

     //do something

});

Encode URL in JavaScript?

To prevent double encoding it's a good idea to decode the url before encoding (if you are dealing with user entered urls for example, which might be already encoded).

Lets say we have abc%20xyz 123 as input (one space is already encoded):

encodeURI("abc%20xyz 123")            //   wrong: "abc%2520xyz%20123"
encodeURI(decodeURI("abc%20xyz 123")) // correct: "abc%20xyz%20123"

How to do an update + join in PostgreSQL?

First Table Name: tbl_table1 (tab1). Second Table Name: tbl_table2 (tab2).

Set the tbl_table1's ac_status column to "INACTIVE"

update common.tbl_table1 as tab1
set ac_status= 'INACTIVE' --tbl_table1's "ac_status"
from common.tbl_table2 as tab2
where tab1.ref_id= '1111111' 
and tab2.rel_type= 'CUSTOMER';

How to convert QString to int?

You don't have all digit characters in your string. So you have to split by space

QString Abcd = "123.5 Kb";
Abcd.split(" ")[0].toInt();    //convert the first part to Int
Abcd.split(" ")[0].toDouble(); //convert the first part to double
Abcd.split(" ")[0].toFloat();  //convert the first part to float

Update: I am updating an old answer. That was a straight forward answer to the specific question, with a strict assumption. However as noted by @DomTomCat in comments and @Mikhail in answer, In general one should always check whether the operation is successful or not. So using a boolean flag is necessary.

bool flag;
double v = Abcd.split(" ")[0].toDouble(&flag); 
if(flag){
  // use v
}

Also if you are taking that string as user input, then you should also be doubtful about whether the string is really splitable with space. If there is a possibility that the assumption may break then a regex verifier is more preferable. A regex like the following will extract the floating point value and the prefix character of 'b'. Then you can safely convert the captured strings to double.

([0-9]*\.?[0-9]+)\s+(\w[bB])

You can have an utility function like the following

QPair<double, QString> split_size_str(const QString& str){
    QRegExp regex("([0-9]*\\.?[0-9]+)\\s+(\\w[bB])");
    int pos = regex.indexIn(str);
    QStringList captures = regex.capturedTexts();
    if(captures.count() > 1){
        double value = captures[1].toDouble(); // should succeed as regex matched
        QString unit = captures[2]; // should succeed as regex matched
        return qMakePair(value, unit);
    }
    return qMakePair(0.0f, QString());
}

Unit testing with Spring Security

Using a static in this case is the best way to write secure code.

Yes, statics are generally bad - generally, but in this case, the static is what you want. Since the security context associates a Principal with the currently running thread, the most secure code would access the static from the thread as directly as possible. Hiding the access behind a wrapper class that is injected provides an attacker with more points to attack. They wouldn't need access to the code (which they would have a hard time changing if the jar was signed), they just need a way to override the configuration, which can be done at runtime or slipping some XML onto the classpath. Even using annotation injection would be overridable with external XML. Such XML could inject the running system with a rogue principal.

Load arrayList data into JTable

You can do something like what i did with my List< Future< String > > or any other Arraylist, Type returned from other class called PingScan that returns List> because it implements service executor. Anyway the code down note that you can use foreach and retrieve data from the List.

 PingScan p = new PingScan();
 List<Future<String>> scanResult = p.checkThisIP(jFormattedTextField1.getText(), jFormattedTextField2.getText());
                for (final Future<String> f : scanResult) {
                    try {
                        if (f.get() instanceof String) {
                            String ip = f.get();
                            Object[] data = {ip};
                            tableModel.addRow(data);
                        }
                    } catch (InterruptedException | ExecutionException ex) {
                        Logger.getLogger(gui.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

Forbidden: You don't have permission to access / on this server, WAMP Error

This could be one solution.

public class RegisterActivity extends AppCompatActivity {

    private static final String TAG = "RegisterActivity";
    private static final String URL_FOR_REGISTRATION = "http://192.168.10.4/android_login_example/register.php";
    ProgressDialog progressDialog;

    private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputAge;
    private Button btnSignUp;
    private Button btnLinkLogin;
    private RadioGroup genderRadioGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        // Progress dialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);

        signupInputName = (EditText) findViewById(R.id.signup_input_name);
        signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
        signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
        signupInputAge = (EditText) findViewById(R.id.signup_input_age);

        btnSignUp = (Button) findViewById(R.id.btn_signup);
        btnLinkLogin = (Button) findViewById(R.id.btn_link_login);

        genderRadioGroup = (RadioGroup) findViewById(R.id.gender_radio_group);
        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitForm();
            }
        });
        btnLinkLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent i = new Intent(getApplicationContext(),MainActivity.class);
                startActivity(i);
            }
        });
    }

    private void submitForm() {

        int selectedId = genderRadioGroup.getCheckedRadioButtonId();
        String gender;
        if(selectedId == R.id.female_radio_btn)
            gender = "Female";
        else
            gender = "Male";

        registerUser(signupInputName.getText().toString(),
                signupInputEmail.getText().toString(),
                signupInputPassword.getText().toString(),
                gender,
                signupInputAge.getText().toString());
    }

    private void registerUser(final String name,  final String email, final String password,
                              final String gender, final String dob) {
        // Tag used to cancel the request
        String cancel_req_tag = "register";

        progressDialog.setMessage("Adding you ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                URL_FOR_REGISTRATION, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    if (!error) {
                        String user = jObj.getJSONObject("user").getString("name");
                        Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();

                        // Launch login activity
                        Intent intent = new Intent(
                                RegisterActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {



                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", name);
                params.put("email", email);
                params.put("password", password);
                params.put("gender", gender);
                params.put("age", dob);
                return params;
            }
        };
        // Adding request to request queue
        AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
    }

    private void showDialog() {
        if (!progressDialog.isShowing())
            progressDialog.show();
    }

    private void hideDialog() {
        if (progressDialog.isShowing())
            progressDialog.dismiss();
    }
    }

getSupportActionBar() The method getSupportActionBar() is undefined for the type TaskActivity. Why?

Can you set the ActionBar before you set the Contient View? This order would be better:

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

    ActionBar actionBar =getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);            
  }

Detect Android phone via Javascript / jQuery

js version, catches iPad too:

var is_mobile = /mobile|android/i.test (navigator.userAgent);

Regex for string contains?

Just don't anchor your pattern:

/Test/

The above regex will check for the literal string "Test" being found somewhere within it.

Convert RGB to Black & White in OpenCV

I do something similar in one of my blog postings. A simple C++ example is shown.

The aim was to use the open source cvBlobsLib library for the detection of spot samples printed to microarray slides, but the images have to be converted from colour -> grayscale -> black + white as you mentioned, in order to achieve this.

How to pretty print XML from Java?

Just another solution which works for us

import java.io.StringWriter;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

**
 * Pretty Print XML String
 * 
 * @param inputXmlString
 * @return
 */
public static String prettyPrintXml(String xml) {

    final StringWriter sw;

    try {
        final OutputFormat format = OutputFormat.createPrettyPrint();
        final org.dom4j.Document document = DocumentHelper.parseText(xml);
        sw = new StringWriter();
        final XMLWriter writer = new XMLWriter(sw, format);
        writer.write(document);
    }
    catch (Exception e) {
        throw new RuntimeException("Error pretty printing xml:\n" + xml, e);
    }
    return sw.toString();
}

What are Runtime.getRuntime().totalMemory() and freeMemory()?

Codified version of all other answers (at the time of writing):

import java.io.*;

/**
 * This class is based on <a href="http://stackoverflow.com/users/2478930/cheneym">cheneym</a>'s
 * <a href="http://stackoverflow.com/a/18375641/253468">awesome interpretation</a>
 * of the Java {@link Runtime}'s memory query methods, which reflects intuitive thinking.
 * Also includes comments and observations from others on the same question, and my own experience.
 * <p>
 * <img src="https://i.stack.imgur.com/GjuwM.png" alt="Runtime's memory interpretation">
 * <p>
 * <b>JVM memory management crash course</b>:
 * Java virtual machine process' heap size is bounded by the maximum memory allowed.
 * The startup and maximum size can be configured by JVM arguments.
 * JVMs don't allocate the maximum memory on startup as the program running may never require that.
 * This is to be a good player and not waste system resources unnecessarily.
 * Instead they allocate some memory and then grow when new allocations require it.
 * The garbage collector will be run at times to clean up unused objects to prevent this growing.
 * Many parameters of this management such as when to grow/shrink or which GC to use
 * can be tuned via advanced configuration parameters on JVM startup.
 *
 * @see <a href="http://stackoverflow.com/a/42567450/253468">
 *     What are Runtime.getRuntime().totalMemory() and freeMemory()?</a>
 * @see <a href="http://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf">
 *     Memory Management in the Sun Java HotSpot™ Virtual Machine</a>
 * @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html">
 *     Full VM options reference for Windows</a>
 * @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html">
 *     Full VM options reference for Linux, Mac OS X and Solaris</a>
 * @see <a href="http://www.oracle.com/technetwork/articles/java/vmoptions-jsp-140102.html">
 *     Java HotSpot VM Options quick reference</a>
 */
public class SystemMemory {

    // can be white-box mocked for testing
    private final Runtime runtime = Runtime.getRuntime();

    /**
     * <b>Total allocated memory</b>: space currently reserved for the JVM heap within the process.
     * <p>
     * <i>Caution</i>: this is not the total memory, the JVM may grow the heap for new allocations.
     */
    public long getAllocatedTotal() {
        return runtime.totalMemory();
    }

    /**
     * <b>Current allocated free memory</b>: space immediately ready for new objects.
     * <p>
     * <i>Caution</i>: this is not the total free available memory,
     * the JVM may grow the heap for new allocations.
     */
    public long getAllocatedFree() {
        return runtime.freeMemory();
    }

    /**
     * <b>Used memory</b>:
     * Java heap currently used by instantiated objects. 
     * <p>
     * <i>Caution</i>: May include no longer referenced objects, soft references, etc.
     * that will be swept away by the next garbage collection.
     */
    public long getUsed() {
        return getAllocatedTotal() - getAllocatedFree();
    }

    /**
     * <b>Maximum allocation</b>: the process' allocated memory will not grow any further.
     * <p>
     * <i>Caution</i>: This may change over time, do not cache it!
     * There are some JVMs / garbage collectors that can shrink the allocated process memory.
     * <p>
     * <i>Caution</i>: If this is true, the JVM will likely run GC more often.
     */
    public boolean isAtMaximumAllocation() {
        return getAllocatedTotal() == getTotal();
        // = return getUnallocated() == 0;
    }

    /**
     * <b>Unallocated memory</b>: amount of space the process' heap can grow.
     */
    public long getUnallocated() {
        return getTotal() - getAllocatedTotal();
    }

    /**
     * <b>Total designated memory</b>: this will equal the configured {@code -Xmx} value.
     * <p>
     * <i>Caution</i>: You can never allocate more memory than this, unless you use native code.
     */
    public long getTotal() {
        return runtime.maxMemory();
    }

    /**
     * <b>Total free memory</b>: memory available for new Objects,
     * even at the cost of growing the allocated memory of the process.
     */
    public long getFree() {
        return getTotal() - getUsed();
        // = return getAllocatedFree() + getUnallocated();
    }

    /**
     * <b>Unbounded memory</b>: there is no inherent limit on free memory.
     */
    public boolean isBounded() {
        return getTotal() != Long.MAX_VALUE;
    }

    /**
     * Dump of the current state for debugging or understanding the memory divisions.
     * <p>
     * <i>Caution</i>: Numbers may not match up exactly as state may change during the call.
     */
    public String getCurrentStats() {
        StringWriter backing = new StringWriter();
        PrintWriter out = new PrintWriter(backing, false);
        out.printf("Total: allocated %,d (%.1f%%) out of possible %,d; %s, %s %,d%n",
                getAllocatedTotal(),
                (float)getAllocatedTotal() / (float)getTotal() * 100,
                getTotal(),
                isBounded()? "bounded" : "unbounded",
                isAtMaximumAllocation()? "maxed out" : "can grow",
                getUnallocated()
        );
        out.printf("Used: %,d; %.1f%% of total (%,d); %.1f%% of allocated (%,d)%n",
                getUsed(),
                (float)getUsed() / (float)getTotal() * 100,
                getTotal(),
                (float)getUsed() / (float)getAllocatedTotal() * 100,
                getAllocatedTotal()
        );
        out.printf("Free: %,d (%.1f%%) out of %,d total; %,d (%.1f%%) out of %,d allocated%n",
                getFree(),
                (float)getFree() / (float)getTotal() * 100,
                getTotal(),
                getAllocatedFree(),
                (float)getAllocatedFree() / (float)getAllocatedTotal() * 100,
                getAllocatedTotal()
        );
        out.flush();
        return backing.toString();
    }

    public static void main(String... args) {
        SystemMemory memory = new SystemMemory();
        System.out.println(memory.getCurrentStats());
    }
}

How to programmatically set drawableLeft on Android button?

as @Jérémy Reynaud pointing out, as described in this answer, the safest way to set the left drawable without changing the values of the other drawables (top, right, and bottom) is by using the previous values from the button with setCompoundDrawablesWithIntrinsicBounds:

Drawable leftDrawable = getContext().getResources()
                          .getDrawable(R.drawable.yourdrawable);

// Or use ContextCompat
// Drawable leftDrawable = ContextCompat.getDrawable(getContext(),
//                                        R.drawable.yourdrawable);

Drawable[] drawables = button.getCompoundDrawables();
button.setCompoundDrawablesWithIntrinsicBounds(leftDrawable,drawables[1],
                                               drawables[2], drawables[3]);

So all your previous drawable will be preserved.

Check if list<t> contains any of another list

Here is a sample to find if there are match elements in another list

List<int> nums1 = new List<int> { 2, 4, 6, 8, 10 };
List<int> nums2 = new List<int> { 1, 3, 6, 9, 12};

if (nums1.Any(x => nums2.Any(y => y == x)))
{
    Console.WriteLine("There are equal elements");
}
else
{
    Console.WriteLine("No Match Found!");
}

How to trigger the onclick event of a marker on a Google Maps V3?

For future Googlers, If you get an error similar below after you trigger click for a polygon

"Uncaught TypeError: Cannot read property 'vertex' of undefined"

then try the code below

google.maps.event.trigger(polygon, "click", {});

How to make a website secured with https

I think you are getting confused with your site Authentication and SSL.

If you need to get your site into SSL, then you would need to install a SSL certificate into your web server. You can buy a certificate for yourself from one of the places like Symantec etc. The certificate would contain your public/private key pair, along with other things.

You wont need to do anything in your source code, and you can still continue to use your Form Authntication (or any other) in your site. Its just that, any data communication that takes place between the web server and the client will encrypted and signed using your certificate. People would use secure-HTTP (https://) to access your site.

View this for more info --> http://en.wikipedia.org/wiki/Transport_Layer_Security

Render Partial View Using jQuery in ASP.NET MVC

Using standard Ajax call to achieve same result

        $.ajax({
            url: '@Url.Action("_SearchStudents")?NationalId=' + $('#NationalId').val(),
            type: 'GET',
            error: function (xhr) {
                alert('Error: ' + xhr.statusText);

            },
            success: function (result) {

                $('#divSearchResult').html(result);
            }
        });




public ActionResult _SearchStudents(string NationalId)
        {

           //.......

            return PartialView("_SearchStudents", model);
        }

Creating a PDF from a RDLC Report in the Background

You don't need to have a reportViewer control anywhere - you can create the LocalReport on the fly:

var lr = new LocalReport
{
    ReportPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? @"C:\", "Reports", "PathOfMyReport.rdlc"),
    EnableExternalImages = true
};

lr.DataSources.Add(new ReportDataSource("NameOfMyDataSet", model));

string mimeType, encoding, extension;

Warning[] warnings;
string[] streams;
var renderedBytes = lr.Render
    (
        "PDF",
        @"<DeviceInfo><OutputFormat>PDF</OutputFormat><HumanReadablePDF>False</HumanReadablePDF></DeviceInfo>",
        out mimeType,
        out encoding,
        out extension,
        out streams,
        out warnings
    );

var saveAs = string.Format("{0}.pdf", Path.Combine(tempPath, "myfilename"));

var idx = 0;
while (File.Exists(saveAs))
{
    idx++;
    saveAs = string.Format("{0}.{1}.pdf", Path.Combine(tempPath, "myfilename"), idx);
}

using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write))
{
    stream.Write(renderedBytes, 0, renderedBytes.Length);
    stream.Close();
}

lr.Dispose();

You can also add parameters: (lr.SetParameter()), handle subreports: (lr.SubreportProcessing+=YourHandler), or pretty much anything you can think of.

Does WhatsApp offer an open API?

  1. is the correct answer. WhatsApp is intentionally a closed system without an API for external access.

There were several projects available that reverse engineered the WhatsApp webservice interfaces. However, to my knowledge all of them are now discontinued/defunct due to legal action against them from WhatsApp.

For mobile phone applications there is a limited URL-Scheme-API available on IPhone and Android (Android-intent possible as well).

How to access SOAP services from iPhone

I've historically rolled my own access at a low level (XML generation and parsing) to deal with the occasional need to do SOAP style requests from Objective-C. That said, there's a library available called SOAPClient (soapclient) that is open source (BSD licensed) and available on Google Code (mac-soapclient) that might be of interest.

I won't attest to it's abilities or effectiveness, as I've never used it or had to work with it's API's, but it is available and might provide a quick solution for you depending on your needs.

Apple had, at one time, a very broken utility called WS-MakeStubs. I don't think it's available on the iPhone, but you might also be interested in an open-source library intended to replace that - code generate out Objective-C for interacting with a SOAP client. Again, I haven't used it - but I've marked it down in my notes: wsdl2objc

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

Two constructors

Let's, just as example:

public class Test {     public Test() {         System.out.println("NO ARGS");     }      public Test(String s) {         this();         System.out.println("1 ARG");     }      public static void main(String args[])     {         Test t = new Test("s");     } } 

It will print

>>> NO ARGS >>> 1 ARG 

The correct way to call the constructor is by:

this(); 

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

I had the same problem in my Vue.js and SpringBoot projects. If somebody work with spring you can add this code:

@Bean
public FilterRegistrationBean simpleCorsFilter() {  
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();  
    CorsConfiguration config = new CorsConfiguration();  
    config.setAllowCredentials(true); 
    // *** URL below needs to match the Vue client URL and port ***
    config.setAllowedOrigins(Collections.singletonList("http://localhost:8080")); 
    config.setAllowedMethods(Collections.singletonList("*"));  
    config.setAllowedHeaders(Collections.singletonList("*"));  
    source.registerCorsConfiguration("/**", config);  
    FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);  
    return bean;  
}   

I found solution in this article Build a Simple CRUD App with Spring Boot and Vue.js

Make columns of equal width in <table>

Use following property same as table and its fully dynamic:

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed; /* optional, for equal spacing */_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid pink;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz klxjgkldjklg </li>_x000D_
  <li>baz</li>_x000D_
  <li>baz lds.jklklds</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

May be its solve your issue.

What is the correct syntax for 'else if'?

Here is a little refactoring of your function (it does not use "else" or "elif"):

def function(a):
    if a not in (1, 2):
        a = 3
    print(str(a) + "a")

@ghostdog74: Python 3 requires parentheses for "print".

Opening Chrome From Command Line

Use the start command as follows.

start "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" http://www.google.com

It will be better to close chrome instances before you open a new one. You can do that as follows:

taskkill /IM chrome.exe
start "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" http://www.google.com

That'll work for you.

How to pass multiple parameters in thread in VB

Pass multiple parameter for VB.NET 3.5

 Public Class MyWork

    Public Structure thread_Data            
        Dim TCPIPAddr As String
        Dim TCPIPPort As Integer            
    End Structure

    Dim STthread_Data As thread_Data
    STthread_Data.TCPIPAddr = "192.168.2.2"
    STthread_Data.TCPIPPort = 80  

    Dim multiThread As Thread = New Thread(AddressOf testthread)
    multiThread.SetApartmentState(ApartmentState.MTA)
    multiThread.Start(STthread_Data)     

    Private Function testthread(ByVal STthread_Data As thread_Data) 
        Dim IPaddr as string = STthread_Data.TCPIPAddr
        Dim IPport as integer = STthread_Data.TCPIPPort
        'Your work'        
    End Function

End Class

Python reading from a file and saving to utf-8

Process text to and from Unicode at the I/O boundaries of your program using open with the encoding parameter. Make sure to use the (hopefully documented) encoding of the file being read. The default encoding varies by OS (specifically, locale.getpreferredencoding(False) is the encoding used), so I recommend always explicitly using the encoding parameter for portability and clarity (Python 3 syntax below):

with open(filename, 'r', encoding='utf8') as f:
    text = f.read()

# process Unicode text

with open(filename, 'w', encoding='utf8') as f:
    f.write(text)

If still using Python 2 or for Python 2/3 compatibility, the io module implements open with the same semantics as Python 3's open and exists in both versions:

import io
with io.open(filename, 'r', encoding='utf8') as f:
    text = f.read()

# process Unicode text

with io.open(filename, 'w', encoding='utf8') as f:
    f.write(text)

Referencing a string in a string array resource with xml

In short: I don't think you can, but there seems to be a workaround:.

If you take a look into the Android Resource here:

http://developer.android.com/guide/topics/resources/string-resource.html

You see than under the array section (string array, at least), the "RESOURCE REFERENCE" (as you get from an XML) does not specify a way to address the individual items. You can even try in your XML to use "@array/yourarrayhere". I know that in design time you will get the first item. But that is of no practical use if you want to use, let's say... the second, of course.

HOWEVER, there is a trick you can do. See here:

Referencing an XML string in an XML Array (Android)

You can "cheat" (not really) the array definition by addressing independent strings INSIDE the definition of the array. For example, in your strings.xml:

<string name="earth">Earth</string>
<string name="moon">Moon</string>

<string-array name="system">
    <item>@string/earth</item>
    <item>@string/moon</item>
</string-array>

By using this, you can use "@string/earth" and "@string/moon" normally in your "android:text" and "android:title" XML fields, and yet you won't lose the ability to use the array definition for whatever purposes you intended in the first place.

Seems to work here on my Eclipse. Why don't you try and tell us if it works? :-)

How to increase Java heap space for a tomcat app

For Windows Service, you need to run tomcat9w.exe (or 6w/7w/8w) depending on your version of tomcat. First, make sure tomcat is stopped. Then double click on tomcat9w.exe. Navigate to the Java tab. If you know you have 64 bit Windows with 64 bit Java and 64 bit Tomcat, then feel free to set the memory higher than 512. You'll need to do some task manager monitoring to determine how high to set it. For most apps developed in 2019... I'd recommend an initial memory pool of 1024, and the maximum memory pool of 2048. Of course if your computer has tons of RAM... feel free to go as high as you want. Also, see this answer: How to increase Maximum Memory Pool Size? Apache Tomcat 9

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

How to update SQLAlchemy row entry?

user.no_of_logins += 1
session.commit()

excel plot against a date time x series

[excel 2010] separate the date and time into separate columns and select both as X-Axis and data as graph series see http://www.79783.mrsite.com/USERIMAGES/horizontal_axis_date_and_time2.xlsx

Case objects vs Enumerations in Scala

Another disadvantage of case classes versus Enumerations when you will need to iterate or filter across all instances. This is a built-in capability of Enumeration (and Java enums as well) while case classes don't automatically support such capability.

In other words: "there's no easy way to get a list of the total set of enumerated values with case classes".

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

ALTER TABLE `tbl_celebrity_rows` ADD CONSTRAINT `tbl_celebrity_rows_ibfk_1` FOREIGN KEY (`celebrity_id`) 
REFERENCES `tbl_celebrities`(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;

Spring jUnit Testing properties file

As for the testing, you should use from Spring 4.1 which will overwrite the properties defined in other places:

@TestPropertySource("classpath:application-test.properties")

Test property sources have higher precedence than those loaded from the operating system's environment or Java system properties as well as property sources added by the application like @PropertySource

A server with the specified hostname could not be found

First of all check your internet connection.. go to safari and check by searching something on google(dont try google.com only.. because it can be cached). If it is working fine, then try now in your app. It must work. This is fired while not having proper internet connection.

How to read pickle file?

There is a read_pickle function as part of pandas 0.22+

import pandas as pd

object = pd.read_pickle(r'filepath')

Multiline string literal in C#

You can use @ and "".

        string sourse = @"{
        ""items"":[
        {
            ""itemId"":0,
            ""name"":""item0""
        },
        {
            ""itemId"":1,
            ""name"":""item1""
        }
        ]
    }";

Arrays in type script

This is a very c# type of code:

var bks: Book[] = new Book[2];

In Javascript / Typescript you don't allocate memory up front like that, and that means something completely different. This is how you would do what you want to do:

var bks: Book[] = [];
bks.push(new Book());
bks[0].Author = "vamsee";
bks[0].BookId = 1;
return bks.length;

Now to explain what new Book[2]; would mean. This would actually mean that call the new operator on the value of Book[2]. e.g.:

Book[2] = function (){alert("hey");}
var foo = new Book[2]

and you should see hey. Try it

What is System, out, println in System.out.println() in Java

The first answer you posted (System is a built-in class...) is pretty spot on.

You can add that the System class contains large portions which are native and that is set up by the JVM during startup, like connecting the System.out printstream to the native output stream associated with the "standard out" (console).

Load local images in React.js

You have diferent ways to achieve this, here is an example:

import myimage from './...' // wherever is it.

in your img tag just put this into src:

<img src={myimage}...>

You can also check official docs here: https://facebook.github.io/react-native/docs/image.html

Event detect when css property changed using Jquery

Note

Mutation events have been deprecated since this post was written, and may not be supported by all browsers. Instead, use a mutation observer.

Yes you can. DOM L2 Events module defines mutation events; one of them - DOMAttrModified is the one you need. Granted, these are not widely implemented, but are supported in at least Gecko and Opera browsers.

Try something along these lines:

document.documentElement.addEventListener('DOMAttrModified', function(e){
  if (e.attrName === 'style') {
    console.log('prevValue: ' + e.prevValue, 'newValue: ' + e.newValue);
  }
}, false);

document.documentElement.style.display = 'block';

You can also try utilizing IE's "propertychange" event as a replacement to DOMAttrModified. It should allow to detect style changes reliably.

Error: The 'brew link' step did not complete successfully

You probably already installed an older version of node.js using a different method, so you need to manually remove the files that are getting in brew's way.

Do brew link -n node and manually delete those conflicting files and directories, then try brew link node again.

Elegant way to create empty pandas DataFrame with NaN of type float

For multiple columns you can do:

df = pd.DataFrame(np.zeros([nrow, ncol])*np.nan)

Viewing unpushed Git commits

You could try....

gitk

I know it is not a pure command line option but if you have it installed and are on a GUI system it's a great way to see exactly what you are looking for plus a whole lot more.

(I'm actually kind of surprised no one mentioned it so far.)

Bootstrap 4 Dropdown Menu not working?

Via JavaScript Call the dropdowns via JavaScript:

Paste this is code after bootstrap.min.js

$('.dropdown-toggle').dropdown();

Also, make sure you include popper.min.js before bootstrap.min.js

Dropdowns are positioned thanks to Popper.js (except when they are contained in a navbar).

Stop Chrome Caching My JS Files

You can open an incognito window instead. Switching to an incognito window worked for me when disabling the cache in a normal chrome window still didn't reload a JavaScript file I had changed since the last cache.

https://www.quora.com/Does-incognito-mode-on-Chrome-use-the-cache-that-was-previously-stored

How to change icon on Google map marker

we can change the icon of markers, i did it on right click event. Lets see if it works for you...

// Create a Marker
var marker = new google.maps.Marker({
    position: location,
    map: map,
    title:'Sample Tool Tip'
  });


// Set Icon on any event
google.maps.event.addListener(marker, "rightclick", function() {
        marker.setIcon('blank.png'); // set image path here...
});

Best way to replace multiple characters in a string?

advanced way using regex

import re
text = "hello ,world!"
replaces = {"hello": "hi", "world":" 2020", "!":"."}
regex = re.sub("|".join(replaces.keys()), lambda match: replaces[match.string[match.start():match.end()]], text)
print(regex)

Where should I put <script> tags in HTML markup?

Script blocks DOM load untill it's loaded and executed.

If you place scripts at the end of <body> all of DOM has chance to load and render (page will "display" faster). <script> will have access to all of those DOM elements.

In other hand placing it after <body> start or above will execute script (where there's still no DOM elements).

You are including jQuery which means you can place it wherever you wish and use .ready()

How to set array length in c# dynamically

Use this:

 Array.Resize(ref myArr, myArr.Length + 5);

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

In our case, we were using Hibernate and we had many variables referencing the same Hibernate mapped entity. We were creating and saving these references in a loop. Each reference opened a cursor and kept it open.

We discovered this by using a query to check the number of open cursors while running our code, stepping through with a debugger and selectively commenting things out.

As to why each new reference opened another cursor - the entity in question had collections of other entities mapped to it and I think this had something to do with it (perhaps not just this alone but in combination with how we had configured the fetch mode and cache settings). Hibernate itself has had bugs around failing to close open cursors, though it looks like these have been fixed in later versions.

Since we didn't really need to have so many duplicate references to the same entity anyway, the solution was to stop creating and holding onto all those redundant references. Once we did that the problem when away.

How to use Python to execute a cURL command?

This could be achieve with the below mentioned psuedo code approach

Import os import requests Data = os.execute(curl URL) R= Data.json()

how do I give a div a responsive height

I know this is a little late to the party but you could use viewport units

From caniuse.com:

Viewport units: vw, vh, vmin, vmax - CR Length units representing 1% of the viewport size for viewport width (vw), height (vh), the smaller of the two (vmin), or the larger of the two (vmax).

Support: http://caniuse.com/#feat=viewport-units

_x000D_
_x000D_
div {_x000D_
/* 25% of viewport */_x000D_
  height: 25vh;_x000D_
  width: 15rem;_x000D_
  background-color: #222;_x000D_
  color: #eee;_x000D_
  font-family: monospace;_x000D_
  padding: 2rem;_x000D_
}
_x000D_
<div>responsive height</div>
_x000D_
_x000D_
_x000D_

How to take the first N items from a generator or list?

Slicing a list

top5 = array[:5]
  • To slice a list, there's a simple syntax: array[start:stop:step]
  • You can omit any parameter. These are all valid: array[start:], array[:stop], array[::step]

Slicing a generator

 import itertools
 top5 = itertools.islice(my_list, 5) # grab the first five elements
  • You can't slice a generator directly in Python. itertools.islice() will wrap an object in a new slicing generator using the syntax itertools.islice(generator, start, stop, step)

  • Remember, slicing a generator will exhaust it partially. If you want to keep the entire generator intact, perhaps turn it into a tuple or list first, like: result = tuple(generator)

How to sort an array in Bash

This question looks closely related. And BTW, here's a mergesort in Bash (without external processes):

mergesort() {
  local -n -r input_reference="$1"
  local -n output_reference="$2"
  local -r -i size="${#input_reference[@]}"
  local merge previous
  local -a -i runs indices
  local -i index previous_idx merged_idx \
           run_a_idx run_a_stop \
           run_b_idx run_b_stop

  output_reference=("${input_reference[@]}")
  if ((size == 0)); then return; fi

  previous="${output_reference[0]}"
  runs=(0)
  for ((index = 0;;)) do
    for ((++index;; ++index)); do
      if ((index >= size)); then break 2; fi
      if [[ "${output_reference[index]}" < "$previous" ]]; then break; fi
      previous="${output_reference[index]}"
    done
    previous="${output_reference[index]}"
    runs+=(index)
  done
  runs+=(size)

  while (("${#runs[@]}" > 2)); do
    indices=("${!runs[@]}")
    merge=("${output_reference[@]}")
    for ((index = 0; index < "${#indices[@]}" - 2; index += 2)); do
      merged_idx=runs[indices[index]]
      run_a_idx=merged_idx
      previous_idx=indices[$((index + 1))]
      run_a_stop=runs[previous_idx]
      run_b_idx=runs[previous_idx]
      run_b_stop=runs[indices[$((index + 2))]]
      unset runs[previous_idx]
      while ((run_a_idx < run_a_stop && run_b_idx < run_b_stop)); do
        if [[ "${merge[run_a_idx]}" < "${merge[run_b_idx]}" ]]; then
          output_reference[merged_idx++]="${merge[run_a_idx++]}"
        else
          output_reference[merged_idx++]="${merge[run_b_idx++]}"
        fi
      done
      while ((run_a_idx < run_a_stop)); do
        output_reference[merged_idx++]="${merge[run_a_idx++]}"
      done
      while ((run_b_idx < run_b_stop)); do
        output_reference[merged_idx++]="${merge[run_b_idx++]}"
      done
    done
  done
}

declare -ar input=({z..a}{z..a})
declare -a output

mergesort input output

echo "${input[@]}"
echo "${output[@]}"

Understanding Chrome network log "Stalled" state

My case is the page is sending multiple requests with different parameters when it was open. So most are being "stalled". Following requests immediately sent gets "stalled". Avoiding unnecessary requests would be better (to be lazy...).

jQuery-UI datepicker default date

Try passing in a Date object instead. I can't see why it doesn't work in the format you have entered:

<script type="text/javascript">
$(function() {               
    $("#birthdate" ).datepicker({
        changeMonth: true,
        changeYear: true,
        yearRange: '1920:2010',
        dateFormat : 'dd-mm-yy',
        defaultDate: new Date(1985, 00, 01)
    });
});
</script>

http://api.jqueryui.com/datepicker/#option-defaultDate

Specify either an actual date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.

Declaring variables inside loops, good practice or bad practice?

Since your second question is more concrete, I'm going to address it first, and then take up your first question with the context given by the second. I wanted to give a more evidence-based answer than what's here already.

Question #2: Do most compilers realize that the variable has already been declared and just skip that portion, or does it actually create a spot for it in memory each time?

You can answer this question for yourself by stopping your compiler before the assembler is run and looking at the asm. (Use the -S flag if your compiler has a gcc-style interface, and -masm=intel if you want the syntax style I'm using here.)

In any case, with modern compilers (gcc 10.2, clang 11.0) for x86-64, they only reload the variable on each loop pass if you disable optimizations. Consider the following C++ program—for intuitive mapping to asm, I'm keeping things mostly C-style and using an integer instead of a string, although the same principles apply in the string case:

#include <iostream>

static constexpr std::size_t LEN = 10;

void fill_arr(int a[LEN])
{
    /* *** */
    for (std::size_t i = 0; i < LEN; ++i) {
        const int t = 8;

        a[i] = t;
    }
    /* *** */
}

int main(void)
{
    int a[LEN];

    fill_arr(a);

    for (std::size_t i = 0; i < LEN; ++i) {
        std::cout << a[i] << " ";
    }

    std::cout << "\n";

    return 0;
}

We can compare this to a version with the following difference:

    /* *** */
    const int t = 8;

    for (std::size_t i = 0; i < LEN; ++i) {
        a[i] = t;
    }
    /* *** */

With optimization disabled, gcc 10.2 puts 8 on the stack on every pass of the loop for the declaration-in-loop version:

    mov QWORD PTR -8[rbp], 0
.L3:
    cmp QWORD PTR -8[rbp], 9
    ja  .L4
    mov DWORD PTR -12[rbp], 8 ;?

whereas it only does it once for the out-of-loop version:

    mov DWORD PTR -12[rbp], 8 ;?
    mov QWORD PTR -8[rbp], 0
.L3:
    cmp QWORD PTR -8[rbp], 9
    ja  .L4

Does this make a performance impact? I didn't see an appreciable difference in runtime between them with my CPU (Intel i7-7700K) until I pushed the number of iterations into the billions, and even then the average difference was less than 0.01s. It's only a single extra operation in the loop, after all. (For a string, the difference in in-loop operations is obviously a bit greater, but not dramatically so.)

What's more, the question is largely academic, because with an optimization level of -O1 or higher gcc outputs identical asm for both source files, as does clang. So, at least for simple cases like this, it's unlikely to make any performance impact either way. Of course, in a real-world program, you should always profile rather than make assumptions.

Question #1: Is declaring a variable inside a loop a good practice or bad practice?

As with practically every question like this, it depends. If the declaration is inside a very tight loop and you're compiling without optimizations, say for debugging purposes, it's theoretically possible that moving it outside the loop would improve performance enough to be handy during your debugging efforts. If so, it might be sensible, at least while you're debugging. And although I don't think it's likely to make any difference in an optimized build, if you do observe one, you/your pair/your team can make a judgement call as to whether it's worth it.

At the same time, you have to consider not only how the compiler reads your code, but also how it comes off to humans, yourself included. I think you'll agree that a variable declared in the smallest scope possible is easier to keep track of. If it's outside the loop, it implies that it's needed outside the loop, which is confusing if that's not actually the case. In a big codebase, little confusions like this add up over time and become fatiguing after hours of work, and can lead to silly bugs. That can be much more costly than what you reap from a slight performance improvement, depending on the use case.

Open an html page in default browser with VBA?

I find the most simple is

shell "explorer.exe URL"

This also works to open local folders.

Play audio with Python

You can find information about Python audio here: http://wiki.python.org/moin/Audio/

It doesn't look like it can play .mp3 files without external libraries. You could either convert your .mp3 file to a .wav or other format, or use a library like PyMedia.

How do I get formatted JSON in .NET using C#?

You may use following standard method for getting formatted Json

JsonReaderWriterFactory.CreateJsonWriter(Stream stream, Encoding encoding, bool ownsStream, bool indent, string indentChars)

Only set "indent==true"

Try something like this

    public readonly DataContractJsonSerializerSettings Settings = 
            new DataContractJsonSerializerSettings
            { UseSimpleDictionaryFormat = true };

    public void Keep<TValue>(TValue item, string path)
    {
        try
        {
            using (var stream = File.Open(path, FileMode.Create))
            {
                //var currentCulture = Thread.CurrentThread.CurrentCulture;
                //Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

                try
                {
                    using (var writer = JsonReaderWriterFactory.CreateJsonWriter(
                        stream, Encoding.UTF8, true, true, "  "))
                    {
                        var serializer = new DataContractJsonSerializer(type, Settings);
                        serializer.WriteObject(writer, item);
                        writer.Flush();
                    }
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception.ToString());
                }
                finally
                {
                    //Thread.CurrentThread.CurrentCulture = currentCulture;
                }
            }
        }
        catch (Exception exception)
        {
            Debug.WriteLine(exception.ToString());
        }
    }

Pay your attention to lines

    var currentCulture = Thread.CurrentThread.CurrentCulture;
    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
    ....
    Thread.CurrentThread.CurrentCulture = currentCulture;

For some kinds of xml-serializers you should use InvariantCulture to avoid exception during deserialization on the computers with different Regional settings. For example, invalid format of double or DateTime sometimes cause them.

For deserializing

    public TValue Revive<TValue>(string path, params object[] constructorArgs)
    {
        try
        {
            using (var stream = File.OpenRead(path))
            {
                //var currentCulture = Thread.CurrentThread.CurrentCulture;
                //Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

                try
                {
                    var serializer = new DataContractJsonSerializer(type, Settings);
                    var item = (TValue) serializer.ReadObject(stream);
                    if (Equals(item, null)) throw new Exception();
                    return item;
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception.ToString());
                    return (TValue) Activator.CreateInstance(type, constructorArgs);
                }
                finally
                {
                    //Thread.CurrentThread.CurrentCulture = currentCulture;
                }
            }
        }
        catch
        {
            return (TValue) Activator.CreateInstance(typeof (TValue), constructorArgs);
        }
    }

Thanks!

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

How to resolve merge conflicts in Git repository?

I like using WinMerge (free tool) that does both full entire directory tree comparison/merge and also individual file(s) comparison/merge of the full directory tree compare.

No one had mentioned WinMerge in this trail thus far, thus am mentioning here.

The Git merge conflict is telling you that your pull request will undo/lose/overwrite a co-worker's changes, typically because your copy of the content wasn't recent enough.

Steps to resolve can be:

  • Take another new clone of source to a newly named folder,
  • Use WinMerge to compare your content and the most recent content to understand the conflict,
  • For the file(s) changed by both yourself and your co-worker that are causing the Git Merge conflict, look at the lines that your co-worker has added/changed/deleted as per compared to the code lines that you have added/changed/deleted.
  • Use the winmerge left / right code section move arrows to ensure your co-workers work is in your copy of the file and you aren't clobbering their work.

i.e. no magic way to resolve Git merge conflicts other than manually looking at what each person has done to the same source file(s).

That is what I'm thinking.

Note: WinMerge creates .bak files .. and you don't want them copied to source control AzOps / TFS etc .. so if you are sure you have done the edit correctly, remove the .bak files.

Counting the number of option tags in a select tag in jQuery

Ok, i had a few problems because i was inside a

$('.my-dropdown').live('click', function(){  
});

I had multiples inside my page that's why i used a class.

My drop down was filled automatically by a ajax request when i clicked it, so i only had the element $(this)

so...

I had to do:

$('.my-dropdown').live('click', function(){
  total_tems = $(this).find('option').length;
});

php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

I think it is not useful to configure the mysql server without caching_sha2_password encryption, we have to find a way to publish, send or obtain secure information through the network. As you see in the code below I dont use variable $db_name, and Im using a user in mysql server with standar configuration password. Just create a Standar user password and config all privilages. it works, but how i said without segurity.

<?php
$db_name="db";
$mysql_username="root";
$mysql_password="****";
$server_name="localhost";
$conn=mysqli_connect($server_name,$mysql_username,$mysql_password);

if ($conn) {
    echo "connetion success";
}
else{
    echo mysqli_error($conn);
}

?>

CSS - Expand float child DIV height to parent's height

Please set parent div to overflow: hidden
then in child divs you can set a large amount for padding-bottom. for example
padding-bottom: 5000px
then margin-bottom: -5000px
and then all child divs will be the height of the parent.
Of course this wont work if you are trying to put content in the parent div (outside of other divs that is)

_x000D_
_x000D_
.parent{_x000D_
    border: 1px solid black;_x000D_
    overflow: hidden;_x000D_
    height: auto;_x000D_
}_x000D_
.child{_x000D_
    float: left;_x000D_
    padding-bottom: 1500px;_x000D_
    margin-bottom: -1500px;_x000D_
}_x000D_
.child1{_x000D_
    background: red;_x000D_
    padding-right: 10px;    _x000D_
}_x000D_
.child2{_x000D_
    background: green;_x000D_
    padding-left: 10px;_x000D_
}
_x000D_
<div class="parent">_x000D_
    <div class="child1 child">_x000D_
        One line text in child1_x000D_
    </div>_x000D_
    <div class="child2 child">_x000D_
        Three line text in child2<br />_x000D_
        Three line text in child2<br />_x000D_
        Three line text in child2_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Example: http://jsfiddle.net/Tareqdhk/DAFEC/

Check if string has space in between (or anywhere)

It's also possible to use a regular expression to achieve this when you want to test for any whitespace character and not just a space.

var text = "sossjj ssskkk";
var regex = new Regex(@"\s");
regex.IsMatch(text); // true

How do I iterate over a JSON structure?

You can use a mini library like objx - http://objx.googlecode.com/

You can write code like this:

var data =  [ {"id":"10", "class": "child-of-9"},
              {"id":"11", "class": "child-of-10"}];

// alert all IDs
objx(data).each(function(item) { alert(item.id) });

// get all IDs into a new array
var ids = objx(data).collect("id").obj();

// group by class
var grouped = objx(data).group(function(item){ return item.class; }).obj()

There are more 'plugins' available to let you handle data like this, see http://code.google.com/p/objx-plugins/wiki/PluginLibrary

How to set timeout for a line of c# code

I use something like this (you should add code to deal with the various fails):

    var response = RunTaskWithTimeout<ReturnType>(
        (Func<ReturnType>)delegate { return SomeMethod(someInput); }, 30);


    /// <summary>
    /// Generic method to run a task on a background thread with a specific timeout, if the task fails,
    /// notifies a user
    /// </summary>
    /// <typeparam name="T">Return type of function</typeparam>
    /// <param name="TaskAction">Function delegate for task to perform</param>
    /// <param name="TimeoutSeconds">Time to allow before task times out</param>
    /// <returns></returns>
    private T RunTaskWithTimeout<T>(Func<T> TaskAction, int TimeoutSeconds)
    {
        Task<T> backgroundTask;

        try
        {
            backgroundTask = Task.Factory.StartNew(TaskAction);
            backgroundTask.Wait(new TimeSpan(0, 0, TimeoutSeconds));
        }
        catch (AggregateException ex)
        {
            // task failed
            var failMessage = ex.Flatten().InnerException.Message);
            return default(T);
        }
        catch (Exception ex)
        {
            // task failed
            var failMessage = ex.Message;
            return default(T);
        }

        if (!backgroundTask.IsCompleted)
        {
            // task timed out
            return default(T);
        }

        // task succeeded
        return backgroundTask.Result;
    }

Vagrant ssh authentication failure

I am using Vagrant with a Puphpet setup from May 2015 and had this problem. It appears that the configuration that was generated didn't handle Vagrant 1.7.4 (or maybe a bit earlier?) behavior of regenerating ssh keys if it detects an insecure key.

I solved it by adding the following in my Puphpet generated Vagrantfile (local setup) inside the "if File.file?(customKey)" clause:

config.ssh.insert_key = false

Reference commit

How to place two divs next to each other?

Try to use flexbox model. It is easy and short to write.

Live Jsfiddle

CSS:

#wrapper {
  display: flex;
  border: 1px solid black;
}
#first {
    border: 1px solid red;
}
#second {
    border: 1px solid green;
}

default direction is row. So, it aligns next to each other inside the #wrapper. But it is not supported IE9 or less than that versions

Test process.env with Jest

I think you could try this too:

const currentEnv = process.env;
process.env = { ENV_NODE: 'whatever' };

// test code...

process.env = currentEnv;

This works for me and you don't need module things

How can I set the color of a selected row in DataGrid

I had this problem and I nearly tore my hair out, and I wasn't able to find the appropriate answer on the net. I was trying to control the background color of the selected row in a WPF DataGrid. It just wouldn't do it. In my case, the reason was that I also had a CellStyle in my datagrid, and the CellStyle overrode the RowStyle I was setting. Interestingly so, because the CellStyle wasn't even setting the background color, which was instead bing set by the RowBackground and AlternateRowBackground properties. Nevertheless, trying to set the background colour of the selected row did not work at all when I did this:

        <DataGrid ... >
        <DataGrid.RowBackground>
            ...
        </DataGrid.RowBackground>
        <DataGrid.AlternatingRowBackground>
            ...
        </DataGrid.AlternatingRowBackground>
        <DataGrid.RowStyle>
            <Style TargetType="{x:Type DataGridRow}">
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="Background" Value="Pink"/>
                        <Setter Property="Foreground" Value="White"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </DataGrid.RowStyle>
        <DataGrid.CellStyle>
            <Style TargetType="{x:Type DataGridCell}">
                <Setter Property="Foreground" Value="{Binding MyProperty}" />
            </Style>
        </DataGrid.CellStyle>

and it did work when I moved the desired style for the selected row out of the row style and into the cell style, like so:

    <DataGrid ... >
        <DataGrid.RowBackground>
            ...
        </DataGrid.RowBackground>
        <DataGrid.AlternatingRowBackground>
            ...
        </DataGrid.AlternatingRowBackground>
        <DataGrid.CellStyle>
            <Style TargetType="{x:Type DataGridCell}">
                <Setter Property="Foreground" Value="{Binding MyProperty}" />
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="Background" Value="Pink"/>
                        <Setter Property="Foreground" Value="White"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </DataGrid.CellStyle>

Just posting this in case someone has the same problem.

How to get maximum value from the Collection (for example ArrayList)?

Here are three more ways to find the maximum value in a list, using streams:

List<Integer> nums = Arrays.asList(-1, 2, 1, 7, 3);
Optional<Integer> max1 = nums.stream().reduce(Integer::max);
Optional<Integer> max2 = nums.stream().max(Comparator.naturalOrder());
OptionalInt max3 = nums.stream().mapToInt(p->p).max();
System.out.println("max1: " + max1.get() + ", max2: " 
   + max2.get() + ", max3: " + max3.getAsInt());

All of these methods, just like Collections.max, iterate over the entire collection, hence they require time proportional to the size of the collection.

Why does find -exec mv {} ./target/ + not work?

The standard equivalent of find -iname ... -exec mv -t dest {} + for find implementations that don't support -iname or mv implementations that don't support -t is to use a shell to re-order the arguments:

find . -name '*.[cC][pP][pP]' -type f -exec sh -c '
  exec mv "$@" /dest/dir/' sh {} +

By using -name '*.[cC][pP][pP]', we also avoid the reliance on the current locale to decide what's the uppercase version of c or p.

Note that +, contrary to ; is not special in any shell so doesn't need to be quoted (though quoting won't harm, except of course with shells like rc that don't support \ as a quoting operator).

The trailing / in /dest/dir/ is so that mv fails with an error instead of renaming foo.cpp to /dest/dir in the case where only one cpp file was found and /dest/dir didn't exist or wasn't a directory (or symlink to directory).

What is the difference between git clone and checkout?

checkout can be use for many case :

1st case : switch between branch in local repository For instance : git checkout exists_branch_to_switch

You can also create new branch and switch out in throught this case with -b

git checkout -b new_branch_to_switch

2nd case : restore file from x rev

git checkout rev file_to_restore ...

C# DateTime to UTC Time without changing the time

You can use the overloaded constructor of DateTime:

DateTime utcDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, DateTimeKind.Utc);

Make: how to continue after a command fails?

To get make to actually ignore errors on a single line, you can simply suffix it with ; true, setting the return value to 0. For example:

rm .lambda .lambda_t .activity .activity_t_lambda 2>/dev/null; true

This will redirect stderr output to null, and follow the command with true (which always returns 0, causing make to believe the command succeeded regardless of what actually happened), allowing program flow to continue.

When to use which design pattern?

Usually the process is the other way around. Do not go looking for situations where to use design patterns, look for code that can be optimized. When you have code that you think is not structured correctly. try to find a design pattern that will solve the problem.

Design patterns are meant to help you solve structural problems, do not go design your application just to be able to use design patterns.

SQL Server - Return value after INSERT

This is how I use OUTPUT INSERTED, when inserting to a table that uses ID as identity column in SQL Server:

'myConn is the ADO connection, RS a recordset and ID an integer
Set RS=myConn.Execute("INSERT INTO M2_VOTELIST(PRODUCER_ID,TITLE,TIMEU) OUTPUT INSERTED.ID VALUES ('Gator','Test',GETDATE())")
ID=RS(0)

HTML table: keep the same width for columns

In your case, since you are only showing 3 columns:

Name    Value       Business
  or
Name    Business    Ecommerce Pro

why not set all 3 to have a width of 33.3%. since only 3 are ever shown at once, the browser should render them all a similar width.

How do I create a circle or square with just CSS - with a hollow center?

Try This

_x000D_
_x000D_
div.circle {_x000D_
  -moz-border-radius: 50px/50px;_x000D_
  -webkit-border-radius: 50px 50px;_x000D_
  border-radius: 50px/50px;_x000D_
  border: solid 21px #f00;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
}_x000D_
_x000D_
div.square {_x000D_
  border: solid 21px #f0f;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
}
_x000D_
<div class="circle">_x000D_
  <img/>_x000D_
</div>_x000D_
 <hr/>_x000D_
<div class="square">_x000D_
  <img/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

More here

How do I convert an integer to binary in JavaScript?

This is how I manage to handle it:

const decbin = nbr => {
  if(nbr < 0){
     nbr = 0xFFFFFFFF + nbr + 1
  }
  return parseInt(nbr, 10).toString(2)
};

got it from this link: https://locutus.io/php/math/decbin/

Can't connect to MySQL server on 'localhost' (10061) after Installation

In Windows 7

  1. press Windows+R it opens Run
  2. Enter services.msc
  3. Find out mysql right click and start
  4. if mysql was not found
    1. Run cmd as administrator
    2. goto C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin directory(to go back use cd..) and type mysqld.exe --install
  5. follow step 3

That's all

Excel VBA If cell.Value =... then

I think it would make more sense to use "Find" function in Excel instead of For Each loop. It works much much faster and it's designed for such actions. Try this:

 Sub FindSomeCells(strSearchQuery As String)   

    Set SearchRange = Worksheets("Sheet1").Range("A1:A100")
    FindWhat = strSearchQuery
    Set FoundCells = FindAll(SearchRange:=SearchRange, _
                            FindWhat:=FindWhat, _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByColumns, _
                            MatchCase:=False, _
                            BeginsWith:=vbNullString, _
                            EndsWith:=vbNullString, _
                            BeginEndCompare:=vbTextCompare)
    If FoundCells Is Nothing Then
        Debug.Print "Value Not Found"
    Else
        For Each FoundCell In FoundCells
            FoundCell.Interior.Color = XlRgbColor.rgbLightGreen
        Next FoundCell
    End If

End Sub

That subroutine searches for some string and returns a collections of cells fullfilling your search criteria. Then you can do whatever you want with the cells in that collection. Forgot to add the FindAll function definition:

Function FindAll(SearchRange As Range, _
                FindWhat As Variant, _
               Optional LookIn As XlFindLookIn = xlValues, _
                Optional LookAt As XlLookAt = xlWhole, _
                Optional SearchOrder As XlSearchOrder = xlByRows, _
                Optional MatchCase As Boolean = False, _
                Optional BeginsWith As String = vbNullString, _
                Optional EndsWith As String = vbNullString, _
                Optional BeginEndCompare As VbCompareMethod = vbTextCompare) As Range
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' FindAll
' This searches the range specified by SearchRange and returns a Range object
' that contains all the cells in which FindWhat was found. The search parameters to
' this function have the same meaning and effect as they do with the
' Range.Find method. If the value was not found, the function return Nothing. If
' BeginsWith is not an empty string, only those cells that begin with BeginWith
' are included in the result. If EndsWith is not an empty string, only those cells
' that end with EndsWith are included in the result. Note that if a cell contains
' a single word that matches either BeginsWith or EndsWith, it is included in the
' result.  If BeginsWith or EndsWith is not an empty string, the LookAt parameter
' is automatically changed to xlPart. The tests for BeginsWith and EndsWith may be
' case-sensitive by setting BeginEndCompare to vbBinaryCompare. For case-insensitive
' comparisons, set BeginEndCompare to vbTextCompare. If this parameter is omitted,
' it defaults to vbTextCompare. The comparisons for BeginsWith and EndsWith are
' in an OR relationship. That is, if both BeginsWith and EndsWith are provided,
' a match if found if the text begins with BeginsWith OR the text ends with EndsWith.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Dim FoundCell As Range
Dim FirstFound As Range
Dim LastCell As Range
Dim ResultRange As Range
Dim XLookAt As XlLookAt
Dim Include As Boolean
Dim CompMode As VbCompareMethod
Dim Area As Range
Dim MaxRow As Long
Dim MaxCol As Long
Dim BeginB As Boolean
Dim EndB As Boolean
CompMode = BeginEndCompare
If BeginsWith <> vbNullString Or EndsWith <> vbNullString Then
    XLookAt = xlPart
Else
    XLookAt = LookAt
End If
' this loop in Areas is to find the last cell
' of all the areas. That is, the cell whose row
' and column are greater than or equal to any cell
' in any Area.

For Each Area In SearchRange.Areas
    With Area
        If .Cells(.Cells.Count).Row > MaxRow Then
            MaxRow = .Cells(.Cells.Count).Row
        End If
        If .Cells(.Cells.Count).Column > MaxCol Then
            MaxCol = .Cells(.Cells.Count).Column
        End If
    End With
Next Area
Set LastCell = SearchRange.Worksheet.Cells(MaxRow, MaxCol)
On Error GoTo 0
Set FoundCell = SearchRange.Find(what:=FindWhat, _
        after:=LastCell, _
        LookIn:=LookIn, _
        LookAt:=XLookAt, _
        SearchOrder:=SearchOrder, _
        MatchCase:=MatchCase)
If Not FoundCell Is Nothing Then
    Set FirstFound = FoundCell
    Do Until False ' Loop forever. We'll "Exit Do" when necessary.
        Include = False
        If BeginsWith = vbNullString And EndsWith = vbNullString Then
            Include = True
        Else
            If BeginsWith <> vbNullString Then
                If StrComp(Left(FoundCell.Text, Len(BeginsWith)), BeginsWith, BeginEndCompare) = 0 Then
                    Include = True
                End If
            End If
            If EndsWith <> vbNullString Then
                If StrComp(Right(FoundCell.Text, Len(EndsWith)), EndsWith, BeginEndCompare) = 0 Then
                    Include = True
                End If
            End If
        End If
        If Include = True Then
            If ResultRange Is Nothing Then
                Set ResultRange = FoundCell
            Else
                Set ResultRange = Application.Union(ResultRange, FoundCell)
            End If
        End If
        Set FoundCell = SearchRange.FindNext(after:=FoundCell)
        If (FoundCell Is Nothing) Then
            Exit Do
        End If
        If (FoundCell.Address = FirstFound.Address) Then
            Exit Do
        End If
    Loop
End If
Set FindAll = ResultRange
End Function

How to include jQuery in ASP.Net project?

if you build an MVC project, its included by default. otherwise, what Nick said.

How to generate .env file for laravel?

There's another explanation for why .env doesn't exist, and it happens when you move all the Laravel files.

Take this workflow: in your project directory you do laravel new whatever, Laravel is installed in whatever, you do mv * .. to move all the files to your project folder, and you remove whatever. The problem is, mv doesn't move hidden files by default, so the .env files are left behind, and are removed!

what is .subscribe in angular?

A Subscription is an object that represents a disposable resource, usually the execution of an Observable. A Subscription has one important method, unsubscribe, that takes no argument and just disposes of the resource held by the subscription.

import { interval } from 'rxjs';

const observable = interval(1000);
const subscription = observable.subscribe(a=> console.log(a));

/** This cancels the ongoing Observable execution which
was started by calling subscribe with an Observer.*/

subscription.unsubscribe();

A Subscription essentially just has an unsubscribe() function to release resources or cancel Observable executions.

import { interval } from 'rxjs';

const observable1 = interval(400);
const observable2 = interval(300);

const subscription = observable1.subscribe(x => console.log('first: ' + x));
const childSubscription = observable2.subscribe(x => console.log('second: ' + x));

subscription.add(childSubscription);

setTimeout(() => {
// It unsubscribes BOTH subscription and childSubscription
subscription.unsubscribe();
}, 1000);

According to the official documentation, Angular should unsubscribe for you, but apparently, there is a bug.

Download files from SFTP with SSH.NET library

While the example works, its not the correct way to handle the streams...

You need to ensure the closing of the files/streams with the using clause.. Also, add try/catch to handle IO errors...

       public void DownloadAll()
    {
        string host = @"sftp.domain.com";
        string username = "myusername";
        string password = "mypassword";

        string remoteDirectory = "/RemotePath/";
        string localDirectory = @"C:\LocalDriveFolder\Downloaded\";

        using (var sftp = new SftpClient(host, username, password))
        {
            sftp.Connect();
            var files = sftp.ListDirectory(remoteDirectory);

            foreach (var file in files)
            {
                string remoteFileName = file.Name;
                if ((!file.Name.StartsWith(".")) && ((file.LastWriteTime.Date == DateTime.Today))

                    using (Stream file1 = File.OpenWrite(localDirectory + remoteFileName))
                    { 
                        sftp.DownloadFile(remoteDirectory + remoteFileName, file1);
                    }
            }

        }
    }

Warning: comparison with string literals results in unspecified behaviour

You can't compare strings with == in C. For C, strings are just (zero-terminated) arrays, so you need to use string functions to compare them. See the man page for strcmp() and strncmp().

If you want to compare a character you need to compare to a character, not a string. "a" is the string a, which occupies two bytes (the a and the terminating null byte), while the character a is represented by 'a' in C.

Remove .php extension with .htaccess

Gumbo's answer in the Stack Overflow question How to hide the .html extension with Apache mod_rewrite should work fine.

Re 1) Change the .html to .php

Re a.) Yup, that's possible, just add #tab to the URL.

Re b.) That's possible using QSA (Query String Append), see below.

This should also work in a sub-directory path:

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L]

MySQL Results as comma separated list

In my case i have to concatenate all the account number of a person who's mobile number is unique. So i have used the following query to achieve that.

SELECT GROUP_CONCAT(AccountsNo) as Accounts FROM `tblaccounts` GROUP BY MobileNumber

Query Result is below:

Accounts
93348001,97530801,93348001,97530801
89663501
62630701
6227895144840002
60070021
60070020
60070019
60070018
60070017
60070016
60070015

How to do an INNER JOIN on multiple columns

If you want to search on both FROM and TO airports, you'll want to join on the Airports table twice - then you can use both from and to tables in your results set:

SELECT
   Flights.*,fromAirports.*,toAirports.*
FROM
   Flights
INNER JOIN 
   Airports fromAirports on Flights.fairport = fromAirports.code
INNER JOIN 
   Airports toAirports on Flights.tairport = toAirports.code
WHERE
 ...

Running Java Program from Command Line Linux

Guys let's understand the syntax of it.

  1. If class file is present in the Current Dir.

    java -cp . fileName

  2. If class file is present within the Dir. Go to the Parent Dir and enter below cmd.

    java -cp . dir1.dir2.dir3.fileName

  3. If there is a dependency on external jars then,

    java -cp .:./jarName1:./jarName2 fileName

    Hope this helps.

Text File Parsing with Python

From the accepted answer, it looks like your desired behaviour is to turn

skip 0
skip 1
skip 2
skip 3
"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636

into

2012,06,23,03,09,13.23,4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,NAN,-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636

If that's right, then I think something like

import csv

with open("test.dat", "rb") as infile, open("test.csv", "wb") as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile, quoting=False)
    for i, line in enumerate(reader):
        if i < 4: continue
        date = line[0].split()
        day = date[0].split('-')
        time = date[1].split(':')
        newline = day + time + line[1:]
        writer.writerow(newline)

would be a little simpler than the reps stuff.

Confused about UPDLOCK, HOLDLOCK

Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N for the S/U and U/S contention, as in No Conflict.

As for the HOLDLOCK hint the documentation states:

HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.

...

SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...

and the Transaction Isolation Level topic explains what SERIALIZABLE means:

No other transactions can modify data that has been read by the current transaction until the current transaction completes.

Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.

Therefore the behavior you see is perfectly explained by the product documentation:

  • UPDLOCK does not block concurrent SELECT nor INSERT, but blocks any UPDATE or DELETE of the rows selected by T1
  • HOLDLOCK means SERALIZABLE and therefore allows SELECTS, but blocks UPDATE and DELETES of the rows selected by T1, as well as any INSERT in the range selected by T1 (which is the entire table, therefore any insert).
  • (UPDLOCK, HOLDLOCK): your experiment does not show what would block in addition to the case above, namely another transaction with UPDLOCK in T2:
    SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
  • TABLOCKX no need for explanations

The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...

After OP edit:

I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.

The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.

Reading a text file with SQL Server

What does your text file look like?? Each line a record?

You'll have to check out the BULK INSERT statement - that should look something like:

BULK INSERT dbo.YourTableName
FROM 'D:\directory\YourFileName.csv'
WITH
(
  CODEPAGE = '1252',
  FIELDTERMINATOR = ';',
  CHECK_CONSTRAINTS
) 

Here, in my case, I'm importing a CSV file - but you should be able to import a text file just as well.

From the MSDN docs - here's a sample that hopefully works for a text file with one field per row:

BULK INSERT dbo.temp 
   FROM 'c:\temp\file.txt'
   WITH 
      (
         ROWTERMINATOR ='\n'
      )

Seems to work just fine in my test environment :-)

SQL to search objects, including stored procedures, in Oracle

i reached this question while trying to find all procedures which use a certain table

Oracle SQL Developer offers this capability, as pointed out in this article : https://www.thatjeffsmith.com/archive/2012/09/search-and-browse-database-objects-with-oracle-sql-developer/

From the View menu, choose Find DB Object. Choose a DB connection. Enter the name of the table. At Object Types, keep only functions, procedures and packages. At Code section, check All source lines.

enter image description here

How to debug a GLSL shader?

If you want to visualize the variations of a value across the screen, you can use a heatmap function similar to this (I wrote it in hlsl, but it is easy to adapt to glsl):

float4 HeatMapColor(float value, float minValue, float maxValue)
{
    #define HEATMAP_COLORS_COUNT 6
    float4 colors[HEATMAP_COLORS_COUNT] =
    {
        float4(0.32, 0.00, 0.32, 1.00),
        float4(0.00, 0.00, 1.00, 1.00),
        float4(0.00, 1.00, 0.00, 1.00),
        float4(1.00, 1.00, 0.00, 1.00),
        float4(1.00, 0.60, 0.00, 1.00),
        float4(1.00, 0.00, 0.00, 1.00),
    };
    float ratio=(HEATMAP_COLORS_COUNT-1.0)*saturate((value-minValue)/(maxValue-minValue));
    float indexMin=floor(ratio);
    float indexMax=min(indexMin+1,HEATMAP_COLORS_COUNT-1);
    return lerp(colors[indexMin], colors[indexMax], ratio-indexMin);
}

Then in your pixel shader you just output something like:

return HeatMapColor(myValue, 0.00, 50.00);

And can get an idea of how it varies across your pixels:

enter image description here

Of course you can use any set of colors you like.

Java Does Not Equal (!=) Not Working?

Sure, you can use equals if you want to go along with the crowd, but if you really want to amaze your fellow programmers check for inequality like this:

if ("success" != statusCheck.intern())

intern method is part of standard Java String API.

How to reset all checkboxes using jQuery or pure JS?

In some cases the checkbox may be selected by default. If you want to restore default selection rather than set as unselected, compare the defaultChecked property.

$(':checkbox').each(function(i,item){ 
        this.checked = item.defaultChecked; 
}); 

Multiple radio button groups in MVC 4 Razor

Ok here's how I fixed this

My model is a list of categories. Each category contains a list of its subcategories.
with this in mind, every time in the foreach loop, each RadioButton will have its category's ID (which is unique) as its name attribue.
And I also used Html.RadioButton instead of Html.RadioButtonFor.

Here's the final 'working' pseudo-code:

@foreach (var cat in Model.Categories)
{
  //A piece of code & html here
  @foreach (var item in cat.SubCategories)
  {
     @Html.RadioButton(item.CategoryID.ToString(), item.ID)
  }    
}

The result is:

<input name="127" type="radio" value="110">

Please note that I HAVE NOT put all these radio button groups inside a form. And I don't know if this solution will still work properly in a form.

Thanks to all of the people who helped me solve this ;)

How do I remove a single file from the staging area (undo git add)?

My sample:

$ git status
On branch feature/wildfire/VNL-425-update-wrong-translation
Your branch and 'origin/feature/wildfire/VNL-425-update-wrong-translation' have diverged,
and have 4 and 1 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    modified:   ShopBack/Source/Date+Extension.swift
    modified:   ShopBack/Source/InboxData.swift
    modified:   ShopBack/en.lproj/Localizable.strings

As you may notice

> Changes to be committed:
>       (use "git reset HEAD <file>..." to unstage)

Access non-numeric Object properties by index?

"I'm specifically looking to target the index, just like the first example - if it's possible."

No, it isn't possible.

The closest you can get is to get an Array of the object's keys, and use that:

var keys = Object.keys( obj );

...but there's no guarantee that the keys will be returned in the order you defined. So it could end up looking like:

keys[ 0 ];  // 'evenmore'
keys[ 1 ];  // 'something'

How to convert Javascript datetime to C# datetime?

Newtonsoft.Json.JsonConvert.SerializeObject(Convert.ToDateTime(dr[col.ColumnName])).Replace('"', ' ').Trim();

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

How to iterate a loop with index and element in Swift

Starting with Swift 3, it is

for (index, element) in list.enumerated() {
  print("Item \(index): \(element)")
}

I want to get the type of a variable at runtime

i have tested that and it worked

val x = 9
def printType[T](x:T) :Unit = {println(x.getClass.toString())}

Test if a string contains a word in PHP?

<?php
//  Use this function and Pass Mixed string and what you want to search in mixed string.
//  For Example :
    $mixedStr = "hello world. This is john duvey";
    $searchStr= "john";

    if(strpos($mixedStr,$searchStr)) {
      echo "Your string here";
    }else {
      echo "String not here";
    }

Regex for remove everything after | (with | )

If you want to get everything after | excluding set character use this code.

[^|]*$

Others solutions \|.*$

Results : | mypcworld

This one [^|]*$

Results : mypcworld

http://regexr.com/3elkd

Flask Download a File

I was also developing a similar application. I was also getting not found error even though the file was there. This solve my problem. I mention my download folder in 'static_folder':

app = Flask(__name__,static_folder='pdf')

My code for the download is as follows:

@app.route('/pdf/<path:filename>', methods=['GET', 'POST'])
def download(filename):    
    return send_from_directory(directory='pdf', filename=filename)

This is how I am calling my file from html.

<a class="label label-primary" href=/pdf/{{  post.hashVal }}.pdf target="_blank"  style="margin-right: 5px;">Download pdf </a>
<a class="label label-primary" href=/pdf/{{  post.hashVal }}.png target="_blank"  style="margin-right: 5px;">Download png </a>

Joda DateTime to Timestamp conversion

I've solved this problem in this way.

String dateUTC = rs.getString("date"); //UTC
DateTime date;
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").withZoneUTC();
date = dateTimeFormatter.parseDateTime(dateUTC);

In this way you ignore the server TimeZone forcing your chosen TimeZone.

Get the directory from a file path in java (android)

I have got solution on this after 4 days, Please note following points while giving path to File class in Android(Java):

  1. Use path for internal storage String path="/storage/sdcard0/myfile.txt";
  2. path="/storage/sdcard1/myfile.txt";
  3. mention permissions in Manifest file.

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

  4. First check file length for confirmation.
  5. Check paths in ES File Explorer regarding sdcard0 & sdcard1 is this same or else......

e.g.

File file=new File(path);
long=file.length();//in Bytes

error: (-215) !empty() in function detectMultiScale

I ran the same code. There are two things to note here. 1. Give the entire path of the .xml files. 2. Give a key press event instruction at the end.

Add this block of code at the end and run your file, worked for me:

k = cv2.waitKey(0)
if k == 27:         # wait for ESC key to exit
    cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
    cv2.imwrite('messigray.png',img)
    cv2.destroyAllWindows()

For example, my code looked like

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_eye.xml')

img = cv2.imread('lena.jpg')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)
#faces = face_cascade.detectMultiScale(gray)

for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (ex,ey,ew,eh) in eyes:
        cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

cv2.imshow('img',img)

k = cv2.waitKey(0)
if k == 27:         # wait for ESC key to exit
    cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
    cv2.imwrite('messigray.png',img)
    cv2.destroyAllWindows()

My output looked like this:

ouput

How to delete a record by id in Flask-SQLAlchemy

Just want to share another option:

# mark two objects to be deleted
session.delete(obj1)
session.delete(obj2)

# commit (or flush)
session.commit()

http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#deleting

In this example, the following codes shall works fine:

obj = User.query.filter_by(id=123).one()
session.delete(obj)
session.commit()

MAC addresses in JavaScript

If this is for an intranet application and all of the clients use DHCP, you can query the DHCP server for the MAC address for a given IP address.

accessing a docker container from another container

Using docker-compose, services are exposed to each other by name by default. Docs.
You could also specify an alias like;

version: '2.1'
services:
  mongo:
    image: mongo:3.2.11
  redis:
    image: redis:3.2.10
  api:
    image: some-image
    depends_on:
      - mongo
      - solr
    links:
      - "mongo:mongo.openconceptlab.org"
      - "solr:solr.openconceptlab.org"
      - "some-service:some-alias"

And then access the service using the specified alias as a host name, e.g mongo.openconceptlab.org for mongo in this case.

Storing SHA1 hash values in MySQL

I would use VARCHAR for variable length data, but not with fixed length data. Because a SHA-1 value is always 160 bit long, the VARCHAR would just waste an additional byte for the length of the fixed-length field.

And I also wouldn’t store the value the SHA1 is returning. Because it uses just 4 bit per character and thus would need 160/4 = 40 characters. But if you use 8 bit per character, you would only need a 160/8 = 20 character long field.

So I recommend you to use BINARY(20) and the UNHEX function to convert the SHA1 value to binary.

I compared storage requirements for BINARY(20) and CHAR(40).

CREATE TABLE `binary` (
    `id` int unsigned auto_increment primary key,
    `password` binary(20) not null
);
CREATE TABLE `char` (
    `id` int unsigned auto_increment primary key,
    `password` char(40) not null
);

With million of records binary(20) takes 44.56M, while char(40) takes 64.57M. InnoDB engine.

Get Number of Rows returned by ResultSet in Java

        rs.last();
        int rows = rs.getRow();
        rs.beforeFirst();

change background image in body

You would need to use Javascript for this. You can set the style of the background-image for the body like so.

var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(http://localhost/background.png)';

Just make sure you replace the URL with the actual URL.

Application Installation Failed in Android Studio

Allow or enable "Installation from USB" in the developer options.

Calling a method inside another method in same class

It is just an overload. The add method is from the ArrayList class. Look that Staff inherits from it.

How to run a cron job inside a docker container?

There is another way to do it, is to use Tasker, a task runner that has cron (a scheduler) support.

Why ? Sometimes to run a cron job, you have to mix, your base image (python, java, nodejs, ruby) with the crond. That means another image to maintain. Tasker avoid that by decoupling the crond and you container. You can just focus on the image that you want to execute your commands, and configure Tasker to use it.

Here an docker-compose.yml file, that will run some tasks for you

version: "2"

services:
    tasker:
        image: strm/tasker
        volumes:
            - "/var/run/docker.sock:/var/run/docker.sock"
        environment:
            configuration: |
                logging:
                    level:
                        ROOT: WARN
                        org.springframework.web: WARN
                        sh.strm: DEBUG
                schedule:
                    - every: minute
                      task: hello
                    - every: minute
                      task: helloFromPython
                    - every: minute
                      task: helloFromNode
                tasks:
                    docker:
                        - name: hello
                          image: debian:jessie
                          script:
                              - echo Hello world from Tasker
                        - name: helloFromPython
                          image: python:3-slim
                          script:
                              - python -c 'print("Hello world from python")'
                        - name: helloFromNode
                          image: node:8
                          script:
                              - node -e 'console.log("Hello from node")'

There are 3 tasks there, all of them will run every minute (every: minute), and each of them will execute the script code, inside the image defined in image section.

Just run docker-compose up, and see it working. Here is the Tasker repo with the full documentation:

http://github.com/opsxcq/tasker

Executing multi-line statements in the one-line command-line?

this style can be used in makefiles too (and in fact it is used quite often).

python - <<EOF
import sys
for r in range(3): print 'rob'
EOF

or

python - <<-EOF
    import sys
    for r in range(3): print 'rob'
EOF

in latter case leading tab characters are removed too (and some structured outlook can be achieved)

instead of EOF can stand any marker word not appearing in the here document at a beginning of a line (see also here documents in the bash manpage or here).

Using logging in multiple modules

Throwing in another solution.

In my module's init.py I have something like:

# mymodule/__init__.py
import logging

def get_module_logger(mod_name):
  logger = logging.getLogger(mod_name)
  handler = logging.StreamHandler()
  formatter = logging.Formatter(
        '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
  handler.setFormatter(formatter)
  logger.addHandler(handler)
  logger.setLevel(logging.DEBUG)
  return logger

Then in each module I need a logger, I do:

# mymodule/foo.py
from [modname] import get_module_logger
logger = get_module_logger(__name__)

When the logs are missed, you can differentiate their source by the module they came from.

delete word after or around cursor in VIM

The below works for Normal mode: I agree with Dan Olson's answer that you should probably be in normal mode for most deletions. More details below.

If the cursor is inside the word:
diw to delete in the word (doesn't include spaces)
daw to delete around the word (includes spaces before the next word).

If the cursor is at the start of the word, just press dw.

This can be multiplied by adding the usual numbers for movement, e.g. 2w to move forward 2 words, so d2w deletes two words.

Insert Mode ^w
The idea of using hjkl for movement in Vim is that it's more productive to keep your hands on the home row. At the end of a word ^w works great to quickly delete the word. If you've gone into insert mode, entered some text and used the arrow keys to end up in the middle of the word you've gone against the home-row philosophy.
If you're in normal mode and want to change the word you can simply use the c (change) rather than d (delete) if you'd like to completely change the word, and re-enter insert mode without having to press i to get back to typing.

First Heroku deploy failed `error code=H10`

For me it was Package.json it was empty from dependencies even though i thought i did install them.. so I had to reinstall them with --save option in the end and verify they were added to the package.json.. and then push it again and it worked.

How to get the selected radio button value using js

Try this, I hope this one will work

function loadRadioButton(objectName, selectedValue) {

    var radioButtons = document.getElementsByName(objectName);

    if (radioButtons != null) {
        for (var radioCount = 0; radioCount < radioButtons.length; radioCount++) {
            if (radioButtons[radioCount].value == selectedValue) {
                radioButtons[radioCount].checked = true;
            }
        }
    }
}

Printing with sed or awk a line following a matching pattern

It's the line after that match that you're interesting in, right? In sed, that could be accomplished like so:

sed -n '/ABC/{n;p}' infile

Alternatively, grep's A option might be what you're looking for.

-A NUM, Print NUM lines of trailing context after matching lines.

For example, given the following input file:

foo
bar
baz
bash
bongo

You could use the following:

$ grep -A 1 "bar" file
bar
baz
$ sed -n '/bar/{n;p}' file
baz

Hope that helps.

How do I assign a port mapping to an existing Docker container?

I'm also interested in this problem.

As @Thasmo mentioned, port forwardings can be specified ONLY with docker run (and docker create) command.
Other commands, docker start does not have -p option and docker port only displays current forwardings.

To add port forwardings, I always follow these steps,

  1. stop running container

    docker stop test01
    
  2. commit the container

    docker commit test01 test02
    

    NOTE: The above, test02 is a new image that I'm constructing from the test01 container.

  3. re-run from the commited image

    docker run -p 8080:8080 -td test02
    

Where the first 8080 is the local port and the second 8080 is the container port.

Using OR in SQLAlchemy

or_() function can be useful in case of unknown number of OR query components.

For example, let's assume that we are creating a REST service with few optional filters, that should return record if any of filters return true. On the other side, if parameter was not defined in a request, our query shouldn't change. Without or_() function we must do something like this:

query = Book.query
if filter.title and filter.author:
    query = query.filter((Book.title.ilike(filter.title))|(Book.author.ilike(filter.author)))
else if filter.title:
    query = query.filter(Book.title.ilike(filter.title))
else if filter.author:
    query = query.filter(Book.author.ilike(filter.author))

With or_() function it can be rewritten to:

query = Book.query
not_null_filters = []
if filter.title:
    not_null_filters.append(Book.title.ilike(filter.title))
if filter.author:
    not_null_filters.append(Book.author.ilike(filter.author))

if len(not_null_filters) > 0:
    query = query.filter(or_(*not_null_filters))

How should I escape strings in JSON?

If you are using fastexml jackson, you can use the following: com.fasterxml.jackson.core.io.JsonStringEncoder.getInstance().quoteAsString(input)

If you are using codehaus jackson, you can use the following: org.codehaus.jackson.io.JsonStringEncoder.getInstance().quoteAsString(input)

Define preprocessor macro through CMake?

For a long time, CMake had the add_definitions command for this purpose. However, recently the command has been superseded by a more fine grained approach (separate commands for compile definitions, include directories, and compiler options).

An example using the new add_compile_definitions:

add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION})
add_compile_definitions(WITH_OPENCV2)

Or:

add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION} WITH_OPENCV2)

The good part about this is that it circumvents the shabby trickery CMake has in place for add_definitions. CMake is such a shabby system, but they are finally finding some sanity.

Find more explanation on which commands to use for compiler flags here: https://cmake.org/cmake/help/latest/command/add_definitions.html

Likewise, you can do this per-target as explained in Jim Hunziker's answer.

ggplot with 2 y axes on each side and different scales

I acknowledge and agree with hadley (and others), that separate y-scales are "fundamentally flawed". Having said that – I often wish ggplot2 had the feature – particularly, when the data is in wide-format and I quickly want to visualise or check the data (i.e. for personal use only).

While the tidyverse library makes it fairly easy to convert the data to long-format (such that facet_grid() will work), the process is still not trivial, as seen below:

library(tidyverse)
df.wide %>%
    # Select only the columns you need for the plot.
    select(date, column1, column2, column3) %>%
    # Create an id column – needed in the `gather()` function.
    mutate(id = n()) %>%
    # The `gather()` function converts to long-format. 
    # In which the `type` column will contain three factors (column1, column2, column3),
    # and the `value` column will contain the respective values.
    # All the while we retain the `id` and `date` columns.
    gather(type, value, -id, -date) %>%
    # Create the plot according to your specifications
    ggplot(aes(x = date, y = value)) +
        geom_line() +
        # Create a panel for each `type` (ie. column1, column2, column3).
        # If the types have different scales, you can use the `scales="free"` option.
        facet_grid(type~., scales = "free")

How to get the size of a file in MB (Megabytes)?

You can use FileChannel in Java.

FileChannel has the size() method to determine the size of the file.

    String fileName = "D://words.txt";

    Path filePath = Paths.get(fileName);

    FileChannel fileChannel = FileChannel.open(filePath);
    long fileSize = fileChannel.size();

    System.out.format("The size of the file: %d bytes", fileSize);

Or you can determine the file size using Apache Commons' FileUtils' sizeOf() method. If you are using maven, add this to pom.xml file.

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

Try the following coding,

    String fileName = "D://words.txt";
    File f = new File(fileName);

    long fileSize = FileUtils.sizeOf(f);        

    System.out.format("The size of the file: %d bytes", fileSize);

These methods will output the size in Bytes. So to get the MB size, you need to divide the file size from (1024*1024).

Now you can simply use the if-else conditions since the size is captured in MB.

Manifest merger failed : uses-sdk:minSdkVersion 14

In Android Studio 1.1.0: File - Project Structure - Tab Flavors - Select Min SDK Version which is higher than in Manifest

Clear text from textarea with selenium

In my experience, this turned out to be the most efficient

driver.find_element_by_css_selector('foo').send_keys(u'\ue009' + u'\ue003')

We are sending Ctrl + Backspace to delete all characters from the input, you can also replace backspace with delete.

EDIT: removed Keys dependency

How to show and update echo on same line

You can try this.. My own version of it..

funcc() {
while true ; do 
for i in \| \/ \- \\ \| \/ \- \\; do 
  echo -n -e "\r$1  $i  "
sleep 0.5
done  
#echo -e "\r                                                                                      "
[ -f /tmp/print-stat ] && break 2
done
}

funcc "Checking Kubectl" & &>/dev/null
sleep 5
touch /tmp/print-stat
echo -e "\rPrint Success                  "

Node update a specific package

Always you can do it manually. Those are the steps:

  • Go to the NPM package page, and search for the GitHub link.
  • Now download the latest version using GitHub download link, or by clonning. git clone github_url
  • Copy the package to your node_modules folder for e.g. node_modules/browser-sync

Now it should work for you. To be sure it will not break in the future when you do npm i, continue the upcoming two steps:

  • Check the version of the new package by reading the package.json file in it's folder.
  • Open your project package.json and set the same version for where it's appear in the dependencies part of your package.json

While it's not recommened to do it manually. Sometimes it's good to understand how things are working under the hood, to be able to fix things. I found myself doing it from time to time.

download a file from Spring boot rest service

I would suggest using a StreamingResponseBody since with it the application can write directly to the response (OutputStream) without holding up the Servlet container thread. It is a good approach if you are downloading a file very large.

@GetMapping("download")
public StreamingResponseBody downloadFile(HttpServletResponse response, @PathVariable Long fileId) {

    FileInfo fileInfo = fileService.findFileInfo(fileId);
    response.setContentType(fileInfo.getContentType());
    response.setHeader(
        HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + fileInfo.getFilename() + "\"");

    return outputStream -> {
        int bytesRead;
        byte[] buffer = new byte[BUFFER_SIZE];
        InputStream inputStream = fileInfo.getInputStream();
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
    };
}

Ps.: When using StreamingResponseBody, it is highly recommended to configure TaskExecutor used in Spring MVC for executing asynchronous requests. TaskExecutor is an interface that abstracts the execution of a Runnable.

More info: https://medium.com/swlh/streaming-data-with-spring-boot-restful-web-service-87522511c071

How to apply an XSLT Stylesheet in C#

Based on Daren's excellent answer, note that this code can be shortened significantly by using the appropriate XslCompiledTransform.Transform overload:

var myXslTrans = new XslCompiledTransform(); 
myXslTrans.Load("stylesheet.xsl"); 
myXslTrans.Transform("source.xml", "result.html"); 

(Sorry for posing this as an answer, but the code block support in comments is rather limited.)

In VB.NET, you don't even need a variable:

With New XslCompiledTransform()
    .Load("stylesheet.xsl")
    .Transform("source.xml", "result.html")
End With

How to get memory available or used in C#

You can use:

Process proc = Process.GetCurrentProcess();

To get the current process and use:

proc.PrivateMemorySize64;

To get the private memory usage. For more information look at this link.

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

Just add those below line in pom.xml file on the top of <modelversion> tag:

<repositories>
  <repository>
    <id>central</id>
    <name>Central Repository</name>
    <url>http://repo.maven.apache.org/maven2</url>
    <layout>default</layout>
    <snapshots>
      <enabled>false</enabled>
    </snapshots>
  </repository>
</repositories>

CSS Selector "(A or B) and C"?

Not yet, but there is the experimental :matches() pseudo-class function that does just that:

:matches(.a .b) .c {
  /* stuff goes here */
}

You can find more info on it here and here. Currently, most browsers support its initial version :any(), which works the same way, but will be replaced by :matches(). We just have to wait a little more before using this everywhere (I surely will).

Convert date to day name e.g. Mon, Tue, Wed

Very Simply Short week day name with Month and year

echo date('D, d-M-y');

output

Tue, 16-Feb-21

as per my requirements

return $item->start_time->format("D, d-M");

output

Tue, 16-Feb