Programs & Examples On #Listview

A ListView is a graphical screen control or widget provided by UI libraries in a majority of modern operating systems to show items in a list form.

How to handle ListView click in Android

The two answers before mine are correct - you can use OnItemClickListener.

It's good to note that the difference between OnItemClickListener and OnItemSelectedListener, while sounding subtle, is in fact significant, as item selection and focus are related with the touch mode of your AdapterView.

By default, in touch mode, there is no selection and focus. You can take a look here for further info on the subject.

ListView item background via custom selector

It's enough,if you put in list_row_layout.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:background="@drawable/listitem_background">... </LinearLayout>

listitem_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/dark" android:state_pressed="true" />
    <item android:drawable="@color/dark" android:state_focused="true" />
    <item android:drawable="@android:color/white" />
</selector>

Output Django queryset as JSON

You can use JsonResponse with values. Simple example:

from django.http import JsonResponse

def some_view(request):
    data = list(SomeModel.objects.values())  # wrap in list(), because QuerySet is not JSON serializable
    return JsonResponse(data, safe=False)  # or JsonResponse({'data': data})

Or another approach with Django's built-in serializers:

from django.core import serializers
from django.http import HttpResponse

def some_view(request):
    qs = SomeModel.objects.all()
    qs_json = serializers.serialize('json', qs)
    return HttpResponse(qs_json, content_type='application/json')

In this case result is slightly different (without indent by default):

[
    {
        "model": "some_app.some_model",
        "pk": 1,
        "fields": {
            "name": "Elon",
            "age": 48,
            ...
        }
    },
    ...
]

I have to say, it is good practice to use something like marshmallow to serialize queryset.

...and a few notes for better performance:

  • use pagination if your queryset is big;
  • use objects.values() to specify list of required fields to avoid serialization and sending to client unnecessary model's fields (you also can pass fields to serializers.serialize);

How to stop EditText from gaining focus at Activity startup in Android

The easiest way is to add android:windowSoftInputMode="stateAlwaysHidden" in the activity tag of the Manifest.xml file

How to dynamically remove items from ListView on a button click?

Have a button on list and let it onclick feature in xml like to get postion first

public void OnClickButton(View V){
  final int postion = listView.getPositionForView(V);
    System.out.println("postion selected is : "+postion);
Delete(postion);

}
public void Delete(int position){
    if (adapter.getCount() > 0) {

        //Log.d("largest no is",""+largestitemno);
        //deleting the latest added by subtracting one 1 
        comment = (GenrricStoring) adapter.getItem(position);
        //Log.d("Deleting item is: ",""+comment);
        dbconnection.deleteComment(comment);
        List<GenrricStoring> values = dbconnection.getAllComments();
        //updating the content on the screen
        this.adapter = new UserItemAdapter(this, android.R.layout.simple_list_item_1, values);
        listView.setAdapter(adapter);
    }
    else
    {
        int duration = Toast.LENGTH_SHORT;
        //for showing nothing is left in the list
        Toast toast = Toast.makeText(getApplicationContext(),"Db is empty", duration);
        toast.setGravity(Gravity.CENTER, 0, 0);

        toast.show();
    }

}

Custom Adapter for List View

public class ListAdapter extends ArrayAdapter<Item> {

    private int resourceLayout;
    private Context mContext;

    public ListAdapter(Context context, int resource, List<Item> items) {
        super(context, resource, items);
        this.resourceLayout = resource;
        this.mContext = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

        if (v == null) {
            LayoutInflater vi;
            vi = LayoutInflater.from(mContext);
            v = vi.inflate(resourceLayout, null);
        }

        Item p = getItem(position);

        if (p != null) {
            TextView tt1 = (TextView) v.findViewById(R.id.id);
            TextView tt2 = (TextView) v.findViewById(R.id.categoryId);
            TextView tt3 = (TextView) v.findViewById(R.id.description);

            if (tt1 != null) {
                tt1.setText(p.getId());
            }

            if (tt2 != null) {
                tt2.setText(p.getCategory().getId());
            }

            if (tt3 != null) {
                tt3.setText(p.getDescription());
            }
        }

        return v;
    }

}

This is a class I had used for my project. You need to have a collection of your items which you want to display, in my case it's <Item>. You need to override View getView(int position, View convertView, ViewGroup parent) method.

R.layout.itemlistrow defines the row of the ListView.

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content" android:orientation="vertical"
    android:layout_width="fill_parent">

    <TableRow android:layout_width="fill_parent"
              android:id="@+id/TableRow01"
              android:layout_height="wrap_content">

        <TextView android:textColor="#FFFFFF"
                  android:id="@+id/id"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:text="id" android:textStyle="bold" 
                  android:gravity="left"
                  android:layout_weight="1" 
                  android:typeface="monospace"
                  android:height="40sp" />
    </TableRow>

    <TableRow android:layout_height="wrap_content"
              android:layout_width="fill_parent">

        <TextView android:textColor="#FFFFFF" 
                  android:id="@+id/categoryId"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:text="categoryId" 
                  android:layout_weight="1" 
                  android:height="20sp" />

        <TextView android:layout_height="wrap_content"
                  android:layout_width="fill_parent" 
                  android:layout_weight="1"
                  android:textColor="#FFFFFF"
                  android:gravity="right"
                  android:id="@+id/description"
                  android:text="description" 
                  android:height="20sp" />
    </TableRow>

</TableLayout>

In the MainActivity define ListViewlike this,

ListView yourListView = (ListView) findViewById(R.id.itemListView);

// get data from the table by the ListAdapter
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, List<yourItem>);

yourListView .setAdapter(customAdapter);

How to remove listview all items

Remove the data from the adapter and call adapter.notifyDataSetChanged();

Showing empty view when ListView is empty

It should be like this:

<TextView android:id="@android:id/empty"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="No Results" />

Note the id attribute.

setOnItemClickListener on custom ListView

If it helps anyone, I found that the problem was I already had an android:onClick event in my layout file (which I inflated for the ListView rows). This was superseding the onItemClick event.

Android ListView with different layouts for each row

Since you know how many types of layout you would have - it's possible to use those methods.

getViewTypeCount() - this methods returns information how many types of rows do you have in your list

getItemViewType(int position) - returns information which layout type you should use based on position

Then you inflate layout only if it's null and determine type using getItemViewType.

Look at this tutorial for further information.

To achieve some optimizations in structure that you've described in comment I would suggest:

  • Storing views in object called ViewHolder. It would increase speed because you won't have to call findViewById() every time in getView method. See List14 in API demos.
  • Create one generic layout that will conform all combinations of properties and hide some elements if current position doesn't have it.

I hope that will help you. If you could provide some XML stub with your data structure and information how exactly you want to map it into row, I would be able to give you more precise advise. By pixel.

How to implement Android Pull-to-Refresh

To get the latest Lollipop Pull-To Refresh:

  1. Download the latest Lollipop SDK and Extras/Android support library
  2. Set Project's Build Target to Android 5.0 (otherwise support package can have errors with resources)
  3. Update your libs/android-support-v4.jar to 21st version
  4. Use android.support.v4.widget.SwipeRefreshLayout plus android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener

Detailed guide could be found here: http://antonioleiva.com/swiperefreshlayout/

Plus for ListView I recommend to read about canChildScrollUp() in the comments ;)

OnItemCLickListener not working in listview

you need to do 2 steps in your listview_item.xml

  1. set the root layout with: android:descendantFocusability="blocksDescendants"
  2. set any focusable or clickable view in this item with:
    android:clickable="false"
    android:focusable="false"
    android:focusableInTouchMode="false"

Here is an example: listview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:gravity="center_vertical"
    android:orientation="vertical"
    android:descendantFocusability="blocksDescendants">

    <RadioButton
        android:id="@+id/script_name_radio_btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textColor="#000"
        android:padding="5dp"
        android:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false"
        />

</LinearLayout>

Best way to update data with a RecyclerView adapter

DiffUtil can the best choice for updating the data in the RecyclerView Adapter which you can find in the android framework. DiffUtil is a utility class that can calculate the difference between two lists and output a list of update operations that converts the first list into the second one.

Most of the time our list changes completely and we set new list to RecyclerView Adapter. And we call notifyDataSetChanged to update adapter. NotifyDataSetChanged is costly. DiffUtil class solves that problem now. It does its job perfectly!

Android Recyclerview vs ListView with Viewholder

I used a ListView with Glide image loader, having memory growth. Then I replaced the ListView with a RecyclerView. It is not only more difficult in coding, but also leads to a more memory usage than a ListView. At least, in my project.

In another activity I used a complex list with EditText's. In some of them an input method may vary, also a TextWatcher can be applied. If I used a ViewHolder, how could I replace a TextWatcher during scrolling? So, I used a ListView without a ViewHolder, and it works.

How to lazy load images in ListView in Android

I just want to add one more good example, XML Adapters. As it's is used by Google and I am also using the same logic to avoid an OutOfMemory error.

Basically this ImageDownloader is your answer (as it covers most of your requirements). Some you can also implement in that.

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

ListView.FocusedItem.Index 

or you can use foreach loop like this

int index= -1;
foreach (ListViewItem itm in listView1.SelectedItems)
{
    if (itm.Selected)
    {
        index= itm.Index;
    }
}

Best way to make WPF ListView/GridView sort on column-header clicking?

It all depends really, if you're using the DataGrid from the WPF Toolkit then there is a built in sort, even a multi-column sort which is very useful. Check more out here:

Vincent Sibals Blog

Alternatively, if you're using a different control that doesn't support sorting, i'd recommend the following methods:

Li Gao's Custom Sorting

Followed by:

Li Gao's Faster Sorting

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

You can also use the iteration count (i) as the key:

render() {
    return (
      <ol>
        {this.props.results.map((result, i) => (
          <li key={i}>{result.text}</li>
        ))}
      </ol>
    );
}

notifyDataSetChange not working from custom adapter

I have the same problem, and i realize that. When we create adapter and set it to listview, listview will point to object somewhere in memory which adapter hold, data in this object will show in listview.

adapter = new CustomAdapter(data);
listview.setadapter(adapter);

if we create an object for adapter with another data again and notifydatasetchanged():

adapter = new CustomAdapter(anotherdata);
adapter.notifyDataSetChanged();

this will do not affect to data in listview because the list is pointing to different object, this object does not know anything about new object in adapter, and notifyDataSetChanged() affect nothing. So we should change data in object and avoid to create a new object again for adapter

Sorting A ListView By Column

You can use a manual sorting algorithm like this

public void ListItemSorter(object sender, ColumnClickEventArgs e)
    {
        ListView list = (ListView)sender;
        int total = list.Items.Count;
        list.BeginUpdate();
        ListViewItem[] items = new ListViewItem[total];
        for (int i = 0; i < total; i++)
        {
            int count = list.Items.Count;
            int minIdx = 0;
            for (int j = 1; j < count; j++)
                if (list.Items[j].SubItems[e.Column].Text.CompareTo(list.Items[minIdx].SubItems[e.Column].Text) < 0)
                    minIdx = j;
            items[i] = list.Items[minIdx];
            list.Items.RemoveAt(minIdx);
        }
        list.Items.AddRange(items);
        list.EndUpdate();
    }

this method uses selection sort in O^2 order and as Ascending. You can change the '>' with '<' for a descending or add an argument for this method. It sorts any column that is clicked and works perfect for small amount of data.

Android: How to detect double-tap?

Realization single and double click

public abstract class DoubleClickListener implements View.OnClickListener {

private static final long DOUBLE_CLICK_TIME_DELTA = 200;

private long lastClickTime = 0;

private View view;

private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
    @Override
    public void run() {
        onSingleClick(view);
    }
};

private void runTimer(){
    handler.removeCallbacks(runnable);
    handler.postDelayed(runnable,DOUBLE_CLICK_TIME_DELTA);
}

@Override
public void onClick(View view) {
    this.view = view;
    long clickTime = System.currentTimeMillis();
    if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA){
        handler.removeCallbacks(runnable);
        lastClickTime = 0;
        onDoubleClick(view);
    } else {
        runTimer();
        lastClickTime = clickTime;
    }
}

public abstract void onSingleClick(View v);
public abstract void onDoubleClick(View v);

}

android.content.res.Resources$NotFoundException: String resource ID #0x0

if you get the values in int you have to use string for that it is throwing the error

before

  holder.villageName.setText(villageModelList.get(position).getVillageName());
    holder.villageCount.setText(villageModelList.get(position).getPeopleCount());
    holder.peopleCount.setText(villageModelList.get(position).getPeopleCount());

after

  holder.villageName.setText(villageModelList.get(position).getVillageName());
    holder.villageCount.setText(String.valueOf(villageModelList.get(position).getPeopleCount()));
    holder.peopleCount.setText(String.valueOf(villageModelList.get(position).getPeopleCount()));

you can solve the error by adding the String.valueOf

List View Filter Android

Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..

lv = (ListView) findViewById(R.id.list_view);
    inputSearch = (EditText) findViewById(R.id.inputSearch);

// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name,    products);
lv.setAdapter(adapter);       
inputSearch.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text
        MainActivity.this.adapter.getFilter().filter(cs);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

    @Override
    public void afterTextChanged(Editable arg0) {}
});

The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.

EDIT

To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.

class CustomAdapter extends BaseAdapter implements Filterable {

    public View getView(){
    ...
    }
    public Integer getCount()
    {
    ...
    }

    @Override
    public Filter getFilter() {

        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                arrayListNames = (List<String>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<String> FilteredArrayNames = new ArrayList<String>();

                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                    String dataNames = mDatabaseOfNames.get(i);
                    if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                        FilteredArrayNames.add(dataNames);
                    }
                }

                results.count = FilteredArrayNames.size();
                results.values = FilteredArrayNames;
                Log.e("VALUES", results.values.toString());

                return results;
            }
        };

        return filter;
    }
}

Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.

Add Items to Columns in a WPF ListView

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/>

Then you can add columns and populate it in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Add columns
    var gridView = new GridView();
    this.listView.View = gridView;
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Id", DisplayMemberBinding = new Binding("Id") });
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Name", DisplayMemberBinding = new Binding("Name") });

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

And then just populate the list in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem
{
    public int Id { get; set; }

    public string Name { get; set; }
}

Android ListView with onClick items

You start new activities with intents. One method to send data to an intent is to pass a class that implements parcelable in the intent. Take note you are passing a copy of the class.

http://developer.android.com/reference/android/os/Parcelable.html

Here I have an onItemClick. I create intent and putExtra an entire class into the intent. The class I'm sending has implemented parcelable. Tip: You only need implement the parseable over what is minimally needed to re-create the class. Ie maybe a filename or something simple like a string something that a constructor can use to create the class. The new activity can later getExtras and it is essentially creating a copy of the class with its constructor method.

Here I launch the kmlreader class of my app when I recieve an onclick in the listview.

Note: below summary is a list of the class that I am passing so get(position) returns the class infact it is the same list that populates the listview

List<KmlSummary> summary = null;
...

public final static String EXTRA_KMLSUMMARY = "com.gosylvester.bestrides.util.KmlSummary";

...

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    lastshownitem = position;
    Intent intent = new Intent(context, KmlReader.class);
    intent.putExtra(ImageTextListViewActivity.EXTRA_KMLSUMMARY,
            summary.get(position));
    startActivity(intent);
}

later in the new activity I pull out the parseable class with

kmlSummary = intent.getExtras().getParcelable(
                ImageTextListViewActivity.EXTRA_KMLSUMMARY);

//note:
//KmlSummary implements parcelable.
//there is a constructor method for parcel in
// and a overridden writetoparcel method
// these are really easy to setup.

public KmlSummary(Parcel in) {
    this._id = in.readInt();
    this._description = in.readString();
    this._name = in.readString();
    this.set_bounds(in.readDouble(), in.readDouble(), in.readDouble(),
    in.readDouble());
    this._resrawid = in.readInt();
    this._resdrawableid = in.readInt();
     this._pathstring = in.readString();
    String s = in.readString();
    this.set_isThumbCreated(Boolean.parseBoolean(s));
}

@Override
public void writeToParcel(Parcel arg0, int arg1) {
    arg0.writeInt(this._id);
    arg0.writeString(this._description);
    arg0.writeString(this._name);
    arg0.writeDouble(this.get_bounds().southwest.latitude);
    arg0.writeDouble(this.get_bounds().southwest.longitude);
    arg0.writeDouble(this.get_bounds().northeast.latitude);
    arg0.writeDouble(this.get_bounds().northeast.longitude);
    arg0.writeInt(this._resrawid);
    arg0.writeInt(this._resdrawableid);
    arg0.writeString(this.get_pathstring());
    String s = Boolean.toString(this.isThumbCreated());
    arg0.writeString(s);
}

Good Luck Danny117

C# Clear all items in ListView

How about

DataSource = null;
DataBind();

How to display list items as columns?

You can do that using CSS3.

Here is the HTML code snippet:

_x000D_
_x000D_
<ul id="listitem_ascolun">_x000D_
 <li>1</li>_x000D_
 <li>2</li>_x000D_
 <li>3</li>_x000D_
 <li>4</li>    _x000D_
 <li>5</li>_x000D_
 <li>6</li>_x000D_
 <li>7</li>_x000D_
 <li>8</li>_x000D_
 <li>9</li>_x000D_
 <li>10</li>_x000D_
 <li>11</li>_x000D_
 <li>12</li>    _x000D_
</ul>
_x000D_
_x000D_
_x000D_

& Here is the CSS3 code snippet :

_x000D_
_x000D_
#listitem_ascolun ul{margin:0;padding:0;list-style:none;}_x000D_
_x000D_
#listitem_ascolun {_x000D_
    height: 500px;  _x000D_
    column-count: 4;_x000D_
 -webkit-column-count: 4;_x000D_
 -moz-column-count: 4;_x000D_
}_x000D_
_x000D_
#listitem_ascolun li {_x000D_
    display: inline-block;_x000D_
}
_x000D_
_x000D_
_x000D_

How to add a ListView to a Column in Flutter?

Try using Slivers:

Container(
    child: CustomScrollView(
      slivers: <Widget>[
        SliverList(
          delegate: SliverChildListDelegate(
            [
              HeaderWidget("Header 1"),
              HeaderWidget("Header 2"),
              HeaderWidget("Header 3"),
              HeaderWidget("Header 4"),
            ],
          ),
        ),
        SliverList(
          delegate: SliverChildListDelegate(
            [
              BodyWidget(Colors.blue),
              BodyWidget(Colors.red),
              BodyWidget(Colors.green),
              BodyWidget(Colors.orange),
              BodyWidget(Colors.blue),
              BodyWidget(Colors.red),
            ],
          ),
        ),
        SliverGrid(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
          delegate: SliverChildListDelegate(
            [
              BodyWidget(Colors.blue),
              BodyWidget(Colors.green),
              BodyWidget(Colors.yellow),
              BodyWidget(Colors.orange),
              BodyWidget(Colors.blue),
              BodyWidget(Colors.red),
            ],
          ),
        ),
      ],
    ),
  ),
)

Add item to Listview control

  • Very Simple

    private void button1_Click(object sender, EventArgs e)
    {
        ListViewItem item = new ListViewItem();
        item.SubItems.Add(textBox2.Text);
        item.SubItems.Add(textBox3.Text);
        item.SubItems.Add(textBox4.Text);
        listView1.Items.Add(item);
        textBox2.Clear();
        textBox3.Clear();
        textBox4.Clear();
    }
    
  • You can also Do this stuff...

        ListViewItem item = new ListViewItem();
        item.SubItems.Add("Santosh");
        item.SubItems.Add("26");
        item.SubItems.Add("India");
    

ListView inside ScrollView is not scrolling on Android

