Programs & Examples On #Recycle

Can I use library that used android support with Androidx projects.

Comment This Line in gradle.properties

android.useAndroidX=true

error: resource android:attr/fontVariationSettings not found

@All the issue is because of the latest major breaking changes in the google play service and firebase June 17, 2019 release.

If you are on Ionic or Cordova project. Please go through all the plugins where it has dependency google play service and firebase service with + mark

Example:

In my firebase cordova integration I had com.google.firebase:firebase-core:+ com.google.firebase:firebase-messaging:+ So the plus always downloading the latest release which was causing error. Change + with version number as per the March 15, 2019 release https://developers.google.com/android/guides/releases

Make sure to replace + symbols with actual version in build.gradle file of cordova library

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

Try updating your buildToolVersion to 27.0.2 instead of 27.0.3

The error probably occurring because of compatibility issue with build tools

Android Studio 3.0 Execution failed for task: unable to merge dex

I also got the similar error.

Problem :

enter image description here

Solution :

Main root cause for this issue ismultiDex is not enabled. So in the Project/android/app/build.gradle, enable the multiDex

For further information refer the documentation: https://developer.android.com/studio/build/multidex#mdex-gradle

enter image description here

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

I moved implementation to module-level build.gradle from root-level build.gradle. It solves the issue.

No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0

I had the same issue with my Ionic 2 project, all I did to resolved the issues was

  • Open "ionic_project_folder/platforms/android/project.properties"
  • Change target=android-25 to target=android-26
  • Run ionic build --release android

Hope this helps someone!

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

May be this problem is due to facebook library. Replace

compile 'com.facebook.android:facebook-android-sdk:[4,5)'

by

compile 'com.facebook.android:facebook-android-sdk:4.26.0'

Setting up Gradle for api 26 (Android)

Appears to be resolved by Android Studio 3.0 Canary 4 and Gradle 3.0.0-alpha4.

All com.android.support libraries must use the exact same version specification

implementation 'com.android.support:appcompat-v7:26.1.0'

after this line You have to add new Line in your gradle

implementation 'com.android.support:design:26.1.0'

CardView background color always white

XML code

<android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view_top"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:cardCornerRadius="5dp"
        app:contentPadding="25dp"
        app:cardBackgroundColor="#e4bfef"
        app:cardElevation="4dp"
        app:cardMaxElevation="6dp" />

From the code

CardView card = findViewById(R.id.card_view_top);
card.setCardBackgroundColor(Color.parseColor("#E6E6E6"));

Restore a deleted file in the Visual Studio Code Recycle Bin

Just look up the files you deleted, inside Recycle Bin. Right click on it and do restore as you do normally with other deleted files. It is similar as you do normally because VS code also uses normal trash of your system.

Changing background color of selected item in recyclerview

Create Drawable file in Drawable foloder

<item android:drawable="@color/SelectedColor" android:state_pressed="true"></item>
<item android:drawable="@color/SelectedColor" android:state_selected="true"></item>
<item android:drawable="@color/DefultColor"></item>

And in xml file

android:background="@drawable/Drawable file"

In RecyclerView onBindViewHolder

holder.button.setSelected(holder.button.isSelected()?true:false);

Like toggle button

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

This is a simple way from XML only

spanCount for number of columns

layoutManager for making it grid or linear(Vertical or Horizontal)

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/personListRecyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:spanCount="2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Simple Android RecyclerView example

Now you need 1 adapter for all RecyclerView

  • One adapter can be used in for all RecyclerView. So NO onBindViewHolder, No onCreateViewHolder handling.
  • No code for setting adapter from Java/Kotlin class. Check sample class.
  • You can set events and custom data for every list by using Binding Adapters.

screenshot

I show here setting two different RecyclerView by 1 adapter -

activity_home.xml

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

    <data>

        <variable
            name="listOne"
            type="java.util.List"/>

        <variable
            name="listTwo"
            type="java.util.List"/>

        <variable
            name="onItemClickListenerOne"
            type="com.ks.nestedrecyclerbindingexample.callbacks.OnItemClickListener"/>

        <variable
            name="onItemClickListenerTwo"
            type="com.ks.nestedrecyclerbindingexample.callbacks.OnItemClickListener"/>

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.RecyclerView
            rvItemLayout="@{@layout/row_one}"
            rvList="@{listOne}"
            rvOnItemClick="@{onItemClickListenerOne}"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layoutManager="android.support.v7.widget.LinearLayoutManager"
            />

        <android.support.v7.widget.RecyclerView
            rvItemLayout="@{@layout/row_two}"
            rvList="@{listTwo}"
            rvOnItemClick="@{onItemClickListenerTwo}"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layoutManager="android.support.v7.widget.LinearLayoutManager"
            />

    </LinearLayout>

</layout>

You can see I pass list, item layout id and click listener from layout.

rvItemLayout="@{@layout/row_one}"
rvList="@{listOne}"
rvOnItemClick="@{onItemClickListenerOne}"

This custom attributes are created by BindingAdapter.

public class BindingAdapters {
    @BindingAdapter(value = {"rvItemLayout", "rvList", "rvOnItemClick"}, requireAll = false)
    public static void setRvAdapter(RecyclerView recyclerView, int rvItemLayout, List rvList, @Nullable OnItemClickListener onItemClickListener) {
        if (rvItemLayout != 0 && rvList != null && rvList.size() > 0)
            recyclerView.setAdapter(new GeneralAdapter(rvItemLayout, rvList, onItemClickListener));
    }
}

Now from Activity, you pass list, click listener like

HomeActivity.java

public class HomeActivity extends AppCompatActivity {
    ActivityHomeBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_home);
        binding.setListOne(new ArrayList()); // pass your list or set list from response of API
        binding.setListTwo(new ArrayList());
        binding.setOnItemClickListenerOne(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object object) {
                if (object instanceof ModelParent) {
                    // TODO: your action here
                }
            }
        });
        binding.setOnItemClickListenerTwo(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object object) {
                if (object instanceof ModelChild) {
                    // TODO: your action here  
                }
            }
        });
    }
}

You don't want read too much, directly clone/download full example on from my github repo. And try it yourself.

You can see GeneralAdapter.java in above repo.

If you have problems while setting up data binding, please see this answer.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

There was an error in understanding of return Type Just add Header and it will solve your problem

@Headers("Content-Type: application/json")

Android Horizontal RecyclerView scroll Direction

You can do it with just xml.

the app:reverseLayout="true" do the job!

<android.support.v7.widget.RecyclerView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:divider="@null"
                        android:orientation="horizontal"
                        app:reverseLayout="true"
                        app:layoutManager="android.support.v7.widget.LinearLayoutManager" />

Margin between items in recycler view Android

Use CardView in Recyclerview Item Layout like this :

 <android.support.v7.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:card_view="http://schemas.android.com/tools"
        card_view:cardCornerRadius="10dp"
        app:cardBackgroundColor="#ACACAC"
        card_view:cardElevation="5dp"
        app:contentPadding="10dp"
        card_view:cardUseCompatPadding="true">

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

My Settings Screenshot: image

Thanks to this post.

Just turn off instant run in your settings. You can easily search the keyword "instant" like I showed and it would switch to the window you want.

The number of method references in a .dex file cannot exceed 64k API 17

Can also try this :

android{
    .
    .
    // to avoid DexIndexOverflowException
    dexOptions {
       jumboMode true
    }
}

Hope it helps someone. Thanks

Execution failed for task ':app:processDebugResources' even with latest build tools

I changed the target=android-26 to target=android-23

project.properties

this works great for me.

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

In DefaultConfig Add multiDexEnabled = true

    defaultConfig {
    applicationId "com.test"
    minSdkVersion 16
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    multiDexEnabled = true
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

For me I think there might be some issue in installing android NDK from android studio. I was able to resolve this in following manner

Downloaded android ndk from

https://developer.android.com/ndk/downloads/index.html

and placed inside ndk-bundle (where your android sdk is installed ). For more info check this screens.

https://app.box.com/s/dfi4h9k7v4h0tmbu3z9qnqx3d12fdejn

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

check that, in your "google-services.json" file your package_name is available or not

How to add a recyclerView inside another recyclerView

I would like to suggest to use a single RecyclerView and populate your list items dynamically. I've added a github project to describe how this can be done. You might have a look. While the other solutions will work just fine, I would like to suggest, this is a much faster and efficient way of showing multiple lists in a RecyclerView.

The idea is to add logic in your onCreateViewHolder and onBindViewHolder method so that you can inflate proper view for the exact positions in your RecyclerView.

I've added a sample project along with that wiki too. You might clone and check what it does. For convenience, I am posting the adapter that I have used.

public class DynamicListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int FOOTER_VIEW = 1;
    private static final int FIRST_LIST_ITEM_VIEW = 2;
    private static final int FIRST_LIST_HEADER_VIEW = 3;
    private static final int SECOND_LIST_ITEM_VIEW = 4;
    private static final int SECOND_LIST_HEADER_VIEW = 5;

    private ArrayList<ListObject> firstList = new ArrayList<ListObject>();
    private ArrayList<ListObject> secondList = new ArrayList<ListObject>();

    public DynamicListAdapter() {
    }

    public void setFirstList(ArrayList<ListObject> firstList) {
        this.firstList = firstList;
    }

    public void setSecondList(ArrayList<ListObject> secondList) {
        this.secondList = secondList;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        // List items of first list
        private TextView mTextDescription1;
        private TextView mListItemTitle1;

        // List items of second list
        private TextView mTextDescription2;
        private TextView mListItemTitle2;

        // Element of footer view
        private TextView footerTextView;

        public ViewHolder(final View itemView) {
            super(itemView);

            // Get the view of the elements of first list
            mTextDescription1 = (TextView) itemView.findViewById(R.id.description1);
            mListItemTitle1 = (TextView) itemView.findViewById(R.id.title1);

            // Get the view of the elements of second list
            mTextDescription2 = (TextView) itemView.findViewById(R.id.description2);
            mListItemTitle2 = (TextView) itemView.findViewById(R.id.title2);

            // Get the view of the footer elements
            footerTextView = (TextView) itemView.findViewById(R.id.footer);
        }

        public void bindViewSecondList(int pos) {

            if (firstList == null) pos = pos - 1;
            else {
                if (firstList.size() == 0) pos = pos - 1;
                else pos = pos - firstList.size() - 2;
            }

            final String description = secondList.get(pos).getDescription();
            final String title = secondList.get(pos).getTitle();

            mTextDescription2.setText(description);
            mListItemTitle2.setText(title);
        }

        public void bindViewFirstList(int pos) {

            // Decrease pos by 1 as there is a header view now.
            pos = pos - 1;

            final String description = firstList.get(pos).getDescription();
            final String title = firstList.get(pos).getTitle();

            mTextDescription1.setText(description);
            mListItemTitle1.setText(title);
        }

        public void bindViewFooter(int pos) {
            footerTextView.setText("This is footer");
        }
    }

    public class FooterViewHolder extends ViewHolder {
        public FooterViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class FirstListHeaderViewHolder extends ViewHolder {
        public FirstListHeaderViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class FirstListItemViewHolder extends ViewHolder {
        public FirstListItemViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class SecondListHeaderViewHolder extends ViewHolder {
        public SecondListHeaderViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class SecondListItemViewHolder extends ViewHolder {
        public SecondListItemViewHolder(View itemView) {
            super(itemView);
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v;

        if (viewType == FOOTER_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_footer, parent, false);
            FooterViewHolder vh = new FooterViewHolder(v);
            return vh;

        } else if (viewType == FIRST_LIST_ITEM_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_first_list, parent, false);
            FirstListItemViewHolder vh = new FirstListItemViewHolder(v);
            return vh;

        } else if (viewType == FIRST_LIST_HEADER_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_first_list_header, parent, false);
            FirstListHeaderViewHolder vh = new FirstListHeaderViewHolder(v);
            return vh;

        } else if (viewType == SECOND_LIST_HEADER_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_second_list_header, parent, false);
            SecondListHeaderViewHolder vh = new SecondListHeaderViewHolder(v);
            return vh;

        } else {
            // SECOND_LIST_ITEM_VIEW
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_second_list, parent, false);
            SecondListItemViewHolder vh = new SecondListItemViewHolder(v);
            return vh;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        try {
            if (holder instanceof SecondListItemViewHolder) {
                SecondListItemViewHolder vh = (SecondListItemViewHolder) holder;
                vh.bindViewSecondList(position);

            } else if (holder instanceof FirstListHeaderViewHolder) {
                FirstListHeaderViewHolder vh = (FirstListHeaderViewHolder) holder;

            } else if (holder instanceof FirstListItemViewHolder) {
                FirstListItemViewHolder vh = (FirstListItemViewHolder) holder;
                vh.bindViewFirstList(position);

            } else if (holder instanceof SecondListHeaderViewHolder) {
                SecondListHeaderViewHolder vh = (SecondListHeaderViewHolder) holder;

            } else if (holder instanceof FooterViewHolder) {
                FooterViewHolder vh = (FooterViewHolder) holder;
                vh.bindViewFooter(position);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {

        int firstListSize = 0;
        int secondListSize = 0;

        if (secondList == null && firstList == null) return 0;

        if (secondList != null)
            secondListSize = secondList.size();
        if (firstList != null)
            firstListSize = firstList.size();

        if (secondListSize > 0 && firstListSize > 0)
            return 1 + firstListSize + 1 + secondListSize + 1;   // first list header, first list size, second list header , second list size, footer
        else if (secondListSize > 0 && firstListSize == 0)
            return 1 + secondListSize + 1;                       // second list header, second list size, footer
        else if (secondListSize == 0 && firstListSize > 0)
            return 1 + firstListSize;                            // first list header , first list size
        else return 0;
    }

    @Override
    public int getItemViewType(int position) {

        int firstListSize = 0;
        int secondListSize = 0;

        if (secondList == null && firstList == null)
            return super.getItemViewType(position);

        if (secondList != null)
            secondListSize = secondList.size();
        if (firstList != null)
            firstListSize = firstList.size();

        if (secondListSize > 0 && firstListSize > 0) {
            if (position == 0) return FIRST_LIST_HEADER_VIEW;
            else if (position == firstListSize + 1)
                return SECOND_LIST_HEADER_VIEW;
            else if (position == secondListSize + 1 + firstListSize + 1)
                return FOOTER_VIEW;
            else if (position > firstListSize + 1)
                return SECOND_LIST_ITEM_VIEW;
            else return FIRST_LIST_ITEM_VIEW;

        } else if (secondListSize > 0 && firstListSize == 0) {
            if (position == 0) return SECOND_LIST_HEADER_VIEW;
            else if (position == secondListSize + 1) return FOOTER_VIEW;
            else return SECOND_LIST_ITEM_VIEW;

        } else if (secondListSize == 0 && firstListSize > 0) {
            if (position == 0) return FIRST_LIST_HEADER_VIEW;
            else return FIRST_LIST_ITEM_VIEW;
        }

        return super.getItemViewType(position);
    }
}

There is another way of keeping your items in a single ArrayList of objects so that you can set an attribute tagging the items to indicate which item is from first list and which one belongs to second list. Then pass that ArrayList into your RecyclerView and then implement the logic inside adapter to populate them dynamically.

Hope that helps.

android : Error converting byte to dex

In my case, using :

enter image description here

I had the issue during transformClassesWithDexFor when the maximum heap size for the Gradle daemon is superior to 4Go. By changing my ~/gradle.properties with org.gradle.jvmargs=-Xmx2048m (meaning I reduce the heap size to 2Go instead of 4Go) the dex then runs in a separate process and I no longer have the issue.

14:52:26.412 [WARN] [org.gradle.api.Project]

Running dex as a separate process.

To run dex in process, the Gradle daemon needs a larger heap.

It currently has 2048 MB.

For faster builds, increase the maximum heap size for the Gradle daemon to at least 4608 MB (based on the dexOptions.javaMaxHeapSize = 4g).

To do this set org.gradle.jvmargs=-Xmx4608M in the project gradle.properties.

RecyclerView - Get view at particular position

You can use use both

recyclerViewInstance.findViewHolderForAdapterPosition(adapterPosition) and recyclerViewInstance.findViewHolderForLayoutPosition(layoutPosition). Be sure that RecyclerView view uses two type of positions

Adapter position : Position of an item in the adapter. This is the position from the Adapter's perspective. Layout position : Position of an item in the latest layout calculation. This is the position from the LayoutManager's perspective. You should use getAdapterPosition() for findViewHolderForAdapterPosition(adapterPosition) and getLayoutPosition() for findViewHolderForLayoutPosition(layoutPosition).

Take a member variable to hold previously selected item position in recyclerview adapter and other member variable to check whether user is clicking for first time or not.

Sample code and screen shots are attached for more information at the bottom.

public class MainActivity extends AppCompatActivity {     

private RecyclerView mRecyclerList = null;    
private RecyclerAdapter adapter = null;    

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

    mRecyclerList = (RecyclerView) findViewById(R.id.recyclerList);    
}    

@Override    
protected void onStart() {    
    RecyclerView.LayoutManager layoutManager = null;    
    String[] daysArray = new String[15];    
    String[] datesArray = new String[15];    

    super.onStart();    
    for (int i = 0; i < daysArray.length; i++){    
        daysArray[i] = "Sunday";    
        datesArray[i] = "12 Feb 2017";    
    }    

    adapter = new RecyclerAdapter(mRecyclerList, daysArray, datesArray);    
    layoutManager = new LinearLayoutManager(MainActivity.this);    
    mRecyclerList.setAdapter(adapter);    
    mRecyclerList.setLayoutManager(layoutManager);    
}    
}    


public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyCardViewHolder>{          

private final String TAG = "RecyclerAdapter";        
private Context mContext = null;        
private TextView mDaysTxt = null, mDateTxt = null;    
private LinearLayout mDateContainerLayout = null;    
private String[] daysArray = null, datesArray = null;    
private RecyclerView mRecyclerList = null;    
private int previousPosition = 0;    
private boolean flagFirstItemSelected = false;    

public RecyclerAdapter(RecyclerView mRecyclerList, String[] daysArray, String[] datesArray){    
    this.mRecyclerList = mRecyclerList;    
    this.daysArray = daysArray;    
    this.datesArray = datesArray;    
}    

@Override    
public MyCardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {    
    LayoutInflater layoutInflater = null;    
    View view = null;    
    MyCardViewHolder cardViewHolder = null;    
    mContext = parent.getContext();    
    layoutInflater = LayoutInflater.from(mContext);    
    view = layoutInflater.inflate(R.layout.date_card_row, parent, false);    
    cardViewHolder = new MyCardViewHolder(view);    
    return cardViewHolder;    
}    

@Override    
public void onBindViewHolder(MyCardViewHolder holder, final int position) {    
    mDaysTxt = holder.mDaysTxt;    
    mDateTxt = holder.mDateTxt;    
    mDateContainerLayout = holder.mDateContainerLayout;    

    mDaysTxt.setText(daysArray[position]);    
    mDateTxt.setText(datesArray[position]);    

    if (!flagFirstItemSelected){    
        mDateContainerLayout.setBackgroundColor(Color.GREEN);    
        flagFirstItemSelected = true;    
    }else {    
        mDateContainerLayout.setBackground(null);    
    }    
}    

@Override    
public int getItemCount() {    
    return daysArray.length;    
}    

class MyCardViewHolder extends RecyclerView.ViewHolder{    
    TextView mDaysTxt = null, mDateTxt = null;    
    LinearLayout mDateContainerLayout = null;    
    LinearLayout linearLayout = null;    
    View view = null;    
    MyCardViewHolder myCardViewHolder = null;    

    public MyCardViewHolder(View itemView) {    
        super(itemView);    
        mDaysTxt = (TextView) itemView.findViewById(R.id.daysTxt);    
        mDateTxt = (TextView) itemView.findViewById(R.id.dateTxt);    
        mDateContainerLayout = (LinearLayout) itemView.findViewById(R.id.dateContainerLayout);    

        mDateContainerLayout.setOnClickListener(new View.OnClickListener() {    
            @Override    
            public void onClick(View v) {    
                LinearLayout linearLayout = null;    
                View view = null;    

                if (getAdapterPosition() == previousPosition){    
                    view = mRecyclerList.findViewHolderForAdapterPosition(previousPosition).itemView;    
                    linearLayout = (LinearLayout) view.findViewById(R.id.dateContainerLayout);    
                    linearLayout.setBackgroundColor(Color.GREEN);    
                    previousPosition = getAdapterPosition();    

                }else {    
                    view = mRecyclerList.findViewHolderForAdapterPosition(previousPosition).itemView;    
                    linearLayout = (LinearLayout) view.findViewById(R.id.dateContainerLayout);    
                    linearLayout.setBackground(null);    

                    view = mRecyclerList.findViewHolderForAdapterPosition(getAdapterPosition()).itemView;    
                    linearLayout = (LinearLayout) view.findViewById(R.id.dateContainerLayout);    
                    linearLayout.setBackgroundColor(Color.GREEN);    
                    previousPosition = getAdapterPosition();    
                }    
            }    
        });    
    }    
}       

} first element selected second element selected and previously selected item becomes unselected fifth element selected and previously selected item becomes unselected

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

in build file change compile files('AF-Android-SDK.jar') to compile files('libs/AF-Android-SDK.jar') it will work

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

Project Rebuild solved my problem.

In Android studio in the toolbar.. Build>Rebuild Project.

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

All the above not working for me.. Because I am using Facebook Ad dependency..

Incase If anybody using this dependency compile 'com.facebook.android:audience-network-sdk:4.16.0'

Try this code instead of above

compile ('com.facebook.android:audience-network-sdk:4.16.0'){
exclude group: 'com.google.android.gms'
}

Recyclerview inside ScrollView not scrolling smoothly

If you are using VideoView or heavy weight widgets in your childviews keep your RecyclerView with height wrap_content inside a NestedScrollView with height match_parent Then scrolling will work smooth as perfectly as you want it.

FYI,

<android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:nestedScrollingEnabled="false"
            android:layout_height="wrap_content"
            android:clipToPadding="false" />

</android.support.v4.widget.NestedScrollView>

Thanks Micro this was from your hint!

karthik

Add views below toolbar in CoordinatorLayout

I managed to fix this by adding:

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

to the FrameLayout like so:

 <FrameLayout
        android:id="@+id/content"
        android:layout_marginTop="?android:attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       />

How can I make sticky headers in RecyclerView? (Without external lib)

Yo,

This is how you do it if you want just one type of holder stick when it starts getting out of the screen (we are not caring about any sections). There is only one way without breaking the internal RecyclerView logic of recycling items and that is to inflate additional view on top of the recyclerView's header item and pass data into it. I'll let the code speak.

import android.graphics.Canvas
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView

class StickyHeaderItemDecoration(@LayoutRes private val headerId: Int, private val HEADER_TYPE: Int) : RecyclerView.ItemDecoration() {

private lateinit var stickyHeaderView: View
private lateinit var headerView: View

private var sticked = false

// executes on each bind and sets the stickyHeaderView
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
    super.getItemOffsets(outRect, view, parent, state)

    val position = parent.getChildAdapterPosition(view)

    val adapter = parent.adapter ?: return
    val viewType = adapter.getItemViewType(position)

    if (viewType == HEADER_TYPE) {
        headerView = view
    }
}

override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
    super.onDrawOver(c, parent, state)
    if (::headerView.isInitialized) {

        if (headerView.y <= 0 && !sticked) {
            stickyHeaderView = createHeaderView(parent)
            fixLayoutSize(parent, stickyHeaderView)
            sticked = true
        }

        if (headerView.y > 0 && sticked) {
            sticked = false
        }

        if (sticked) {
            drawStickedHeader(c)
        }
    }
}

private fun createHeaderView(parent: RecyclerView) = LayoutInflater.from(parent.context).inflate(headerId, parent, false)

private fun drawStickedHeader(c: Canvas) {
    c.save()
    c.translate(0f, Math.max(0f, stickyHeaderView.top.toFloat() - stickyHeaderView.height.toFloat()))
    headerView.draw(c)
    c.restore()
}

private fun fixLayoutSize(parent: ViewGroup, view: View) {

    // Specs for parent (RecyclerView)
    val widthSpec = View.MeasureSpec.makeMeasureSpec(parent.width, View.MeasureSpec.EXACTLY)
    val heightSpec = View.MeasureSpec.makeMeasureSpec(parent.height, View.MeasureSpec.UNSPECIFIED)

    // Specs for children (headers)
    val childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec, parent.paddingLeft + parent.paddingRight, view.getLayoutParams().width)
    val childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec, parent.paddingTop + parent.paddingBottom, view.getLayoutParams().height)

    view.measure(childWidthSpec, childHeightSpec)

    view.layout(0, 0, view.measuredWidth, view.measuredHeight)
}

}

And then you just do this in your adapter:

override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
    super.onAttachedToRecyclerView(recyclerView)
    recyclerView.addItemDecoration(StickyHeaderItemDecoration(R.layout.item_time_filter, YOUR_STICKY_VIEW_HOLDER_TYPE))
}

Where YOUR_STICKY_VIEW_HOLDER_TYPE is viewType of your what is supposed to be sticky holder.

How to update/refresh specific item in RecyclerView

In your adapter class, in onBindViewHolder method, set ViewHolder to setIsRecyclable(false) as in below code.

@Override
public void onBindViewHolder(RecyclerViewAdapter.ViewHolder p1, int p2)
{
    // TODO: Implement this method
    p1.setIsRecyclable(false);

    // Then your other codes
}

CheckBox in RecyclerView keeps on checking different items

