text:
Q: How does WebRTC handle many-to-many connections? if I am in a room with other 7 users, I am wondering if WebRTC force every user to establish a connection to each one of other participants.
Obviously it would consume something like 7kb/s*7 download and even upload, and many connection cannot handle this if their connection is already busy.
Instead with some kind of media relay the bandwidth usage would be only 7kb/s but you would lose bandwidth adaptation between peers.
Do you know any media relay, or way to solve this problem? is TURN server ( like https://code.google.com/p/rfc5766-turn-server/ ) suitable for this kind of job ( multicast included )?

A: A TURN server works as a fallback relay server in order to enable connectivity when direct peer-to-peer connectivity is impossible because of firewalls or other network issues. (More information here: press P for speaker notes.) TURN servers are not designed for media distribution.
A Multipoint Control Unit could solve the problem you refer to: there's an example topology for this here. As stated in the notes for that slide:

This is a server that's made specifically to do distribution of media,
  and can handle large numbers of participants; it can also do smart
  things like selective stream forwarding, mixing of the audio or video,
  or recording.

A: Have a look at https://datatracker.ietf.org/doc/html/draft-ietf-rtcweb-use-cases-and-requirements-06 for details about WebRTC use cases. The authors mention a multi-user conferencing solution that uses a central server. So the best solution of establishing multi-user A/V conferences using WebRTC is to have such a central server that does the audio mixing and A/V "broadcasting" to all peers.
This circumvents the bandwidth problems you mention in your question. Currently a whole bunch of start-ups and established service providers are working on WebRTC-based conferencing solutions, just let your favourite web search engine pick some examples.
A TURN server alone doesn't suffice since TURN is only used to relay data for hosts that can't be reached directly (possibly because of firewalls). TURN servers don't terminate WebRTC connections.

A: Yes, you would have to establish separate connections to each of your peers. In order to solve this you could use a media server like kurento.
With a media server every peer would connect to the media server, the server would then combine the video streams from your peers into one by placing them side by side and then send you the new stream. This saves peers the trouble of having to download streams from every other peer.

A: You are right that bandwidth adaption between peers is an issue.
A TURN server does not solve this issue since all it does is provide a stable endpoint, typically for people behind very restrictive NAT setups.
The solution to this issue lies in scalable video codecs. These video codecs are specifically designed to solve the multi-way video conferencing problem.  H.264/SVC is one such scalable codec and it is currently used by Google+ Hangouts.  VP8 also has temporal and spatial scalability and is used in WebRTC.
The scalable video codecs are designed so that parts of the stream, typically individual UDP packets, can be removed from the stream while preserving the ability to decode the video at a lower quality.  At least three types of scalabilities are used:

*

*Temporal, in which the frames-per-second is reduced.

*Spatial, where the number of pixels is reduced.

*Quality, where the color resolutios is reduced.

If you implement a video conferencing server, you can go into the VP8 stream at a lower level than the WebRTC-level, do the necessary changes to each video stream, and solve the bandwidth adaption issue.

A: If the question still stands , here is my suggestion :
Based on your SIP server install a RTP proxy software such as if you are using kamailio couple it with rtpengine.


text:
Q: Suppose that $ a,b \in \mathbb{Z}$ If 4 divides $ a^2 + b^2$, then $a$ and $b$ are not odd. I am trying to prove old test exercises and this one is resisting me.
I know you can believe that I meant $a^ 2 + b ^ 2$ is divisible by 4, but no, in the test it says that 4 is divisible by $a ^ 2+ b^2$.
Suppose that $ a,b \in \mathbb{Z}$  If 4 is divisible by $ a^2 + b^2$, then $a$ and $b$ are not odd.
I started like this:
Suppose that a and b are even, then $a = 2m$ and $b = 2n$ for some $m,n \in \mathbb{Z} $.
Thus  $$ a^2 = (2m)^2 \ \mbox{and}\ \  b^2= (2n)^2$$
$$ a ^2 + b^2= (2m)^2 + (2n)^2$$
$$ a^2 + b^2 = (4 m^2 + 4n^2) = 2(2m^2+2n^2) $$
Now $$2m ^ 2 + 2n^2\in \mathbb{Z} = k$$ Then
$$ a^2+b^2= 2k$$
Is this a correct proof?/ Any better ways to prove this.
Sorry for the lousy English.
Thanks.

A: I'm going to assume you mean $a^2 + b^2$ is divisible by $4$.
Assume $a, b$ are odd. Then $a^2 + b^2 = (2k +1)^2 + (2j+1)^2 = (4k^2 + 4k + 1) + (4j^2 + 4j + 1) = 2(2k^2 + 2j^2 + 2k + 2j + 1)$.
This is not divisible by $4$ since the highest power of $2$ is in the product is only $1$.
We have created a contradiction, so $a,b$ cannot both be odd and satisfy $a^2 + b^2$ is divisible by $4$.

A: As Good Morning Captain wrote,
I assume you meant that
$a^2+b^2$
is divisible by $4$.
Consider the values
modulo $4$.
If $a$ is even,
$a=2n$,
then
$a^2 = 4n^2$
leaves a remainder of $0$.
If $a$ is odd,
$a=2n+1$,
then
$a^2 = 4n^2+4n+1 = 4(n^2+n)+1$
leaves a remainder of $1$.
Since each of $a^2$ and $b^2$
can have remainders of
only $0$ or $1$,
their sum can only have
remainders of
$0, 1$, or $2$
and the first
($0$)
happens only when
both are even.

A: I did a more thorough investigation and I found this proof.
Prove by contradiction
Assume $4|(a^2+b^2)$, where a and b are both odd.
Then $a=2m+1$, $b=2n+1$
Substitute in the equation and  $4|4(m^2+m+n^2+n)+2$
We know that $a|b$ if $a|(b+xa) \forall x \in \mathbb{z}$. Since $(m^2+m+n^2+n)$ is an integer, you have $4|4(m^2+m+n^2+n)+2−4(m^2+m+n^2+n)$ where we have used the above formula with $x = -(m^2 + m + n^2 + n)$. This simplifies to $4|2$, which is a contradiction.
This proof was done by user John Colanduoni in this post Proving by Contradiction
I will proceed to put my post as a duplicate.

A: I am with the other commenters that they probably meant that $a^2+b^2$ is divisible by $4$, because that would actually make for a somewhat interesting proof, whereas assuming that $4$ is divisible by $a^2+b^2$ really does not. In fact, if $4$ is divisible by $a^2+b^2$, then $a$ and $b$ can both be odd: they can both be $1$, and so $a^2+b^2=1+1-2$, which divides $4$.
OK, but you asked about your own proof: Well, it's pretty bad, to be honest. Your proof as a whole shows that $a^2+b^2$ is even if both $a$ and $b$ are even ... which is not only a trivial result, but most importantly it is not what you need to show: if you were thinking that your proof shows that if $a^2+b^2$ is even then both $a$ and $b$ must be even, you're wrong: $a$ and $b$ both being odd would also result in $a^2+b^2$ being even. And second, why should $a^2+b^2$ be even? The claim that $4$ is divisible by $a^2+b^2$ does not mean that $a^2+b^2$ is even: $1$ divides $4$, but is odd.

redpajama_set_name: RedPajamaStackExchange


text:
Q: TextView value changed in last N seconds How to check in Android if the value in TextView has not changed in last 2 seconds.
I have a condition that value in a TextView is kept changing as my app receiving data from Bluetooth.
I have to check when data stops coming, so on basis of that, I can update my UI.
Here is my code for handling text view
 textOngoingBP.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
       Logger.log(Level.DEBUG,TAG, --OnText CHanged");
    }

    @Override
    public void afterTextChanged(Editable editable) {
       // startTest and stopTest is button for start test
       startTest.setVisibility(View.GONE);
       stopTest.setVisibility(View.VISIBLE);
       Logger.log(Level.DEBUG,TAG,"--AfterText Changed");
    }
});

Here I have to make start button visible and stop button gone when no data is coming. Any idea?

A: You can use a Timer and reset the timer every time that a TextView has been edited.
Try this:
Timer timer = new Timer();

//timer.schedule(new MyTask(),2000);

class MyTask extends TimerTask {
        public void run() {
            Log.i("TAG","2 seconds.");
        }
    }

textOngoingBP.addTextChangedListener(new TextWatcher() {
     @Override
     public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

     }

     @Override
     public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
         //timer.cancel();
         //timer = new Timer();
         //timer.schedule(new MyTask(),2000);
         Logger.log(Level.DEBUG,TAG, --OnText CHanged");
    }

     @Override
     public void afterTextChanged(Editable editable) {

         timer.schedule(new MyTask(),2000);
    startTest.setVisibility(View.GONE);
    stopTest.setVisibility(View.VISIBLE);
    Logger.log(Level.DEBUG,TAG,"--AfterText CHanged");
           }
          }
        );

A: You could have something like this, that saves the time it was up last updated.
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;

/**
 * This class was created by Anthony M Cannon on 15/05/2018.
 */
public class ChangingTextView extends android.support.v7.widget.AppCompatTextView {

    private long lastUpdated = -1;

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

    public ChangingTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ChangingTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        lastUpdated = System.currentTimeMillis();
        super.setText(text, type);
    }

    public long getLastUpdated() {
        return lastUpdated;
    }
}

Then you could have a background thread that checks it every so often.


text:
Q: How to get percentage axes in a Highcharts Treemap? I have a HighCharts Treemap showing a set of categories containing subcategories. The point of the graph is to show how much of the data is in Category A, and how much of Category A is in Subcategory A1.
I have created this as follows:
http://jsfiddle.net/jbcfk93m/
$(function () {
$('#container').highcharts({
    series: [{
        colorByPoint: true,
        layoutAlgorithm: "stripes",
        alternateStartingDirection: true,
        allowPointSelect: true,
        point: {
            events: {
                click: function () {
                        alert(this.name + ": " + this.value);
                    }
                }
        },
        dataLabels: {

        },
        type: "treemap",
        levels: [{
            level: 1,
            dataLabels: {
                enabled: true,
                align: 'right',
                rotation: 30,
                crop: false,
                overflow: 'none',
                inside: false,
                style: {
                    fontSize: '15px',
                    fontWeight: 'bold'
                }
            }
        }, {
            level: 2,
            dataLabels: {
                style: {
                }
            },
            layoutAlgorithm: "stripes",
        }],
        data: [{
            // Add parents without values
            id: 'CategoryA',
            name: 'Category A'
        }, {
            id: 'CategoryB',
            name: 'Category B',
        }, {
            // And the children with values
            name: 'Subcat A1',
            value: 4,
            parent: 'CategoryA'
        }, {
            name: 'Subcat A2',
            value: 6,
            parent: 'CategoryA'
        }, {
            name: 'Subcat B1',
            value: 6,
            parent: 'CategoryB'
        }, {
            name: 'Subcat B2',
            value: 2,
            parent: 'CategoryB'
        }
        ]
    }],
    title: {
        text: 'Treemap',
        margin: 100
    },
    xAxis: {
        min: 0,
        max: 100
    }
});
});

I want to get both the X- and Y axes in the graph to show percentages so I can more easily see how much of my data is in a certain category.
Does anyone know how to do this?

