text:
Q: Arranging numbers in an array (Swedish Math Olympiad 1986) Consider an $m\times n$ array of real numbers.  Let $d>0$.  Suppose that the difference between the maximum number and the minimum number in each row is at most $d$.  We then sort the numbers in each column so that the maximum element is in the first row and the minimum element is in the  last row (so each column is arranged in decreasing order).  Show that the difference between the maximum number and the minimum number in each row (after the change) is still $\le d$.
Source : Swedish Math Olympiad 1986, also Principles and Techniques in Combinatorics
Here is my attempt.  Let $M_k$ and $m_k$ be the original largest and smallest elements of the $k$th row.  Let $M'_k$ and $m'_k$ be the new largest and smallest elements of the $k$th row.  We have $M'_1\ge M'_2 \ge ... \ge M'_m$ and $m_1'\ge m_2' \ge ... \ge m'_m$.  Let's try induction on $k$.
For $k=1$, suppose that $M'_1$ was originally in row $i$.  Then $M'_1\le M_i$.  We know that $m'_1$ is in the same column as some element originally from row $i$.  Let that element be $a_i$.  Therefore $m'_1\ge a_i\ge m_i$ so $M'_1-m'_1\le M_i-m_i\le d$.
Let $1<k\le m$.  Suppose that $M'_k$ was originally in row $i$ so $M'_k\le M_i$.  We know that $m'_k$ is in the same column as some element $a_i$ originally from row $i$.  Suppose that $a_i$ is in row $j$ after the change.  If $j\ge k$, then $m'_k\ge a_i\ge m_i$ so $M'_k-m'_k\le M_i-m_i\le d$.  We now assume $j<k$.  What to do here?
BTW in the book "Principles and Techniques in Combinatorics" this problem is in chapter 3 which is about pigeonhole principle.  So if you have a solution with pigeonhole that'd be great.

A: Here's an approach, but it doesn't use PP.
Claim: Given $n$ intervals $[a_i, a_i + d]$ on the real line.
In each interval, one real number $b_i$ is chosen.
Sort the $a_i, b_i$ in increasing order to get the sequences $a'_i, b'_i$
Then, $ b'_k \in [ a'_k , a'_k + d]$.
Proof: Do this yourself. If stuck, show what you've tried.
Show that $b'_k \geq a'_k$. Prove by contradiction.
Show that $b'_k \leq a'_k+d$. Prove by contradiction.
Corollary: The problem holds.
Let $ a_i = \min_k m_{i, k}$ be the minimum in each row.
Add an additional $n+1$st column, with entries  $m_{i,n+1} =d +  a_i$.
Fix a column $k$.
By definition, each element $m_{i, k} \in [a_i, a_i + d]$.
Now, apply the claim to conclude that $m'_{i, k}\in [a'_k, a'_k + d] \quad \forall i$.
Fix a row $i$.
We have  $m'_{i, k } \in [a'_k, a'_k + d] \quad \forall k$,
Hence, the difference between the max and min in each row (for $n+1$ columns) is still $ \leq d$.
Hence, the difference between the max and min in each row (for $n$ columns) is still $ \leq d$.

Note: In the claim, I used intervals of exactly length $d$ to ensure that we could sort the intervals cleanly. Otherwise, we could have nested intervals, and then it might not be clear how to sort the rows in increasing order.
As it turns out, this was unnecessary. We have a stronger claim:

Given $n$ intervals $[a_i, b_i]$, with elements $c_i \in [a_i, b_i]$, and we sort each individual sequence $a_i, b_i, c_i$ in increasing order, then $ c'_i \in [a'_i, b'_i]$.
Note: If we sorted the intervals just by the first coordinate, then the claim need not be true. IE $c'_i \not \in [a_{i'}, b_{i'}]$.

However, I can't apply the stronger claim to the problem. Any help here is greatly appreciated.  The trouble that I run into is that ultimately, we still have to show that $ b'_i - a'_i \leq d$. While this is recognizable as the 2 column case, it is essentially the entire argument (IE the induction on the number of columns is trivial).
My solution avoids this because $b'_i - a'_i = d$ by construction. Doing so felt a bit forced / unnatural, though I know why I thought of doing it.

A: Here is another approach, though it again doesn't use PP.
We first prove the 2 column case. Consider the bipartite graph, with vertices represented by these values in each column, and we draw an edge between 2 values in different columns if their difference is at most $d$.
Observe that each $a_i$ is connected to (at least the) corresponding $b_i$.
For a subset $C$ consisting of vertices in a column, let $Im(C)$ be the vertices that they are connected with. Then, the previous observation establishes $ |C| \leq |Im(C)|$.
Now, when we re-arrange the columns, suppose that $a_i'$ is not connected to $b_i'$.
$a_i'$ is connected to some $b_k'$. Let the minimal index be $K$, and $ i \neq K$.
WLOG $i < K$. (The case of $i>K$ can be dealt with similarly.)
Then, with $C = \{b_1', b_2', \ldots b_{K-1}'\}$, $Im(C) \subset \{a_1', a_2', \ldots a_{i-1}'\}$.
This gives us $|C| > |Im(C)|$, which is a contradiction.
Hence, $a_i'$ is connected to $b_i'$, so their difference is at most $d$.
Now, for the general $n-$column case, the above establishes that for any 2 columns, the rearranged columns have entries with difference at most $d$ in each row. Hence, this is true for the entire row.


text:
Q: How to plot array with dates of coordinates in python? I am new with python.
I have a array with coordinates, and i want to plot in 3d (X,Y,Z) only points.
My array look like Dates=[[x1,y1,z1],[x2,y2,z2],.....[xn,yn,zn]]
I tried:
plt.plot(Dates[:][0],Dates[:][1]Dates[:][2])

plt.show()

but only plot a point.
too:
for i in range(len(Dates)):
`plt.plot(Dates[i][0],Dates[i][1]Dates[i][2])`
 plt.show()

but plot point sequence and not all points in a figure.
Thanks for your help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SELECT etat, count( * ) AS 'nombre' from commande GROUP BY etat; how to transform this query to DQL :
SELECT etat, count( * ) AS 'nombre' from commande GROUP BY etat;

A: Please try this
select c,count(c.id) nombre from acmeBundle:commande c group by c.etat

Where clause is not included.
You should have commande entity. It will return all the fields from commande entity and count. You can rectify for your needs


text:
Q: jQuery: Currency Format Number I have number like this in my html

950000

and I want jQuery change it to

Rp. 950.000

How can I do that in jQUery?

A: There is a plugin for that, jquery-formatcurrency.
You can set the decimal separator (default .) and currency symbol (default $) for custom formatting or use the built in International Support.  The format for Bahasa Indonesia (Indonesia) - Indonesian (Indonesia) coded id-ID looks closest to what you have provided.

A: You can use this way to format your currency needing.
var xx = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
});
xx.format(123456.789); // '$123,456.79'

For more info you can access this link.
https://www.justinmccandless.com/post/formatting-currency-in-javascript/

A:

var input=950000;
var output=parseInt(input).toLocaleString();
alert(output);

A: $(document).ready(function() {
    var num = $('div.number').text()
    num = addPeriod(num);
    $('div.number').text('Rp. '+num)
});

function addPeriod(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    }
    return x1 + x2;
}

A: Divide by 1000, and use .toFixed(3) to fix the number of decimal places.
var output = (input/1000).toFixed(3);

[EDIT]
The above solution only applies if the dot in the original question is for a decimal point. However the OP's comment below implies that it is intended as a thousands separator.
In this case, there isn't a single line solution (Javascript doesn't have it built in), but it can be achieved with a fairly short function.
A good example can be found here: http://www.mredkj.com/javascript/numberFormat.html#addcommas
Alternatively, a more complex string formatting function which mimics the printf() function from the C language can be found here: http://www.diveintojavascript.com/projects/javascript-sprintf

A: Here is the cool regex style for digit grouping:
thenumber.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");

A: Please find in the below code what I developed to support internationalization. It formats the given numeric value to language specific format. In the given example I have used 'en' while have tested for 'es', 'fr' and other countries where in the format varies. It not only stops user from keying characters but formats the value on tab out. Have created components for Number as well as for Decimal format.
Apart from this have created parseNumber(value, locale) and parseDecimal(value, locale) functions  which will parse the formatted data for any other business purposes. The said function will accept the formatted data and will return the non-formatted value.
I have used JQuery validator plugin in the below shared code.
HTML:

                                    Number Field:

                                    <input type="text" id="numberField"
                                           name="numberField"
                                           class="form-control"
                                           autocomplete="off"
                                           maxlength="17"
                                           data-rule-required="true"
                                           data-msg-required="Cannot be blank."
                                           data-msg-maxlength="Exceeding the maximum limit of 13 digits. Example: 1234567890123"
                                           data-rule-numberExceedsMaxLimit="en"
                                           data-msg-numberExceedsMaxLimit="Exceeding the maximum limit of 13 digits. Example: 1234567890123"
                                           onkeydown="return isNumber(event, 'en')"
                                           onkeyup="return updateField(this)"
                                           onblur="numberFormatter(this,
                                                       'en',
                                                       'Invalid character(s) found. Please enter valid characters.')">

                                    Decimal Field:

                                    <input type="text" id="decimalField"
                                           name="decimalField"
                                           class="form-control"
                                           autocomplete="off"
                                           maxlength="20"
                                           data-rule-required="true"
                                           data-msg-required="Cannot be blank."
                                           data-msg-maxlength="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00"
                                           data-rule-decimalExceedsMaxLimit="en"
                                           data-msg-decimalExceedsMaxLimit="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00"
                                           onkeydown="return isDecimal(event, 'en')"
                                           onkeyup="return updateField(this)"
                                           onblur="decimalFormatter(this,
                                               'en',
                                               'Invalid character(s) found. Please enter valid characters.')">

