问:
Clear typeahead after onSelect
I have used typeahead on my project and is working ok.  Now, I have created a list so that a selection from typehead will be added into that list.  That is working fine as well.  Problem is after adding the selected item to the list, I have to manually delete the previous selection from the input.  .val("") apparently doesn't work on typeahead.

Here is my code:

```<code>var $songlist = $('#song-list tr'),
        $counter = 1,
        $typeahead = $('input.typeahead');

    $typeahead.typeahead({
        ajax: "{{ url('/admin/music/typeahead') }}",
        onSelect:function(item) {
            //console.log(item);
            $songlist.append("<td>"+
                    $counter + '. ' + item.text +
                "</td>"
            );
           $typeahead.val(''); // -> does not work
        }
    });
</code>```

答:
Edit typeahead.js,  find the below code and replace :

this.$element
  .val(this.updater(text))
  .change();

with an empty string like  :

this.$element
  .val(this.updater(' '))
  .change();

as I've shown in following code

```<code>Typeahead.prototype = {
        constructor: Typeahead,
        //=============================================================================================================
        //  Utils
        //  Check if an event is supported by the browser eg. 'keypress'
        //  * This was included to handle the "exhaustive deprecation" of jQuery.browser in jQuery 1.8
        //=============================================================================================================
        eventSupported: function (eventName) {
            var isSupported = (eventName in this.$element);

            if (!isSupported) {
                this.$element.setAttribute(eventName, 'return;');
                isSupported = typeof this.$element[eventName] === 'function';
            }

            return isSupported;
        },
        select: function () {
            var $selectedItem = this.$menu.find('.active');
            if($selectedItem.length) {
                var value = $selectedItem.attr('data-value');
                var text = this.$menu.find('.active a').text();

                if (this.options.onSelect) {
                    this.options.onSelect({
                        value: value,
                        text: text
                    });
                }
                this.$element
                    .val(this.updater(text)) //here you need to pass empty string
                    .change();
            }
            return this.hide();
        },
        updater: function (item) {
            return item;
        },
        show: function () {
            var pos = $.extend({}, this.$element.position(), {
                height: this.$element[0].offsetHeight
            });

            this.$menu.css({
                top: pos.top + pos.height,
                left: pos.left
            });

            if(this.options.alignWidth) {
                var width = $(this.$element[0]).outerWidth();
                this.$menu.css({
                    width: width
                });
            }

            this.$menu.show();
            this.shown = true;
            return this;
        },
        hide: function () {
            this.$menu.hide();
            this.shown = false;
            return this;
        },
        ajaxLookup: function () {

            var query = $.trim(this.$element.val());

            if (query === this.query) {
                return this;
            }

            // Query changed
            this.query = query;

            // Cancel last timer if set
            if (this.ajax.timerId) {
                clearTimeout(this.ajax.timerId);
                this.ajax.timerId = null;
            }

            if (!query || query.length < this.ajax.triggerLength) {
                // cancel the ajax callback if in progress
                if (this.ajax.xhr) {
                    this.ajax.xhr.abort();
                    this.ajax.xhr = null;
                    this.ajaxToggleLoadClass(false);
                }

                return this.shown ? this.hide() : this;
            }

            function execute() {
                this.ajaxToggleLoadClass(true);

                // Cancel last call if already in progress
                if (this.ajax.xhr)
                    this.ajax.xhr.abort();

                var params = this.ajax.preDispatch ? this.ajax.preDispatch(query) : {
                    query: query
                };
                this.ajax.xhr = $.ajax({
                    url: this.ajax.url,
                    data: params,
                    success: $.proxy(this.ajaxSource, this),
                    type: this.ajax.method || 'get',
                    dataType: 'json'
                });
                this.ajax.timerId = null;
            }

            // Query is good to send, set a timer
            this.ajax.timerId = setTimeout($.proxy(execute, this), this.ajax.timeout);

            return this;
        },
        ajaxSource: function (data) {
            this.ajaxToggleLoadClass(false);
            var that = this, items;
            if (!that.ajax.xhr)
                return;
            if (that.ajax.preProcess) {
                data = that.ajax.preProcess(data);
            }
            // Save for selection retreival
            that.ajax.data = data;

            // Manipulate objects
            items = that.grepper(that.ajax.data) || [];
            if (!items.length) {
                return that.shown ? that.hide() : that;
            }

            that.ajax.xhr = null;
            return that.render(items.slice(0, that.options.items)).show();
        },
        ajaxToggleLoadClass: function (enable) {
            if (!this.ajax.loadingClass)
                return;
            this.$element.toggleClass(this.ajax.loadingClass, enable);
        },
        lookup: function (event) {
            var that = this, items;
            if (that.ajax) {
                that.ajaxer();
            }
            else {
                that.query = that.$element.val();

                if (!that.query) {
                    return that.shown ? that.hide() : that;
                }

                items = that.grepper(that.source);

                if (!items) {
                    return that.shown ? that.hide() : that;
                }
                //Bhanu added a custom message- Result not Found when no result is found
                if (items.length == 0) {
                    items[0] = {'id': -21, 'name': "Result not Found"}
                }
                return that.render(items.slice(0, that.options.items)).show();
            }
        },
        matcher: function (item) {
            return ~item.toLowerCase().indexOf(this.query.toLowerCase());
        },
        sorter: function (items) {
            if (!this.options.ajax) {
                var beginswith = [],
                    caseSensitive = [],
                    caseInsensitive = [],
                    item;

                while (item = items.shift()) {
                    if (!item.toLowerCase().indexOf(this.query.toLowerCase()))
                        beginswith.push(item);
                    else if (~item.indexOf(this.query))
                        caseSensitive.push(item);
                    else
                        caseInsensitive.push(item);
                }

                return beginswith.concat(caseSensitive, caseInsensitive);
            } else {
                return items;
            }
        },
        highlighter: function (item) {
            var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
            if (item != undefined)
                return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
                    return '<strong>' + match + '</strong>';
                });
            else
                return 'No matches found!';
        },
        render: function (items) {
            var that = this, display, isString = typeof that.options.displayField === 'string';

            items = $(items).map(function (i, item) {
                if (typeof item === 'object') {
                    display = isString ? item[that.options.displayField] : that.options.displayField(item);
                    i = $(that.options.item).attr('data-value', item[that.options.valueField]);
                } else {
                    display = item;
                    i = $(that.options.item).attr('data-value', item);
                }
                i.find('a').html(that.highlighter(display));
                return i[0];
            });

            if(that.autoSelect){
                items.first().addClass('active');
            }

            this.$menu.html(items);
            return this;
        },
        //------------------------------------------------------------------
        //  Filters relevent results
        //
        grepper: function (data) {
            var that = this, items, display, isString = typeof that.options.displayField === 'string';

            if (isString && data && data.length) {
                if (data[0].hasOwnProperty(that.options.displayField)) {
                    items = $.grep(data, function (item) {
                        display = isString ? item[that.options.displayField] : that.options.displayField(item);
                        return that.matcher(display);
                    });
                } else if (typeof data[0] === 'string') {
                    items = $.grep(data, function (item) {
                        return that.matcher(item);
                    });
                } else {
                    return null;
                }
            } else {
                return null;
            }
            return this.sorter(items);
        },
        next: function (event) {
            var active = this.$menu.find('.active').removeClass('active'),
                next = active.next();

            if (!next.length) {
                next = $(this.$menu.find('li')[0]);
            }

            if (this.options.scrollBar) {
                var index = this.$menu.children("li").index(next);
                if (index % 8 == 0) {
                    this.$menu.scrollTop(index * 26);
                }
            }

            next.addClass('active');
        },
        prev: function (event) {
            var active = this.$menu.find('.active').removeClass('active'),
                prev = active.prev();

            if (!prev.length) {
                prev = this.$menu.find('li').last();
            }

            if (this.options.scrollBar) {

                var $li = this.$menu.children("li");
                var total = $li.length - 1;
                var index = $li.index(prev);

                if ((total - index) % 8 == 0) {
                    this.$menu.scrollTop((index - 7) * 26);
                }

            }

            prev.addClass('active');

        },
        listen: function () {
            this.$element
                .on('focus', $.proxy(this.focus, this))
                .on('blur', $.proxy(this.blur, this))
                .on('keypress', $.proxy(this.keypress, this))
                .on('keyup', $.proxy(this.keyup, this));

            if (this.eventSupported('keydown')) {
                this.$element.on('keydown', $.proxy(this.keydown, this))
            }

            this.$menu
                .on('click', $.proxy(this.click, this))
                .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
                .on('mouseleave', 'li', $.proxy(this.mouseleave, this))
        },
        move: function (e) {
            if (!this.shown)
                return

            switch (e.keyCode) {
                case 9: // tab
                case 13: // enter
                case 27: // escape
                    e.preventDefault();
                    break

                case 38: // up arrow
                    e.preventDefault()
                    this.prev()
                    break

                case 40: // down arrow
                    e.preventDefault()
                    this.next()
                    break
            }

            e.stopPropagation();
        },
        keydown: function (e) {
            this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40, 38, 9, 13, 27])
            this.move(e)
        },
        keypress: function (e) {
            if (this.suppressKeyPressRepeat)
                return
            this.move(e)
        },
        keyup: function (e) {
            switch (e.keyCode) {
                case 40: // down arrow
                case 38: // up arrow
                case 16: // shift
                case 17: // ctrl
                case 18: // alt
                    break

                case 9: // tab
                case 13: // enter
                    if (!this.shown)
                        return
                    this.select()
                    break

                case 27: // escape
                    if (!this.shown)
                        return
                    this.hide()
                    break

                default:
                    if (this.ajax)
                        this.ajaxLookup()
                    else
                        this.lookup()
            }

            e.stopPropagation()
            e.preventDefault()
        },
        focus: function (e) {
            this.focused = true
        },
        blur: function (e) {
            this.focused = false
            if (!this.mousedover && this.shown)
                this.hide()
        },
        click: function (e) {
            e.stopPropagation()
            e.preventDefault()
            this.select()
            this.$element.focus()
        },
        mouseenter: function (e) {
            this.mousedover = true
            this.$menu.find('.active').removeClass('active')
            $(e.currentTarget).addClass('active')
        },
        mouseleave: function (e) {
            this.mousedover = false
            if (!this.focused && this.shown)
                this.hide()
        },
        destroy: function() {
            this.$element
                .off('focus', $.proxy(this.focus, this))
                .off('blur', $.proxy(this.blur, this))
                .off('keypress', $.proxy(this.keypress, this))
                .off('keyup', $.proxy(this.keyup, this));

            if (this.eventSupported('keydown')) {
                this.$element.off('keydown', $.proxy(this.keydown, this))
            }

            this.$menu
                .off('click', $.proxy(this.click, this))
                .off('mouseenter', 'li', $.proxy(this.mouseenter, this))
                .off('mouseleave', 'li', $.proxy(this.mouseleave, this))
            this.$element.removeData('typeahead');
        }
    };`enter code here`
</code>```