A: I didn't find anything about axis on treemaps and i'm not really sure if showing a percentage on X and Y axis would help you that much, because you basically have to multiply the values on X and Y(eg. if your subcat B1 is from 20% to 100% on X axis and from 60% to 100% on the Y axis then you would have to do (100% - 20%) * (100% - 60%) = 32%).
I did implement however a tooltip formatter that will show you the percentage when you hover over the subcategories.
formatter: function () {
    var total = 0;
    for (var i = 0; i < this.series.data.length; i++)
    {
        if (this.series.data[i].node.children.length == 0)
        total+=this.series.data[i].node.val;
    }
    var value;
    if (this.point.node.children.length == 0)
    {
        value = this.point.options.value;
    }
    else
    {
        value = this.point.node.childrenTotal;
    }

    return this.key + " " + (value / total) *100 + " %";
}

Here is the working fiddle http://jsfiddle.net/jbcfk93m/4/


text:
Q: Let's put a $\mathrm{Pin}$ in it$.$ As it turns out, the low-energy behaviour of (gapped) systems with fermionic degrees of freedom can be described by a so-called Spin TQFT. Such models require the introduction of a (S)pin structure. If the base manifold is non-trivial, the (S)pin structure is not in general unique, and different structures are physically inequivalent.
As long as we keep the discussion abstract, this all makes sense to me. But when I try to map these mathematical statements into real-life systems, nothing makes much sense anymore. If I have an actual physical system — say, a superconductor — that supports fermionic excitations, then the dynamics surely must be unique.

*

*What determines which (S)pin structure is the correct one? How do we know, a priori, which of the inequivalent structures is actually realised?

*(How) Can we modify a system so as to change the (S)pin structure (and nothing else, if possible)? What are the measurable differences we may observe before and after the change?


text:
Q: To insert or not insert quotation marks, that is the question! Can the following sentence be correct with and without quotation marks?

Did Mother say we are going to Disney World?

I would answer yes, but I have read in the past the word "that" should be inserted if no quotations are to be used.

Did Mother say that we are going to Disney World?

I have one more with the same question:

Nan explained the essay "Doughboys" is about World War I.

This one I would say needs "that" inserted in order to get rid of dialog quotation marks, but I'm probably wrong---just about the time I think I have some part of grammar figured out and is "absolute" I find it is not absolute at all!
Thank you for your assistance.

A: When you say, "Did mother say we are going to Disney World?" it's grammatically correct. You don't need the quotations, but only if you aren't sure those were her exact words. If you were quoting her, however, you would say:

Did mother say "We are going to Disney World"?

It all depends on if you were repeating the mother's exact words. Otherwise, it's paraphrasing and no quotations are necessary. A "that" can also be used here.

Nan explained the essay "Doughboys" is about World War 1.

In this situation, you need the quotation marks, because you are giving the title of something. Feel free to add a "that" in there but the quotation marks must stay.


text:
Q: Scan file with 3 possible regex in one method I am trying to retrive data from a folder which contains 3 .txt file (the same information) but in a different order.
The data that I need to get is : Date Text number (one ligne)
But the structure of my file is unique for each of them
file1 :
Date text
number

file2 :
Date
Text number

file3 :
Date
Text
number

Any suggestion !

A: (Date)\/?\s*(text)\/?\s*(number)

Try this.grab group 1,2,3 .See demo.
https://regex101.com/r/iS6jF6/22

A: This pattern should be alright:
(?i)(date)(?:\/|\s*)(text)(?:\/|\s*)(number)
Java string in code:
 var pattern = "(?i)(date)(?:\\/|\\s*)(text)(?:\\/|\\s*)(number)";

Output:
Match 1:
    0: [11,32] Date/text number
    1: [11,15] Date
    2: [16,20] text
    3: [26,32] number
Match 2:
    0: [45,66] Date Text/number
    1: [45,49] Date
    2: [55,59] Text
    3: [60,66] number
Match 3:
    0: [81,107] Date Text number
    1: [81,85] Date
    2: [91,95] Text
    3: [101,107] number


text:
Q: Can't get text of an XML element in python I am trying to parse an XML file in python. Here is a small portion of the XML code:

   <ph>text1 </ph>
      DESIRED TEXT
   <ph>text2</ph>
   <ph>sometext...</ph>

I want to get "DESIRED TEXT". I did the following:
import xml.etree.ElementTree as ET

tree = ET.parse(dir)
root = tree.getroot()

for el in root.findall("./body/p"):
    print(el.attrib, el.text)

el.attrib return the correct values (which is XXX in this case) but el.text return None.
What am I missing? What should I use instead of .text?
Thanks in advance.

A: You can use xmltodict lib:
import xmltodict

with open('file.xml', 'r') as f:
    result = xmltodict.parse(f.read())['body']['p']['#text']

Output:
DESIRED TEXT

A: below (no need to install an external library)
import xml.etree.ElementTree as ET

xml = '''

   <ph>text1 </ph>
      DESIRED TEXT
   <ph>text2</ph>
   <ph>sometext...</ph>

'''

root = ET.fromstring(xml)
print(root.findall('.//ph')[0].tail.strip())


text:
Q: Strange square-numerical symbols show as characters in Firefox I have been seeing these strange symbols for a while now, and am curious as to what they are, and why they appear. Sometimes, they appear so frequently in one page, the writing is indecipherable. The symbols appear as they do below in Firefox, but they appear as little squares in Internet Explorer.
Here's an example:

*

*What are they?

*How do I get rid of them?

A: In general Firefox renders all Unicode characters that it can't find a glyph for in your fonts as a box containing the character code. If you go to eg. a Chinese web site and you don't have Chinese fonts installed, you'll get nothing but little boxes.
However that particular character in the screenshot is � U+FFFD REPLACEMENT CHARACTER. (I get a diamond shape with a question mark; you might also get a square box or just a question mark.)
Unless someone has deliberately typed that character, which is unlikely (except for me just doing it above), U+FFFD means someone has screwed up their encodings at some point along the line, and either:

*

*tried to encode a character into an encoding that doesn't support it, for example if someone tried to send a Chinese character in a Latin-1 encoding, or

*served an encoded byte sequence as UTF-8 when actually it's something else.
In the particular screenshot it is clearly a problem where "smart quotes" have been submitted as single Windows code page 1252 bytes. Then the data has probably been misattributed as UTF-8.
Where the misattribution is due to your browser guessing the charset wrong (for stupid pages that don't label their charsets), you can fix it by going to View->Encoding and guessing the right one. Where the misattribution is due to the web site's own processing of strings, there's not much you can do about it. Unfortunately many web sites get charsets wrong, particularly those written in Unicode-ignorant languages like PHP, classic-ASP, Ruby and JSP (despite Java's native strings, JSP/Servlet is pretty broken wrt encodings).

A: They're unicode PLACEHOLDERS; the number represents the unicode codepoint for the glyph that's missing in the font(s) available.  Use a font that covers more of the unicode characters needed, and these boxes will be replaced by nice international characters.
Note that this can also be caused by having the browser (or other app) assume the wrong document encoding.  For instance, if your character encoding settings specify that a document should be interpreted as cyrillic (russian) encoding, and your document is actually encoded as chinese, then then you'll get wrong glyphs where the character maps happen to overlap, and placeholder glyphs (the boxes with numbers) where the character maps don't overlap.

A: They're unicode symbols; I asked this question w/r/t printing on superuser.

A: The characters that the symbol represents are smart quotes (" and "), incorreclty input by an all-too-eager copy and paste finger. Or rather they're what programs like Microsoft Word uses to represent smart quotes.
Either the both quotes should be ", or the first should be " and the second ".


text:
Q: Electric field inside a charged conductor Why is electric field inside a charged  conductor always zero? In an uncharged conductor if an electric field is applied then the charges reconfigure themselves as to have no net electric field. In a case of a charged conductor when a net electric field always zero even when there is no electric field applied. Can someone explain both the cases. When there is no electric field applied and when there is?

A: All you need to do is think about the fact that at any place inside a conductor the local charge can move around.
So if there is an electric field at any given place, then the charge there will move around. It will be accelerated in the direction of the electric field.
Now you can have an electric field inside a conductor in a dynamic situation. This is what happens inside an antenna when it is absorbing or emitting radio waves, for example. But it is the static case where the electric field has to be zero. It must be zero because if it were not zero then the charge would be accelerating so the situation would not be static!
Note the logic here. So far I have not given a demonstration of the physical cause of why the electric field is zero (I will come to that in a moment). It is a piece of detective work. The argument is saying "in view of the fact that the charge here is not accelerating, the electric field must be zero." The detective has determined that since the body is dead, it has been killed, but he does not yet know how or why.
So now let's come to the how and why. What happens is that the charges inside the conductor move, and move again, and keeping moving, moving, and thus build up in one place or another, and as they do so they are themselves producing electric fields. And the lovely thing is, as soon as some charge accumulates in one place, it will produce a field such as to discourage other charge from going there (because like charges repel). Thus you have the possibility that eventually (and in practice pretty quickly) the charge can find a configuration so that it just cancels, inside the conductor at least, whatever fields would otherwise be there, by itself providing an equal and opposite field. As soon as the charge manages to find that configuration, it will stay there so the whole situation is stable.


text:
Q: Combine Chart.js programmatic and legend based dataset toggling How can I make programmatic toggling of datasets play together with the one from ChartJS' legend clicking?
Here's a repro of my problem:

*

*Run below snippet.

*Toggle fruit data off with button: just works!

*Toggle fruit data back on with button: just works!

*Toggle fruit off by clicking the legend item: works.

*Toggle fruit back on by clicking the legend item: works.

*Toggle fruit again with the button: ⚠ broken!

I expect the custom logic to play nice with ChartJS' built in feature.

const chart = new Chart(document.getElementById("chart").getContext("2d"), {
  type: "bar",
  data: {
    labels: ["label1", "label2", "label3"],
    datasets: [
      { label: "Fruit", backgroundColor: "IndianRed", data: [1,2,3] },
      { label: "Veggies", backgroundColor: "LightGreen", data: [2,5,3] },
    ]
  }
 });

 function togglestuff() {
   const dataset = chart.data.datasets.find(ds => ds.label === "Fruit");
   dataset.hidden = !dataset.hidden;
   chart.update();
 }

<canvas id="chart" height="75px"></canvas>

<button id="hide" onclick="togglestuff()">
  Toggle fruit programmatically
</button>

What am I doing wrong?

A: Turns out hidden works, but there's also a property visible which then needs to be programmatically used with setDatasetVisibility(datasetIndex, visibility) .
So, one method would be:

*

*Get dataset index with indexOf or similar

*Get metadata at that index with chart.getDatasetMeta(index)

*Use metadata.visible and pass it to setDatasetVisibility(...)

*chart.update() as per usual

const chart = new Chart(document.getElementById("chart").getContext("2d"), {
  type: "bar",
  data: {
    labels: ["label1", "label2", "label3"],
    datasets: [
      { label: "Fruit", backgroundColor: "IndianRed", data: [1,2,3] },
      { label: "Veggies", backgroundColor: "LightGreen", data: [2,5,3] },
    ]
  }
 });

 function togglestuff() {
   const dataset = chart.data.datasets.find(ds => ds.label === "Fruit");
   const index = chart.data.datasets.indexOf(dataset);
   const metadata = chart.getDatasetMeta(index);
   chart.setDatasetVisibility(
     index,
     !metadata.visible,
   );
   chart.update();
 }

<canvas id="chart" height="75px"></canvas>

<button id="hide" onclick="togglestuff()">
  Toggle fruit programmatically
</button>