What worked for me is to nullify the listeners on the viewHolder when the view is going to be recycled (onViewRecycled):

 override fun onViewRecycled(holder: AttendeeViewHolder) {
            super.onViewRecycled(holder)
            holder.itemView.hasArrived.setOnCheckedChangeListener(null);
            holder.itemView.edit.setOnClickListener { null }
        }

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

I suppose you want to use this image as an icon. As Android is telling you, your image is too large. What you just need to do is scale your image so that Android knows which size of the image to use and when according to screen resolution. To accomplish this, in Android Studio: 1. right click on the res folder, 2. select Image Asset 3. Select icon Type 4. Give the icon a name 5. Select Image on Asset Type 6. Trim your image Click next and finish. In your xml or source code just refer to the image which will now be located either in the layout or mipmap folder according to asset type selected. The error will go away.

How to get a context in a recycler view adapter

You can define:

Context ctx; 

And on onCreate initialise ctx to:

ctx=parent.getContext(); 

Note: Parent is a ViewGroup.

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

I ran into the same problem when I have update data while the RecyclerView is scrolling. And I fixed it with the following solution:

  1. Stop scroll our RecyclerView before update data.
  2. Custom layout manager likes with the preceding answer.
  3. Use DiffUtils to ensure updating data is correct.

How to update RecyclerView Adapter Data?

I found out that a really simple way to reload the RecyclerView is to just call

recyclerView.removeAllViews();

This will first remove all content of the RecyclerView and then add it again with the updated values.

How can a divider line be added in an Android RecyclerView?

  class ItemOffsetDecoration(
        context: Context,
        private val paddingLeft: Int,
        private val paddingRight: Int
    ) : RecyclerView.ItemDecoration() {
        private var mDivider: Drawable? = null

        init {
            mDivider = ContextCompat.getDrawable(context, R.drawable.divider_medium)
        }

        override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
            val left = parent.paddingLeft + paddingLeft
            val right = parent.width - parent.paddingRight - paddingRight
            val childCount = parent.childCount
            for (i in 0 until childCount) {
                val child = parent.getChildAt(i)
                val params = child.layoutParams as RecyclerView.LayoutParams
                val top = child.bottom + params.bottomMargin
                val bottom = top + (mDivider?.intrinsicHeight ?: 0)

                mDivider?.let {
                    it.setBounds(left, top, right, bottom)
                    it.draw(c)
                }
            }
        }
    }

You just need to specify a color in R.drawable.divider_medium

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/black" />
    <size
        android:height="1dp"
        android:width="1dp" />

</shape>

and add it to your recyclerView

recyclerView.addItemDecoration(
                        ItemOffsetDecoration(
                            this,
                            resources.getDimension(resources.getDimension(R.dimen.dp_70).roundToInt()).roundToInt(),
                            0
                        )
                    )

refernce this

RecyclerView - How to smooth scroll to top of item on a certain position?

I want to more fully address the issue of scroll duration, which, should you choose any earlier answer, will in fact will vary dramatically (and unacceptably) according to the amount of scrolling necessary to reach the target position from the current position .

To obtain a uniform scroll duration the velocity (pixels per millisecond) must account for the size of each individual item - and when the items are of non-standard dimension then a whole new level of complexity is added.

This may be why the RecyclerView developers deployed the too-hard basket for this vital aspect of smooth scrolling.

Assuming that you want a semi-uniform scroll duration, and that your list contains semi-uniform items then you will need something like this.

/** Smoothly scroll to specified position allowing for interval specification. <br>
 * Note crude deceleration towards end of scroll
 * @param rv        Your RecyclerView
 * @param toPos     Position to scroll to
 * @param duration  Approximate desired duration of scroll (ms)
 * @throws IllegalArgumentException */
private static void smoothScroll(RecyclerView rv, int toPos, int duration) throws IllegalArgumentException {
    int TARGET_SEEK_SCROLL_DISTANCE_PX = 10000;     // See androidx.recyclerview.widget.LinearSmoothScroller
    int itemHeight = rv.getChildAt(0).getHeight();  // Height of first visible view! NB: ViewGroup method!
    itemHeight = itemHeight + 33;                   // Example pixel Adjustment for decoration?
    int fvPos = ((LinearLayoutManager)rv.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
    int i = Math.abs((fvPos - toPos) * itemHeight);
    if (i == 0) { i = (int) Math.abs(rv.getChildAt(0).getY()); }
    final int totalPix = i;                         // Best guess: Total number of pixels to scroll
    RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(rv.getContext()) {
        @Override protected int getVerticalSnapPreference() {
            return LinearSmoothScroller.SNAP_TO_START;
        }
        @Override protected int calculateTimeForScrolling(int dx) {
            int ms = (int) ( duration * dx / (float)totalPix );
            // Now double the interval for the last fling.
            if (dx < TARGET_SEEK_SCROLL_DISTANCE_PX ) { ms = ms*2; } // Crude deceleration!
            //lg(format("For dx=%d we allot %dms", dx, ms));
            return ms;
        }
    };
    //lg(format("Total pixels from = %d to %d = %d [ itemHeight=%dpix ]", fvPos, toPos, totalPix, itemHeight));
    smoothScroller.setTargetPosition(toPos);
    rv.getLayoutManager().startSmoothScroll(smoothScroller);
}

PS: I curse the day I began indiscriminately converting ListView to RecyclerView.

How to use RecyclerView inside NestedScrollView?

At least as far back as Material Components 1.3.0-alpha03, it doesn't matter if the RecyclerView is nested (in something other than a ScrollView or NestedScrollView). Just put app:layout_behavior="@string/appbar_scrolling_view_behavior" on its top level parent that's a sibling of the AppBarLayout in the CoordinatorLayout.

This has been working for me when using a single Activity architecture with Jetpack Naviagation, where all Fragments are sharing the same AppBar from the Activity's layout. I make the FragmentContainer the direct child of the CoordinatorLayout that also contains the AppBarLayout, like below. The RecyclerViews in the various fragments are scrolling normally and the AppBar folds away and reappears as expected.

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/coordinatorLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            app:defaultNavHost="true"
            app:navGraph="@navigation/mobile_navigation"/>

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appbar_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:liftOnScroll="true">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:minHeight="?attr/actionBarSize"
                android:theme="?attr/actionBarTheme"
                app:layout_scrollFlags="scroll|enterAlways|snap" />

        </com.google.android.material.appbar.AppBarLayout>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

liftOnScroll (used to for app bars to look like they have zero elevation when at the top of the page) works if each fragment passes the ID of its RecyclerView to AppBarLayout.liftOnScrollTargetViewId in Fragment.onResume. Or pass 0 if the Fragment doesn't scroll.

Error inflating class android.support.design.widget.NavigationView

I had similar error. When i use

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">

    <item name="colorPrimary">#673AB7</item>
    <item name="colorPrimaryDark">#512DA8</item>
    <item name="colorAccent">#00BCD4</item>
    <item name="android:textColorPrimary">#212121</item>
    <item name="android:textColorSecondary">#727272</item>

</style>

works for me when i remove the android:textColorPrimary and android:textColorSecondary theme items.

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">

    <item name="colorPrimary">#673AB7</item>
    <item name="colorPrimaryDark">#512DA8</item>
    <item name="colorAccent">#00BCD4</item>

</style>

Try working with a very simple App theme to start off with.

EDIT:

This tutorial will help. My understanding is that using "android:textColorPrimary" requires minimum api level 21. Using the same tag without "android:" uses the design support library. Any support library widget will try to find the "textColorPrimary" item instead of "android:textColorPrimary" and if it fails to find the same it throws the above mentioned error.

How to disable RecyclerView scrolling?

I know this already has an accepted answer, but the solution doesn't take into account a use-case that I came across.

I specifically needed a header item that was still clickable, yet disabled the scrolling mechanism of the RecyclerView. This can be accomplished with the following code:

recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
                            @Override
     public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
         return e.getAction() == MotionEvent.ACTION_MOVE;
     }

     @Override
     public void onTouchEvent(RecyclerView rv, MotionEvent e) {

     }

     @Override
     public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
});

How to filter a RecyclerView with a SearchView

This is my take on expanding @klimat answer to not losing filtering animation.

public void filter(String query){
    int completeListIndex = 0;
    int filteredListIndex = 0;
    while (completeListIndex < completeList.size()){
        Movie item = completeList.get(completeListIndex);
        if(item.getName().toLowerCase().contains(query)){
            if(filteredListIndex < filteredList.size()) {
                Movie filter = filteredList.get(filteredListIndex);
                if (!item.getName().equals(filter.getName())) {
                    filteredList.add(filteredListIndex, item);
                    notifyItemInserted(filteredListIndex);
                }
            }else{
                filteredList.add(filteredListIndex, item);
                notifyItemInserted(filteredListIndex);
            }
            filteredListIndex++;
        }
        else if(filteredListIndex < filteredList.size()){
            Movie filter = filteredList.get(filteredListIndex);
            if (item.getName().equals(filter.getName())) {
                filteredList.remove(filteredListIndex);
                notifyItemRemoved(filteredListIndex);
            }
        }
        completeListIndex++;
    }
}

Basically what it does is looking through a complete list and adding/removing items to a filtered list one by one.

Handle Button click inside a row in RecyclerView

You need to return true inside onInterceptTouchEvent() when you handle click event.

RecyclerView: Inconsistency detected. Invalid item position

in my case , this solve my issue

rv.setAdapter(null);
rv.setItemAnimator(null);

PS: my problem ocur when i do seache filter in my recyclerview adapter

Best way to update data with a RecyclerView adapter

@inmyth's answer is correct, just modify the code a bit, to handle empty list.