Its a bad practice to have two different scrolling views together. ListView itself has its own scrolling functionality and height is auto adjusted according to Adapter settings for your row items (Keelping in mind, we are not setting specific height to ListView in our Layout xml). However in your case, you can replace ListView with a class and this will adjust height for your ListView keeping in mind that your ListView is inside ScrollView.

This will help you:

public class ExpandableHeightListview extends ListView
{

    boolean expanded = false;

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

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

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

    public boolean isExpanded()
    {
        return expanded;
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        // HACK! TAKE THAT ANDROID!
        if (isExpanded())
        {
            // Calculate entire height by providing a very large height hint.
            // But do not use the highest 2 bits of this integer; those are
            // reserved for the MeasureSpec mode.
            int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);

            ViewGroup.LayoutParams params = getLayoutParams();
            params.height = getMeasuredHeight();
        }
        else
        {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    public void setExpanded(boolean expanded)
    {
        this.expanded = expanded;
    }
}

Now extend your ListView with this class, just change your ListView tag from your resource xml to smothing like this,

<yourpackagename.ExpandableHeightListview
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/White"
            android:scrollbars="none"
            android:orientation="vertical"
            android:fadingEdge="none">
            </cyourpackagename.ExpandableHeightListview>

This will solve your scrolling problem of ListView, as now the parent scrolling is managed by ScrollView rather then ListView.

android listview item height

  android:textAppearance="?android:attr/textAppearanceLarge" 

seemed no effect.

  android:minHeight="?android:attr/listPreferredItemHeight" 

changed the height for me

How to Animate Addition or Removal of Android ListView Rows

Have you considered animating a sweep to the right? You could do something like drawing a progressively larger white bar across the top of the list item, then removing it from the list. The other cells would still jerk into place, but it'd better than nothing.

How to get the bluetooth devices as a list?

I tried the below code,

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<TextView 
    android:id="@+id/bluetoothstate" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
<Button
    android:id="@+id/listpaireddevices" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:text="List Paired Devices" 
    android:enabled="false"
    /> 
<TextView
    android:id="@+id/bluetoothstate" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />

ListPairedDevicesActivity.java

import java.util.Set;

import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListPairedDevicesActivity extends ListActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);

  ArrayAdapter<String> btArrayAdapter 
    = new ArrayAdapter<String>(this,
             android.R.layout.simple_list_item_1);

  BluetoothAdapter bluetoothAdapter 
   = BluetoothAdapter.getDefaultAdapter();
  Set<BluetoothDevice> pairedDevices 
   = bluetoothAdapter.getBondedDevices();

  if (pairedDevices.size() > 0) {
      for (BluetoothDevice device : pairedDevices) {
       String deviceBTName = device.getName();
       String deviceBTMajorClass 
        = getBTMajorDeviceClass(device
          .getBluetoothClass()
          .getMajorDeviceClass());
       btArrayAdapter.add(deviceBTName + "\n" 
         + deviceBTMajorClass);
      }
  }
  setListAdapter(btArrayAdapter);

 }

 private String getBTMajorDeviceClass(int major){
  switch(major){ 
  case BluetoothClass.Device.Major.AUDIO_VIDEO:
   return "AUDIO_VIDEO";
  case BluetoothClass.Device.Major.COMPUTER:
   return "COMPUTER";
  case BluetoothClass.Device.Major.HEALTH:
   return "HEALTH";
  case BluetoothClass.Device.Major.IMAGING:
   return "IMAGING"; 
  case BluetoothClass.Device.Major.MISC:
   return "MISC";
  case BluetoothClass.Device.Major.NETWORKING:
   return "NETWORKING"; 
  case BluetoothClass.Device.Major.PERIPHERAL:
   return "PERIPHERAL";
  case BluetoothClass.Device.Major.PHONE:
   return "PHONE";
  case BluetoothClass.Device.Major.TOY:
   return "TOY";
  case BluetoothClass.Device.Major.UNCATEGORIZED:
   return "UNCATEGORIZED";
  case BluetoothClass.Device.Major.WEARABLE:
   return "AUDIO_VIDEO";
  default: return "unknown!";
  }
 }

 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
  // TODO Auto-generated method stub
  super.onListItemClick(l, v, position, id);

     Intent intent = new Intent();
     setResult(RESULT_OK, intent);
     finish();
 }

}

AndroidBluetooth.java

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AndroidBluetooth extends Activity {

 private static final int REQUEST_ENABLE_BT = 1;
 private static final int REQUEST_PAIRED_DEVICE = 2;

    /** Called when the activity is first created. */
 Button btnListPairedDevices;
 TextView stateBluetooth;
 BluetoothAdapter bluetoothAdapter;

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

        btnListPairedDevices = (Button)findViewById(R.id.listpaireddevices);

        stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        CheckBlueToothState();

        btnListPairedDevices.setOnClickListener(btnListPairedDevicesOnClickListener);
    }

    private void CheckBlueToothState(){
     if (bluetoothAdapter == null){
         stateBluetooth.setText("Bluetooth NOT support");
        }else{
         if (bluetoothAdapter.isEnabled()){
          if(bluetoothAdapter.isDiscovering()){
           stateBluetooth.setText("Bluetooth is currently in device discovery process.");
          }else{
           stateBluetooth.setText("Bluetooth is Enabled.");
           btnListPairedDevices.setEnabled(true);
          }
         }else{
          stateBluetooth.setText("Bluetooth is NOT Enabled!");
          Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
             startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
         }
        }
    }

    private Button.OnClickListener btnListPairedDevicesOnClickListener
    = new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   Intent intent = new Intent();
   intent.setClass(AndroidBluetooth.this, ListPairedDevicesActivity.class);
   startActivityForResult(intent, REQUEST_PAIRED_DEVICE); 
  }};

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  if(requestCode == REQUEST_ENABLE_BT){
   CheckBlueToothState();
  }if (requestCode == REQUEST_PAIRED_DEVICE){
   if(resultCode == RESULT_OK){

   }
  } 
 }   
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test.AndroidBluetooth"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidBluetooth"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
  <activity android:name=".ListPairedDevicesActivity" 
      android:label="AndroidBluetooth: List of Paired Devices"/>
    </application>
</manifest>

How to customize listview using baseadapter

I suggest using a custom Adapter, first create a Xml-file, for example layout/customlistview.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" >
    <ImageView
        android:id="@+id/image"
        android:layout_alignParentRight="true"
        android:paddingRight="4dp" />
    <TextView
        android:id="@+id/title"
        android:layout_toLeftOf="@id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="23sp"
        android:maxLines="1" />
    <TextView
        android:id="@+id/subtitle"
        android:layout_toLeftOf="@id/image" android:layout_below="@id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" /> 
</RelativeLayout>

Assuming you have a custom class like this

public class CustomClass {

    private long id;
    private String title, subtitle, picture;

    public CustomClass () {
    }

    public CustomClass (long id, String title, String subtitle, String picture) {
        this.id = id;
        this.title= title;
        this.subtitle= subtitle;
        this.picture= picture;
    }
    //add getters and setters
}

And a CustomAdapter.java uses the xml-layout

public class CustomAdapter extends ArrayAdapter {

private Context context;
private int resource;
private LayoutInflater inflater;

public CustomAdapter (Context context, List<CustomClass> values) { // or String[][] or whatever

    super(context, R.layout.customlistviewitem, values);

    this.context = context;
    this.resource = R.layout.customlistview;
    this.inflater = LayoutInflater.from(context);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    convertView = (RelativeLayout) inflater.inflate(resource, null);

    CustomClass item = (CustomClass) getItem(position);

    TextView textviewTitle = (TextView) convertView.findViewById(R.id.title);
    TextView textviewSubtitle = (TextView) convertView.findViewById(R.id.subtitle);
    ImageView imageview = (ImageView) convertView.findViewById(R.id.image);

    //fill the textviews and imageview with the values
    textviewTitle = item.getTtile();
    textviewSubtitle = item.getSubtitle();

    if (item.getAfbeelding() != null) {
        int imageResource = context.getResources().getIdentifier("drawable/" + item.getImage(), null, context.getPackageName());
        Drawable image = context.getResources().getDrawable(imageResource);
    }
    imageview.setImageDrawable(image);

    return convertView;
    }
}

Did you manage to do it? Feel free to ask if you want more info on something :)

EDIT: Changed the adapter to suit a List instead of just a List

Recyclerview and handling different type of row inflation

You can use this library:
https://github.com/kmfish/MultiTypeListViewAdapter (written by me)

  • Better reuse the code of one cell
  • Better expansion
  • Better decoupling

Setup adapter:

adapter = new BaseRecyclerAdapter();
adapter.registerDataAndItem(TextModel.class, LineListItem1.class);
adapter.registerDataAndItem(ImageModel.class, LineListItem2.class);
adapter.registerDataAndItem(AbsModel.class, AbsLineItem.class);

For each line item:

public class LineListItem1 extends BaseListItem<TextModel, LineListItem1.OnItem1ClickListener> {

    TextView tvName;
    TextView tvDesc;


    @Override
    public int onGetLayoutRes() {
        return R.layout.list_item1;
    }

    @Override
    public void bindViews(View convertView) {
        Log.d("item1", "bindViews:" + convertView);
        tvName = (TextView) convertView.findViewById(R.id.text_name);
        tvDesc = (TextView) convertView.findViewById(R.id.text_desc);

        tvName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != attachInfo) {
                    attachInfo.onNameClick(getData());
                }
            }
        });
        tvDesc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != attachInfo) {
                    attachInfo.onDescClick(getData());
                }
            }
        });

    }

    @Override
    public void updateView(TextModel model, int pos) {
        if (null != model) {
            Log.d("item1", "updateView model:" + model + "pos:" + pos);
            tvName.setText(model.getName());
            tvDesc.setText(model.getDesc());
        }
    }

    public interface OnItem1ClickListener {
        void onNameClick(TextModel model);
        void onDescClick(TextModel model);
    }
}

Creating columns in listView and add items

I didn't see anyone answer this correctly. So I'm posting it here. In order to get columns to show up you need to specify the following line.

lvRegAnimals.View = View.Details;

And then add your columns after that.

lvRegAnimals.Columns.Add("Id", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);

Hope this helps anyone else looking for this answer in the future.

Create listview in fragment android

Please use ListFragment. Otherwise, it won't work.

EDIT 1: Then you'll only need setListAdapter() and getListView().

android listview get selected item

final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

      }                 
});

I hope this fixes your problem.

Get clicked item and its position in RecyclerView

Use getLayoutPosition() in your custom interface java method. This will return the selected position of an item, check full detail on

https://becody.com/get-clicked-item-and-its-position-in-recyclerview/

How do you dynamically add elements to a ListView on Android?

        This is the simple answer how to add datas dynamically in listview android kotlin


class MainActivity : AppCompatActivity(){
        
            var listItems = arrayListOf<String>()
            val array = arrayOf("a","b","c","d","e")
            var listView: ListView? = null
    
            private lateinit var adapter: listViewAdapter
        
            override fun onCreate(savedInstanceState: Bundle?) {
                super.onCreate(savedInstanceState)
                setContentView(R.layout.scrollview_layout)
        
                listItems.add("a")
                listItems.add("b")
                listItems.add("c")
                listItems.add("d")
                listItems.add("e")
        
                //if you want to add array items to a list you can try this for each loop
                for(items in array)
                    listItems.add(items)
                
                //check the result in console
                Log.e("TAG","listItems array: $listItems")
    
            adapter = ListViewAdapter()
            adapter.updateList(listItems)
            adapter.notifyDataSetChanged()
        
            }
        }


//Here is the adapter class
    class ListviewAdapter : BaseAdapter(){
    
    private var itemsList = arrayListOf<String>()
    
    override fun getView(position: Int, container: View?, parent: ViewGroup?): View {
            var view  = container
            val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            if (view == null)
                view = inflater.inflate(R.layout.list_pc_summary, parent, false)
    
    return view
    }
    
    override fun getItem(position: Int): Any  = itemsList[position]
    
    override fun getItemId(position: Int): Long = position.toLong()
    
    override fun getCount(): Int = itemsList.size
    
    fun updateList(listItems: ArrayList<String>()){
        this.itemsList = listItems
        notifyDatSetChanged
    
    }
   
        }
       
    //Here I just explained two ways, we can do this many ways.

Horizontal ListView in Android?

For my application, I use a HorizontalScrollView containing LinearLayout inside, which has orientation set to horizontal. In order to add images inside, I create ImageViews inside the activity and add them to my LinearLayout. For example:

<HorizontalScrollView 
        android:id="@+id/photo_scroll"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:scrollbars="horizontal"
        android:visibility="gone">

        <LinearLayout 
            android:id="@+id/imageview_holder"
            android:layout_width="wrap_content"
            android:orientation="horizontal"
            android:layout_height="match_parent">

        </LinearLayout>
    </HorizontalScrollView>

An this works perfectly fine for me. In the activity all I have to do is something like the code below:

LinearLayout imgViewHolder = findViewById(R.id.imageview_holder);
ImageView img1 = new ImageView(getApplicationContext());
//set bitmap
//set img1 layout params
imgViewHolder.add(img1);
ImageView img2 = new ImageView(getApplicationContext());
//set bitmap
//set img2 layout params
imgViewHolder.add(img2); 

As I said that works for me, and I hope it helps somebody looking to achieve this as well.

Android ListView with Checkbox and all clickable

Set the listview adapter to "simple_list_item_multiple_choice"

ArrayAdapter<String> adapter;

List<String> values; // put values in this

//Put in listview
adapter = new ArrayAdapter<UserProfile>(
this,
android.R.layout.simple_list_item_multiple_choice, 
values);
setListAdapter(adapter);    

How do I remove lines between ListViews on Android?

Or in XML:

android:divider="@drawable/list_item_divider"
android:dividerHeight="1dp"

You can use a color for the drawable (e.g. #ff112233), but be aware, that pre-cupcake releases have a bug in which the color cannot be set. Instead a 9-patch or a image must be used..

Add Items to ListView - Android

public OnClickListener moreListener = new OnClickListener() {

    @Override
      public void onClick(View v) {
          adapter.add("aaaa")
      }
}

Listview Scroll to the end of the list after updating the list

You need to use these parameters in your list view:

  • Scroll lv.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);

  • Set the head of the list to it bottom lv.setStackFromBottom(true);

You can also set these parameters in XML, eg. like this:

<ListView
   ...
   android:transcriptMode="alwaysScroll"
   android:stackFromBottom="true" />

How to change text color of simple list item

try this code...

<RelativeLayout 
         xmlns:android="http://schemas.android.com/apk/res/android" 
         android:layout_width="fill_parent" 
         android:layout_height="fill_parent" 
         android:background="#ffff00"> 

    <ListView 
            android:id="@+id/android:list" 
            android:layout_marginTop="2px" 
            android:layout_marginLeft="2px" 
            android:layout_marginRight="2px"
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:layout_weight="1" 
            android:background="@drawable/shape_1" 
            android:listSelector="@drawable/shape_3" 
            android:textColor="#ffff00" 
            android:layout_marginBottom="44px" /> 
</RelativeLayout>

How to show an empty view with a RecyclerView?

On your adapter's getItemViewType check if the adapter has 0 elements and return a different viewType if so.

Then on your onCreateViewHolder check if the viewType is the one you returned earlier and inflate a diferent view. In this case a layout file with that TextView

EDIT

If this is still not working then you might want to set the size of the view programatically like this:

Point size = new Point();
((WindowManager)itemView.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(size);

And then when you inflate your view call:

inflatedView.getLayoutParams().height = size.y;
inflatedView.getLayoutParams().width = size.x;

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

I'm was facing the same problem with exactly the same error log. In my case onProgress() of the AsyncTask adds the values to the adapter using mAdapter.add(newEntry). To avoid the UI becoming less responsive I set mAdapter.setNotifyOnChange(false) and call mAdapter.notifyDataSetChanged() 4 times the second. Once per second the array is sorted.

This work well and looks very addictive, but unfortunately it is possible to crash it by touching the shown list items often enough.

But it seems I have found an acceptable workaround. My guess it that even if you just work on the ui thread the adapter does not accept many changes to it's data without calling notifyDataSetChanged(), because of this I created a queue that is storing all the new items until the mentioned 300ms are over. If this moment is reached I add all the stored items in one shot and call notifyDataSetChanged(). Until now I was not able to crash the list anymore.

Adding an onclicklistener to listview (android)

If your Activity extends ListActivity, you can simply override the OnListItemClick() method like so:

/** {@inheritDoc} */
@Override  
protected void onListItemClick(ListView l, View v, int pos, long id) {  
    super.onListItemClick(l, v, pos, id);

    // TODO : Logic
}  

How to Get a Layout Inflater Given a Context?

You can also use this code to get LayoutInflater:

LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)

How to implement endless list with RecyclerView?

I achieved an infinite scrolling type implementation using this logic in the onBindViewHolder method of my RecyclerView.Adapter class.

    if (position == mItems.size() - 1 && mCurrentPage <= mTotalPageCount) {
        if (mCurrentPage == mTotalPageCount) {
            mLoadImagesListener.noMorePages();
        } else {
            int newPage = mCurrentPage + 1;
            mLoadImagesListener.loadPage(newPage);
        }
    }

With this code when the RecyclerView gets to the last item, it increments the current page and callbacks on an interface which is responsible for loading more data from the api and adding the new results to the adapter.

I can post more complete example if this isn't clear?

Clear listview content?

Just put the code ListView.Items.Clear(); on your method

C# listView, how do I add items to columns 2, 3 and 4 etc?

You can add items / sub-items to the ListView like:

ListViewItem item = new ListViewItem(new []{"1","2","3","4"});
listView1.Items.Add(item);

But I suspect your problem is with the View Type. Set it in the designer to Details or do the following in code:

listView1.View = View.Details;

WPF ListView - detect when selected item is clicked

This worked for me.

Single-clicking a row triggers the code-behind.

XAML:

<ListView x:Name="MyListView" MouseLeftButtonUp="MyListView_MouseLeftButtonUp">
    <GridView>
        <!-- Declare GridViewColumns. -->
    </GridView>
</ListView.View>

Code-behind:

private void MyListView_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    System.Windows.Controls.ListView list = (System.Windows.Controls.ListView)sender;
    MyClass selectedObject = (MyClass)list.SelectedItem;
    // Do stuff with the selectedObject.
}

Android ListView Divider

Folks, here's why you should use 1px instead of 1dp or 1dip: if you specify 1dp or 1dip, Android will scale that down. On a 120dpi device, that becomes something like 0.75px translated, which rounds to 0. On some devices, that translates to 2-3 pixels, and it usually looks ugly or sloppy

For dividers, 1px is the correct height if you want a 1 pixel divider and is one of the exceptions for the "everything should be dip" rule. It'll be 1 pixel on all screens. Plus, 1px usually looks better on hdpi and above screens

"It's not 2012 anymore" edit: you may have to switch over to dp/dip starting at a certain screen density

update listview dynamically with adapter

I created a method just for that. I use it any time I need to manually update a ListView. Hopefully this gives you an idea of how to implement your own

public static void UpdateListView(List<SomeObject> SomeObjects, ListView ListVw)
{    
    if(ListVw != null)
    {
        final YourAdapter adapter = (YourAdapter) ListVw.getAdapter();

        //You'll have to create this method in your adapter class. It's a simple setter.
        adapter.SetList(SomeObjects);

        adapter.notifyDataSetChanged();
    }
}

I'm using an adapter that inherites from BaseAdapter. Should work for any other type of adapter.

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

How to scroll to top of long ScrollView layout?

Had the same issue, probably some kind of bug.