text:
Q: How to define usort for my array to be sorted in a specific order? I am trying to build a php class which should sort my results coming from a mysql database in the order of their "similarity" to the entered search query. I am using the php function similar_text.
class compare {

static $_base = NULL;

static function setBase($base) {
    if (!isset ($base) or !is_string($base)) {
        $base = "";
    }
    self::$_base = strtolower($base);
}

static function cmp($a) {
    if (!is_string(self::$_base)){
        self::setBase();
    }
    similar_text(self::$_base, strtolower($a), $a_pct);
    return $a_pct;
}

static function eachcmp($src, $arr)
{
    $ordered = array();
    foreach($arr as $key => $val)
    {
        $sim = cmp($val);
        $ordered[]["something"] = $arr[$key]["something"];
        $ordered[]["something2"] = $arr[$key]["something2"];
        $ordered[]["sim"] = $sim;
    }
}

}
As you can see in the function "eachcmp" I am comparing each value in the array with the Base and then writing all the values into a new array. Now my problem starts here. How can I now order the array in the order of $ordered[]["sim"]? I know I probably need to use usort, but I dont know which function to give as parameters for usort.
Thx for help!
phpheini

A: First of all, I think your function should look like this:
static function eachcmp($src, $arr)
{
    $ordered = array();
    foreach($arr as $key => $val)
    {
        $sim = cmp($val);
        $data = array();
        $data["something"] = $arr[$key]["something"];
        $data["something2"] = $arr[$key]["something2"];
        $data["sim"] = $sim;
        $ordered[] = $data;
    }
}

Otherwise you would be creating the new array elements in the $ordered array.
Now for the usort. usort expects an array and a comparison function. In PHP >= 5.3 you can use lambda functions for that. A suitable comparison function for your need might look like this:
 usort($ordered, function($a, $b) {
    $al = intval($a["sim"]);
    $bl = intval($a["sim"]);
    if ($al == $bl) {
        return 0;
    }
    return ($al > $bl) ? +1 : -1;
 });


text:
Q: How to extract JSON/Table from a javascript variable in python I have been trying to scrape https://support.riverbed.com/content/support/eos_eoa.html which contains a paginated table generated in javascript.
I am currently using beautiful soup to capture the script element. However the variable EOL_ENTRIES hold the data I need but I am unable to parse it. Any tips on how to successfully scrape the data.
The ultimate aim is to actually put this data in PowerBI, However PBI is only able to scrape the first page.
Any help is much appreciated.
import re
from bs4 import BeautifulSoup

http = httplib2.Http()
url='https://support.riverbed.com/content/support/eos_eoa.html'
resp, data = http.request(url)
html = data.decode("UTF-8")
soup = BeautifulSoup(html, 'html5lib')

#the 37th script which contains the data
script_with_data = soup.find_all('script')[37]

The Sample output looks like
<script type="text/javascript">

        var EOL_ENTRIES = [

                {
                    productFamily: 'SteelCentral',
                    shortName: 'SteelCentral AppInternals Collector v9',
                    link: 'https:\/\/support.riverbed.com\/content\/support\/eos_eoa\/steelcentral-cascade-opnet\/SteelCentral-AppInternals-Console-v9-and-AppInternals-Collector-v9-BrowserMetrix-OnPremise.html',
                    linkOverride: 'https:\/\/support.riverbed.com\/content\/support\/eos_eoa\/steelcentral-cascade-opnet\/SteelCentral-AppInternals-Console-v9-and-AppInternals-Collector-v9-BrowserMetrix-OnPremise.html',
                    sku: 'AIXCOL',
                    skuOverride: '',
                    description: 'SteelCentral AppInternals Collector v9',
                    limitedAvailability: '',
                    limitedAvailabilityFormatted: '',
                    endOfAvailability: 'Wed Jul 03 00:00:00 PDT 2019',
                    endOfAvailabilityFormatted: 'Wed Jul 03 00:00:00 PDT 2019',
                    endOfSupportFeatures: 'Sat Aug 31 00:00:00 PDT 2019',
                    endOfSupportFeaturesFormatted: 'Sat Aug 31 00:00:00 PDT 2019',
                    endOfSupportMaintenance: 'Sat Aug 31 00:00:00 PDT 2019',
                    endOfSupportMaintenanceFormatted: 'Sat Aug 31 00:00:00 PDT 2019'}
];

A: The data is in JavaScript, so you need some preprocessing to be able to load it with json module:
import re
import json
import requests
from bs4 import BeautifulSoup

url = 'https://support.riverbed.com/content/support/eos_eoa.html'
soup = BeautifulSoup(requests.get(url).content, 'html5lib')

# select <script> tag of interest
s = soup.find(lambda t: t.name == 'script' and 'var EOL_ENTRIES' in t.text)

# extract string from this script tag
t = re.search(r'var EOL_ENTRIES = (\[.*\]);', s.text, flags=re.S)[1]

# preprocess the string
t = t.replace("'", '"')
t = re.sub(r'^(\s*)(.*?):', r'\1"\2":', t, flags=re.M)

# decode string to Python data
data = json.loads(t)

# uncomment this to print all data:
# print(json.dumps(data, indent=4))

# print some data to screen:
for product in data:
    print('{:<40} {:<40} {}'.format(product['sku'], product['productFamily'], product['shortName']))

Prints:
AIXCOL                                   SteelCentral                             SteelCentral AppInternals Collector v9
AIXCOL-AN                                SteelCentral                             SteelCentral AppInternals Collector v9
AIXCOL-LP                                SteelCentral                             SteelCentral AppInternals Collector v9
AIXCOL-LP-MODEL                          SteelCentral                             SteelCentral AppInternals Collector v9
AIXCOL-LS                                SteelCentral                             SteelCentral AppInternals Collector v9
AIXCOL-LS-MODEL                          SteelCentral                             SteelCentral AppInternals Collector v9
AIXCOL-SITE                              SteelCentral                             SteelCentral AppInternals Collector v9
AIXCOL-SUB-LIC                           SteelCentral                             SteelCentral AppInternals Collector v9
PANCOL                                   SteelCentral                             SteelCentral AppInternals Collector v9

... and so on.

A: If you are trying to get the data into Power BI, I would take a different approach: extract the data and load it into a dataframe, which can then be exported to Excel/CSV which PBI can read.
So I would try this:
import pandas as pd
prods = str(script_with_data).split('var EOL_ENTRIES = [')[1].split('}')[0].replace('\t','').replace('\n','').split(',')
    rows = []
    for prod in prods:
        row = []
        row.extend([prod.split(': ')[0],prod.split(': ')[1].replace("'","")])
        rows.append(row)

    pd.DataFrame(rows)

and from here use standard panda methods to export the dataframe.


text:
Q: Angular 8 Material not rendering My Angular 8 Material components are not rendering correctly .It should look like the example below:

But it looks like this:

Here is the app.module.ts:
import { FormsModule } from '@angular/forms';
import {MatFormFieldModule} from '@angular/material/form-field';