public class NewsAdapter extends RecyclerView.Adapter<...> {    
    ...
    private static List mFeedsList;
    ...    
    public void swap(List list){
            if (mFeedsList != null) {
                mFeedsList.clear();
                mFeedsList.addAll(list);
            }
            else {
                mFeedsList = list;
            }
            notifyDataSetChanged();
    }

I am using Retrofit to fetch the list, on Retrofit's onResponse() use,

adapter.swap(feedList);

Remove all items from RecyclerView

This works great for me:

public void clear() {
    int size = data.size();
    if (size > 0) {
        for (int i = 0; i < size; i++) {
            data.remove(0);
        }

        notifyItemRangeRemoved(0, size);
    }
}

Source: https://github.com/mikepenz/LollipopShowcase/blob/master/app/src/main/java/com/mikepenz/lollipopshowcase/adapter/ApplicationAdapter.java

or:

public void clear() {
    int size = data.size();
    data.clear();
    notifyItemRangeRemoved(0, size);
}

For you:

@Override
protected void onRestart() {
    super.onRestart();

    // first clear the recycler view so items are not populated twice
    recyclerAdapter.clear();

    // then reload the data
    PostCall doPostCall = new PostCall(); // my AsyncTask... 
    doPostCall.execute();
}

Java finished with non-zero exit value 2 - Android Gradle

You may be using a low quality cable/defected cable to connect your device to the PC, I replaced the cable and it worked for me.

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

I had such dependancy in build.gradle -

compile 'com.android.support:recyclerview-v7:+'

But it causes unstable builds. Ensure it works ok for you, and look in your android sdk manager for current version of support lib available, and replace this dependency with

def final RECYCLER_VIEW_VER = '23.1.1'
compile "com.android.support:recyclerview-v7:${RECYCLER_VIEW_VER}"

recyclerview No adapter attached; skipping layout

These Lines must be in OnCreate:

mmAdapter = new Adapter(msgList);
mrecyclerView.setAdapter(mmAdapter);

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

Solution (Updated: 24-may-2016): Change build.gradle (project)

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:X.X.X-lastVersionGradle'
    classpath 'com.google.gms:google-services:X.X.X-lastVersionGServices' // If use google-services

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

X.X.X-lastVersionGradle: For example: 2.1.0

X.X.X-lastVersionGServices: For example: 3.0.0 (support Firebase Analytics)

Note: if you're using the google-services plugin has to be the same version (if there)

Warning!! -> 2.2.0-alpha throws Unsupported major.minor version 52.0 if you don't use java JDK 8u91 and NetBeans 8.1

Single selection in RecyclerView

This happens because RecyclerView, as the name suggests, does a good job at recycling its ViewHolders. This means that every ViewHolder, when it goes out of sight (actually, it takes a little more than going out of sight, but it makes sense to simplify it that way), it is recycled; this implies that the RecyclerView takes this ViewHolder that is already inflated and replaces its elements with the elements of another item in your data set.

Now, what is going on here is that once you scroll down and your first, selected, ViewHolders go out of sight, they are being recycled and used for other positions of your data set. Once you go up again, the ViewHolders that were bound to the first 5 items are not necessarely the same, now.

This is why you should keep an internal variable in your adapter that remembers the selection state of each item. This way, in the onBindViewHolder method, you can know if the item whose ViewHolder is currently being bound was selected or not, and modify a View accordingly, in this case your RadioButton's state (though I would suggest to use a CheckBox if you plan on selecting multiple items).

If you want to learn more about RecyclerView and its inner workings, I invite you to check FancyAdapters, a project I started on GitHub. It is a collection of adapters that implement selection, drag&drop of elements and swipe to dismiss capabilities. Maybe by checking the code you can obtain a good understanding on how RecyclerView works.

How to open a different activity on recyclerView item onclick

This question has been asked long ago but none of the answers above helped me out, though Milad Moosavi`s answer was very close. To open a new activity from a certain position on the recycler view, the following code may help:


    @Override
    public void onBindViewHolder(@NonNull TripViewHolder holder, int position) {
        Trip currentTrip = trips.get(position);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), EditTrip.class);
                v.getContext().startActivity(intent);
            }
        });

        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Intent intent = new Intent(v.getContext(), ReadTripActivity.class);
                v.getContext().startActivity(intent);

                return false;
            }
        });
    }

Refreshing data in RecyclerView and keeping its scroll position

The top answer by @DawnYu works, but the recyclerview will first scroll to the top, then go back to the intended scroll position causing a "flicker like" reaction which isn't pleasant.

To refresh the recyclerView, especially after coming from another activity, without flickering, and maintaining the scroll position, you need to do the following.

  1. Ensure you are updating you recycler view using DiffUtil. Read more about that here: https://www.journaldev.com/20873/android-recyclerview-diffutil
  2. Onresume of your activity, or at the point you want to update your activity, load data to your recyclerview. Using the diffUtil, only the updates will be made on the recyclerview while maintaining it position.

Hope this helps.

Android Recyclerview GridLayoutManager column spacing

The answers on for this question seem more complex than they should be. Here's my take on this.

Let's say you want 1dp spacing between grid items. Do the following:

  1. Add a padding of 0.5dp to each item
  2. Add a padding of -0.5dp to the RecycleView
  3. That's it! :)

Android Recyclerview vs ListView with Viewholder

RecyclerView was created as a ListView improvement, so yes, you can create an attached list with ListView control, but using RecyclerView is easier as it:

  1. Reuses cells while scrolling up/down : this is possible with implementing View Holder in the ListView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.

  2. Decouples list from its container : so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.

mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));

  1. Animates common list actions : Animations are decoupled and delegated to ItemAnimator. There is more about RecyclerView, but I think these points are the main ones.

So, to conclude, RecyclerView is a more flexible control for handling "list data" that follows patterns of delegation of concerns and leaves for itself only one task - recycling items.

How to build a Horizontal ListView with RecyclerView?

Is there a better way to implement this now with Recyclerview now?

Yes.

When you use a RecyclerView, you need to specify a LayoutManager that is responsible for laying out each item in the view. The LinearLayoutManager allows you to specify an orientation, just like a normal LinearLayout would.

To create a horizontal list with RecyclerView, you might do something like this:

LinearLayoutManager layoutManager
    = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

RecyclerView myList = (RecyclerView) findViewById(R.id.my_recycler_view);
myList.setLayoutManager(layoutManager);

Get clicked item and its position in RecyclerView

Here is the simplest and the easiest way to find the position of the clicked item:

I've also faced the same problem.

I wanted to find of the position of the clicked/selected item of the RecyclerView() and perform some specific operations on that particular item.

getAdapterPosition() method works like a charm for these kind of stuff. I found this method after a day of long research and after trying numerous other methods.

int position = getAdapterPosition();
Toast.makeText(this, "Position is: "+position, Toast.LENGTH_SHORT).show();

You do not have to use any extra method. Just create a global variable named 'position' and initialize it with getAdapterPosition() in any of the major method of the adapter (class or similar).

Here is a brief documentation from this link.

getAdapterPosition added in version 22.1.0 int getAdapterPosition () Returns the Adapter position of the item represented by this ViewHolder. Note that this might be different than the getLayoutPosition() if there are pending adapter updates but a new layout pass has not happened yet. RecyclerView does not handle any adapter updates until the next layout traversal. This may create temporary inconsistencies between what user sees on the screen and what adapter contents have. This inconsistency is not important since it will be less than 16ms but it might be a problem if you want to use ViewHolder position to access the adapter. Sometimes, you may need to get the exact adapter position to do some actions in response to user events. In that case, you should use this method which will calculate the Adapter position of the ViewHolder.

Happy to help. Feel free to ask doubts.

How to show an empty view with a RecyclerView?

I added RecyclerView and alternative ImageView to the RelativeLayout:

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

    <ImageView
        android:id="@+id/no_active_jobs"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/ic_active_jobs" />

    <android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

and then in Adapter:

@Override
public int getItemCount() {
    if (mOrders.size() == 0) {
        mRecyclerView.setVisibility(View.INVISIBLE);
    } else {
        mRecyclerView.setVisibility(View.VISIBLE);
    }
    return mOrders.size();
}

Add a new item to recyclerview programmatically?

First add your item to mItems and then use:

mAdapter.notifyItemInserted(mItems.size() - 1);

this method is better than using:

mAdapter.notifyDataSetChanged();

in performance.

How to save RecyclerView's scroll position using RecyclerView.State?

I would just like to share the recent predicament I encounter with the RecyclerView. I hope that anyone experiencing the same problem will benefit.

My Project Requirement: So I have a RecyclerView that list some clickable items in my Main Activity (Activity-A). When the Item is clicked a new Activity is shown with the Item Details (Activity-B).

I implemented in the Manifest file the that the Activity-A is the parent of Activity-B, that way, I have a back or home button on the ActionBar of the Activity-B

Problem: Every time I pressed the Back or Home button in the Activity-B ActionBar, the Activity-A goes into the full Activity Life Cycle starting from onCreate()

Even though I implemented an onSaveInstanceState() saving the List of the RecyclerView's Adapter, when Activity-A starts it's lifecycle, the saveInstanceState is always null in the onCreate() method.

Further digging in the internet, I came across the same problem but the person noticed that the Back or Home button below the Anroid device (Default Back/Home button), the Activity-A does not goes into the Activity Life-Cycle.

Solution:

  1. I removed the Tag for Parent Activity in the manifest for Activity-B
  2. I enabled the home or back button on Activity-B

    Under onCreate() method add this line supportActionBar?.setDisplayHomeAsUpEnabled(true)

  3. In the overide fun onOptionsItemSelected() method, I checked for the item.ItemId on which item is clicked based on the id. The Id for the back button is

    android.R.id.home

    Then implement a finish() function call inside the android.R.id.home

    This will end the Activity-B and bring Acitivy-A without going through the entire life-cycle.

For my requirement this is the best solution so far.

     override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_show_project)

    supportActionBar?.title = projectName
    supportActionBar?.setDisplayHomeAsUpEnabled(true)

}


 override fun onOptionsItemSelected(item: MenuItem?): Boolean {

    when(item?.itemId){

        android.R.id.home -> {
            finish()
        }
    }

    return super.onOptionsItemSelected(item)
}

How do I make WRAP_CONTENT work on a RecyclerView

This now works as they've made a release in version 23.2, as stated in this post. Quoting the official blogpost

This release brings an exciting new feature to the LayoutManager API: auto-measurement! This allows a RecyclerView to size itself based on the size of its contents. This means that previously unavailable scenarios, such as using WRAP_CONTENT for a dimension of the RecyclerView, are now possible. You’ll find all built in LayoutManagers now support auto-measurement.

App crashing when trying to use RecyclerView on android 5.0

You need to use setLayoutManager in the RecyclerView#onCreate() method. Before adding recyclerView to a view, it must have the LayoutManager set.

 private RecyclerView menuAsList;

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

    menuAsList = (RecyclerView) findViewById(R.id.recyclerView_mainMenu);
    menuAsList.setLayoutManager(new LinearLayoutManager(Home.this));

}

RecyclerView expand/collapse items

Please don't use any library for this effect instead use the recommended way of doing it according to Google I/O. In your recyclerView's onBindViewHolder method do this:

final boolean isExpanded = position==mExpandedPosition;
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        mExpandedPosition = isExpanded ? -1:position;
        TransitionManager.beginDelayedTransition(recyclerView);
        notifyDataSetChanged();
    }
});
  • Where details is my view that will be displayed on touch (call details in your case. Default Visibility.GONE).
  • mExpandedPosition is an int variable initialized to -1

And for the cool effects that you wanted, use these as your list_item attributes:

android:background="@drawable/comment_background"
android:stateListAnimator="@animator/comment_selection"

where comment_background is:

<selector
xmlns:android="http://schemas.android.com/apk/res/android"
android:constantSize="true"
android:enterFadeDuration="@android:integer/config_shortAnimTime"
android:exitFadeDuration="@android:integer/config_shortAnimTime">

<item android:state_activated="true" android:drawable="@color/selected_comment_background" />
<item android:drawable="@color/comment_background" />
</selector>

and comment_selection is:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_activated="true">
    <objectAnimator
        android:propertyName="translationZ"
        android:valueTo="@dimen/z_card"
        android:duration="2000"
        android:interpolator="@android:interpolator/fast_out_slow_in" />
</item>

<item>
    <objectAnimator
        android:propertyName="translationZ"
        android:valueTo="0dp"
        android:duration="2000"
        android:interpolator="@android:interpolator/fast_out_slow_in" />
</item>
</selector>

How to properly highlight selected item on RecyclerView?

Decision with Interfaces and Callbacks. Create Interface with select and unselect states:

public interface ItemTouchHelperViewHolder {
    /**
     * Called when the {@link ItemTouchHelper} first registers an item as being moved or swiped.
     * Implementations should update the item view to indicate it's active state.
     */
    void onItemSelected();


    /**
     * Called when the {@link ItemTouchHelper} has completed the move or swipe, and the active item
     * state should be cleared.
     */
    void onItemClear();
}

Implement interface in ViewHolder:

   public static class ItemViewHolder extends RecyclerView.ViewHolder implements
            ItemTouchHelperViewHolder {

        public LinearLayout container;
        public PositionCardView content;

        public ItemViewHolder(View itemView) {
            super(itemView);
            container = (LinearLayout) itemView;
            content = (PositionCardView) itemView.findViewById(R.id.content);

        }

               @Override
    public void onItemSelected() {
        /**
         * Here change of item
         */
        container.setBackgroundColor(Color.LTGRAY);
    }

    @Override
    public void onItemClear() {
        /**
         * Here change of item
         */
        container.setBackgroundColor(Color.WHITE);
    }
}

Run state change on Callback:

public class ItemTouchHelperCallback extends ItemTouchHelper.Callback {

    private final ItemTouchHelperAdapter mAdapter;

    public ItemTouchHelperCallback(ItemTouchHelperAdapter adapter) {
        this.mAdapter = adapter;
    }

    @Override
    public boolean isLongPressDragEnabled() {
        return true;
    }

    @Override
    public boolean isItemViewSwipeEnabled() {
        return true;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        int swipeFlags = ItemTouchHelper.END;
        return makeMovementFlags(dragFlags, swipeFlags);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        ...
    }

    @Override
    public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
        ...
    }

    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
        if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
            if (viewHolder instanceof ItemTouchHelperViewHolder) {
                ItemTouchHelperViewHolder itemViewHolder =
                        (ItemTouchHelperViewHolder) viewHolder;
                itemViewHolder.onItemSelected();
            }
        }
        super.onSelectedChanged(viewHolder, actionState);
    }

    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        super.clearView(recyclerView, viewHolder);
        if (viewHolder instanceof ItemTouchHelperViewHolder) {
            ItemTouchHelperViewHolder itemViewHolder =
                    (ItemTouchHelperViewHolder) viewHolder;
            itemViewHolder.onItemClear();
        }
    }   
}

Create RecyclerView with Callback (example):

mAdapter = new BuyItemsRecyclerListAdapter(MainActivity.this, positionsList, new ArrayList<BuyItem>());
positionsList.setAdapter(mAdapter);
positionsList.setLayoutManager(new LinearLayoutManager(this));
ItemTouchHelper.Callback callback = new ItemTouchHelperCallback(mAdapter);
mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(positionsList);

See more in article of iPaulPro: https://medium.com/@ipaulpro/drag-and-swipe-with-recyclerview-6a6f0c422efd#.6gh29uaaz

RecyclerView inside ScrollView is not working

UPDATE: this answer is out dated now as there are widgets like NestedScrollView and RecyclerView that support nested scrolling.

you should never put a scrollable view inside another scrollable view !

i suggest you make your main layout recycler view and put your views as items of recycler view.

take a look at this example it show how to use multiple views inside recycler view adapter. link to example

Scroll RecyclerView to show selected item on top

I use the code below to smooth-scroll an item (thisView) to the top.
It works also for GridLayoutManager with views of different heights:

View firstView = mRecyclerView.getChildAt(0);
int toY = firstView.getTop();
int firstPosition = mRecyclerView.getChildAdapterPosition(firstView);
View thisView = mRecyclerView.getChildAt(thisPosition - firstPosition);
int fromY = thisView.getTop();

mRecyclerView.smoothScrollBy(0, fromY - toY);

Seems to work good enough for a quick solution.

RecyclerView vs. ListView

Advantages of RecyclerView over listview :

  1. Contains ViewHolder by default.

  2. Easy animations.

  3. Supports horizontal , grid and staggered layouts

Advantages of listView over recyclerView :

  1. Easy to add divider.

  2. Can use inbuilt arrayAdapter for simple plain lists

  3. Supports Header and footer .

  4. Supports OnItemClickListner .

How to animate RecyclerView items when they appear

I created animation from pbm's answer with little modification to make the aninmation run only once

in the other word the Animation appear with you scroll down only

private int lastPosition = -1;

private void setAnimation(View viewToAnimate, int position) {
    // If the bound view wasn't previously displayed on screen, it's animated
    if (position > lastPosition) {
        ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        anim.setDuration(new Random().nextInt(501));//to make duration random number between [0,501)
        viewToAnimate.startAnimation(anim);
        lastPosition = position;
    }
}

and in onBindViewHolder call the function

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

holder.getTextView().setText("some text");

// call Animation function
setAnimation(holder.itemView, position);            
}

How do I get the position selected in a RecyclerView?

I think the most correct way to get item position is

View.OnClickListener onClickListener = new View.OnClickListener() {
    @Override public void onClick(View v) {
      View view = v;
      View parent = (View) v.getParent();
      while (!(parent instanceof RecyclerView)){
        view=parent;
        parent = (View) parent.getParent();
      }
      int position = recyclerView.getChildAdapterPosition(view);
}

Because view, you click not always the root view of your row layout. If view is not a root one (e.g buttons), you will get Class cast exception. Thus at first we need to find the view, which is the a dirrect child of you reciclerview. Then, find position using recyclerView.getChildAdapterPosition(view);

Nested Recycler view height doesn't wrap its content

Yes the workaround shown in all answer is correct , that is we need to customize the linear layout manager to calculate the height of its child items dynamically at run time. But all answers not working as expected .Please the below answer for custom layout manger with all orientation support.

public class MyLinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {

private static boolean canMakeInsetsDirty = true;
private static Field insetsDirtyField = null;

private static final int CHILD_WIDTH = 0;
private static final int CHILD_HEIGHT = 1;
private static final int DEFAULT_CHILD_SIZE = 100;

private final int[] childDimensions = new int[2];
private final RecyclerView view;

private int childSize = DEFAULT_CHILD_SIZE;
private boolean hasChildSize;
private int overScrollMode = ViewCompat.OVER_SCROLL_ALWAYS;
private final Rect tmpRect = new Rect();

@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(Context context) {
    super(context);
    this.view = null;
}

@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
    super(context, orientation, reverseLayout);
    this.view = null;
}

@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(RecyclerView view) {
    super(view.getContext());
    this.view = view;
    this.overScrollMode = ViewCompat.getOverScrollMode(view);
}

@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(RecyclerView view, int orientation, boolean reverseLayout) {
    super(view.getContext(), orientation, reverseLayout);
    this.view = view;
    this.overScrollMode = ViewCompat.getOverScrollMode(view);
}

public void setOverScrollMode(int overScrollMode) {
    if (overScrollMode < ViewCompat.OVER_SCROLL_ALWAYS || overScrollMode > ViewCompat.OVER_SCROLL_NEVER)
        throw new IllegalArgumentException("Unknown overscroll mode: " + overScrollMode);
    if (this.view == null) throw new IllegalStateException("view == null");
    this.overScrollMode = overScrollMode;
    ViewCompat.setOverScrollMode(view, overScrollMode);
}

public static int makeUnspecifiedSpec() {
    return View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
}

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);

    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);

    final boolean hasWidthSize = widthMode != View.MeasureSpec.UNSPECIFIED;
    final boolean hasHeightSize = heightMode != View.MeasureSpec.UNSPECIFIED;

    final boolean exactWidth = widthMode == View.MeasureSpec.EXACTLY;
    final boolean exactHeight = heightMode == View.MeasureSpec.EXACTLY;

    final int unspecified = makeUnspecifiedSpec();

    if (exactWidth && exactHeight) {
        // in case of exact calculations for both dimensions let's use default "onMeasure" implementation
        super.onMeasure(recycler, state, widthSpec, heightSpec);
        return;
    }

    final boolean vertical = getOrientation() == VERTICAL;

    initChildDimensions(widthSize, heightSize, vertical);

    int width = 0;
    int height = 0;

    // it's possible to get scrap views in recycler which are bound to old (invalid) adapter entities. This
    // happens because their invalidation happens after "onMeasure" method. As a workaround let's clear the
    // recycler now (it should not cause any performance issues while scrolling as "onMeasure" is never
    // called whiles scrolling)
    recycler.clear();

    final int stateItemCount = state.getItemCount();
    final int adapterItemCount = getItemCount();
    // adapter always contains actual data while state might contain old data (f.e. data before the animation is
    // done). As we want to measure the view with actual data we must use data from the adapter and not from  the
    // state
    for (int i = 0; i < adapterItemCount; i++) {
        if (vertical) {
            if (!hasChildSize) {
                if (i < stateItemCount) {
                    // we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
                    // we will use previously calculated dimensions
                    measureChild(recycler, i, widthSize, unspecified, childDimensions);
                } else {
                    logMeasureWarning(i);
                }
            }
            height += childDimensions[CHILD_HEIGHT];
            if (i == 0) {
                width = childDimensions[CHILD_WIDTH];
            }
            if (hasHeightSize && height >= heightSize) {
                break;
            }
        } else {
            if (!hasChildSize) {
                if (i < stateItemCount) {
                    // we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
                    // we will use previously calculated dimensions
                    measureChild(recycler, i, unspecified, heightSize, childDimensions);
                } else {
                    logMeasureWarning(i);
                }
            }
            width += childDimensions[CHILD_WIDTH];
            if (i == 0) {
                height = childDimensions[CHILD_HEIGHT];
            }
            if (hasWidthSize && width >= widthSize) {
                break;
            }
        }
    }

    if (exactWidth) {
        width = widthSize;
    } else {
        width += getPaddingLeft() + getPaddingRight();
        if (hasWidthSize) {
            width = Math.min(width, widthSize);
        }
    }

    if (exactHeight) {
        height = heightSize;
    } else {
        height += getPaddingTop() + getPaddingBottom();
        if (hasHeightSize) {
            height = Math.min(height, heightSize);
        }
    }

    setMeasuredDimension(width, height);

    if (view != null && overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS) {
        final boolean fit = (vertical && (!hasHeightSize || height < heightSize))
                || (!vertical && (!hasWidthSize || width < widthSize));

        ViewCompat.setOverScrollMode(view, fit ? ViewCompat.OVER_SCROLL_NEVER : ViewCompat.OVER_SCROLL_ALWAYS);
    }
}

private void logMeasureWarning(int child) {
    if (BuildConfig.DEBUG) {
        Log.w("MyLinearLayoutManager", "Can't measure child #" + child + ", previously used dimensions will be reused." +
                "To remove this message either use #setChildSize() method or don't run RecyclerView animations");
    }
}

private void initChildDimensions(int width, int height, boolean vertical) {
    if (childDimensions[CHILD_WIDTH] != 0 || childDimensions[CHILD_HEIGHT] != 0) {
        // already initialized, skipping
        return;
    }
    if (vertical) {
        childDimensions[CHILD_WIDTH] = width;
        childDimensions[CHILD_HEIGHT] = childSize;
    } else {
        childDimensions[CHILD_WIDTH] = childSize;
        childDimensions[CHILD_HEIGHT] = height;
    }
}

@Override
public void setOrientation(int orientation) {
    // might be called before the constructor of this class is called
    //noinspection ConstantConditions
    if (childDimensions != null) {
        if (getOrientation() != orientation) {
            childDimensions[CHILD_WIDTH] = 0;
            childDimensions[CHILD_HEIGHT] = 0;
        }
    }
    super.setOrientation(orientation);
}

public void clearChildSize() {
    hasChildSize = false;
    setChildSize(DEFAULT_CHILD_SIZE);
}

public void setChildSize(int childSize) {
    hasChildSize = true;
    if (this.childSize != childSize) {
        this.childSize = childSize;
        requestLayout();
    }
}

private void measureChild(RecyclerView.Recycler recycler, int position, int widthSize, int heightSize, int[] dimensions) {
    final View child;
    try {
        child = recycler.getViewForPosition(position);
    } catch (IndexOutOfBoundsException e) {
        if (BuildConfig.DEBUG) {
            Log.w("MyLinearLayoutManager", "MyLinearLayoutManager doesn't work well with animations. Consider switching them off", e);
        }
        return;
    }

    final RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) child.getLayoutParams();

    final int hPadding = getPaddingLeft() + getPaddingRight();
    final int vPadding = getPaddingTop() + getPaddingBottom();

    final int hMargin = p.leftMargin + p.rightMargin;
    final int vMargin = p.topMargin + p.bottomMargin;

    // we must make insets dirty in order calculateItemDecorationsForChild to work
    makeInsetsDirty(p);
    // this method should be called before any getXxxDecorationXxx() methods
    calculateItemDecorationsForChild(child, tmpRect);

    final int hDecoration = getRightDecorationWidth(child) + getLeftDecorationWidth(child);
    final int vDecoration = getTopDecorationHeight(child) + getBottomDecorationHeight(child);

    final int childWidthSpec = getChildMeasureSpec(widthSize, hPadding + hMargin + hDecoration, p.width, canScrollHorizontally());
    final int childHeightSpec = getChildMeasureSpec(heightSize, vPadding + vMargin + vDecoration, p.height, canScrollVertically());

    child.measure(childWidthSpec, childHeightSpec);

    dimensions[CHILD_WIDTH] = getDecoratedMeasuredWidth(child) + p.leftMargin + p.rightMargin;
    dimensions[CHILD_HEIGHT] = getDecoratedMeasuredHeight(child) + p.bottomMargin + p.topMargin;

    // as view is recycled let's not keep old measured values
    makeInsetsDirty(p);
    recycler.recycleView(child);
}

private static void makeInsetsDirty(RecyclerView.LayoutParams p) {
    if (!canMakeInsetsDirty) {
        return;
    }
    try {
        if (insetsDirtyField == null) {
            insetsDirtyField = RecyclerView.LayoutParams.class.getDeclaredField("mInsetsDirty");
            insetsDirtyField.setAccessible(true);
        }
        insetsDirtyField.set(p, true);
    } catch (NoSuchFieldException e) {
        onMakeInsertDirtyFailed();
    } catch (IllegalAccessException e) {
        onMakeInsertDirtyFailed();
    }
}

private static void onMakeInsertDirtyFailed() {
    canMakeInsetsDirty = false;
    if (BuildConfig.DEBUG) {
        Log.w("MyLinearLayoutManager", "Can't make LayoutParams insets dirty, decorations measurements might be incorrect");
    }
}
}

Display a RecyclerView in Fragment

You should retrieve RecyclerView in a Fragment after inflating core View using that View. Perhaps it can't find your recycler because it's not part of Activity

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_artist_tracks, container, false);
    final FragmentActivity c = getActivity();
    final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(c);
    recyclerView.setLayoutManager(layoutManager);

    new Thread(new Runnable() {
        @Override
        public void run() {
            final RecyclerAdapter adapter = new RecyclerAdapter(c);
            c.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    recyclerView.setAdapter(adapter);
                }
            });
        }
    }).start();

    return view;
}

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

You can scroll to the bottom of the last item, if the height of the last item is too large, you need to offset

 private void scrollToBottom(final RecyclerView recyclerView) {
        // scroll to last item to get the view of last item
        final LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        final RecyclerView.Adapter adapter = recyclerView.getAdapter();
        final int lastItemPosition = adapter.getItemCount() - 1;
    
        layoutManager.scrollToPositionWithOffset(lastItemPosition, 0);
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                // then scroll to specific offset
                View target = layoutManager.findViewByPosition(lastItemPosition);
                if (target != null) {
                    int offset = recyclerView.getMeasuredHeight() - target.getMeasuredHeight();
                    layoutManager.scrollToPositionWithOffset(lastItemPosition, offset);
                }
            }
        });



    }

How to get file name from file path in android

Other Way is:

String[] parts = selectedFilePath.split("/");
    final String fileName = parts[parts.length-1];

How to implement endless list with RecyclerView?

Although there are so many answers to the question, I would like to share our experience of creating the endless list view. We have recently implemented custom Carousel LayoutManager that can work in the cycle by scrolling the list infinitely as well as up to a certain point. Here is a detailed description on GitHub.

I suggest you take a look at this article with short but valuable recommendations on creating custom LayoutManagers: http://cases.azoft.com/create-custom-layoutmanager-android/

Is there an addHeaderView equivalent for RecyclerView?

You can just place your header and your RecyclerView in a NestedScrollView:

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

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

        <android.support.v7.widget.RecyclerView
            android:id="@+id/list_recylclerview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

In order for scrolling to work correctly, you need to disable nested scrolling on your RecyclerView:

myRecyclerView.setNestedScrollingEnabled(false);

Android 5.0 - Add header/footer to a RecyclerView

You can used this GitHub library allowing to add Header and/or Footer in your RecyclerView in the simplest way possible.

You need to add HFRecyclerView library in your project or you can also grab it from Gradle:

compile 'com.mikhaellopez:hfrecyclerview:1.0.0'

This is a result in image:

Preview

EDIT:

If you just want to add a margin at the top and/or bottom with this library: SimpleItemDecoration:

int offsetPx = 10;
recyclerView.addItemDecoration(new StartOffsetItemDecoration(offsetPx));
recyclerView.addItemDecoration(new EndOffsetItemDecoration(offsetPx));

How to create RecyclerView with multiple view type?

first you must create 2 layout xml . after that inside recyclerview adapter TYPE_CALL and TYPE_EMAIL are two static values with 1 and 2 respectively in adapter class.

now Define two static values ??at the Recycler view Adapter class level for example : private static int TYPE_CALL = 1; private static int TYPE_EMAIL = 2;

Now create view holder with multiple views like this:

class CallViewHolder extends RecyclerView.ViewHolder {

    private TextView txtName;
    private TextView txtAddress;

    CallViewHolder(@NonNull View itemView) {
        super(itemView);
        txtName = itemView.findViewById(R.id.txtName);
        txtAddress = itemView.findViewById(R.id.txtAddress);
    }
}
class EmailViewHolder extends RecyclerView.ViewHolder {

    private TextView txtName;
    private TextView txtAddress;

    EmailViewHolder(@NonNull View itemView) {
        super(itemView);
        txtName = itemView.findViewById(R.id.txtName);
        txtAddress = itemView.findViewById(R.id.txtAddress);
    }
}

Now code as below in onCreateViewHolder and onBindViewHolder method in recyclerview adapter:

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
    View view;
    if (viewType == TYPE_CALL) { // for call layout
        view = LayoutInflater.from(context).inflate(R.layout.item_call, viewGroup, false);
        return new CallViewHolder(view);

    } else { // for email layout
        view = LayoutInflater.from(context).inflate(R.layout.item_email, viewGroup, false);
        return new EmailViewHolder(view);
    }
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
    if (getItemViewType(position) == TYPE_CALL) {
        ((CallViewHolder) viewHolder).setCallDetails(employees.get(position));
    } else {
        ((EmailViewHolder) viewHolder).setEmailDetails(employees.get(position));
    }
}

Android RecyclerView addition & removal of items

Incase Anyone wants to implement something like this in Main class instead of Adapter class, you can use:

public void removeAt(int position) {
    peopleListUser.remove(position);

    friendsListRecycler.getAdapter().notifyItemRemoved(position);
    friendsListRecycler.getAdapter().notifyItemRangeChanged(position, peopleListUser.size());
}

where friendsListRecycler is the Adapter name

Recyclerview and handling different type of row inflation

You can just return ItemViewType and use it. See below code:

@Override
public int getItemViewType(int position) {

    Message item = messageList.get(position);
    // return my message layout
    if(item.getUsername() == Message.userEnum.I)
        return R.layout.item_message_me;
    else
        return R.layout.item_message; // return other message layout
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(viewType, viewGroup, false);
    return new ViewHolder(view);
}

Get visible items in RecyclerView

Every answer above is correct and I would like to add also a snapshot from my working codes.

recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
           //some code when initially scrollState changes
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            //Some code while the list is scrolling
            LinearLayoutManager lManager = (LinearLayoutManager) recycler.getLayoutManager();
            int firstElementPosition = lManager.findFirstVisibleItemPosition();
            
        }
    });

Why doesn't RecyclerView have onItemClickListener()?

I use this method to start an Intent from RecyclerView:

@Override
 public void onBindViewHolder(ViewHolder viewHolder, int i) {

    final MyClass myClass = mList.get(i);
    viewHolder.txtViewTitle.setText(myclass.name);
   ...
    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
      @Override
       public void onClick(View v){
             Intent detailIntent = new Intent(mContext, type.class);                                                            
             detailIntent.putExtra("MyClass", myclass);
             mContext.startActivity(detailIntent);
       }
}
);

notifyDataSetChanged not working on RecyclerView

Try this method:

List<Business> mBusinesses2 = mBusinesses;
mBusinesses.clear();
mBusinesses.addAll(mBusinesses2);
//and do the notification

a little time consuming, but it should work.

How to add dividers and spaces between items in RecyclerView?

Here's my lazy approach but it works: wrap the CardView in a layout and set a padding/margin on the parent layout to mimic the divider, and force the normal divider to null

list_item.xml

<LinearLayout
    android:id="@+id/entry_item_layout_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingBottom="<divider_size>" > // this is the divider
    <CardView
        android:layout_width="<width_size>"
        android:layout_height="<height_size>">
        ...
    </CardView>
</LinearLayout

list.xml

<RecyclerView
 android:divider="@null"
 android:layout_width="<width_size>"
 android:layout_height="<height_size>"
 ...
/>

RecyclerView onClick

You can pass a clickListener to Adapter.

In your Activity:

private View.OnClickListener mItemClick = new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        Intent intent = null;
        int position = list.getChildPosition(v);
        switch (position) {
            case 0:
                intent = new Intent(MainActivity.this, LeakCanaryActivity.class);
                break;
            case 1:
                intent = new Intent(MainActivity.this, ButterKnifeFragmentActivity.class);
                break;
        }
        if (intent != null) {
            MainActivity.this.startActivity(intent);
        }
    }
};

then pass it to Adapter:

MainAdapter mainAdapter = new MainAdapter(this, mItemClick);

In Adapter's onCreateViewHolder:

 @Override
public MainAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
    View itemView = activity.getLayoutInflater().inflate(R.layout.main_adapter_item, viewGroup, false);
    ViewHolder holder = new ViewHolder(itemView);
    itemView.setOnClickListener(mItemClick);
    return holder;
}

How to import RecyclerView for Android L-preview

My dependencies;

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:25.1.0'

    //RecyclerView dependency
    compile 'com.android.support:recyclerview-v7:25.1.0'

    // Instrumentation dependencies use androidTestCompile
    // (as opposed to testCompile for local unit tests run in the JVM)
    androidTestCompile 'junit:junit:4.12'
    androidTestCompile 'com.android.support:support-annotations:25.1.0'
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support.test:rules:0.5'
}

I added only compile 'com.android.support:recyclerview-v7:25.1.0'. The important thing is to add RecycleView dependency which is as the same version as appcompat

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

Go to your web.config/App.config to verify which .net runtime you are using

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>

Here is the solution:

  1. .NET 4.6 and above. You don’t need to do any additional work to support TLS 1.2, it’s supported by default.

  2. .NET 4.5. TLS 1.2 is supported, but it’s not a default protocol. You need to opt-in to use it. The following code will make TLS 1.2 default, make sure to execute it before making a connection to secured resource:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

  1. .NET 4.0. TLS 1.2 is not supported, but if you have .NET 4.5 (or above) installed on the system then you still can opt in for TLS 1.2 even if your application framework doesn’t support it. The only problem is that SecurityProtocolType in .NET 4.0 doesn’t have an entry for TLS1.2, so we’d have to use a numerical representation of this enum value:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

  1. .NET 3.5 or below. TLS 1.2 is not supported (*) and there is no workaround. Upgrade your application to more recent version of the framework.

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

Shouldn't you add to the login form?;

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> 

As stated in the here in the Spring security documentation

IIS: Idle Timeout vs Recycle

IIS now has

Idle Time-out Action : Suspend setting

Suspending is just freezes the process and it is much more efficient than the destroying the process.

Android findViewById() in Custom View

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    ImageHolder holder = null;
    if (row == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ImageHolder();
        editText = (EditText) row.findViewById(R.id.id_number_custom);
        loadButton = (ImageButton) row.findViewById(R.id.load_data_button);
        row.setTag(holder);
    } else {
        holder = (ImageHolder) row.getTag();
    }


    holder.editText.setText("Your Value");
    holder.loadButton.setImageBitmap("Your Bitmap Value");
    return row;
}

Fixing slow initial load for IIS

I was getting a consistent 15 second delay on the first request after 4 minutes of inactivity. My problem was that my app was using Windows Integrated Authentication to SQL Server and the service profile was in a different domain than the server. This caused a cross-domain authentication from IIS to SQL upon app initialization - and this was the real source of my delay. I changed to using a SQL login instead of windows authentication. The delay was immediately gone. I still have all the app initialization settings in place to help improve performance but they may have not been needed at all in my case.

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

I had this problem and found that removing the following folder helped, even with the non-Express edition.Express:

C:\Users\<user>\Documents\IISExpress

Save bitmap to file function

Two example works for me, for your reference.

Bitmap bitmap = Utils.decodeBase64(base64);
try {
    File file = new File(filePath);
    FileOutputStream fOut = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();
}
catch (Exception e) {
    e.printStackTrace();
    LOG.i(null, "Save file error!");
    return false;
}

and this one

Bitmap savePic = Utils.decodeBase64(base64);
File file = new File(filePath);
File path = new File(file.getParent());

if (savePic != null) {
    try {
        // build directory
        if (file.getParent() != null && !path.isDirectory()) {
            path.mkdirs();
        }
        // output image to file
        FileOutputStream fos = new FileOutputStream(filePath);
        savePic.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
        ret = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
} else {
    LOG.i(TAG, "savePicture image parsing error");
}

How to Find App Pool Recycles in Event Log

It seemed quite hard to find this information, but eventually, I came across this question
You have to look at the 'System' event log, and filter by the WAS source.
Here is more info about the WAS (Windows Process Activation Service)

how to empty recyclebin through command prompt?

Create cmd file with line:

for %%p in (C D E F G H I J K L M N O P Q R S T U V W X Y Z) do if exist "%%p:\$Recycle.Bin" rundll32.exe advpack.dll,DelNodeRunDLL32 "%%p:\$Recycle.Bin"

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

I have build such kind of application using approximatively the same approach except :

  • I cache the generated image on the disk and always generate two to three images in advance in a separate thread.
  • I don't overlay with a UIImage but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.

Whenever the user start zooming, I acquire the CGPDFPage and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context is like :

CGAffineTransform currentCTM = CGContextGetCTM(context);    
if (currentCTM.a == 1.0 && baseImage) {
    //Calculate ideal scale
    CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
    CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height; 
    CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);

    CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
    CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
    CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
    @synchronized(issue) { 
        CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
        pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
        CGContextConcatCTM(context, pdfToPageTransform);    
        CGContextDrawPDFPage(context, pdfPage);
    }
}

issue is the object containg the CGPDFDocumentRef. I synchronize the part where I access the pdfDoc property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef object do some internal caching that I did not find how to get rid of.

How can I make a horizontal ListView in Android?

This might be a very late reply but it is working for us. We are using the same gallery provided by Android, just that, we have adjusted the left margin such a way that the screens left end is considered as Gallery's center. That really worked well for us.

How to get the file name from a full path using JavaScript?

The complete answer is:

<html>
    <head>
        <title>Testing File Upload Inputs</title>
        <script type="text/javascript">

        function replaceAll(txt, replace, with_this) {
            return txt.replace(new RegExp(replace, 'g'),with_this);
        }

        function showSrc() {
            document.getElementById("myframe").href = document.getElementById("myfile").value;
            var theexa = document.getElementById("myframe").href.replace("file:///","");
            var path = document.getElementById("myframe").href.replace("file:///","");
            var correctPath = replaceAll(path,"%20"," ");
            alert(correctPath);
        }
        </script>
    </head>
    <body>
        <form method="get" action="#"  >
            <input type="file"
                   id="myfile"
                   onChange="javascript:showSrc();"
                   size="30">
            <br>
            <a href="#" id="myframe"></a>
        </form>
    </body>
</html>

What's the fastest way to delete a large folder in Windows?

The worst way is to send to Recycle Bin: you still need to delete them. Next worst is shift+delete with Windows Explorer: it wastes loads of time checking the contents before starting deleting anything.

Next best is to use rmdir /s/q foldername from the command line. del /f/s/q foldername is good too, but it leaves behind the directory structure.

The best I've found is a two line batch file with a first pass to delete files and outputs to nul to avoid the overhead of writing to screen for every singe file. A second pass then cleans up the remaining directory structure:

del /f/s/q foldername > nul
rmdir /s/q foldername

This is nearly three times faster than a single rmdir, based on time tests with a Windows XP encrypted disk, deleting ~30GB/1,000,000 files/15,000 folders: rmdir takes ~2.5 hours, del+rmdir takes ~53 minutes. More info at Super User.

This is a regular task for me, so I usually move the stuff I need to delete to C:\stufftodelete and have those del+rmdir commands in a deletestuff.bat batch file. This is scheduled to run at night, but sometimes I need to run it during the day so the quicker the better.

Technet documentation for del command can be found here. Additional info on the parameters used above:

  • /f - Force (i.e. delete files even if they're read only)
  • /s - Recursive / Include Subfolders (this definition from SS64, as technet simply states "specified files", which isn't helpful).
  • /q - Quiet (i.e. do not prompt user for confirmation)

Documentation for rmdir here. Parameters are:

  • /s - Recursive (i.e. same as del's /s parameter)
  • /q - Quiet (i.e. same as del's /q parameter)

Specifying trust store information in spring boot application.properties

I was also having the same issue with Spring Boot and embedded Tomcat.

From what I understand these properties only set the Tomcat configuration parameters. According to the Tomcat documentation this is only used for Client authentication (i.e. for two-way SSL) and not for verifying remote certificates:

truststoreFile - The trust store file to use to validate client certificates.

https://tomcat.apache.org/tomcat-8.0-doc/config/http.html

In order to configure the trust store for HttpClient it largely depends on the HttpClient implementation you use. For instance for RestTemplate by default Spring Boot uses a SimpleClientHttpRequestFactory based on standard J2SE classes like java.net.HttpURLConnection.

I've come up with a solution based on the Apache HttpClient docs and these posts: http://vincentdevillers.blogspot.pt/2013/02/configure-best-spring-resttemplate.html http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/

Basically this allows for a RestTemplate bean that only trusts certificates signed by the root CA in the configured truststore.

@Configuration
public class RestClientConfig {

    // e.g. Add http.client.ssl.trust-store=classpath:ssl/truststore.jks to application.properties
    @Value("${http.client.ssl.trust-store}")
    private Resource trustStore;

    @Value("${http.client.ssl.trust-store-password}")
    private char[] trustStorePassword;

    @Value("${http.client.maxPoolSize}")
    private Integer maxPoolSize;


    @Bean
    public ClientHttpRequestFactory httpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    @Bean
    public HttpClient httpClient() {

        // Trust own CA and all child certs
        Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
        try {
            SSLContext sslContext = SSLContexts
                    .custom()
                    .loadTrustMaterial(trustStore.getFile(),
                            trustStorePassword)
                    .build();

            // Since only our own certs are trusted, hostname verification is probably safe to bypass
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    new HostnameVerifier() {

                        @Override
                        public boolean verify(final String hostname,
                                final SSLSession session) {
                            return true;
                        }
            });

            socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslSocketFactory)
                    .build();           

        } catch (Exception e) {
            //TODO: handle exceptions
            e.printStackTrace();
        }

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        connectionManager.setMaxTotal(maxPoolSize);
        // This client is for internal connections so only one route is expected
        connectionManager.setDefaultMaxPerRoute(maxPoolSize);
        return HttpClientBuilder.create()
                .setConnectionManager(connectionManager)
                .disableCookieManagement()
                .disableAuthCaching()
                .build();
    }

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(httpRequestFactory());
        return restTemplate;
    }    
}

And then you can use this custom Rest client whenever you need to, e.g.:

@Autowired
private RestTemplate restTemplate;

restTemplate.getForEntity(...)

This assumes your trying to connect to a Rest endpoint, but you can also use the above HttpClient bean for whatever you want.

Query EC2 tags from within instance

For those crazy enough to use Fish shell on EC2, here's a handy snippet for your /home/ec2-user/.config/fish/config.fish. The hostdata command now will list all your tags as well as the public IP and hostname.

set -x INSTANCE_ID (wget -qO- http://instance-data/latest/meta-data/instance-id)
set -x REGION (wget -qO- http://instance-data/latest/meta-data/placement/availability-zone | sed 's/.$//')

function hostdata
    aws ec2 describe-tags --region $REGION --filter "Name=resource-id,Values=$INSTANCE_ID" --output=text | sed -r 's/TAGS\t(.*)\t.*\t.*\t(.*)/\1="\2"/'
    ec2-metadata | grep public-hostname
    ec2-metadata | grep public-ipv4
end

How to dump a dict to a json file?

Combine the answer of @mgilson and @gnibbler, I found what I need was this:


d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
j = json.dumps(d, indent=4)
f = open('sample.json', 'w')
print >> f, j
f.close()

It this way, I got a pretty-print json file. The tricks print >> f, j is found from here: http://www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/

How to dump only specific tables from MySQL?

If you're in local machine then use this command

/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

For remote machine, use below one

/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

SVN remains in conflict?

Ok here's how to fix it:

svn remove --force filename
svn resolve --accept=working  filename
svn commit

more details are at: http://svnbook.red-bean.com/en/1.8/svn.tour.treeconflicts.html

What is the correct JSON content type?

Always try to remember these three content types even though there are many content types. as you may have to use these more frequently.

  • Content-Type: application/json
  • Content-Type: application/xml
  • Content-Type: text/html

PHP 7: Missing VCRUNTIME140.dll

On the side bar of the PHP 7 alpha download page, it does say this:

VC9, VC11 & VC14 More recent versions of PHP are built with VC9, VC11 or VC14 (Visual Studio 2008, 2012 or 2015 compiler respectively) and include improvements in performance and stability.

  • The VC9 builds require you to have the Visual C++ Redistributable for Visual Studio 2008 SP1 x86 or x64 installed

  • The VC11 builds require to have the Visual C++ Redistributable for Visual Studio 2012 x86 or x64 installed

  • The VC14 builds require to have the Visual C++ Redistributable for Visual Studio 2015 x86 or x64 installed

There's been a problem with some of those links, so the files are also available from Softpedia.

In the case of the PHP 7 alpha, it's the last option that's required.

I think that the placement of this information is poor, as it's kind of marginalized (i.e.: it's basically literally in the margin!) whereas it's actually critical for the software to run.

I documented my experiences of getting PHP 7 alpha up and running on Windows 8.1 in PHP: getting PHP7 alpha running on Windows 8.1, and it covers some more symptoms that might crop up. They're out of scope for this question but might help other people.

Other symptom of this issue:

  • Apache not starting, claiming php7apache2_4.dll is missing despite it definitely being in place, and offering nothing else in any log.
  • php-cgi.exe - The FastCGI process exited unexpectedly (as per @ftexperts's comment below)

Attempted solution:

  • Using the php7apache2_4.dll file from an earlier PHP 7 dev build. This did not work.

(I include those for googleability.)

how to add value to combobox item

Now you can use insert method instead add

' Visual Basic
CheckedListBox1.Items.Insert(0, "Copenhagen")

How to compare two NSDates: Which is more recent?

NSDate has a compare function.

compare: Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.

(NSComparisonResult)compare:(NSDate *)anotherDate

Parameters: anotherDate The date with which to compare the receiver. This value must not be nil. If the value is nil, the behavior is undefined and may change in future versions of Mac OS X.

Return Value:

  • If the receiver and anotherDate are exactly equal to each other, NSOrderedSame
  • If the receiver is later in time than anotherDate, NSOrderedDescending
  • If the receiver is earlier in time than anotherDate, NSOrderedAscending.

Validate Dynamically Added Input fields

Try using input arrays:

<form action="try.php" method="post">
    <div id="events_wrapper">
        <div id="sub_events">
            <input type="text" name="firstname[]" />                                       
        </div>
    </div>
    <input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
    <input type="submit" name="submit" value="submit" />
</form>

and add this script and jQuery, using foreach() to retrieve the data being $_POST'ed:

<script>                                                                                    
    $(document).ready(function(){
        $("#add_another_event").click(function(){
        var $address = $('#sub_events');
        var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
        var newNum = num + 1;
        var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');

        //set all div id's and the input id's
        newElem.children('div').each (function (i) {
            this.id = 'input' + (newNum*5 + i);
        });

        newElem.find('input').each (function () {
            this.id = this.id + newNum;
            this.name = this.name + newNum;
        });

        if (num > 0) {
            $('.clonedAddress:last').after(newElem);
        } else {
            $address.after(newElem);
        }

        $('#btnDel').removeAttr('disabled');
        });

        $("#remove").click(function(){

        });

    });
</script>

How do you remove duplicates from a list whilst preserving order?

An in-place method

This method is quadratic, because we have a linear lookup into the list for every element of the list (to that we have to add the cost of rearranging the list because of the del s).

That said, it is possible to operate in place if we start from the end of the list and proceed toward the origin removing each term that is present in the sub-list at its left

This idea in code is simply

for i in range(len(l)-1,0,-1): 
    if l[i] in l[:i]: del l[i] 

A simple test of the implementation

In [91]: from random import randint, seed                                                                                            
In [92]: seed('20080808') ; l = [randint(1,6) for _ in range(12)] # Beijing Olympics                                                                 
In [93]: for i in range(len(l)-1,0,-1): 
    ...:     print(l) 
    ...:     print(i, l[i], l[:i], end='') 
    ...:     if l[i] in l[:i]: 
    ...:          print( ': remove', l[i]) 
    ...:          del l[i] 
    ...:     else: 
    ...:          print() 
    ...: print(l)
[6, 5, 1, 4, 6, 1, 6, 2, 2, 4, 5, 2]
11 2 [6, 5, 1, 4, 6, 1, 6, 2, 2, 4, 5]: remove 2
[6, 5, 1, 4, 6, 1, 6, 2, 2, 4, 5]
10 5 [6, 5, 1, 4, 6, 1, 6, 2, 2, 4]: remove 5
[6, 5, 1, 4, 6, 1, 6, 2, 2, 4]
9 4 [6, 5, 1, 4, 6, 1, 6, 2, 2]: remove 4
[6, 5, 1, 4, 6, 1, 6, 2, 2]
8 2 [6, 5, 1, 4, 6, 1, 6, 2]: remove 2
[6, 5, 1, 4, 6, 1, 6, 2]
7 2 [6, 5, 1, 4, 6, 1, 6]
[6, 5, 1, 4, 6, 1, 6, 2]
6 6 [6, 5, 1, 4, 6, 1]: remove 6
[6, 5, 1, 4, 6, 1, 2]
5 1 [6, 5, 1, 4, 6]: remove 1
[6, 5, 1, 4, 6, 2]
4 6 [6, 5, 1, 4]: remove 6
[6, 5, 1, 4, 2]
3 4 [6, 5, 1]
[6, 5, 1, 4, 2]
2 1 [6, 5]
[6, 5, 1, 4, 2]
1 5 [6]
[6, 5, 1, 4, 2]

In [94]:                                                                                                                             

How to plot two columns of a pandas data frame using points?

Pandas uses matplotlib as a library for basic plots. The easiest way in your case will using the following:

import pandas as pd
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20)}
df= pd.DataFrame(sample_data)
df.plot(x='col_name_1', y='col_name_2', style='o')

enter image description here

However, I would recommend to use seaborn as an alternative solution if you want have more customized plots while not going into the basic level of matplotlib. In this case you the solution will be following:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20)}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df)

enter image description here

Is there a way to get colored text in GitHubflavored Markdown?

As an alternative to rendering a raster image, you can embed a SVG:

https://gist.github.com/CyberShadow/95621a949b07db295000

Unfortunately, even though you can select and copy text when you open the .svg file, the text is not selectable when the SVG image is embedded.

Text not wrapping in p tag

That is because you have continuous text, means single long word without space. To break it add word-break: break-all;

.submenu div p {
    color:#fff;
    margin: 0;
    padding:0;
    width:100%;
    position: relative; word-break: break-all; background:red
}

DEMO

How do I find all the files that were created today in Unix/Linux?

If you're did something like accidentally rsync'd to the wrong directory, the above suggestions work to find new files, but for me, the easiest was connecting with an SFTP client like Transmit then ordering by date and deleting.

Can I run multiple programs in a Docker container?

There can be only one ENTRYPOINT, but that target is usually a script that launches as many programs that are needed. You can additionally use for example Supervisord or similar to take care of launching multiple services inside single container. This is an example of a docker container running mysql, apache and wordpress within a single container.

Say, You have one database that is used by a single web application. Then it is probably easier to run both in a single container.

If You have a shared database that is used by more than one application, then it would be better to run the database in its own container and the applications each in their own containers.

There are at least two possibilities how the applications can communicate with each other when they are running in different containers:

  1. Use exposed IP ports and connect via them.
  2. Recent docker versions support linking.

How to access local files of the filesystem in the Android emulator?

You can use the adb command which comes in the tools dir of the SDK:

adb shell

It will give you a command line prompt where you can browse and access the filesystem. Or you can extract the files you want:

adb pull /sdcard/the_file_you_want.txt

Also, if you use eclipse with the ADT, there's a view to browse the file system (Window->Show View->Other... and choose Android->File Explorer)

How do I position an image at the bottom of div?

< img style="vertical-align: bottom" src="blah.png" >

Works for me. Inside a parallax div as well.

Simple regular expression for a decimal with a precision of 2

This worked with me:

(-?[0-9]+(\.[0-9]+)?)

Group 1 is the your float number and group 2 is the fraction only.

How do you specify a debugger program in Code::Blocks 12.11?

  1. Go to settings >> Debugger.
  2. Now as you can see in the image below. There's a tree. Common->GDB/CDB Debugger -> Default. enter image description here

  3. Click on executable path (on the right) to find the address to gdb32.exe .

  4. Click gdb32.exe >> OK.

THATS IT!! This worked for me.

Is there a css cross-browser value for "width: -moz-fit-content;"?

At last I fixed it simply using:

display: table;

Converting a date in MySQL from string field

STR_TO_DATE allows you to do this, and it has a format argument.

Parallel.ForEach vs Task.Factory.StartNew

Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.

How to make a JFrame button open another JFrame class in Netbeans?

This link works with me: video

The answer posted before didn't work for me until the second click

So what I did is Directly call:

        new NewForm().setVisible(true);

        this.dispose();//to close the current jframe

How to use jQuery in AngularJS

The best option is create a directive and wrap the slider features there. The secret is use $timeout, the jquery code will be called only when DOM is ready.

angular.module('app')
.directive('my-slider', 
    ['$timeout', function($timeout) {
        return {
            restrict:'E',
            scope: true,
            template: '<div id="{{ id }}"></div>',
            link: function($scope) {
                $scope.id = String(Math.random()).substr(2, 8);

                $timeout(function() {
                    angular.element('#'+$scope.id).slider();                    
                });
            }
        };
    }]
);

Reading a cell value in Excel vba and write in another Cell

The individual alphabets or symbols residing in a single cell can be inserted into different cells in different columns by the following code:

For i = 1 To Len(Cells(1, 1))
Cells(2, i) = Mid(Cells(1, 1), i, 1)
Next

If you do not want the symbols like colon to be inserted put an if condition in the loop.

How to reset sequence in postgres and fill id column with new data?

The best way to reset a sequence to start back with number 1 is to execute the following:

ALTER SEQUENCE <tablename>_<id>_seq RESTART WITH 1

So, for example for the users table it would be:

ALTER SEQUENCE users_id_seq RESTART WITH 1

Reading binary file and looping over each byte

To read a file — one byte at a time (ignoring the buffering) — you could use the two-argument iter(callable, sentinel) built-in function:

with open(filename, 'rb') as file:
    for byte in iter(lambda: file.read(1), b''):
        # Do stuff with byte

It calls file.read(1) until it returns nothing b'' (empty bytestring). The memory doesn't grow unlimited for large files. You could pass buffering=0 to open(), to disable the buffering — it guarantees that only one byte is read per iteration (slow).

with-statement closes the file automatically — including the case when the code underneath raises an exception.

Despite the presence of internal buffering by default, it is still inefficient to process one byte at a time. For example, here's the blackhole.py utility that eats everything it is given:

#!/usr/bin/env python3
"""Discard all input. `cat > /dev/null` analog."""
import sys
from functools import partial
from collections import deque

chunksize = int(sys.argv[1]) if len(sys.argv) > 1 else (1 << 15)
deque(iter(partial(sys.stdin.detach().read, chunksize), b''), maxlen=0)

Example:

$ dd if=/dev/zero bs=1M count=1000 | python3 blackhole.py

It processes ~1.5 GB/s when chunksize == 32768 on my machine and only ~7.5 MB/s when chunksize == 1. That is, it is 200 times slower to read one byte at a time. Take it into account if you can rewrite your processing to use more than one byte at a time and if you need performance.

mmap allows you to treat a file as a bytearray and a file object simultaneously. It can serve as an alternative to loading the whole file in memory if you need access both interfaces. In particular, you can iterate one byte at a time over a memory-mapped file just using a plain for-loop:

from mmap import ACCESS_READ, mmap

with open(filename, 'rb', 0) as f, mmap(f.fileno(), 0, access=ACCESS_READ) as s:
    for byte in s: # length is equal to the current file size
        # Do stuff with byte

mmap supports the slice notation. For example, mm[i:i+len] returns len bytes from the file starting at position i. The context manager protocol is not supported before Python 3.2; you need to call mm.close() explicitly in this case. Iterating over each byte using mmap consumes more memory than file.read(1), but mmap is an order of magnitude faster.

How do I link a JavaScript file to a HTML file?

Below you have some VALID html5 example document. The type attribute in script tag is not mandatory in HTML5.

You use jquery by $ charater. Put libraries (like jquery) in <head> tag - but your script put allways at the bottom of document (<body> tag) - due this you will be sure that all libraries and html document will be loaded when your script execution starts. You can also use src attribute in bottom script tag to include you script file instead of putting direct js code like above.

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="utf-8">_x000D_
    <title>Example</title>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
    <div>Im the content</div>_x000D_
_x000D_
    <script>_x000D_
        alert( $('div').text() ); // show message with div content_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Deploying website: 500 - Internal server error

For me, the following code in the web.config was the culprit. When I removed it, the web site worked fine.

  <staticContent>
    <mimeMap fileExtension=".mp4" mimeType="video/mp4" />
  </staticContent>

Syntax for a single-line Bash infinite while loop

while true; do foo; sleep 2; done

By the way, if you type it as a multiline (as you are showing) at the command prompt and then call the history with arrow up, you will get it on a single line, correctly punctuated.

$ while true
> do
>    echo "hello"
>    sleep 2
> done
hello
hello
hello
^C
$ <arrow up> while true; do    echo "hello";    sleep 2; done

How do I calculate power-of in C#?

You are looking for the static method Math.Pow().

Fetch API with Cookie

Have just solved. Just two f. days of brutforce

For me the secret was in following:

  1. I called POST /api/auth and see that cookies were successfully received.

  2. Then calling GET /api/users/ with credentials: 'include' and got 401 unauth, because of no cookies were sent with the request.

The KEY is to set credentials: 'include' for the first /api/auth call too.

Pretty printing XML in Python

Take a look at the vkbeautify module.

It is a python version of my very popular javascript/nodejs plugin with the same name. It can pretty-print/minify XML, JSON and CSS text. Input and output can be string/file in any combinations. It is very compact and doesn't have any dependency.

Examples:

import vkbeautify as vkb

vkb.xml(text)                       
vkb.xml(text, 'path/to/dest/file')  
vkb.xml('path/to/src/file')        
vkb.xml('path/to/src/file', 'path/to/dest/file') 

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

You could try "Clean Tomcat Work Directory" or simply "Clean..". This supposed to discard all published state and republish from scratch.

In Python, how do I iterate over a dictionary in sorted key order?

sorted returns a list, hence your error when you try to iterate over it, but because you can't order a dict you will have to deal with a list.

I have no idea what the larger context of your code is, but you could try adding an iterator to the resulting list. like this maybe?:

return iter(sorted(dict.iteritems()))

of course you will be getting back tuples now because sorted turned your dict into a list of tuples

ex: say your dict was: {'a':1,'c':3,'b':2} sorted turns it into a list:

[('a',1),('b',2),('c',3)]

so when you actually iterate over the list you get back (in this example) a tuple composed of a string and an integer, but at least you will be able to iterate over it.

AndroidStudio SDK directory does not exists

Choose one of the options- OPTION A

  1. Delete the 'local.properties' file in 'Gradle Script'
  2. Create new 'local.properties' file there
  3. Paste this into your new 'local.properties' file sdk.dir=/Users/uttam/Library/Android/sdk

OPTION B

  1. copy the 'local.properties' file from your any old project.
  2. paste this in your new project, you will be asked confirmation, choose 'replace'

HAPPY CODING :)

Choosing line type and color in Gnuplot 4.0

I know the question is old but I found this very helpful http://www.gnuplot.info/demo_canvas/dashcolor.html . So you can choose linetype and linecolor separately but you have to precede everything by "set termoption dash" (worked for me in gnuplot 4.4).

Convert String to equivalent Enum value

Assuming you use Java 5 enums (which is not so certain since you mention old Enumeration class), you can use the valueOf method of java.lang.Enum subclass:

MyEnum e = MyEnum.valueOf("ONE_OF_CONSTANTS");

Changing :hover to touch/click for mobile devices

I got the same trouble, in mobile device with Microsoft's Edge browser. I can solve the problem with: aria-haspopup="true". It need to add to the div and the :hover, :active, :focus for the other mobile browsers.

Example html:

<div class="left_bar" aria-haspopup="true">

CSS:

.left_bar:hover, .left_bar:focus, .left_bar:active{
    left: 0%;
    }

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

You need to re-add that certificate to your machine or chose another certificate.

To choose another certificate or to recreate one, head over to the Project's properties page, click on Signing tab and either

  • Click on Select from store
  • Click on Select from file
  • Click on Create test certificate

Once either of these is done, you should be able to build it again.

jquery validate check at least one checkbox

The validate plugin will only validate the current/focused element.Therefore you will need to add a custom rule to the validator to validate all the checkboxes. Similar to the answer above.

$.validator.addMethod("roles", function(value, elem, param) {
   return $(".roles:checkbox:checked").length > 0;
},"You must select at least one!");

And on the element:

<input class='{roles: true}' name='roles' type='checkbox' value='1' />

In addition, you will likely find the error message display, not quite sufficient. Only 1 checkbox is highlighted and only 1 message displayed. If you click another separate checkbox, which then returns a valid for the second checkbox, the original one is still marked as invalid, and the error message is still displayed, despite the form being valid. I have always resorted to just displaying and hiding the errors myself in this case.The validator then only takes care of not submitting the form.

The other option you have is to write a function that will change the value of a hidden input to be "valid" on the click of a checkbox and then attach the validation rule to the hidden element. This will only validate in the onSubmit event though, but will display and hide messages at the appropriate times. Those are about the only options that you can use with the validate plugin.

Hope that helps!

Checking if type == list in python

Python 3.7.7

import typing
if isinstance([1, 2, 3, 4, 5] , typing.List):
    print("It is a list")

Stacked bar chart

You need to transform your data to long format and shouldn't use $ inside aes:

DF <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

library(reshape2)
DF1 <- melt(DF, id.var="Rank")

library(ggplot2)
ggplot(DF1, aes(x = Rank, y = value, fill = variable)) + 
  geom_bar(stat = "identity")

enter image description here

Specify a Root Path of your HTML directory for script links?

I recommend using the HTML <base> element:

<head>
    <base href="http://www.example.com/default/">
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
</head>

In this example, the stylesheet is located in http://www.example.com/default/style.css, the script in http://www.example.com/default/script.js. The advantage of <base> over / is that it is more flexible. Your whole website can be located in a subdirectory of a domain, and you can easily alter the default directory of your website.

Matplotlib/pyplot: How to enforce axis range?

Try putting the call to axis after all plotting commands.

How to get root access on Android emulator?

I know this question is pretty old. But we can able to get root in Emulator with the help of Magisk by following https://github.com/shakalaca/MagiskOnEmulator

Basically, it patch initrd.img(if present) and ramdisk.img for working with Magisk.

How to find a number in a string using JavaScript?

// stringValue can be anything in which present any number
`const stringValue = 'last_15_days';
// /\d+/g is regex which is used for matching number in string
// match helps to find result according to regex from string and return match value
 const result = stringValue.match(/\d+/g);
 console.log(result);`

output will be 15

If You want to learn more about regex here are some links:

https://www.w3schools.com/jsref/jsref_obj_regexp.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

https://www.tutorialspoint.com/javascript/javascript_regexp_object.htm

How to pass parameters using ui-sref in ui-router to controller

You don't necessarily need to have the parameters inside the URL.

For instance, with:

$stateProvider
.state('home', {
  url: '/',
  views: {
    '': {
      templateUrl: 'home.html',
      controller: 'MainRootCtrl'

    },
  },
  params: {
    foo: null,
    bar: null
  }
})

You will be able to send parameters to the state, using either:

$state.go('home', {foo: true, bar: 1});
// or
<a ui-sref="home({foo: true, bar: 1})">Go!</a>

Of course, if you reload the page once on the home state, you will loose the state parameters, as they are not stored anywhere.

A full description of this behavior is documented here, under the params row in the state(name, stateConfig) section.

Javascript counting number of objects in object

In recent browsers you can use:

Object.keys(obj.Data).length

See MDN

For older browsers, use the for-in loop in Michael Geary's answer.

How to kill a process running on particular port in Linux?

To know the pid of service running on particular port :

netstat -tulnap | grep :*port_num*

you will get the description of that process. Now use kill or kill -9 pid. Easily killed.

e.g

netstat -ap | grep :8080

tcp6       0      0 :::8080       :::*    LISTEN      1880/java 

Now:

kill -9 1880

Remember to run all commands as root

using if else with eval in aspx page

 <%if (System.Configuration.ConfigurationManager.AppSettings["OperationalMode"] != "live") {%>
                        &nbsp;[<%=System.Environment.MachineName%>]
                        <%}%>

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

Make use of Parameter Grouping (Laravel 4.2). For your example, it'd be something like this:

Model::where(function ($query) {
    $query->where('a', '=', 1)
          ->orWhere('b', '=', 1);
})->where(function ($query) {
    $query->where('c', '=', 1)
          ->orWhere('d', '=', 1);
});

Bootstrap 4 navbar color

Update 2019

Remember that whatever CSS overrides you define must be the same CSS specificity or greater in order to properly override Bootstrap's CSS.

Bootstrap 4.1+

The Navbar is transparent by default. If you only want to change the background color, it can be done simply by applying the color to the <navbar class="bg-custom">, but remember that won't change the other colors such as the links, hover and dropdown menu colors.

Here's CSS that will change any relevant Navbar colors in Bootstrap 4...

/* change the background color */
.navbar-custom {
    background-color: #ff5500;
}
/* change the brand and text color */
.navbar-custom .navbar-brand,
.navbar-custom .navbar-text {
    color: rgba(255,255,255,.8);
}
/* change the link color */
.navbar-custom .navbar-nav .nav-link {
    color: rgba(255,255,255,.5);
}
/* change the color of active or hovered links */
.navbar-custom .nav-item.active .nav-link,
.navbar-custom .nav-item:focus .nav-link,
.navbar-custom .nav-item:hover .nav-link {
    color: #ffffff;
}

Demo: http://www.codeply.com/go/U9I2byZ3tS


Override Navbar Light or Dark

If you're using the Bootstrap 4 Navbar navbar-light or navbar-dark classes, then use this in the overrides. For example, changing the Navbar link colors...

.navbar-light .nav-item.active .nav-link,
.navbar-light .nav-item:focus .nav-link,
.navbar-light .nav-item:hover .nav-link {
        color: #ffffff;
}

When making any Bootstrap customizations, you need to understand CSS Specificity. Overrides in your custom CSS need to use selectors that are as specific as the bootstrap.css. Read more


Transparent Navbar

Notice that the Bootstrap 4 Navbar is transparent by default. Use navbar-dark for dark/bold background colors, and use navbar-light if the navbar is a lighter color. This will effect the color of the text and color of the toggler icon as explained here.

Related: https://stackoverflow.com/a/18530995/171456

Is there a way to pass jvm args via command line to maven?

I think MAVEN_OPTS would be most appropriate for you. See here: http://maven.apache.org/configure.html

In Unix:

Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.

In Win, you need to set environment variable via the dialogue box

Add ... environment variable by opening up the system properties (WinKey + Pause),... In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.

How to return a result from a VBA function

Just setting the return value to the function name is still not exactly the same as the Java (or other) return statement, because in java, return exits the function, like this:

public int test(int x) {
    if (x == 1) {
        return 1; // exits immediately
    }

    // still here? return 0 as default.
    return 0;
}

In VB, the exact equivalent takes two lines if you are not setting the return value at the end of your function. So, in VB the exact corollary would look like this:

Public Function test(ByVal x As Integer) As Integer
    If x = 1 Then
        test = 1 ' does not exit immediately. You must manually terminate...
        Exit Function ' to exit
    End If

    ' Still here? return 0 as default.
    test = 0
    ' no need for an Exit Function because we're about to exit anyway.
End Function 

Since this is the case, it's also nice to know that you can use the return variable like any other variable in the method. Like this:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test <> 1 Then ' Test the currently set return value
        test = 0 ' Reset the return value to a *new* value
    End If

End Function 

Or, the extreme example of how the return variable works (but not necessarily a good example of how you should actually code)—the one that will keep you up at night:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test > 0 Then

        ' RECURSIVE CALL...WITH THE RETURN VALUE AS AN ARGUMENT,
        ' AND THE RESULT RESETTING THE RETURN VALUE.
        test = test(test - 1)

    End If

End Function

How do I disable right click on my web page?

Do it like below (It works on firefox too):

$(document).on("contextmenu",function(e){

     if( e.button == 2 ) {
         e.preventDefault();
          callYourownFucntionOrCodeHere();
     }
return true;
});

Best way of invoking getter by reflection

You can use Reflections framework for this

import static org.reflections.ReflectionUtils.*;
Set<Method> getters = ReflectionUtils.getAllMethods(someClass,
      withModifier(Modifier.PUBLIC), withPrefix("get"), withAnnotation(annotation));

How to change the Eclipse default workspace?

On Ubuntu I went to

~/.eclipse/org.eclipse.platform_4.3.0_1473617060_linux_gtk_x86_64/configuration/config.ini 

and added this line at the bottom

[email protected]/workspace

and changed workspace to the dir path from my home to where I put my workspace.

I combined @Frank answer with @Ronan Quillevere's comment

Android java.exe finished with non-zero exit value 1

I've had the same issue just now, and it turned out to be caused by a faulty attrs.xml file in one of my modules. The file initially had two stylable attributes for one of my custom views, but I had deleted one when it turned out I no longer needed it. This was apparently, however, not registered correctly with the IDE and so the build failed when it couldn't find the attribute.

The solution for me was to re-add the attribute, run a clean project after which the build succeeded and I could succesfully remove the attribute again without any further problems.

Hope this helps someone.

How to SSH to a VirtualBox guest externally through a host?

Use NAT network adapter and Add port forward. Mention actual host ip.Do not use 127.0.0.1 or localhost.

Removing html5 required attribute with jQuery

Using Javascript:

document.querySelector('#edit-submitted-first-name').required = false;

Using jQuery:

$('#edit-submitted-first-name').removeAttr('required');

What is Java String interning?

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()

Basically doing String.intern() on a series of strings will ensure that all strings having same contents share same memory. So if you have list of names where 'john' appears 1000 times, by interning you ensure only one 'john' is actually allocated memory.

This can be useful to reduce memory requirements of your program. But be aware that the cache is maintained by JVM in permanent memory pool which is usually limited in size compared to heap so you should not use intern if you don't have too many duplicate values.


More on memory constraints of using intern()

On one hand, it is true that you can remove String duplicates by internalizing them. The problem is that the internalized strings go to the Permanent Generation, which is an area of the JVM that is reserved for non-user objects, like Classes, Methods and other internal JVM objects. The size of this area is limited, and is usually much smaller than the heap. Calling intern() on a String has the effect of moving it out from the heap into the permanent generation, and you risk running out of PermGen space.

-- From: http://www.codeinstructions.com/2009/01/busting-javalangstringintern-myths.html


From JDK 7 (I mean in HotSpot), something has changed.

In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.

-- From Java SE 7 Features and Enhancements

Update: Interned strings are stored in main heap from Java 7 onwards. http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html#jdk7changes

How to apply filters to *ngFor?

Pipe would be best approach. but below one would also work.

<div *ng-for="#item of itemsList">
  <ng-container *ng-if="conditon(item)">
    // my code
  </ng-container>
</div>

How to add local jar files to a Maven project?

Important part in dependency is: ${pom.basedir} (instead of just ${basedir})

<dependency>
    <groupId>org.example</groupId>
    <artifactId>example</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${pom.basedir}/src/lib/example.jar</systemPath>
</dependency>

JavaScript data grid for millions of rows

I can say with pretty good certainty that you seriously do not need to show millions of rows of data to the user.

There is no user in the world that will be able to comprehend or manage that data set so even if you technically manage to pull it off, you won't solve any known problem for that user.

Instead I would focus on why the user wants to see the data. The user does not want to see the data just to see the data, there is usually a question being asked. If you focus on answering those questions instead, then you would be much closer to something that solves an actual problem.

How to schedule a task to run when shutting down windows

What I can suggest doing is creating a shortcut to the .bat file (for example on your desktop) and a when you want to shutdown your computer (and run the .bat file) click on the shortcut you created. After doing this, edit the .bat file and add this line of code to the end or where needed:

c:\windows\system32\shutdown -s -f -t 00

What this does it is

  1. Runs the shutdown process
  2. Displays a alert
  3. Forces all running processes to stop
  4. Executes immediately

How to convert int[] into List<Integer> in Java?

Streams

In Java 8 you can do this

int[] ints = {1,2,3};
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());

Difference between maven scope compile and provided for JAR packaging

If jar file is like executable spring boot jar file then scope of all dependencies must be compile to include all jar files.

But if jar file used in other packages or applications then it does not need to include all dependencies in jar file because these packages or applications can provide other dependencies themselves.

Getting Spring Application Context

I know this question is answered, but I would like to share the Kotlin code I did to retrieve the Spring Context.

I am not a specialist, so I am open to critics, reviews and advices:

https://gist.github.com/edpichler/9e22309a86b97dbd4cb1ffe011aa69dd

package com.company.web.spring

import com.company.jpa.spring.MyBusinessAppConfig
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import org.springframework.stereotype.Component
import org.springframework.web.context.ContextLoader
import org.springframework.web.context.WebApplicationContext
import org.springframework.web.context.support.WebApplicationContextUtils
import javax.servlet.http.HttpServlet

@Configuration
@Import(value = [MyBusinessAppConfig::class])
@ComponentScan(basePackageClasses  = [SpringUtils::class])
open class WebAppConfig {
}

/**
 *
 * Singleton object to create (only if necessary), return and reuse a Spring Application Context.
 *
 * When you instantiates a class by yourself, spring context does not autowire its properties, but you can wire by yourself.
 * This class helps to find a context or create a new one, so you can wire properties inside objects that are not
 * created by Spring (e.g.: Servlets, usually created by the web server).
 *
 * Sometimes a SpringContext is created inside jUnit tests, or in the application server, or just manually. Independent
 * where it was created, I recommend you to configure your spring configuration to scan this SpringUtils package, so the 'springAppContext'
 * property will be used and autowired at the SpringUtils object the start of your spring context, and you will have just one instance of spring context public available.
 *
 *Ps: Even if your spring configuration doesn't include the SpringUtils @Component, it will works tto, but it will create a second Spring Context o your application.
 */
@Component
object SpringUtils {

        var springAppContext: ApplicationContext? = null
    @Autowired
    set(value) {
        field = value
    }



    /**
     * Tries to find and reuse the Application Spring Context. If none found, creates one and save for reuse.
     * @return returns a Spring Context.
     */
    fun ctx(): ApplicationContext {
        if (springAppContext!= null) {
            println("achou")
            return springAppContext as ApplicationContext;
        }

        //springcontext not autowired. Trying to find on the thread...
        val webContext = ContextLoader.getCurrentWebApplicationContext()
        if (webContext != null) {
            springAppContext = webContext;
            println("achou no servidor")
            return springAppContext as WebApplicationContext;
        }

        println("nao achou, vai criar")
        //None spring context found. Start creating a new one...
        val applicationContext = AnnotationConfigApplicationContext ( WebAppConfig::class.java )

        //saving the context for reusing next time
        springAppContext = applicationContext
        return applicationContext
    }

    /**
     * @return a Spring context of the WebApplication.
     * @param createNewWhenNotFound when true, creates a new Spring Context to return, when no one found in the ServletContext.
     * @param httpServlet the @WebServlet.
     */
    fun ctx(httpServlet: HttpServlet, createNewWhenNotFound: Boolean): ApplicationContext {
        try {
            val webContext = WebApplicationContextUtils.findWebApplicationContext(httpServlet.servletContext)
            if (webContext != null) {
                return webContext
            }
            if (createNewWhenNotFound) {
                //creates a new one
                return ctx()
            } else {
                throw NullPointerException("Cannot found a Spring Application Context.");
            }
        }catch (er: IllegalStateException){
            if (createNewWhenNotFound) {
                //creates a new one
                return ctx()
            }
            throw er;
        }
    }
}

Now, a spring context is publicly available, being able to call the same method independent of the context (junit tests, beans, manually instantiated classes) like on this Java Servlet:

@WebServlet(name = "MyWebHook", value = "/WebHook")
public class MyWebServlet extends HttpServlet {


    private MyBean byBean
            = SpringUtils.INSTANCE.ctx(this, true).getBean(MyBean.class);


    public MyWebServlet() {

    }
}

How to concatenate two MP4 files using FFmpeg?

this worked for me (on windows)

ffmpeg -i "concat:input1|input2" -codec copy output

an example...

ffmpeg -i "concat:01.mp4|02.mp4" -codec copy output.mp4

Python

Using some python code to do it with as many mp4 there are in a folder (install python from python.org, copy and paste and save this code into a file called mp4.py and run it from the cmd opened in the folder with python mp4.py and all the mp4 in the folder will be concatenated)

import glob
import os

stringa = ""
for f in glob.glob("*.mp4"):
    stringa += f + "|"
os.system("ffmpeg -i \"concat:" + stringa + "\" -codec copy output.mp4")

Version 2 with Python

Taken from my post on my blog, this is how I do it in python:

import os
import glob

def concatenate():
    stringa = "ffmpeg -i \"concat:"
    elenco_video = glob.glob("*.mp4")
    elenco_file_temp = []
    for f in elenco_video:
        file = "temp" + str(elenco_video.index(f) + 1) + ".ts"
        os.system("ffmpeg -i " + f + " -c copy -bsf:v h264_mp4toannexb -f mpegts " + file)
        elenco_file_temp.append(file)
    print(elenco_file_temp)
    for f in elenco_file_temp:
        stringa += f
        if elenco_file_temp.index(f) != len(elenco_file_temp)-1:
            stringa += "|"
        else:
            stringa += "\" -c copy  -bsf:a aac_adtstoasc output.mp4"
    print(stringa)
    os.system(stringa)

concatenate()

Python how to plot graph sine wave

import math
import turtle

ws = turtle.Screen()
ws.bgcolor("lightblue")
fred = turtle.Turtle()
for angle in range(360):
    y = math.sin(math.radians(angle))
    fred.goto(angle, y * 80)

ws.exitonclick()

Call a method of a controller from another controller using 'scope' in AngularJS

Here is good Demo in Fiddle how to use shared service in directive and other controllers through $scope.$on

HTML

<div ng-controller="ControllerZero">
    <input ng-model="message" >
    <button ng-click="handleClick(message);">BROADCAST</button>
</div>

<div ng-controller="ControllerOne">
    <input ng-model="message" >
</div>

<div ng-controller="ControllerTwo">
    <input ng-model="message" >
</div>

<my-component ng-model="message"></my-component>

JS

var myModule = angular.module('myModule', []);

myModule.factory('mySharedService', function($rootScope) {
    var sharedService = {};

    sharedService.message = '';

    sharedService.prepForBroadcast = function(msg) {
        this.message = msg;
        this.broadcastItem();
    };

    sharedService.broadcastItem = function() {
        $rootScope.$broadcast('handleBroadcast');
    };

    return sharedService;
});

By the same way we can use shared service in directive. We can implement controller section into directive and use $scope.$on

myModule.directive('myComponent', function(mySharedService) {
    return {
        restrict: 'E',
        controller: function($scope, $attrs, mySharedService) {
            $scope.$on('handleBroadcast', function() {
                $scope.message = 'Directive: ' + mySharedService.message;
            });
        },
        replace: true,
        template: '<input>'
    };
});

And here three our controllers where ControllerZero used as trigger to invoke prepForBroadcast

function ControllerZero($scope, sharedService) {
    $scope.handleClick = function(msg) {
        sharedService.prepForBroadcast(msg);
    };

    $scope.$on('handleBroadcast', function() {
        $scope.message = sharedService.message;
    });
}

function ControllerOne($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'ONE: ' + sharedService.message;
    });
}

function ControllerTwo($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'TWO: ' + sharedService.message;
    });
}

The ControllerOne and ControllerTwo listen message change by using $scope.$on handler.

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

I had the same problem many times, these things worked for me:

  • restarting my phone + xCode.
  • checking that both your Mac and your iPhone are connected to the same Network.( has a high potential ).
  • repairing my phone.

C# Linq Group By on multiple columns

var consolidatedChildren =
    from c in children
    group c by new
    {
        c.School,
        c.Friend,
        c.FavoriteColor,
    } into gcs
    select new ConsolidatedChild()
    {
        School = gcs.Key.School,
        Friend = gcs.Key.Friend,
        FavoriteColor = gcs.Key.FavoriteColor,
        Children = gcs.ToList(),
    };

var consolidatedChildren =
    children
        .GroupBy(c => new
        {
            c.School,
            c.Friend,
            c.FavoriteColor,
        })
        .Select(gcs => new ConsolidatedChild()
        {
            School = gcs.Key.School,
            Friend = gcs.Key.Friend,
            FavoriteColor = gcs.Key.FavoriteColor,
            Children = gcs.ToList(),
        });

How to get all count of mongoose model?

Background for the solution

As stated in the mongoose documentation and in the answer by Benjamin, the method Model.count() is deprecated. Instead of using count(), the alternatives are the following:

Model.countDocuments(filterObject, callback)

Counts how many documents match the filter in a collection. Passing an empty object {} as filter executes a full collection scan. If the collection is large, the following method might be used.

Model.estimatedDocumentCount()

This model method estimates the number of documents in the MongoDB collection. This method is faster than the previous countDocuments(), because it uses collection metadata instead of going through the entire collection. However, as the method name suggests, and depending on db configuration, the result is an estimate as the metadata might not reflect the actual count of documents in a collection at the method execution moment.

Both methods return a mongoose query object, which can be executed in one of the following two ways. Use .exec() if you want to execute a query at a later time.

The solution

Option 1: Pass a callback function

For example, count all documents in a collection using .countDocuments():

someModel.countDocuments({}, function(err, docCount) {
    if (err) { return handleError(err) } //handle possible errors
    console.log(docCount)
    //and do some other fancy stuff
})

Or, count all documents in a collection having a certain name using .countDocuments():

someModel.countDocuments({ name: 'Snow' }, function(err, docCount) {
    //see other example
}

Option 2: Use .then()

A mongoose query has .then() so it’s “thenable”. This is for a convenience and query itself is not a promise.

For example, count all documents in a collection using .estimatedDocumentCount():

someModel
    .estimatedDocumentCount()
    .then(docCount => {
        console.log(docCount)
        //and do one super neat trick
    })
    .catch(err => {
        //handle possible errors
    })

Option 3: Use async/await

When using async/await approach, the recommended way is to use it with .exec() as it provides better stack traces.

const docCount = await someModel.countDocuments({}).exec();

Learning by stackoverflowing,

How to get maximum value from the Collection (for example ArrayList)?

Here is the fucntion

public int getIndexOfMax(ArrayList<Integer> arr){
    int MaxVal = arr.get(0); // take first as MaxVal
    int indexOfMax = -1; //returns -1 if all elements are equal
    for (int i = 0; i < arr.size(); i++) {
        //if current is less then MaxVal
        if(arr.get(i) < MaxVal ){
            MaxVal = arr.get(i); // put it in MaxVal
            indexOfMax = i; // put index of current Max
        }
    }
    return indexOfMax;  
}

Embed Youtube video inside an Android app

Embedding the YouTube player in Android is very simple & it hardly takes you 10 minutes,

1) Enable YouTube API from Google API console
2) Download YouTube player Jar file
3) Start using it in Your app

Here are the detailed steps http://www.feelzdroid.com/2017/01/embed-youtube-video-player-android-app-example.html.

Just refer it & if you face any problem, let me know, ill help you

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

This is what solved it for us and these folks:

Our project started with Django 1.4, we went to 1.5 and then to 1.7. Our wsgi.py looked like this:

import os

from django.core.handlers.wsgi import WSGIHandler

os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
application = WSGIHandler()

When I updated to the 1.7 style WSGI handler:

import os

from django.core.wsgi import get_wsgi_application

os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
application = get_wsgi_application()

Everything works now.

How to download Visual Studio Community Edition 2015 (not 2017)

The "official" way to get the vs2015 is to go to https://my.visualstudio.com/ ; join the " Visual Studio Dev Essentials" and then search the relevant file to download https://my.visualstudio.com/Downloads?q=Visual%20Studio%202015%20with%20Update%203

Creating a dictionary from a CSV file

with pandas, it is much easier, for example. assuming you have the following data as CSV and let's call it test.txt / test.csv (you know CSV is a sort of text file )

a,b,c,d
1,2,3,4
5,6,7,8

now using pandas

import pandas as pd
df = pd.read_csv("./text.txt")
df_to_doct = df.to_dict()

for each row, it would be

df.to_dict(orient='records')

and that's it.

Manually map column names with class properties

The simple solution to the problem Kaleb is trying to solve is just to accept the property name if the column attribute doesn't exist:

Dapper.SqlMapper.SetTypeMap(
    typeof(T),
    new Dapper.CustomPropertyTypeMap(
        typeof(T),
        (type, columnName) =>
            type.GetProperties().FirstOrDefault(prop =>
                prop.GetCustomAttributes(false)
                    .OfType<ColumnAttribute>()
                    .Any(attr => attr.Name == columnName) || prop.Name == columnName)));

How do I display a decimal value to 2 decimal places?

If you need to keep only 2 decimal places (i.e. cut off all the rest of decimal digits):

decimal val = 3.14789m;
decimal result = Math.Floor(val * 100) / 100; // result = 3.14

If you need to keep only 3 decimal places:

decimal val = 3.14789m;
decimal result = Math.Floor(val * 1000) / 1000; // result = 3.147

How do you create a Marker with a custom icon for google maps API v3?

marker = new google.maps.Marker({
    map:map,
    // draggable:true,
    // animation: google.maps.Animation.DROP,
    position: new google.maps.LatLng(59.32522, 18.07002),
    icon: 'http://cdn.com/my-custom-icon.png' // null = default icon
  });

How can I split and parse a string in Python?

If it's always going to be an even LHS/RHS split, you can also use the partition method that's built into strings. It returns a 3-tuple as (LHS, separator, RHS) if the separator is found, and (original_string, '', '') if the separator wasn't present:

>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf4fda703454')

>>> "shazam".partition("_")
('shazam', '', '')

Get length of array?

Function

Public Function ArrayLen(arr As Variant) As Integer
    ArrayLen = UBound(arr) - LBound(arr) + 1
End Function

Usage

Dim arr(1 To 3) As String  ' Array starting at 1 instead of 0: nightmare fuel
Debug.Print ArrayLen(arr)  ' Prints 3.  Everything's going to be ok.

XSL xsl:template match="/"

It's worth noting, since it's confusing for people new to XML, that the root (or document node) of an XML document is not the top-level element. It's the parent of the top-level element. This is confusing because it doesn't seem like the top-level element can have a parent. Isn't it the top level?

But look at this, a well-formed XML document:

<?xml-stylesheet href="my_transform.xsl" type="text/xsl"?>
<!-- Comments and processing instructions are XML nodes too, remember. -->
<TopLevelElement/>

The root of this document has three children: a processing instruction, a comment, and an element.

So, for example, if you wanted to write a transform that got rid of that comment, but left in any comments appearing anywhere else in the document, you'd add this to the identity transform:

<xsl:template match="/comment()"/>

Even simpler (and more commonly useful), here's an XPath pattern that matches the document's top-level element irrespective of its name: /*.

Flutter - The method was called on null

You have a CryptoListPresenter _presenter but you are never initializing it. You should either be doing that when you declare it or in your initState() (or another appropriate but called-before-you-need-it method).

One thing I find that helps is that if I know a member is functionally 'final', to actually set it to final as that way the analyzer complains that it hasn't been initialized.

EDIT:

I see diegoveloper beat me to answering this, and that the OP asked a follow up.

@Jake - it's hard for us to tell without knowing exactly what CryptoListPresenter is, but depending on what exactly CryptoListPresenter actually is, generally you'd do final CryptoListPresenter _presenter = new CryptoListPresenter(...);, or

CryptoListPresenter _presenter;

@override
void initState() {
  _presenter = new CryptoListPresenter(...);
}

How to include layout inside layout?

Note that if you include android:id... into the <include /> tag, it will override whatever id was defined inside the included layout. For example:

<include
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:id="@+id/some_id_if_needed"
   layout="@layout/yourlayout" />

yourlayout.xml:

<LinearLayout
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:id="@+id/some_other_id">
   <Button
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:id="@+id/button1" />
 </LinearLayout>

Then you would reference this included layout in code as follows:

View includedLayout = findViewById(R.id.some_id_if_needed);
Button insideTheIncludedLayout = (Button)includedLayout.findViewById(R.id.button1);

Xcode doesn't see my iOS device but iTunes does

I tried all of the above to no avail. I had been using the phone for ages and suddenly the Organizer thought "this device is currently not connected". A reset of the phone fixed it for me (hold Home & Power until the Apple logo). I did so with it still connected to the MacBook, but it shouldn't be necessary.

Javascript Print iframe contents only

I had issues with all of the above solutions in IE8, have found a decent workaround that is tested in IE 8+9, Chrome, Safari and Firefox. For my situation i needed to print a report that was generated dynamically:

// create content of iframe
var content = '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'+
'<head><link href="/css/print.css" media="all" rel="stylesheet" type="text/css"></head>'+
'<body>(rest of body content)'+
'<script type="text/javascript">function printPage() { window.focus(); window.print();return; }</script>'+
'</body></html>';

Note the printPage() javascript method before the body close tag.

Next create the iframe and append it to the parent body so its contentWindow is available:

var newIframe = document.createElement('iframe');
newIframe.width = '0';
newIframe.height = '0';
newIframe.src = 'about:blank';
document.body.appendChild(newIframe);

Next set the content:

newIframe.contentWindow.contents = content;
newIframe.src = 'javascript:window["contents"]';

Here we are setting the dynamic content variable to the iframe's window object then invoking it via the javascript: scheme.

Finally to print; focus the iframe and call the javascript printPage() function within the iframe content:

newIframe.focus();
setTimeout(function() {
  newIframe.contentWindow.printPage();
}, 200);
return;

The setTimeout is not necessarily needed, however if you're loading large amounts of content i found Chrome occasionally failed to print without it so this step is recommended. The alternative is to wrap 'newIframe.contentWindow.printPage();' in a try catch and place the setTimeout wrapped version in the catch block.

Hope this helps someone as i spent a lot of time finding a solution that worked well across multiple browsers. Thanks to SpareCycles.

EDIT:

Instead of using setTimeout to call the printPage function use the following:

newIframe.onload = function() {
    newIframe.contentWindow.printPage();
}

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

@Dinh Nhat, your setter method looks wrong because you put a primitive type there again and it should be:

public void setClient_os_id(Integer clientOsId) {
client_os_id = clientOsId;
}

Mock HttpContext.Current in Test Init Method

Below Test Init will also do the job.

[TestInitialize]
public void TestInit()
{
  HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
  YourControllerToBeTestedController = GetYourToBeTestedController();
}

How do I clone a github project to run locally?

You clone a repository with git clone [url]. Like so,

$ git clone https://github.com/libgit2/libgit2

Getting value GET OR POST variable using JavaScript?

Here is my answer for this given a string returnURL which is like http://host.com/?param1=abc&param2=cde. It's fairly basic as I'm beginning at JavaScript (this is actually part of my first program ever in JS), and making it simpler to understand rather than tricky.

Notes

  • No sanity checking of values
  • Just outputting to the console - you'll want to store them in an array or something
  • this is only for GET, and not POST

    var paramindex = returnURL.indexOf('?');
    if (paramindex > 0) {
        var paramstring = returnURL.split('?')[1];
        while (paramindex > 0) {
            paramindex = paramstring.indexOf('=');
            if (paramindex > 0) {
                var parkey = paramstring.substr(0,paramindex);
                console.log(parkey)
                paramstring = paramstring.substr(paramindex+1) // +1 to strip out the =
            }
            paramindex = paramstring.indexOf('&');
            if (paramindex > 0) {
                var parvalue = paramstring.substr(0,paramindex);
                console.log(parvalue)
                paramstring = paramstring.substr(paramindex+1) // +1 to strip out the &
            } else { // we're at the end of the URL
                var parvalue = paramstring
                console.log(parvalue)
                break;
            }
        }
    }
    

Mongoose: Find, modify, save

You could also write it a little more cleaner using updateOne & $set, plus async/await.

const updateUser = async (newUser) => {
  try {
    await User.updateOne({ username: oldUsername }, {
      $set: {
        username: newUser.username,
        password: newUser.password,
        rights: newUser.rights
      }
    })
  } catch (err) {
    console.log(err)
  }
}

Since you don't need the resulting document, you can just use updateOne instead of findOneAndUpdate.

Here's a good discussion about the difference: MongoDB 3.2 - Use cases for updateOne over findOneAndUpdate

With MySQL, how can I generate a column containing the record index in a table?

Here comes the structure of template I used:

  select
          /*this is a row number counter*/
          ( select @rownum := @rownum + 1 from ( select @rownum := 0 ) d2 ) 
          as rownumber,
          d3.*
  from 
  ( select d1.* from table_name d1 ) d3

And here is my working code:

select     
           ( select @rownum := @rownum + 1 from ( select @rownum := 0 ) d2 ) 
           as rownumber,
           d3.*
from
(   select     year( d1.date ), month( d1.date ), count( d1.id )
    from       maindatabase d1
    where      ( ( d1.date >= '2013-01-01' ) and ( d1.date <= '2014-12-31' ) )
    group by   YEAR( d1.date ), MONTH( d1.date ) ) d3

How can I replace non-printable Unicode characters in Java?

I have redesigned the code for phone numbers +9 (987) 124124 Extract digits from a string in Java

 public static String stripNonDigitsV2( CharSequence input ) {
    if (input == null)
        return null;
    if ( input.length() == 0 )
        return "";

    char[] result = new char[input.length()];
    int cursor = 0;
    CharBuffer buffer = CharBuffer.wrap( input );
    int i=0;
    while ( i< buffer.length()  ) { //buffer.hasRemaining()
        char chr = buffer.get(i);
        if (chr=='u'){
            i=i+5;
            chr=buffer.get(i);
        }

        if ( chr > 39 && chr < 58 )
            result[cursor++] = chr;
        i=i+1;
    }

    return new String( result, 0, cursor );
}

git cherry-pick says "...38c74d is a merge but no -m option was given"

-m means the parent number.

From the git doc:

Usually you cannot cherry-pick a merge because you do not know which side of the merge should be considered the mainline. This option specifies the parent number (starting from 1) of the mainline and allows cherry-pick to replay the change relative to the specified parent.

For example, if your commit tree is like below:

- A - D - E - F -   master
   \     /
    B - C           branch one

then git cherry-pick E will produce the issue you faced.

git cherry-pick E -m 1 means using D-E, while git cherry-pick E -m 2 means using B-C-E.

Language Books/Tutorials for popular languages

For PHP, I'd recommend Advanced PHP Programming by George Schlossnagle. If you're just getting started in PHP, it's probably not the best book to start, but after you have an idea of what you are doing, it's a book that (in my opinion) tells you a lot of best practices and tips that you might miss out on otherwise.

For learning Lisp, I've been recommend to read Practical Common Lisp by Peter Seibel. This one is available online at http://www.gigamonkeys.com/book/.

For Lua, I recommend Programming in Lua by Roberto Ierusalimschy. This book is not the best programming book out there, but among the current selection of Lua books, this would be the best. This first edition of the book is also available online at http://www.lua.org/pil/. As the back cover of the book mentions, the book is oriented towards those who already have some programming experience in another language.

Redirect stdout to a file in Python?

There is contextlib.redirect_stdout() function in Python 3.4+:

from contextlib import redirect_stdout

with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        print('it now prints to `help.text`')

It is similar to:

import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout(new_target):
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value

that can be used on earlier Python versions. The latter version is not reusable. It can be made one if desired.

It doesn't redirect the stdout at the file descriptors level e.g.:

import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, redirect_stdout(f):
    print('redirected to a file')
    os.write(stdout_fd, b'not redirected')
    os.system('echo this also is not redirected')

b'not redirected' and 'echo this also is not redirected' are not redirected to the output.txt file.

To redirect at the file descriptor level, os.dup2() could be used:

import os
import sys
from contextlib import contextmanager

def fileno(file_or_fd):
    fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)()
    if not isinstance(fd, int):
        raise ValueError("Expected a file (`.fileno()`) or a file descriptor")
    return fd

@contextmanager
def stdout_redirected(to=os.devnull, stdout=None):
    if stdout is None:
       stdout = sys.stdout

    stdout_fd = fileno(stdout)
    # copy stdout_fd before it is overwritten
    #NOTE: `copied` is inheritable on Windows when duplicating a standard stream
    with os.fdopen(os.dup(stdout_fd), 'wb') as copied: 
        stdout.flush()  # flush library buffers that dup2 knows nothing about
        try:
            os.dup2(fileno(to), stdout_fd)  # $ exec >&to
        except ValueError:  # filename
            with open(to, 'wb') as to_file:
                os.dup2(to_file.fileno(), stdout_fd)  # $ exec > to
        try:
            yield stdout # allow code to be run with the redirected stdout
        finally:
            # restore stdout to its previous value
            #NOTE: dup2 makes stdout_fd inheritable unconditionally
            stdout.flush()
            os.dup2(copied.fileno(), stdout_fd)  # $ exec >&copied

The same example works now if stdout_redirected() is used instead of redirect_stdout():

import os
import sys

stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, stdout_redirected(f):
    print('redirected to a file')
    os.write(stdout_fd, b'it is redirected now\n')
    os.system('echo this is also redirected')
print('this is goes back to stdout')

The output that previously was printed on stdout now goes to output.txt as long as stdout_redirected() context manager is active.

Note: stdout.flush() does not flush C stdio buffers on Python 3 where I/O is implemented directly on read()/write() system calls. To flush all open C stdio output streams, you could call libc.fflush(None) explicitly if some C extension uses stdio-based I/O:

try:
    import ctypes
    from ctypes.util import find_library
except ImportError:
    libc = None
else:
    try:
        libc = ctypes.cdll.msvcrt # Windows
    except OSError:
        libc = ctypes.cdll.LoadLibrary(find_library('c'))

def flush(stream):
    try:
        libc.fflush(None)
        stream.flush()
    except (AttributeError, ValueError, IOError):
        pass # unsupported

You could use stdout parameter to redirect other streams, not only sys.stdout e.g., to merge sys.stderr and sys.stdout:

def merged_stderr_stdout():  # $ exec 2>&1
    return stdout_redirected(to=sys.stdout, stdout=sys.stderr)

Example:

from __future__ import print_function
import sys

with merged_stderr_stdout():
     print('this is printed on stdout')
     print('this is also printed on stdout', file=sys.stderr)

Note: stdout_redirected() mixes buffered I/O (sys.stdout usually) and unbuffered I/O (operations on file descriptors directly). Beware, there could be buffering issues.

To answer, your edit: you could use python-daemon to daemonize your script and use logging module (as @erikb85 suggested) instead of print statements and merely redirecting stdout for your long-running Python script that you run using nohup now.

How to fix Warning Illegal string offset in PHP

Please check that your key exists in the array or not, instead of simply trying to access it.

Replace:

$myVar = $someArray['someKey']

With something like:

if (isset($someArray['someKey'])) {
    $myVar = $someArray['someKey']
}

or something like:

if(is_array($someArray['someKey'])) {
    $theme_img = 'recent_works_iso_thumbnail';
}else {
    $theme_img = 'recent_works_iso_thumbnail';
}

DateTime and CultureInfo

Use CultureInfo class to change your culture info.

var dutchCultureInfo = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCultureInfo);

Query to list all stored procedures

This will give just the names of the stored procedures.

select specific_name
from information_schema.routines
where routine_type = 'PROCEDURE';

Difference between "managed" and "unmanaged"

This is more general than .NET and Windows. Managed is an environment where you have automatic memory management, garbage collection, type safety, ... unmanaged is everything else. So for example .NET is a managed environment and C/C++ is unmanaged.

C# cannot convert method to non delegate type

You can simplify your class code to this below and it will work as is but if you want to make your example work, add parenthesis at the end : string x = getTitle();

public class Pin
{
   public string Title { get; set;}
}

:not(:empty) CSS selector is not working?

input:not(:invalid){
 border: 1px red solid;
}

// or 

input:not(:focus):not(:invalid){
 border: 1px red solid;
}

List files ONLY in the current directory

You can use the pathlib module.

from pathlib import Path
x = Path('./')
print(list(filter(lambda y:y.is_file(), x.iterdir())))

Sorting table rows according to table header column using javascript or jquery

I think this might help you:
Here is the JSFiddle demo:

And here is the code:

_x000D_
_x000D_
var stIsIE = /*@cc_on!@*/ false;_x000D_
sorttable = {_x000D_
  init: function() {_x000D_
    if (arguments.callee.done) return;_x000D_
    arguments.callee.done = true;_x000D_
    if (_timer) clearInterval(_timer);_x000D_
    if (!document.createElement || !document.getElementsByTagName) return;_x000D_
    sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;_x000D_
    forEach(document.getElementsByTagName('table'), function(table) {_x000D_
      if (table.className.search(/\bsortable\b/) != -1) {_x000D_
        sorttable.makeSortable(table);_x000D_
      }_x000D_
    });_x000D_
  },_x000D_
  makeSortable: function(table) {_x000D_
    if (table.getElementsByTagName('thead').length == 0) {_x000D_
      the = document.createElement('thead');_x000D_
      the.appendChild(table.rows[0]);_x000D_
      table.insertBefore(the, table.firstChild);_x000D_
    }_x000D_
    if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];_x000D_
    if (table.tHead.rows.length != 1) return;_x000D_
    sortbottomrows = [];_x000D_
    for (var i = 0; i < table.rows.length; i++) {_x000D_
      if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {_x000D_
        sortbottomrows[sortbottomrows.length] = table.rows[i];_x000D_
      }_x000D_
    }_x000D_
    if (sortbottomrows) {_x000D_
      if (table.tFoot == null) {_x000D_
        tfo = document.createElement('tfoot');_x000D_
        table.appendChild(tfo);_x000D_
      }_x000D_
      for (var i = 0; i < sortbottomrows.length; i++) {_x000D_
        tfo.appendChild(sortbottomrows[i]);_x000D_
      }_x000D_
      delete sortbottomrows;_x000D_
    }_x000D_
    headrow = table.tHead.rows[0].cells;_x000D_
    for (var i = 0; i < headrow.length; i++) {_x000D_
      if (!headrow[i].className.match(/\bsorttable_nosort\b/)) {_x000D_
        mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);_x000D_
        if (mtch) {_x000D_
          override = mtch[1];_x000D_
        }_x000D_
        if (mtch && typeof sorttable["sort_" + override] == 'function') {_x000D_
          headrow[i].sorttable_sortfunction = sorttable["sort_" + override];_x000D_
        } else {_x000D_
          headrow[i].sorttable_sortfunction = sorttable.guessType(table, i);_x000D_
        }_x000D_
        headrow[i].sorttable_columnindex = i;_x000D_
        headrow[i].sorttable_tbody = table.tBodies[0];_x000D_
        dean_addEvent(headrow[i], "click", sorttable.innerSortFunction = function(e) {_x000D_
_x000D_
          if (this.className.search(/\bsorttable_sorted\b/) != -1) {_x000D_
            sorttable.reverse(this.sorttable_tbody);_x000D_
            this.className = this.className.replace('sorttable_sorted',_x000D_
              'sorttable_sorted_reverse');_x000D_
            this.removeChild(document.getElementById('sorttable_sortfwdind'));_x000D_
            sortrevind = document.createElement('span');_x000D_
            sortrevind.id = "sorttable_sortrevind";_x000D_
            sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';_x000D_
            this.appendChild(sortrevind);_x000D_
            return;_x000D_
          }_x000D_
          if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {_x000D_
            sorttable.reverse(this.sorttable_tbody);_x000D_
            this.className = this.className.replace('sorttable_sorted_reverse',_x000D_
              'sorttable_sorted');_x000D_
            this.removeChild(document.getElementById('sorttable_sortrevind'));_x000D_
            sortfwdind = document.createElement('span');_x000D_
            sortfwdind.id = "sorttable_sortfwdind";_x000D_
            sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';_x000D_
            this.appendChild(sortfwdind);_x000D_
            return;_x000D_
          }_x000D_
          theadrow = this.parentNode;_x000D_
          forEach(theadrow.childNodes, function(cell) {_x000D_
            if (cell.nodeType == 1) {_x000D_
              cell.className = cell.className.replace('sorttable_sorted_reverse', '');_x000D_
              cell.className = cell.className.replace('sorttable_sorted', '');_x000D_
            }_x000D_
          });_x000D_
          sortfwdind = document.getElementById('sorttable_sortfwdind');_x000D_
          if (sortfwdind) {_x000D_
            sortfwdind.parentNode.removeChild(sortfwdind);_x000D_
          }_x000D_
          sortrevind = document.getElementById('sorttable_sortrevind');_x000D_
          if (sortrevind) {_x000D_
            sortrevind.parentNode.removeChild(sortrevind);_x000D_
          }_x000D_
_x000D_
          this.className += ' sorttable_sorted';_x000D_
          sortfwdind = document.createElement('span');_x000D_
          sortfwdind.id = "sorttable_sortfwdind";_x000D_
          sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';_x000D_
          this.appendChild(sortfwdind);_x000D_
          row_array = [];_x000D_
          col = this.sorttable_columnindex;_x000D_
          rows = this.sorttable_tbody.rows;_x000D_
          for (var j = 0; j < rows.length; j++) {_x000D_
            row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];_x000D_
          }_x000D_
          row_array.sort(this.sorttable_sortfunction);_x000D_
          tb = this.sorttable_tbody;_x000D_
          for (var j = 0; j < row_array.length; j++) {_x000D_
            tb.appendChild(row_array[j][1]);_x000D_
          }_x000D_
          delete row_array;_x000D_
        });_x000D_
      }_x000D_
    }_x000D_
  },_x000D_
_x000D_
  guessType: function(table, column) {_x000D_
    sortfn = sorttable.sort_alpha;_x000D_
    for (var i = 0; i < table.tBodies[0].rows.length; i++) {_x000D_
      text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);_x000D_
      if (text != '') {_x000D_
        if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {_x000D_
          return sorttable.sort_numeric;_x000D_
        }_x000D_
        possdate = text.match(sorttable.DATE_RE)_x000D_
        if (possdate) {_x000D_
          first = parseInt(possdate[1]);_x000D_
          second = parseInt(possdate[2]);_x000D_
          if (first > 12) {_x000D_
            return sorttable.sort_ddmm;_x000D_
          } else if (second > 12) {_x000D_
            return sorttable.sort_mmdd;_x000D_
          } else {_x000D_
            sortfn = sorttable.sort_ddmm;_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    return sortfn;_x000D_
  },_x000D_
  getInnerText: function(node) {_x000D_
    if (!node) return "";_x000D_
    hasInputs = (typeof node.getElementsByTagName == 'function') &&_x000D_
      node.getElementsByTagName('input').length;_x000D_
    if (node.getAttribute("sorttable_customkey") != null) {_x000D_
      return node.getAttribute("sorttable_customkey");_x000D_
    } else if (typeof node.textContent != 'undefined' && !hasInputs) {_x000D_
      return node.textContent.replace(/^\s+|\s+$/g, '');_x000D_
    } else if (typeof node.innerText != 'undefined' && !hasInputs) {_x000D_
      return node.innerText.replace(/^\s+|\s+$/g, '');_x000D_
    } else if (typeof node.text != 'undefined' && !hasInputs) {_x000D_
      return node.text.replace(/^\s+|\s+$/g, '');_x000D_
    } else {_x000D_
      switch (node.nodeType) {_x000D_
        case 3:_x000D_
          if (node.nodeName.toLowerCase() == 'input') {_x000D_
            return node.value.replace(/^\s+|\s+$/g, '');_x000D_
          }_x000D_
        case 4:_x000D_
          return node.nodeValue.replace(/^\s+|\s+$/g, '');_x000D_
          break;_x000D_
        case 1:_x000D_
        case 11:_x000D_
          var innerText = '';_x000D_
          for (var i = 0; i < node.childNodes.length; i++) {_x000D_
            innerText += sorttable.getInnerText(node.childNodes[i]);_x000D_
          }_x000D_
          return innerText.replace(/^\s+|\s+$/g, '');_x000D_
          break;_x000D_
        default:_x000D_
          return '';_x000D_
      }_x000D_
    }_x000D_
  },_x000D_
  reverse: function(tbody) {_x000D_
    // reverse the rows in a tbody_x000D_
    newrows = [];_x000D_
    for (var i = 0; i < tbody.rows.length; i++) {_x000D_
      newrows[newrows.length] = tbody.rows[i];_x000D_
    }_x000D_
    for (var i = newrows.length - 1; i >= 0; i--) {_x000D_
      tbody.appendChild(newrows[i]);_x000D_
    }_x000D_
    delete newrows;_x000D_
  },_x000D_
  sort_numeric: function(a, b) {_x000D_
    aa = parseFloat(a[0].replace(/[^0-9.-]/g, ''));_x000D_
    if (isNaN(aa)) aa = 0;_x000D_
    bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''));_x000D_
    if (isNaN(bb)) bb = 0;_x000D_
    return aa - bb;_x000D_
  },_x000D_
  sort_alpha: function(a, b) {_x000D_
    if (a[0] == b[0]) return 0;_x000D_
    if (a[0] < b[0]) return -1;_x000D_
    return 1;_x000D_
  },_x000D_
  sort_ddmm: function(a, b) {_x000D_
    mtch = a[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    m = mtch[2];_x000D_
    d = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt1 = y + m + d;_x000D_
    mtch = b[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    m = mtch[2];_x000D_
    d = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt2 = y + m + d;_x000D_
    if (dt1 == dt2) return 0;_x000D_
    if (dt1 < dt2) return -1;_x000D_
    return 1;_x000D_
  },_x000D_
  sort_mmdd: function(a, b) {_x000D_
    mtch = a[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    d = mtch[2];_x000D_
    m = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt1 = y + m + d;_x000D_
    mtch = b[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    d = mtch[2];_x000D_
    m = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt2 = y + m + d;_x000D_
    if (dt1 == dt2) return 0;_x000D_
    if (dt1 < dt2) return -1;_x000D_
    return 1;_x000D_
  },_x000D_
  shaker_sort: function(list, comp_func) {_x000D_
    var b = 0;_x000D_
    var t = list.length - 1;_x000D_
    var swap = true;_x000D_
    while (swap) {_x000D_
      swap = false;_x000D_
      for (var i = b; i < t; ++i) {_x000D_
        if (comp_func(list[i], list[i + 1]) > 0) {_x000D_
          var q = list[i];_x000D_
          list[i] = list[i + 1];_x000D_
          list[i + 1] = q;_x000D_
          swap = true;_x000D_
        }_x000D_
      }_x000D_
      t--;_x000D_
_x000D_
      if (!swap) break;_x000D_
_x000D_
      for (var i = t; i > b; --i) {_x000D_
        if (comp_func(list[i], list[i - 1]) < 0) {_x000D_
          var q = list[i];_x000D_
          list[i] = list[i - 1];_x000D_
          list[i - 1] = q;_x000D_
          swap = true;_x000D_
        }_x000D_
      }_x000D_
      b++;_x000D_
_x000D_
    }_x000D_
  }_x000D_
}_x000D_
if (document.addEventListener) {_x000D_
  document.addEventListener("DOMContentLoaded", sorttable.init, false);_x000D_
}_x000D_
/* for Internet Explorer */_x000D_
/*@cc_on @*/_x000D_
/*@if (@_win32)_x000D_
    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");_x000D_
    var script = document.getElementById("__ie_onload");_x000D_
    script.onreadystatechange = function() {_x000D_
        if (this.readyState == "complete") {_x000D_
            sorttable.init(); // call the onload handler_x000D_
        }_x000D_
    };_x000D_
/*@end @*/_x000D_
/* for Safari */_x000D_
if (/WebKit/i.test(navigator.userAgent)) { // sniff_x000D_
  var _timer = setInterval(function() {_x000D_
    if (/loaded|complete/.test(document.readyState)) {_x000D_
      sorttable.init(); // call the onload handler_x000D_
    }_x000D_
  }, 10);_x000D_
}_x000D_
/* for other browsers */_x000D_
window.onload = sorttable.init;_x000D_
_x000D_
function dean_addEvent(element, type, handler) {_x000D_
  if (element.addEventListener) {_x000D_
    element.addEventListener(type, handler, false);_x000D_
  } else {_x000D_
    if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;_x000D_
    if (!element.events) element.events = {};_x000D_
    var handlers = element.events[type];_x000D_
    if (!handlers) {_x000D_
      handlers = element.events[type] = {};_x000D_
      if (element["on" + type]) {_x000D_
        handlers[0] = element["on" + type];_x000D_
      }_x000D_
    }_x000D_
    handlers[handler.$$guid] = handler;_x000D_
    element["on" + type] = handleEvent;_x000D_
  }_x000D_
};_x000D_
dean_addEvent.guid = 1;_x000D_
_x000D_
function removeEvent(element, type, handler) {_x000D_
  if (element.removeEventListener) {_x000D_
    element.removeEventListener(type, handler, false);_x000D_
  } else {_x000D_
    if (element.events && element.events[type]) {_x000D_
      delete element.events[type][handler.$$guid];_x000D_
    }_x000D_
  }_x000D_
};_x000D_
_x000D_
function handleEvent(event) {_x000D_
  var returnValue = true;_x000D_
  event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);_x000D_
  var handlers = this.events[event.type];_x000D_
  for (var i in handlers) {_x000D_
    this.$$handleEvent = handlers[i];_x000D_
    if (this.$$handleEvent(event) === false) {_x000D_
      returnValue = false;_x000D_
    }_x000D_
  }_x000D_
  return returnValue;_x000D_
};_x000D_
_x000D_
function fixEvent(event) {_x000D_
  event.preventDefault = fixEvent.preventDefault;_x000D_
  event.stopPropagation = fixEvent.stopPropagation;_x000D_
  return event;_x000D_
};_x000D_
fixEvent.preventDefault = function() {_x000D_
  this.returnValue = false;_x000D_
};_x000D_
fixEvent.stopPropagation = function() {_x000D_
  this.cancelBubble = true;_x000D_
}_x000D_
if (!Array.forEach) {_x000D_
  Array.forEach = function(array, block, context) {_x000D_
    for (var i = 0; i < array.length; i++) {_x000D_
      block.call(context, array[i], i, array);_x000D_
    }_x000D_
  };_x000D_
}_x000D_
Function.prototype.forEach = function(object, block, context) {_x000D_
  for (var key in object) {_x000D_
    if (typeof this.prototype[key] == "undefined") {_x000D_
      block.call(context, object[key], key, object);_x000D_
    }_x000D_
  }_x000D_
};_x000D_
String.forEach = function(string, block, context) {_x000D_
  Array.forEach(string.split(""), function(chr, index) {_x000D_
    block.call(context, chr, index, string);_x000D_
  });_x000D_
};_x000D_
var forEach = function(object, block, context) {_x000D_
  if (object) {_x000D_
    var resolve = Object;_x000D_
    if (object instanceof Function) {_x000D_
      resolve = Function;_x000D_
    } else if (object.forEach instanceof Function) {_x000D_
      object.forEach(block, context);_x000D_
      return;_x000D_
    } else if (typeof object == "string") {_x000D_
      resolve = String;_x000D_
    } else if (typeof object.length == "number") {_x000D_
      resolve = Array;_x000D_
    }_x000D_
    resolve.forEach(object, block, context);_x000D_
  }_x000D_
}
_x000D_
table.sortable thead {_x000D_
  background-color: #eee;_x000D_
  color: #666666;_x000D_
  font-weight: bold;_x000D_
  cursor: default;_x000D_
}
_x000D_
<table class="sortable">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>S.L.</th>_x000D_
      <th>name</th>_x000D_
      <th>Goal</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>1</td>_x000D_
      <td>Ronaldo</td>_x000D_
      <td>120</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>2</td>_x000D_
      <td>Messi</td>_x000D_
      <td>66</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>3</td>_x000D_
      <td>Ribery</td>_x000D_
      <td>10</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>Bale</td>_x000D_
      <td>22</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

JS is used here without any other JQuery Plugin.

Highlighting Text Color using Html.fromHtml() in Android?

Adding also Kotlin version with:

  • getting text from resources (strings.xml)
  • getting color from resources (colors.xml)
  • "fetching HEX" moved as extension
fun getMulticolorSpanned(): Spanned {
    // Get text from resources
    val text: String = getString(R.string.your_text_from_resources)

    // Get color from resources and parse it to HEX (RGB) value
    val warningHexColor = getHexFromColors(R.color.your_error_color)

    // Use above string & color in HTML
    val html = "<string>$text<span style=\"color:#$warningHexColor;\">*</span></string>"

    // Parse HTML (base on API version)
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
    } else {
        Html.fromHtml(html)
    }
}

And Kotlin extension (with removing alpha):

fun Context.getHexFromColors(
    colorRes: Int
): String {
    val labelColor: Int = ContextCompat.getColor(this, colorRes)
    return String.format("%X", labelColor).substring(2)
}

Demo

demo

Inserting data to table (mysqli insert)

In mysqli_query(first parameter should be connection,your sql statement) so

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
mysqli_query($connection_name,'INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)');

but best practice is

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
$sql_statement="INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)";
mysqli_query($connection_name,$sql_statement);

Getting next element while cycling through a list

The simple solution is to remove IndexError by incorporating the condition:

if(index<(len(li)-1))

The error 'index out of range' will not occur now as the last index will not be reached. The idea is to access the next element while iterating. On reaching the penultimate element, you can access the last element.

Use enumerate method to add index or counter to an iterable(list, tuple, etc.). Now using the index+1, we can access the next element while iterating through the list.

li = [0, 1, 2, 3]

running = True
while running:
    for index, elem in enumerate(li):
        if(index<(len(li)-1)):
            thiselem = elem
            nextelem = li[index+1]

Unable to read repository at http://download.eclipse.org/releases/indigo

No meu caso era o anti-vírus que estava bloqueando a conexão do eclipse, desativei o anti-víruse tudo funcionou o//.

Translation: In my case it was the anti-virus that was blocking the connection from eclipse. I disabled the anti-virus and everything worked.

Cannot open backup device. Operating System error 5

Please check the access to drives.First create one folder and go to folder properties ,

You may find the security tab ,click on that check whether your user id having the access or not.

if couldn't find the your id,please click the add buttion and give user name with full access.

Set auto height and width in CSS/HTML for different screen sizes

///UPDATED DEMO 2 WATCH SOLUTION////

I hope that is the solution you're looking for! DEMO1 DEMO2

With that solution the only scrollbar in the page is on your contents section in the middle! In that section build your structure with a sidebar or whatever you want!

You can do that with that code here:

<div class="navTop">
<h1>Title</h1>
    <nav>Dynamic menu</nav>
</div>
<div class="container">
    <section>THE CONTENTS GOES HERE</section>
</div>
<footer class="bottomFooter">
    Footer
</footer>

With that css:

.navTop{
width:100%;
border:1px solid black;
float:left;
}
.container{
width:100%;
float:left;
overflow:scroll;
}
.bottomFooter{
float:left;
border:1px solid black;
width:100%;
}

And a bit of jquery:

$(document).ready(function() {
  function setHeight() {
    var top = $('.navTop').outerHeight();
    var bottom = $('footer').outerHeight();
    var totHeight = $(window).height();
    $('section').css({ 
      'height': totHeight - top - bottom + 'px'
    });
  }

  $(window).on('resize', function() { setHeight(); });
  setHeight();
});

DEMO 1

If you don't want jquery

<div class="row">
    <h1>Title</h1>
    <nav>NAV</nav>
</div>

<div class="row container">
    <div class="content">
        <div class="sidebar">
            SIDEBAR
        </div>
        <div class="contents">
            CONTENTS
        </div>
    </div>
    <footer>Footer</footer>
</div>

CSS

*{
margin:0;padding:0;    
}
html,body{
height:100%;
width:100%;
}
body{
display:table;
}
.row{
width: 100%;
background: yellow;
display:table-row;
}
.container{
background: pink;
height:100%; 
}
.content {
display: block;
overflow:auto;
height:100%;
padding-bottom: 40px;
box-sizing: border-box;
}
footer{ 
position: fixed; 
bottom: 0; 
left: 0; 
background: yellow;
height: 40px;
line-height: 40px;
width: 100%;
text-align: center;
}
.sidebar{
float:left;
background:green;
height:100%;
width:10%;
}
.contents{
float:left;
background:red;
height:100%;
width:90%;
overflow:auto;
}

DEMO 2

converting numbers in to words C#

When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:

{1, "one"}
{2, "two"}
{30, "thirty"}

You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.

After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.

Making TextView scrollable on Android

For a vertically or horizontally scrollable TextView some of the other answers help, but I needed to be able to scroll both ways.

What finally worked is a ScrollView with a HorizontalScrollView inside of it, and a TextView inside the HSV. It's very smooth and can easily go side to side or top to bottom in one swipe. It also only allows scrolling in one direction at a time so there's none of the jumping side to side while scrolling up or down.

An EditText with editing and cursor disabled works, but it feels terrible. Each attempt to scroll moves the cursor and it requires many swipes to go top to bottom or side to side in even a ~100-line file.

Using setHorizontallyScrolling(true) can work, but there's no similar method to allow vertical scrolling, and it doesn't work inside of a ScrollView as far as I can tell (just learning though, could be wrong).

Find intersection of two nested lists?

You should flatten using this code ( taken from http://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks ), the code is untested, but I'm pretty sure it works:


def flatten(x):
    """flatten(sequence) -> list

    Returns a single, flat list which contains all elements retrieved
    from the sequence and all recursively contained sub-sequences
    (iterables).

    Examples:
    >>> [1, 2, [3,4], (5,6)]
    [1, 2, [3, 4], (5, 6)]
    >>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)])
    [1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]"""

    result = []
    for el in x:
        #if isinstance(el, (list, tuple)):
        if hasattr(el, "__iter__") and not isinstance(el, basestring):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

After you had flattened the list, you perform the intersection in the usual way:


c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]

def intersect(a, b):
     return list(set(a) & set(b))

print intersect(flatten(c1), flatten(c2))

How can I validate a string to only allow alphanumeric characters in it?

Based on cletus's answer you may create new extension.

public static class StringExtensions
{        
    public static bool IsAlphaNumeric(this string str)
    {
        if (string.IsNullOrEmpty(str))
            return false;

        Regex r = new Regex("^[a-zA-Z0-9]*$");
        return r.IsMatch(str);
    }
}

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.

No visible cause for "Unexpected token ILLEGAL"

I am going to add one more answer to the pile. THis problem could happen also because of encoding. You want utf8 encoding to be on safe side. Some editors by default use utf16 which can cause issue. One quick way to test this, is, for example in VS code, simply recreate the same content but use the local editor of vscode to create the file. Hope this helps some.

jQuery prevent change for select

This worked for me, no need to keep a lastSelected if you know the optionIndex to select.

var optionIndex = ...
$(this)[0].options[optionIndex].selected = true;

How can I install an older version of a package via NuGet?

I've used Xavier's answer quite a bit. I want to add that restricting the package version to a specified range is easy and useful in the latest versions of NuGet.

For example, if you never want Newtonsoft.Json to be updated past version 3.x.x in your project, change the corresponding package element in your packages.config file to look like this:

<package id="Newtonsoft.Json" version="3.5.8" allowedVersions="[3.0, 4.0)" targetFramework="net40" />

Notice the allowedVersions attribute. This will limit the version of that package to versions between 3.0 (inclusive) and 4.0 (exclusive). Then, when you do an Update-Package on the whole solution, you don't need to worry about that particular package being updated past version 3.x.x.

The documentation for this functionality is here.

case statement in SQL, how to return multiple variables?

The basic way, unfortunately, is to repeat yourself.

SELECT
  CASE WHEN <condition 1> THEN <a1> WHEN <condition 2> THEN <a2> ELSE <a3> END,
  CASE WHEN <condition 1> THEN <b1> WHEN <condition 2> THEN <b2> ELSE <b3> END
FROM 
  <table> 

Fortunately, most RDBMS are clever enough to NOT have to evaluate the conditions multiple times. It's just redundant typing.


In MS SQL Server (2005+) you could possible use CROSS APPLY as an alternative to this. Though I have no idea how performant it is...

SELECT
  *
FROM
  <table>
CROSS APPLY
  (
   SELECT a1, b1 WHERE <condition 1>
   UNION ALL
   SELECT a2, b2 WHERE <condition 2>
   UNION ALL
   SELECT a3, b3 WHERE <condition 3>
  )
  AS case_proxy

The noticable downside here is that there is no ELSE equivalent and as all the conditions could all return values, they need to be framed such that only one can ever be true at a time.


EDIT

If Yuck's answer is changed to a UNION rather than JOIN approach, it becomes very similar to this. The main difference, however, being that this only scans the input data set once, rather than once per condition (100 times in your case).


EDIT

I've also noticed that you may mean that the values returned by the CASE statements are fixed. All records that match the same condition get the exact sames values in value1 and value2. This could be formed like this...

WITH
  checked_data AS
(
  SELECT
    CASE WHEN <condition1> THEN 1
         WHEN <condition2> THEN 2
         WHEN <condition3> THEN 3
         ...
         ELSE                   100
    END AS condition_id,
    *
  FROM
    <table>
)
,
  results (condition_id, value1, value2) AS
(
   SELECT 1, a1, b1
   UNION ALL
   SELECT 2, a2, b2
   UNION ALL
   SELECT 3, a3, b3
   UNION ALL
   ...
   SELECT 100, a100, b100
)
SELECT
  *
FROM
  checked_data
INNER JOIN
  results
    ON results.condition_id = checked_data.condition_id

jQuery Validate Required Select

The solution mentioned by @JMP worked in my case with a little modification: I use element.value instead of value in the addmethod.

$.validator.addMethod("valueNotEquals", function(value, element, arg){
    // I use element.value instead value here, value parameter was always null
    return arg != element.value; 
}, "Value must not equal arg.");

// configure your validation
$("form").validate({
    rules: {
        SelectName: { valueNotEquals: "0" }
    },
    messages: {
        SelectName: { valueNotEquals: "Please select an item!" }
    }  
});

It could be possible, that I have a special case here, but didn't track down the cause. But @JMP's solution should work in regular cases.

How to format DateTime columns in DataGridView?

You can set the format in aspx, just add the property "DateFormatString" in your BoundField.

DataFormatString="{0:dd/MM/yyyy hh:mm:ss}"

How to "crop" a rectangular image into a square with CSS?

Use CSS: overflow:

.thumb {
   width:230px;
   height:230px;
   overflow:hidden
}

How do I set up CLion to compile and run?

You can also use Microsoft Visual Studio compiler instead of Cygwin or MinGW in Windows environment as the compiler for CLion.

Just go to find Actions in Help and type "Registry" without " and enable CLion.enable.msvc Now configure toolchain with Microsoft Visual Studio Compiler. (You need to download it if not already downloaded)

follow this link for more details: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html

How do I import the javax.servlet API in my Eclipse project?

Include servlet-api.jar from your server lib folder.enter image description here

Do this step

enter image description here

ERROR 1049 (42000): Unknown database 'mydatabasename'

Create database which gave error as Unknown database, Login to mysql shell:

sudo mysql -u root -p
create database db_name;

Now try restoring database using .sql file, -p flag will ask for a sql user's password once command is executed.

sudo mysql -u root -p db_name < db_name.sql

How do I make an HTTP request in Swift?

Basic Swift 3+ Solution

guard let url = URL(string: "http://www.stackoverflow.com") else { return }

let task = URLSession.shared.dataTask(with: url) { data, response, error in

  guard let data = data, error == nil else { return }

  print(NSString(data: data, encoding: String.Encoding.utf8.rawValue))
}

task.resume()

"Debug certificate expired" error in Eclipse Android plugins

I had this problem couple of weeks ago. I first tried the troubleshooting on the Android developer site, but without luck. After that I reinstalled the Android SDK, which solved my problem.

Copy to Clipboard for all Browsers using javascript

This works on firefox 3.6.x and IE:

    function copyToClipboardCrossbrowser(s) {           
        s = document.getElementById(s).value;               

        if( window.clipboardData && clipboardData.setData )
        {
            clipboardData.setData("Text", s);
        }           
        else
        {
            // You have to sign the code to enable this or allow the action in about:config by changing
            //user_pref("signed.applets.codebase_principal_support", true);
            netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

            var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
            if (!clip) return;

            // create a transferable

            var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
            if (!trans) return;

            // specify the data we wish to handle. Plaintext in this case.
            trans.addDataFlavor('text/unicode');

            // To get the data from the transferable we need two new objects
            var str = new Object();
            var len = new Object();

            var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);

            str.data= s;        

            trans.setTransferData("text/unicode",str, str.data.length * 2);

            var clipid=Components.interfaces.nsIClipboard;              
            if (!clip) return false;
            clip.setData(trans,null,clipid.kGlobalClipboard);      
        }
    }

undefined reference to WinMain@16 (codeblocks)

I was interested in setting up graphics for Code Blocks when I ran into a this error: (took me 2 hrs to solve it)

I guess you need to have a bit of luck with this. In my case i just changed the order of contents in Settings menu->Compiler and Debugger->Global compiler settings->Linker settings->Other Linker Options: The working sequence is: -lmingw32 -lSDL -lSDLmain

Determine distance from the top of a div to top of window with javascript

You can use .offset() to get the offset compared to the document element and then use the scrollTop property of the window element to find how far down the page the user has scrolled:

var scrollTop     = $(window).scrollTop(),
    elementOffset = $('#my-element').offset().top,
    distance      = (elementOffset - scrollTop);

The distance variable now holds the distance from the top of the #my-element element and the top-fold.

Here is a demo: http://jsfiddle.net/Rxs2m/

Note that negative values mean that the element is above the top-fold.

C++ sorting and keeping track of indexes

vector<pair<int,int> >a;

for (i = 0 ;i < n ; i++) {
    // filling the original array
    cin >> k;
    a.push_back (make_pair (k,i)); // k = value, i = original index
}

sort (a.begin(),a.end());

for (i = 0 ; i < n ; i++){
    cout << a[i].first << " " << a[i].second << "\n";
}

Now a contains both both our values and their respective indices in the sorted.

a[i].first = value at i'th.

a[i].second = idx in initial array.

How can I use pointers in Java?

You can use addresses and pointers using the Unsafe class. However as the name suggests, these methods are UNSAFE and generally a bad idea. Incorrect usage can result in your JVM randomly dying (actually the same problem get using pointers incorrectly in C/C++)

While you may be used to pointers and think you need them (because you don't know how to code any other way), you will find that you don't and you will be better off for it.

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

Set your editor to point to this program:

/Applications/TextEdit.app/Contents/MacOS/TextEdit

With SVN, you should set SVN_EDITOR environment variable to:

$ export SVN_EDITOR=/Applications/TextEdit.app/Contents/MacOS/TextEdit

And then, when you try committing something, TextEdit will launch.

How to combine two or more querysets in a Django view?

Concatenating the querysets into a list is the simplest approach. If the database will be hit for all querysets anyway (e.g. because the result needs to be sorted), this won't add further cost.

from itertools import chain
result_list = list(chain(page_list, article_list, post_list))

Using itertools.chain is faster than looping each list and appending elements one by one, since itertools is implemented in C. It also consumes less memory than converting each queryset into a list before concatenating.

Now it's possible to sort the resulting list e.g. by date (as requested in hasen j's comment to another answer). The sorted() function conveniently accepts a generator and returns a list:

result_list = sorted(
    chain(page_list, article_list, post_list),
    key=lambda instance: instance.date_created)

If you're using Python 2.4 or later, you can use attrgetter instead of a lambda. I remember reading about it being faster, but I didn't see a noticeable speed difference for a million item list.

from operator import attrgetter
result_list = sorted(
    chain(page_list, article_list, post_list),
    key=attrgetter('date_created'))

How to suppress binary file matching results in grep

This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:

bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk  ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$

Python list directory, subdirectory, and files

A bit simpler one-liner:

import os
from itertools import product, chain

chain.from_iterable([[os.sep.join(w) for w in product([i[0]], i[2])] for i in os.walk(dir)])

string.split - by multiple character delimiter

string tests = "abc][rfd][5][,][.";
string[] reslts = tests.Split(new char[] { ']', '[' }, StringSplitOptions.RemoveEmptyEntries);

Are HTTPS headers encrypted?

Yes, headers are encrypted. It's written here.

Everything in the HTTPS message is encrypted, including the headers, and the request/response load.

Mailto: Body formatting

From the first result on Google:

mailto:[email protected]_t?subject=Header&body=This%20is...%20the%20first%20line%0D%0AThis%20is%20the%20second

How to change current Theme at runtime in Android

You can finish the Acivity and recreate it afterwards in this way your activity will be created again and all the views will be created with the new theme.

mysql update column with value from another table

Store your data in temp table

Select * into tempTable from table1

Now update the column

 UPDATE table1
    SET table1.FileName = (select FileName from tempTable where tempTable.id = table1.ID);

How can I shuffle an array?

Use the modern version of the Fisher–Yates shuffle algorithm:

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

ES2015 (ES6) version

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.

Use

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

Implementing prototype

Using Object.defineProperty (method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr). The following will allow you to call arr.shuffle() to shuffle the array arr:

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});

How to run function of parent window when child window closes?

This is an old post, but I thought I would add another method to do this:

var win = window.open("http://www.google.com");

var winClosed = setInterval(function () {

    if (win.closed) {
        clearInterval(winClosed);
        foo(); //Call your function here
    }

}, 250);

You don't have to modify the contents or use any event handlers from the child window.

Pass Array Parameter in SqlCommand

If you can use a tool like "dapper", this can be simply:

int[] ages = { 20, 21, 22 }; // could be any common list-like type
var rows = connection.Query<YourType>("SELECT * from TableA WHERE Age IN @ages",
          new { ages }).ToList();

Dapper will handle unwrapping this to individual parameters for you.

How to call Stored Procedures with EntityFramework?

This is an example of querying MySQL procedure using Entity Framework

This is the definition of my Stored Procedure in MySQL:

CREATE PROCEDURE GetUpdatedAds (
    IN curChangeTracker BIGINT
    IN PageSize INT
) 
BEGIN
   -- select some recored...
END;

And this is how I query it using Entity Framework:

 var curChangeTracker = new SqlParameter("@curChangeTracker", MySqlDbType.Int64).Value = 0;
 var pageSize = new SqlParameter("@PageSize", (MySqlDbType.Int64)).Value = 100;

 var res = _context.Database.SqlQuery<MyEntityType>($"call GetUpdatedAds({curChangeTracker}, {pageSize})");

Note that I am using C# String Interpolation to build my Query String.

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

By default wamp sets the following as the default for any directory not explicitly declared:

<Directory />
    AllowOverride none
    Require all denied
</Directory>

For me, if I comment out the line that says Require all denied I started having access to the directory in question. I don't recommend this.

Instead in the directory directive I included Require local as below:

<Directory "C:/GitHub/head_count/">
    AllowOverride All
    Allow from all
    Require local
</Directory>

NOTE: I was still getting permission denied when I only had Allow from all. Adding Require local helped for me.

Class method decorator with self arguments?

from re import search
from functools import wraps

def is_match(_lambda, pattern):
    def wrapper(f):
        @wraps(f)
        def wrapped(self, *f_args, **f_kwargs):
            if callable(_lambda) and search(pattern, (_lambda(self) or '')): 
                f(self, *f_args, **f_kwargs)
        return wrapped
    return wrapper

class MyTest(object):

    def __init__(self):
        self.name = 'foo'
        self.surname = 'bar'

    @is_match(lambda x: x.name, 'foo')
    @is_match(lambda x: x.surname, 'foo')
    def my_rule(self):
        print 'my_rule : ok'

    @is_match(lambda x: x.name, 'foo')
    @is_match(lambda x: x.surname, 'bar')
    def my_rule2(self):
        print 'my_rule2 : ok'



test = MyTest()
test.my_rule()
test.my_rule2()

ouput: my_rule2 : ok

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

My solution was a little bit different and faster :)

  1. Go to Windows Credentials (Start-> Windows Credentials) and remove credentials for your repository (they starts with git:xxx)
  2. Go to VSCode and in Terminal write:

    config credential.helper wincred

  3. Go to Visual Studio (no VSCode) and make a git pull. A popup will show asking for credentials. Put your credentials for the repo

  4. Go to VSCode and make a git pull. Credentials were automatically fetched from wincred store

Credentials are automatically created and stored in wincredentials, so the next time you cannot be asked for credentials. (also a Personal Access Token will be provided from visualstudio.com if you are using DevOps hosted git repo).

jQuery Selector: Id Ends With?

$('element[id$=txtTitle]')

It's not strictly necessary to quote the text fragment you are matching against

Convert an integer to an array of digits

I modified Jon Skeet's accepted answer as it does not accept negative values.

This now accepts and converts the number appropriately:

public static void main(String[] args) {
    int number = -1203;
    boolean isNegative = false;
    String temp = Integer.toString(number);

    if(temp.charAt(0)== '-') {
        isNegative = true;
    }
    int len = temp.length();
    if(isNegative) {
        len = len - 1;
    }
    int[] myArr = new int[len];

    for (int i = 0; i < len; i++) {
        if (isNegative) {
            myArr[i] = temp.charAt(i + 1) - '0';
        }
        if(!isNegative) {
            myArr[i] = temp.charAt(i) - '0';
        }
    }

    if (isNegative) {
        for (int i = 0; i < len; i++) {
            myArr[i] = myArr[i] * (-1);
        }
    }

    for (int k : myArr) {
        System.out.println(k);
    }
}

Output

-1
-2
0
-3

How to add a constant column in a Spark DataFrame?

As the other answers have described, lit and typedLit are how to add constant columns to DataFrames. lit is an important Spark function that you will use frequently, but not for adding constant columns to DataFrames.

You'll commonly be using lit to create org.apache.spark.sql.Column objects because that's the column type required by most of the org.apache.spark.sql.functions.

Suppose you have a DataFrame with a some_date DateType column and would like to add a column with the days between December 31, 2020 and some_date.

Here's your DataFrame:

+----------+
| some_date|
+----------+
|2020-09-23|
|2020-01-05|
|2020-04-12|
+----------+

Here's how to calculate the days till the year end:

val diff = datediff(lit(Date.valueOf("2020-12-31")), col("some_date"))
df
  .withColumn("days_till_yearend", diff)
  .show()
+----------+-----------------+
| some_date|days_till_yearend|
+----------+-----------------+
|2020-09-23|               99|
|2020-01-05|              361|
|2020-04-12|              263|
+----------+-----------------+

You could also use lit to create a year_end column and compute the days_till_yearend like so:

import java.sql.Date

df
  .withColumn("yearend", lit(Date.valueOf("2020-12-31")))
  .withColumn("days_till_yearend", datediff(col("yearend"), col("some_date")))
  .show()
+----------+----------+-----------------+
| some_date|   yearend|days_till_yearend|
+----------+----------+-----------------+
|2020-09-23|2020-12-31|               99|
|2020-01-05|2020-12-31|              361|
|2020-04-12|2020-12-31|              263|
+----------+----------+-----------------+

Most of the time, you don't need to use lit to append a constant column to a DataFrame. You just need to use lit to convert a Scala type to a org.apache.spark.sql.Column object because that's what's required by the function.

See the datediff function signature:

enter image description here

As you can see, datediff requires two Column arguments.

Redirect with CodeIgniter

If your directory structure is like this,

site
  application
         controller
                folder_1
                   first_controller.php
                   second_controller.php
                folder_2
                   first_controller.php
                   second_controller.php

And when you are going to redirect it in same controller in which you are working then just write the following code.

 $this->load->helper('url');
    if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic
    {
         redirect('same_controller/method', 'refresh');
    }

And if you want to redirect to another control then use the following code.

$this->load->helper('url');
if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic
{
     redirect('folder_name/any_controller_name/method', 'refresh');
}

Page Redirect after X seconds wait using JavaScript

You actually need to pass a function inside the window.setTimeout() which you want to execute after 5000 milliseconds, like this:

$(document).ready(function () {
    // Handler for .ready() called.
    window.setTimeout(function () {
        location.href = "https://www.google.co.in";
    }, 5000);
});

For More info: .setTimeout()

Installing specific laravel version with composer create-project

composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist

And then you probably need to install all of vendor packages, so

composer install

I can't install python-ldap

As a general solution to install Python packages with binary dependencies [1] on Debian/Ubuntu:

sudo apt-get build-dep python-ldap
# installs system dependencies (but not the package itself)
pew workon my_virtualenv # enter your virtualenv
pip install python-ldap

You'll have to check the name of your Python package on Ubuntu versus PyPI. In this case they're the same.

Obviously doesn't work if the Python package is not in the Ubuntu repos.

[1] I learnt this trick when trying to pip install matplotlib on Ubuntu.

Simple Java Client/Server Program

There is a fundamental concept of IP routing: You must have a unique IP address if you want your machine to be reachable via the Internet. This is called a "Public IP Address". "www.whatismyipaddress.com" will give you this. If your server is behind some default gateway, IP packets would reach you via that router. You can not be reached via your private IP address from the outside world. You should note that private IP addresses of client and server may be same as long as their corresponding default gateways have different addresses (that's why IPv4 is still in effect) I guess you're trying to ping from your private address of your client to the public IP address of the server (provided by whatismyipaddress.com). This is not feasible. In order to achieve this, a mapping from private to public address is required, a process called Network Address Translation or NAT in short. This is configured in Firewall or Router. You can create your own private network (say via wifi). In this case, since your client and server would be on the same logical network, no private to public address translation would be required and hence you can communicate using your private IP addresses only.

Setting Elastic search limit to "unlimited"

You can use the from and size parameters to page through all your data. This could be very slow depending on your data and how much is in the index.

http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-from-size.html

What Vim command(s) can be used to quote/unquote words?

If you use the vim plugin https://github.com/tpope/vim-surround (or use VSCode Vim plugin, which comes with vim-surround pre-installed), its pretty convinient!

add

ysiw' // surround in word `'`

drop

ds' // drop surround `'`

change

cs'" // change surround from `'` to `"`

It even works for html tags!

cst<em> // change surround from current tag to `<em>`

check out the readme on github for better examples

Best way to track onchange as-you-type in input type="text"?

there is a quite near solution (do not fix all Paste ways) but most of them:

It works for inputs as well as for textareas:

<input type="text" ... >
<textarea ... >...</textarea>

Do like this:

<input type="text" ... onkeyup="JavaScript: ControlChanges()" onmouseup="JavaScript: ControlChanges()" >
<textarea ... onkeyup="JavaScript: ControlChanges()" onmouseup="JavaScript: ControlChanges()" >...</textarea>

As i said, not all ways to Paste fire an event on all browsers... worst some do not fire any event at all, but Timers are horrible to be used for such.

But most of Paste ways are done with keyboard and/or mouse, so normally an onkeyup or onmouseup are fired after a paste, also onkeyup is fired when typing on keyboard.

Ensure yor check code does not take much time... otherwise user get a poor impresion.

Yes, the trick is to fire on key and on mouse... but beware both can be fired, so take in mind such!!!

How do I trim leading/trailing whitespace in a standard way?

These functions will modify the original buffer, so if dynamically allocated, the original pointer can be freed.

#include <string.h>

void rstrip(char *string)
{
  int l;
  if (!string)
    return;
  l = strlen(string) - 1;
  while (isspace(string[l]) && l >= 0)
    string[l--] = 0;
}

void lstrip(char *string)
{
  int i, l;
  if (!string)
    return;
  l = strlen(string);
  while (isspace(string[(i = 0)]))
    while(i++ < l)
      string[i-1] = string[i];
}

void strip(char *string)
{
  lstrip(string);
  rstrip(string);
}

All ASP.NET Web API controllers return 404

If you manage the IIS and you are the one who have to create new site then check the "Application Pool" and be sure the CLR version must be selected. In my situation, it had been selected "No Managed Code". After changed to v4.0 it started to work.

How to add a color overlay to a background image?

Try this, it's simple and clear. I have found it from here : https://css-tricks.com/tinted-images-multiple-backgrounds/

.tinted-image {

  width: 300px;
  height: 200px;

  background: 
    /* top, transparent red */ 
    linear-gradient(
      rgba(255, 0, 0, 0.45), 
      rgba(255, 0, 0, 0.45)
    ),
    /* bottom, image */
    url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
}

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

BLOB is for binary data (videos, images, documents, other)

CLOB is for large text data (text)

Maximum size on MySQL 2GB

Maximum size on Oracle 128TB

How to install maven on redhat linux

I made the following script:

#!/bin/bash

# Target installation location
MAVEN_HOME="/your/path/here"

# Link to binary tar.gz archive
# See https://maven.apache.org/download.cgi?html_a_name#Files
MAVEN_BINARY_TAR_GZ_ARCHIVE="http://www.trieuvan.com/apache/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz"

# Configuration parameters used to start up the JVM running Maven, i.e. "-Xms256m -Xmx512m"
# See https://maven.apache.org/configure.html
MAVEN_OPTS="" # Optional (not needed)

if [[ ! -d $MAVEN_HOME ]]; then
  # Create nonexistent subdirectories recursively
  mkdir -p $MAVEN_HOME