Title: Clear typeahead after onSelect

Body:
I have used typeahead on my project and is working ok.  Now, I have created a list so that a selection from typehead will be added into that list.  That is working fine as well.  Problem is after adding the selected item to the list, I have to manually delete the previous selection from the input.  .val("") apparently doesn't work on typeahead.

Here is my code:

var $songlist = $('#song-list tr'),
        $counter = 1,
        $typeahead = $('input.typeahead');

    $typeahead.typeahead({
        ajax: "{{ url('/admin/music/typeahead') }}",
        onSelect:function(item) {
            //console.log(item);
            $songlist.append(""+
                    $counter + '. ' + item.text +
                "	"
            );
           $typeahead.val(''); // -> does not work
        }
    });

Body:
Edit typeahead.js,  find the below code and replace :

this.$element
  .val(this.updater(text))
  .change();

with an empty string like  :

this.$element
  .val(this.updater(' '))
  .change();

as I've shown in following code

Typeahead.prototype = {
        constructor: Typeahead,
        //=============================================================================================================
        //  Utils
        //  Check if an event is supported by the browser eg. 'keypress'
        //  * This was included to handle the "exhaustive deprecation" of jQuery.browser in jQuery 1.8
        //=============================================================================================================
        eventSupported: function (eventName) {
            var isSupported = (eventName in this.$element);

            if (!isSupported) {
                this.$element.setAttribute(eventName, 'return;');
                isSupported = typeof this.$element[eventName] === 'function';
            }

            return isSupported;
        },
        select: function () {
            var $selectedItem = this.$menu.find('.active');
            if($selectedItem.length) {
                var value = $selectedItem.attr('data-value');
                var text = this.$menu.find('.active a').text();

                if (this.options.onSelect) {
                    this.options.onSelect({
                        value: value,
                        text: text
                    });
                }
                this.$element
                    .val(this.updater(text)) //here you need to pass empty string
                    .change();
            }
            return this.hide();
        },
        updater: function (item) {
            return item;
        },
        show: function () {
            var pos = $.extend({}, this.$element.position(), {
                height: this.$element[0].offsetHeight
            });

            this.$menu.css({
                top: pos.top + pos.height,
                left: pos.left
            });

            if(this.options.alignWidth) {
                var width = $(this.$element[0]).outerWidth();
                this.$menu.css({
                    width: width
                });
            }

            this.$menu.show();
            this.shown = true;
            return this;
        },
        hide: function () {
            this.$menu.hide();
            this.shown = false;
            return this;
        },
        ajaxLookup: function () {

            var query = $.trim(this.$element.val());

            if (query === this.query) {
                return this;
            }

            // Query changed
            this.query = query;

            // Cancel last timer if set
            if (this.ajax.timerId) {
                clearTimeout(this.ajax.timerId);
                this.ajax.timerId = null;
            }

            if (!query || query.length < this.ajax.triggerLength) {
                // cancel the ajax callback if in progress
                if (this.ajax.xhr) {
                    this.ajax.xhr.abort();
                    this.ajax.xhr = null;
                    this.ajaxToggleLoadClass(false);
                }

                return this.shown ? this.hide() : this;
            }

            function execute() {
                this.ajaxToggleLoadClass(true);

                // Cancel last call if already in progress
                if (this.ajax.xhr)
                    this.ajax.xhr.abort();

                var params = this.ajax.preDispatch ? this.ajax.preDispatch(query) : {
                    query: query
                };
                this.ajax.xhr = $.ajax({
                    url: this.ajax.url,
                    data: params,
                    success: $.proxy(this.ajaxSource, this),
                    type: this.ajax.method || 'get',
                    dataType: 'json'
                });
                this.ajax.timerId = null;
            }

            // Query is good to send, set a timer
            this.ajax.timerId = setTimeout($.proxy(execute, this), this.ajax.timeout);

            return this;
        },
        ajaxSource: function (data) {
            this.ajaxToggleLoadClass(false);
            var that = this, items;
            if (!that.ajax.xhr)
                return;
            if (that.ajax.preProcess) {
                data = that.ajax.preProcess(data);
            }
            // Save for selection retreival
            that.ajax.data = data;

            // Manipulate objects
            items = that.grepper(that.ajax.data) || [];
            if (!items.length) {
                return that.shown ? that.hide() : that;
            }

            that.ajax.xhr = null;
            return that.render(items.slice(0, that.options.items)).show();
        },
        ajaxToggleLoadClass: function (enable) {
            if (!this.ajax.loadingClass)
                return;
            this.$element.toggleClass(this.ajax.loadingClass, enable);
        },
        lookup: function (event) {
            var that = this, items;
            if (that.ajax) {
                that.ajaxer();
            }
            else {
                that.query = that.$element.val();

                if (!that.query) {
                    return that.shown ? that.hide() : that;
                }

                items = that.grepper(that.source);

                if (!items) {
                    return that.shown ? that.hide() : that;
                }
                //Bhanu added a custom message- Result not Found when no result is found
                if (items.length == 0) {
                    items[0] = {'id': -21, 'name': "Result not Found"}
                }
                return that.render(items.slice(0, that.options.items)).show();
            }
        },
        matcher: function (item) {
            return ~item.toLowerCase().indexOf(this.query.toLowerCase());
        },
        sorter: function (items) {
            if (!this.options.ajax) {
                var beginswith = [],
                    caseSensitive = [],
                    caseInsensitive = [],
                    item;

                while (item = items.shift()) {
                    if (!item.toLowerCase().indexOf(this.query.toLowerCase()))
                        beginswith.push(item);
                    else if (~item.indexOf(this.query))
                        caseSensitive.push(item);
                    else
                        caseInsensitive.push(item);
                }

                return beginswith.concat(caseSensitive, caseInsensitive);
            } else {
                return items;
            }
        },
        highlighter: function (item) {
            var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
            if (item != undefined)
                return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
                    return '<strong>' + match + '</strong>';
                });
            else
                return 'No matches found!';
        },
        render: function (items) {
            var that = this, display, isString = typeof that.options.displayField === 'string';

            items = $(items).map(function (i, item) {
                if (typeof item === 'object') {
                    display = isString ? item[that.options.displayField] : that.options.displayField(item);
                    i = $(that.options.item).attr('data-value', item[that.options.valueField]);
                } else {
                    display = item;
                    i = $(that.options.item).attr('data-value', item);
                }
                i.find('a').html(that.highlighter(display));
                return i[0];
            });

            if(that.autoSelect){
                items.first().addClass('active');
            }

            this.$menu.html(items);
            return this;
        },
        //------------------------------------------------------------------
        //  Filters relevent results
        //
        grepper: function (data) {
            var that = this, items, display, isString = typeof that.options.displayField === 'string';

            if (isString && data && data.length) {
                if (data[0].hasOwnProperty(that.options.displayField)) {
                    items = $.grep(data, function (item) {
                        display = isString ? item[that.options.displayField] : that.options.displayField(item);
                        return that.matcher(display);
                    });
                } else if (typeof data[0] === 'string') {
                    items = $.grep(data, function (item) {
                        return that.matcher(item);
                    });
                } else {
                    return null;
                }
            } else {
                return null;
            }
            return this.sorter(items);
        },
        next: function (event) {
            var active = this.$menu.find('.active').removeClass('active'),
                next = active.next();

            if (!next.length) {
                next = $(this.$menu.find('li')[0]);
            }

            if (this.options.scrollBar) {
                var index = this.$menu.children("li").index(next);
                if (index % 8 == 0) {
                    this.$menu.scrollTop(index * 26);
                }
            }

            next.addClass('active');
        },
        prev: function (event) {
            var active = this.$menu.find('.active').removeClass('active'),
                prev = active.prev();

            if (!prev.length) {
                prev = this.$menu.find('li').last();
            }

            if (this.options.scrollBar) {

                var $li = this.$menu.children("li");
                var total = $li.length - 1;
                var index = $li.index(prev);

                if ((total - index) % 8 == 0) {
                    this.$menu.scrollTop((index - 7) * 26);
                }

            }

            prev.addClass('active');

        },
        listen: function () {
            this.$element
                .on('focus', $.proxy(this.focus, this))
                .on('blur', $.proxy(this.blur, this))
                .on('keypress', $.proxy(this.keypress, this))
                .on('keyup', $.proxy(this.keyup, this));

            if (this.eventSupported('keydown')) {
                this.$element.on('keydown', $.proxy(this.keydown, this))
            }

            this.$menu
                .on('click', $.proxy(this.click, this))
                .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
                .on('mouseleave', 'li', $.proxy(this.mouseleave, this))
        },
        move: function (e) {
            if (!this.shown)
                return

            switch (e.keyCode) {
                case 9: // tab
                case 13: // enter
                case 27: // escape
                    e.preventDefault();
                    break

                case 38: // up arrow
                    e.preventDefault()
                    this.prev()
                    break

                case 40: // down arrow
                    e.preventDefault()
                    this.next()
                    break
            }

            e.stopPropagation();
        },
        keydown: function (e) {
            this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40, 38, 9, 13, 27])
            this.move(e)
        },
        keypress: function (e) {
            if (this.suppressKeyPressRepeat)
                return
            this.move(e)
        },
        keyup: function (e) {
            switch (e.keyCode) {
                case 40: // down arrow
                case 38: // up arrow
                case 16: // shift
                case 17: // ctrl
                case 18: // alt
                    break

                case 9: // tab
                case 13: // enter
                    if (!this.shown)
                        return
                    this.select()
                    break

                case 27: // escape
                    if (!this.shown)
                        return
                    this.hide()
                    break

                default:
                    if (this.ajax)
                        this.ajaxLookup()
                    else
                        this.lookup()
            }

            e.stopPropagation()
            e.preventDefault()
        },
        focus: function (e) {
            this.focused = true
        },
        blur: function (e) {
            this.focused = false
            if (!this.mousedover && this.shown)
                this.hide()
        },
        click: function (e) {
            e.stopPropagation()
            e.preventDefault()
            this.select()
            this.$element.focus()
        },
        mouseenter: function (e) {
            this.mousedover = true
            this.$menu.find('.active').removeClass('active')
            $(e.currentTarget).addClass('active')
        },
        mouseleave: function (e) {
            this.mousedover = false
            if (!this.focused && this.shown)
                this.hide()
        },
        destroy: function() {
            this.$element
                .off('focus', $.proxy(this.focus, this))
                .off('blur', $.proxy(this.blur, this))
                .off('keypress', $.proxy(this.keypress, this))
                .off('keyup', $.proxy(this.keyup, this));

            if (this.eventSupported('keydown')) {
                this.$element.off('keydown', $.proxy(this.keydown, this))
            }

            this.$menu
                .off('click', $.proxy(this.click, this))
                .off('mouseenter', 'li', $.proxy(this.mouseenter, this))
                .off('mouseleave', 'li', $.proxy(this.mouseleave, this))
            this.$element.removeData('typeahead');
        }
    };`enter code here`