@NgModule({
   declarations: [
   AppComponent,
   LoginComponent
],
imports: [
  BrowserModule,
  AppRoutingModule,
  BrowserAnimationsModule,
  FormsModule,
  MatFormFieldModule
],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Here is the app.component.html
<div class="example-container">
<mat-form-field>
    <input matInput placeholder="Input">
</mat-form-field>

<mat-form-field>
    <textarea matInput placeholder="Textarea"></textarea>
</mat-form-field>

<mat-form-field>
    <mat-select placeholder="Select">
        <mat-option value="option">Option</mat-option>
    </mat-select>
</mat-form-field>

A: I think you should use   MatSelectModule and  MatInputModule
Because MatFormModule used for Matform
So your module should be like this
import { FormsModule } from '@angular/forms';
import {MatFormFieldModule} from '@angular/material/form-field';

import {MatSelectModule,MatInputModule} from '@angular/material/form-field';

@NgModule({
   declarations: [
   AppComponent,
   LoginComponent
],
imports: [
  BrowserModule,
  AppRoutingModule,
  BrowserAnimationsModule,
  FormsModule,
  MatFormFieldModule,
  MatSelectModule,
  MatInputModule
],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

and also you can import css in style.css file
@import "~@angular/material/prebuilt-themes/indigo-pink.css";

WORKING DEMO

A: You have to add MatInputModule (for input and textareas) and MatSelectModule (for select) to your app.module.ts file.
You can see what is needed for component at the top of this pages:
material input component
material select component


text:
Q: jQuery - Apply Multiple Events on Multiple Fields - NOT WORKING I have HTML like this:

                Start Date
                <input class="form-control" type="text" id="start_date_of_page" value="" placeholder="">

                End Date
                <input class="form-control" type="text" id="end_date_of_page" value="" placeholder="">

                State
                <select required id="state_id_of_page" name="state_id" class="form-control">
                    <option value="">Please Select State</option>
                    <option value=253>Alabama</option>
                    <option value=254>Alaska</option>
                    <option value=303>Alberta</option>
                    <option value=255>Arizona</option>
                    <option value=256>Arkansas</option>
                    <option value=304>British Columbia</option>
                    <option value=257>California</option>
                    <option value=258>Colorado</option>
                    <option value=259>Connecticut</option>
                    <option value=260>Delaware</option>
                    <option value=317>District of Columbia</option>
                    <option value=261>Florida</option>
                    <option value=262>Georgia</option>
                    <option value=263>Hawaii</option>
                    <option value=264>Idaho</option>
                    <option value=265>Illinois</option>
                    <option value=266>Indiana</option>
                    <option value=267>Iowa</option>
                    <option value=268>Kansas</option>
                    <option value=269>Kentucky</option>
                    <option value=270>Louisiana</option>
                    <option value=271>Maine</option>
                    <option value=305>Manitoba</option>
                    <option value=272>Maryland</option>
                    <option value=273>Massachusetts</option>
                    <option value=274>Michigan</option>
                    <option value=275>Minnesota</option>
                    <option value=276>Mississippi</option>
                    <option value=277>Missouri</option>
                    <option value=278>Montana</option>
                    <option value=279>Nebraska</option>
                    <option value=280>Nevada</option>
                    <option value=306>New Brunswick</option>
                    <option value=281>New Hampshire</option>
                    <option value=282>New Jersey</option>
                    <option value=283>New Mexico</option>
                    <option value=284>New York</option>
                    <option value=307>Newfoundland and Labrador</option>
                    <option value=285>North Carolina</option>
                    <option value=286>North Dakota</option>
                    <option value=314>Northwest Territories</option>
                    <option value=309>Nova Scotia</option>
                    <option value=315>Nunavut</option>
                    <option value=287>Ohio</option>
                    <option value=288>Oklahoma</option>
                    <option value=310>Ontario</option>
                    <option value=289>Oregon</option>
                    <option value=290>Pennsylvania</option>
                    <option value=311>Prince Edward Island</option>
                    <option value=312>Quebec</option>
                    <option value=291>Rhode Island</option>
                    <option value=313>Saskatchewan</option>
                    <option value=292>South Carolina</option>
                    <option value=293>South Dakota</option>
                    <option value=294>Tennessee</option>
                    <option value=295>Texas</option>
                    <option value=296>Utah</option>
                    <option value=297>Vermont</option>
                    <option value=298>Virginia</option>
                    <option value=299>Washington</option>
                    <option value=300>West Virginia</option>
                    <option value=301>Wisconsin</option>
                    <option value=302>Wyoming</option>
                    <option value=316>Yukon</option>
                </select>

                Company
                <select required id="company_id_of_page" name="company_id" class="form-control">
                    <option value="">Please Select a Company</option>
                    <option value=0>Data Before Company Divition</option>
                    <option value=2>HP-CA</option>
                    <option value=1>HP-NY</option>
                </select>

And the jQuery for handling events is like this:
$(document).ready(function(e)
{
    $(document).on("keyup change", "#start_date_of_page #end_date_of_page #state_id_of_page #company_id_of_page", function()
    {
        alert("Working!!!!");
    });
}

But there is no alert when anything changes, so the jQuery events are not working.
Can anyone tell me what I am doing wrong?

A: Working fine you have Syntax error in your code
missing , in selectors
instead of
 "#start_date_of_page #end_date_of_page `#state_id_of_page #company_id_of_page"

use
"#start_date_of_page,#end_date_of_page,`#state_id_of_page,#company_id_of_page"

Working demo http://jsfiddle.net/ocptrcfu/1/

A: $(function(){
    $(document).on('change', 'input,select', function(event){
        console.log(event);
        console.log( $(this).val() );
        alert("Working!!!!");
    });
});


text:
Q: Laravel SOAP request call I'm looking to get access to a specific API (found here: https://jigsaw.w3.org/css-validator/manual.html#api), however this is a SOAP api and I've never worked with SOAP. So I install this package: https://codedredd.github.io/laravel-soap/ and I try a test call. It looks like this:
    $response = Soap::baseWsdl('https://jigsaw.w3.org/css-validator/validator')
        ->call('validator', [
            'text' => $text,
            'lang' => 'en',
        ]);

    dd($response);

however I already know this is going to fail because I have no idea what to put into the ->call('')
and as expected I get the response:

#response: GuzzleHttp\Psr7\Response {#1715
-reasonPhrase: "Bad Request"

Help?

A: According to the documentation you provided. https://jigsaw.w3.org/css-validator/manual.html#api
You have to set the output to either 'application/soap+xml' or 'soap12'
$response = Soap::baseWsdl('https://www.w3.org/2005/09/css-validator.wsdl')
    ->call('validator', [
        'uri' => $text,
        'lang' => 'en',
        'output' => 'application/soap+xml'
    ]);

dd($response);

A: Answer: This is not a SOAP API. That's embarrassing. The title of the documentation was "CSS Validator Web Service API SOAP 1.2" so I had assumed it was going to be a SOAP API. But no, the SOAP part is just a reference to returning XML.


text:
Q: How to get searched word or params in searched url I am making Google clone website. I want to get the searched word from a search bar of landing page and put that searched word into the search bar of list page, so I can let users know what they searched.
I thought about using props to pass the searched words from landing page to list page, but it seems diffcult to make because I'm using the same search bar in the website. If it's possible that would be awesome!
However, I'm thinking about to get searched word or params in searched URL.
If I search a rabbit, then the URL changed to http://localhost:3000/searched/rabbit.
Therefore, I think I can get the searched word from URL and put it into the search bar.
Once I got the searched word, I will put the word into the value of autocomplete of input.
I'm using react, redux and ant design.
I would appreciate any advices from you. Thank you!
Main page code
<form className="HomeLoader">

      <SearchBar />
    </form>

Customized Search bar codes
import { useCallback, useEffect, useState } from 'react';
import { useHistory, useLocation, useParams } from 'react-router-dom';
import { Input, AutoComplete } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import { useCookies } from 'react-cookie';
import styled from 'styled-components';

import './SearchBar.css';
import { maxRecentHistoryLength } from '../../../assets/values';

const { Search } = Input;

const SearchBar = () => {
  const [cookies, setCookie] = useCookies(['history']);
  const [options, setOptions] = useState<any>([]);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [searchValue, setSearchValue] = useState('00');
  const [first, setFirst] = useState(true);
  const [removeFlag, setRemoveFlag] = useState(false);
  const [selectFlag, setSelectFlag] = useState(false);
  const history = useHistory();
  const location = useLocation();
  const [defaultSearchValue, setDefaultSearchValue] = useState('');

  const renderItem = (title: string, index: number) => ({
    value: title,
    label: (

        {title}

          <CloseOutlined onClick={() => removeHistory(title)} />

    ),
  });

  const makeOptions = useCallback(() => {
    const newOptions: any[] = [];
    if (cookies['history']) {
      cookies['history'].forEach((element: string, index: number) => {
        newOptions.push(renderItem(element, index));
      });
    }
    setOptions(newOptions);
  }, [cookies, cookies['history']]);

  const removeHistory = (title: string) => {
    const historyCookie = cookies['history'];
    const duplicateIndex = historyCookie.indexOf(title);
    if (duplicateIndex !== -1) {
      historyCookie.splice(duplicateIndex, 1);
    }
    setCookie('history', historyCookie);
    setRemoveFlag(true);
  };

  const handler = async (text: string) => {
    setSearchValue(text);
    if (removeFlag) {
      setSearchValue('');
      setRemoveFlag(false);
      return;
    }
    if (text.length === 0) {
      return;
    }
    setDropdownOpen(false);
    let historyCookie;
    if (cookies['history']) {
      historyCookie = cookies['history'];
      const duplicateIndex = historyCookie.indexOf(text);
      if (duplicateIndex !== -1) {
        historyCookie.splice(duplicateIndex, 1);
      }
      historyCookie.splice(0, 0, text);
      historyCookie.splice(maxRecentHistoryLength);
    } else {
      historyCookie = [text];
    }
    setCookie('history', historyCookie);

    history.push(`/searched/${text}`);
  };

  useEffect(() => {
    makeOptions();
  }, [makeOptions]);

  useEffect(() => {
    if (first) {
      setDropdownOpen(false);
      setFirst(false);
    } else {
      if (searchValue.length === 0) {
        setDropdownOpen(true);
      } else {
        setDropdownOpen(false);
      }
    }
  }, [searchValue]);

  useEffect(() => {
    if (selectFlag) {
      if (removeFlag) {
        setSearchValue('');
        setRemoveFlag(false);
      } else {
        handler(searchValue);
      }
      setSelectFlag(false);
    }
  }, [selectFlag]);

  useEffect(() => {
    if (location.pathname) {
      setSearchValue(searchValue);
    }
  }, [location]);

  return (

      <AutoComplete
        // I think I will put the searched value into the value of AutoComplete
        value={searchValue}
        open={dropdownOpen}
        dropdownClassName="certain-category-search-dropdown"
        style={{ width: '100%' }}
        options={options}
        onSelect={(value) => {
          setSearchValue(value);
          setSelectFlag(true);
        }}
      >


text:
Q: Handling input change depending on the number of key value pairs Suppose we have this form right here full of key values pairs (i.e. in this case)
const data = {
  maxPosts: 9999999,
  key: "value"
};

However there can be more key-value pairs and hence more inputs in the picture below.
What is a good way of handling the input change depending on the data given? Because I cannot hardcode all the input handlers like such (as the inputs are dependent on the KV Pairs):

      changeKey1: function (event) {
        // change state
      },
      changeVal1: function (event) {
        // Change State
      },
      changeKey2: function (event) {
        // Change State
      },

Ultimately the user will be editing these values and then press submit to confirm their edit changes. Is there anyway of doing this with React Hooks?

A: Yes, here is a simple example of managing N states.
const generateNValues = N => [...Array(N).keys()];

function TextAreaManager() {
  const [valuesManager, setValuesManager] = useState(generateNValues(10));
  return (
    <Flexbox>
      {valuesManager.map((value, i) => (
        <TextBoxItem
          key={i}
          value={value}
          onChange={e => {
            valuesManager[i] = e.target.value;
            setValuesManager([...valuesManager]);
          }}
        />
      ))}
      <PinkButton
        onClick={() =>
          setValuesManager([...Array(valuesManager.length).fill('')])
        }
      >
        Reset All
      </PinkButton>
    </Flexbox>
  );
}


text:
Q: How to load counter form current text in Objective C I am new in iOS and I am facing problem to  load counter from where it left count.
My code is like this
In
viewDidLoad()
{
    if (!_currentTimeInSeconds) {

           }_currentTimeInSeconds = 0 ;
     if (!_myTimer) {
            _myTimer = [self createTimer];
        }
}
- (NSTimer *)createTimer {
    return [NSTimer scheduledTimerWithTimeInterval:1.0
                                            target:self
                                          selector:@selector(timerTicked:)
                                          userInfo:nil
                                           repeats:YES];
}

- (NSString *)formattedTime:(int)totalSeconds
{
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;

    return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
}
- (void)timerTicked:(NSTimer *)timer {

    _currentTimeInSeconds++;

    clockLabel.text = [self formattedTime:_currentTimeInSeconds];

}
-(void)updateTime
{
    NSDate *date= [NSDate date];
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc]init]; //for hour and minute

    formatter1.dateFormat = @"hh:mm:ss";// use any format

    clockLabel.text = [formatter1 stringFromDate:date];
}

For Save
 NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
 Timmer=clockLabel.text;
 [defaults setValue:Timmer forKey:@"Timmer"];
 [defaults synchronize];

For Retrive
 NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
Timmer=[defaults objectForKey:@"Timmer"];
clockLabel.text=Timmer;

This code is setting value from 0.
I need to set the value from where I left count.How to do this?
Thanks in Advance!

A: If you want to retrieve the count even after you quit and relaunch the app, then you should save/store the value into NSUserDefaults.

A: Just Set value in NSUserDefaults when you leave your controller . And this whole code tested and its work completely fine. see above commented video.
var _currentTimeInSeconds : Int = Int()
var _myTimer : Timer = Timer()

override func viewDidLoad() {
        super.viewDidLoad()
        _currentTimeInSeconds = 0 ;
        _myTimer = self.createTimer()
 }

func createTimer()-> Timer {
        return Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerTicked), userInfo: nil, repeats: true)
}
func timerTicked(_ timer: Timer) {
    _currentTimeInSeconds += 1;
    label.text = self.formattedTime(self._currentTimeInSeconds)

}
func formattedTime(_ totalSeconds: Int) -> String {
    let seconds: Int = totalSeconds % 60
    let minutes: Int = (totalSeconds / 60) % 60
    let hours: Int = totalSeconds / 3600
    return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}
func updateTime() {
        let date = Date()
        let formatter1 = DateFormatter()
        //for hour and minute
        formatter1.dateFormat = "hh:mm:ss"
        // use any format
        label.text = formatter1.string(from: date)
}
override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
        print(_currentTimeInSeconds)
        let defaults = UserDefaults.standard
        defaults.setValue(_currentTimeInSeconds, forKey: "Timmer")
        defaults.synchronize()
}
override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        let defaults = UserDefaults.standard
        if  (defaults.object(forKey: "Timmer") != nil){
            _currentTimeInSeconds = defaults.object(forKey: "Timmer") as! Int
            print(_currentTimeInSeconds)
        }
 }

Happy Coding.

A: - (void)viewDidLoad {

    timeSec=[[NSString stringWithFormat:@"%ld",(long)[[NSUserDefaults standardUserDefaults]integerForKey:@"timeSec"]] intValue];
    timeMin=[[NSString stringWithFormat:@"%ld",(long)[[NSUserDefaults standardUserDefaults]integerForKey:@"timeMin"]] intValue];
    [self StartTimer];
}
-(void) StartTimer
{
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    self.lbl_timer.text=@"00:00";

}
- (void)timerTick:(NSTimer *)timer
{
    timeSec++;
    if (timeSec == 60)
    {

        timeSec = 0;
        timeMin++;
    }
    self.lbl_timer.text= [NSString stringWithFormat:@"%02d:%02d", timeMin, timeSec];;
}

when you back to the screen that time add this code.like back button or close button action
[timer invalidate];
[[NSUserDefaults standardUserDefaults]setInteger:timeSec forKey:@"timeSec"];
[[NSUserDefaults standardUserDefaults]setInteger:timeMin forKey:@"timeMin"];


text: Q: The maps $\delta: V \to B \otimes V$ and $\delta': V \otimes V^* \to B$. Let $B$ be a coalgebra and $V$ a vector space. Suppose that we have a coaction $\delta: V \to B \otimes V$. Is the map $\delta$ equivalent to a map $\delta': V \otimes V^* \to B$? Thank you very much.


text:
Q: java: UTF-32 to UTF-16 convertor I'm trying to get the java escape code.
Example: 1F612 ==> \ud83d\ude12
I tried:
String toConvert = "\ud83d\ude12";
String result = "";
for(int x=0;x<toConvert.length();x++){
    int codePoint = Character.codePointAt(toConvert, x);
    String hexStr = Integer.toHexString(codePoint);
    hexStr = formatUTF(hexStr);
    result += hexStr;
}
System.out.println(result);

formatUTF function:
public static String formatUTF(String hex){
    String text = hex;
    for(int x = 0; x<4-hex.length();x++)
        text = "0"+text;
    return "\\u"+text;
}

but the output:
run:
\u1f612\ude12

Note: 1F612 Hex = 128530 Integer
please help.

A: Maybe this clarifies all.
    for (int i = 0; i < toConvert.length(); ) {
        int codePoint = Character.codePointAt(toConvert, i);
        i += Character.charCount(codePoint);
        System.out.printf("[%d] cp: %x%n", i, codePoint);
    }
    for (int i = 0; i < toConvert.length(); ++i) {
        char ch = toConvert.charAt(i);
        System.out.printf("[%d] c: %x%n", i, (int)ch);
    }

It yields one single code point of two 16 bit chars.
    [2] cp: 1f612
    [0] c: d83d
    [1] c: de12

Exactly as the UTF-16 standard says.


text:
Q: How to echo output as it is generated How do I echo something for every iteration of the following loop:
<?
    for($i=0;$i<5;$i++) {
          // some (slow) logic
          echo $i;
    }
?>

I would like to see the value of $i output as it runs, however this outputs nothing and then 0 1 2 3 4 after the script is executed.

A: Try this one.  The key here is knowing what output_buffering value(default=4096) was set for your server.
ob_start();
$buffer = str_repeat(" ", 4096)."\r\n\r\n";

for ($i=0; $i<25; $i++) {
      echo $buffer.$i;
        ob_flush();
        flush();
          sleep(1);
}

ob_end_flush();

http://php.net/manual/en/outcontrol.configuration.php

A: So build a string, then echo the string:
$str = '';
for($i = 0; $i < 5; $i++) {
   $str .= $i;
}
echo $str;

Note that this, in practice, changes nothing. Such a tiny loop will execute almost instantly and display almost instantly. If you're doing this in a browser context, you'll likely get all the digits coming across in a single network packet and the browser rendering/displaying them at once as well.


text:
Q: Redirect customer on same page instead of customer Dashboard I am using hide price extension, After login redirect customer on same page.

A: Please follow this steps.

*

*Log in to Admin Panel.

*Go to Stores > Configuration

*Under Customers, select Customer Configuration

*Click the Login Options

*Set "Redirect Customer to Account Dashboard after Logging in" to No.

*Save configuration.

So, it will work as you want.
Happy Coding.

A: if you are doing this in controller do something like that
use Magento\Framework\Controller\ResultFactory;

class Actionname name extends \Magento\Framework\App\Action\Action
{
    public function execute()
    {
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);

        // Your code

        $resultRedirect->setUrl($this->_redirect->getRefererUrl());
        return $resultRedirect;
    }
}