JavaScript:
            /*
     * @author: dinesh.lomte
     */
    /* Holds the maximum limit of digits to be entered in number field. */
    var numericMaxLimit = 13;
    /* Holds the maximum limit of digits to be entered in decimal field. */
    var decimalMaxLimit = 16;

    /**
     *
     * @param {type} value
     * @param {type} locale
     * @returns {Boolean}
     */
    parseDecimal = function(value, locale) {

        value = value.trim();
        if (isNull(value)) {
            return 0.00;
        }
        if (isNull(locale)) {
            return value;
        }
        if (getNumberFormat(locale)[0] === '.') {
            value = value.replace(/\./g, '');
        } else {
            value = value.replace(
                    new RegExp(getNumberFormat(locale)[0], 'g'), '');
        }
        if (getNumberFormat(locale)[1] === ',') {
            value = value.replace(
                    new RegExp(getNumberFormat(locale)[1], 'g'), '.');
        }
        return value;
    };

    /**
     *
     * @param {type} element
     * @param {type} locale
     * @param {type} nanMessage
     * @returns {Boolean}
     */
    decimalFormatter = function (element, locale, nanMessage) {

        showErrorMessage(element.id, false, null);
        if (isNull(element.id) || isNull(element.value) || isNull(locale)) {
            return true;
        }
        var value = element.value.trim();
        value = value.replace(/\s/g, '');
        value = parseDecimal(value, locale);
        var numberFormatObj = new Intl.NumberFormat(locale,
                {   minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }
        );
        if (numberFormatObj.format(value) === 'NaN') {
            showErrorMessage(element.id, true, nanMessage);
            setFocus(element.id);
            return false;
        }
        element.value =
                numberFormatObj.format(value);
        return true;
    };

    /**
     *
     * @param {type} element
     * @param {type} locale
     * @param {type} nanMessage
     * @returns {Boolean}
     */
    numberFormatter = function (element, locale, nanMessage) {

        showErrorMessage(element.id, false, null);
        if (isNull(element.id) || isNull(element.value) || isNull(locale)) {
            return true;
        }
        var value = element.value.trim();
        var format = getNumberFormat(locale);
        if (hasDecimal(value, format[1])) {
            showErrorMessage(element.id, true, nanMessage);
            setFocus(element.id);
            return false;
        }
        value = value.replace(/\s/g, '');
        value = parseNumber(value, locale);
        var numberFormatObj = new Intl.NumberFormat(locale,
                {   minimumFractionDigits: 0,
                    maximumFractionDigits: 0
                }
        );
        if (numberFormatObj.format(value) === 'NaN') {
            showErrorMessage(element.id, true, nanMessage);
            setFocus(element.id);
            return false;
        }
        element.value =
                numberFormatObj.format(value);
        return true;
    };

    /**
     *
     * @param {type} id
     * @param {type} flag
     * @param {type} message
     * @returns {undefined}
     */
    showErrorMessage = function(id, flag, message) {

        if (flag) {
            // only add if not added
            if ($('#'+id).parent().next('.app-error-message').length === 0) {
                var errorTag = '
' + message + '
';
                $('#'+id).parent().after(errorTag);
            }
        } else {
            // remove it
            $('#'+id).parent().next(".app-error-message").remove();
        }
    };

    /**
     *
     * @param {type} id
     * @returns
     */
    setFocus = function(id) {

        id = id.trim();
        if (isNull(id)) {
            return;
        }
        setTimeout(function() {
            document.getElementById(id).focus();
        }, 10);
    };

    /**
     *
     * @param {type} value
     * @param {type} locale
     * @returns {Array}
     */
    parseNumber = function(value, locale) {

        value = value.trim();
        if (isNull(value)) {
            return 0;
        }
        if (isNull(locale)) {
            return value;
        }
        if (getNumberFormat(locale)[0] === '.') {
            return value.replace(/\./g, '');
        }
        return value.replace(
                new RegExp(getNumberFormat(locale)[0], 'g'), '');
    };

    /**
     *
     * @param {type} locale
     * @returns {Array}
     */
    getNumberFormat = function(locale) {

        var format = [];
        var numberFormatObj = new Intl.NumberFormat(locale,
                {   minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }
        );
        var value = numberFormatObj.format('132617.07');
        format[0] = value.charAt(3);
        format[1] = value.charAt(7);
        return format;
    };

    /**
     *
     * @param {type} value
     * @param {type} fractionFormat
     * @returns {Boolean}
     */
    hasDecimal = function(value, fractionFormat) {

        value = value.trim();
        if (isNull(value) || isNull(fractionFormat)) {
            return false;
        }
        if (value.indexOf(fractionFormat) >= 1) {
            return true;
        }
    };

    /**
     *
     * @param {type} event
     * @param {type} locale
     * @returns {Boolean}
     */
    isNumber = function(event, locale) {

        var keyCode = event.which ? event.which : event.keyCode;
        // Validating if user has pressed shift character
        if (keyCode === 16) {
            return false;
        }
        if (isNumberKey(keyCode)) {
            return true;
        }
        var numberFormatter = [32, 110, 188, 190];
        if (keyCode === 32
                && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {
            return true;
        }
        if (numberFormatter.indexOf(keyCode) >= 0
                && getNumberFormat(locale)[0] === getFormat(keyCode)) {
            return true;
        }
        return false;
    };

    /**
     *
     * @param {type} event
     * @param {type} locale
     * @returns {Boolean}
     */
    isDecimal = function(event, locale) {

        var keyCode = event.which ? event.which : event.keyCode;
        // Validating if user has pressed shift character
        if (keyCode === 16) {
            return false;
        }
        if (isNumberKey(keyCode)) {
            return true;
        }
        var numberFormatter = [32, 110, 188, 190];
        if (keyCode === 32
                && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {
            return true;
        }
        if (numberFormatter.indexOf(keyCode) >= 0
                && (getNumberFormat(locale)[0] === getFormat(keyCode)
                    || getNumberFormat(locale)[1] === getFormat(keyCode))) {
            return true;
        }
        return false;
    };

    /**
     *
     * @param {type} keyCode
     * @returns {Boolean}
     */
    isNumberKey = function(keyCode) {

        if ((keyCode >= 48 && keyCode <= 57)
                || (keyCode >= 96 && keyCode <= 105)) {
            return true;
        }
        var keys = [8, 9, 13, 35, 36, 37, 39, 45, 46, 109, 144, 173, 189];
        if (keys.indexOf(keyCode) !== -1) {
            return true;
        }
        return false;
    };

    /**
     *
     * @param {type} keyCode
     * @returns {JSON@call;parse.numberFormatter.value|String}
     */
    getFormat = function(keyCode) {

        var jsonString = '{"numberFormatter" : [{"key":"32", "value":" ", "description":"space"}, {"key":"188", "value":",", "description":"comma"}, {"key":"190", "value":".", "description":"dot"}, {"key":"110", "value":".", "description":"dot"}]}';
        var jsonObject = JSON.parse(jsonString);
        for (var key in jsonObject.numberFormatter) {
            if (jsonObject.numberFormatter.hasOwnProperty(key)
                    && keyCode === parseInt(jsonObject.numberFormatter[key].key)) {
                return jsonObject.numberFormatter[key].value;
            }
        }
        return '';
    };

    /**
     *
     * @type String
     */
    var jsonString = '{"shiftCharacterNumberMap" : [{"char":")", "number":"0"}, {"char":"!", "number":"1"}, {"char":"@", "number":"2"}, {"char":"#", "number":"3"}, {"char":"$", "number":"4"}, {"char":"%", "number":"5"}, {"char":"^", "number":"6"}, {"char":"&", "number":"7"}, {"char":"*", "number":"8"}, {"char":"(", "number":"9"}]}';

    /**
     *
     * @param {type} value
     * @returns {JSON@call;parse.shiftCharacterNumberMap.number|String}
     */
    getShiftCharSpecificNumber = function(value) {

        var jsonObject = JSON.parse(jsonString);
        for (var key in jsonObject.shiftCharacterNumberMap) {
            if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)
                    && value === jsonObject.shiftCharacterNumberMap[key].char) {
                return jsonObject.shiftCharacterNumberMap[key].number;
            }
        }
        return '';
    };

    /**
     *
     * @param {type} value
     * @returns {Boolean}
     */
    isShiftSpecificChar = function(value) {

        var jsonObject = JSON.parse(jsonString);
        for (var key in jsonObject.shiftCharacterNumberMap) {
            if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)
                    && value === jsonObject.shiftCharacterNumberMap[key].char) {
                return true;
            }
        }
        return false;
    };

    /**
     *
     * @param {type} element
     * @returns {undefined}
     */
    updateField = function(element) {

        var value = element.value;

        for (var index = 0; index < value.length; index++) {
            if (!isShiftSpecificChar(value.charAt(index))) {
                continue;
            }
            element.value = value.replace(
                    value.charAt(index),
                    getShiftCharSpecificNumber(value.charAt(index)));
        }
    };

    /**
     *
     * @param {type} value
     * @param {type} element
     * @param {type} params
     */
    jQuery.validator.addMethod('numberExceedsMaxLimit', function(value, element, params) {

        value = parseInt(parseNumber(value, params));
        if (value.toString().length > numericMaxLimit) {
            showErrorMessage(element.id, false, null);
            setFocus(element.id);
            return false;
        }
        return true;
    }, 'Exceeding the maximum limit of 13 digits. Example: 1234567890123.');

    /**
     *
     * @param {type} value
     * @param {type} element
     * @param {type} params
     */
    jQuery.validator.addMethod('decimalExceedsMaxLimit', function(value, element, params) {

        value = parseFloat(parseDecimal(value, params)).toFixed(2);
        if (value.toString().substring(
                0, value.toString().lastIndexOf('.')).length > numericMaxLimit
                || value.toString().length > decimalMaxLimit) {
            showErrorMessage(element.id, false, null);
            setFocus(element.id);
            return false;
        }
        return true;
    }, 'Exceeding the maximum limit of 16 digits. Example: 1234567890123.00.');

    /**
     * @param {type} id
     * @param {type} locale
     * @returns {boolean}
     */
    isNumberExceedMaxLimit = function(id, locale) {

        var value = parseInt(parseNumber(
                document.getElementById(id).value, locale));
        if (value.toString().length > numericMaxLimit) {
            setFocus(id);
            return true;
        }
        return false;
    };

    /**
     * @param {type} id
     * @param {type} locale
     * @returns {boolean}
     */
    isDecimalExceedsMaxLimit = function(id, locale) {

        var value = parseFloat(parseDecimal(
                document.getElementById(id).value, locale)).toFixed(2);
        if (value.toString().substring(
                0, value.toString().lastIndexOf('.')).length > numericMaxLimit
                || value.toString().length > decimalMaxLimit) {
            setFocus(id);
            return true;
        }
        return false;
    };

A: function converter()
{

var number = $(.number).text();

var number = 'Rp. '+number;

s(.number).val(number);
}

A: you can also do it using Inputmask Library ...
for demo see here
$(document).ready(function(){
    $("#amount").inputmask('decimal', {
        'alias': 'numeric',
        'groupSeparator': ',',
        'digits': 2,
        'digitsOptional': false,
        // 'prefix': 'Rs ',
        'placeholder': '0',
        /* 'autoGroup': true,
        'radixPoint': ".",
        'allowMinus': false,*/
    });
});


text:
Q: is it better to get few properties from a vertex or getting the whole vertex in gremlin which of these queries is cost effective when considering network calls and query process time
1)
g.V().has('personId','1234')
=> V[4232]

2)
g.V().has('personId','1234').values('name','age')
=> chris
=> 24

3)
g.V().has('personId','1234').valueMap('name','age')
    => [name:[chris],age:[24]]