  # Curl location of tar.gz archive & extract without first directory
  curl -L $MAVEN_BINARY_TAR_GZ_ARCHIVE | tar -xzf - -C $MAVEN_HOME --strip 1

  # Creating a symbolic/soft link to Maven in the primary directory of executable commands on the system
  ln -s $MAVEN_HOME/bin/mvn /usr/bin/mvn

  # Permanently set environmental variable (if not null)
  if [[ -n $MAVEN_OPTS ]]; then
    echo "export MAVEN_OPTS=$MAVEN_OPTS" >> ~/.bashrc
  fi

  # Using MAVEN_HOME, MVN_HOME, or M2 as your env var is irrelevant, what counts
  # is your $PATH environment.
  # See http://stackoverflow.com/questions/26609922/maven-home-mvn-home-or-m2-home
  echo "export PATH=$MAVEN_HOME/bin:$PATH" >> ~/.bashrc
else
  # Do nothing if target installation directory already exists
  echo "'$MAVEN_HOME' already exists, please uninstall existing maven first."
fi

How to pass a list from Python, by Jinja2 to JavaScript

To pass some context data to javascript code, you have to serialize it in a way it will be "understood" by javascript (namely JSON). You also need to mark it as safe using the safe Jinja filter, to prevent your data from being htmlescaped.

You can achieve this by doing something like that:

The view

import json

@app.route('/')
def my_view():
    data = [1, 'foo']
    return render_template('index.html', data=json.dumps(data))

The template

<script type="text/javascript">
    function test_func(data) {
        console.log(data);
    }
    test_func({{ data|safe }})
</script>

Edit - exact answer

So, to achieve exactly what you want (loop over a list of items, and pass them to a javascript function), you'd need to serialize every item in your list separately. Your code would then look like this:

The view

import json

@app.route('/')
def my_view():
    data = [1, "foo"]
    return render_template('index.html', data=map(json.dumps, data))

The template

{% for item in data %}
    <span onclick=someFunction({{ item|safe }});>{{ item }}</span>
{% endfor %}

Edit 2

In my example, I use Flask, I don't know what framework you're using, but you got the idea, you just have to make it fit the framework you use.

Edit 3 (Security warning)

NEVER EVER DO THIS WITH USER-SUPPLIED DATA, ONLY DO THIS WITH TRUSTED DATA!

Otherwise, you would expose your application to XSS vulnerabilities!

In CSS how do you change font size of h1 and h2

h1 {
  font-weight: bold;
  color: #fff;
  font-size: 32px;
}

h2 {
  font-weight: bold;
  color: #fff;
  font-size: 24px;
}

Note that after color you can use a word (e.g. white), a hex code (e.g. #fff) or RGB (e.g. rgb(255,255,255)) or RGBA (e.g. rgba(255,255,255,0.3)).

How to debug (only) JavaScript in Visual Studio?

For debugging JavaScript code in VS2015, there is no need for

  1. Enabling script debugging in IE Options -> Advanced tab
  2. Writing debugger statement in JavaScript code

Attaching IE didn't work, but here is a workaround.

Select IE

enter image description here

and press F5. This will attach both worker process and IE as shown here- enter image description here

If you are not interested in debugging server code, detach it from Processes window. enter image description here

You will still face the slowness when you press F5 and all your server code compiles and loads up in VS. Note that you can detach and attach again the IE instance launched from VS. JavaScript breakpoints are hit the same way they are in server side code.

regex to match a single character that is anything but a space

  • \s matches any white-space character
  • \S matches any non-white-space character
  • You can match a space character with just the space character;
  • [^ ] matches anything but a space character.

Pick whichever is most appropriate.

Parsing string as JSON with single quotes?

Using single quotes for keys are not allowed in JSON. You need to use double quotes.

For your use-case perhaps this would be the easiest solution:

str = '{"a":1}';

Source:

If a property requires quotes, double quotes must be used. All property names must be surrounded by double quotes.

Maven Java EE Configuration Marker with Java Server Faces 1.2

I had the same problem. After adding velocity dependencies in my maven project i was getting the same error in marker tab. Then I noticed that the web.xml file that maven project creates has servlet2.3 schema. When i changed it to servlet 3.0 schema and save the project then this error gone. Here is the web.xml file that maven creates

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
</web-app>

Change it to

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
                        version="3.0">
    <display-name>Archetype Created Web Application</display-name>

</web-app>

save the project, and your error would gone.

After that if markers tab is still showing message then Select the project. Do mouse right click. Select Maven --> Update Project.

Hopefully error would be gone then.

Thanks

how to list all sub directories in a directory

To just get the simple list of folders without full path, you can use:

Directory.GetDirectories(parentDirectory).Select(d => Path.GetRelativePath(parentDirectory, d)

You seem to not be depending on "@angular/core". This is an error

Faced the same Issue. While running ngserve you should be in the apps directory. To confirm(on GIT BASH : you will have (master) after the directory path at gitbash prompt, if you are at app directory.)

How do I add a auto_increment primary key in SQL Server database?

In SQL Server 2008:

  • Right click on table
  • Go to design
  • Select numeric datatype
  • Add Name to the new column
  • Make Identity Specification to 'YES'

Passing a dictionary to a function as keyword parameters

Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary

So my example becomes:

d = dict(p1=1, p2=2)
def f2(p1,p2):
    print p1, p2
f2(**d)

resize2fs: Bad magic number in super-block while trying to open

After reading about LVM and being familiar with PV -> VG -> LV, this works for me :

0) #df -h

Filesystem               Size  Used Avail Use% Mounted on
devtmpfs                 1.9G     0  1.9G   0% /dev
tmpfs                    1.9G     0  1.9G   0% /dev/shm
tmpfs                    1.9G  824K  1.9G   1% /run
tmpfs                    1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/mapper/fedora-root   15G  2.1G   13G  14% /
tmpfs                    1.9G     0  1.9G   0% /tmp
/dev/md126p1             976M  119M  790M  14% /boot
tmpfs                    388M     0  388M   0% /run/user/0

1) # vgs