if you are doing somewhere out of controller do something like that
protected $resultRedirect;

public function __construct(
  \Magento\Framework\Controller\ResultFactory $result
){
   $this->resultRedirect = $result;
}

public function execute()
{
    $resultRedirect = $this->resultRedirect->create(ResultFactory::TYPE_REDIRECT);
    $resultRedirect->setUrl($this->_redirect->getRefererUrl());

    return $resultRedirect;
 }


text:
Q: recursion - data structure course - print all possible series I need to print all possible series that their sum is equal to N;
for example is n == 4 the output should be:
[1, 1, 1, 1]
[1, 1, 2]
[1, 2, 1]
[1, 3]
[2, 1, 1]
[2, 2]
[3, 1]
[4]

My way of thinking to solve this problem was:
print the series that the number i is not in the series
print the series that the number i is in the series, now need to find the sum of N-i.
my code:
#include <stdio.h>
#include <stdlib.h>

void printArr(int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {

        printf(" %d ", arr[i]);
    }
    printf("\n");

}

void printAllHelper(int* a,int size, int sum, int used,int index) {
    if (sum == 0) {
        a -= used;
        printArr(a, used);
    }
    else if (sum < 0 || index == size)
    {
        return;
    }
    else {
        for(int i = 1 ; i <= size ; i ++)
        {
            printAllHelper(a, size, sum, used, index + 1);
            if (i <= sum)
            {
                *a = i;
            }
            printAllHelper(a+1, size, sum -i, used +1, index + 1);

        }

    }

}

void printAll(int num) {
    int* myArray = (int*)malloc(num * sizeof(int));
    printAllHelper(myArray,num,num,0,0);

}

void main() {
    printAll(4);
}

my output:
 3  1
 3  1
 3  1
 3  1
 3  1
 3  1
 3  1
 3  1
 3  1
 4
 1  3
 4
 2  2
 4
 3  1
 4
 4
 1  3
 1  1  2
 1  3
 1  2  1
 1  3
 1  3
 1  3
 4
 1  3
 4
 2  2
 4
 3  1
 4
 4
 2  2
 2  1  1
 2  2
 2  2
 2  2
 2  2
 4
 1  3
 4
 2  2
 4
 3  1
 4
 4
 3  1
 3  1
 3  1
 3  1
 3  1
 4
 1  3
 4
 2  2
 4
 3  1
 4
 4
 4
 4