4)
 g.V().has('personId','1234').properties('name','age')
        => vp[name->chris
         =>vp[age->24]

does getting the whole vertex cost us more of network bandwidth . i usually get vertices as the query processing is done quickly

A: The cheapest will be options two and three. Returning an Element, which would be  a Vertex, Edge, VertexProperty will be more costly than returning an individual result or a Map or results. Even the following is less expensive than returning an entire Element:
g.V(1).valueMap(true)

which from a data perspective is basically the same as g.V(1).
The basic rule ends up being not so different than SQL. You likely wouldn't do a SELECT * FROM table, nor should you return all the data from an element - only retrieve the data you need.


text:
Q: jQuery Mobile 1.1.0 RC1 Modifying HREF for AJAX Posts in iOS Safari Disclaimer: I am using jQuery Mobile 1.1.0 RC1 which is not a stable release yet. I have a link that needs to post an AJAX request and return a JSON response but when the link is clicked it seems that jQuery Mobile changes the HREF to a hash (#) in iOS Safari on the iPhone. It does not do this when testing in browsers with iPhone User Agents. Here is my basic HTML and JS to show what I have:
Send Ajax Request

and the JS
$('#tab a').on('click', function(e){
        var $this = $(this);
        var jsonUrl = $this.attr("href");
        alert(jsonUrl);

        $.mobile.showPageLoadingMsg();

        $.ajax({
            type: "POST",
            url: jsonUrl,
            success: function(data) {
                $.mobile.hidePageLoadingMsg();
                alert(data);
            }
        });
        return false;
});

The value for "jsonUrl" becomes "#" (instead of the url to my ajax request) and then the value of the data variable returns the entire page and not the JSON feed that I want. The weird thing is that this only happens in iOS Safari on the iPhone. It works fine and the JSON feed comes back when I try the jQuery Mobile site with a different user agent in OSX Safari or Firefox.
I've tried adding rel="external" and data-type="ajax" to the link and it doesn't fix it. I'm also using jQuery Mobile 1.1.0 RC1, but I'm not sure if that is the issue or if I'm just not using jQuery Mobile correctly. I also don't have any other jQuery Mobile specific JS in my code, so maybe I'm missing something that will fix this. Appreciate the help.

A: Instead of:
$this.attr('href')

Use this:
$this.data('href') || $this.attr('href')

jQuery Mobile 1.1.0RC1 and on (including released 1.1.0) will set the href to any link to # when it is clicked, and store the href in a data-href attribute, until it's done doing it's thing, then put it back. It only does this on iOS Mobile Safari.
I've blogged a bit more about this, with links to related github issues discussions and some info on applying this with Ruby on Rails jQuery UJS here:
http://scottwb.com/blog/2012/06/29/jquery-mobile-breaks-your-hrefs-on-ios-mobile-safari/


text:
Q: Can one use Window.Onscroll method to include detection of scroll direction? Can one use Window.Onscroll method to include detection of scroll direction?

A: If you record the scrollX and scrollY on page load and each time a scroll event occurs, then you can compare the previous values with the new values to know which direction you scrolled.  Here's a proof of concept:
function scrollFunc(e) {
    if ( typeof scrollFunc.x == 'undefined' ) {
        scrollFunc.x=window.pageXOffset;
        scrollFunc.y=window.pageYOffset;
    }
    var diffX=scrollFunc.x-window.pageXOffset;
    var diffY=scrollFunc.y-window.pageYOffset;

    if( diffX<0 ) {
        // Scroll right
    } else if( diffX>0 ) {
        // Scroll left
    } else if( diffY<0 ) {
        // Scroll down
    } else if( diffY>0 ) {
        // Scroll up
    } else {
        // First scroll event
    }
    scrollFunc.x=window.pageXOffset;
    scrollFunc.y=window.pageYOffset;
}
window.onscroll=scrollFunc

A: With jquery, you can also register a custom scroll event which supplies the scroll change as an argument to the event handler:
var previous_scroll = $(window).scrollTop();

$(window).on('scroll', function() {
    var scroll = $(window).scrollTop(),
        scroll_change = scroll - previous_scroll;
    previous_scroll = scroll;
    $(window).trigger('custom_scroll', [scroll_change]);
});

Then instead of scroll, bind to custom_scroll:
$(window).on('custom_scroll', function pos(e, scroll_change) {
    console.log(scroll_change);
});

A: I had trouble making this work in ie8 (although it is compliant for ie9, FF and Chrome) - all scrolls seem to be detected as horizontal.
Here is a modified script demo that also works in ie8 and may cover a few more browsers.
function scrollFunc(e) {

   function getMethod() {
        var x = 0, y = 0;
        if ( typeof( window.pageYOffset ) == 'number' ) {
          x = window.pageXOffset;
          y = window.pageYOffset;
        }

        else if( document.body && (document.body.scrollLeft || document.body.scrollTop ) ) {
          x = document.body.scrollLeft;
          y = document.body.scrollTop;
        }

        else if( document.documentElement && (document.documentElement.scrollLeft ||     document.documentElement.scrollTop ) ) {
          x = document.documentElement.scrollLeft;
          y = document.documentElement.scrollTop;
        }

         return [x, y];
    }

    var xy = getMethod();
    var xMethod = xy[0];
    var yMethod = xy[1];

    if ( typeof scrollFunc.x == 'undefined' ) {
       scrollFunc.x = xMethod;
       scrollFunc.y = yMethod;
    }

    var diffX = scrollFunc.x - xMethod;
    var diffY = scrollFunc.y - yMethod;

    if( diffX<0 ) {
       // Scroll right
    } else if( diffX>0 ) {
       // Scroll left
    } else if( diffY<0 ) {
       // Scroll down
    } else if( diffY>0 ) {
       // Scroll up
    } else {
       // First scroll event
    }
    scrollFunc.x = xMethod;
    scrollFunc.y = yMethod;
}

window.onscroll=scrollFunc


text:
Q: How can i make space after punctations in C My Homework is
Some certain punctuations, period (.), comma (,), colon (:), semi-colon (;), question mark
(?), and exclamation mark(!), should be followed by a space. For example, the following
strings should be corrected because there is no space after the above punctuations.
(There might be some other punctuations which need a space after; however, given
punctuations (.,:;?!) will suffice)
I saw you playing soccer.You are such a good player.
I saw you playing soccer. You are such a good player.
Hello!How are you?Fine thanks,and you.
Hello! How are you? Fine thanks, and you.
I am trying to make space after all punctations but i getting error
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char string[200];
scanf("%s", string[200]);
char string1[200] = " ";
for(int i=0;i<strlen(string);i++){
if( s[i] !='.' && ',' && ';' && ':' && '!' && '?'){

  string1 = string1 + string[i];

}

else{

  string1= string1 + string[i] + " ";

}
}
string = string1;
printf("new string : %s", string);
return 0;
}

can someone help me  or can someone convert my c++ code to C
using namespace std;
int main()
{
string s;
cout<<"Please enter the string"<<endl;
cin>>s;

cout<<"Input string:"<<s<<endl;
string s1="";
for(int i=0;i<s.length();i++)
{
    if(s[i]!='.'&&s[i]!=','&&s[i]!=';'&&s[i]!=':'&&s[i]!='!'&&s[i]!='?')
    s1=s1+s[i];
    else
    s1=s1+s[i]+" ";
}
s=s1;
cout<<"Updated string:"<<s<<endl;
return 0;
}

I am trying to make space but cant in C lang can someone figured out ?

A: Operator + does not work on operands of type char[]. You should just copy the characters to string1:
for(int i = 0, i1 = 0, string_length = strlen(string); i < string_length; i++)
{
    string1[i1++] = string[i];

    if (string[i] is one of the punctuation characters)
        string1[i1++] = ' ';
}

I moved strlen call to initialization part of the for loop so that it's called only once, instead of many times.
But pay attention to one minor problem with this code. If the punctuation character is already followed by a space then the resulting string will have two spaces. If you are not fine with this then you would have to add more code.


text:
Q: How to select nodes where all children is satisfied? I have a tree structure of light bulbs. I want to turn on all the light bulbs starting from the leafs of the tree. A light bulb cannot be turned on unless all its immediate children are turned on.
The relation between the nodes in the tree structure is represented by table A:
Table A:

node_id integer
  child_node_id integer

Table B represents the nodes in the tree:
Table B:

id integer
  state boolean

The state of table B represents the states true = on and false = off.
Question:
I would like to select all the light bulbs which are turned off AND has all immediate children turned on.
This is probably very simple, but I can't seem to get my head around it.

A: I would first rethink the design. You only need one table:
CREATE TABLE c (
  id integer PRIMARY KEY
 ,parent_id integer REFERENCES c(id)
 ,state boolean
);

With the layout as presented in the question, the query could be:
SELECT DISTINCT a.*
FROM   a
JOIN   b ON a.node_id = b.id
LEFT   JOIN a ca ON ca.child_node_id = a.node_id
LEFT   JOIN b cb ON cb.id = ca.node_id AND cb.state = FALSE
WHERE  b.state = FALSE
AND    cb.id IS NULL

This includes nodes that are turned off and have no children at all.
To exclude nodes without children, replace the first LEFT JOIN with a plain JOIN.
Or, may be faster:
SELECT a.*
FROM   a
JOIN   b ON a.node_id = b.id
WHERE  NOT EXISTS (
   SELECT 1
   FROM   a ca
   JOIN   b cb ON cb.id = ca.node_id
   WHERE  ca.child_node_id = a.node_id
   AND    cb.state = FALSE
   )


text:
Q: How to checkout submodule in GitHub action? I've got a repository with a submodule and I'm creating a build when I push to certain branches or tags. The problem I have is that my checkout step cannot access my submodule. The setup is:

*

*Both repositories are on GitHub.

*I'm the owner of both repositories.

*Both repositories are private.

*The repositories are only accessible with ssh (https disabled).

I've tried using the GitHub Action actions/checkout@v2 to no avail. As can be seen below I've tried using the 'ssh-key' option where I've added the public key to the the submodules repositories deploy keys and the private key to the secrets of the repository where I run the action. I get the following error messages:
Fetching the repository
  /usr/bin/git -c protocol.version=2 fetch --no-tags --prune --progress --no-recurse-submodules --depth=1 origin __myrepo__
  ERROR: Repository not found.
  Error: fatal: Could not read from remote repository.

  Please make sure you have the correct access rights
  and the repository exists.
  The process '/usr/bin/git' failed with exit code 128
  Waiting 13 seconds before trying again
  /usr/bin/git -c protocol.version=2 fetch --no-tags --prune --progress --no-recurse-submodules --depth=1 origin __myrepo__
  ERROR: Repository not found.
  Error: fatal: Could not read from remote repository.

  Please make sure you have the correct access rights
  and the repository exists.
  The process '/usr/bin/git' failed with exit code 128
  Waiting 19 seconds before trying again
  /usr/bin/git -c protocol.version=2 fetch --no-tags --prune --progress --no-recurse-submodules --depth=1 origin __myrepo__
  ERROR: Repository not found.
  Error: fatal: Could not read from remote repository.

  Please make sure you have the correct access rights
  and the repository exists.
  Error: The process '/usr/bin/git' failed with exit code 128

I've tried with and without the ssh-key as well as with true and recursive option on submodules. The destination of the submodule is in a directory called src. The checkout step in my workflow is the following:
Step-01:
  runs-on: ubuntu-18.04
  steps:
    - name: Checkout repository
      uses: actions/checkout@v2
      with:
        submodules: 'true'
        ssh-key: ${{ secrets.PRIVATE_KEY_FOR_DEPLOY_KEY_IN_SUBMODULE }}

The .gitmodules is:
[submodule "name"]
    path = src/name
    url = git@github.com:user/repository.git
    branch = master

I'm very new to GitHub Actions (CI/CD overall) and not super comfortable with submodules so I may very well have made some basic mistakes.

A: I finally got it working, completely thanks to this.
To clarify the situation SAML SSO is enforced. So instead of using SSH to try and access the submodule I used a personal access token (PAT) where the SSO has been authorized.
What I did:

*

*I generated a PAT in account settings.

*I enabled SSO and authorized it.

*I added the token in the repository (that wants to access the submodule) secrets.

*I updated the workflow to the following (just change the ssh-key line).

Step-01:
  runs-on: ubuntu-18.04
  steps:
    - name: Checkout repository
      uses: actions/checkout@v2
      with:
        submodules: 'true'
        token: ${{ secrets.PAT_TOKEN }}

A: Got it working as well, mostly thanks to @Nelumbo answer above.
Few things to keep in mind if you use new fine-grained Personal Access Tokens (PAT):

*

*Make sure that to add permission to access the parent repo as well, not only submodule repos, because when token param to checkout step this token will be used to checkout everything, not only submodules.

*The token is good for a year max, so be prepared that the issue will come back, set a reminded and do not freak out.

*The token only needs to have read-only permissions to Contents and Metadata (from Repository permissions), and none of the Account permissions.


text:
Q: How to specify a COMSTR for the Command Builder in 'scons' Many of the builtin builders in scons have $*COMSTR variables which are used to change the default output of their associated Builder.  We can use $*COMSTR variables to optionally make our build processes more legible.
I would like to set a $*COMSTR variable for a Command builder.
target = 'mydb.db3'

populatesql = 'populate.sql'
sources = [populatesql]

command = '@sqlite3 $TARGET < ' + populatesql

built_database = env.Command(target, sources, command)

I've found that I can prefix my command with the '@' character to suppress output, but I've been unable to discover how to utilize a $*COMSTR with the Command builder.  Am I missing a trick here?
Thanks.

A: You don't associate a command string with a builder. Command strings are associate with an Action object.
If you want a command string, just write something like this:
built_database = env.Command(target, sources,
                             Action('mySqlite3', 'Generating $TARGET with sqlite3'))

or if you want that more fine tuned
env['SQLITE3COMSTR'] = 'Generating $TARGET from $SOURCES with sqlite3'
...
built_database = env.Command(target, sources, Action('mySqlite3', '$SQLITE3COMSTR'))


text:
Q: Error with QGIS and Grass Tools I wanted to use the r.viewshed tool in QGIS. Everytime I want to start the tool there is a error (german):
Dieser Algorithmus kann nicht ausgeführt werden run :-(
GRASS GIS 7 ist anscheinend nicht richtig auf dem System installiert und konfiguriert. Bitte vor der Ausführung von GRASS GIS 7-Algorithmen installieren.
Do I have to install GRASS 7 to use the tools?
I am using a Mac with 10.13 and QGIS 2.18


text:
Q: Thunderbird outgoing password Roadrunner/time warner/spectrum now required a password for outgoing mail.  I use a different server for incoming mail. How do I set the outgoing password?
Thunderbird 52.3.0

A: FWIW, SMTP (outgoing mail dispatch) is busted in my area.   But the Thunderbird config with authenticated outgoing mail that has worked for months for me is this, for outgoing mail, under Tools, Account Settings


text:
Q: Query two db using group by and display detail information I have two tables
1: itemInfo
product_id  brand   name    category
1   Garden  Goodcake    cake

2: itemRecord
record_id shopType price inputTime product_id
1   0   7.2     2012-03-20 17:58:56 1
69  2   6.4     2012-03-20 19:33:12 1
70  0   9.9     2012-03-19 00:00:00 1
71  3   5.5     2012-03-18 05:22:00 1
72  0   6.8     2012-03-19 20:26:29 1
73  0   10.1    2012-03-17 12:27:00 1
74  3   7.9     2012-03-16 00:00:00 1
75  1   6.7     2012-03-15 00:00:00 1
76  1   8.8     2012-03-14 11:24:00 1
77  2   12.5    2012-03-13 10:26:19 1
78  0   7.2     2012-03-21 11:25:23 1
146 2   5       2012-03-21 12:53:04 1
149 3   4.9     2012-03-21 10:00:00 1
150 3   5.1     2012-03-21 12:20:00 1

I would like to display the latest 7 days of cheapest price of product_id = 1.
If the same day, the cheapest price is same, just display the latest.
The final table should be:
product_id brand   name     category inputTime  shopType minimum_price record_id
1          Garden  Goodcake cake     2012-03-21 3        4.9           149
1          Garden  Goodcake cake     2012-03-20 2        6.4           69
1          Garden  Goodcake cake     2012-03-19 2        6.8           72
...
1          Garden  Goodcake cake     2012-03-15 1        6.7           75

I have tried my best to write a sql that like:
SELECT r.product_id, i.brand, i.name, i.category, DATE_FORMAT( r.inputTime, '%e-%b' ) AS inputTime, r.shopType, MIN( r.price ) AS minimum_price, r.record_id
FROM itemRecord AS r, itemInfo AS i
WHERE r.product_id = '1'
AND i.id = r.product_id
GROUP BY DATE( r.inputTime ) DESC
LIMIT 0 , 7

However, the table is:
product_id  brand   name    category    inputTime   shopType    minimum_price   record_id
1   Garden  Goodcake cake       21-Mar  0   4.9     78
1   Garden  Goodcake cake       20-Mar  0   6.4     1
1   Garden  Goodcake cake       19-Mar  0   6.8     70
1   Garden  Goodcake cake       18-Mar  3   5.5     71
1   Garden  Goodcake cake       17-Mar  0   10.1    73
1   Garden  Goodcake cake       16-Mar  3   7.9     74
1   Garden  Goodcake cake       15-Mar  1   6.7     75

For example, the first row result, it displays the correct minimum price 4.9, but the record_id is wrong, also, the shopType is wrong too.
I have research a lot, but still cannot solve the problem.
Please help...

A: JOIN them:
SELECT r.product_id, i.brand, i.name, i.category, DATE_FORMAT( r.inputTime, '%e-%b' ) AS inputTime, r.shopType, r.price AS minimum_price, r.record_id
FROM (  SELECT *
        FROM itemRecord
        WHERE product_id = '1'
        ORDER BY price ASC, inputTime DESC) AS r
INNER JOIN itemInfo As i
ON r.product_id = i.product_id
WHERE i.id = r.product_id
GROUP BY DATE(r.inputTime)
LIMIT 0, 7

Explanation:
I do an inner query which renders the table order by price ASC instead of the default, lets say id ASC. When you GROUP BY the rows, it uses the columns from the first row by default, which in this case is the one with lowest price.
Your solution didn't work since it might aswell have chosen the first id and not the lowest price row. The only column which was correct was the MIN( r.price ), but as you noticed that function did not affect the other columns in the result.


text:
Q: class.openid.php file content is displayed on the page When I start the page (on my development environment) I see content of a php file
content of a class.openid.php on the page.
On the production site everything is ok.
Why that is happening?

A: This normally means that the PHP parser isn't being invoked. (Unless of course other .php files are being loaded correctly.)
As such, you need to check the web server with your development environment to ensure that the necessary content handler and module for PHP is being loaded and that .php files are assigned to that handler, etc.

A: Probably, short_open_tag in PHP configuration is set to 0 and your class.openid.php has <? instead of <?php in the beginning of the file.
Open class.openid.php, locate <? at the beginning of the file and replace it with <?php

A: There are 4 reasons this might happen:

*

*Apache handler for PHP is broken (n/a in your case)

*PHP is somehow broken (n/a in your case)

*The code uses short open tag (<?...?>) but it's turned off in the server

*File EOL is somehow broken, typical of FTP clients (change FTP upload type from ASCII/text to binary)*

*You can find this by editing the uploaded file, the code will most likely show up on the same line. If this is the case, I sure hope you have a copy of the file in question :), or else you're have to add the new lines manually yourself.


text:
Q: Outlook Exchange change email from name base on send Is it possible to change the From Name of an email (not the sending address) when sending an email from Outlook Exchange?
Is there any add-in that can help us achieve this?
I can see with Exchange only admin can change the sending from name. Is there an alternative?

A: In general, you can't do that out of the box. The latest version of hosted (M365) Exchange allows to configure a mailbox to send as one of its proxy SMTP addresses, but the sender display name will still be the same.
You can try to use an addin like Proxy Manager (I am its author) - besides allowing to send through any of the mailbox proxy addresses, it also allows an end-user to change the sender display name.


text:
Q: Using variables in typeScript graphQL code generator I followed this tutorial to auto generate the schema of my graphql endpoint in my front application.
However now I need to use variables, so I did something like this:
export const GET_TODO = gql`
  query GetTodo($id: Int!) {
    todos(id: $id) {
        id
        text
        completed
      }
    }
  }

I want to know if there is a way I can get the variable type "automatically" without having to redefine it in the front.
E.g.
...
 query GetTodo($id: AutoGeneratedTodoIdType) {
...

PS: I am using react, in case there are framework/library specific solutions.

A: Yes you can, you will usually have exported types in the generated file such as GetTodoVariables


text:
Q: How to determine which MasterPage an error was generated from? We have a large ASP WebForms application and I'm trying to make the error page look better and be more helpful.  We have several MasterPages, one of them is for displaying content inside an iframe in a modal window we open via JavaScript.  Right now if an error occurs in one of these modal pages the modal iframe gets redirected to our ~/Error.aspx page with contains the normal site design  - inside the modal which is on top of the site design.  It looks quite dumb.
What I'd like to do is determine the masterpage of the page that generated the error, and then change the masterpage of the Error page so that it does not repeat the design from inside the iframe.  Is this possible to do?

A: After a lot of debugging, I seem to have found a way to do what I want in VB, although it's a  bit hacky...
Public Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    'Attempt to determine if this error came from a page displayed within a modal
    Dim page = TryCast(HttpContext.Current.CurrentHandler, _BasePage)
    If page IsNot Nothing Then
        Dim masterPageFile As String = page.MasterPageFile
        'The best we can to here is to find the masterpage and see if it
        'contains the string "modal" since that's normally how we name these things
        If Not String.IsNullOrWhiteSpace(masterPageFile) AndAlso masterPageFile.Contains("modal", StringComparison.OrdinalIgnoreCase) Then
            '==============
            'We did it!!!
            '==============
         End If
    Else
        'Either `HttpContext.Current.CurrentHandler` or `Page` is `Nothing`, so this might be a 404 or other error.
        'Let's see if there are other ways to determine if we are in a modal.

        Dim pathToAttemptedFile = HttpContext.Current.Request.Path
        Dim referrerUrl = HttpContext.Current.Request.UrlReferrer.AbsolutePath

        If (Not String.IsNullOrWhiteSpace(pathToAttemptedFile) AndAlso pathToAttemptedFile.Contains(tokenInUrlPath, StringComparison.OrdinalIgnoreCase)) OrElse
           (Not String.IsNullOrWhiteSpace(referrerUrl) AndAlso referrerUrl.Contains(tokenInUrlPath, StringComparison.OrdinalIgnoreCase)) Then
            '==============
            'We did it!!!
            '==============
        End If
    End If
End Sub


text:
Q: blank fields getting submitted on struts2 action
*

*The arraylist variable name is itmLst in action.

*Item PurchaseDate,EntryDate,ItemCost and ItemDepreciation fields are to be displayed and accepted from user and to be submitted to action.

<s:iterator value = "itmLst" status="row_id" var="itmLst" id="itmLst" >
    <s:if test="#row_id.index % 2 == 0">

    </s:if>
    <s:else>

    </s:else>

         <s:property value="itemNo" />
         <s:text name=":" />
         <s:property value="itemName" />

       <s:textfield name = "itmLst.purDmys"
                   value = "%{itmLst[#row_id.index].purDmys}"
                      id = "purDmys%{#row_id.count}"
                cssClass = "TCMask[##/##/####,dd/mm/yyyy] textfield-date-month"
               maxLength = "10" />

    <s:if test='itmLst.entCod == "T" || itmLst.entCod == "t"'>

           <s:textfield name = "itmLst.entDmys"
                       value = "%{itmLst[#row_id.index].entDmys}"
                          id = "entDmys%{#row_id.count}"
                    cssClass = "TCMask[##/##/####,dd/mm/yyyy] textfield-date-month"
                   maxLength = "10" />

     </s:if>
     <s:else>

            <s:text name="N/A" />

    </s:else>
     <s:property value="itemStatus" />

           <s:textfield name = "itmLst.itemCost"
                          id = "itemCost%{#row_id.count}"
                       value = "%{itmLst[#row_id.index].itemCost}"
                    cssClass = "textfield-amount"
                   maxLength = "10" />

         <s:textfield name = "itmLst.itemDepr"
                        id = "itemDepr%{#row_id.count}"
                     value = "%{itmLst[#row_id.index].itemDepr}"
                  cssClass = "textfield-amount"
                 maxLength = "10" />

     <s:property value="depDmys" />
     <s:property value="sgDepAmt" />

         <s:select name = "itmLst.actionSel"
                   list = "#{ 'K':getText('Keep As It Is'),'M':getText('Update Modified Values') ,'D':getText('Delete Item') }"
                  theme = "simple" />

    <s:if test="#row_id.index % 10 == 0">

                <s:submit key = "update"
                     cssClass = "ovalbutton"
                       method = "postItems" />

                <s:submit key = "cancel"
                     cssClass = "ovalbutton"
                           id = "cancelBtn"
                       method = "cancel"/>

    </s:if>
</s:iterator>

A: When submitted from JSP to action class, the list will always be blank unless you have named the elements on JSP like itmList[0].itemNo, itmList[0].purDmys etc.
You can assign these names while iterating the list.


text:
Q: Sonar.tests property for test class My java package has both source and junit in same package then, how to define sonar.tests property for the below case?
Source file: /src/java/ABC/Hello.java
Test file.    : /src/java/ABC/HelloUnitTest.java
And seems the property only looks for directories not files to separate them.


text:
Q: Does jquery clone() user documentfragment internally? I am inserting elements into dom dynamically and for that i m using following steps :(jquery) The initial dom structure is as below:
<div parent div>
 </div>
 <div child div template>
</div>

*

*clone the parent div using jquery .clone()

*clone the child div and do manipulation

*append to the cloned parent

*do this for all child data

*(parentdiv original).replaceAll(clonedparent)
Basically i want to clone the parent div in a manner so that it is available as a
documentfragment and so that appending doesnt happen on the dom and gain performance .
Will jQuery clone() give the performance advantage by behaving like documentfragment?
Or is there a better way to do this? I don't want to construct each child element as HTML string as the structure of them is pretty complex.

A: jQuery clone() does a plain DOM cloneNode(), except on IE, which inappropriately copies event listeners if you do that. To work around that, on IE jQuery does something utterly ghastly which really you don't want to know about. Which ain't fast.
replaceAll() is also not fast. It has to remove each child node from the DOM (which is particularly slow in jQuery because of its need to check data when removing something from the DOM) and add the new nodes one-by-one.
I don't really see what cloning gets you here really. Just do the manipulations directly on the children. If you've got a lot of manipulations to do and you're triggering relayouts that make it slow, you could temporarily hide the parent or detach it from the document, re-appending it when you're finished.


text:
Q: Any suggestions on why ytdl wouldn't be downloading my video properly? I am currently creating a discord bot that will download a YouTube video into video.mp4 and play that video using the established connection, however, I keep getting this unfamiliar error that I am not sure how to interpret. The important section of my code is as follows:
        console.log(video); //YouTube video id ex: 6Fw4B5ALC1o
        const connection2 = joinVoiceChannel({
            channelId: msg.member.voice.channel.id,
            guildId: msg.guild.id,
            adapterCreator: msg.channel.guild.voiceAdapterCreator

        });
        ytdl('https://www.youtube.com/watch?v=' + video).pipe(fs.createWriteStream('video.mp4'))
        console.log("video downloaded");

        const player = createAudioPlayer('video.mp4');
        console.log("player created");
        player.play();

The error:
/Users/sam/Desktop/DCordBot/node_modules/@discordjs/voice/dist/index.js:944
    if (resource.ended) {
                 ^

TypeError: Cannot read properties of undefined (reading 'ended')
    at AudioPlayer.play (/Users/sam/Desktop/DCordBot/node_modules/@discordjs/voice/dist/index.js:944:18)
    at Client.<anonymous> (/Users/sam/Desktop/DCordBot/main.js:179:16)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

The size of video.mp4 is consistently 0 bytes, which confuses me, because if I insert the link "http://www....." + "videoID" into the search bar it will bring up the YouTube video that I want. I am not sure why, but it's not downloading the video properly, does anyone have any suggestions or insight as to what the problem might be? Thanks.


text:
Q: Django store JSON data to models image I want to save json data to models. How can this possible. I tried using url but could not given proper result. Please suggest any method to resolve this. If i use get method then this will get the data that will show in command line but not in simplified method. I followed this https://ask.metafilter.com/154077/How-do-I-read-a-JSON-object-in-Python but this will also does not solve my problem.

    #My alert
    [{"BillNo":"4353","BillDetails":"my bill","Amount":"455"},{"BillNo":"4353","BillDetails":"my bill","Amount":"455"},{"BillNo":"4353","BillDetails":"my bill","Amount":"455"},{"BillNo":"4353","BillDetails":"my bill","Amount":"455"},{"BillNo":"4353","BillDetails":"my bill","Amount":"45"},{"BillNo":"43","BillDetails":"my bill","Amount":"600"}]

    Bill No: <input type="text" name="billno" id="billNo" autocomplete="off">
       Amount: <input type="text" name="amount2" id="amnt" pattern="[0-9]+" title="please enter amount" autocomplete="off">

       Bill Details: <input type="text" id="billDetails" name="billdetails" style="margin: 1px 0px 20px; width: 850px; height: 42px;" autocomplete="off">
       <button type="button" id="btnAdd" class="button" value="Add">Add</button> <button type="button" id="btn2" class="button" value="Complete all entries">Complete All entries</button>

         Bill No
         Bill Details
         Amount
         Action

          Total :

    <input id="btnjson" type="submit" value="ok"  />

#views.py

@csrf_exempt
def jsdata(request):
 b_details = request.POST['']
 data = json.loads(list(array1))
 for billno in data():
  print(billno)

    #models

    class Mvouchar(models.Model):
     related = models.ForeignKey(Signs, on_delete=models.CASCADE, null=True, blank=True)
     bill_no = models.CharField(max_length=80, null=True, blank=True)
     bill_details = models.CharField(max_length=1000, null=True, blank=True)
     am = models.CharField(max_length=30, null=True, blank=True)

A: b_details = request.POST[''] causing the problem . Because the key is not exist. You can change it to b_details = request.POST.get['']. It will return None if key is not present.
You need to change the API call to POST request something like this
$.ajax({
        url: '/jsondata/',
        data: {
          'BillNo': $(this).find('td').eq(0).text().trim();
           ...
        },
        dataType: 'json',
        success: function (data) {
          if (data.is_taken) {
            alert("Message.");
          }
        }
      });

I have very little knowledge in AJAX and JQuery. I referred post How do I POST with jQuery/Ajax in Django? and https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html.


text:
Q: String Null in ConfigurationBuilder.Build() after Deployment to Azure Service Apps I'm trying to deploy a .NET Core 2.1 application to an Azure Service App. I'm able to run my solution locally successfully, but when I deploy the application out to Azure Service Apps, I begin to get the following error when I call dotnet /home/site/wwwroot/MyApplication.dll on the application.
Unhandled Exception: System.ArgumentNullException: String reference not set to an instance of a String.
Parameter name: s
   at System.Text.Encoding.GetBytes(String s)
   at MyApplication.Startup.ConfigureServices(IServiceCollection services) in /home/vsts/work/1/s/MyApplication/Startup.cs:line 51
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at MyApplication.Program.Main(String[] args) in /home/vsts/work/1/s/MyApplication/Program.cs:line 23
   at MyApplication.Program.<Main>(String[] args)
bash: line 1:  1096 Aborted                 (core dumped) dotnet /home/site/wwwroot/MyApplication/MyApplication.dll

This appears that I have a null reference on line 51 of my Startup.cs method, inside the ConfigureServices method. This correlates to the line where I build my configuration, using _configuration = builder.Build()

public IConfiguration _configuration { get; set; }

public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
{
    _configuration = configuration;
    _hostingEnvironment = hostingEnvironment;
}

public void ConfigureServices(IServiceCollection services)
{
    var builder = new ConfigurationBuilder()
                      .SetBasePath(_hostingEnvironment.ContentRootPath)
                      .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                      .AddEnvironmentVariables();

    _configuration = builder.Build();  // this is line 51

    var appSettingsSection = _configuration.GetSection("AppSettings");
    ...
}

Which the only thing that I can think of would be my appsettings.json transformation. In dev, I point to my dev server, in prod, I point to production. So after the build, I have a file transformation set up to make this change.
However, I've pulled the generated appsettings.json from the App Service, inserted it into my local appsettings.json, and it still compiles and runs just fine.
Here's the appsettings.json that is getting deployed. It's the exact same, except for the name of the server and username/password strings.
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AppSettings": {
    "SecretKey": "MySecretKey",
    "SuperAdminEmail": "myemail@domain.com"
  },
  "ConnectionStrings": {
    "AuthDatabase": "Server=prod.mydomain.com;Database=Authentication;User Id=myUser;Password=Password1!;TrustServerCertificate=true"
  },
  "AllowedHosts": "*"
}

I can't see what would be causing this. I tried deploying this to an AWS Lightsail Ubuntu 18.04 instance to see if that works. I got the same error sometimes, however, after enough tries of killing the service, rebooting the server, and other items, I got it to run for 10 minutes, before it crashed again.
I'm not great with logging, especially on Azure App Services... how can I go about tracking down WHAT string is null, and what I can do to verify that it has any necessary values?

A: As you mentioned in the comments, the value of _hostingEnvironment.ContentrootPath on the AppService is '/home' and this is the issue as your application is not able to read something due to the wrong path referred by the AppService.
You can change your ContentRootPath by following this SO post and accordingly choose the approach as per your requirements.


text:
Q: .net desktop app installation I am creating a  C# .Net 4.0 desktop application for a client.  When I sent him the .msi files it requires administration privileges when trying to install.  I realize the reason why is because I am installing the application into the "Program Files" directory.
Is there a way to install an application into an area on the users machine that doesn't require them to install as Administrator?
I'm using .Net 4.0

A: depending on what dependencies the app has you could try an XCOPY deployment - although is seems that is only documented for VS2005 + VS2008...
We usually embed all dependencis into the app (in our case EXE-file), this way it can be "installed" by just copying it... as long as the framework needed (i.e. .NET4 in our case) is already there...
see http://msdn.microsoft.com/en-us/library/ms235291%28VS.90%29.aspx

A: Not sure whether this will solve the "requires Administrator" problem, but you can change the target folder for your installation in "File System" view of your setup project:

*

*Right-click on the setup project in the solution explorer and choose View / File System.

*Select "Application Folder".

*In Properties, change the DefaultLocation.

Also it is usually a good idea to distribute setup.exe alongside *.msi, so any missing prerequisites may be installed automatically.

A: If you add the manifest file and assign to application then you need to set the Execution level.
Following is the line where you can set the Execution level.
<requestedExecutionLevel  level="asInvoker" uiAccess="false" />
If you want your exe run always run as administator then you need to change the above statement as follow
<requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
See the following link how to create manifest file.
http://mahesg.wordpress.com/2007/07/30/adding-manifest-to-net-application/

A: I have got around the administration privileges by adding the "User's Application Data Folder" by right clicking on "File System on Target Machine" and moved all files from the "Application Folder" into it. The setup still prompts for the install directory but it is ignored. Shortcuts can still be setup as normal.
It installs to the following directory on Win7 C:\Users\username\AppData\Roaming
Under xp it goes some where under documents and settings folder.
I asked the question why does google chrome not require permission and found that it installed to a slightly different folder C:\Users\username\AppData\Local\Google\Chrome\Application.


text:
Q: Delphi: set Content-type of TCustomRestRequest on PUT I'm fighting a REST API call from Delphi. I want to send a PUT request to a server, with contenttype set to application/json:
    aCustomRestClient.BaseURL := domein;
    aCustomRestRequest.Client := aCustomRestClient;
    aCustomRestRequest.Response := aCustomRestResponse;
    aCustomRestRequest.Method := rmPUT;

    aCustomRestRequest.Resource := '/service/API/1501/allowanceCategory';
    aCustomRestRequest.Params.AddHeader('sessionId', SessionToken);

    qryAllowanceCategory.First;
    o := TJSONObject.Create;
    arr:=TJSONarray.create;

    try
      o.AddPair('createdBy',qryAllowanceCategory.fieldbyname('createdBy').AsString);
{lot more pairs here}
      o.AddPair('percentage', TJSONnumber.create(qryAllowanceCategory.fieldbyname('percentage').AsFloat));
      o.AddPair('remark',    'JUR '+ qryAllowanceCategory.fieldbyname('remark').AsString);
      arr.add(o);

      aCustomRestRequest.ClearBody;
      aCustomRestResponse.contenttype:='application/json';
      aCustomRestClient.contenttype:='application/json';
      aCustomRestRequest.AddBody(arr.ToString);

      aCustomRestRequest.Execute;

However, when I view my request as sent with Fiddler:
PUT http://shadow.jdvretail.com/service/API/1501/allowanceCategory HTTP/1.1
Connection: Keep-Alive
Content-Type: application/x-www-form-urlencoded
Accept: application/json, text/plain; q=0.9, text/html;q=0.8,
Accept-Charset: utf-8, *;q=0.8
Authorization: Basic <<Authorization properly filled>>
User-Agent: Embarcadero RESTClient/1.0
sessionId: <<sessionID GUID properly filled here>>
Content-Length: 542

The Content-type remains wrong... how/where do I correctly set the contentType to 'application/json'?

A: TRestClient.AddBody(<string>) has an optional second parameter allowing to set the content type.
procedure AddBody(const ABodyContent: string; AContentType: TRESTContentType = ctNone); overload;


text:
Q: Is there a dplyr equivalent to data.table::rleid? data.table offers a nice convenience function, rleid for run-length encoding:
library(data.table)
DT = data.table(grp=rep(c("A", "B", "C", "A", "B"), c(2, 2, 3, 1, 2)), value=1:10)
rleid(DT$grp)
# [1] 1 1 2 2 3 3 3 4 5 5

I can mimic this in base R with:
df <- data.frame(DT)
rep(seq_along(rle(df$grp)$values), times = rle(df$grp)$lengths)
# [1] 1 1 2 2 3 3 3 4 5 5

Does anyone know of a dplyr equivalent (?) or is the "best" way to create the rleid behavior with dplyr is to do something like the following
library(dplyr)

my_rleid = rep(seq_along(rle(df$grp)$values), times = rle(df$grp)$lengths)

df %>%
  mutate(rleid = my_rleid)

A: A simplification (involving no additional package) of the approach used by the OP could be:
DT %>%
 mutate(rleid = with(rle(grp), rep(seq_along(lengths), lengths)))

   grp value rleid
1    A     1     1
2    A     2     1
3    B     3     2
4    B     4     2
5    C     5     3
6    C     6     3
7    C     7     3
8    A     8     4
9    B     9     5
10   B    10     5

Or:
DT %>%
 mutate(rleid = rep(seq(ls <- rle(grp)$lengths), ls))

A: From v1.1.0 dplyr added the function consecutive_id() modeled after data.table::rleid() with the same support for multiple vectors and the treatment of NA values.
 library(dplyr)

 DT %>%
   mutate(id = consecutive_id(grp))

    grp value id
 1:   A     1  1
 2:   A     2  1
 3:   B     3  2
 4:   B     4  2
 5:   C     5  3
 6:   C     6  3
 7:   C     7  3
 8:   A     8  4
 9:   B     9  5
10:   B    10  5

A: You can just do (when you have both data.table and dplyr loaded):
DT <- DT %>% mutate(rlid = rleid(grp))

this gives:

> DT
    grp value rlid
 1:   A     1    1
 2:   A     2    1
 3:   B     3    2
 4:   B     4    2
 5:   C     5    3
 6:   C     6    3
 7:   C     7    3
 8:   A     8    4
 9:   B     9    5
10:   B    10    5

When you don't want to load data.table separately you can also use (as mentioned by @DavidArenburg in the comments):
DT <- DT %>% mutate(rlid = data.table::rleid(grp))

And as @RichardScriven said in his comment you can just copy/steal it:
myrleid <- data.table::rleid

A: If you want to use just base R and dplyr, the better way is to wrap up your own one or two line version of rleid() as a function and then apply that whenever you need it.
library(dplyr)

myrleid <- function(x) {
    x <- rle(x)$lengths
    rep(seq_along(x), times=x)
}

## Try it out
DT <- DT %>% mutate(rlid = myrleid(grp))
DT
#   grp value rlid
# 1:   A     1    1
# 2:   A     2    1
# 3:   B     3    2
# 4:   B     4    2
# 5:   C     5    3
# 6:   C     6    3
# 7:   C     7    3
# 8:   A     8    4
# 9:   B     9    5
#10:   B    10    5

A: You can do it using the lag function from dplyr.
DT <-
    DT %>%
    mutate(rleid = (grp != lag(grp, 1, default = "asdf"))) %>%
    mutate(rleid = cumsum(rleid))

gives
> DT
    grp value rleid
 1:   A     1     1
 2:   A     2     1
 3:   B     3     2
 4:   B     4     2
 5:   C     5     3
 6:   C     6     3
 7:   C     7     3
 8:   A     8     4
 9:   B     9     5
10:   B    10     5

A: There are a lot of very good solutions here, but I would like to note that some do not give the same result as data.table::rleid() when the data has NAs. Keep in mind that data.table::rleid() increments everytime there is a change, including NAs.
Data:
library(data.table)
library(dplyr)

# Data
DT2 = data.table(grp=rep(c("A", "B", NA, "C", "A", NA, "B", NA), c(2, 2, 2, 3, 1, 1, 2, 1)), value=1:14)
df <- data.frame(DT2)

# data.table reild
DT2[, rleid := rleid(DT2$grp)]
DT2
#>      grp value rleid
#>  1:    A     1     1
#>  2:    A     2     1
#>  3:    B     3     2
#>  4:    B     4     2
#>  5: <NA>     5     3
#>  6: <NA>     6     3
#>  7:    C     7     4
#>  8:    C     8     4
#>  9:    C     9     4
#> 10:    A    10     5
#> 11: <NA>    11     6
#> 12:    B    12     7
#> 13:    B    13     7
#> 14: <NA>    14     8

Just for example, Alex's solution is perfect for OP but doesn't give same result as data.table::rleid() when dealing with NAs:
# Alex's solution
df %>%
  mutate(rleid = (grp != lag(grp, 1, default = "asdf"))) %>%
  mutate(rleid = cumsum(rleid))
#>     grp value rleid
#> 1     A     1     1
#> 2     A     2     1
#> 3     B     3     2
#> 4     B     4     2
#> 5  <NA>     5    NA
#> 6  <NA>     6    NA
#> 7     C     7    NA
#> 8     C     8    NA
#> 9     C     9    NA
#> 10    A    10    NA
#> 11 <NA>    11    NA
#> 12    B    12    NA
#> 13    B    13    NA
#> 14 <NA>    14    NA

Here is an easy to read and understand tidyverse (although slower) equivalent to data.table::rleid():
# like rleid()
df %>%
  mutate(
    rleid = cumsum(
      ifelse(is.na(grp), "DEFAULT", grp) != lag(ifelse(is.na(grp), "DEFAULT", grp), default = "DEFAULT")
    )
  )
#>     grp value rleid
#> 1     A     1     1
#> 2     A     2     1
#> 3     B     3     2
#> 4     B     4     2
#> 5  <NA>     5     3
#> 6  <NA>     6     3
#> 7     C     7     4
#> 8     C     8     4
#> 9     C     9     4
#> 10    A    10     5
#> 11 <NA>    11     6
#> 12    B    12     7
#> 13    B    13     7
#> 14 <NA>    14     8

Here is an easy to read and understand tidyverse equivalent to data.table::rleid() but that ignores NAs:
# like rleid() but ignoring NAs
df %>%
 mutate(
    rleid = cumsum(
      (!is.na(grp)) & (grp != lag(ifelse(is.na(grp), "DEFAULT", grp), default = "DEFAULT"))
    )
 )
#>     grp value rleid
#> 1     A     1     1
#> 2     A     2     1
#> 3     B     3     2
#> 4     B     4     2
#> 5  <NA>     5     2
#> 6  <NA>     6     2
#> 7     C     7     3
#> 8     C     8     3
#> 9     C     9     3
#> 10    A    10     4
#> 11 <NA>    11     4
#> 12    B    12     5
#> 13    B    13     5
#> 14 <NA>    14     5

Created on 2022-08-27 with reprex v2.0.2


text:
Q: Something Weird in my markup. Twitter bootsrap tab not working I designed a markup and i'm trying to make a tab on bootsrap with jquery. I wrote markup code as below. Please examine why the tabs are not working? What wrong with my code.
in javascript console it showing
ReferenceError: $ is not defined
    <!doctype html>

<meta charset="UTF-8">
<title>Just Live 24</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/tv-theme.css">
<link href="css/main_pricetable.css" rel="stylesheet">

Home

Profile

Messages

Settings

bmnmn,b,mbn...

.werewr..

.jkhk..

llkjlk...

A: <!DOCTYPE html>

<meta charset="UTF-8">
<title>Example of Twitter Bootstrap 3 Tabs</title>

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">

Home

Profile

Messages

Settings

bmnmn,b,mbn...

.werewr..

.jkhk..

llkjlk...

http://jsfiddle.net/7r6kgooh/

A: Most probably you forgot to attach http in script src attribute.
src="http://code.jquery.com/jquery-1.11.0.min.js"
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"

As a result browser is unable to fetch scripts and is not recogizing jquery shorthand (i.e. $).


text:
Q: how to fetch Input given value to an array i'm working on a calculator based on some Json data i want when i enter the longitude and latitude i get the Grid Code associated to that longitude and latitude.the problem is when i get the value form the input the result reurnd is 0 means the value of the input is undefined
this is how my code look like

<!DOCTYPE html>

<form action="" id="my-form">

    Enter Lat
    <input type="text" id="lat" step="any">
    Enter Long
    <input type="textr" id="long" step="any">

  <input type="button" id="Btn" value="Calculate" >

result

</form>

A: The reason why you get zero value is because you called your lookupGridcodeByLatAndLong function in the first time with passing your lat and lang value, both value will return undefined because you haven't input them yet.
You have to fill them with value, then hit the button to get the lat and lang value before you do your calculation to get the GRIDCODE and actually you don't need to parse your object value as parameter, because you initialized it as global parameter, so you can still use it inside your function without parse it.

<!DOCTYPE html>

<form action="" id="my-form">

    Enter Lat
    <input type="text" id="lat" step="any">
    Enter Long
    <input type="textr" id="long" step="any">

  <input type="button" id="Btn" value="Calculate" >

result

</form>


text:
Q: app-server should be considered as an actor in u.c basic flow/ u.c diagram? I am building an android chat application which sync with Firebase, and also app server which comunicate with the Firebase for analysing text messages with the help of AI algorithms.
Sholud i considered the application server and Firebase as an actors in use case scenarios and u.c diagram?

A: No, for the same reason that Thomas Kilian has pointed out in his answer to this question:
Use Case diagram - System as an Actor


text:
Q: How do I successfully create ordered categorical data from an existing column? Here's a dataframe  - 'dist_copy'  - with values I would like to change to categorical.  I've only included one column, but there are additional columns I want to convert as well.

state
dist_id
pct_free_reduced_lunch

Illinois
1111
80% - 100%

Illinois
1112
0 - 20%

Illinois
2365
40% - 60%

dist_copy.pct_free_reduced_lunch.unique()
returns
array(['80% - 100%', '60% - 80%', '0 - 20%', '20% - 40%', '40% - 60%'], dtype=object)
Previously, I used pd.Categorical to change all the values in the 'pct_free_reduced_lunch' column to 'categorical', and established the order, with this code:
dist_copy['pct_free_reduced_lunch'] = pd.Categorical(dist_copy['pct_free_reduced_lunch'],
     categories=['0 — 20%','20% — 40%', '40% — 60%', '60% — 80%',  '80% - 100%'], ordered=True)

Today, this code isn't working, and only retains the first value, changing all other values to NaN.

state
dist_id
pct_free_reduced_lunch

Illinois
1111
80% - 100%

Illinois
1112
NaN

Illinois
2365
NaN

What am I doing wrong, or misunderstanding?
UPDATE:  The above code began to work AFTER I copy-pasted each categorical value from the array returned by unique() into the categories array inside the pd.Categorical function, in the desired order.
When I merely entered them from scratch, NaNs were created.
WHY?  I would really love to know!

A: You are using dashes instead of hyphens for you categories argument, all but for '80% - 100%'. But in the data there are only hyphens and therefore all but '80% - 100%' turn into NaN.
Try using categories=sorted(dist_copy.pct_free_reduced_lunch.unique()) to avoid this kind of typo.


text:
Q: SimpleDateFormat is giving future date as formatted Date     String timestamp = "2020-05-22 12:58:04.517123+05:30";
    Date d = null;
    try {
        d = ext.parse(timestamp);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } */
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").parse(timestamp);
    System.out.println(date);
    // o/p : Fri May 22 13:06:41 IST 2020

we can see that SimpleDateFormat is producing Future Date. What might be the reason ?

A: java.time.OffsetDateTime
You have an input and a formatting pattern that both use microseconds. The Date type is limited to milliseconds.
You should not be using the terrible Date and SimpleDateFormat classes. Use only java.time classes.
Edit your input text to comply with the ISO 8601 standard. Replace the SPACE in the middle with T.
String input = "2020-05-22 12:58:04.517123+05:30".replace( " " , "T" ) ;
OffsetDateTime odt = OffsetDateTime.parse( input ) ;

A: If you can use java.time for this, do it. Do it like in the answer given by @BasilBorque or provide a pattern that parses Strings of the given format directly without replacing the whitespace with a T to make it the ISO pattern:
public static void main(String[] args) {
    String timestamp = "2020-05-22 12:58:04.517123+05:30";
    // parse the string to an OffsetDateTime using a matching pattern
    OffsetDateTime odt = OffsetDateTime.parse(timestamp,
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSXXXXX"));
    // print the result in the default (ISO) pattern
    System.out.println(odt);
}

The result looks like
2020-05-22T12:58:04.517123+05:30

and is formattable in many different ways.

A: In 12:58:04.517123+05:30 517123 is considered millisecond, which translates to roughly 8 minutes 37 seconds. That's the reason your time is changing. Another important aspect of Date is that it has no concept of timezone, it's merely tells no. of milliseconds from epoch. So when you do toString() it display time in JVM timezone.


text:
Q: Is there a currently maintained way to use Qt Mobility with PyQt? I downloaded an example from PySide QtMobility examples, and it looks like, at least some time in the past, there was support for QtMobility in PySide.
When I tried to run the script, it's no surprise there is no module to import (because of course I haven't installed nothing yet)
from QtMobility.Location import QGeoServiceProvider, QGraphicsGeoMap, QGeoMapPolylineObject
from QtMobility.Location import QGeoCoordinate, QGeoMapRectangleObject, QGeoMapPixmapObject
from QtMobility.Location import QGeoMapPolygonObject, QGeoMapCircleObject, QGeoMapTextObject
from QtMobility.Location import QGeoMapRouteObject, QGeoRouteRequest

>> ImportError: No module named QtMobility.Location

I didn't find any setup.py or other way to even try to install this module, and anyway I suspect it is rather old (last commit by the end of 2011).
So, questions are:

*

*Shoud I try to use this PyQt mobility library? How difficult would it be to make it work with current PyQt/PySide?

*Is there any ongoing development in this field? (mapping SDKs for PyQt/PySide)?

I am already trying to make some progress with SlippyMap class taken from here, and I'm think about porting it to Qt Graphics Framework (with MapView and MapScene classes, and layers, and draggable polyline nodes, and stuff) but honestly, it would be much better to use something already existing with possible.


text:
Q: CakePHP without mod_rewrite causes 404 errors I'm pretty new to Cake, so I tryed to start with the blog tutorial.
I installed CakePHP 2.3.8 in webroot.
Configured SQL and deleted all 3 .htaccess-files, cause i have no mod_rewrite. In core.php I activated
    Configure::write('App.baseUrl', env('SCRIPT_NAME'));
I created the Posts-Model, Controller and the index-View like the tutorial says.
The APP/View/Pages/home.ctp tells me, everything's allright.
But when i try to open /posts/index i get a 404. Why?

A: Without mod_rewrite the urls look like www.example.com/index.php/controllername/actionname/param, i.e. in your example you have to call /index.php/posts/index (or /index.php/posts/).


text:
Q: Select the table row (only one row) and edit the content in cells With my code below, you can add/select the whole row and when edit button pressed, that print the current row on the screen.
Furthermore, previously all the rows are disabled! Instead of print the current row, I'll be able to edit the row when selected.
# -*- coding: utf-8 -*-
import sqlite3 as sql
from PyQt4 import QtCore, QtGui
import sys, os

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.tabs = QtGui.QTabWidget(self)
        self.general = QtGui.QWidget()
        self.tabs.addTab(self.general, "General")
        cWidget = QtGui.QWidget(self)
        self.setCentralWidget(cWidget)
        self.general_table = QtGui.QTableWidget(self.general)
        self.setHeader()

        add_record = QtGui.QPushButton("Add Record")
        edit = QtGui.QPushButton("Edit")
        layout = QtGui.QVBoxLayout(cWidget)
        layout.addWidget(self.tabs)
        layout.addWidget(add_record)
        layout.addWidget(edit)

        self.connect(add_record, QtCore.SIGNAL('clicked()'), self.addRecord)
        self.connect(edit, QtCore.SIGNAL('clicked()'), self.edit)

        self.general_table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)

    def addRecord(self):
        rcount_general = self.general_table.rowCount()
        self.general_table.insertRow(rcount_general)

    def edit(self):
        indexes = self.general_table.selectionModel().selectedRows()
        for index in sorted(indexes):
            print("Row %d is selected" % index.row())

    def setHeader(self):
        # General
        self.general_table.setRowCount(1)
        self.general_table.setColumnCount(3)
        self.general_table.setHorizontalHeaderLabels(["A1", "A2", "A3"])

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

A: You could call the setFlags function on the item.

*

*For editable:

item = QtGui.QTableWidgetItem()
item.setFlags(QtCore.Qt.ItemIsSelectable |  QtCore.Qt.ItemIsEnabled )
self.your_table.setItem(row, column, item)

*

*For not editable:

item = QtGui.QTableWidgetItem()
item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable |
              QtCore.Qt.ItemIsEnabled)
self.your_table.setItem(row, column, item)


text:
Q: R.oo package won't install on RStudio Server I'm perplexed that the R.oo package installation fails on RStudio server, any idea on how I can get around it?
Installing package(s) into '/home/rstudio/R/library'
(as 'lib' is unspecified)
trying URL 'http://ftp.heanet.ie/mirrors/cran.r-project.org/src/contrib/R.oo_1.9.3.tar.gz'
Content type 'application/x-gzip' length 372217 bytes (363 Kb)
opened URL
==================================================
downloaded 363 Kb

* installing *source* package 'R.oo' ...
** package 'R.oo' successfully unpacked and MD5 sums checked
** R
** inst
** preparing package for lazy loading
Error in match(el, set, 0L) : object 'R.KEYWORDS' not found
Error : unable to load R code in package 'R.oo'
ERROR: lazy loading failed for package 'R.oo'
* removing '/home/rstudio/R/library/R.oo'
Warning in install.packages :
  installation of package 'R.oo' had non-zero exit status

A: As of last night: I can confirm this problem on two different RStudio servers, one running R.2.14.1, the other R.2.15.1, so it's not R version. One is our linux server, the other is an amazon EC2 server. And no problem installing on a local RStudio (OSX; R.2.15.0).
HOWEVER:  as of an hour ago, this problem has disappeared. On both RStudio Servers, R.oo now installs fine.  So, try again!

A: According to the author of the R.oo and R.KEYWORDS packages, there was an incompatibility between the last version of R.KEYWORDS (v1.4.2) and R.oo (the cran version 1.9.3 was incompatible, not being the last one v1.9.8). He corrected that recently.


text:
Q: Convergence of series to a $C^{\infty}$ function Let $S_+ = \mathbb{R} \times \{t>0\}$ and $\,f \in C^{\infty}(S^+)$ such that $\,f$ and all its derivatives have continuous limits as $t \to 0^+$.
In this paper the author defines the following extension of $f$ for $t<0$:
\begin{equation}
  Ef(x,t) = \sum_{k=1}^{\infty} a_k \,\phi(b_k t)\, f(x,b_k t)
\end{equation}
where

*

*$\phi \in C^{\infty}(\mathbb{R})$ with: $\phi(t)=1$ for $0\leq t\leq1$ and $\,\phi(t)=0$ for $t\geq$2;

*${a_k}, {b_k}$ such that:

*

*$b_k < 0$ and $b_k \to - \infty$,

*$\sum_{k=1}^\infty|a_k||b_k|^n <\infty$ for $\, n = 0,1, 2, \dots$,

*$\sum_{k=1}^\infty (a_k)(b_k)^n = 1$ for $\, n = 0,1, 2, \dots$.

The existence of sequences $\{a_k\}, \{b_k\}$ such that 2. holds is proved in the paper.
My observations

*

*Since $b_k \to -\infty$, for each $t<0$ the sum in $Ef$ is finite and therefore $Ef$ is pointwise well defined.

*If $C$ is a compact set in $\mathbb{R}\times(-\infty,0)$ and $\bar{t} = \max_{(x,t) \in C} t$, let $\bar{N}$ be such that for every $k \geq \bar{N}$ one has $b_k \bar{t} > 2$. Then since  $b_k t \geq b_k \bar{t} > 2 $ for all $t \in C$, it follows that:
$$ Ef(x,t) = \sum_{k=1}^\bar{N} a_k \,\phi(b_k t)\, f(x,b_k t)\qquad \forall (x,t) \in C $$
It follows that on every compact set $C \subset \mathbb{R}\times(-\infty,0)$ $Ef$ is uniform limit of functions in $C^\infty(\mathbb{R}\times(-\infty,0))$. Then it easy to see that the restriction of
$Ef$ to $t<0$ is in $C^{\infty}(\mathbb{R}\times(-\infty,0))$.

My question:
I have shown that $Ef(t,x)$ is well defined for every $(t,x) \in R^2$,
moreover the restriction of $Ef$ to $t<0$ is in $C^{\infty}(\mathbb{R}\times(-\infty,0))$. I'm left with $Ef(t,x)$ has derivative as $t\to 0^-$.

Question: How to prove that
  $\lim_{t\to 0^-} Ef(x,t)$ and
  $ \lim_{t\to 0^-} \partial_t^n \partial_x^j Ef(x,t)$
  exist finite?

Remarks
a) I believe that to answer the question "dominated convergence" using the  second point of 2.2 is what
is needed, but I'm missing the details.
b) If the limit exist then they agree to those for $t\to 0^+$, since using the third point in 2.:
$$ \lim_{t\to 0^-} Ef(x,t) = \sum_{k=1}^{\infty} \lim_{t\to 0^-} a_k \,\phi(b_k t)\, f(x,b_k t) = f(x, 0^+) \sum_{k=1}^{\infty} a_k   = f(x, 0^+)$$
$$ \lim_{t\to 0^-} \partial_t^n \partial_x^j Ef(x,t) = \sum_{k=1}^{\infty} \lim_{t\to 0^-} a_k \sum_{j \leq n} C_{j,k} \partial_t^{n-j} \,\phi(b_k t)\,\partial_t^j  \partial_x^j f(x,b_k t) = \partial_t^m \partial_x^n f(x, 0^+) \sum_{k=1}^{\infty} a_k b_k^n = \partial_t^m \partial_x^n f(x,0^+)$$


text:
Q: Factoring a Polynomial Having No Rational Roots For example: $$ x^3-6x^2+3x-10 $$
The rational roots test tells me that possible roots are $\pm\ 10, 5, 2, 1$. However, none of these roots will divide the polynomial into a more workable nominal.
How can I efficiently determine how to factor this without resources such as Wolfram|Alpha?
Thank you.

A: Turgeon already mentioned Cardano; here's how to apply it to your polynomial.
The first thing you need to do is to depress your cubic. "Depression" is the generalization of the usual "completing the square" done on quadratics. In particular, we make a variable substitution that removes the quadratic term.
In this case, from Vieta's formulas, we know that the mean of the roots is $6/3=2$, so we let $x=u+2$. This yields the polynomial $u^3-9u-20$.
Now we come to Cardano's piece of trickery. Cardano assumes that a root $u$ of $u^3-9u-20$ can be written in the form $u=r+s$. If we make that substitution, we obtain
$$(r+s)^3-9(r+s)-20=r^3+s^3+3(r+s)(rs-3)-20$$
From this, we obtain the system of equations
$$\begin{align*}
r^3+s^3&=20\\
r^3 s^3&=27
\end{align*}$$
Using Vieta's formulas again, we obtain the "quadratic" equation
$$(r^3)^2-20(r^3)+27=0$$
You should now be able to obtain $r$ and $s$. You already know that $x=r+s+2$ is one root of your cubic; divide that out of the original cubic, and solve the remaining quadratic. Done.

A: By the intermediate value theorem, there's a root between $5$ and $6$.  You can use Newton's method to quickly find a close approximation to it.  Call that number $a$.  Then $x-a$ is a factor.  Use long division to find the quadratic factor.  The arithmetic may get a bit messy, but after that you're just solving a quadratic equation.

A: Two things you can use:

*

*Cubic formula;

*Newton's method.


text:
Q: Catalyst MVC save multiple objects using a single form I am using Catalyst Perl MVC framework with HTML::FormHandler as forms processor.
Are there any ways to create multiple objects and save them into appropriate separate tables using single form?

A: After some time was spent reading the documentation and finally IRC help I figured out how to do it. It's quite simple.
Let's say we have 2 related tables: 'account' and 'user'. And 'account' hasMany 'users', with this relationship being called 'users'.
The code in controller Account.pm stays the same (remember we are using HTML::FormHandler to process the form and create new objects):
sub register : Chained('base') :PathPart('register') :Args(0) {
    my ($self, $c ) = @_;
    my $account = $c->model('DB::Account')->new_result({});
    return $self->form_create($c, $account);
}
sub form_create {
    my ( $self, $c, $account ) = @_;
    my $form = MyApp::Form::Account->new();
    $c->stash( template => 'account/form.tt2', form => $form );
    $form->process( item => $account, params => $c->req->params );
    return unless $form->validated;
}

All we do is use http://metacpan.org/pod/HTML::FormHandler::Field::Repeatable like that in our lib/MyApp/Form/Account.pm:
package MyApp::Form::Account;

use HTML::FormHandler::Moose;
extends 'HTML::FormHandler::Model::DBIC';
use namespace::autoclean;

has '+item_class' => ( default => 'Account' );
has_field 'organization';
# other fields ...

# User Part Form
has_field 'users' => ( type => 'Repeatable' ); # 'users' is our relationship name!
has_field 'users.first';
has_field 'users.last';
# and so on...
has_field 'submit' => ( type => 'Submit', value => 'Submit' );
__PACKAGE__->meta->make_immutable;
1;

After submitting we get freshly created 'account' and 'user' objects, where 'user' already has corresponding 'account_id' inserted :)

A: *

*Form submits

*Params are validated
$form->process()

*Data is inserted into tables as appropriate.
$rec =  $c->model(table_1)->create(valid_data);
    $rec->create_related('relationship_name', related_data);
I am unaware of a method for having DBIC perform both inserts automatically.  But that isn't to say that one doesn't exist.  I just didn't see anything in the FormHandler::DBIC documentation.


text:
Q: gdbserver for Python I wonder what is the flow that I need to foloow to remotely debug a Python script?
For C/CPP, on instance A I run:
gdbserver :1234 binary

And from gdb, on instance B, I run
gdb binary
target remote $host:1234

Is there any Python alternative for this flow. Can anyone point me to a Hello world example demoing a remote debug? Thanks

A: Here you have a list of debugging tools:
https://wiki.python.org/moin/PythonDebuggingTools
rpdb  is cross platform and support remote debugging.


text:
Q: Solving dice throwing and coin tossing problem using tensorflow probability, variance is wrong I am not very proficient in Statistics, I am trying to learn. So please bear with me. I saw this question in Quora - Which basically states the following -

A fair dice is rolled if the result is an odd number then a fair coin
  is tossed 3 times. Otherwise, if the result is even number then a fair
  coin will be tossed 2 times. In both cases, # of heads is counted.
  What's the variance of # heads obtained?

I wanted to solve it using Python and tf-probability. Here is what I did -
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
tf.enable_eager_execution()
probs = [1/6.] * 6

dices = tfp.distributions.Multinomial(total_count=1000, probs=probs)

n = dices.sample()

HEAD = 1
TAIL = 0
l = list(n.numpy())
heads_even = []
heads_odd = []
for i, nums in enumerate(l):
    mul_by = 3 if (i + 1) % 2 != 0 else 2
    tosses = tfp.distributions.Bernoulli(probs=0.5)
    coin_flip_data = tosses.sample(nums * mul_by)
    l2 = coin_flip_data.numpy()
    unique, counts = np.unique(l2, return_counts=True)
    head_tails = dict(zip(unique, counts))
    if (i + 1) % 2 != 0:
        heads_odd.append(head_tails[HEAD])
    else:
        heads_even.append(head_tails[HEAD])

total_heads = heads_odd + heads_even
final_nd_arr = np.array(total_heads)
print(final_nd_arr.var())

However, the final_nd_arr.var() is of course nowhere near to the actual answer (it is 2089.805555555556) , 0.68 (As people have mentioned in the Quora answer).
I am unable to find out what I am doing wrong. How can I rectify my mistake?
Any pointer will be helpful. Thanks a lot in advance.
--------- EDIT
To give more data,
dices.sample() => array([169., 173., 149., 171., 175., 163.], dtype=float32)
heads_odd => [266, 210, 259]
heads_even => [176, 167, 145]
total_heads => [266, 210, 259, 176, 167, 145]

A: You are computing the variance over the wrong distribution. The variance we are looking for applies to the experiment where you would roll the dice over and over again, each time count the number of heads, and compute the variance over the number of heads. You are doing this in your code, but your are summing the total number of heads over all the dice rolls, and then taking the variance of these sums for each possible outcome of the dice.
This will give the correct result. I added some comments that hopefully clarify it:
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np

tf.enable_eager_execution()

# Simulate the outcome of 1000 dice rolls
probs = [1/6.] * 6
dices = tfp.distributions.Multinomial(total_count=1000, probs=probs)
n = dices.sample()
l = list(n.numpy().astype(int))

L = []
# Loop over 6 possible dice outcomes
for i in range(len(l)):
    # Loop over the rolls for this dice outcome
    for _ in range(l[i]):
        # For each of the dice rolls,
        # Flip a coin 2 or three times
        num_tosses = 3 if (i + 1) % 2 != 0 else 2
        tosses = tfp.distributions.Bernoulli(probs=0.5)
        coin_flip_data = tosses.sample(num_tosses)

        # And count the number of heads
        num_heads = np.sum(coin_flip_data.numpy())
        L += [num_heads]

np.var(L)
> 0.668999


text:
Q: IN clause causing query to run slow For a better performance I am storing variable in Global table and then using it in sub-query but it's the opposite - performance is very slow.If I remove IN clause query performance is faster. Is there any other ways I can use below IN clause differently to optimize performance or any suggestions for better performance. Thanks for any help.
Insert into GlobalTempTable(
  BranchID; //inserting branchID in gtt, this is not required and can be null
);

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate, Employee.EmpName
FROM Orders
JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
JOIN Employee ON Customers.SalesID = Employee.EmpID;
WHERE Orders.OrDate <= '2020-04-01'
AND (BranchID IS NULL or Employee.BranchID IN (SELECT BranchID FROM GlobalTempTable )); //this IN clause is
causing query to run slow

A: Try replacing with EXISTS:
EXISTS ( SELECT 1 FROM GlobalTempTable gtt Employee.BranchID = gtt.BranchID )

And be sure you have an index on GlobalTempTable(BranchID).


text:
Q: How to rename the set of files with pattern I have files which has name as following:

P50_FR_8_q2_scrolls.csv

Here the value 50 and 8 needs renaming & The results should be something like:

P21_FR_3_q2_scrolls.csv

I tired few similar to rename 's/\d{3}(\d{*})\.csv$P21_$1.csv' *.csv
But no luck. (It seems I am really bad at Linux regex)
The value 50->21 and 8->3 is something that i know. But the starting value and ending value is not always in same digit size.

A: Try
rename -n 's/50(_.*)_8/21$1_3/' *.csv

The -n flag doesn't do any renaming. You can test patterns this way. Remove it for actually performing the renaming.


text:
Q: How to convert an integer with n decimal places to a float I have this integer
7839486009458047182
I have a variable that tells me this number should have n decimal places (In this case 18)
How can I change it to 7.839486009458047182
(If React has this as a method I could use in a template that's even better!)

A: If you're not too bothered about precision, you can simply divide the integer by 10 ** decimals, for example:

console.log(7839486009458047182 / (10 ** 18));
// ^ 7.839486009458047

Mind that floats have limited precision. If precision is key, keep it as an integer (or bigint). If it's just for display purposes, then a small amount of imprecision shouldn't be an issue.

A: You can divide the integer by 10 raised to the number of decimal places.

let integer = 7839486009458047182

function setDP(number, decimalPlaces) {
  return number / 10 ** decimalPlaces
}

console.log(setDP(integer, 18))


text:
Q: Pythonanywhere - Error code: Unhandled Exception Using Python 2.7 and Django 1.10.4, I was trying to deploy my app to pythonanywhere, but I keep getting this error.

Error Log

wsgi.py
import os
import sys

path = '/home/hellcracker/First-Blog'
if path not in sys.path:
    sys.path.append(path)

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

from django.core.wsgi import get_wsgi_application
from django.contrib.staticfiles.handlers import StaticFilesHandler
application = StaticFilesHandler(get_wsgi_application())

I can't tell where the error is coming from.
Any help would be appreciated!

A: First of all, check the link give in the error log - https://help.pythonanywhere.com/pages/DebuggingImportError/
You could also search for 'from django core wsgi no module named wsgi'. There are many answers already, and I think you should be able to find the answer to your problem there.

A: Make sure that your project name is "mysite" if not update this line
os.environ['DJANGO_SETTINGS_MODULE'] = '<your-project-name>.settings'

Project name will be the directory name parent to your app name, see that in your local machine.