来源: stackexchange

问:
Want to get content of a span on amazon.de
I will get a the text of a span on https://www.amazon.de/

I tried like that

```<code>$('.a-spacing-top-extra-large:first').text();
</code>```

and much other things, but every time i get this error.

```<code>VM186:211 Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '.a-spacing-top-extra-large:first' is not a valid selector.(…)
</code>```

I tried much things, with jquery or javascript but all the time same error.
On other sites this code works

I know that there are other guys who have a worked code but i dont find a way...

I want to get it with jquery or javascript

答:
Amazon doesn't use the jQuery library which is why your script is not working.

If you wanted to select that node using plain JavaScript you would use something like this document.getElementsByClassName("a-spacing-top-extra-large")[0].textContent

ContentLicense: CC BY-SA 3.0

Body:
I will get a the text of a span on https://www.amazon.de/

I tried like that

$('.a-spacing-top-extra-large:first').text();

and much other things, but every time i get this error.

VM186:211 Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '.a-spacing-top-extra-large:first' is not a valid selector.(…)

I tried much things, with jquery or javascript but all the time same error.
On other sites this code works

I know that there are other guys who have a worked code but i dont find a way...

I want to get it with jquery or javascript


问:
Numpy: how to convert observations to probabilities?
I have a feature matrix and a corresponding targets, which are ones or zeroes:

```<code># raw observations
features = np.array([[1, 1, 0],
                     [1, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 0, 1]])

targets = np.array([1, 0, 1, 1, 0, 0])
</code>```

As you can see, each feature may correspond to both ones and zeros. I need to convert my raw observation matrix to probability matrix, where each feature will correspond to the probability of seeing one as  a target:

```<code>[1 1 0] -> 0.5
[0 1 0] -> 0.67
[0 0 1] -> 0
</code>```

I have constructed a quite straight-forward solution:

```<code>import numpy as np

# raw observations
features = np.array([[1, 1, 0],
                     [1, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 0, 1]])

targets = np.array([1, 0, 1, 1, 0, 0])

from collections import Counter

def convert_obs_to_proba(features, targets):
    features_ = []
    targets_ = []

    # compute unique rows (idx will point to some representative)
    b = np.ascontiguousarray(features).view(np.dtype((np.void, features.dtype.itemsize * features.shape[1])))
    _, idx = np.unique(b, return_index=True)

    idx = idx[::-1]

    zeros = Counter()
    ones = Counter()

    # collect row-wise number of one and zero targets
    for i, row in enumerate(features[:]):
        if targets[i] == 0:
            zeros[tuple(row)] += 1
        else:
            ones[tuple(row)] += 1

    # iterate over unique features and compute probabilities
    for k in idx:
        unique_row = features[k]

        zero_count = zeros[tuple(unique_row)]
        one_count = ones[tuple(unique_row)]

        proba = float(one_count) / float(zero_count + one_count)

        features_.append(unique_row)
        targets_.append(proba)

    return np.array(features_), np.array(targets_)

features_, targets_ = convert_obs_to_proba(features, targets)

print(features_)
print(targets_)
</code>```

which:

extracts unique features;

counts number of zero and one observations targets for each unique feature;

computes probability and constructs the result.

Could it be solved in a prettier way using some advanced numpy magic?

Update. Previous code was pretty inefficient O(n^2). Converted it to more performance-friendly. Old code:

```<code>import numpy as np

# raw observations
features = np.array([[1, 1, 0],
                     [1, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 0, 1]])

targets = np.array([1, 0, 1, 1, 0, 0])

def convert_obs_to_proba(features, targets):
    features_ = []
    targets_ = []

    # compute unique rows (idx will point to some representative)
    b = np.ascontiguousarray(features).view(np.dtype((np.void, features.dtype.itemsize * features.shape[1])))
    _, idx = np.unique(b, return_index=True)

    idx = idx[::-1]

    # calculate ZERO class occurences and ONE class occurences
    for k in idx:
        unique_row = features[k]

        zeros = 0
        ones = 0

        for i, row in enumerate(features[:]):
            if np.array_equal(row, unique_row):
                if targets[i] == 0:
                    zeros += 1
                else:
                    ones += 1

        proba = float(ones) / float(zeros + ones)

        features_.append(unique_row)
        targets_.append(proba)

    return np.array(features_), np.array(targets_)

features_, targets_ = convert_obs_to_proba(features, targets)

print(features_)
print(targets_)
</code>```

答:
It's easy using Pandas:

```<code>df = pd.DataFrame(features)
df['targets'] = targets
</code>```

Now you have:

```<code>   0  1  2  targets
0  1  1  0        1
1  1  1  0        0
2  0  1  0        1
3  0  1  0        1
4  0  1  0        0
5  0  0  1        0
</code>```

Now, the fancy part:

```<code>df.groupby([0,1,2]).targets.mean()
</code>```

Gives you:

```<code>0  1  2
0  0  1    0.000000
   1  0    0.666667
1  1  0    0.500000
Name: targets, dtype: float64
</code>```

Pandas doesn't print the 0 at the leftmost part of the 0.666 row, but if you inspect the value there, it is indeed 0.

Body:
I have a feature matrix and a corresponding targets, which are ones or zeroes:

# raw observations
features = np.array([[1, 1, 0],
                     [1, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 0, 1]])

targets = np.array([1, 0, 1, 1, 0, 0])

As you can see, each feature may correspond to both ones and zeros. I need to convert my raw observation matrix to probability matrix, where each feature will correspond to the probability of seeing one as  a target:

[1 1 0] -> 0.5
[0 1 0] -> 0.67
[0 0 1] -> 0

I have constructed a quite straight-forward solution:

import numpy as np

# raw observations
features = np.array([[1, 1, 0],
                     [1, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 0, 1]])

targets = np.array([1, 0, 1, 1, 0, 0])

from collections import Counter

def convert_obs_to_proba(features, targets):
    features_ = []
    targets_ = []

    # compute unique rows (idx will point to some representative)
    b = np.ascontiguousarray(features).view(np.dtype((np.void, features.dtype.itemsize * features.shape[1])))
    _, idx = np.unique(b, return_index=True)

    idx = idx[::-1]

    zeros = Counter()
    ones = Counter()

    # collect row-wise number of one and zero targets
    for i, row in enumerate(features[:]):
        if targets[i] == 0:
            zeros[tuple(row)] += 1
        else:
            ones[tuple(row)] += 1

    # iterate over unique features and compute probabilities
    for k in idx:
        unique_row = features[k]

        zero_count = zeros[tuple(unique_row)]
        one_count = ones[tuple(unique_row)]

        proba = float(one_count) / float(zero_count + one_count)

        features_.append(unique_row)
        targets_.append(proba)

    return np.array(features_), np.array(targets_)

features_, targets_ = convert_obs_to_proba(features, targets)

print(features_)
print(targets_)

which:

extracts unique features;

counts number of zero and one observations targets for each unique feature;

computes probability and constructs the result.

Could it be solved in a prettier way using some advanced numpy magic?

Update. Previous code was pretty inefficient O(n^2). Converted it to more performance-friendly. Old code:

import numpy as np

# raw observations
features = np.array([[1, 1, 0],
                     [1, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 0, 1]])

targets = np.array([1, 0, 1, 1, 0, 0])

def convert_obs_to_proba(features, targets):
    features_ = []
    targets_ = []

    # compute unique rows (idx will point to some representative)
    b = np.ascontiguousarray(features).view(np.dtype((np.void, features.dtype.itemsize * features.shape[1])))
    _, idx = np.unique(b, return_index=True)

    idx = idx[::-1]

    # calculate ZERO class occurences and ONE class occurences
    for k in idx:
        unique_row = features[k]

        zeros = 0
        ones = 0

        for i, row in enumerate(features[:]):
            if np.array_equal(row, unique_row):
                if targets[i] == 0:
                    zeros += 1
                else:
                    ones += 1

        proba = float(ones) / float(zeros + ones)

        features_.append(unique_row)
        targets_.append(proba)

    return np.array(features_), np.array(targets_)

features_, targets_ = convert_obs_to_proba(features, targets)

print(features_)
print(targets_)

Body:
It's easy using Pandas:

df = pd.DataFrame(features)
df['targets'] = targets

Now you have:

   0  1  2  targets
0  1  1  0        1
1  1  1  0        0
2  0  1  0        1
3  0  1  0        1
4  0  1  0        0
5  0  0  1        0

Now, the fancy part:

df.groupby([0,1,2]).targets.mean()

Gives you:

0  1  2
0  0  1    0.000000
   1  0    0.666667
1  1  0    0.500000
Name: targets, dtype: float64

Pandas doesn't print the 0 at the leftmost part of the 0.666 row, but if you inspect the value there, it is indeed 0.


问:
Display the result of a command prompt in Windows 10
I'm making an application where I have to enable and disable the UWF in Windows 10.
But I want to intercept the success or failure, the problem is that when I only displays a letter.

```<code>string output = string.Empty;
        string error = string.Empty;

        ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd", "/c uwfmgr.exe volume protect c:");
        processStartInfo.RedirectStandardOutput = true;
        processStartInfo.RedirectStandardError = true;

        processStartInfo.UseShellExecute = false;
        processStartInfo.Verb = "runas";
        Process process = Process.Start(processStartInfo);

        using (StreamReader streamReader = process.StandardOutput)
        {
            output = streamReader.ReadToEnd();
        }

        using (StreamReader streamReader = process.StandardError)
        {
            error = streamReader.ReadToEnd();
        }

        if (!string.IsNullOrEmpty(error))
        {
            MessageBox.Show("Error: " + error);
            return;
        }
        MessageBox.Show("OK: " + output);
</code>```

Here comes the message box "OK U"

Thanks

答:
Thank you for your reply.
I tried to read the articles but given my lack of experience I can apply what it says, Could you give me a little extra help?
The thing I noticed is that I can enable the UWF only if you use the following code