Please try to explain to me your way of thinking, and how you approach this kind of problem, I want to be the very best like no one ever was :(.....

A: Your reasoning is not quite correct, but your code is almost right. The loop in your else part should be
    for(int i = 1 ; i <= sum ; i ++)  {
        *a = i;
        printAllHelper(a+1, size, sum-i, used+1, index+1);
    }

With this, I get the output
 1  1  1  1
 1  1  2
 1  2  1
 1  3
 2  1  1
 2  2
 3  1
 4

The idea is basically: "The numbers sum to sum if the first number i is any number from 1 to sum and the rest of the numbers sum to sum - i."
Also, note that your code shows some room for improvement, e.g. the used and index variables seem a bit redundant. And with not adding numbers larger than sum or smaller than 1, the check whether sum < 0 || index == size is not necessary, either. Thus you also do not need the size parameter. Your printAllHelper could be simplified to something like this:
void printAllHelper(int* a, int sum, int index) {
    if (sum == 0) {
        printArr(a, index);
    } else {
        for(int i = 1 ; i <= sum ; i++)  {
            a[index] = i;
            printAllHelper(a, sum-i, index+1);
        }
    }
}

(Note: C is not my native language, if you see more things to improve, please comment.)


text:
Q: ¿Cómo funciona la sentencia raiserror en SQL? He estado buscando información acerca de la palabra reservada "raiserror" en SQL, sin mucho éxito.
¿Alguien podría explicarme cómo funciona? Sobre todo tengo duda en los parámetros que deben utilizarse dentro de ésta sentencia.
Ojalá puedan ayudarme.

A: RAISERROR es una palabra reservada en SQL SERVER como lo son el resto de tipos definidos y métodos, para garantizar la gramática del lenguaje Transact-SQL que utiliza SQL SERVER.
El método RAISERROR genera un mensaje de error. Se puede emplear con un mensaje del catálogo 'sys.messages' o puedes generar un mensaje personalizado. El mensaje se devuelve como un mensaje de error de servidor a la aplicación que realiza la llamada o a un bloque CATCH.
A partir de SQL SERVER 2012 se recomienza el uso de THROW
El uso más común es el siguiente.
Ejemplo de uso
-- Mensaje simple

RAISERROR (
           N'This is a message.', -- Mensaje de ejemplo
           10, -- Severity,
           1   -- State
);
-- DEVUELVE: This is a message.
GO

-- Mensaje con parámetros

RAISERROR (N'This is message %s %d.', -- Mensaje de ejemplo
           10, -- Severity,
           1, -- State,
           N'number', -- Primer argumento
           5          -- Segundo argumento
           --,N...    -- Más argumentos
);
-- DEVUELVE: This is message number 5.
GO

Dentro de TRY ... CATCH
BEGIN TRY
    -- RAISERROR con 'severity' 11-19 para causar la ejecución de bloque CATCH
    RAISERROR ('Error raised in TRY block.',
               16, -- Severity.
               1 -- State.
               );
END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- RAISE ERROR en bloque catch para forzar la devolución de error personalizado
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;

Notas importantes

*

*Las funciones del sistema ERROR_LINE, ERROR_MESSAGE, ERROR_NUMBER,
  ERROR_PROCEDURE, ERROR_SEVERITY, ERROR_STATE y @@ERROR informan de los
  valores especificados por RAISERROR. Cuando se ejecuta RAISERROR con
  un nivel de gravedad 11 o superior en un bloque TRY, transfiere el
  control al bloque CATCH asociado. El error se devuelve al autor de la
  llamada si RAISERROR se ejecuta

*RAISERROR se puede utilizar como alternativa a PRINT para devolver
  mensajes a las aplicaciones que realizan llamadas. La sustitución de
  caracteres que RAISERROR admite es similar a la de la función printf
  de la biblioteca de C estándar, mientras que no sucede lo mismo con la
  instrucción PRINT de Transact-SQL. La instrucción PRINT no se ve
  afectada por los bloques TRY, mientras que, si RAISERROR se ejecuta
  con un nivel de gravedad de 11 a 19 en un bloque TRY, transfiere el
  control al bloque CATCH asociado. Especifique un nivel de gravedad 10
  o inferior para que RAISERROR devuelva un mensaje desde un bloque TRY
  sin invocar el bloque CATCH.

*El argumento 'State' puede contener valores entre 0 - 255 y se emplea
  para generar marcas que ayuden a identificar el origen del error que
  se desea generar.


text:
Q: iPhone: Safari doesn't work well with JavaScript turned off Why does my iPhone require JavaScript to be turned on for Safari to work well, while my other iPhone does not require the same?
I have the following two iPhones, both running iOS 11.4.1 (current as of this writing):

*

*An iPhone 8 Plus, where Safari doesn't work with JavaScript turned-off.

*An iPhone 6 Plus, where Safari works well with JavaScript turned-off.


text:
Q: column names in 2nd row of csv file I have a csv file with a blank row above the column names.
Is it possible to correct for this in R?
Right now, I open the csv and remove the blank row before running the R code. But I want to avoid this work if I can.
What is the correct/best way to remove the blank row and then label the columns.
I have tried:
 df <- read.csv("SourceFile/filename.csv", header= TRUE, row.names = 2)

but I get this error:
Error in read.table(file = file, header = header, sep = sep, quote = quote,  :
  more columns than column names

A: In the readr package, the read_csv function has a skip argument. https://readr.tidyverse.org/reference/read_delim.html
There is also a skip_empty_rows argument if you want to be more aggressive.

A: For your case, try:
read.csv(...,skip=1)

Hope this is helpful!


text:
Q: не могу подобрать коэффициенты для Линейного конгруэнтного метода Xₙ₊₁ = (a * Xₙ + c) mod N
необходимо параметры a и c подобрать с помощью теоремы 1 так, чтобы период последовательности был максимальным T = N. Сама теорема:
Линейная конгруэнтная последовательность, определенная числами N, a, c и x0, имеет период T = N тогда и только тогда, когда:

*

*числа c и N взаимно простые;

*b = a − 1 кратно p для каждого простого p, являющегося делителем N;

*b кратно 4, если N кратно 4.
Подбираю:N=125480,a=62741,c=13 всем условиям удовлетворяет: у N простые делители 5 и 3137, b=62740 делится на оба. N и с взаимно простые 100%, b и N кратно 4. Но не работает. Начальный X(0) не совпадает с X(N+1). подскажите что не так делаю?

A: Рассмотрим цикл из двух чисел. Нулевое - 1, следующее - 2, потом опять 1, опять 2...
Ваше N+1-е число - третье - равно 2 и не равно нулевому. Значит, последовательность 1 2 1 2 ... не циклична с периодом 2? Так?
Пояснять, где ошибка?
Какое расстояние между N+1-м и нулевым числами? Неужели N?
Так что сравнивайте все же X(0) и X(N), так оно логичнее...
long long X(long long x) { return (62741*x + 13)%125480; }
int main()
{
    long long x = 100;
    for(int i = 0; i < 125480; ++i) x = X(x);
    cout << x;
}

Посмотрите, что даст этот код, тут: https://ideone.com/27FA63


text:
Q: Prime Number Solutions Let p, q, and r be prime numbers such that $$2pqr + p + q + r = 2020$$ Find $$ pq +qr+rp $$
I believe I got the correct answer of $p,q,r$ being $2, 17, 29$ which results in an answer of $585$. I solved it because I knew one of the prime numbers had to be $2$ as $2pqr$ is always even and $p + q + r$ will be odd without $2$ as $2$ is the only even prime where the sum must be even as $2020$ is even. Then setting $p=2$ I was able to see $17$ and $29$ would work. As this was during a math competition I did not use rigorous techniques as I needed to do it quickly.
What could be a fast rigorous way to do this question? Any help would be greatly appreciated, thanks.

A: HINT.-A way could be, using the identity $(p+q)^2-(p-q)^2=4pq$, to go from $4pq+(p+q)=2018$, to   $$(S+D+\dfrac12)(S-D+\dfrac12)=2018$$ where $S=p+q$ and $D=p-q$  so one has
$$(2S+2D+1)(2S-2D+1)=8073=3^3\cdot13\cdot23$$ attention enough gives
$$2S+2D+1=3^2\cdot13\Rightarrow S+D=58\\2S-2D+1=3\cdot23\Rightarrow S-D=34$$ which gives
$p+q$ and $p-q$.

A: After you render, let us say, $r=2$, you have
$4pq+p+q=2018$
If we multiply by $4$ and add $1$, the left side factors:
$16pq+4p+4q+1=(4p+1)(4q+1)=8073$
Assuming $p\ge q$ we must have $4q+1\le\sqrt{8073}<90$ so the only choices for $q$ are $2,3,5,7,11,13,17,19$. Since $8073=3^3×13×23$ the available $4q+1$ factors $<90$ are as follows.  Red numbers fail to be prime values for $p,q$ and are no solutions.  Blue numbers are good solutions.
$4q+1=3^2=9,q=2,4p+1=897,\color{red}{p=224}$
$4q+1=13,q=3,4p+1=621,\color{red}{p=155}$
$\color{blue}{4q+1=69,q=17,4p+1=117,p=29}$


text:
Q: DAX measure to count duplicates? I'm looking for some guidance on how to structure a DAX measure that will count whether a row is a duplicate.
To be counted as a duplicate, the combination of the two columns named: Latitude & Longitude need to be identical. The customers are distinct here.
How would I create a DAX measure called occurrence in Power BI to capture that?

Customer
Latitude
Longitude
Occurance

C1
25.2318994
89.0194663
3

C2
25.2318994
89.0194663
3

C3
22.8698924
89.0379756
2

C4
25.2318994
89.0194663
3

C5
22.8698924
89.0379756
2

C6
23.2740535
88.0194665
1

A: Maybe with ALLEXCEPT:
Occurrence = CALCULATE(COUNTROWS(Table), ALLEXCEPT(Table, Table[Lat], Table[Lon]))

A: You can try this below measure-
Occurrence =

var curent_row_lat = min(your_table_name_5[Latitude])
var curent_row_lon = min(your_table_name_5[Longitude])

RETURN
COUNTROWS(
    FILTER(
        ALL(your_table_name_5),
        your_table_name_5[Latitude] = curent_row_lat
            && your_table_name_5[Longitude] = curent_row_lon
    )
)

Output-

A: Occurence =
    RANKX(
        FILTER(
                'Table',
                'Table'[Latitude]=EARLIER('Table'[Latitude]) &&  'Table'[Longitude]=EARLIER('Table'[Longitude])
                ),
        'Table'[Customer], , DESC
        )


text:
Q: Multiline strings in HAML template helpers I'd like to be able to pass a multiline string to a haml helper.
I have a function format_code, that accepts a string and a set of line numbers to highlight.
The purpose of this function is to convert raw source into formatted HTML with highlighted lines, line numbers, newlines converted to brs, etc.
If I call it like this:
%p Some HAMl

=format_code("def something
  a = b
  b = c
end", :highlight_line => 2)

%p Some more HAML

The reason for doing this is to embed a code example into a HAML document.
HAML complains about nesting in plain text. The nesting takes place within a string so I had assumed this would be OK. The same call works fine in irb.
I would use a helper, but I want to be able to pass a parameter hash. Any thoughts?

A: I'm supposing you want to hardcode a code example into a HAML template, so you really want something to which my immediate response is: "you don't want this". In that case, I would probably choose:
:ruby
  code = <<-CODE
    def something
      a = b
      b = c
    end
  CODE

%p Some HAMl

=format_code(code, :highlight_line => 2)

%p Some more HAML

A: I tried different variants, and I think the easiest one is the following (code taken directly from yours):
%p Some HAMl

=format_code("def something\t  a = b\t  b = c\tend", :highlight_line => 2)

%p Some more HAML

This should at least the problem with multiple lines ...


text:
Q: Updating a val in scala by reassigning I am trying to update the value stored in a val in scala. I know i can't just directly do this like this: val x = 2; x = 1. This is not what I am doing, as I know you cannot reassign to a val. This is what I am trying to do:
    val fp = List((1,2));
    val fp = fp ::: List((1,3)); //hoping that x is List((1,2),(1,3))

But I get an message saying:
 error: recursive value fp needs type

Also note, that I am restricted to using immutable data structures and vals only.
Any guidance would be appreciated

A: You can't reassign val in Scala. You should either use var:
var fp = List((1,2))
fp = fp ::: List((1,3))

Or use two vals:
val fp = List((1,2))
val fp2 = fp ::: List((1,3))

Usually you should try to avoid using vars, if you can. It makes your programs cleaner, and this way is surely more functional. So, I would prefer second option with two vals.
By the way, note, that you don't need to use semicolons. In fact, their usage in Scala is kind of discouraged.

A: In Scala, we encourage you to not reassign, as it creates undesirable side effects throughout your code, and makes it harder to reason about.
You need to get in the habit of throwing away variables and their mutations and starting to consider bindings of expressions. Var is considered bad form in Scala. As is reassignment. The following does exactly what you want, without any of the unwanted side effects vars and mutation would create:
val x = 2; val y = 1

If you needed to "mutate" x, then you could do something like the following:
val x = 2
val y = x + 2 // x = 2, y = 4

So that what you wanted from th fp would look like this:
val fp = List((1,2));
val fp1 = fp ::: List((1,3));


text:
Q: Netbook running ubuntu 11.10 screen backlight never comes back after it dims My netbook running 11.10 ubuntu goes to sleep after 10 minutes of inactivity as per settings.  After the screens dims, I cannot get the backlight to come back on.  I can see the faint text of the screen. Any clues?
Thanks.

A: There is already a bug report on Launchpad for your problem and I think that it should be solved soon; if you can't wait, there are some tricks suggested in the comments of that bug.
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/872652


text:
Q: CAEmitterLayer emit continuously in a line I am creating a very simple particle system with CoreAnimation.
This is my cell:
UIImage *image = [UIImage imageNamed:@"spark"];
CAEmitterCell *cell = [CAEmitterCell emitterCell];
[cell setContents:(id)image.CGImage];
[cell setBirthRate:250.f];
[cell setScale:.25f];
[cell setColor:[UIColor colorWithRed:1.0 green:0.2 blue:0.1 alpha:0.5].CGColor];
[cell setLifetime:5.0f];

and layer:
CAEmitterLayer *emitterLayer = [CAEmitterLayer layer];
[emitterLayer setEmitterCells:@[cell]];
[emitterLayer setFrame:bounds];
[emitterLayer setRenderMode:kCAEmitterLayerAdditive];
[self.view.layer addSublayer:emitterLayer];

Now, I move the emitterLayer's position to wherever I'm touching:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    self.emitterLayer.emitterPosition = [[touches anyObject] locationInView:self.view];
}

However, the problem is, it doesn't emit the particles continuously. But rather, at regular intervals(dotted as oppose to a line):

I thought perhaps it's because I'm not animating it. So I tried to add a simple animation to move the emitter from top left to bottom right of the screen just to see if that works:
CGPoint startPos = CGPointZero;
CGPoint endPos = CGPointMake(bounds.size.width, bounds.size.height);

CABasicAnimation* ba = [CABasicAnimation animationWithKeyPath:@"emitterPosition"];
ba.fromValue = [NSValue valueWithCGPoint:startPos];
ba.toValue = [NSValue valueWithCGPoint:endPos];
ba.duration = .5f;
[emitterLayer addAnimation:ba forKey:nil];

What I expected is a line be be formed with particles emitted continuously. However, what I see particles being emitted at intervals, like this:
Is it possible to have the emitterLayer follow your touch up and continuously emit these particles like a drawing and not be dotted?
Thanks

A: I'd suggest removing the animation and to create the line effect via the CAEmitterCell's velocity and emissionLongitude properties:
UIImage *image = [UIImage imageNamed:@"spark"];
CAEmitterCell *cell = [CAEmitterCell emitterCell];
[cell setContents:(id)image.CGImage];
[cell setBirthRate:250.f];
[cell setScale:.25f];
[cell setColor:[UIColor colorWithRed:1.0 green:0.2 blue:0.1 alpha:0.5].CGColor];
[cell setLifetime:5.0f];
[cell setEmissionLongitude:M_PI_4]; //The emission angle
[cell setVelocity:500]; //adjust as needed, together with BirthRate

CAEmitterLayer *emitterLayer = [CAEmitterLayer layer];
[emitterLayer setEmitterCells:@[cell]];
[emitterLayer setFrame:bounds];
[emitterLayer setRenderMode:kCAEmitterLayerAdditive];
[self.view.layer addSublayer:emitterLayer];

A: That looks awfully like the pattern you'd see using an ease-in ease-out animation curve, which I think is the default for CAAnimations. The points are closer together at either end, suggesting it is slower at the beginning and end.
Change the timing function of the animation to linear and you should see the effect you want.
To get a continuous line of emitters the only thing I could get to work was to slow the animation down, which doesn't really give the right effect. It looks like moving the emitter position skips a few renders, I'm not sure why.
You also need to play with the scaling a bit and probably use a CAShapeLayer to draw the actual line you're after.
In fact, a better solution is probably to use a smaller emitter layer which you move along at the end of the line, with a CAShapeLayer which you animate the strokeEnd of to leave the drawing in there.

A: It seems to me like your birthRate is set way too low. Try changing it from 250.f to something like 1500.f and post the results.

A: The effect you are looking to achieve (I saw a link in a comment) is probably best achieved without a particle system. What you usually use for this effect depends on individual approach, but I've had success with both.
One, is to create a render buffer: You draw directly onto this buffer with a colour at maximum value. This could be a UIView for instance. At a timed interval, you decrease every pixel value in this view by a percentage (say 0.05%). New pixels added start bright and fade over time this way, so you have no gaps between points. This is CPU intensive!
The other is to create a 'trianglestrip': you will need to go into a lower level graphics API for this such as OpenGL. The idea is that you create a section of triangles (or quads) that form a 'ribbon' under your finger. Each new section that is added begins fading to 0% alpha and is then removed. There is an implementation of this technique in cocos2d which is called CCMotionStreak that is perfect for this. The benefit is that you supply a texture (as you would a particle system) so it keeps designers happy


text:
Q: SUPEE 7405- ISSUES Found for 1.7.0.2 Version (Solutions Inside) Magento version: 1.7.0.2
PHP version: 5.3.5 (less than 5.4 have issues)
Issues after installing patch: and SOLUTION!
1. ORDER page is BLANK
Solution to blank Order page
app/code/core/Mage/Adminhtml/Helper/Sales.php
Search for "$links = [];" change to "$links = array();"
2. Broke images in backend. All product images before the patch are Visible on Front and Back end. But, after Patch install, if you upload a product image you will see it is BROKEN/INVISIBLE on Backend, but VISIBLE on Frontend.
Solution to Broken images
*Go to /lib/Varien/File/Uploader.php
EDIT THE FOLLOWING LINES
Find this line:
chmod($destinationFile, 0640);
Modify to this:
chmod($destinationFile, 0755);
In other words, only permissions issue*
3. SOAP API URL /index.php/api/v2_soap/index/?wsdl=1 (Known issues, reported by someone else.
No solutions yet for SOAP API URL issue... ANYONE GOT IDEAS?

A: I'm facing with the #3 but I think because of third party extension. I have not found the reason yet but below is temporary solution for how to fix it.
Go to file app/code/core/Mage/Core/Model/Config.php and comment lines from 960 to 963.
Before:
foreach ($fileName as $configFile) {
                $configFile = $this->getModuleDir('etc', $modName).DS.$configFile;
                if ($mergeModel->loadFile($configFile)) {

                    $this->_makeEventsLowerCase(Mage_Core_Model_App_Area::AREA_GLOBAL, $mergeModel);
                    $this->_makeEventsLowerCase(Mage_Core_Model_App_Area::AREA_FRONTEND, $mergeModel);
                    $this->_makeEventsLowerCase(Mage_Core_Model_App_Area::AREA_ADMIN, $mergeModel);
                    $this->_makeEventsLowerCase(Mage_Core_Model_App_Area::AREA_ADMINHTML, $mergeModel);

                    $mergeToObject->extend($mergeModel, true);
                }
            }

After:
foreach ($fileName as $configFile) {
                $configFile = $this->getModuleDir('etc', $modName).DS.$configFile;
                if ($mergeModel->loadFile($configFile)) {

                    //$this->_makeEventsLowerCase(Mage_Core_Model_App_Area::AREA_GLOBAL, $mergeModel);
                    //$this->_makeEventsLowerCase(Mage_Core_Model_App_Area::AREA_FRONTEND, $mergeModel);
                    //$this->_makeEventsLowerCase(Mage_Core_Model_App_Area::AREA_ADMIN, $mergeModel);
                    //$this->_makeEventsLowerCase(Mage_Core_Model_App_Area::AREA_ADMINHTML, $mergeModel);

                    $mergeToObject->extend($mergeModel, true);
                }
            }


text:
Q: html 5 video tag preload attribute not working in firefox   <video class="student-video" controls preload="none">
      <source src="video.mp4" type="video/mp4">
  </video>

somehow this works perfectly in chrome but doesn't work in firefox.
Is there anyway for firefox to prevent autoplay?

A: I have heard about this problem, you can try this:

*

*Go to Preferences > Advanced > General

*In Browsing section, unmark the "Use hardware acceleration when available:

*Save it.

Now restart Firefox and check your video.
It may help you, in some cases this is also issue.
You can also try this:
How to play MP4 video in firefox

A: Try to remove the "proload" option from the code and test


text:
Q: Unicode Escape Error in timeit module python I am currently using timeit inbuilt library of python for getting execution time of small snippets of code.
My Code:-
import timeit

print(timeit.timeit(setup='env = "C:\\Users\\MyName"', stmt='a = f"{env} is my username"'))

The above code Upon execution produces Unicode Escape Error.
Error Stack:-
Traceback (most recent call last):
  File "D:/Users/apple/vul.py", line 3, in <module>
    print(timeit.timeit(setup='env = "C:\\Users\\MyName"', stmt='a = f"{env} is my username"'))
  File "C:\Users\apple\AppData\Local\Programs\Python\Python37-32\lib\timeit.py", line 232, in timeit
    return Timer(stmt, setup, timer, globals).timeit(number)
  File "C:\Users\apple\AppData\Local\Programs\Python\Python37-32\lib\timeit.py", line 109, in __init__
    compile(setup, dummy_src_name, "exec")
  File "<timeit-src>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

This error in general is produced when there is an Escape sequence interpretation inside a string (via a single \ followed by a character). But in my case I have already Escaped the backslash inside the string using \\(double backslashes).

A: You have correctly diagnosed the problem: an escape sequence interpretation inside a string.
You have escaped the backslash once. That means that timeit receives in its setup parameter the following string: 'env = "C:\Users\MyName"' with one single \ on every occurence. And when it executes the string, it finds what it sees as an offending Unicode sequence :'\Users'.
It is easy to fix:
print(timeit.timeit(setup=r'env = "C:\\Users\\MyName"', stmt='a = f"{env} is my username"'))


text:
Q: send console output to Visual Studio 2010 I'm using Visual Studio 2010 c++ to develop some custom direct show filters. I'm using ffmpeg for the encoding process and if I run tests as a standard console then any ffmpeg errors are displayed in the console window, as one might expect. However the main application is a windows app which doesnt have a console window. When I get errors from ffmpeg all I can use is a fairly generic error return number and it would be great to see what would have been displayed in the console window.
Is it possible to get the output from ffmpeg of what would go to a console window to display in one of the 'Studio output windows. I've ticked the 'Redirect all output window text to the immediate window' option in Tools->Options->Debugging->General but this doesn't like the correct option and it doesn't work anyway.
Thanks!
Dave

A: You can redirect ffmpeg output using custom output routine:
av_log_set_callback(&FfmpegLog);

void FfmpegLog(void *ptr, int level, const char *fmt, va_list vl)
{
    static char message[8192];
    const char *module = NULL;

    if (ptr)
    {
        AVClass *avc = *(AVClass**) ptr;
        if (avc->item_name)
            module = avc->item_name(ptr);
    }
    vsnprintf_s(message, sizeof message, sizeof message, fmt, vl);
    std::cout << "[ffmpeg][" << (module ? module : "") << "][" << level << "] : " << message;
}


text:
Q: sql script, if and go statements I need to surround the following sql script with an if statment that checks the existence of one table. There's a lot more fields to the statement but the snippet below should be enough to get the idea.
If I surround this whole batch with an if statement it doesn't like that i have GOs between if statments. If i take out the GOs it complains about TMP_FIELD being an invalid column.
What are some ways to do this the right way? All i'm doing is taking a bunch of fields and changing from varchar to datetime. This is part of a setup.exe file so I just need it to run once and not for future upgrades. The way I determine that is if a certain table exists then don't run the script.
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'MY_TABLE') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
  ALTER TABLE MY_TABLE ADD TMP_FIELD datetime
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'MY_TABLE') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
  UPDATE MY_TABLE SET TMP_FIELD = modifiedDate
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'MY_TABLE') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
  ALTER TABLE MY_TABLE DROP COLUMN modifiedDate
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'MY_TABLE') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
  ALTER TABLE MY_TABLE ADD modifiedDate datetime
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'MY_TABLE') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
  UPDATE MY_TABLE SET modifiedDate = TMP_FIELD
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'MY_TABLE') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
  ALTER TABLE MY_TABLE DROP COLUMN TMP_FIELD