  VG     #PV #LV #SN Attr   VSize   VFree   
  fedora   1   2   0 wz--n- 231.88g 212.96g

2) # vgdisplay

  --- Volume group ---
  VG Name               fedora
  System ID
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  3
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                2
  Open LV               2
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               231.88 GiB
  PE Size               4.00 MiB
  Total PE              59361
  Alloc PE / Size       4844 / 18.92 GiB
  Free  PE / Size       54517 / 212.96 GiB
  VG UUID               9htamV-DveQ-Jiht-Yfth-OZp7-XUDC-tWh5Lv

3) # lvextend -l +100%FREE /dev/mapper/fedora-root

  Size of logical volume fedora/root changed from 15.00 GiB (3840 extents) to 227.96 GiB (58357 extents).
  Logical volume fedora/root successfully resized.

4) #lvdisplay

5) #fd -h

6) # xfs_growfs /dev/mapper/fedora-root

meta-data=/dev/mapper/fedora-root isize=512    agcount=4, agsize=983040 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=1        finobt=1 spinodes=0 rmapbt=0
         =                       reflink=0
data     =                       bsize=4096   blocks=3932160, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=1
log      =internal               bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
data blocks changed from 3932160 to 59757568

7) #df -h

Filesystem               Size  Used Avail Use% Mounted on
devtmpfs                 1.9G     0  1.9G   0% /dev
tmpfs                    1.9G     0  1.9G   0% /dev/shm
tmpfs                    1.9G  828K  1.9G   1% /run
tmpfs                    1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/mapper/fedora-root  228G  2.3G  226G   2% /
tmpfs                    1.9G     0  1.9G   0% /tmp
/dev/md126p1             976M  119M  790M  14% /boot
tmpfs                    388M     0  388M   0% /run/user/0