```<code>ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd", "/k uwfmgr.exe volume protect " + cmbBox_Disk.SelectedItem.ToString().Substring(0, 2) + " & exit");
processStartInfo.CreateNoWindow = false;
processStartInfo.WindowStyle = ProcessWindowStyle.Normal;
processStartInfo.UseShellExecute = true;
processStartInfo.Verb = "runas";
Process process = Process.Start(processStartInfo);

processStartInfo = new ProcessStartInfo("cmd", "/k uwfmgr.exe filter enable & exit");
processStartInfo.CreateNoWindow = false;
processStartInfo.WindowStyle = ProcessWindowStyle.Normal;
processStartInfo.UseShellExecute = true;
processStartInfo.Verb = "runas";
process = Process.Start(processStartInfo);
</code>```

but the problem is that in this way if there is an error I can not agree with the user.

Body:
I'm making an application where I have to enable and disable the UWF in Windows 10.
But I want to intercept the success or failure, the problem is that when I only displays a letter.

string output = string.Empty;
        string error = string.Empty;

        ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd", "/c uwfmgr.exe volume protect c:");
        processStartInfo.RedirectStandardOutput = true;
        processStartInfo.RedirectStandardError = true;

        processStartInfo.UseShellExecute = false;
        processStartInfo.Verb = "runas";
        Process process = Process.Start(processStartInfo);

        using (StreamReader streamReader = process.StandardOutput)
        {
            output = streamReader.ReadToEnd();
        }

        using (StreamReader streamReader = process.StandardError)
        {
            error = streamReader.ReadToEnd();
        }

        if (!string.IsNullOrEmpty(error))
        {
            MessageBox.Show("Error: " + error);
            return;
        }
        MessageBox.Show("OK: " + output);

Here comes the message box "OK U"

Thanks

Body:
Thank you for your reply.
I tried to read the articles but given my lack of experience I can apply what it says, Could you give me a little extra help?
The thing I noticed is that I can enable the UWF only if you use the following code

ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd", "/k uwfmgr.exe volume protect " + cmbBox_Disk.SelectedItem.ToString().Substring(0, 2) + " & exit");
processStartInfo.CreateNoWindow = false;
processStartInfo.WindowStyle = ProcessWindowStyle.Normal;
processStartInfo.UseShellExecute = true;
processStartInfo.Verb = "runas";
Process process = Process.Start(processStartInfo);

processStartInfo = new ProcessStartInfo("cmd", "/k uwfmgr.exe filter enable & exit");
processStartInfo.CreateNoWindow = false;
processStartInfo.WindowStyle = ProcessWindowStyle.Normal;
processStartInfo.UseShellExecute = true;
processStartInfo.Verb = "runas";
process = Process.Start(processStartInfo);

but the problem is that in this way if there is an error I can not agree with the user.


问:
Attempted to add an ID already in GraphQLSegment
My Relay/GraphQL fragment contains two different queries, both of which return objects of the same type, and there is often some overlap between the result sets returned by either (and that's perfectly fine with me). I see the following warnings in the browser:

```<code>Attempted to add an ID already in GraphQLSegment: client:client:15254944391:UmV2aWV3ZXI6MQ==
cra.dll.js:106483 Attempted to add noncontiguous index to GraphQLSegment: 52 to (0, 2)
cra.dll.js:106483 Attempted to add noncontiguous index to GraphQLSegment: 53 to (0, 2)
cra.dll.js:106483 Attempted to add noncontiguous index to GraphQLSegment: 54 to (0, 2)
cra.dll.js:106483 Attempted to add noncontiguous index to GraphQLSegment: 55 to (0, 2)
</code>```

Can someone confirm that this is indeed due to me seeing the same Relay object twice? How do I silence the warning or at least debug it further?

答:
Can tell with out looking at the code but you might be running your nodeDefinition on your type 2x. If you defined the globalIDField on your top level object, like so:

```<code>let {nodeInterface, nodeField } = nodeDefinitions(
(globalId) => {
  let { type, id } = fromGlobalId(globalId)
  console.log('NodeDefinitions (globalId), id:', id)
  console.log('NodeDefinitions (globalId), type:', type)

  if (type === 'TopLevelObject') {
    return toplevelobject
  }
  return null
},
(obj) => {
  if (obj instanceof TopLevelObject) {
    return toplevelobjectType
  }
  return null
}
</code>```

)

Then you should refer to any other objects like this:

let itemType = new GraphQLObjectType({
    name: 'Item',
    fields: () => ({
      id: fromGlobalId('Item', obj => obj._id),
      // OR, not both..
      id: {
        type: new GraphQLNonNull(GraphQLID),
        resolve: (obj) => obj._id
      },
      name: { type: GraphQLString },
      url: { type: GraphQLString },
      state: { type: GraphQLString },
      likesCount: { type: GraphQLInt },
      createdAt: {
        type: GraphQLString,
        resolve: ...
      }
    }),
    interfaces: [nodeInterface]
  })

Either seems to work. If you want to share your code, happy to look at it.