GO

A: You don't really need to do all that gymnastic for changing the type of a column, do you?
create table MY_TABLE (
    modifiedDate varchar(20)
)
go

insert MY_TABLE (modifiedDate) values ('2012-10-20 17:50:41')
go

select * from MY_TABLE
go

alter table MY_TABLE alter column modifiedDate datetime
go

select * from MY_TABLE
go

drop table MY_TABLE
go

So, I would write your statement like this:
if exists (select table_name from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'MY_TABLE')
begin
  alter table MY_TABLE alter column modifiedDate datetime
end

A: The GOs mark the end of a batch of TSQL statements. You can't mix DDL (data definition language) statements like ALTER TABLE with DML (data manipulation language) statements like UPDATE TABLE in the same batch.
Each batch is compiled on it's own. So when the ALTER TABLE and UPDATE TABLE statements are in the same batch, SQL Server can't compile the update statement because the column modifiedData hasn't actually been created yet.

A: If you want to get around 'Invalid column ..' errors, one option is to use dynamic SQL.
e.g. :
create table dbo.t1 (id int primary key, cola varchar(20))
go

insert dbo.t1 values (1, 'one')
insert dbo.t1 values (2, 'two')
go

if not exists(select  * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 't1' and COLUMN_NAME = 'colb')
BEGIN
    -- add new column 'colb', and set its value initially to existing values in 'cola'
    ALTER TABLE dbo.t1 ADD colb varchar(20)

    DECLARE @v NVARCHAR(500)
    SET @v = N'UPDATE dbo.t1 SET colb = cola'
    EXEC (@v) -- use dynamic SQL, otherwise will get Invalid column name colb error.
END
GO

Note that dynamic SQL should be considered a last resort. David Brabant's answer seems to be the way to go for your original problem.


text:
Q: Hour/minute adds one hour from datetime with lubridate I would like to extract the hour/minute/second from a datetime. Example dataframe:
df <- structure(list(Study_date_time_PACS = structure(c(1515146548, 1515146548, 1514970658, 1514970658, 1515151732, 1515151732, 1517476589, 1517476589, 1543848246, 1543848246),
                                                class = c("POSIXct", "POSIXt"),
                                                tzone = "UTC")),
          .Names = "Study_date_time",
          row.names = c(NA, -10L),
          class = c("tbl_df", "tbl", "data.frame"))
print(df)

# A tibble: 10 x 1
   Study_date_time
   <dttm>
 1 2018-01-05 10:02:28
 2 2018-01-05 10:02:28
 3 2018-01-03 09:10:58
 4 2018-01-03 09:10:58
 5 2018-01-05 11:28:52
 6 2018-01-05 11:28:52
 7 2018-02-01 09:16:29
 8 2018-02-01 09:16:29
 9 2018-12-03 14:44:06
10 2018-12-03 14:44:06