Best Regards,

Show which git tag you are on?

When you check out a tag, you have what's called a "detached head". Normally, Git's HEAD commit is a pointer to the branch that you currently have checked out. However, if you check out something other than a local branch (a tag or a remote branch, for example) you have a "detached head" -- you're not really on any branch. You should not make any commits while on a detached head.

It's okay to check out a tag if you don't want to make any edits. If you're just examining the contents of files, or you want to build your project from a tag, it's okay to git checkout my_tag and work with the files, as long as you don't make any commits. If you want to start modifying files, you should create a branch based on the tag:

$ git checkout -b my_tag_branch my_tag

will create a new branch called my_tag_branch starting from my_tag. It's safe to commit changes on this branch.

Define the selected option with the old input in Laravel / Blade

After Playing around a bit I came up with this and it seems to work just splendidly

<select name="options[]" id="options" class="form-control" multiple>
    @foreach($settings->includes->get('optionList') as $option)
        <option value="{{ $option->id }}" {{ (collect(old('options'))->contains($option->id)) ? 'selected':'' }}>{{ $option->name }}</option>
    @endforeach
</select>

I may be 100% wrong in leveraging the collect function but it works fine on many of my tests. After seeing a few other posts on the site I saw someone recommend leveraging the in_array($needle, $array) function but after noticing that if my old('options') was null it would error out because it requires in_array requires, bet you guessed an array. So after finding the solution to that albeit ugly solution I played with the collect method because after all we are using larval right! well anyway the ugly solution is as follows