Even the fullScroll(ScrollView.FOCUS_UP) from the other answer didn't work.
Only thing that worked for me was calling scroll_view.smoothScrollTo(0,0) right after the dialog is shown.

ArrayAdapter in android to create simple listview

ArrayAdapter uses a TextView to display each item within it. Behind the scenes, it uses the toString() method of each object that it holds and displays this within the TextView. ArrayAdapter has a number of constructors that can be used and the one that you have used in your example is:

ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)

By default, ArrayAdapter uses the default TextView to display each item. But if you want, you could create your own TextView and implement any complex design you'd like by extending the TextView class. This would then have to go into the layout for your use. You could reference this in the textViewResourceId field to bind the objects to this view instead of the default.

For your use, I would suggest that you use the constructor:

ArrayAdapter(Context context, int resource, T[] objects). 

In your case, this would be:

ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values)

and it should be fine. This will bind each string to the default TextView display - plain and simple white background.

So to answer your question, you do not have to use the textViewResourceId.

Android: ListView elements with multiple clickable buttons

Isn't the platform solution for this implementation to use a context menu that shows on a long press?

Is the question author aware of context menus? Stacking up buttons in a listview has performance implications, will clutter your UI and violate the recommended UI design for the platform.

On the flipside; context menus - by nature of not having a passive representation - are not obvious to the end user. Consider documenting the behaviour?

This guide should give you a good start.

http://www.mikeplate.com/2010/01/21/show-a-context-menu-for-long-clicks-in-an-android-listview/

How can I make a horizontal ListView in Android?

After reading this post, I have implemented my own horizontal ListView. You can find it here: http://dev-smart.com/horizontal-listview/ Let me know if this helps.

Android ListView Text Color

I needed to make a ListView with items of different colors. I modified Shardul's method a bit and result in this:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_list_item_1, colorString) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                TextView textView = (TextView) super.getView(position, convertView, parent);
                textView.setBackgroundColor(assignBackgroundColor(position));
                textView.setTextColor(assignTextColor(position));
                return textView;
            }
        };
        colorList.setAdapter(adapter);

assignBackgroundColor() and assignTextColor() are methods that assign color you want. They can be replaced with int[] arrays.

Android ListView headers

You probably are looking for an ExpandableListView which has headers (groups) to separate items (childs).

Nice tutorial on the subject: here.

Android: how to refresh ListView contents?

Another easy way:

//In your ListViewActivity:
public void refreshListView() {
    listAdapter = new ListAdapter(this);
    setListAdapter(listAdapter);
}

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

Change

 mAdapter = new RecordingsListAdapter(this, recordings);

to

 mAdapter = new RecordingsListAdapter(getActivity(), recordings);

and also make sure that recordings!=null at mAdapter = new RecordingsListAdapter(this, recordings);

How to autosize and right-align GridViewColumn data in WPF?

I liked user1333423's solution except that it always re-sized every column; i needed to allow some columns to be fixed width. So in this version columns with a width set to "Auto" will be auto-sized and those set to a fixed amount will not be auto-sized.

public class AutoSizedGridView : GridView
{
    HashSet<int> _autoWidthColumns;

    protected override void PrepareItem(ListViewItem item)
    {
        if (_autoWidthColumns == null)
        {
            _autoWidthColumns = new HashSet<int>();

            foreach (var column in Columns)
            {
                if(double.IsNaN(column.Width))
                    _autoWidthColumns.Add(column.GetHashCode());
            }                
        }

        foreach (GridViewColumn column in Columns)
        {
            if (_autoWidthColumns.Contains(column.GetHashCode()))
            {
                if (double.IsNaN(column.Width))
                    column.Width = column.ActualWidth;

                column.Width = double.NaN;                    
            }          
        }

        base.PrepareItem(item);
    }        
}

Get Selected Item Using Checkbox in Listview

It's a simplifications but very easy... You need to add the the focusable flag to the checkbox, as written before. You need also to add the clickable flag, as shown here:

android:focusable="false"
android:clickable="false"

Than you control the checkbox state from within the ListView (ListFragment in my case) onListItemClick event.

This the sample onListItemClick method:

public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//Get related checkbox and change flag status..
CheckBox cb = (CheckBox)v.findViewById(R.id.rowDone);
cb.setChecked(!cb.isChecked());
Toast.makeText(getActivity(), "Click item", Toast.LENGTH_SHORT).show();
}

WPF ListView turn off selection

Here's the default template for ListViewItem from Blend:

Default ListViewItem Template:

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListViewItem}">
                    <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="true">
                            <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
                        </Trigger>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="IsSelected" Value="true"/>
                                <Condition Property="Selector.IsSelectionActive" Value="false"/>
                            </MultiTrigger.Conditions>
                            <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.InactiveSelectionHighlightBrushKey}}"/>
                            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}}"/>
                        </MultiTrigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

Just remove the IsSelected Trigger and IsSelected/IsSelectionActive MultiTrigger, by adding the below code to your Style to replace the default template, and there will be no visual change when selected.

Solution to turn off the IsSelected property's visual changes:

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListViewItem}">
                <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
                    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

C#: How do you edit items and subitems in a listview?

I use a hidden textbox to edit all the listview items/subitems. The only problem is that the textbox needs to disappear as soon as any event takes place outside the textbox and the listview doesn't trigger the scroll event so if you scroll the listview the textbox will still be visible. To bypass this problem I created the Scroll event with this overrided listview.

Here is my code, I constantly reuse it so it might be help for someone:

ListViewItem.ListViewSubItem SelectedLSI;
private void listView2_MouseUp(object sender, MouseEventArgs e)
{
    ListViewHitTestInfo i = listView2.HitTest(e.X, e.Y);
    SelectedLSI = i.SubItem;
    if (SelectedLSI == null)
        return;

    int border = 0;
    switch (listView2.BorderStyle)
    {
        case BorderStyle.FixedSingle:
            border = 1;
            break;
        case BorderStyle.Fixed3D:
            border = 2;
            break;
    }

    int CellWidth = SelectedLSI.Bounds.Width;
    int CellHeight = SelectedLSI.Bounds.Height;
    int CellLeft = border + listView2.Left + i.SubItem.Bounds.Left;
    int CellTop =listView2.Top + i.SubItem.Bounds.Top;
    // First Column
    if (i.SubItem == i.Item.SubItems[0])
        CellWidth = listView2.Columns[0].Width;

    TxtEdit.Location = new Point(CellLeft, CellTop);
    TxtEdit.Size = new Size(CellWidth, CellHeight);
    TxtEdit.Visible = true;
    TxtEdit.BringToFront();
    TxtEdit.Text = i.SubItem.Text;
    TxtEdit.Select();
    TxtEdit.SelectAll();
}
private void listView2_MouseDown(object sender, MouseEventArgs e)
{
    HideTextEditor();
}
private void listView2_Scroll(object sender, EventArgs e)
{
    HideTextEditor();
}
private void TxtEdit_Leave(object sender, EventArgs e)
{
    HideTextEditor();
}
private void TxtEdit_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
        HideTextEditor();
}
private void HideTextEditor()
{
    TxtEdit.Visible = false;
    if (SelectedLSI != null)
        SelectedLSI.Text = TxtEdit.Text;
    SelectedLSI = null;
    TxtEdit.Text = "";
}

Android List View Drag and Drop sort

I have been working on this for some time now. Tough to get right, and I don't claim I do, but I'm happy with it so far. My code and several demos can be found at

Its use is very similar to the TouchInterceptor (on which the code is based), although significant implementation changes have been made.

DragSortListView has smooth and predictable scrolling while dragging and shuffling items. Item shuffles are much more consistent with the position of the dragging/floating item. Heterogeneous-height list items are supported. Drag-scrolling is customizable (I demonstrate rapid drag scrolling through a long list---not that an application comes to mind). Headers/Footers are respected. etc.?? Take a look.

Changing background color of ListView items on Android

Did you mean to change the background color of the custom listitems when you click on it?

If so:

You just add the following code to your listview layout in xml.


android:drawSelectorOnTop="true" android:listSelector="@android:drawable/list_selector_background"


The list selector here uses default selector which has a dark grey color. You can make your own drawable and assign it to the list selector as above.

Hope this is what you wanted.

Android draw a Horizontal line between views

If you does not want to use an extra view just for underlines. Add this style on your textView.

style="?android:listSeparatorTextViewStyle"

Just down side is it will add extra properties like

android:textStyle="bold"
android:textAllCaps="true"

which you can easily override.

Android ListView in fragment example

Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment will return a ListView you can then populate.

ListView with OnItemClickListener

Though a very old question, but I am still posting an answer to it so that it may help some one. If you are using any layout inside the list view then use ...

android:descendantFocusability="blocksDescendants"    

... on the first parent layout inside the list. This works as magic the click will not be consumed by any element inside the list but will directly go to the list item.

How to get the selected item from ListView?

MyClass selItem = (MyClass) myList.getSelectedItem(); //

You never instantiated your class.

Xamarin.Forms ListView: Set the highlight color of a tapped item

Only for Android

Add in your custom theme

<item name="android:colorActivatedHighlight">@android:color/transparent</item>

Android Endless List

I've been working in another solution very similar to that, but, I am using a footerView to give the possibility to the user download more elements clicking the footerView, I am using a "menu" which is shown above the ListView and in the bottom of the parent view, this "menu" hides the bottom of the ListView, so, when the listView is scrolling the menu disappear and when scroll state is idle, the menu appear again, but when the user scrolls to the end of the listView, I "ask" to know if the footerView is shown in that case, the menu doesn't appear and the user can see the footerView to load more content. Here the code:

Regards.

listView.setOnScrollListener(new OnScrollListener() {

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // TODO Auto-generated method stub
        if(scrollState == SCROLL_STATE_IDLE) {
            if(footerView.isShown()) {
                bottomView.setVisibility(LinearLayout.INVISIBLE);
            } else {
                bottomView.setVisibility(LinearLayout.VISIBLE);
            } else {
                bottomView.setVisibility(LinearLayout.INVISIBLE);
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {

    }
});

Android : How to set onClick event for Button in List item of ListView

Try This,

public View getView(final int position, View convertView,ViewGroup parent) 
{
   if(convertView == null)
   {
        LayoutInflater inflater = getLayoutInflater();
        convertView  = (LinearLayout)inflater.inflate(R.layout.YOUR_LAYOUT, null);
   }

   Button Button1= (Button)  convertView  .findViewById(R.id.BUTTON1_ID);

   Button1.setOnClickListener(new OnClickListener() 
   { 
       @Override
       public void onClick(View v) 
       {
           // Your code that you want to execute on this button click
       }

   });


   return convertView ;
}

It may help you....

How to select an item in a ListView programmatically?

ListViewItem.IsSelected = true;
ListViewItem.Focus();

C# ListView Column Width Auto

I believe the author was looking for an equivalent method via the IDE that would generate the code behind and make sure all parameters were in place, etc. Found this from MS:

Creating Event Handlers on the Windows Forms Designer

Coming from a VB background myself, this is what I was looking for, here is the brief version for the click adverse:

  1. Click the form or control that you want to create an event handler for.
  2. In the Properties window, click the Events button
  3. In the list of available events, click the event that you want to create an event handler for.
  4. In the box to the right of the event name, type the name of the handler and press ENTER

How to change color of ListView items on focus and on click

The child views in your list row should be considered selected whenever the parent row is selected, so you should be able to just set a normal state drawable/color-list on the views you want to change, no messy Java code necessary. See this SO post.

Specifically, you'd set the textColor of your textViews to an XML resource like this one:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@color/black" /> <!-- focused -->
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@color/black" /> <!-- focused and pressed-->
    <item android:state_pressed="true" android:drawable="@color/green" /> <!-- pressed -->
    <item android:drawable="@color/black" /> <!-- default -->
</selector> 

How to display a list of images in a ListView in Android?

File name should match the layout id which in this example is : items_list_item.xml in the layout folder of your application

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >  

<ImageView android:id="@+id/R.id.list_item_image"
  android:layout_width="100dip"
  android:layout_height="wrap_content" />  
</LinearLayout>

How to change color and font on ListView

You can select a child like

TextView tv = (TextView)lv.getChildAt(0);
tv.setTextColor(Color.RED);
tv.setTextSize(12);    

How to handle the click event in Listview in android?

Error is coming in your code from this statement as you said

Intent intent = new Intent(context, SendMessage.class);

This is due to you are providing context of OnItemClickListener anonymous class into the Intent constructor but according to constructor of Intent

android.content.Intent.Intent(Context packageContext, Class<?> cls)

You have to provide context of you activity in which you are using intent that is the MainActivity class context. so your statement which is giving error will be converted to

Intent intent = new Intent(MainActivity.this, SendMessage.class);

Also for sending your message from this MainActivity to SendMessage class please see below code

lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                ListEntry entry= (ListEntry) parent.getAdapter().getItem(position);
                Intent intent = new Intent(MainActivity.this, SendMessage.class);
                intent.putExtra(EXTRA_MESSAGE, entry.getMessage());
                startActivity(intent);
            }
        });

Please let me know if this helps you

EDIT:- If you are finding some issue to get the value of list do one thing declear your array list

ArrayList<ListEntry> members = new ArrayList<ListEntry>();

globally i.e. before oncreate and change your listener as below

 lv.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {
                    Intent intent = new Intent(MainActivity.this, SendMessage.class);
                    intent.putExtra(EXTRA_MESSAGE, members.get(position));
                    startActivity(intent);
                }
            });

So your whole code will look as

public class MainActivity extends Activity {
    public final static String EXTRA_MESSAGE = "com.example.ListViewTest.MESSAGE";
ArrayList<ListEntry> members = new ArrayList<ListEntry>();

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

        members.add(new ListEntry("BBB","AAA",R.drawable.tab1_hdpi));
        members.add(new ListEntry("ccc","ddd",R.drawable.tab2_hdpi));
        members.add(new ListEntry("assa","cxv",R.drawable.tab3_hdpi));
        members.add(new ListEntry("BcxsadvBB","AcxdxvAA"));
        members.add(new ListEntry("BcxvadsBB","AcxzvAA"));
        members.add(new ListEntry("BcxvBB","AcxvAA"));
        members.add(new ListEntry("BvBB","AcxsvAA"));
        members.add(new ListEntry("BcxvBB","AcxsvzAA"));
        members.add(new ListEntry("Bcxadv","AcsxvAA"));
        members.add(new ListEntry("BcxcxB","AcxsvAA"));
        ListView lv = (ListView)findViewById(R.id.listView1);
        Log.i("testTag","before start adapter");
        StringArrayAdapter ad = new StringArrayAdapter (members,this);
        Log.i("testTag","after start adapter");
        Log.i("testTag","set adapter");
        lv.setAdapter(ad);
        lv.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
                        Intent intent = new Intent(MainActivity.this, SendMessage.class);
                        intent.putExtra(EXTRA_MESSAGE, members.get(position).getMessage());
                        startActivity(intent);
                    }
                });
    }

Where getMessage() will be a getter method specified in your ListEntry class which you are using to get message which was previously set.

Best Way to Refresh Adapter/ListView on Android

You should use adapter.notifyDataSetChanged(). What does the logs says when you use that?

How can I get Android Wifi Scan Results into a list?

refer below link for getting ScanResult with redundant ssid removed from the list

duplicate SSID in scanning wifi result

Populating a ListView using an ArrayList?

tutorial

Also look up ArrayAdapter interface:

ArrayAdapter(Context context, int textViewResourceId, List<T> objects)

OnItemClickListener using ArrayAdapter for ListView

Ok, after the information that your Activity extends ListActivity here's a way to implement OnItemClickListener:

public class newListView extends ListView {

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

    @Override
    public void setOnItemClickListener(
            android.widget.AdapterView.OnItemClickListener listener) {
        super.setOnItemClickListener(listener);
        //do something when item is clicked

    }

}

RecyclerView vs. ListView

For list views to have good performance you'll need to implement the holder pattern, and that's easy to mess up especially when you want to populate the list with several different kinds of views.

The RecyclerView bakes this pattern in, making it more difficult to mess up. It's also more flexible, making it easier to handle different layouts, that aren't straight linear, like a grid.

how to put focus on TextBox when the form load?

I solved my problem with changing "TabIndex" property of TextBox. I set 0 for TextBox that I want to focus it on Form when the program start.

Java method: Finding object in array list given a known attribute value

To improve performance of the operation, if you're always going to want to look up objects by some unique identifier, then you might consider using a Map<Integer,Dog>. This will provide constant-time lookup by key. You can still iterate over the objects themselves using the map values().

A quick code fragment to get you started:

// Populate the map
Map<Integer,Dog> dogs = new HashMap<Integer,Dog>();
for( Dog dog : /* dog source */ ) {
    dogs.put( dog.getId(), dog );
}

// Perform a lookup
Dog dog = dogs.get( id );

This will help speed things up a bit if you're performing multiple lookups of the same nature on the list. If you're just doing the one lookup, then you're going to incur the same loop overhead regardless.

Grouping functions (tapply, by, aggregate) and the *apply family