Body:
My Relay/GraphQL fragment contains two different queries, both of which return objects of the same type, and there is often some overlap between the result sets returned by either (and that's perfectly fine with me). I see the following warnings in the browser:

Attempted to add an ID already in GraphQLSegment: client:client:15254944391:UmV2aWV3ZXI6MQ==
cra.dll.js:106483 Attempted to add noncontiguous index to GraphQLSegment: 52 to (0, 2)
cra.dll.js:106483 Attempted to add noncontiguous index to GraphQLSegment: 53 to (0, 2)
cra.dll.js:106483 Attempted to add noncontiguous index to GraphQLSegment: 54 to (0, 2)
cra.dll.js:106483 Attempted to add noncontiguous index to GraphQLSegment: 55 to (0, 2)

Can someone confirm that this is indeed due to me seeing the same Relay object twice? How do I silence the warning or at least debug it further?

Body:
Can tell with out looking at the code but you might be running your nodeDefinition on your type 2x. If you defined the globalIDField on your top level object, like so:

let {nodeInterface, nodeField } = nodeDefinitions(
(globalId) => {
  let { type, id } = fromGlobalId(globalId)
  console.log('NodeDefinitions (globalId), id:', id)
  console.log('NodeDefinitions (globalId), type:', type)

  if (type === 'TopLevelObject') {
    return toplevelobject
  }
  return null
},
(obj) => {
  if (obj instanceof TopLevelObject) {
    return toplevelobjectType
  }
  return null
}

)

Then you should refer to any other objects like this:

let itemType = new GraphQLObjectType({
    name: 'Item',
    fields: () => ({
      id: fromGlobalId('Item', obj => obj._id),
      // OR, not both..
      id: {
        type: new GraphQLNonNull(GraphQLID),
        resolve: (obj) => obj._id
      },
      name: { type: GraphQLString },
      url: { type: GraphQLString },
      state: { type: GraphQLString },
      likesCount: { type: GraphQLInt },
      createdAt: {
        type: GraphQLString,
        resolve: ...
      }
    }),
    interfaces: [nodeInterface]
  })

Either seems to work. If you want to share your code, happy to look at it.


问:
Get text from field on keyup, but with delay for further typing
I have a form which is submitted remotely when the various elements change.  On a search field in particular I'm using a keyup to detect when the text in the field changes.  The problem with this is that when someone types "chicken" then the form is submitted seven times, with only the last one counting.

What would be better is something like this

keyup detected - start waiting (for one second)

another keyup detected - restart waiting time

waiting finishes - get value and submit form

before I go off and code my own version of this (I'm really a backend guy with only a little js, I use jQuery for everything), is there already an existing solution to this?  It seems like it would be a common requirement.  A jQuery plugin maybe?  If not, what's the simplest and best way to code this?

UPDATE - current code added for Dan (below)

Dan - this may be relevant.  One of the jQuery plugins I'm using on the page (tablesorter) requires this file - "tablesorter/jquery-latest.js", which, if included, leads to the same error with your code as before:

jQuery("input#search").data("timeout", null) is undefined
  http://192.168.0.234/javascripts/main.js?1264084467
  Line 11

Maybe there's some sort of conflict between different jQuery definitions? (or something)

```<code>$(document).ready(function() {
  //initiate the shadowbox player
//  Shadowbox.init({
//    players:  ['html', 'iframe']
//  });
});

jQuery(function(){
  jQuery('input#search')
    .data('timeout', null)
    .keyup(function(){
      jQuery(this).data('timeout', setTimeout(function(){
          var mytext = jQuery('input#search').val();
          submitQuizForm();
          jQuery('input#search').next().html(mytext);
        }, 2000)
     )
     .keydown(function(){
       clearTimeout(jQuery(this).data('timeout'));
     });
    });
});

function submitQuizForm(){
  form = jQuery("#searchQuizzes");
  jQuery.ajax({
    async:true,
    data:jQuery.param(form.serializeArray()),
    dataType:'script',
    type:'get',
    url:'/millionaire/millionaire_quizzes',
    success: function(msg){
     // $("#chooseQuizMainTable").trigger("update");
    }
  });
  return true;
}
</code>```

答:
Nice job, Max, that was very helpful to me! I've made a slight improvement to your function by making it more general:

```<code>function afterDelayedEvent(eventtype, selector, action, delay) {
    $(selector).bind(eventtype, function() {
        if (typeof(window['inputTimeout']) != "undefined") {
            clearTimeout(inputTimeout);
        }
        inputTimeout = setTimeout(action, delay);
    });
}
</code>```

This way you can use it for any type of event, although keyup is probably the most useful here.

ContentLicense: CC BY-SA 4.0

Body:
I have a form which is submitted remotely when the various elements change.  On a search field in particular I'm using a keyup to detect when the text in the field changes.  The problem with this is that when someone types "chicken" then the form is submitted seven times, with only the last one counting.

What would be better is something like this

keyup detected - start waiting (for one second)

another keyup detected - restart waiting time

waiting finishes - get value and submit form

before I go off and code my own version of this (I'm really a backend guy with only a little js, I use jQuery for everything), is there already an existing solution to this?  It seems like it would be a common requirement.  A jQuery plugin maybe?  If not, what's the simplest and best way to code this?

UPDATE - current code added for Dan (below)

Dan - this may be relevant.  One of the jQuery plugins I'm using on the page (tablesorter) requires this file - "tablesorter/jquery-latest.js", which, if included, leads to the same error with your code as before:

jQuery("input#search").data("timeout", null) is undefined
  http://192.168.0.234/javascripts/main.js?1264084467
  Line 11

Maybe there's some sort of conflict between different jQuery definitions? (or something)

$(document).ready(function() {
  //initiate the shadowbox player
//  Shadowbox.init({
//    players:  ['html', 'iframe']
//  });
});

jQuery(function(){
  jQuery('input#search')
    .data('timeout', null)
    .keyup(function(){
      jQuery(this).data('timeout', setTimeout(function(){
          var mytext = jQuery('input#search').val();
          submitQuizForm();
          jQuery('input#search').next().html(mytext);
        }, 2000)
     )
     .keydown(function(){
       clearTimeout(jQuery(this).data('timeout'));
     });
    });
});

function submitQuizForm(){
  form = jQuery("#searchQuizzes");
  jQuery.ajax({
    async:true,
    data:jQuery.param(form.serializeArray()),
    dataType:'script',
    type:'get',
    url:'/millionaire/millionaire_quizzes',
    success: function(msg){
     // $("#chooseQuizMainTable").trigger("update");
    }
  });
  return true;
}

Body:
Nice job, Max, that was very helpful to me! I've made a slight improvement to your function by making it more general:

function afterDelayedEvent(eventtype, selector, action, delay) {
    $(selector).bind(eventtype, function() {
        if (typeof(window['inputTimeout']) != "undefined") {
            clearTimeout(inputTimeout);
        }
        inputTimeout = setTimeout(action, delay);
    });
}

This way you can use it for any type of event, although keyup is probably the most useful here.

ContentLicense: CC BY-SA 2.5


问:
Postgres sql insert query syntax error from phpPgAdmin
Trying to execute a standard insert query, but it doesn't work.

```<code>INSERT INTO users (vk_id, eu_name, eu_society, eu_notes, eu_want_team)
VALUES ("123123133","Eu name","Eu society","Eu notes","true")
</code>```

The error I get is the following:

```<code>ERROR:  syntax error at or near "INTO" LINE 1: SELECT COUNT(*) AS
 total FROM (INSERT INTO users (vk_id, eu_...
</code>```

What is causing this error?

答:
you could try this as well

INSERT INTO "user" ("username", "password_hash", "first_name", "last_name")
VALUES( 'Foo',MD5('54321'),'Foo','Bar' );

Body:
Trying to execute a standard insert query, but it doesn't work.

INSERT INTO users (vk_id, eu_name, eu_society, eu_notes, eu_want_team)
VALUES ("123123133","Eu name","Eu society","Eu notes","true")

The error I get is the following:

ERROR:  syntax error at or near "INTO" LINE 1: SELECT COUNT(*) AS
 total FROM (INSERT INTO users (vk_id, eu_...

What is causing this error?


问:
ASP .NET MVC multiple models in one view
I have this two classes:

```<code>public class Kolobezka : IEntity1
{
    public virtual int Id { get; set; }
    public virtual int VelikostKola { get; set; }
    public virtual string Znacka { get; set; }
    public virtual string Stav { get; set; }
    public virtual string Description { get; set; }
    public virtual Kategorie_kolobezek Kategorie { get; set; }
    public virtual int Dostupnost { get; set; }

}
public class Rezervace : IEntity1
    {
        public virtual int Id { get; set; }
        public virtual Kolobezka Rez_kolobezky { get; set; }
        [Required(ErrorMessage = "Jméno je požadováno!")]
        public virtual string Jmeno { get; set; }
        [Required(ErrorMessage = "Příjmení je požadováno!")]
        public virtual string Prijmeni { get; set; }
        [Required(ErrorMessage = "Datum začátku rezervace je požadováno!")]
        public virtual DateTime Datum_od { get; set; }
        [Required(ErrorMessage = "Datum konce rezervace je požadováno!")]
        public virtual DateTime Datum_do { get; set; }
        public virtual string Popis { get; set; }
    }
</code>```

So I need in one view called Index use two Ilists from those two clases because of this:

```<code>@foreach (Kolobezka k in Model)
        {

            foreach (Rezervace r1 in r)
            {
                if(k.Id == r1.Rez_kolobezky.Id && r1.Datum_od < DateTime.Now && r1.Datum_do > DateTime.Now)
                {
                    k.Dostupnost = 1;
                }
            }

            if (k.Dostupnost == 0)
            {
                <tr class="bg-danger">
                    <td>
                        @Ajax.ActionLink(k.Id.ToString(), "Detail", new { id = k.Id },
                       new AjaxOptions() { UpdateTargetId = "modalContent",
                           InsertionMode = InsertionMode.Replace, OnBegin = "openModalWindow" })
                    </td>
                    <td>@k.VelikostKola</td>
                    <td>@k.Znacka</td>
                    <td>@k.Kategorie.Nazev</td>
                    <td>@k.Stav</td>
                </tr>
            }
</code>```

Whot should I write instead r in the second foreach.
The beginning of index view looks like this:

```<code>@using ClassLibrary1.Model
@model IList<Kolobezka>

@{
    ViewBag.Title = "Index";
}
</code>```

Thank you a lot.

答:
Create another class and create 2 properties each of the type you want.

```<code>public class Compound {
    public Kolobezka foo {get; set;}
    public Rezervace bar {get; set;}
}
</code>```

Then you can pass this compound object to the view like this.

```<code>@model Compound
</code>```

Now you can access the objects. You can also have list instead of single object in case you want that. Hope that this helps

Body:
I have this two classes:

public class Kolobezka : IEntity1
{
    public virtual int Id { get; set; }
    public virtual int VelikostKola { get; set; }
    public virtual string Znacka { get; set; }
    public virtual string Stav { get; set; }
    public virtual string Description { get; set; }
    public virtual Kategorie_kolobezek Kategorie { get; set; }
    public virtual int Dostupnost { get; set; }

}
public class Rezervace : IEntity1
    {
        public virtual int Id { get; set; }
        public virtual Kolobezka Rez_kolobezky { get; set; }
        [Required(ErrorMessage = "Jméno je požadováno!")]
        public virtual string Jmeno { get; set; }
        [Required(ErrorMessage = "Příjmení je požadováno!")]
        public virtual string Prijmeni { get; set; }
        [Required(ErrorMessage = "Datum začátku rezervace je požadováno!")]
        public virtual DateTime Datum_od { get; set; }
        [Required(ErrorMessage = "Datum konce rezervace je požadováno!")]
        public virtual DateTime Datum_do { get; set; }
        public virtual string Popis { get; set; }
    }

So I need in one view called Index use two Ilists from those two clases because of this:

@foreach (Kolobezka k in Model)
        {

            foreach (Rezervace r1 in r)
            {
                if(k.Id == r1.Rez_kolobezky.Id && r1.Datum_od < DateTime.Now && r1.Datum_do > DateTime.Now)
                {
                    k.Dostupnost = 1;
                }
            }

            if (k.Dostupnost == 0)
            {

                        @Ajax.ActionLink(k.Id.ToString(), "Detail", new { id = k.Id },
                       new AjaxOptions() { UpdateTargetId = "modalContent",
                           InsertionMode = InsertionMode.Replace, OnBegin = "openModalWindow" })

                    @k.VelikostKola
                    @k.Znacka
                    @k.Kategorie.Nazev
                    @k.Stav

            }

Whot should I write instead r in the second foreach.
The beginning of index view looks like this:

@using ClassLibrary1.Model
@model IList<Kolobezka>

@{
    ViewBag.Title = "Index";
}

Thank you a lot.

Body:
Create another class and create 2 properties each of the type you want.

public class Compound {
    public Kolobezka foo {get; set;}
    public Rezervace bar {get; set;}
}

Then you can pass this compound object to the view like this.

@model Compound

Now you can access the objects. You can also have list instead of single object in case you want that. Hope that this helps


问:
CListCtrl is not creating groups
I am trying to make groupings using a CListCtrl trough the following code:

```<code>        LVGROUP lg = { 0 };
        lg.cbSize = sizeof(lg);

        lg.state = LVGS_NORMAL | LVGS_COLLAPSIBLE;
        lg.mask = LVGF_GROUPID | LVGF_HEADER | LVGF_STATE | LVGF_ALIGN | LVGF_STATE | LVGF_DESCRIPTIONTOP | LVGF_DESCRIPTIONBOTTOM | LVGF_FOOTER | LVGF_TASK | LVGF_SUBTITLE | LVGF_SUBSET;
        lg.uAlign = LVGA_HEADER_LEFT | LVGA_FOOTER_RIGHT;

        LVITEM item = { 0 };
        item.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_GROUPID;
        item.iSubItem = 0;
        item.state = 0;
        item.stateMask = LVIS_SELECTED;

        CString s;

        lg.iGroupId = 0;

        s = L"Office";
        lg.pszHeader = s.GetBuffer();
        lg.cchHeader = s.GetLength();

        pListCtrl->InsertGroup(lg.iGroupId, &lg);

        item.iGroupId = 0;

        s = "Pen";
        item.pszText = s.GetBuffer();
        item.cchTextMax = s.GetLength();

        pListCtrl->InsertItem(&item);

        s = "Pencil";
        item.pszText = s.GetBuffer();
        item.cchTextMax = s.GetLength();

        pListCtrl->InsertItem(&item);

        lg.iGroupId = 1;

        s = L"Workshop";
        lg.pszHeader = s.GetBuffer();
        lg.cchHeader = s.GetLength();

        pListCtrl->InsertGroup(lg.iGroupId, &lg);

        item.iGroupId = 1;

        s = "Hammer";
        item.pszText = s.GetBuffer();
        item.cchTextMax = s.GetLength();

        pListCtrl->InsertItem(&item);

        s = "Drill";
        item.pszText = s.GetBuffer();
        item.cchTextMax = s.GetLength();

        pListCtrl->InsertItem(&item);

        s = "Saw";
        item.pszText = s.GetBuffer();
        item.cchTextMax = s.GetLength();

        pListCtrl->InsertItem(&item);
</code>```

but everything is shown ungrouped

How can I make the groups work as they should?

答:
It turns out there is the need of a manifest, which I added to stdafx.h

```<code>#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
</code>```

Title: CListCtrl is not creating groups

Body:
I am trying to make groupings using a CListCtrl trough the following code:

        LVGROUP lg = { 0 };
        lg.cbSize = sizeof(lg);

        lg.state = LVGS_NORMAL | LVGS_COLLAPSIBLE;
        lg.mask = LVGF_GROUPID | LVGF_HEADER | LVGF_STATE | LVGF_ALIGN | LVGF_STATE | LVGF_DESCRIPTIONTOP | LVGF_DESCRIPTIONBOTTOM | LVGF_FOOTER | LVGF_TASK | LVGF_SUBTITLE | LVGF_SUBSET;
        lg.uAlign = LVGA_HEADER_LEFT | LVGA_FOOTER_RIGHT;

        LVITEM item = { 0 };
        item.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_GROUPID;
        item.iSubItem = 0;
        item.state = 0;
        item.stateMask = LVIS_SELECTED;

        CString s;

        lg.iGroupId = 0;

        s = L"Office";
        lg.pszHeader = s.GetBuffer();
        lg.cchHeader = s.GetLength();

        pListCtrl->InsertGroup(lg.iGroupId, &lg);

        item.iGroupId = 0;

        s = "Pen";
        item.pszText = s.GetBuffer();
        item.cchTextMax = s.GetLength();

        pListCtrl->InsertItem(&item);

        s = "Pencil";
        item.pszText = s.GetBuffer();
        item.cchTextMax = s.GetLength();

        pListCtrl->InsertItem(&item);

        lg.iGroupId = 1;

        s = L"Workshop";
        lg.pszHeader = s.GetBuffer();
        lg.cchHeader = s.GetLength();

        pListCtrl->InsertGroup(lg.iGroupId, &lg);

        item.iGroupId = 1;

        s = "Hammer";
        item.pszText = s.GetBuffer();
        item.cchTextMax = s.GetLength();

        pListCtrl->InsertItem(&item);

        s = "Drill";
        item.pszText = s.GetBuffer();
        item.cchTextMax = s.GetLength();

        pListCtrl->InsertItem(&item);

        s = "Saw";
        item.pszText = s.GetBuffer();
        item.cchTextMax = s.GetLength();

        pListCtrl->InsertItem(&item);

but everything is shown ungrouped

How can I make the groups work as they should?

Body:
It turns out there is the need of a manifest, which I added to stdafx.h

#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")


问:
What to do about Eclipse's "No repository found containing: ..." error messages?
I'm running Eclipse's Helios EE bundle on Linux to which I added the subversive plugins, the m2e Maven integration and the Mylin connector for Trac. For the last couple of weeks I've been trying to install updates, and every time I get back a message like

```<code>No repository found containing <something or other>
</code>```

The latest one was

```<code>An error occurred while collecting items to be installed
session context was:(profile=epp.package.jee, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=).
No repository found containing: osgi.bundle,org.eclipse.team.svn,0.7.9.I20110318-1700
No repository found containing: osgi.bundle,org.eclipse.team.svn.core,0.7.9.I20110523-1700
No repository found containing: osgi.bundle,org.eclipse.team.svn.help,0.7.9.I20110318-1700
No repository found containing: osgi.bundle,org.eclipse.team.svn.mylyn,0.7.9.I20110318-1700
No repository found containing: osgi.bundle,org.eclipse.team.svn.ui,0.7.9.I20110523-1700
No repository found containing: org.eclipse.update.feature,org.eclipse.team.svn,0.7.9.I20110523-1700
No repository found containing: org.eclipse.update.feature,org.eclipse.team.svn.mylyn,0.7.9.I20110523-1700
No repository found containing: org.eclipse.update.feature,org.eclipse.team.svn.resource.ignore.rules.jdt,0.7.9.I20110523-1700
</code>```

What does it all mean and how do I fix that? If Eclipse has been able to contact the repositories to check for new files, why isn't it able to download those files from those some repositories? Or does the error message mean something entirely different?

答:
I had the same problem on windows 10.
My eclipse version was installed from an exe, downloaded from eclipse site.

What solved for me was to use the zip version instead:
http://www.eclipse.org/downloads/eclipse-packages/

Body:
I'm running Eclipse's Helios EE bundle on Linux to which I added the subversive plugins, the m2e Maven integration and the Mylin connector for Trac. For the last couple of weeks I've been trying to install updates, and every time I get back a message like

No repository found containing <something or other>

The latest one was

An error occurred while collecting items to be installed
session context was:(profile=epp.package.jee, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=).
No repository found containing: osgi.bundle,org.eclipse.team.svn,0.7.9.I20110318-1700
No repository found containing: osgi.bundle,org.eclipse.team.svn.core,0.7.9.I20110523-1700
No repository found containing: osgi.bundle,org.eclipse.team.svn.help,0.7.9.I20110318-1700
No repository found containing: osgi.bundle,org.eclipse.team.svn.mylyn,0.7.9.I20110318-1700
No repository found containing: osgi.bundle,org.eclipse.team.svn.ui,0.7.9.I20110523-1700
No repository found containing: org.eclipse.update.feature,org.eclipse.team.svn,0.7.9.I20110523-1700
No repository found containing: org.eclipse.update.feature,org.eclipse.team.svn.mylyn,0.7.9.I20110523-1700
No repository found containing: org.eclipse.update.feature,org.eclipse.team.svn.resource.ignore.rules.jdt,0.7.9.I20110523-1700

What does it all mean and how do I fix that? If Eclipse has been able to contact the repositories to check for new files, why isn't it able to download those files from those some repositories? Or does the error message mean something entirely different?


问:
.htaccess rewrite subdomain as request parameter
Ho I Can rewrite this request types:

```<code>http://name1.domain1.com/        -> index.php?subdomain=name1
http://name2.domain2.org/        -> index.php?subdomain=name2
</code>```

I need manage subdomain GET variable in php script ( index.php ).
I need of generic rule for all domain.

This is my .htaccess file, but it's not working.

```<code>RewriteEngine On

# Parse the subdomain as a variable we can access in PHP, and
# run the main index.php script
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST}        !^www
RewriteCond %{HTTP_HOST}         ^([^\.]+)\.([^\.]+)\.([^\.]+)$
RewriteRule ^(.*)$ /$1?subdomain=%1
</code>```

Thanks.

答:
Assuming you are using PHP. You don't need to put it as query parameter since from PHP you can already see which is the URL the client's browser requested.

```<code>echo $_SERVER['HTTP_HOST']
</code>```

output:

```<code>bubbles.domain.com
</code>```

You just need to parse it.

```<code>$host= (explode( '.', $_SERVER['HTTP_HOST']))[0];
$subdomain = $host[0];

if($subdomain == 'www' || $subdomain == 'www2')
    $subdomain = $host[1];

echo $subdomain;
</code>```

output:

```<code>bubbles
</code>```

Body:
Ho I Can rewrite this request types:

http://name1.domain1.com/        -> index.php?subdomain=name1
http://name2.domain2.org/        -> index.php?subdomain=name2

I need manage subdomain GET variable in php script ( index.php ).
I need of generic rule for all domain.

This is my .htaccess file, but it's not working.

RewriteEngine On

# Parse the subdomain as a variable we can access in PHP, and
# run the main index.php script
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST}        !^www
RewriteCond %{HTTP_HOST}         ^([^\.]+)\.([^\.]+)\.([^\.]+)$
RewriteRule ^(.*)$ /$1?subdomain=%1

Thanks.

Body:
Assuming you are using PHP. You don't need to put it as query parameter since from PHP you can already see which is the URL the client's browser requested.

echo $_SERVER['HTTP_HOST']

output:

bubbles.domain.com

You just need to parse it.

$host= (explode( '.', $_SERVER['HTTP_HOST']))[0];
$subdomain = $host[0];

if($subdomain == 'www' || $subdomain == 'www2')
    $subdomain = $host[1];

echo $subdomain;

output:

bubbles


问:
RxJS Observables, when to unsubscibe?
I have a couple of questions about Angular. I recently started to experiment with Angular and really cant get a grip of when I should unsubscribe, there is obviously recommended to use the AsyncPipe but in some cases there is no way to use it.

If I subscribe to a HTTP request in a service, does the Observable unsubscribe itself or is it persistent through out the application lifetime?

When I subscribe (without the AsyncPipe) to a HTTP request in a component I could manually unsubscribe in the ngOnDestroy lifecycle hook which is fine but in my case I have a submit method to create account

account.component.html

```<code><account-item>
 *ngFor="let account of collection$"
 [data]="account"
</account-item>
</code>```

account.component.ts

```<code>public collection$: Observable<Account[]>;
private subscription: Subscription;

 constructor(
  private service: AccountService
 ) {}

 ngOnInit() {
   this.collection$ = this.service.getAll()
 }

 createAccount(obj) {
  this.subscription = this.service.create(obj)
   .subscribe(
    success => this.collection$ = this.service.getAll(),
    error => Observable.throw(error)
  );
}

ngOnDestroy() {
 this.subscription.unsubscribe();
}
</code>```

From what I know the subscription is now persistent until my AccountComponent is destroyed, but is there a way to use AsyncPipe here instead or is it better for me to subscribe in the service itself?

I've read something about finite and infinite Observables but haven't really understand when a Observable is finite or not.

Another problem I'm facing is that in success => this.collection$ = this.service.getAll() my UI doesn't update with the new account list when I use ChangeDetectionStrategy.OnPush but works just fine with ChangeDetectionStrategy.Default

This is the service method that fetches the account data

```<code> getAll() {
  return this.http.get(ENDPOINT_ACCOUNT)
    .map((response: Response) => response.json().data)
}
</code>```

答:
What you need to think when dealing with Observables and functionnal programming more globaly is that you don't describe how things are done but describe what things are.

In your example, you collection is the combination of on the one hand the initial fetch from the service and on the other hand, all updates that may occur, so if you want to avoid subscribing in the component, you can do such a thing:

```<code>class Foo {
  public collection$: Observable < Account[] > ;
  private createAccount$ = new Subject<Account>();

  constructor(
    private service: AccountService
  ) {}

  ngOnInit() {
    let initialAccounts = this.service.getAll().share();
    let accountUpdate = initialAccounts.switchMap(()=>this.createAccount$.switchMap(account=>{
      return this.service.create(account).switchMap(()=>this.service.getAll())
    }))
    this.collection$ = Observable.merge(initialAccounts,accountUpdate);
  }

  createAccount(obj:Account) {
    this.createAccount$.next(obj);
  }

}
</code>```

We are using here the merge operator to take the data from either initialAccounts or createAccount$. It is always a good thing to combine your observables together and subscribe once, because this way you don't have to imperatively manage your subscription.

The fact is most of the time, you don't need to subscribe() at all.

Title: RxJS Observables, when to unsubscibe?

Body:
I have a couple of questions about Angular. I recently started to experiment with Angular and really cant get a grip of when I should unsubscribe, there is obviously recommended to use the AsyncPipe but in some cases there is no way to use it.

If I subscribe to a HTTP request in a service, does the Observable unsubscribe itself or is it persistent through out the application lifetime?

When I subscribe (without the AsyncPipe) to a HTTP request in a component I could manually unsubscribe in the ngOnDestroy lifecycle hook which is fine but in my case I have a submit method to create account

account.component.html

<account-item>
 *ngFor="let account of collection$"
 [data]="account"
</account-item>

account.component.ts

public collection$: Observable<Account[]>;
private subscription: Subscription;

 constructor(
  private service: AccountService
 ) {}

 ngOnInit() {
   this.collection$ = this.service.getAll()
 }

 createAccount(obj) {
  this.subscription = this.service.create(obj)
   .subscribe(
    success => this.collection$ = this.service.getAll(),
    error => Observable.throw(error)
  );
}

ngOnDestroy() {
 this.subscription.unsubscribe();
}

From what I know the subscription is now persistent until my AccountComponent is destroyed, but is there a way to use AsyncPipe here instead or is it better for me to subscribe in the service itself?

I've read something about finite and infinite Observables but haven't really understand when a Observable is finite or not.

Another problem I'm facing is that in success => this.collection$ = this.service.getAll() my UI doesn't update with the new account list when I use ChangeDetectionStrategy.OnPush but works just fine with ChangeDetectionStrategy.Default

This is the service method that fetches the account data

 getAll() {
  return this.http.get(ENDPOINT_ACCOUNT)
    .map((response: Response) => response.json().data)
}

Body:
What you need to think when dealing with Observables and functionnal programming more globaly is that you don't describe how things are done but describe what things are.

In your example, you collection is the combination of on the one hand the initial fetch from the service and on the other hand, all updates that may occur, so if you want to avoid subscribing in the component, you can do such a thing:

class Foo {
  public collection$: Observable < Account[] > ;
  private createAccount$ = new Subject<Account>();

  constructor(
    private service: AccountService
  ) {}

  ngOnInit() {
    let initialAccounts = this.service.getAll().share();
    let accountUpdate = initialAccounts.switchMap(()=>this.createAccount$.switchMap(account=>{
      return this.service.create(account).switchMap(()=>this.service.getAll())
    }))
    this.collection$ = Observable.merge(initialAccounts,accountUpdate);
  }

  createAccount(obj:Account) {
    this.createAccount$.next(obj);
  }

}

We are using here the merge operator to take the data from either initialAccounts or createAccount$. It is always a good thing to combine your observables together and subscribe once, because this way you don't have to imperatively manage your subscription.

The fact is most of the time, you don't need to subscribe() at all.


问:
C# 5 extension method working as the C# 6 null conditional operator
I have a piece of code similar to:

```<code>var colour = car.Wheels[0].Trim.Bolts[0].Colour.Substring(0, 3);
</code>```

Unfortunately car, Wheels, Trim, Bolts, Colour can all be null; Wheels, Bolts and Colour can be empty as well.

Is there an Object extension method I can use that will do all the null/empty checks for me?

I'd prefer a solution that can easily be replaced with the ?. operator, once I upgrade to C# 6+.

答:
What about this extension method?

```<code>public static T IfNotNull<R, T>(this R r, Func<R, T> selector)
{
    if (r != null)
    {
        return selector(r);
    }
    else
    {
        return default(T);
    }
}
</code>```

Which will leave you with this nasty code:

```<code>var colour = car.Wheels.IfNotNull(w => w.FirstOrDefault())
                       .IfNotNull(w => w.Trim)
                       .IfNotNull(w => w.Substring(0, 3));
</code>```

Personally I would still prefer simple if statements.

Body:
I have a piece of code similar to:

var colour = car.Wheels[0].Trim.Bolts[0].Colour.Substring(0, 3);

Unfortunately car, Wheels, Trim, Bolts, Colour can all be null; Wheels, Bolts and Colour can be empty as well.

Is there an Object extension method I can use that will do all the null/empty checks for me?

I'd prefer a solution that can easily be replaced with the ?. operator, once I upgrade to C# 6+.

Body:
What about this extension method?

public static T IfNotNull<R, T>(this R r, Func<R, T> selector)
{
    if (r != null)
    {
        return selector(r);
    }
    else
    {
        return default(T);
    }
}

Which will leave you with this nasty code:

var colour = car.Wheels.IfNotNull(w => w.FirstOrDefault())
                       .IfNotNull(w => w.Trim)
                       .IfNotNull(w => w.Substring(0, 3));

Personally I would still prefer simple if statements.


问:
How do I deserialize Drupal JSON Services strings in Android?
I am using Drupal Services along with the JSON Services module as a data source.

I am using the DrupalCloud library, https://github.com/skyred/DrupalCloud/wiki, and am wondering how to best process the results that I receive from a userLogin() call.

If the call itself fails we get:

```<code>{
  "#error": true,
  "#message": "Some message"
}
</code>```

If the call succeeds but the login credentials are wrong:

```<code>{
  "#error": false,
  "#data": {
    "#error": true,
    "#message": "Some message"
  }
}
</code>```

If the call success and the login credentials are correct, it returns:

```<code>{
  "#error": false,
  "#data": {
    "sessid": "foo",
    "user": {
      "uid": "69",
      "name": "Russell Jones",
      "pass": "bar",
      "mail": "russell@test.net",
      "roles": {
        "2": "authenticated user",
        "5": "Student"
      },
    }
  }
}
</code>```

How do I go about using this data meaningfully?  Or rather, how do I test to see if the call worked, and if the login was successful or not.

答:
This is one way to parse the last JSON message in your question:</p>

```<code>public void readJsonString(String jsonString) throws JSONException
{
    JSONObject jsonObject = new JSONObject(jsonString);
    boolean error = jsonObject.getBoolean("#error");
    if (!error)
    {
        JSONObject data = jsonObject.getJSONObject("#data");
        String sessionId = data.getString("sessid");
        JSONObject user = data.getJSONObject("user");
        int uid = user.getInt("uid");
        String name = user.getString("name");

        // you get the pattern, same way with the other fields...
    }
}
</code>```

Body:
I am using Drupal Services along with the JSON Services module as a data source.

I am using the DrupalCloud library, https://github.com/skyred/DrupalCloud/wiki, and am wondering how to best process the results that I receive from a userLogin() call.

If the call itself fails we get:

{
  "#error": true,
  "#message": "Some message"
}

If the call succeeds but the login credentials are wrong:

{
  "#error": false,
  "#data": {
    "#error": true,
    "#message": "Some message"
  }
}

If the call success and the login credentials are correct, it returns:

{
  "#error": false,
  "#data": {
    "sessid": "foo",
    "user": {
      "uid": "69",
      "name": "Russell Jones",
      "pass": "bar",
      "mail": "russell@test.net",
      "roles": {
        "2": "authenticated user",
        "5": "Student"
      },
    }
  }
}

How do I go about using this data meaningfully?  Or rather, how do I test to see if the call worked, and if the login was successful or not.

Body:
This is one way to parse the last JSON message in your question:

public void readJsonString(String jsonString) throws JSONException
{
    JSONObject jsonObject = new JSONObject(jsonString);
    boolean error = jsonObject.getBoolean("#error");
    if (!error)
    {
        JSONObject data = jsonObject.getJSONObject("#data");
        String sessionId = data.getString("sessid");
        JSONObject user = data.getJSONObject("user");
        int uid = user.getInt("uid");
        String name = user.getString("name");

        // you get the pattern, same way with the other fields...
    }
}


问:
Taking a sample of a CSV?
I have a program converting a CSV to a valid JSON file.

I would like to change it to take a random subset of my CSV file (as its 50k lines) and make a JSON from this. Here is my code so far -

```<code>import csv
import json

csvfile = open('C:\\Users\\ADMIN\\Desktop\\CSV_1.csv', 'r')
jsonfile = open('C:\\Users\\ADMIN\\Desktop\\Testing\\file.json', 'w')

with open('C:\\Users\\ADMIN\\Desktop\\CSV_1.csv') as f:
    reader = csv.DictReader(f)
    rows = list(reader)

with open('C:\\Users\\ADMIN\\Desktop\\Testing\\file.json', 'w') as f:
    json.dump(rows, f)
</code>```

What's the most efficient way to do this?

Thanks.

答:
You can apply random.sample(lst, n) to the list of rows to fetch n number of rows from the list of rows randomly, something like this :

```<code>import random
rows_subset = random.sample(rows, 50)

# Then later in the code, dump the json and write it to the other file.
with open('gen.json', 'w') as f:
    f.write(json.dumps(rows_subset))
</code>```

This will give you list of 50 rows which you can then use or write to another file.

Title: Taking a sample of a CSV?

Body:
I have a program converting a CSV to a valid JSON file.

I would like to change it to take a random subset of my CSV file (as its 50k lines) and make a JSON from this. Here is my code so far -

import csv
import json

csvfile = open('C:\\Users\\ADMIN\\Desktop\\CSV_1.csv', 'r')
jsonfile = open('C:\\Users\\ADMIN\\Desktop\\Testing\\file.json', 'w')

with open('C:\\Users\\ADMIN\\Desktop\\CSV_1.csv') as f:
    reader = csv.DictReader(f)
    rows = list(reader)

with open('C:\\Users\\ADMIN\\Desktop\\Testing\\file.json', 'w') as f:
    json.dump(rows, f)

What's the most efficient way to do this?

Thanks.

Body:
You can apply random.sample(lst, n) to the list of rows to fetch n number of rows from the list of rows randomly, something like this :

import random
rows_subset = random.sample(rows, 50)

# Then later in the code, dump the json and write it to the other file.
with open('gen.json', 'w') as f:
    f.write(json.dumps(rows_subset))

This will give you list of 50 rows which you can then use or write to another file.


问:
How to show JSON with an array inside in Angular 2?
After solve lot of problems to make my app work, http headers and more... now it's working!

Now, when I try to show the data into my app I have a little problem - ask.

I have this schema:

```<code>export class Morosos {
idlor:  String;  comunidad: String; vivienda: String;  demandado:   String;  importe:   String;  datos: [{ fecha: String, dato: String }];  date: { type: Date };}
</code>```

And I have this on .html component:

```<code><tr *ngFor="let p of results; let i=index">
  <td>{{p.idlor}}</td>
  <td>{{p.comunidad}}</td>
  <td>{{p.vivienda}}</td>
  <td>{{p.demandado}}</td>
  <td>{{p.importe}}</td>
  <td>{{p.datos | json}} </td>
  <td>{{p.date}}</td>
</tr>
</code>```

And i got this:

IDLOR Comunidad   Vivienda    Demandado   Importe Datos   Fecha
  LOR01/16  XXX XXX XXX     XXXX    [ { "fecha": "08/03/2017", "dato": "Pagado
  Ejecucion" }, { "fecha": "27/07/2016", "dato": "Carta enviada" }
  ] 1970-01-01T00:00:00.000Z

As you can see I have a JSON on "Datos" which is an array, now my dude is how to put it into a
 too.

Thanks :)

答:
You can use one mre ngFor in the td with ul tag.

{{p}}

	```

Body:
After solve lot of problems to make my app work, http headers and more... now it's working!

Now, when I try to show the data into my app I have a little problem - ask.

I have this schema:

export class Morosos {
idlor:  String;  comunidad: String; vivienda: String;  demandado:   String;  importe:   String;  datos: [{ fecha: String, dato: String }];  date: { type: Date };}

And I have this on .html component:

  {{p.idlor}}
  {{p.comunidad}}
  {{p.vivienda}}
  {{p.demandado}}
  {{p.importe}}
  {{p.datos | json}}
  {{p.date}}

And i got this:

IDLOR Comunidad   Vivienda    Demandado   Importe Datos   Fecha
  LOR01/16  XXX XXX XXX     XXXX    [ { "fecha": "08/03/2017", "dato": "Pagado
  Ejecucion" }, { "fecha": "27/07/2016", "dato": "Carta enviada" }
  ] 1970-01-01T00:00:00.000Z

As you can see I have a JSON on "Datos" which is an array, now my dude is how to put it into a
 too.

Thanks :)

Body:
You can use one mre ngFor in the td with ul tag.

<td>
  <ul *ngFor="let p of p.datos">
    <li>{{p}}</li>
   </ul>
</td>


问:
Feed RSS not updating for W3 validator
I have a problem with my feed rss actually.

I did many tests, and i have to modify my feed rss view (customize it).

Here it's my feed rss : http://agro-media.fr/?feed=email

When you are in the link, you see there is no apparent problems.

However, when you check this link in W3 validator or if you choose this feed in mailchimp, he says "THIS IS NOT A VALID RSS FEED, because there is on the top of the feed this :

```<code>link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</code>```

BUT NO WAY. I deleted it before...

I already did many things like :
- clear WP Rocket cache
- clear Varnish cache
- clear chrome cache
- Server reboot

I don't have more ideas, maybe you can help me ...

thanks a lot guys, have a good day.

答:
Thank you @Dmitry Kurilsky, but i found the problem :

App like feedvalidator or w3c feed validator have cache, and they're updated after a while.

Plus : I merged my feed with mailchimp, and the update between the both is very intense --> I have to wait few hours until the change (synchronization) on the feed make effect.

Sorry for my english tho.

Title: Feed RSS not updating for W3 validator

Body:
I have a problem with my feed rss actually.

I did many tests, and i have to modify my feed rss view (customize it).

Here it's my feed rss : http://agro-media.fr/?feed=email

When you are in the link, you see there is no apparent problems.

However, when you check this link in W3 validator or if you choose this feed in mailchimp, he says "THIS IS NOT A VALID RSS FEED, because there is on the top of the feed this :

link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

BUT NO WAY. I deleted it before...

I already did many things like :
- clear WP Rocket cache
- clear Varnish cache
- clear chrome cache
- Server reboot

I don't have more ideas, maybe you can help me ...

thanks a lot guys, have a good day.


问:
Facebook Meta Tags
My problem was when some one is liking my website, the image, description, title etc. where completly wrong it took the first
 which is the service level agreement in my website. So I figured I have to add opengraph meta tags so I did:

```<code><meta property="og:url" content="http://url.com/" />
<meta property="og:site_name" content="My Web" />
<meta property="og:type" content="website" />
<meta property="og:title" content="My Web.com" />
<meta property="og:image" content="http://url.com/logo.png" />
<meta property="og:description" content="My Web is a new community" />
<meta property="fb:app_id" content="7363627862327638" />
</code>```

The problem is, it is still not working, the likes information is wrong, and I waited atleast 72 hours, so the cache of Facebook is not the problem.

Does anyone know what could be the problem? Thanks alot already!

答:
Try this it worked for me -
Use Dynamic content in meta tag.

```<code><?php

$params = array();
if(count($_GET) > 0) {
    $params = $_GET;
} else {
    $params = $_POST;
}
// defaults
if($params['type'] == "") $params['type'] = "restaurant";
if($params['locale'] == "") $params['locale'] = "en_US";
if($params['title'] == "") $params['title'] = "default title";
if($params['image'] == "") $params['image'] = "thumb";
if($params['description'] == "") $params['description'] = "default description";

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# MY_APP_NAME_SPACE: http://ogp.me/ns/fb/MY_APP_NAME_SPACE#">
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

        <!-- Open Graph meta tags -->
        <meta property="fb:app_id" content="MY_APP_ID" />
        <meta property="og:site_name" content="meta site name"/>
        <meta property="og:url" content="URL?type=<?php echo $params['type']; ?>&locale=<?php echo $params['locale']; ?>&title=<?php echo $params['title']; ?>&image=<?php echo $params['image']; ?>&description=<?php echo $params['description']; ?>"/>
        <meta property="og:type" content="MY_APP_NAME_SPACE:<?php echo $params['type']; ?>"/>
        <meta property="og:locale" content="<?php echo $params['locale']; ?>"/>
        <meta property="og:title" content="<?php echo $params['title']; ?>"/>
        <meta property="og:image" content="URL<?php echo $params['image']; ?>.png"/>
        <meta property="og:description" content="<?php echo $params['description']; ?>"/>

    </head>
</html>
</code>```

Title: Facebook Meta Tags

Body:
My problem was when some one is liking my website, the image, description, title etc. where completly wrong it took the first
 which is the service level agreement in my website. So I figured I have to add opengraph meta tags so I did:

<meta property="og:url" content="http://url.com/" />
<meta property="og:site_name" content="My Web" />
<meta property="og:type" content="website" />
<meta property="og:title" content="My Web.com" />
<meta property="og:image" content="http://url.com/logo.png" />
<meta property="og:description" content="My Web is a new community" />
<meta property="fb:app_id" content="7363627862327638" />

The problem is, it is still not working, the likes information is wrong, and I waited atleast 72 hours, so the cache of Facebook is not the problem.

Does anyone know what could be the problem? Thanks alot already!

Body:
Try this it worked for me -
Use Dynamic content in meta tag.

<?php

$params = array();
if(count($_GET) > 0) {
    $params = $_GET;
} else {
    $params = $_POST;
}
// defaults
if($params['type'] == "") $params['type'] = "restaurant";
if($params['locale'] == "") $params['locale'] = "en_US";
if($params['title'] == "") $params['title'] = "default title";
if($params['image'] == "") $params['image'] = "thumb";
if($params['description'] == "") $params['description'] = "default description";

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# MY_APP_NAME_SPACE: http://ogp.me/ns/fb/MY_APP_NAME_SPACE#">
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

        <!-- Open Graph meta tags -->
        <meta property="fb:app_id" content="MY_APP_ID" />
        <meta property="og:site_name" content="meta site name"/>
        <meta property="og:url" content="URL?type=<?php echo $params['type']; ?>&locale=<?php echo $params['locale']; ?>&title=<?php echo $params['title']; ?>&image=<?php echo $params['image']; ?>&description=<?php echo $params['description']; ?>"/>
        <meta property="og:type" content="MY_APP_NAME_SPACE:<?php echo $params['type']; ?>"/>
        <meta property="og:locale" content="<?php echo $params['locale']; ?>"/>
        <meta property="og:title" content="<?php echo $params['title']; ?>"/>
        <meta property="og:image" content="URL<?php echo $params['image']; ?>.png"/>
        <meta property="og:description" content="<?php echo $params['description']; ?>"/>

    </head>
</html>


问:
using PHP filter_var_array(), why does the FILTER_CALLBACK cast the function argument to a string?
In the following code, why does the callback function cast the $value argument as string? </p>

```<code>$post_values = $_POST['dates'];
/*
var_dump of $post_values
array(1) { [0]=> array(3) { ["date"]=> string(10) "2016-05-10" ["starttime"]=> string(5) "12:30" ["endtime"]=> string(5) "14:33" } }
*/

$args = [
  'dates' => [
    'filter' => FILTER_CALLBACK,
    'options' => function ($value) {
      // The $value here has been cast to string. Why?
      // $value now has value of: string(10) "2016-05-10".
      // I expect it to be an array.
      return $value;
    }
  ]
];

$filtered_values = filter_var_array($post_values, $args);
</code>```

答: To achieve the desired result it seems I am using filter_var_array() incorrectly. filter_var_array() will loop through each array element which is the reason the $value is cast to string.</p>

Body:
In the following code, why does the callback function cast the $value argument as string?

$post_values = $_POST['dates'];
/*
var_dump of $post_values
array(1) { [0]=> array(3) { ["date"]=> string(10) "2016-05-10" ["starttime"]=> string(5) "12:30" ["endtime"]=> string(5) "14:33" } }
*/

$args = [
  'dates' => [
    'filter' => FILTER_CALLBACK,
    'options' => function ($value) {
      // The $value here has been cast to string. Why?
      // $value now has value of: string(10) "2016-05-10".
      // I expect it to be an array.
      return $value;
    }
  ]
];

$filtered_values = filter_var_array($post_values, $args);


问:
Validation not working on Ranges?
Can someone explain to me why my validation won't get triggered when I submit a string such as "foo" to number?

```<code>class Course < ActiveRecord::Base

  validates :number, :inclusion => 0..100

end
</code>```

Only when I change my code to this...

```<code>class Course < ActiveRecord::Base

  validates :number, :inclusion  => 0..100, :numericality => true

end
</code>```

... the validation gets triggered.

Is this a Rails bug or am I missing something really fundamental here?

I am using Rails 4.2.0 by the way.

答:
This turned out to work best for me:</p>

```<code>class Course < ActiveRecord::Base

    validates :number, :numericality => { :greater_than_or_equal_to => 0, :less_than_or_equal_to => 100 }

end
</code>```

Title: Validation not working on Ranges?

Body:
Can someone explain to me why my validation won't get triggered when I submit a string such as "foo" to number?

class Course < ActiveRecord::Base

  validates :number, :inclusion => 0..100

end

Only when I change my code to this...

class Course < ActiveRecord::Base

  validates :number, :inclusion  => 0..100, :numericality => true

end

... the validation gets triggered.

Is this a Rails bug or am I missing something really fundamental here?

I am using Rails 4.2.0 by the way.

Body:
This turned out to work best for me:

class Course < ActiveRecord::Base

    validates :number, :numericality => { :greater_than_or_equal_to => 0, :less_than_or_equal_to => 100 }

end