@if (old("options")){{ (in_array($option->id, old("options")) ? "selected":"") }}@endif

inline but man that looks ugly to me so long story short I am using the following instead

{{ (collect(old('options'))->contains($option->id)) ? 'selected':'' }}

Hope this helps others!!

This does not seem to work for a non multiple select field ill get back with one that does work for that though.

Express-js wildcard routing to cover everything under and including a path

For those who are learning node/express (just like me): do not use wildcard routing if possible!

I also wanted to implement the routing for GET /users/:id/whatever using wildcard routing. This is how I got here.

More info: https://blog.praveen.science/wildcard-routing-is-an-anti-pattern/

Java 8 Streams: multiple filters vs. complex condition

The code that has to be executed for both alternatives is so similar that you can’t predict a result reliably. The underlying object structure might differ but that’s no challenge to the hotspot optimizer. So it depends on other surrounding conditions which will yield to a faster execution, if there is any difference.

Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace filter(x -> x.isCool()) by filter(ItemType::isCool). That way you have eliminated the synthetic delegating method created for your lambda expression. So combining two filters using two method references might create the same or lesser delegation code than a single filter invocation using a lambda expression with &&.

But, as said, this kind of overhead will be eliminated by the HotSpot optimizer and is negligible.

In theory, two filters could be easier parallelized than a single filter but that’s only relevant for rather computational intense tasks¹.