On the side note, here is how the various plyr functions correspond to the base *apply functions (from the intro to plyr document from the plyr webpage http://had.co.nz/plyr/)

Base function   Input   Output   plyr function 
---------------------------------------
aggregate        d       d       ddply + colwise 
apply            a       a/l     aaply / alply 
by               d       l       dlply 
lapply           l       l       llply  
mapply           a       a/l     maply / mlply 
replicate        r       a/l     raply / rlply 
sapply           l       a       laply 

One of the goals of plyr is to provide consistent naming conventions for each of the functions, encoding the input and output data types in the function name. It also provides consistency in output, in that output from dlply() is easily passable to ldply() to produce useful output, etc.

Conceptually, learning plyr is no more difficult than understanding the base *apply functions.

plyr and reshape functions have replaced almost all of these functions in my every day use. But, also from the Intro to Plyr document:

Related functions tapply and sweep have no corresponding function in plyr, and remain useful. merge is useful for combining summaries with the original data.

How to read the output from git diff?

Lets take a look at example advanced diff from git history (in commit 1088261f in git.git repository):

diff --git a/builtin-http-fetch.c b/http-fetch.c
similarity index 95%
rename from builtin-http-fetch.c
rename to http-fetch.c
index f3e63d7..e8f44ba 100644
--- a/builtin-http-fetch.c
+++ b/http-fetch.c
@@ -1,8 +1,9 @@
 #include "cache.h"
 #include "walker.h"

-int cmd_http_fetch(int argc, const char **argv, const char *prefix)
+int main(int argc, const char **argv)
 {
+       const char *prefix;
        struct walker *walker;
        int commits_on_stdin = 0;
        int commits;
@@ -18,6 +19,8 @@ int cmd_http_fetch(int argc, const char **argv, const char *prefix)
        int get_verbosely = 0;
        int get_recover = 0;

+       prefix = setup_git_directory();
+
        git_config(git_default_config, NULL);

        while (arg < argc && argv[arg][0] == '-') {

Lets analyze this patch line by line.

  • The first line

    diff --git a/builtin-http-fetch.c b/http-fetch.c
    is a "git diff" header in the form diff --git a/file1 b/file2. The a/ and b/ filenames are the same unless rename/copy is involved (like in our case). The --git is to mean that diff is in the "git" diff format.

  • Next are one or more extended header lines. The first three

    similarity index 95%
    rename from builtin-http-fetch.c
    rename to http-fetch.c
    tell us that the file was renamed from builtin-http-fetch.c to http-fetch.c and that those two files are 95% identical (which was used to detect this rename).

    The last line in extended diff header, which is
    index f3e63d7..e8f44ba 100644
    tell us about mode of given file (100644 means that it is ordinary file and not e.g. symlink, and that it doesn't have executable permission bit), and about shortened hash of preimage (the version of file before given change) and postimage (the version of file after change). This line is used by git am --3way to try to do a 3-way merge if patch cannot be applied itself.

  • Next is two-line unified diff header

    --- a/builtin-http-fetch.c
    +++ b/http-fetch.c
    Compared to diff -U result it doesn't have from-file-modification-time nor to-file-modification-time after source (preimage) and destination (postimage) file names. If file was created the source is /dev/null; if file was deleted, the target is /dev/null.
    If you set diff.mnemonicPrefix configuration variable to true, in place of a/ and b/ prefixes in this two-line header you can have instead c/, i/, w/ and o/ as prefixes, respectively to what you compare; see git-config(1)

  • Next come one or more hunks of differences; each hunk shows one area where the files differ. Unified format hunks starts with line like

    @@ -1,8 +1,9 @@
    or
    @@ -18,6 +19,8 @@ int cmd_http_fetch(int argc, const char **argv, ...
    It is in the format @@ from-file-range to-file-range @@ [header]. The from-file-range is in the form -<start line>,<number of lines>, and to-file-range is +<start line>,<number of lines>. Both start-line and number-of-lines refer to position and length of hunk in preimage and postimage, respectively. If number-of-lines not shown it means that it is 0.

    The optional header shows the C function where each change occurs, if it is a C file (like -p option in GNU diff), or the equivalent, if any, for other types of files.

  • Next comes the description of where files differ. The lines common to both files begin with a space character. The lines that actually differ between the two files have one of the following indicator characters in the left print column:

    • '+' -- A line was added here to the first file.
    • '-' -- A line was removed here from the first file.


    So, for example, first chunk

     #include "cache.h"
     #include "walker.h"
    
    -int cmd_http_fetch(int argc, const char **argv, const char *prefix)
    +int main(int argc, const char **argv)
     {
    +       const char *prefix;
            struct walker *walker;
            int commits_on_stdin = 0;
            int commits;
    

    means that cmd_http_fetch was replaced by main, and that const char *prefix; line was added.

    In other words, before the change, the appropriate fragment of then 'builtin-http-fetch.c' file looked like this:

    #include "cache.h"
    #include "walker.h"
    
    int cmd_http_fetch(int argc, const char **argv, const char *prefix)
    {
           struct walker *walker;
           int commits_on_stdin = 0;
           int commits;
    

    After the change this fragment of now 'http-fetch.c' file looks like this instead:

    #include "cache.h"
    #include "walker.h"
    
    int main(int argc, const char **argv)
    {
           const char *prefix;
           struct walker *walker;
           int commits_on_stdin = 0;
           int commits;
    
  • There might be

    \ No newline at end of file
    line present (it is not in example diff).

As Donal Fellows said it is best to practice reading diffs on real-life examples, where you know what you have changed.

References:

Content Type text/xml; charset=utf-8 was not supported by service

I was also facing the same problem recently. after struggling a couple of hours,finally a solution came out by addition to

Factory="System.ServiceModel.Activation.WebServiceHostFactory"
to your SVC markup file. e.g.
ServiceHost Language="C#" Debug="true" Service="QuiznetOnline.Web.UI.WebServices.LogService" 
Factory="System.ServiceModel.Activation.WebServiceHostFactory" 

and now you can compile & run your application successfully.

How can I convert a DOM element to a jQuery element?

var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element

Extract the maximum value within each group in a dataframe

There are many possibilities to do this in R. Here are some of them:

df <- read.table(header = TRUE, text = 'Gene   Value
A      12
A      10
B      3
B      5
B      6
C      1
D      3
D      4')

# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)

# tapply
tapply(df$Value, df$Gene, max)

# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))

# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))

# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))

# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]

# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)

# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')

# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]

How to check if a value exists in an object using JavaScript

if( myObj.hasOwnProperty('key') && myObj['key'] === value ){
    ...
}

What is a user agent stylesheet?

Regarding the concept “user agent style sheet”, consult section Cascade in the CSS 2.1 spec.

User agent style sheets are overridden by anything that you set in your own style sheet. They are just the rock bottom: in the absence of any style sheets provided by the page or by the user, the browser still has to render the content somehow, and the user agent style sheet just describes this.

So if you think you have a problem with a user agent style sheet, then you really have a problem with your markup, or your style sheet, or both (about which you wrote nothing).

Cannot set some HTTP headers when using System.Net.WebRequest

WebRequest being abstract (and since any inheriting class must override the Headers property).. which concrete WebRequest are you using ? In other words, how do you get that WebRequest object to beign with ?

ehr.. mnour answer made me realize that the error message you were getting is actually spot on: it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again. That's probably all you were looking for.

Other classes inheriting from WebRequest might have even better properties wrapping certain headers; See this post for instance.

Write HTML file using Java

Velocity is a good candidate for writing this kind of stuff.
It allows you to keep your html and data-generation code as separated as possible.

Remove a file from the list that will be committed

if you have already pushed your commit then. do

git checkout origin/<remote-branch> <filename>
git commit --amend

AND If you have not pushed the changes on the server you can use

git reset --soft HEAD~1

Round to 5 (or other number) in Python

You can “trick” int() into rounding off instead of rounding down by adding 0.5 to the number you pass to int().

How to import Google Web Font in CSS file?

Download the font ttf/other format files, then simply add this CSS code example:

_x000D_
_x000D_
@font-face { font-family: roboto-regular; _x000D_
    src: url('../font/Roboto-Regular.ttf'); } _x000D_
h2{_x000D_
 font-family: roboto-regular;_x000D_
}
_x000D_
_x000D_
_x000D_

Selecting one row from MySQL using mysql_* API

It is working for me..

$show = mysql_query("SELECT data FROM wp_10_options WHERE
 option_name='homepage' limit 1"); $row = mysql_fetch_assoc($show);
 echo $row['data'];

How can I declare dynamic String array in Java

What your looking for is the DefaultListModel - Dynamic String List Variable.

Here is a whole class that uses the DefaultListModel as though it were the TStringList of Delphi. The difference is that you can add Strings to the list without limitation and you have the same ability at getting a single entry by specifying the entry int.

FileName: StringList.java

package YOUR_PACKAGE_GOES_HERE;

//This is the StringList Class by i2programmer
//You may delete these comments
//This code is offered freely at no requirements
//You may alter the code as you wish
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;

public class StringList {

    public static String OutputAsString(DefaultListModel list, int entry) {
        return GetEntry(list, entry);
    }

    public static Object OutputAsObject(DefaultListModel list, int entry) {
        return GetEntry(list, entry);
    }

    public static int OutputAsInteger(DefaultListModel list, int entry) {
        return Integer.parseInt(list.getElementAt(entry).toString());
    }

    public static double OutputAsDouble(DefaultListModel list, int entry) {
        return Double.parseDouble(list.getElementAt(entry).toString());
    }

    public static byte OutputAsByte(DefaultListModel list, int entry) {
        return Byte.parseByte(list.getElementAt(entry).toString());
    }

    public static char OutputAsCharacter(DefaultListModel list, int entry) {
        return list.getElementAt(entry).toString().charAt(0);
    }

    public static String GetEntry(DefaultListModel list, int entry) {
        String result = "";
        result = list.getElementAt(entry).toString();
        return result;
    }

    public static void AddEntry(DefaultListModel list, String entry) {
        list.addElement(entry);
    }

    public static void RemoveEntry(DefaultListModel list, int entry) {
        list.removeElementAt(entry);
    }

    public static DefaultListModel StrToList(String input, String delimiter) {
        DefaultListModel dlmtemp = new DefaultListModel();
        input = input.trim();
        delimiter = delimiter.trim();
        while (input.toLowerCase().contains(delimiter.toLowerCase())) {
            int index = input.toLowerCase().indexOf(delimiter.toLowerCase());
            dlmtemp.addElement(input.substring(0, index).trim());
            input = input.substring(index + delimiter.length(), input.length()).trim();
        }
        return dlmtemp;
    }

    public static String ListToStr(DefaultListModel list, String delimiter) {
        String result = "";
        for (int i = 0; i < list.size(); i++) {
            result = list.getElementAt(i).toString() + delimiter;
        }
        result = result.trim();
        return result;
    }

    public static String LoadFile(String inputfile) throws IOException {
        int len;
        char[] chr = new char[4096];
        final StringBuffer buffer = new StringBuffer();
        final FileReader reader = new FileReader(new File(inputfile));
        try {
            while ((len = reader.read(chr)) > 0) {
                buffer.append(chr, 0, len);
            }
        } finally {
            reader.close();
        }
        return buffer.toString();
    }

    public static void SaveFile(String outputfile, String outputstring) {
        try {
            FileWriter f0 = new FileWriter(new File(outputfile));
            f0.write(outputstring);
            f0.flush();
            f0.close();
        } catch (IOException ex) {
            Logger.getLogger(StringList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

OutputAs methods are for outputting an entry as int, double, etc... so that you don't have to convert from string on the other side.

SaveFile & LoadFile are to save and load strings to and from files.

StrToList & ListToStr are to place delimiters between each entry.

ex. 1<>2<>3<>4<> if "<>" is the delimiter and 1 2 3 & 4 are the entries.

AddEntry & GetEntry are to add and get strings to and from the DefaultListModel.

RemoveEntry is to delete a string from the DefaultListModel.

You use the DefaultListModel instead of an array here like this:

DefaultListModel list = new DefaultListModel();
//now that you have a list, you can run it through the above class methods.

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

Link to the PEP discussing the new bool type in Python 2.3: http://www.python.org/dev/peps/pep-0285/.

When converting a bool to an int, the integer value is always 0 or 1, but when converting an int to a bool, the boolean value is True for all integers except 0.

>>> int(False)
0
>>> int(True)
1
>>> bool(5)
True
>>> bool(-5)
True
>>> bool(0)
False

Python 3.6 install win32api?

Information provided by @Gord

As of September 2019 pywin32 is now available from PyPI and installs the latest version (currently version 224). This is done via the pip command

pip install pywin32

If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx is the version you require, e.g. 224

pip install pywin32==xxx

This differs to the pip command below as that one uses pypiwin32 which currently installs an older (namely 223)

Browsing the docs I see no reason for these commands to work for all python3.x versions, I am unsure on python2.7 and below so you would have to try them and if they do not work then the solutions below will work.


Probably now undesirable solutions but certainly still valid as of September 2019

There is no version of specific version ofwin32api. You have to get the pywin32module which currently cannot be installed via pip. It is only available from this link at the moment.

https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/

The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python version :)


EDIT

Since I posted my answer there are other alternatives to downloading the win32api module.

It is now available to download through pip using this command;

pip install pypiwin32

Also it can be installed from this GitHub repository as provided in comments by @Heath

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

For non-preemptive system,

waitingTime = startTime - arrivalTime

turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime

startTime = Time at which the process started executing

finishTime = Time at which the process finished executing

You can keep track of the current time elapsed in the system(timeElapsed). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime, when finishes, record its finishTime (both same as timeElapsed). That way you can calculate what you need.

Is there anything like .NET's NotImplementedException in Java?

No there isn't and it's probably not there, because there are very few valid uses for it. I would think twice before using it. Also, it is indeed easy to create yourself.

Please refer to this discussion about why it's even in .NET.

I guess UnsupportedOperationException comes close, although it doesn't say the operation is just not implemented, but unsupported even. That could imply no valid implementation is possible. Why would the operation be unsupported? Should it even be there? Interface segregation or Liskov substitution issues maybe?

If it's work in progress I'd go for ToBeImplementedException, but I've never caught myself defining a concrete method and then leave it for so long it makes it into production and there would be a need for such an exception.

Notepad++ change text color?

You can Change it from:

Menu Settings -> Style Configurator

See on screenshot:

enter image description here

Position absolute and overflow hidden

What about position: relative for the outer div? In the example that hides the inner one. It also won't move it in its layout since you don't specify a top or left.

How do I configure PyCharm to run py.test tests?

I'm using 2018.2

I do Run -> Edit Configurations... Then click the + in the upper left of the modal dialog. Select "python tests" -> py.test Then I give it a name like "All test with py.test"

I select Target: module name and put in the module where my tests are (that is 'tests' for me) or the module where all my code is if my tests are mixed in with my code. This was tripping me up.

I set the Python interpreter.

I set the working directory to the project directory.

Double vs. BigDecimal?

If you write down a fractional value like 1 / 7 as decimal value you get

1/7 = 0.142857142857142857142857142857142857142857...

with an infinite sequence of 142857. Since you can only write a finite number of digits you will inevitably introduce a rounding (or truncation) error.

Numbers like 1/10 or 1/100 expressed as binary numbers with a fractional part also have an infinite number of digits after the decimal point:

1/10 = binary 0.0001100110011001100110011001100110...

Doubles store values as binary and therefore might introduce an error solely by converting a decimal number to a binary number, without even doing any arithmetic.

Decimal numbers (like BigDecimal), on the other hand, store each decimal digit as is (binary coded, but each decimal on its own). This means that a decimal type is not more precise than a binary floating point or fixed point type in a general sense (i.e. it cannot store 1/7 without loss of precision), but it is more accurate for numbers that have a finite number of decimal digits as is often the case for money calculations.

Java's BigDecimal has the additional advantage that it can have an arbitrary (but finite) number of digits on both sides of the decimal point, limited only by the available memory.

Convert python datetime to timestamp in milliseconds

You need to parse your time format using strptime.

>>> import time
>>> from datetime import datetime
>>> ts, ms = '20.12.2016 09:38:42,76'.split(',')
>>> ts
'20.12.2016 09:38:42'
>>> ms
'76'
>>> dt = datetime.strptime(ts, '%d.%m.%Y %H:%M:%S')
>>> time.mktime(dt.timetuple())*1000 + int(ms)*10
1482223122760.0

How can I store the result of a system command in a Perl variable?

From Perlfaq8:

You're confusing the purpose of system() and backticks (``). system() runs a command and returns exit status information (as a 16 bit value: the low 7 bits are the signal the process died from, if any, and the high 8 bits are the actual exit value). Backticks (``) run a command and return what it sent to STDOUT.

$exit_status   = system("mail-users");
$output_string = `ls`;

There are many ways to execute external commands from Perl. The most commons with their meanings are:

  • system() : you want to execute a command and don't want to capture its output
  • exec: you don't want to return to the calling perl script
  • backticks : you want to capture the output of the command
  • open: you want to pipe the command (as input or output) to your script

Also see How can I capture STDERR from an external command?

How do I fit an image (img) inside a div and keep the aspect ratio?

Try CSS:

img {
  object-fit: cover;
  height: 48px;
}

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

import the HttpClientModule in your app.module.ts

import {HttpClientModule} from '@angular/common/http';

...
@NgModule({
...
  imports: [
    //other content,
    HttpClientModule
  ]
})

How to make a text box have rounded corners?

This can be done with CSS3:

<input type="text" />

input
{
  -moz-border-radius: 15px;
 border-radius: 15px;
    border:solid 1px black;
    padding:5px;
}

http://jsfiddle.net/UbSkn/1/


However, an alternative would be to put the input inside a div with a rounded background, and no border on the input

Linq : select value in a datatable column

I notice others have given the non-lambda syntax so just to have this complete I'll put in the lambda syntax equivalent:

Non-lambda (as per James's post):

var name = from i in DataContext.MyTable
           where i.ID == 0
           select i.Name

Equivalent lambda syntax:

var name = DataContext.MyTable.Where(i => i.ID == 0)
                              .Select(i => new { Name = i.Name });

There's not really much practical difference, just personal opinion on which you prefer.

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

You could create a JsonConverter. See here for an example thats similar to your question.

jQuery Ajax requests are getting cancelled without being sent

I had the cancelled in Firefox. Some ajax-calls working perfectly fine for me, but it failed for the coworker who actually had to use it.

When I checked this out via the Chrome tricks mentioned above, I found nothing suspicious. When checking it in firebug, it showed the 'loading' animation after the two mallicous calls, and no result tab.

The solution was mega simple: go to history, find the website, rightclick -> forget website.
Forget, not delete.

After that, no problems anymore. My guess is it has something to do with the .htaccess.

Changing nav-bar color after scrolling?

First you make an id named nav (can change whatever you want) inside the nav div (exp: id="nav") Then at the bottom where body tag had been finished. You add this code

<script>
  $(document).ready(function()
  $(window).scroll(function(){
   var scroll = $(window).scrollTop();
     if(scroll>50){
      $("#nav").css("background", "#555");
       }
       else {
      $("#nav").css("background", "transparent");
       }
      })
   })
</script>

How to connect android wifi to adhoc wifi?

If you have a Microsoft Virtual WiFi Miniport Adapter as one of the available network adapters, you may do the following:

  • Run Windows Command Processor (cmd) as Administrator
  • Type: netsh wlan set hostednetwork mode=allow ssid=NAME key=PASSWORD
  • Then: netsh wlan start hostednetwork
  • Open "Control Panel\Network and Internet\Network Connections"
  • Right-click on your active network adapter (the one that you use to connect on the internet) and then click Properties
  • Then open Sharing tab
  • Check "Allow other network users to connect..." and select your WiFi Miniport Adapter
  • Once finished, type: netsh wlan stop hostednetwork

That's it!

Source: How to connect android phone to an ad-hoc network without softwares.

How do you implement a circular buffer in C?

C style, simple ring buffer for integers. First use init than use put and get. If buffer does not contain any data it returns "0" zero.

//=====================================
// ring buffer address based
//=====================================
#define cRingBufCount   512
int     sRingBuf[cRingBufCount];    // Ring Buffer
int     sRingBufPut;                // Input index address
int     sRingBufGet;                // Output index address
Bool    sRingOverWrite;

void    GetRingBufCount(void)
{
int     r;
`       r= sRingBufPut - sRingBufGet;
        if ( r < cRingBufCount ) r+= cRingBufCount;
        return r; 
}

void    InitRingBuffer(void)
{
        sRingBufPut= 0;
        sRingBufGet= 0;
}       

void    PutRingBuffer(int d)
{
        sRingBuffer[sRingBufPut]= d;
        if (sRingBufPut==sRingBufGet)// both address are like ziro
        {
            sRingBufPut= IncRingBufferPointer(sRingBufPut);
            sRingBufGet= IncRingBufferPointer(sRingBufGet);
        }
        else //Put over write a data
        {
            sRingBufPut= IncRingBufferPointer(sRingBufPut);
            if (sRingBufPut==sRingBufGet)
            {
                sRingOverWrite= Ture;
                sRingBufGet= IncRingBufferPointer(sRingBufGet);
            }
        }
}

int     GetRingBuffer(void)
{
int     r;
        if (sRingBufGet==sRingBufPut) return 0;
        r= sRingBuf[sRingBufGet];
        sRingBufGet= IncRingBufferPointer(sRingBufGet);
        sRingOverWrite=False;
        return r;
}

int     IncRingBufferPointer(int a)
{
        a+= 1;
        if (a>= cRingBufCount) a= 0;
        return a;
}

How to Insert Double or Single Quotes

Easier steps:

  1. Highlight the cells you want to add the quotes.
  2. Go to Format–>Cells–>Custom
  3. Copy/Paste the following into the Type field: \"@\" or \'@\'
  4. Done!

find all unchecked checkbox in jquery

To select by class, you can do this:

$("input.className:checkbox:not(:checked)")

How to get current SIM card number in Android?

I think sim serial Number and sim number is unique. You can try this for get sim serial number and get sim number and Don't forget to add permission in manifest file.

TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber = telemamanger.getSimSerialNumber();
String getSimNumber = telemamanger.getLine1Number();

And add below permission into your Androidmanifest.xml file.

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

Let me know if there is any issue.

jQuery UI themes and HTML tables

Why noy just use the theme styles in the table? i.e.

<table>
  <thead class="ui-widget-header">
    <tr>
      <th>Id</th>
      <th>Description</th>
    </td>
  </thead>
  <tbody class="ui-widget-content">
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
      .
      .
      .
  </tbody>
</table>

And you don't need to use any code...

SCCM 2012 application install "Failed" in client Software Center

I'm assuming you figured this out already but:

Technical Reference for Log Files in Configuration Manager

That's a list of client-side logs and what they do. They are located in Windows\CCM\Logs

AppEnforce.log will show you the actual command-line executed and the resulting exit code for each Deployment Type (only for the new style ConfigMgr Applications)

This is my go-to for troubleshooting apps. Haven't really found any other logs that are exceedingly useful.

Youtube - downloading a playlist - youtube-dl

I found the best solution after many attempts for this problem.

youtube-dl --ignore-errors --format bestaudio --extract-audio --audio-format mp3 --audio-quality 160K --output "%(title)s.%(ext)s" --yes-playlist https://www.youtube.com/playlist?list={your-youtube-playlist-id}

Uncaught TypeError: Cannot set property 'onclick' of null

Try to put all your <script ...></script> tags before the </body> tag. Perhaps the js is trying to access an object of the DOM before it's built up.

Add a row number to result set of a SQL query

SELECT
    t.A,
    t.B,
    t.C,
    ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS number
FROM tableZ AS t

See working example at SQLFiddle

Of course, you may want to define the row-numbering order – if so, just swap OVER (ORDER BY (SELECT 1)) for, e.g., OVER (ORDER BY t.C), like in a normal ORDER BY clause.

How can I disable mod_security in .htaccess file?

It is possible to do this, but most likely your host implemented mod_security for a reason. Be sure they approve of you disabling it for your own site.

That said, this should do it;

<IfModule mod_security.c>
  SecFilterEngine Off
  SecFilterScanPOST Off
</IfModule>

Fixing broken UTF-8 encoding

The way is to convert to binary and then to correct encoding

Getting Textarea Value with jQuery

It can be done at easily like as:

     <a id="send-thoughts" href="">Click</a>
     <textarea id="message"></textarea>

        $("a#send-thoughts").click(function() {
            var thought = $("#message").val();
            alert(thought);
        });

Get type of all variables

lapply(your_dataframe, class) gives you something like:

$tikr [1] "factor"

$Date [1] "Date"

$Open [1] "numeric"

$High [1] "numeric"

... etc.

Error while trying to retrieve text for error ORA-01019

Correct the ORACLE_HOME path.

There could be two oracle clients in the system.

I had the same issue, the reason being my ORACLE_HOME was pointed to the oracle installation which was not having the tns.ora file.

Changing the ORACLE_HOME to the Oracle directory which is having the tns.ora solved it.

tns.ora lies in client2\network\admin\

Xampp MySQL not starting - "Attempting to start MySQL service..."

I had an issue with this because I had accidentally installed XAMPP to c:\windows\program files (x86) which caused a Windows permissions issue.

The installation says not to install it there, but I thought it had said to install it there.

I uninstalled and reinstalled to c:\xampp and it worked.

Getting 400 bad request error in Jquery Ajax POST

Finally, I got the mistake and the reason was I need to stringify the JSON data I was sending. I have to set the content type and datatype in XHR object. So the correct version is here:

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: JSON.stringify({
    "subject:title":"Test Name",
    "subject:description":"Creating test subject to check POST method API",
    "sub:tags": ["facebook:work", "facebook:likes"],
    "sampleSize" : 10,
    "values": ["science", "machine-learning"]
  }),
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

May be it will help someone else.

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

The most contextual description of JavaScript's Automatic Semicolon Insertion I have found comes from a book about Crafting Interpreters.

JavaScript’s “automatic semicolon insertion” rule is the odd one. Where other languages assume most newlines are meaningful and only a few should be ignored in multi-line statements, JS assumes the opposite. It treats all of your newlines as meaningless whitespace unless it encounters a parse error. If it does, it goes back and tries turning the previous newline into a semicolon to get something grammatically valid.

He goes on to describe it as you would code smell.

This design note would turn into a design diatribe if I went into complete detail about how that even works, much less all the various ways that that is a bad idea. It’s a mess. JavaScript is the only language I know where many style guides demand explicit semicolons after every statement even though the language theoretically lets you elide them.

Close pre-existing figures in matplotlib when running from eclipse

Nothing works in my case using the scripts above but I was able to close these figures from eclipse console bar by clicking on Terminate ALL (two red nested squares icon).

How can I convert String[] to ArrayList<String>

Like this :

String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));

or

List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);

Code for download video from Youtube on Java, Android

METHOD 1 ( Recommanded )

Library YouTubeExtractor

Add into your gradle file

 allprojects {
        repositories {
            maven { url "https://jitpack.io" }
        }
    }

And dependencies

 compile 'com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'

Add this small code and you done. Demo HERE

public class MainActivity extends AppCompatActivity {

    private static final String YOUTUBE_ID = "ea4-5mrpGfE";

    private final YouTubeExtractor mExtractor = YouTubeExtractor.create();


    private Callback<YouTubeExtractionResult> mExtractionCallback = new Callback<YouTubeExtractionResult>() {
        @Override
        public void onResponse(Call<YouTubeExtractionResult> call, Response<YouTubeExtractionResult> response) {
            bindVideoResult(response.body());
        }

        @Override
        public void onFailure(Call<YouTubeExtractionResult> call, Throwable t) {
            onError(t);
        }
    };


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


//        For android youtube extractor library  com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'
        mExtractor.extract(YOUTUBE_ID).enqueue(mExtractionCallback);

    }


    private void onError(Throwable t) {
        t.printStackTrace();
        Toast.makeText(MainActivity.this, "It failed to extract. So sad", Toast.LENGTH_SHORT).show();
    }


    private void bindVideoResult(YouTubeExtractionResult result) {

//        Here you can get download url link
        Log.d("OnSuccess", "Got a result with the best url: " + result.getBestAvailableQualityVideoUri());

        Toast.makeText(this, "result : " + result.getSd360VideoUri(), Toast.LENGTH_SHORT).show();
    }
}

You can get download link in bindVideoResult() method.

METHOD 2

Using this library android-youtubeExtractor

Add into gradle file

repositories {
    maven { url "https://jitpack.io" }
}

compile 'com.github.HaarigerHarald:android-youtubeExtractor:master-SNAPSHOT'

Here is the code for getting download url.

       String youtubeLink = "http://youtube.com/watch?v=xxxx";

    YouTubeUriExtractor ytEx = new YouTubeUriExtractor(this) {
        @Override
        public void onUrisAvailable(String videoId, String videoTitle, SparseArray<YtFile> ytFiles) {
            if (ytFiles != null) {
                int itag = 22;
// Here you can get download url
                String downloadUrl = ytFiles.get(itag).getUrl();
            }
        }
    };

    ytEx.execute(youtubeLink);

What is a provisioning profile used for when developing iPhone applications?

A Quote from : iPhone Developer Program (~8MB PDF)

A provisioning profile is a collection of digital entities that uniquely ties developers and devices to an authorized iPhone Development Team and enables a device to be used for testing. A Development Provisioning Profile must be installed on each device on which you wish to run your application code. Each Development Provisioning Profile will contain a set of iPhone Development Certificates, Unique Device Identifiers and an App ID. Devices specified within the provisioning profile can be used for testing only by those individuals whose iPhone Development Certificates are included in the profile. A single device can contain multiple provisioning profiles.

Regular expression to match URLs in Java

Here is a proposal of an URL parser regex that recognizes :

  • Protocol
  • Host
  • Port
  • Path (Document/folder)
  • Get parameters
^(?>(?<protocol>[[:alpha:]]+(?>\:[[:alpha:]]+)*)\:\/\/)?(?<host>(?>[[:alnum:]]|[-_.])+)(?>\:(?<port>[[:digit:]]+))?(?<path>\/(?>[[:alnum:]]|[-_.\/])*)?(?>\?(?<request>(?>[[:alnum:]]+=[[:alnum:]]+)(?>\&(?>[[:alnum:]]+=[[:alnum:]]+))*))?$

This regex is able to parse an URL such :

jdbc:hsqldb:hsql://localhost:91/index.

There can be many way to engineer a URL regex, thus the one I propose can be lightly adapted to match more accurate URL grammars.

It can be tested on the following page : https://regex101.com/r/Dy7HE0/5

Be aware that langages native API for regex (such as java.util.regex) don't support smart character classes such as [[:alnum:]] and [[:alpha:]].

Use instead \w and \d.

Only get hash value using md5sum (without filename)

md5="$(md5sum "${my_iso_file}")"
md5="${md5%% *}" # remove the first space and everything after it
echo "${md5}"

Parsing boolean values with argparse

Similar to @Akash but here is another approach that I've used. It uses str than lambda because python lambda always gives me an alien-feelings.

import argparse
from distutils.util import strtobool

parser = argparse.ArgumentParser()
parser.add_argument("--my_bool", type=str, default="False")
args = parser.parse_args()

if bool(strtobool(args.my_bool)) is True:
    print("OK")

Basic Python client socket example

It looks like your client is trying to connect to a non-existent server. In a shell window, run:

$ nc -l 5000

before running your Python code. It will act as a server listening on port 5000 for you to connect to. Then you can play with typing into your Python window and seeing it appear in the other terminal and vice versa.

PHP error: Notice: Undefined index:

Make sure the tags correctly closed. And the closing tag will not include inside a loop. (if it contains in a looping structure).

Undo a git stash

git stash list to list your stashed changes.

git stash show to see what n is in the below commands.

git stash apply to apply the most recent stash.

git stash apply stash@{n} to apply an older stash.

https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning

How to Alter Constraint

No. We cannot alter the constraint, only thing we can do is drop and recreate it

ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]

Foreign Key Constraint

Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade

Primary Key constraint

Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)

How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

For Visual Studio 2015 I found an extension that does just this. It seems to work well and has a reasonably high amount of downloads. So if you can't or don't want to use ReSharper you can install this one instead.

You can also acquire it via NuGet.

How do I convert seconds to hours, minutes and seconds?

You can use datetime.timedelta function:

>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'

Git Bash: Could not open a connection to your authentication agent

It seems you need to run ssh-agent before using it:

eval `ssh-agent -s`

That question was answered in this topic: Could not open a connection to your authentication agent

Iterate keys in a C++ map

Below the more general templated solution to which Ian referred...

#include <map>

template<typename Key, typename Value>
using Map = std::map<Key, Value>;

template<typename Key, typename Value>
using MapIterator = typename Map<Key, Value>::iterator;

template<typename Key, typename Value>
class MapKeyIterator : public MapIterator<Key, Value> {

public:

    MapKeyIterator ( ) : MapIterator<Key, Value> ( ) { };
    MapKeyIterator ( MapIterator<Key, Value> it_ ) : MapIterator<Key, Value> ( it_ ) { };

    Key *operator -> ( ) { return ( Key * const ) &( MapIterator<Key, Value>::operator -> ( )->first ); }
    Key operator * ( ) { return MapIterator<Key, Value>::operator * ( ).first; }
};

template<typename Key, typename Value>
class MapValueIterator : public MapIterator<Key, Value> {

public:

    MapValueIterator ( ) : MapIterator<Key, Value> ( ) { };
    MapValueIterator ( MapIterator<Key, Value> it_ ) : MapIterator<Key, Value> ( it_ ) { };

    Value *operator -> ( ) { return ( Value * const ) &( MapIterator<Key, Value>::operator -> ( )->second ); }
    Value operator * ( ) { return MapIterator<Key, Value>::operator * ( ).second; }
};

All credits go to Ian... Thanks Ian.

How to debug Apache mod_rewrite

Based on Ben's answer you you could do the following when running apache on Linux (Debian in my case).

First create the file rewrite-log.load

/etc/apache2/mods-availabe/rewrite-log.load

RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3

Then enter

$ a2enmod rewrite-log

followed by

$ service apache2 restart

And when you finished with debuging your rewrite rules

$ a2dismod rewrite-log && service apache2 restart

SQL Server remove milliseconds from datetime

May be this will help.. SELECT [Datetime] = CAST('20120228' AS smalldatetime)

o/p: 2012-02-28 00:00:00

Strings as Primary Keys in SQL Database

From performance standpoint - Yes string(PK) will slow down the performance when compared to performance achieved using an integer(PK), where PK ---> Primary Key.

From requirement standpoint - Although this is not a part of your question still I would like to mention. When we are handling huge data across different tables we generally look for the probable set of keys that can be set for a particular table. This is primarily because there are many tables and mostly each or some table would be related to the other through some relation ( a concept of Foreign Key ). Therefore we really cannot always choose an integer as a Primary Key, rather we go for a combination of 3, 4 or 5 attributes as the primary key for that tables. And those keys can be used as a foreign key when we would relate the records with some other table. This makes it useful to relate the records across different tables when required.

Therefore for Optimal Usage - We always make a combination of 1 or 2 integers with 1 or 2 string attributes, but again only if it is required.

Android - Center TextView Horizontally in LinearLayout

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

<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/title_bar_background">

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:padding="10dp"
    android:text="HELLO WORLD" />

</LinearLayout>

How do you remove a specific revision in the git history?

Answers of rado and kareem do nothing for me (only message "Current branch is up to date." appears). Possibly this happens because '^' symbol doesn't work in Windows console. However, according to this comment, replacing '^' by '~1' solves the problem.

git rebase --onto <commit-id>^ <commit-id>

Docker - a way to give access to a host USB or serial device?

If you would like to dynamically access USB devices which can be plugged in while the docker container is already running, for example access a just attached usb webcam at /dev/video0, you can add a cgroup rule when starting the container. This option does not need a --privileged container and only allows access to specific types of hardware.

Step 1

Check the device major number of the type of device you would like to add. You can look it up in the linux kernel documentation. Or you can check it for your device. For example to check the device major number for a webcam connected to /dev/video0, you can do a ls -la /dev/video0. This results in something like:

crw-rw----+ 1 root video 81, 0 Jul  6 10:22 /dev/video0

Where the first number (81) is the device major number. Some common device major numbers:

  • 81: usb webcams
  • 188: usb to serial converters

Step 2

Add rules when you start the docker container:

  • Add a --device-cgroup-rule='c major_number:* rmw' rule for every type of device you want access to
  • Add access to udev information so docker containers can get more info on your usb devices with -v /run/udev:/run/udev:ro
  • Map the /dev volume to your docker container with -v /dev:/dev

Wrap up

So to add all usb webcams and serial2usb devices to your docker container, do:

docker run -it -v /dev:/dev --device-cgroup-rule='c 188:* rmw' --device-cgroup-rule='c 81:* rmw' ubuntu bash

How to send a header using a HTTP request through a curl call?

I've switched from curl to Httpie; the syntax looks like:

http http://myurl HeaderName:value

How to add jQuery code into HTML Page

Before the closing body tag add this (reference to jQuery library). Other hosted libraries can be found here

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

And this

<script>
  //paste your code here
</script>

It should look something like this

<body>
 ........
 ........
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 <script> Your code </script>
</body>

In Python, when to use a Dictionary, List or Set?

When you want an unordered collection of unique elements, use a set. (For example, when you want the set of all the words used in a document).

When you want to collect an immutable ordered list of elements, use a tuple. (For example, when you want a (name, phone_number) pair that you wish to use as an element in a set, you would need a tuple rather than a list since sets require elements be immutable).

When you want to collect a mutable ordered list of elements, use a list. (For example, when you want to append new phone numbers to a list: [number1, number2, ...]).

When you want a mapping from keys to values, use a dict. (For example, when you want a telephone book which maps names to phone numbers: {'John Smith' : '555-1212'}). Note the keys in a dict are unordered. (If you iterate through a dict (telephone book), the keys (names) may show up in any order).

CodeIgniter 404 Page Not Found, but why?

Your folder/file structure seems a little odd to me. I can't quite figure out how you've got this laid out.

Hello I am using CodeIgniter for two applications (a public and an admin app).

This sounds to me like you've got two separate CI installations. If this is the case, I'd recommend against it. Why not just handle all admin stuff in an admin controller? If you do want two separate CI installations, make sure they are definitely distinct entities and that the two aren't conflicting with one another. This line:

$system_folder = "../system";
$application_folder = "../application/admin"; (this line exists of course twice)

And the place you said this exists (/admin/index.php...or did you mean /admin/application/config?) has me scratching my head. You have admin/application/admin and a system folder at the top level?

Deprecated meaning?

Deprecated means they don't recommend using it, and that it isn't undergoing further development. But it should not work differently than it did in a previous version unless documentation explicitly states that.

  1. Yes, otherwise it wouldn't be called "deprecated"

  2. Unless stated otherwise in docs, it should be the same as before

  3. No, but if there were problems in v1 they aren't about to fix them

Close application and launch home screen on Android

Try the following. It works for me.

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1); 
ComponentName componentInfo = taskInfo.get(0).topActivity;
am.restartPackage(componentInfo.getPackageName());

How to set image to fit width of the page using jsPDF?

There where a lot of solutions with .addImage, I tried many of them, but nothing worked out. So I found the .html() function and after some tries the html2canvas-scale-option. This solution is no general solution, you have to adjust the scale so it will fit your pdf, but this is the only solution, which works for me.

var doc = new jspdf.jsPDF({
    orientation: 'p',
    unit: 'pt',
    format: 'a4'
});

doc.html(document.querySelector('#styledTable'), {
    callback: function (doc) {
        doc.save('file.pdf');
    },
    margin: [60, 60, 60, 60],
    x: 32,
    y: 32,
    html2canvas: {
        scale: 0.3, //this was my solution, you have to adjust to your size
        width: 1000 //for some reason width does nothing
    },
});

check all socket opened in linux OS

You can use netstat command

netstat --listen

To display open ports and established TCP connections,

netstat -vatn

To display only open UDP ports try the following command:

netstat -vaun

What is the best algorithm for overriding GetHashCode?

I want to add my newest findings to this thread I came back to so often.

My current visual studio / project setup provides the functionallity to automatically refactors tuples to structs. This will generate a GetHashCode function like so:

        public override int GetHashCode()
        {
            int hashCode = -2088324004;
            hashCode = hashCode * -1521134295 + AuftragGesperrt.GetHashCode();
            hashCode = hashCode * -1521134295 + Auftrag_gesperrt_von.GetHashCode();
            hashCode = hashCode * -1521134295 + Auftrag_gesperrt_am.GetHashCode();
            return hashCode;
        }

C# removing items from listbox

You can't use an enumerator, you have to loop using an index, starting at the last item:

for (int n = listBox1.Items.Count - 1; n >= 0; --n)
{
    string removelistitem = "OBJECT";
    if (listBox1.Items[n].ToString().Contains(removelistitem))
    {
        listBox1.Items.RemoveAt(n);
    }
}

Can media queries resize based on a div element instead of the screen?

For mine I did it by setting the div's max width, hence for small widget won't get affected and the large widget is resized due to the max-width style.

  // assuming your widget class is "widget"
  .widget {
    max-width: 100%;
    height: auto;
  }

Batch files : How to leave the console window open

For leaving the console window open you only have to add to the last command line in the batch file:

' & pause'

Difference between Pragma and Cache-Control headers?

Pragma is the HTTP/1.0 implementation and cache-control is the HTTP/1.1 implementation of the same concept. They both are meant to prevent the client from caching the response. Older clients may not support HTTP/1.1 which is why that header is still in use.

How to give color to each class in scatter plot in R?

This article is old, but I spent a hot minute trying to figure this out so I figured I would post an updated response. My main source is this wonderful PowerPoint: http://www.lrdc.pitt.edu/maplelab/slides/14-Plotting.pdf. Okay, here's what I did:

In this example, my data set is called 'Data' and I was comparing 'Touch' data against 'Gaze' data. The subjects were divided into two groups: 'Red' and 'Blue'.

`plot(Data$Touch[Data$Category == "Blue"], Data$Gaze[Data$Category == "Blue"], main = "Touch v Gaze", xlab = "Gaze(s)", ylab = "Touch (s)", col = "blue", pch = 20)`
  • This set of code creates a scatterplot of Touch v Gaze of my Blue group

    par(new = TRUE)

  • This tells R to create a new plot. This second plot is laid over the first automatically by R when you run all the code together

    plot(Data$Touch[Data$Category == "Red"], Data$Gaze[Data$Category == "Red"], axes = FALSE, xlab = "", ylab = "", col = "red", pch = 2)

  • This is the second plot. I found when I was coding these that R didn't just lay over the data points onto the Blue plot, but it also lay the axes, axes titles, and main title.

  • To get rid of the annoying overlap problem, I used the axes function to get rid of the axes themselves and set the titles to be blank.

    legend(x = 60, y = 50, legend = c("Blue", "Red"), col = c("blue", "red"), pch = c(20, 2))

  • Adding a pretty legend to round out the project

This way may be a bit longer than the pretty ggplots but I did not want to learn something completely new today, hope this helps someone!

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.

How to move (and overwrite) all files from one directory to another?

It's also possible by using rsync, for example:

rsync -va --delete-after src/ dst/

where:

  • -v, --verbose: increase verbosity
  • -a, --archive: archive mode; equals -rlptgoD (no -H,-A,-X)
  • --delete-after: delete files on the receiving side be done after the transfer has completed

If you've root privileges, prefix with sudo to override potential permission issues.

How to iterate through a String

If you want to use enhanced loop, you can convert the string to charArray

for (char ch : exampleString.toCharArray()) {
  System.out.println(ch);
}

CSS display:table-row does not expand when width is set to 100%

If you're using display:table-row etc., then you need proper markup, which includes a containing table. Without it your original question basically provides the equivalent bad markup of:

<tr style="width:100%">
    <td>Type</td>
    <td style="float:right">Name</td>
</tr>

Where's the table in the above? You can't just have a row out of nowhere (tr must be contained in either table, thead, tbody, etc.)

Instead, add an outer element with display:table, put the 100% width on the containing element. The two inside cells will automatically go 50/50 and align the text right on the second cell. Forget floats with table elements. It'll cause so many headaches.

markup:

<div class="view-table">
    <div class="view-row">
        <div class="view-type">Type</div>
        <div class="view-name">Name</div>                
    </div>
</div>

CSS:

.view-table
{
    display:table;
    width:100%;
}
.view-row,
{
    display:table-row;
}
.view-row > div
{
    display: table-cell;
}
.view-name 
{
    text-align:right;
}

How to find most common elements of a list?

To just return a list containing the most common words:

from collections import Counter
words=["i", "love", "you", "i", "you", "a", "are", "you", "you", "fine", "green"]
most_common_words= [word for word, word_count in Counter(words).most_common(3)]
print most_common_words

this prints:

['you', 'i', 'a']

the 3 in "most_common(3)", specifies the number of items to print. Counter(words).most_common() returns a a list of tuples with each tuple having the word as the first member and the frequency as the second member.The tuples are ordered by the frequency of the word.

`most_common = [item for item in Counter(words).most_common()]
print(str(most_common))
[('you', 4), ('i', 2), ('a', 1), ('are', 1), ('green', 1), ('love',1), ('fine', 1)]`

"the word for word, word_counter in", extracts only the first member of the tuple.

jQuery UI " $("#datepicker").datepicker is not a function"

Old question - newer version of .NET (4.5.6) - same issue - new answer

Using NuGet

Make sure you have the following installed via NuGet:

  • jQuery
  • AspNet.ScriptManager.jQuery
  • jQuery.UI.Combined
  • AspNet.ScriptManager.jQuery.UI.Combined

Install them from here [ Tools > NuGet Package Manager > Manage NuGet Packages for Solution ]

Then, jquery and jquery.ui.combined should be added to your ScriptManager in Site.Master. Will look something like this:

    <asp:ScriptManager runat="server">
        <Scripts>
            <%--To learn more about bundling scripts in ScriptManager see https://go.microsoft.com/fwlink/?LinkID=301884 --%>
            <%--Framework Scripts--%>
            <asp:ScriptReference Name="MsAjaxBundle" />
            <asp:ScriptReference Name="jquery" />
            <asp:ScriptReference Name="jquery.ui.combined" />
            <asp:ScriptReference Name="bootstrap" />
            <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />
            <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
            <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
            <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />
            <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />
            <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />
            <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />
            <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />
            <asp:ScriptReference Name="WebFormsBundle" />
            <%--Site Scripts--%>
        </Scripts>
    </asp:ScriptManager>

This solved my same issue. Thank you.

Can't Autowire @Repository annotated interface in Spring Boot

I had a similar problem but with a different cause:

In my case the problem was that in the interface defining the repository

public interface ItemRepository extends Repository {..}

I was omitting the types of the template. Setting them right:

public interface ItemRepository extends Repository<Item,Long> {..}

did the trick.

jQuery: keyPress Backspace won't fire?

Use keyup instead of keypress. This gets all the key codes when the user presses something

Jenkins/Hudson - accessing the current build number?

BUILD_NUMBER is the current build number. You can use it in the command you execute for the job, or just use it in the script your job executes.

See the Jenkins documentation for the full list of available environment variables. The list is also available from within your Jenkins instance at http://hostname/jenkins/env-vars.html.

What does -> mean in C++?

x->y can mean 2 things. If x is a pointer, then it means member y of object pointed to by x. If x is an object with operator->() overloaded, then it means x.operator->().

What is context in _.each(list, iterator, [context])?

Simple use of _.each

_x000D_
_x000D_
_.each(['Hello', 'World!'], function(word){_x000D_
    console.log(word);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

Here's simple example that could use _.each:

_x000D_
_x000D_
function basket() {_x000D_
    this.items = [];_x000D_
    this.addItem = function(item) {_x000D_
        this.items.push(item);_x000D_
    };_x000D_
    this.show = function() {_x000D_
        console.log('items: ', this.items);_x000D_
    }_x000D_
}_x000D_
_x000D_
var x = new basket();_x000D_
x.addItem('banana');_x000D_
x.addItem('apple');_x000D_
x.addItem('kiwi');_x000D_
x.show();
_x000D_
_x000D_
_x000D_

Output:

items:  [ 'banana', 'apple', 'kiwi' ]

Instead of calling addItem multiple times you could use underscore this way:

_.each(['banana', 'apple', 'kiwi'], function(item) { x.addItem(item); });

which is identical to calling addItem three times sequentially with these items. Basically it iterates your array and for each item calls your anonymous callback function that calls x.addItem(item). The anonymous callback function is similar to addItem member function (e.g. it takes an item) and is kind of pointless. So, instead of going through anonymous function it's better that _.each avoids this indirection and calls addItem directly:

_.each(['banana', 'apple', 'kiwi'], x.addItem);

but this won't work, as inside basket's addItem member function this won't refer to your x basket that you created. That's why you have an option to pass your basket x to be used as [context]:

_.each(['banana', 'apple', 'kiwi'], x.addItem, x);

Full example that uses _.each and context:

_x000D_
_x000D_
function basket() {_x000D_
    this.items = [];_x000D_
    this.addItem = function(item) {_x000D_
        this.items.push(item);_x000D_
    };_x000D_
    this.show = function() {_x000D_
        console.log('items: ', this.items);_x000D_
    }_x000D_
}_x000D_
var x = new basket();_x000D_
_.each(['banana', 'apple', 'kiwi'], x.addItem, x);_x000D_
x.show();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

In short, if callback function that you pass to _.each in any way uses this then you need to specify what this should be referring to inside your callback function. It may seem like x is redundant in my example, but x.addItem is just a function and could be totally unrelated to x or basket or any other object, for example:

_x000D_
_x000D_
function basket() {_x000D_
    this.items = [];_x000D_
    this.show = function() {_x000D_
        console.log('items: ', this.items);_x000D_
    }_x000D_
}_x000D_
function addItem(item) {_x000D_
    this.items.push(item);_x000D_
};_x000D_
_x000D_
var x = new basket();_x000D_
_.each(['banana', 'apple', 'kiwi'], addItem, x);_x000D_
x.show();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

In other words, you bind some value to this inside your callback, or you may as well use bind directly like this:

_.each(['banana', 'apple', 'kiwi'], addItem.bind(x));

how this feature can be useful with some different underscore methods?

In general, if some underscorejs method takes a callback function and if you want that callback be called on some member function of some object (e.g. a function that uses this) then you may bind that function to some object or pass that object as the [context] parameter and that's the primary intention. And at the top of underscorejs documentation, that's exactly what they state: The iteratee is bound to the context object, if one is passed

Removing carriage return and new-line from the end of a string in c#

If there's always a single CRLF, then:

myString = myString.Substring(0, myString.Length - 2);

If it may or may not have it, then:

Regex re = new Regex("\r\n$");
re.Replace(myString, "");

Both of these (by design), will remove at most a single CRLF. Cache the regex for performance.

How to use EditText onTextChanged event when I press the number?

Here, I wrote something similar to what u need:

    inputBoxNumberEt.setText(".     ");
    inputBoxNumberEt.setSelection(inputBoxNumberEt.getText().length());
    inputBoxNumberEt.addTextChangedListener(new TextWatcher() {

        boolean ignoreChange = false;

        @Override
        public void afterTextChanged(Editable s) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start,
                                      int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start,
                                  int before, int count) {
            if (!ignoreChange) {
                String string = s.toString();
                string = string.replace(".", "");
                string = string.replace(" ", "");
                if (string.length() == 0)
                    string = ".     ";
                else if (string.length() == 1)
                    string = ".  " + string;
                else if (string.length() == 2)
                    string = "." + string;
                else if (string.length() > 2)
                    string = string.substring(0, string.length() - 2) + "." + string.substring(string.length() - 2, string.length());
                ignoreChange = true;
                inputBoxNumberEt.setText(string);
                inputBoxNumberEt.setSelection(inputBoxNumberEt.getText().length());
                ignoreChange = false;
            }
        }
    });

Map a 2D array onto a 1D array

As other have said C maps in row order

   #include <stdio.h>

   int main(int argc, char **argv) {
   int i, j, k;
   int arr[5][3];
   int *arr2 = (int*)arr;

       for (k=0; k<15; k++) {
          arr2[k] = k;
          printf("arr[%d] = %2d\n", k, arr2[k]);
       }

       for (i=0; i<5; i++) {
         for (j=0; j< 3; j++) {
            printf("arr2[%d][%d] = %2d\n", i, j ,arr[i][j]);
         }
       } 
    } 

Output:

arr[0] =  0
arr[1] =  1
arr[2] =  2
arr[3] =  3
arr[4] =  4
arr[5] =  5
arr[6] =  6
arr[7] =  7
arr[8] =  8
arr[9] =  9
arr[10] = 10
arr[11] = 11
arr[12] = 12
arr[13] = 13
arr[14] = 14
arr2[0][0] =  0
arr2[0][1] =  1
arr2[0][2] =  2
arr2[1][0] =  3
arr2[1][1] =  4
arr2[1][2] =  5
arr2[2][0] =  6
arr2[2][1] =  7
arr2[2][2] =  8
arr2[3][0] =  9
arr2[3][1] = 10
arr2[3][2] = 11
arr2[4][0] = 12
arr2[4][1] = 13
arr2[4][2] = 14

Getting key with maximum value in dictionary?

max(stats, key=stats.get) if stats else None

stats can be an empty dictionary as well and max(stats, key=stats.get) will break in that situation.

Shrink to fit content in flexbox, or flex-basis: content workaround?

It turns out that it was shrinking and growing correctly, providing the desired behaviour all along; except that in all current browsers flexbox wasn't accounting for the vertical scrollbar! Which is why the content appears to be getting cut off.

You can see here, which is the original code I was using before I added the fixed widths, that it looks like the column isn't growing to accomodate the text:

http://jsfiddle.net/2w157dyL/1/

However if you make the content in that column wider, you'll see that it always cuts it off by the same amount, which is the width of the scrollbar.

So the fix is very, very simple - add enough right padding to account for the scrollbar:

http://jsfiddle.net/2w157dyL/2/

_x000D_
_x000D_
  main > section {_x000D_
    overflow-y: auto;_x000D_
    padding-right: 2em;_x000D_
  }
_x000D_
_x000D_
_x000D_

It was when I was trying some things suggested by Michael_B (specifically adding a padding buffer) that I discovered this, thanks so much!

Edit: I see that he also posted a fiddle which does the same thing - again, thanks so much for all your help

How to access static resources when mapping a global front controller servlet on /*

'Static' files in App Engine aren't directly accessible by your app. You either need to upload them twice, or serve the static files yourself, rather than using a static handler.

Missing Microsoft RDLC Report Designer in Visual Studio

If you did a custom installation you need to add Microsoft Sql Server Data Tools. After that you can add Reportviwer to your webform.

How to disable all <input > inside a form with jQuery?

You can do it like this:

//HTML BUTTON
<button type="button" onclick="disableAll()">Disable</button>

//Jquery function
function disableAll() {
    //DISABLE ALL FIELDS THAT ARE NOT DISABLED
    $('form').find(':input:not(:disabled)').prop('disabled', true);

    //ENABLE ALL FIELDS THAT DISABLED
    //$('form').find(':input(:disabled)').prop('disabled', false);
}

How to make an alert dialog fill 90% of screen size?

Above many of the answers are good but none of the worked for me fully. So i combined the answer from @nmr and got this one.

final Dialog d = new Dialog(getActivity());
        //  d.getWindow().setBackgroundDrawable(R.color.action_bar_bg);
        d.requestWindowFeature(Window.FEATURE_NO_TITLE);
        d.setContentView(R.layout.dialog_box_shipment_detail);

        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE); // for activity use context instead of getActivity()
        Display display = wm.getDefaultDisplay(); // getting the screen size of device
        Point size = new Point();
        display.getSize(size);
        int width = size.x - 20;  // Set your heights
        int height = size.y - 80; // set your widths

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(d.getWindow().getAttributes());

        lp.width = width;
        lp.height = height;

        d.getWindow().setAttributes(lp);
        d.show();

jQuery - Appending a div to body, the body is the object?

Instead use use appendTo. append or appendTo returns a jQuery object so you don't have to wrap it inside $().

var holdyDiv = $('<div />').appendTo('body');
holdyDiv.attr('id', 'holdy');

.appendTo() reference: http://api.jquery.com/appendTo/

Alernatively you can try this also.

$('<div />', { id: 'holdy' }).appendTo('body');
               ^
             (Here you can specify any attribute/value pair you want)

How is the default submit button on an HTML form determined?

<form onsubmit="alert('submit');return false;">
    <input name="username">
    <input name="password" type="password">
    <button onclick="if(document.activeElement === this){alert('button 1');}else{default_submit.click();}return false;">button 1</button>
    <button onclick="if(document.activeElement === this){alert('button 2');}else{default_submit.click();}return false;">button 2</button>
    <input id="default_submit" type="submit">
</form>

if you press enter from text input, then the button will not focused, then we ignore this click and click the default submit instead, but if you click the button by mouse, it will be focused, then we apply this click

Using LINQ to concatenate strings

Here is the combined Join/Linq approach I settled on after looking at the other answers and the issues addressed in a similar question (namely that Aggregate and Concatenate fail with 0 elements).

string Result = String.Join(",", split.Select(s => s.Name));

or (if s is not a string)

string Result = String.Join(",", split.Select(s => s.ToString()));

  • Simple
  • easy to read and understand
  • works for generic elements
  • allows using objects or object properties
  • handles the case of 0-length elements
  • could be used with additional Linq filtering
  • performs well (at least in my experience)
  • doesn't require (manual) creation of an additional object (e.g. StringBuilder) to implement

And of course Join takes care of the pesky final comma that sometimes sneaks into other approaches (for, foreach), which is why I was looking for a Linq solution in the first place.

how to use the Box-Cox power transformation in R

If I want tranfer only the response variable y instead of a linear model with x specified, eg I wanna transfer/normalize a list of data, I can take 1 for x, then the object becomes a linear model:

library(MASS)
y = rf(500,30,30)
hist(y,breaks = 12)
result = boxcox(y~1, lambda = seq(-5,5,0.5))
mylambda = result$x[which.max(result$y)]
mylambda
y2 = (y^mylambda-1)/mylambda
hist(y2)

Auto-increment on partial primary key with Entity Framework Core

Specifying the column type as serial for PostgreSQL to generate the id.

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(Order=1, TypeName="serial")]
public int ID { get; set; }

https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL

QtCreator: No valid kits found

Though OP is asking about Windows, this error also occurs on Ubuntu Linux and Google lists this result first when you search for the error"QtCreator: No valid kits found".

On Ubuntu this is solved by running:

For Qt5:

sudo apt-get install qt5-default

For Qt4:

sudo apt-get install qt4-dev-tools libqt4-dev libqt4-core libqt4-gui

This question is answered here and here, though those entries are less SEO-friendly...

How to set image in circle in swift

All the answers above couldn't solve the problem in my case. My ImageView was placed in a customized UITableViewCell. Therefore I had also call the layoutIfNeeded() method from here. Example:

 class NameTableViewCell:UITableViewCell,UITextFieldDelegate { ...

 override func awakeFromNib() {

    self.layoutIfNeeded()
    profileImageView.layoutIfNeeded()

    profileImageView.isUserInteractionEnabled = true
    let square = profileImageView.frame.size.width < profileImageView.frame.height ? CGSize(width: profileImageView.frame.size.width, height: profileImageView.frame.size.width) : CGSize(width: profileImageView.frame.size.height, height:  profileImageView.frame.size.height)
    profileImageView.addGestureRecognizer(tapGesture)
    profileImageView.layer.cornerRadius = square.width/2
    profileImageView.clipsToBounds = true;
}

Logging POST data from $request_body

Try echo_read_request_body.

"echo_read_request_body ... Explicitly reads request body so that the $request_body variable will always have non-empty values (unless the body is so big that it has been saved by Nginx to a local temporary file)."

location /log {
  log_format postdata $request_body;
  access_log /mnt/logs/nginx/my_tracking.access.log postdata;
  echo_read_request_body;
}

IndentationError expected an indented block

You should install a editor (or IDE) supporting Python syntax. It can highlight source code and make basic format checking. For example: Eric4, Spyder, Ninjia, or Emacs, Vi.

How (and why) to use display: table-cell (CSS)

After days trying to find the answer, I finally found

display: table;

There was surprisingly very little information available online about how to actually getting it to work, even here, so on to the "How":

To use this fantastic piece of code, you need to think back to when tables were the only real way to structure HTML, namely the syntax. To get a table with 2 rows and 3 columns, you'd have to do the following:

<table>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>

Similarly to get CSS to do it, you'd use the following:

HTML

<div id="table">
    <div class="tr">
        <div class="td"></div>
        <div class="td"></div>
        <div class="td"></div>
    </div>
    <div class="tr">
        <div class="td"></div>
        <div class="td"></div>
        <div class="td"></div>
    </div>
</div>

CSS

#table{ 
    display: table; 
}
.tr{ 
    display: table-row; 
}
.td{ 
    display: table-cell; }

As you can see in the JSFiddle example below, the divs in the 3rd column have no content, yet are respecting the auto height set by the text in the first 2 columns. WIN!

http://jsfiddle.net/blyzz/1djs97yv/1/

It's worth noting that display: table; does not work in IE6 or 7 (thanks, FelipeAls), so depending on your needs with regards to browser compatibility, this may not be the answer that you are seeking.

parse html string with jquery

I'm not a 100% sure, but won't

$(data)

produce a jquery object with a DOM for that data, not connected anywhere? Or if it's already parsed as a DOM, you could just go $("#myImg", data), or whatever selector suits your needs.

EDIT
Rereading your question it appears your 'data' is already a DOM, which means you could just go (assuming there's only an img in your DOM, otherwise you'll need a more precise selector)

$("img", data).attr ("src")

if you want to access the src-attribute. If your data is just text, it would probably work to do

$("img", $(data)).attr ("src")

Format LocalDateTime with Timezone in Java8

LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"));

Python: convert string to byte array

s = "ABCD"
from array import array
a = array("B", s)

If you want hex:

print map(hex, a)

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

$out.='<option value="'.$key.'">'.$value["name"];

me funciono con esta

"<a  href='javascript:void(0)' onclick='cargar_datos_cliente(\"$row->DSC_EST\")' class='button micro asignar margin-none'>Editar</a>";

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

I was facing the same kind of issue, your version numbers in the dependency of Selenium, TestNG, Junit should the same that you have used in your project. For example, in your project you are using the Selenium version 3.8. This version number should be mentioned in the dependency.

 <dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.0.0-beta1</version>
    <scope>test</scope>
</dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.8.1</version>
    </dependency>       
    <dependency>                
      <groupId>org.testng</groupId>                             
      <artifactId>testng</artifactId>                               
      <version>6.8</version>                                
      <scope>test</scope>                                       
    </dependency>   
  </dependencies>

SQL select statements with multiple tables

select P.*,
A.Street,
A.City,
A.State
from Preson P
inner join Address A on P.id=A.Person_id
where A.Zip=97229
Order by A.Street,A.City,A.State

Run batch file from Java code

import java.lang.Runtime;

Process run = Runtime.getRuntime().exec("cmd.exe", "/c", "Start", "path of the bat file");

This will work for you and is easy to use.

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

As Nayan said the Path has to updated properly in my case the apache-maven was installed in C:\apache-maven and settings.xml was found inside C:\apache-maven\conf\settings.xml

if this doesn't work go to your local repos
in my case C:\Users\<<"name">>.m2\
and search for .lastUpdated and delete them
then build the maven

Change / Add syntax highlighting for a language in Sublime 2/3

This is my recipe

Note: This isn't exactly what OP is asking. These instructions will help you change the colors of items (comments, keywords, etc) that are defined syntax matching rules. For example, use these instructions to change so that all code comments are colored blue instead of green.

I believe the OP is asking how to define this as an item to be colored when found in a JavaScript source file.

  1. Install Package: PackageResourceViewer

  2. Ctrl+Shift+P > [PackageResourceViewer: Open Resource] > [Color Scheme - Default] > [Marina.sublime-color-scheme] (or whichever color scheme you use)

  3. The above command will open a new tab to the file "Marina.sublime-color-scheme".

    • For me, this file was located in my roaming profile %appdata% (C:\Users\walter\AppData\Roaming\Sublime Text 3\Packages\Color Scheme - Default\) .
    • However, if I browse to that path in Windows Explorer, [Color Scheme - Default] is not of a child-dir of [Packages] dir. I suspect that PackageResourceViewer is doing some virtualization.

optional step: On the new color-scheme tab: Ctrl+Shift+P > [Set Syntax: JSON]

  1. Search for the rule you want to change. I wanted to make comments be move visible, so I searched for "Comment"

    • I found it in the "rules" section
 "rules":
    [
        {
            "name": "Comment",
            "scope": "comment, punctuation.definition.comment",
            "foreground": "var(blue6)"
        },
  1. Search for the string "blue6": to find the color variable definitions section. I found it in the "variables" section.

  2. Pick a new color using a tool like http://hslpicker.com/ .

  3. Either define a new color variable, or overwrite the color setting for blue6.

    • Warning: overwriting blue6 will affect all other text-elements in that color scheme which also use blue6 ("Punctuation" "Accessor").
  4. Save your file, the changes will be applied instantly to any open files/tabs.

NOTES

Sublime will handle any of these color styles. Possibly more.

hsla = hue, saturation, lightness, alpha rgba = red, green, blue, alpha

hsla(151, 100%, 41%, 1) - last param is the alpha level (transparency) 1 = opaque, 0.5 = half-transparent, 0 = full-transparent

hsl(151, 100%, 41%) - no alpha channel

rgba(0, 209, 108, 1) - rgb with an alpha channel

rgb(0, 209, 108) - no alpha channel

What is the difference between an IntentService and a Service?

Service

  • Task with no UI,but should not use for long Task. Use Thread within service for long Task
  • Invoke by onStartService()
  • Triggered from any Thread
  • Runs On Main Thread
  • May block main(UI) thread

IntentService

  • Long task usually no communication with main thread if communication is needed then it is done by Handler or broadcast
  • Invoke via Intent
  • triggered from Main Thread (Intent is received on main Thread and worker thread is spawned)
  • Runs on separate thread
  • We can't run task in parallel and multiple intents are Queued on the same worker thread.

Iif equivalent in C#

booleanExpression ? trueValue : falseValue;

Example:

string itemText = count > 1 ? "items" : "item";

http://zamirsblog.blogspot.com/2011/12/c-vb-equivalent-of-iif.html

How do I dynamically change the content in an iframe using jquery?

If you just want to change where the iframe points to and not the actual content inside the iframe, you would just need to change the src attribute.

 $("#myiframe").attr("src", "newwebpage.html");

Instagram API: How to get all user media?

You can user pagination of Instagram PHP API: https://github.com/cosenary/Instagram-PHP-API/wiki/Using-Pagination

Something like that:

    $Instagram = new MetzWeb\Instagram\Instagram(array(
        "apiKey"      => IG_APP_KEY,
        "apiSecret"   => IG_APP_SECRET,
        "apiCallback" => IG_APP_CALLBACK
    ));
    $Instagram->setSignedHeader(true);

    $pictures = $Instagram->getUserMedia(123);
    do {

        foreach ($pictures->data as $picture_data):

            echo '<img src="'.$picture_data->images->low_resolution->url.'">';

        endforeach;

    } while ($pictures = $instagram->pagination($pictures));

Convert wchar_t to char

Here's another way of doing it, remember to use free() on the result.

char* wchar_to_char(const wchar_t* pwchar)
{
    // get the number of characters in the string.
    int currentCharIndex = 0;
    char currentChar = pwchar[currentCharIndex];

    while (currentChar != '\0')
    {
        currentCharIndex++;
        currentChar = pwchar[currentCharIndex];
    }

    const int charCount = currentCharIndex + 1;

    // allocate a new block of memory size char (1 byte) instead of wide char (2 bytes)
    char* filePathC = (char*)malloc(sizeof(char) * charCount);

    for (int i = 0; i < charCount; i++)
    {
        // convert to char (1 byte)
        char character = pwchar[i];

        *filePathC = character;

        filePathC += sizeof(char);

    }
    filePathC += '\0';

    filePathC -= (sizeof(char) * charCount);

    return filePathC;
}

Stylesheet not updating

I ran into this problem too, a lot of people seem to recommend force reloading your page, which won't fix the issue in cases such as if you're running it on a server. I believe the optimal solution in this scenario is to timestamp your css.

  1. This is how I do it in my Django template:

<link rel="stylesheet" href="{% static 'home/radioStyles.css' %}?{% now 'U' %}" type="text/css"/>

Where adding ?{% now 'U' %} to the end of your css file would fix this issue.

  1. How you would do it with just CSS (hopefully someone edits this to a cleaner version, this looks a little janky but it does work, tested it):

<link rel="stylesheet" type="text/css" href="style.css?Wednesday 2nd February 2020 12PM" />

Where ?Wednesday 2nd February 2020 12PM (current date) seems to fix the issue, I also noticed just putting the time fixes it too.

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

Multi-statement Table Valued Function vs Inline Table Valued Function

Internally, SQL Server treats an inline table valued function much like it would a view and treats a multi-statement table valued function similar to how it would a stored procedure.

When an inline table-valued function is used as part of an outer query, the query processor expands the UDF definition and generates an execution plan that accesses the underlying objects, using the indexes on these objects.

For a multi-statement table valued function, an execution plan is created for the function itself and stored in the execution plan cache (once the function has been executed the first time). If multi-statement table valued functions are used as part of larger queries then the optimiser does not know what the function returns, and so makes some standard assumptions - in effect it assumes that the function will return a single row, and that the returns of the function will be accessed by using a table scan against a table with a single row.

Where multi-statement table valued functions can perform poorly is when they return a large number of rows and are joined against in outer queries. The performance issues are primarily down to the fact that the optimiser will produce a plan assuming that a single row is returned, which will not necessarily be the most appropriate plan.

As a general rule of thumb we have found that where possible inline table valued functions should be used in preference to multi-statement ones (when the UDF will be used as part of an outer query) due to these potential performance issues.

When does System.gc() do something?

Most JVMs will kick off a GC (depending on the -XX:DiableExplicitGC and -XX:+ExplicitGCInvokesConcurrent switch). But the specification is just less well defined in order to allow better implementations later on.

The spec needs clarification: Bug #6668279: (spec) System.gc() should indicate that we don't recommend use and don't guarantee behaviour

Internally the gc method is used by RMI and NIO, and they require synchronous execution, which: this is currently in discussion:

Bug #5025281: Allow System.gc() to trigger concurrent (not stop-the-world) full collections

What is the C# equivalent of NaN or IsNumeric?

In addition to the previous correct answers it is probably worth pointing out that "Not a Number" (NaN) in its general usage is not equivalent to a string that cannot be evaluated as a numeric value. NaN is usually understood as a numeric value used to represent the result of an "impossible" calculation - where the result is undefined. In this respect I would say the Javascript usage is slightly misleading. In C# NaN is defined as a property of the single and double numeric types and is used to refer explicitly to the result of diving zero by zero. Other languages use it to represent different "impossible" values.

Remove spaces from std::string in C++

I'm afraid it's the best solution that I can think of. But you can use reserve() to pre-allocate the minimum required memory in advance to speed up things a bit. You'll end up with a new string that will probably be shorter but that takes up the same amount of memory, but you'll avoid reallocations.

EDIT: Depending on your situation, this may incur less overhead than jumbling characters around.

You should try different approaches and see what is best for you: you might not have any performance issues at all.

What determines the monitor my app runs on?

Right click the shortcut and select properties. Make sure you are on the "Shortcut" Tab. Select the RUN drop down box and change it to Maximized.

This may assist in launching the program in full screen on the primary monitor.

How can I do GUI programming in C?

This is guaranteed to have nothing to do with the compiler. All compilers do is compile the code that they are given. What you're looking for is a GUI library, which you can write code against using any compiler that you want.

Of course, that being said, your first order of business should be to ditch Turbo C. That compiler is about 20 years old and continuing to use it isn't doing you any favors. You can't write modern GUI applications, as it will only produce 16-bit code. All modern operating systems are 32-bit, and many are now 64-bit. It's also worth noting that 64-bit editions of Windows will not run 16-bit applications natively. You'll need an emulator for that; it's not really going to engender much feeling of accomplishment if you can only write apps that work in a DOS emulator. :-)

Microsoft's Visual Studio Express C++ is available as a free download. It includes the same compiler available in the full version of the suite. The C++ package also compiles pure C code.

And since you're working in Windows, the Windows API is a natural choice. It allows you to write native Windows applications that have access to the full set of GUI controls. You'll find a nice tutorial here on writing WinAPI applications in C. If you choose to go with Visual Studio, it also includes boilerplate code for a blank WinAPI application that will get you up and running quickly.

If you really care about learning to do this, Charles Petzold's Programming Windows is the canonical resource of the subject, and definitely worth a read. The entire Windows API was written in C, and it's entirely possible to write full-featured Windows applications in C. You don't need no stinkin' C++.

That's the way I'd do it, at least. As the other answers suggest, GTK is also an option. But the applications it generates are just downright horrible-looking on Windows.


EDIT: Oh dear... It looks like you're not alone in wanting to write "GUI" applications using an antiquated compiler. A Google search turns up the following library: TurboGUI: A GUI Framework for Turbo C/C++:

 TurboGUI interface sample

If you're another one of those poor people stuck in the hopelessly out-of-date Indian school system and forced to use Turbo C to complete your education, this might be an option. I'm loathe to recommend it, as learning to work around its limitations will be completely useless to you once you graduate, but apparently it's out there for you if you're interested.

How to get WordPress post featured image URL

Check the code below and let me know if it works for you.

<?php if (has_post_thumbnail( $post->ID ) ): ?>
  <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
  <div id="custom-bg" style="background-image: url('<?php echo $image[0]; ?>')">

  </div>
<?php endif; ?>

Explanation of BASE terminology

It has to do with BASE: the BASE jumper kind is always Basically Available (to new relationships), in a Soft state (none of his relationship last very long) and Eventually consistent (one day he will get married).

Send FormData with other field in AngularJS

You're sending JSON-formatted data to a server which isn't expecting that format. You already provided the format that the server needs, so you'll need to format it yourself which is pretty simple.

var data = '"title='+title+'" "text='+text+'" "file='+file+'"';
$http.post(uploadUrl, data)

Procedure or function !!! has too many arguments specified

For those who might have the same problem as me, I got this error when the DB I was using was actually master, and not the DB I should have been using.

Just put use [DBName] on the top of your script, or manually change the DB in use in the SQL Server Management Studio GUI.

Eclipse error: indirectly referenced from required .class files?

This is as likely a matter of Eclipse's getting confused as it is an actual error. I ignored the error and ran the web service whose endpointInterface it complained about, and it ran fine, except for having to deal with the dialog every time I wanted to run it. Just another opaque error that tells me nothing.

Invalid date in safari

This will not work alert(new Date('2010-11-29')); safari have some weird/strict way of processing date format alert(new Date(String('2010-11-29'))); try like this.

(Or)

Using Moment js will solve the issue though, After ios 14 the safari gets even weird

Try this alert(moment(String("2015-12-31 00:00:00")));

Moment JS

How to terminate a window in tmux?

If you just want to do it once, without adding a shortcut, you can always type

<prefix> 
:
kill-window
<enter>

String's Maximum length in Java - calling length() method

java.io.DataInput.readUTF() and java.io.DataOutput.writeUTF(String) say that a String object is represented by two bytes of length information and the modified UTF-8 representation of every character in the string. This concludes that the length of String is limited by the number of bytes of the modified UTF-8 representation of the string when used with DataInput and DataOutput.

In addition, The specification of CONSTANT_Utf8_info found in the Java virtual machine specification defines the structure as follows.

CONSTANT_Utf8_info {
    u1 tag;
    u2 length;
    u1 bytes[length];
}

You can find that the size of 'length' is two bytes.

That the return type of a certain method (e.g. String.length()) is int does not always mean that its allowed maximum value is Integer.MAX_VALUE. Instead, in most cases, int is chosen just for performance reasons. The Java language specification says that integers whose size is smaller than that of int are converted to int before calculation (if my memory serves me correctly) and it is one reason to choose int when there is no special reason.

The maximum length at compilation time is at most 65536. Note again that the length is the number of bytes of the modified UTF-8 representation, not the number of characters in a String object.

String objects may be able to have much more characters at runtime. However, if you want to use String objects with DataInput and DataOutput interfaces, it is better to avoid using too long String objects. I found this limitation when I implemented Objective-C equivalents of DataInput.readUTF() and DataOutput.writeUTF(String).

Selecting the last value of a column

Regarding @Jon_Schneider's comment, if the column has blank cells just use COUNTA()

=INDEX(G2:G; COUNT**A**(G2:G))

How to get a product's image in Magento?

If you have the product collection object like:

$collection = Mage::getModel('catalog/product')->getCollection(); 

Now you can get product sku using $_product->getSku() if you can't get image path with

echo $this->helper('catalog/image')->init($_product,'small_image')->resize(135);

Or

$_product->getImageUrl();

Then you can add a little code

$productModel = Mage::getModel('catalog/product');
$_prod = $productModel->loadByAttribute('sku', $_product->getSku()); 
$_prod->getImageUrl();

How to study design patterns?

Ask yourself these questions:

What do they do?

What do they decouple/couple?

When should you use them?

When should you not use them?

What missing language feature would make them go away?

What technical debt do you incur by using it?

Is there a simpler way to get the job done?

tar: Error is not recoverable: exiting now

Try to get your archive using wget, I had the same issue when I was downloading archive through browser. Than I just copy archive link and in terminal use the command:

wget http://PATH_TO_ARCHIVE

How to edit the legend entry of a chart in Excel?

There are 3 ways to do this:

1. Define the Series names directly

Right-click on the Chart and click Select Data then edit the series names directly as shown below.

enter image description here

You can either specify the values directly e.g. Series 1 or specify a range e.g. =A2

enter image description here

2. Create a chart defining upfront the series and axis labels

Simply select your data range (in similar format as I specified) and create a simple bar chart. The labels should be defined automatically. enter image description here

3. Define the legend (series names) using VBA

Similarly you can define the series names dynamically using VBA. A simple example below:

ActiveChart.ChartArea.Select
ActiveChart.FullSeriesCollection(1).Name = "=""Hello"""

This will redefine the first series name. Just change the index from (1) to e.g. (2) and so on to change the following series names. What does the VBA above do? It sets the series name to Hello as "=""Hello""" translates to ="Hello" (" have to be escaped by a preceding ").

REST URI convention - Singular or plural name of resource while creating it

How about:

/resource/ (not /resource)

/resource/ means it's a folder contains something called "resource", it's a "resouce" folder.

And also I think the naming convention of database tables is the same, for example, a table called 'user' is a "user table", it contains something called "user".

Easy way to write contents of a Java InputStream to an OutputStream

I think this will work, but make sure to test it... minor "improvement", but it might be a bit of a cost at readability.

byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
    out.write(buffer, 0, len);
}

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

I too faced the same issue.

Follow the below step to solve the issue on (CORS) compliance in browsers.

Include REDRock in your solution with the Cors reference. Include WebActivatorEx reference to Web API solution.

Then Add the file CorsConfig in the Web API App_Start Folder.

[assembly: PreApplicationStartMethod(typeof(WebApiNamespace.CorsConfig), "PreStart")]

namespace WebApiNamespace
{
    public static class CorsConfig
    {
        public static void PreStart()
        {
            GlobalConfiguration.Configuration.MessageHandlers.Add(new RedRocket.WebApi.Cors.CorsHandler());
        }
    }
}

With these changes done i was able to access the webapi in all browsers.

Python: Get the first character of the first string in a list?

Indexing in python starting from 0. You wrote [1:] this would not return you a first char in any case - this will return you a rest(except first char) of string.

If you have the following structure:

mylist = ['base', 'sample', 'test']

And want to get fist char for the first one string(item):

myList[0][0]
>>> b

If all first chars:

[x[0] for x in myList]
>>> ['b', 's', 't']    

If you have a text:

text = 'base sample test'
text.split()[0][0]
>>> b

ng-if check if array is empty

post.capabilities.items will still be defined because it's an empty array, if you check post.capabilities.items.length it should work fine because 0 is falsy.

Is it a good practice to use try-except-else in Python?

OP, YOU ARE CORRECT. The else after try/except in Python is ugly. it leads to another flow-control object where none is needed:

try:
    x = blah()
except:
    print "failed at blah()"
else:
    print "just succeeded with blah"

A totally clear equivalent is:

try:
    x = blah()
    print "just succeeded with blah"
except:
    print "failed at blah()"

This is far clearer than an else clause. The else after try/except is not frequently written, so it takes a moment to figure what the implications are.

Just because you CAN do a thing, doesn't mean you SHOULD do a thing.

Lots of features have been added to languages because someone thought it might come in handy. Trouble is, the more features, the less clear and obvious things are because people don't usually use those bells and whistles.

Just my 5 cents here. I have to come along behind and clean up a lot of code written by 1st-year out of college developers who think they're smart and want to write code in some uber-tight, uber-efficient way when that just makes it a mess to try and read / modify later. I vote for readability every day and twice on Sundays.

How do I see the extensions loaded by PHP?

You asked where do you see loaded extensions in phpinfo() output.

Answer:

They are listed towards the bottom as separate sections/tables and ONLY if they are loaded. Here is an example of extension Curl loaded.

enter image description here ...

... enter image description here

I installed it on Linux Debian with

sudo apt-get install php7.4-curl

How to detect a route change in Angular?

In angular 6 and RxJS6:

import { filter, debounceTime } from 'rxjs/operators';

 this.router.events.pipe(
      filter((event) => event instanceof NavigationEnd),
      debounceTime(40000)
    ).subscribe(
      x => {
      console.log('val',x);
      this.router.navigate(['/']); /*Redirect to Home*/
}
)

Waiting until the task finishes

Use DispatchGroups to achieve this. You can either get notified when the group's enter() and leave() calls are balanced:

func myFunction() {
    var a: Int?

    let group = DispatchGroup()
    group.enter()

    DispatchQueue.main.async {
        a = 1
        group.leave()
    }

    // does not wait. But the code in notify() gets run 
    // after enter() and leave() calls are balanced

    group.notify(queue: .main) {
        print(a)
    }
}

or you can wait:

func myFunction() {
    var a: Int?

    let group = DispatchGroup()
    group.enter()

    // avoid deadlocks by not using .main queue here
    DispatchQueue.global(attributes: .qosDefault).async {
        a = 1
        group.leave()
    }

    // wait ...
    group.wait()

    print(a) // you could also `return a` here
}

Note: group.wait() blocks the current queue (probably the main queue in your case), so you have to dispatch.async on another queue (like in the above sample code) to avoid a deadlock.

Maven: How to rename the war file for the project?

Lookup pom.xml > project tag > build tag.

I would like solution below.

<artifactId>bird</artifactId>
<name>bird</name>

<build>
    ...
    <finalName>${project.artifactId}</finalName>
  OR
    <finalName>${project.name}</finalName>
    ...
</build>

Worked for me. ^^

htaccess <Directory> deny from all

You can use from root directory:

RewriteEngine On
RewriteRule ^(?:system)\b.* /403.html

Or:

RewriteRule ^(?:system)\b.* /403.php # with header('HTTP/1.0 403 Forbidden');

Convert month name to month number in SQL Server

You can do it this way, if you have the date (e.g. SubmittedDate)

DATENAME(MONTH,DATEADD(MONTH, MONTH(SubmittedDate) - 1, 0)) AS ColumnDisplayMonth

Or you can do it this way, if you have the month as an int

DATENAME(MONTH,DATEADD(MONTH, @monthInt - 1, 0)) AS ColumnDisplayMonth

Aesthetics must either be length one, or the same length as the dataProblems

The problem is that skew isn't being subsetted in colour=factor(skew), so it's the wrong length. Since subset(skew, product == 'p1') is the same as subset(skew, product == 'p3'), in this case it doesn't matter which subset is used. So you can solve your problem with:

p1 <- ggplot(df, aes(x=subset(price, product=='p1'),
                     y=subset(price, product=='p3'),
                     colour=factor(subset(skew, product == 'p1')))) +
              geom_point(size=2, shape=19)

Note that most R users would write this as the more concise:

p1 <- ggplot(df, aes(x=price[product=='p1'],
                     y=price[product=='p3'],
                     colour=factor(skew[product == 'p1']))) +
              geom_point(size=2, shape=19)

How do I check the difference, in seconds, between two dates?

import time  
current = time.time()

...job...
end = time.time()
diff = end - current

would that work for you?

Div Size Automatically size of content

As far as I know, display: inline-block is what you probably need. That will make it seem like it's sort of inline but still allow you to use things like margins and such.

Hidden Features of C#?

A couple of things I like:

-If you create an interface similar to

 public interface SomeObject<T> where T : SomeObject<T>, new()

you force anything that inherits from this interface to contain a parameterless constructor. It is very useful for a couple of things I've run across.

-Using anonymous types to create a useful object on the fly:

var myAwesomeObject = new {Name="Foo", Size=10};

-Finally, many Java developers are familiar with syntax like:

public synchronized void MySynchronizedMethod(){}

However, in C# this is not valid syntax. The workaround is a method attribute:

 [MethodImpl(MethodImplOptions.Synchronized)]
 public void MySynchronizedMethod(){}

How can I split and parse a string in Python?

"2.7.0_bf4fda703454".split("_") gives a list of strings:

In [1]: "2.7.0_bf4fda703454".split("_")
Out[1]: ['2.7.0', 'bf4fda703454']

This splits the string at every underscore. If you want it to stop after the first split, use "2.7.0_bf4fda703454".split("_", 1).

If you know for a fact that the string contains an underscore, you can even unpack the LHS and RHS into separate variables:

In [8]: lhs, rhs = "2.7.0_bf4fda703454".split("_", 1)

In [9]: lhs
Out[9]: '2.7.0'

In [10]: rhs
Out[10]: 'bf4fda703454'

An alternative is to use partition(). The usage is similar to the last example, except that it returns three components instead of two. The principal advantage is that this method doesn't fail if the string doesn't contain the separator.

cannot convert data (type interface {}) to type string: need type assertion

As asked for by @??s???? an explanation can be found at https://golang.org/pkg/fmt/#Sprint. Related explanations can be found at https://stackoverflow.com/a/44027953/12817546 and at https://stackoverflow.com/a/42302709/12817546. Here is @Yuanbo's answer in full.

package main

import "fmt"

func main() {
    var data interface{} = 2
    str := fmt.Sprint(data)
    fmt.Println(str)
}

Updating Python on Mac

Echoing above on not messing with OS X install. Have been faced with a couple of reinstalls thinking I could beat the system. The 3.1 install Scott Griffiths offers above works fine with Yosemite, for any Beta testers out there.. Yosemite has Python 2.7.6 as part of OS install, and typing "python3.1" from terminal launches Python 3.1. Same for Python 3.4 (install here).

How to change value for innodb_buffer_pool_size in MySQL on Mac OS?

As stated,

innodb_buffer_pool_size=50M

Following the convention on the other predefined variables, make sure there is no space either side of the equals sign.

Then run

sudo service mysqld stop
sudo service mysqld start

Note

Sometimes, e.g. on Ubuntu, the MySQL daemon is named mysql as opposed to mysqld

I find that running /etc/init.d/mysqld restart doesn't always work and you may get an error like

Stopping mysqld:                                           [FAILED]
Starting mysqld:                                           [  OK  ]

To see if the variable has been set, run show variables and see if the value has been updated.

When to Redis? When to MongoDB?

If your project budged allows you to have enough RAM memory on your environment - answer is Redis. Especially taking in account new Redis 3.2 with cluster functionality.

What is the minimum length of a valid international phone number?

The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).

Illegal character in path at index 16

I ran into the same thing with the Bing Map API. URLEncoder just made things worse, but a replaceAll(" ","%20"); did the trick.

jQuery select box validation

Jquery Select Box Validation.You can Alert Message via alert or Put message in Div as per your requirements.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="message"></div>_x000D_
<form method="post">_x000D_
<select name="year"  id="year">_x000D_
    <option value="0">Year</option>_x000D_
    <option value="1">1919</option>_x000D_
    <option value="2">1920</option>_x000D_
    <option value="3">1921</option>_x000D_
    <option value="4">1922</option>_x000D_
</select>_x000D_
<button id="clickme">Click</button>_x000D_
</form>_x000D_
<script>_x000D_
$("#clickme").click(function(){_x000D_
_x000D_
if( $("#year option:selected").val()=='0'){_x000D_
_x000D_
alert("Please select one option at least");_x000D_
_x000D_
  $("#message").html("Select At least one option");_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
});_x000D_
_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

Here are some real-world examples of the types of relationships:

One-to-one (1:1)

A relationship is one-to-one if and only if one record from table A is related to a maximum of one record in table B.

To establish a one-to-one relationship, the primary key of table B (with no orphan record) must be the secondary key of table A (with orphan records).

For example:

CREATE TABLE Gov(
    GID number(6) PRIMARY KEY, 
    Name varchar2(25), 
    Address varchar2(30), 
    TermBegin date,
    TermEnd date
); 

CREATE TABLE State(
    SID number(3) PRIMARY KEY,
    StateName varchar2(15),
    Population number(10),
    SGID Number(4) REFERENCES Gov(GID), 
    CONSTRAINT GOV_SDID UNIQUE (SGID)
);

INSERT INTO gov(GID, Name, Address, TermBegin) 
values(110, 'Bob', '123 Any St', '1-Jan-2009');

INSERT INTO STATE values(111, 'Virginia', 2000000, 110);

One-to-many (1:M)

A relationship is one-to-many if and only if one record from table A is related to one or more records in table B. However, one record in table B cannot be related to more than one record in table A.

To establish a one-to-many relationship, the primary key of table A (the "one" table) must be the secondary key of table B (the "many" table).

For example:

CREATE TABLE Vendor(
    VendorNumber number(4) PRIMARY KEY,
    Name varchar2(20),
    Address varchar2(20),
    City varchar2(15),
    Street varchar2(2),
    ZipCode varchar2(10),
    Contact varchar2(16),
    PhoneNumber varchar2(12),
    Status varchar2(8),
    StampDate date
);

CREATE TABLE Inventory(
    Item varchar2(6) PRIMARY KEY,
    Description varchar2(30),
    CurrentQuantity number(4) NOT NULL,
    VendorNumber number(2) REFERENCES Vendor(VendorNumber),
    ReorderQuantity number(3) NOT NULL
);

Many-to-many (M:M)

A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa.

To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.

CREATE TABLE Class(
    ClassID varchar2(10) PRIMARY KEY, 
    Title varchar2(30),
    Instructor varchar2(30), 
    Day varchar2(15), 
    Time varchar2(10)
);

CREATE TABLE Student(
    StudentID varchar2(15) PRIMARY KEY, 
    Name varchar2(35),
    Major varchar2(35), 
    ClassYear varchar2(10), 
    Status varchar2(10)
);  

CREATE TABLE ClassStudentRelation(
    StudentID varchar2(15) NOT NULL,
    ClassID varchar2(14) NOT NULL,
    FOREIGN KEY (StudentID) REFERENCES Student(StudentID), 
    FOREIGN KEY (ClassID) REFERENCES Class(ClassID),
    UNIQUE (StudentID, ClassID)
);

How to get the total number of rows of a GROUP BY query?

The method I ended up using is very simple:

$query = 'SELECT a, b, c FROM tbl WHERE oele = 2 GROUP BY boele';
$nrows = $db->query("SELECT COUNT(1) FROM ($query) x")->fetchColumn();

Might not be the most efficient, but it seems to be foolproof, because it actually counts the original query's results.

Resize image in the wiki of GitHub using Markdown

On GitHub, you can use HTML directly instead of Markdown:

<a href="url"><img src="http://url.to/image.png" align="left" height="48" width="48" ></a>

This should make it.

How to check if an array element exists?

array_key_exists() is SLOW compared to isset(). A combination of these two (see below code) would help.

It takes the performance advantage of isset() while maintaining the correct checking result (i.e. return TRUE even when the array element is NULL)

if (isset($a['element']) || array_key_exists('element', $a)) {
       //the element exists in the array. write your code here.
}

The benchmarking comparison: (extracted from below blog posts).

array_key_exists() only : 205 ms
isset() only : 35ms
isset() || array_key_exists() : 48ms

See http://thinkofdev.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/ and http://thinkofdev.com/php-isset-and-multi-dimentional-array/

for detailed discussion.

What does "Table does not support optimize, doing recreate + analyze instead" mean?

Best option is create new table with same properties

CREATE TABLE <NEW.NAME.TABLE> LIKE <TABLE.CRASHED>;
INSERT INTO <NEW.NAME.TABLE> SELECT * FROM <TABLE.CRASHED>;

Rename NEW.NAME.TABLE and TABLE.CRASH

RENAME TABLE <TABLE.CRASHED> TO <TABLE.CRASHED.BACKUP>;
RENAME TABLE <NEW.NAME.TABLE> TO <TABLE.CRASHED>;

After work well, delete

DROP TABLE <TABLE.CRASHED.BACKUP>;

How to change the background color on a Java panel?

I am assuming that we are dealing with a JFrame? The visible portion in the content pane - you have to use jframe.getContentPane().setBackground(...);

Declaring a boolean in JavaScript using just var

No it is not safe. You could later do var IsLoggedIn = "Foo"; and JavaScript will not throw an error.

It is possible to do

var IsLoggedIn = new Boolean(false);
var IsLoggedIn = new Boolean(true);

You can also pass the non boolean variable into the new Boolean() and it will make IsLoggedIn boolean.

var IsLoggedIn = new Boolean(0); // false
var IsLoggedIn = new Boolean(NaN); // false
var IsLoggedIn = new Boolean("Foo"); // true
var IsLoggedIn = new Boolean(1); // true

Java: Simplest way to get last word in a string

If other whitespace characters are possible, then you'd want:

testString.split("\\s+");

SQL Format as of Round off removing decimals

CAST(Round(MySum * 20.0 /100, 0) AS INT)

FYI

MySum * 20 /100, I get 11

This is because when all 3 operands are INTs, SQL Server will do perform integer maths, from left to right, truncating all intermediate results.

58 * 20 / 100 => 1160 / 100 => 11 (truncated from 11.6)

Also for the record ROUND(m,n) returns the result to n decimal places, not n significant figures.

How to change the colors of a PNG image easily?

This should be fairly straightforward in the gimp http://gimp.org/

First make sure your image is RGB (not indexed color) then use the "color to alpha" feature to turn the clubs/diamonds clear, then fill or set the background or whatever to get the color you want.

Parse HTML in Android

Maybe you can use WebView, but as you can see in the doc WebView doesn't support javascript and other stuff like widgets by default.

http://developer.android.com/reference/android/webkit/WebView.html

I think that you can enable javascript if you need it.

"java.lang.OutOfMemoryError : unable to create new native Thread"

You have a chance to face the java.lang.OutOfMemoryError: Unable to create new native thread whenever the JVM asks for a new thread from the OS. Whenever the underlying OS cannot allocate a new native thread, this OutOfMemoryError will be thrown. The exact limit for native threads is very platform-dependent thus its recommend to find out those limits by running a test similar to the below link example. But, in general, the situation causing java.lang.OutOfMemoryError: Unable to create new native thread goes through the following phases:

  1. A new Java thread is requested by an application running inside the JVM
  2. JVM native code proxies the request to create a new native thread to the OS The OS tries to create a new native thread which requires memory to be allocated to the thread
  3. The OS will refuse native memory allocation either because the 32-bit Java process size has depleted its memory address space – e.g. (2-4) GB process size limit has been hit – or the virtual memory of the OS has been fully depleted
  4. The java.lang.OutOfMemoryError: Unable to create new native thread error is thrown.

Reference: https://plumbr.eu/outofmemoryerror/unable-to-create-new-native-thread

The difference between the Runnable and Callable interfaces in Java

Difference between Callable and Runnable are following:

  1. Callable is introduced in JDK 5.0 but Runnable is introduced in JDK 1.0
  2. Callable has call() method but Runnable has run() method.
  3. Callable has call method which returns value but Runnable has run method which doesn't return any value.
  4. call method can throw checked exception but run method can't throw checked exception.
  5. Callable use submit() method to put in task queue but Runnable use execute() method to put in the task queue.

Best way to overlay an ESRI shapefile on google maps?

Just to update these answers, ESRI has included this tool, known as Layer to KML in ArcMap 10.X. Also, a Map to KML tool exists.

Simply import the desired layer (vector or raster) and choose the output location, resolution, etc. Very simple tool.

Add borders to cells in POI generated Excel File

a Helper function:

private void setRegionBorderWithMedium(CellRangeAddress region, Sheet sheet) {
        Workbook wb = sheet.getWorkbook();
        RegionUtil.setBorderBottom(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderLeft(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderRight(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderTop(CellStyle.BORDER_MEDIUM, region, sheet, wb);
    }

When you want to add Border in Excel, then

String cellAddr="$A$11:$A$17";

setRegionBorderWithMedium(CellRangeAddress.valueOf(cellAddr1), sheet);

onchange event for html.dropdownlist

You can do this

@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem() 
  { 

       Text = "Newest to Oldest", Value = "0" }, new SelectListItem() { Text = "Oldest to Newest", Value = "1" } , new
       {
           onchange = @"form.submit();"
       }
})

How do you properly determine the current script directory?

os.path.dirname(os.path.abspath(__file__))

is indeed the best you're going to get.

It's unusual to be executing a script with exec/execfile; normally you should be using the module infrastructure to load scripts. If you must use these methods, I suggest setting __file__ in the globals you pass to the script so it can read that filename.

There's no other way to get the filename in execed code: as you note, the CWD may be in a completely different place.

How to change the integrated terminal in visual studio code or VSCode

For OP's terminal Cmder there is an integration guide, also hinted in the VS Code docs.

If you want to use VS Code tasks and encounter problems after switch to Cmder, there is an update to @khernand's answer. Copy this into your settings.json file:

"terminal.integrated.shell.windows": "cmd.exe",

"terminal.integrated.env.windows": {
  "CMDER_ROOT": "[cmder_root]" // replace [cmder_root] with your cmder path
},
"terminal.integrated.shellArgs.windows": [
  "/k",
  "%CMDER_ROOT%\\vendor\\bin\\vscode_init.cmd" // <-- this is the relevant change
  // OLD: "%CMDER_ROOT%\\vendor\\init.bat"
],

The invoked file will open Cmder as integrated terminal and switch to cmd for tasks - have a look at the source here. So you can omit configuring a separate terminal in tasks.json to make tasks work.

Starting with VS Code 1.38, there is also "terminal.integrated.automationShell.windows" setting, which lets you set your terminal for tasks globally and avoids issues with Cmder.

"terminal.integrated.automationShell.windows": "cmd.exe"

Built in Python hash() function

This is the hash function that Google uses in production for python 2.5:

def c_mul(a, b):
  return eval(hex((long(a) * b) & (2**64 - 1))[:-1])

def py25hash(self):
  if not self:
    return 0 # empty
  value = ord(self[0]) << 7
  for char in self:
    value = c_mul(1000003, value) ^ ord(char)
  value = value ^ len(self)
  if value == -1:
    value = -2
  if value >= 2**63:
    value -= 2**64
  return value

Blocking device rotation on mobile web pages

You could use the screenSize.width and screenSize.height properties and detect when the width > height and then handle that situation, either by letting the user know or by adjusting your screen accordingly.

But the best solution is what @Doozer1979 says... Why would you override what the user prefers?

How to find and replace string?

like some say boost::replace_all

here a dummy example:

    #include <boost/algorithm/string/replace.hpp>

    std::string path("file.gz");
    boost::replace_all(path, ".gz", ".zip");

How to parse data in JSON format?

Very simple:

import json
data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print data['two']

Using the RUN instruction in a Dockerfile with 'source' does not work

You might want to run bash -v to see what's being sourced.

I would do the following instead of playing with symlinks:

RUN echo "source /usr/local/bin/virtualenvwrapper.sh" >> /etc/bash.bashrc