So I run this code but it adds one hour to the "hour"? How can I fix this. I assume it must be something with summertime...
library(lubridate)
df %>%
  mutate(hour_min = hms::as.hms(Study_date_time))

# A tibble: 10 x 2
   Study_date_time     hour_min
   <dttm>              <time>
 1 2018-01-05 10:02:28 11:02
 2 2018-01-05 10:02:28 11:02
 3 2018-01-03 09:10:58 10:10
 4 2018-01-03 09:10:58 10:10
 5 2018-01-05 11:28:52 12:28
 6 2018-01-05 11:28:52 12:28
 7 2018-02-01 09:16:29 10:16
 8 2018-02-01 09:16:29 10:16
 9 2018-12-03 14:44:06 15:44
10 2018-12-03 14:44:06 15:44

A: Probaby due to the timezone-element that gets stripped... Let me guess: You live in a UTC+0100 - region of the planet?
You can use the force_tz() function from the lubridate-package.. but be careful!! Timezones are always a b#tch to work with, so handle with care!
df %>% mutate(hour_min = hms::as.hms( force_tz( Study_date_time ) ) )

# # A tibble: 10 x 2
#   Study_date_time     hour_min
#   <dttm>              <time>
# 1 2018-01-05 10:02:28 10:02
# 2 2018-01-05 10:02:28 10:02
# 3 2018-01-03 09:10:58 09:10
# 4 2018-01-03 09:10:58 09:10
# 5 2018-01-05 11:28:52 11:28
# 6 2018-01-05 11:28:52 11:28
# 7 2018-02-01 09:16:29 09:16
# 8 2018-02-01 09:16:29 09:16
# 9 2018-12-03 14:44:06 14:44
# 10 2018-12-03 14:44:06 14:44

A: I agree that this likely a tz issue (perhaps you can just do hms::as.hms(Study_date_time, tz = 'UTC')) and it'll disappear), however I think you'd also do good without any package, e.g.:
df %>%
  mutate(hour_min = format(Study_date_time, "%H:%M"))


text:
Q: Threejs loading font using fontloader throws and error when using React I'm using the ThreeJS library together with React.
I've installed ThreeJS using npm.
Adding images works fine - I'm importing an image in react like this:
import stockImage from './../../images/download.jpg';

and using it like this works great:
this.addCube(stockImage, { x:2, y:2, z:2 } );

(...)

addCube(imageUrl, aPosition) {
        //Load image as material:
        var anImageMaterial = new THREE.MeshBasicMaterial({
            map : this.textureLoader.load(imageUrl)
        });
        //Make box geometry:
        var box = new THREE.BoxGeometry( 1, 1, 1 );
        //Create mesh:
        var cube = new THREE.Mesh( box, anImageMaterial );
        //Add to scene:
        this.scene.add( cube );
        return cube;
    }

When trying to add text to the canvas using this tutorial.
I'm trying to import the font in react like this:
import helveticaRegular from './../../fonts/helvetiker_regular.typeface.json';

Printing it like this looks good, so it doesn't seem to be a problem with react:
console.log(helveticaRegular);

However using the font like this throws an error:
var loader = new THREE.FontLoader();

loader.load( helveticaRegular, function ( font ) {
        var geometry2 = new THREE.TextGeometry( 'Hello three.js!', {
            font: font,
            size: 80,
            height: 5,
            curveSegments: 12,
            bevelEnabled: true,
            bevelThickness: 10,
            bevelSize: 8,
            bevelSegments: 5
        } );
        this.scene.add(geometry2);
    } );

The error is the following:

Please ignore C:/xammp/... as I'm not using xammp, but the folder naming was from when I used xammp.
Loading fonts like this using xammp, using a regular url does not produce the same error.
I don't know if the problem is due to urls or react or the FileLoader.load function in ThreeJS.

A: FontLoader requires a URL as parameter by signature:
FontLoader.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : null

What you are passing in is instead the imported file, thus FontLoader.load does not like it as under the hood there will be an xhr call with an url parameter.
May be the correct approach is to skip load phase and go with FontLoader.parse(myImportedFont)
FontLoader.parse signature
.parse ( json : Object ) : Font
json — The JSON structure to parse.

Parse a JSON structure and return a Font.


text:
Q: Use C++ to compare changes in XML I have two large XML files which have the same schema but different entries. Each day the entries change and I want to be able to find:

*

*Entry appears in file A but not file B

*Entry appears in file B but not file A

*Entry appears in both file A and B

I'm new to programming and I'm having a hard time understanding an efficient way to approach this. Is using (trillions of) loops the key to this?
Example shortened XML file:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<site_entries>
<entry>
<id><![CDATA[946757316]]></id>
<url><![CDATA[http://www.site.co.uk/cgi-bin/tr.cgi?tid=752276]]></url>
<content><![CDATA[Specialized Dolce Sport 27 Speed]]></content>
<title><![CDATA[Bike]]></title>
<price><![CDATA[£600]]></price>
<date><![CDATA[01-AUG-13]]></date>
<display_reference><![CDATA[214683-50142933_370647]]></display_reference>
<location><![CDATA[City of London]]></location>
<category><![CDATA[Bike]]></category>
</entry>
<entry>
<id><![CDATA[90007316]]></id>
<url><![CDATA[http://www.site.co.uk/cgi-bin/tr.cgi?tid=70952276]]></url>
<content><![CDATA[Giant Sport Offroad Bike]]></content>
<title><![CDATA[Bike]]></title>
<price><![CDATA[£100]]></price>
<date><![CDATA[11-AUG-15]]></date>
<display_reference><![CDATA[2146433-50142933_370647]]></display_reference>
<location><![CDATA[City of London]]></location>
<category><![CDATA[Bike]]></category>
</entry>
</site_entries>

Edit: I can't rely on the entires being in the right order across the files.

A: Here is an example of how this can work using pugixml.
For the purposes of the test the XML files are stored in std::istringstream objects, that can be replaced by std::ifstream objects to read from files.
#include <set>
#include <string>
#include <sstream>
#include <iostream>
#include <algorithm>

#include "pugixml.hpp"

#define con(m) std::cout << m << '\n'
#define err(m) std::cerr << m << std::endl

std::istringstream iss_a(R"~(<?xml version="1.0" encoding="ISO-8859-1" ?>
<site_entries>
<entry>
<id><![CDATA[1]]></id>
</entry>
<entry>
<id><![CDATA[2]]></id>
</entry>
</site_entries>)~");

std::istringstream iss_b(R"~(<?xml version="1.0" encoding="ISO-8859-1" ?>
<site_entries>
<entry>
<id><![CDATA[2]]></id>
</entry>
<entry>
<id><![CDATA[3]]></id>
</entry>
</site_entries>)~");

using str_set = std::set<std::string>;

int main()
{
    pugi::xml_document doc;

    str_set a;
    doc.load(iss_a); // use doc.load_file() in real code

    // fill set a with just the ids from file a
    for(auto&& node: doc.child("site_entries").children("entry"))
        a.emplace(node.child("id").text().as_string());

    str_set b;
    doc.load(iss_b);

    // fill set b with just the ids from file b
    for(auto&& node: doc.child("site_entries").children("entry"))
        b.emplace(node.child("id").text().as_string());

    // now use the <algorithms> library

    str_set b_from_a;
    std::set_difference(a.begin(), a.end(), b.begin(), b.end()
        , std::inserter(b_from_a, b_from_a.begin()));

    str_set a_from_b;
    std::set_difference(b.begin(), b.end(), a.begin(), a.end()
        , std::inserter(a_from_b, a_from_b.begin()));

    str_set a_and_b;
    std::set_intersection(a.begin(), a.end(), b.begin(), b.end()
        , std::inserter(a_and_b, a_and_b.begin()));

    for(auto&& v: a)
        con("a       : " << v);

    con("");

    for(auto&& v: b)
        con("b       : " << v);

    con("");

    for(auto&& v: b_from_a)
        con("b_from_a: " << v);

    con("");

    for(auto&& v: a_from_b)
        con("a_from_b: " << v);

    con("");

    for(auto&& v: a_and_b)
        con("a_and_b : " << v);

    con("");
}

Output:
a       : 1
a       : 2

b       : 2
b       : 3

b_from_a: 1

a_from_b: 3

a_and_b : 2

References:
std::set_difference
std::set_intersection


text:
Q: Using jQuery to get data attributes Now, bear in mind I'm just trying to ensure that the code works by consuming the ready event here. I just want to make sure that the data I expect is getting pulled by jQuery. I've also tried the load event.
In the end I'd want to use the load or ready event to set the image initially and then of course use the hover event to change that image on hover.
I've tried a lot of the answers here on SO and just can't seem to get this working, so hopefully y'all can help me.
JavaScript:
$(document).ready(function () {
    $("#submenumain-link").ready(function () {
        alert($(this).data()["selectedimage"]);
        alert($(this).data()["hoverimage"]);
    });

    $("#submenumain-link").hover(function () {
        alert($(this).data("selectedimage"));
        alert($(this).data("hoverimage"));
    });
});

HTML:
<li id="submenumain-link"
    data-selectedimage="some-image.png"
    data-hoverimage="some-other-image.png">

But for whatever reason the alert messages just state undefined. Am I missing something here?
EDIT
Note that if I place those same alert statements in the hover, it works as expected. What event could I use to do the initialization?

A: $(this).data('selectedimage');

You don't need the brackets []

A: The issue is your .ready() call.  You should use a load event if you want to wait until something is loaded but in this case it is an li element that will already exist so your code should be:
$(document).ready(function() {
    var test = $("#submenumain-link");
    alert(test.data('selectedimage'));
    alert(test.data('hoverimage'));

    test.hover(function() {});
});

A: The real problem is that ready should not be used in this way. The ready event should only be used with making sure the DOM is ready - http://api.jquery.com/ready/
So technically, inside of document.ready, all of the DOM is ready and should be available for these kinds of things. Inside of document.ready, the value of this refers to the document element, so you need to actually grab the li element. Your code should be something like this:
$(document).ready(function () {
    var li = $("#submenumain-link");
    alert(li.data()["selectedimage"]);  // or li.data("selectedimage")

    li.hover(function () {
        //alert($(this).data("selectedimage"));
        //alert($(this).data("hoverimage"));
    });
});

http://jsfiddle.net/XN2LV/

A: It should be alert($(this).data("selectedimage"));
Look here: HTML5 data-* Attributes.


text:
Q: What does this message mean in Firebug?
Possible Duplicates:
Firebug JS warning to jQuery 1.4.2 "The 'charCode' property of a keyup event should not be used. The value is meaningless." To ignore it?
Firebug: "The 'charCode' property of a keyup event should not be used.  The value is meaningless."

I have this error when I start typing on my textbox:

The 'charCode' property of a keydown event should not be used. The value is meaningless.

What does it mean?
Code:
$(document).ready(function(){

    $('#inputField').bind("blur focus keydown keypress keyup", function(){recount();});
    $('input.submitButton').attr('disabled','disabled');

    $('#tweetForm').submit(function(e){

        tweet();
        e.preventDefault();

    });

});

A: This is caused by assigning jQuery to use a key down/up event. it's a meaningless warning and you can safely ignore it. You can turn off javascript warnings in firebug if you wish.

A: Take a look at here. it explains the problem clearly.

A: In non-IE browsers (before version 9), the event associated with a keydown (or keyup) event has a keyCode property, the same property IE uses for all key events.
only the keypress can return an event with a charCode. And, amusingly, a keypress can also return a keyCode in non-IE browsers, corresponding to the unmodified printable key or a control key.