So there is no simple answer.

The bottom line is, don’t think about such performance differences below the odor detection threshold. Use what is more readable.


¹…and would require an implementation doing parallel processing of subsequent stages, a road currently not taken by the standard Stream implementation

How can I make my layout scroll both horizontally and vertically?

Use this:

android:scrollbarAlwaysDrawHorizontalTrack="true"

Example:

<Gallery android:id="@+id/gallery"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:scrollbarAlwaysDrawHorizontalTrack="true" />

How to assign more memory to docker container

That 2GB limit you see is the total memory of the VM in which docker runs.

If you are using docker-for-windows or docker-for-mac you can easily increase it from the Whale icon in the task bar, then go to Preferences -> Advanced:

Docker Preferences

But if you are using VirtualBox behind, open VirtualBox, Select and configure the docker-machine assigned memory.

See this for Mac:

https://docs.docker.com/docker-for-mac/#memory

MEMORY By default, Docker for Mac is set to use 2 GB runtime memory, allocated from the total available memory on your Mac. You can increase the RAM on the app to get faster performance by setting this number higher (for example to 3) or lower (to 1) if you want Docker for Mac to use less memory.

For Windows:

https://docs.docker.com/docker-for-windows/#advanced

Memory - Change the amount of memory the Docker for Windows Linux VM uses

AngularJS - Find Element with attribute

Rather than querying the DOM for elements (which isn't very angular see "Thinking in AngularJS" if I have a jQuery background?) you should perform your DOM manipulation within your directive. The element is available to you in your link function.

So in your myDirective

return {
    link: function (scope, element, attr) {
        element.html('Hello world');
    }
}

If you must perform the query outside of the directive then it would be possible to use querySelectorAll in modern browers

angular.element(document.querySelectorAll("[my-directive]"));

however you would need to use jquery to support IE8 and backwards

angular.element($("[my-directive]"));

or write your own method as demonstrated here Get elements by attribute when querySelectorAll is not available without using libraries?

Using NSPredicate to filter an NSArray based on NSDictionary keys

#import <Foundation/Foundation.h>
// clang -framework Foundation Siegfried.m 
    int
main() {
    NSArray *arr = @[
        @{@"1" : @"Fafner"},
        @{@"1" : @"Fasolt"}
    ];
    NSPredicate *p = [NSPredicate predicateWithFormat:
        @"SELF['1'] CONTAINS 'e'"];
    NSArray *res = [arr filteredArrayUsingPredicate:p];
    NSLog(@"Siegfried %@", res);
    return 0;
}

What is the best open XML parser for C++?

Try TinyXML or IrrXML...Both are lightweight XML parsers ( I'd suggest you to use TinyXML, anyway ).

.prop('checked',false) or .removeAttr('checked')?

Another alternative to do the same thing is to filter on type=checkbox attribute:

$('input[type="checkbox"]').removeAttr('checked');

or

$('input[type="checkbox"]').prop('checked' , false);

Remeber that The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

Know more...

Checking if output of a command contains a certain string in a shell script

Testing $? is an anti-pattern.

if ./somecommand | grep -q 'string'; then
  echo "matched"
fi

How do I block or restrict special characters from input fields with jquery?

Restrict specials characters on keypress. Here's a test page for key codes: http://www.asquare.net/javascript/tests/KeyCode.html

var specialChars = [62,33,36,64,35,37,94,38,42,40,41];

some_element.bind("keypress", function(event) {
// prevent if in array
   if($.inArray(event.which,specialChars) != -1) {
       event.preventDefault();
   }
});

In Angular, I needed a proper currency format in my textfield. My solution:

var angularApp = angular.module('Application', []);

...

// new angular directive
angularApp.directive('onlyNum', function() {
    return function( scope, element, attrs) {

        var specialChars = [62,33,36,64,35,37,94,38,42,40,41];

        // prevent these special characters
        element.bind("keypress", function(event) {
            if($.inArray(event.which,specialChars) != -1) {
                prevent( scope, event, attrs)
             }
        });

        var allowableKeys = [8,9,37,39,46,48,49,50,51,52,53,54,55,56
            ,57,96,97,98,99,100,101,102,103,104,105,110,190];

        element.bind("keydown", function(event) {
            if($.inArray(event.which,allowableKeys) == -1) {
                prevent( scope, event, attrs)
            }
        });
    };
})

// scope.$apply makes angular aware of your changes
function prevent( scope, event, attrs) {
    scope.$apply(function(){
        scope.$eval(attrs.onlyNum);
        event.preventDefault();
    });
    event.preventDefault();
}

In the html add the directive

<input only-num type="text" maxlength="10" id="amount" placeholder="$XXXX.XX"
   autocomplete="off" ng-model="vm.amount" ng-change="vm.updateRequest()">

and in the corresponding angular controller I only allow there to be only 1 period, convert text to number and add number rounding on 'blur'

...

this.updateRequest = function() {
    amount = $scope.amount;
    if (amount != undefined) {
        document.getElementById('spcf').onkeypress = function (e) {
        // only allow one period in currency
        if (e.keyCode === 46 && this.value.split('.').length === 2) {
            return false;
        }
    }
    // Remove "." When Last Character and round the number on blur
    $("#amount").on("blur", function() {
      if (this.value.charAt(this.value.length-1) == ".") {
          this.value.replace(".","");
          $("#amount").val(this.value);
      }
      var num = parseFloat(this.value);
      // check for 'NaN' if its safe continue
      if (!isNaN(num)) {
        var num = (Math.round(parseFloat(this.value) * 100) / 100).toFixed(2);
        $("#amount").val(num);
      }
    });
    this.data.amountRequested = Math.round(parseFloat(amount) * 100) / 100;
}

...

The pipe ' ' could not be found angular2 custom pipe

Make sure you are not facing a "cross module" problem

If the component which is using the pipe, doesn't belong to the module which has declared the pipe component "globally" then the pipe is not found and you get this error message.

In my case I've declared the pipe in a separate module and imported this pipe module in any other module having components using the pipe.

I have declared a that the component in which you are using the pipe is

the Pipe Module

 import { NgModule }      from '@angular/core';
 import { myDateFormat }          from '../directives/myDateFormat';

 @NgModule({
     imports:        [],
     declarations:   [myDateFormat],
     exports:        [myDateFormat],
 })

 export class PipeModule {

   static forRoot() {
      return {
          ngModule: PipeModule,
          providers: [],
      };
   }
 } 

Usage in another module (e.g. app.module)

  // Import APPLICATION MODULES
  ...
  import { PipeModule }    from './tools/PipeModule';

  @NgModule({
     imports: [
    ...
    , PipeModule.forRoot()
    ....
  ],

Execute function after Ajax call is complete

Try this code:

var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
 $.ajax({                                            
     url: 'api.php',                        
     data: 'id1='+q+'',                                                         
     dataType: 'json',
     async:false,                    
     success: function(data)          
     {   
        id = data[0];              
        vname = data[1];
     },
    complete: function (data) {
      printWithAjax(); 
     }
    });

  }//end of the for statement
  }//end of ajax call function

The "complete" function executes only after the "success" of ajax. So try to call the printWithAjax() on "complete". This should work for you.

How to unpack pkl file?

In case you want to work with the original MNIST files, here is how you can deserialize them.

If you haven't downloaded the files yet, do that first by running the following in the terminal:

wget http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz

Then save the following as deserialize.py and run it.

import numpy as np
import gzip

IMG_DIM = 28

def decode_image_file(fname):
    result = []
    n_bytes_per_img = IMG_DIM*IMG_DIM

    with gzip.open(fname, 'rb') as f:
        bytes_ = f.read()
        data = bytes_[16:]

        if len(data) % n_bytes_per_img != 0:
            raise Exception('Something wrong with the file')

        result = np.frombuffer(data, dtype=np.uint8).reshape(
            len(bytes_)//n_bytes_per_img, n_bytes_per_img)

    return result

def decode_label_file(fname):
    result = []

    with gzip.open(fname, 'rb') as f:
        bytes_ = f.read()
        data = bytes_[8:]

        result = np.frombuffer(data, dtype=np.uint8)

    return result

train_images = decode_image_file('train-images-idx3-ubyte.gz')
train_labels = decode_label_file('train-labels-idx1-ubyte.gz')

test_images = decode_image_file('t10k-images-idx3-ubyte.gz')
test_labels = decode_label_file('t10k-labels-idx1-ubyte.gz')

The script doesn't normalize the pixel values like in the pickled file. To do that, all you have to do is

train_images = train_images/255
test_images = test_images/255

How to getText on an input in protractor

getText() function won't work like the way it used to be for webdriver, in order to get it work for protractor you will need to wrap it in a function and return the text something like we did for our protractor framework we have kept it in a common function like -

getText : function(element, callback) {
        element.getText().then (function(text){             
            callback(text);
         });        

    },

By this you can have the text of an element.

Let me know if it is still unclear.

deny directory listing with htaccess

Options -Indexes perfectly works for me ,

here is .htaccess file :

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes <---- This Works for Me :)
    </IfModule>


   ....etc stuff

</IfModule>

Before : enter image description here

After :

enter image description here

Run command on the Ansible host

From the Ansible documentation:

Delegation This isn’t actually rolling update specific but comes up frequently in those cases.

If you want to perform a task on one host with reference to other hosts, use the ‘delegate_to’ keyword on a task. This is ideal for placing nodes in a load balanced pool, or removing them. It is also very useful for controlling outage windows. Be aware that it does not make sense to delegate all tasks, debug, add_host, include, etc always get executed on the controller. Using this with the ‘serial’ keyword to control the number of hosts executing at one time is also a good idea:

---

- hosts: webservers
  serial: 5

  tasks:

  - name: take out of load balancer pool
    command: /usr/bin/take_out_of_pool {{ inventory_hostname }}
    delegate_to: 127.0.0.1

  - name: actual steps would go here
    yum:
      name: acme-web-stack
      state: latest

  - name: add back to load balancer pool
    command: /usr/bin/add_back_to_pool {{ inventory_hostname }}
    delegate_to: 127.0.0.1

These commands will run on 127.0.0.1, which is the machine running Ansible. There is also a shorthand syntax that you can use on a per-task basis: ‘local_action’. Here is the same playbook as above, but using the shorthand syntax for delegating to 127.0.0.1:

---

# ...

  tasks:

  - name: take out of load balancer pool
    local_action: command /usr/bin/take_out_of_pool {{ inventory_hostname }}

# ...

  - name: add back to load balancer pool
    local_action: command /usr/bin/add_back_to_pool {{ inventory_hostname }}

A common pattern is to use a local action to call ‘rsync’ to recursively copy files to the managed servers. Here is an example:

---
# ...
  tasks:

  - name: recursively copy files from management server to target
    local_action: command rsync -a /path/to/files {{ inventory_hostname }}:/path/to/target/

Note that you must have passphrase-less SSH keys or an ssh-agent configured for this to work, otherwise rsync will need to ask for a passphrase.