text:
Q: Is this a legit question? I see an interview question thats goes like this:
Assuming you have an array with numbers 1 to N. Where N is at most 32,000.
This array may have duplicates and you do not know what N is. With, 4KB of
memory available, how would best print all duplicate elements in this array?

If i'm not wrong, printing elements does not cost memory. Unless stored into a buffer and print from it. Otherwise, i think this question is flawed. The question should be asking how best can you store the duplicates with a 4KB memory limit.
[Edit]
I'm trying to ask if this is a valid interview question. And if it is, what is the question trying to achieve?
My thoughts about this interview question would be to find a way to store duplicates efficiently using limited memory storage.
I'm not sure which stack community, this question belongs to. So some moderator please help me.

A: Consider how you find the duplicates. Are you just walking along the list, and the duplicates wave at you?
You might need to remember somehow all the numbers you already passed, and that takes memory.


text:
Q: Why doesn't TextBox1_Click doesn't work while trying to make a click event on a text? Basically I want a textbox to open browser but it doesn't work:
private void TextBox1_Click(object sender, EventArgs e)
{
    webBrowser1.Visible = true;
    button3.Visible = true;
    textBox1.ForeColor = Color.Purple;
}

A: Like the comments are hinting, it's not really clear what you're asking.
WebBrowser is a control element on WinForms which you can make visible, as you're doing correctly.
If however you're trying to open an actual browser, you should open it as so:
System.Diagnostics.Process.Start("IExplore.exe");

redpajama_set_name: RedPajamaStackExchange


text:
Q: Congruence modulo 4 for a generating function leads to perfect squares? Consider the number of integer partitions $p(n)$ of $n$ whose generating function is
$$\sum_{n\geq0}p(n)\,x^n=\prod_{k\geq1}\frac1{1-x^k}.$$
Also, the number of partitions into distinct parts $Q(n)$ of $n$ whose genertaing function is
$$\sum_{n\geq0}Q(n)x^n=\prod_{k\geq1}(1+x^k).$$
Expand the ratio of these two generating functions so that
$$\sum_{n\geq0}a(n)x^n=\prod_{k\geq1}\frac{1+x^k}{1-x^k}.$$

QUESTION. Why is $a(n)\equiv 2\,\, (\text{mod}\, 4)$ iff $n$ is a perfect square, for $n\geq1$?

A: $$\frac{1+x^k}{1-x^k}=(1+x^k)(1+x^k+x^{2k}+\dots)=1+2x^k+2x^{2k}+\dots$$
Multiplying all these together and looking at terms contributing to the coefficient of $x^n$, we see that the term will be contributing something divisible by $4$ unless it comes from multiplying a bunch of $1$s together with $2x^{k\cdot d}$ for $k\mid n$. This means $a(n)\equiv 2d(n)\pmod 4$, where $d(n)$ is the number of divisors of $n$. Since $d(n)$ is odd iff $n$ is a square, we get the result.


text:
Q: Best bugzilla desktop client We've just started to used bugzilla and I found the web interface quite slow and not user-friendly.
I'm wondering if anyone have a suggestion for a client desktop or a browser add-on running under windows.
I found the following page: https://wiki.mozilla.org/Bugzilla:Addons
Which one of these clients (or any other) is the best ?  Any other suggestions ?
I already tried Deskzilla Lite, which seem pretty good. However, there is a lot of field (edit bug) that we don't use (i.e. hardware, os, url, depends on, etc). Is there a desktop client that allow to remove and customize the field used in the bug entry form? On this one, please do not answer I can customize the bugzilla templates, we don't want to use the web interface anyway.

A: Well it depends on your Bugzilla Version. Since I updated to 4.0 I've got no alternative to Deskzilla since MyZilla is not running anymore. LiveProject looks pretty neat but I never tested it, so... Deskzilla lite. :/


text:
Q: Changing accordion so only closes when header is clicked I've got a simple few accordions that are made interactive with vanilla JS. They open perfectly, however once they're open if you click anywhere in the div then they close. I know this is happening because of the following line:
var allPanelElems = accordionElem.querySelectorAll(".checkout-accordion");

However, I'm scratching my head as to how to rephrase the JavaScript so they only close when you click on the accordion header, and not the accordion body too.
Here's the full code:

function initAccordion(accordionElem){

  function handlePanelClick(event){
      showPanel(event.currentTarget);
  }

  function showPanel(panel){
     let expandedPanel = accordionElem.querySelector(".active");
     if (panel === expandedPanel){
         expandedPanel.classList.remove("active");
     } else {
       panel.classList.add("active");
     }

  }
  var allPanelElems = accordionElem.querySelectorAll(".checkout-accordion");
  for (var i = 0, len = allPanelElems.length; i < len; i++){
       allPanelElems[i].addEventListener("click", handlePanelClick);
  }
  showPanel(allPanelElems[0])
}
initAccordion(document.getElementById("checkout-details-container"));
.checkout-details-section {
  height: auto;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

#checkout-details-container {
  height: 90%;
  width: 90%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  margin: 50px 0;
}

.checkout-accordion {
  height: auto;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
  margin: 50px 0;
}

.accordion-header {
  height: 10vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  background-color: #f9f9f9;
  cursor: pointer;
}

.accordion-dropdown {
  height: auto;
  width: 50%;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  margin: 30px 0;
}

.accordion-dropdown label {
  height: 40px;
  width: 100%;
  margin: 10px 0;
  font-size: 24px;
  font-weight: bold;
}

.accordion-dropdown input {
  height: 40px;
  width: 100%;
  margin: 20px 0;
  font-size: 22px;
  color: #999;
  background-color: #f9f9f9;
}

/* Start of checkout details accordion functionality */

#checkout-details-container .accordion-dropdown {
  display: none;
}

#checkout-details-container .active .accordion-dropdown {
  display: flex;
}

Personal Details

      Full name
      <input type="text" name="fullName" value="">
      Enter your email
      <input type="email" name="email" value="">
      Enter your phone number
      <input type="tel" name="phone" value="">

Shipping Address

          House number and street name
          <input type="text" name="firstLine" value="">
          Enter your local area
          <input type="text" name="secondLine" value="">
          Enter your city
          <input type="text" name="city" value="">
          Enter your region
          <input type="text" name="region" value="">
          Enter your postcode
          <input type="text" name="postcode" value="">
          Enter your country
          <input type="text" name="country" value="">

Billing Address

          House number and street name
          <input type="text" name="billingFirst" value="">
          Enter your local area
          <input type="text" name="billingSecond" value="">
          Enter your city
          <input type="text" name="billingCity" value="">
          Enter your region
          <input type="text" name="billingRegion" value="">
          Enter your postcode
          <input type="text" name="billingPostcode" value="">
          Enter your country
          <input type="text" name="billingCountry" value="">

Payment Details

          Enter your card number
          <input type="text" name="cardNumber" value="">
          Enter your card's expiry date
          <input type="date" name="expiryDate" placeholder="DD / YYYY" required pattern="[0-9]{4}-[0-9]{2}" value="">
          Enter your card's CSV
          <input type="text" name="csv" placeholder="123" require pattern="[0-9]{4}" value="">

Weirdly too, it only happens on the second click on the accordion, not the first. There's another weird bug which means if two accordions are open, the first accordion won't close on click until you close the second. If anyone has any idea why that's happening, an answer would be great too.
Thanks, hopefully my questions clear.

A: You could conditionally handle the panel click event by checking if it's coming from the header (as you want). Your JavaScript should be looking somewhat like:

function initAccordion(accordionElem) {
      function handlePanelClick(event) {
        // if the event is coming from the header then show panel
        if (event.path[0].classList[0] === "accordion-header"){
              showPanel(event.currentTarget);
        }
      }

      function showPanel(panel) {
        let expandedPanel = accordionElem.querySelector(".active");
        if (panel === expandedPanel) {
          expandedPanel.classList.remove("active");
        } else {
          panel.classList.add("active");
        }
      }
      var allPanelElems = accordionElem.querySelectorAll(".checkout-accordion");
      for (var i = 0, len = allPanelElems.length; i < len; i++) {
        allPanelElems[i].addEventListener("click", handlePanelClick);
      }
      showPanel(allPanelElems[0]);
    }

    initAccordion(document.getElementById("checkout-details-container"));
.checkout-details-section {
  height: auto;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

#checkout-details-container {
  height: 90%;
  width: 90%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  margin: 50px 0;
}

.checkout-accordion {
  height: auto;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
  margin: 50px 0;
}

.accordion-header {
  height: 10vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  background-color: #f9f9f9;
  cursor: pointer;
}

.accordion-dropdown {
  height: auto;
  width: 50%;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  margin: 30px 0;
}

.accordion-dropdown label {
  height: 40px;
  width: 100%;
  margin: 10px 0;
  font-size: 24px;
  font-weight: bold;
}

.accordion-dropdown input {
  height: 40px;
  width: 100%;
  margin: 20px 0;
  font-size: 22px;
  color: #999;
  background-color: #f9f9f9;
}

/* Start of checkout details accordion functionality */

#checkout-details-container .accordion-dropdown {
  display: none;
}

#checkout-details-container .active .accordion-dropdown {
  display: flex;
}

Personal Details

      Full name
      <input type="text" name="fullName" value="">
      Enter your email
      <input type="email" name="email" value="">
      Enter your phone number
      <input type="tel" name="phone" value="">

Shipping Address

          House number and street name
          <input type="text" name="firstLine" value="">
          Enter your local area
          <input type="text" name="secondLine" value="">
          Enter your city
          <input type="text" name="city" value="">
          Enter your region
          <input type="text" name="region" value="">
          Enter your postcode
          <input type="text" name="postcode" value="">
          Enter your country
          <input type="text" name="country" value="">

Billing Address

          House number and street name
          <input type="text" name="billingFirst" value="">
          Enter your local area
          <input type="text" name="billingSecond" value="">
          Enter your city
          <input type="text" name="billingCity" value="">
          Enter your region
          <input type="text" name="billingRegion" value="">
          Enter your postcode
          <input type="text" name="billingPostcode" value="">
          Enter your country
          <input type="text" name="billingCountry" value="">

Payment Details

          Enter your card number
          <input type="text" name="cardNumber" value="">
          Enter your card's expiry date
          <input type="date" name="expiryDate" placeholder="DD / YYYY" required pattern="[0-9]{4}-[0-9]{2}" value="">
          Enter your card's CSV
          <input type="text" name="csv" placeholder="123" require pattern="[0-9]{4}" value="">


text:
Q: Is $\ x\! \cdot\!\tan(x)\ $ integrable in elementary functions? I'm teaching Calculus and my students asked me to calculate the integral of $\ x\! \cdot\!\tan(x)$.
I spent quite a lot of effort to do this, but I'm now even not sure if the integral could be presented in elementary functions.
Does anybody know how to calculate it, or otherwise prove it is not integrable in elementary functions?

A: Finding an anti-derivative of $x\tan x$ amounts to finding an anti-derivative of $f=\frac{x}{e^x+1}$. Consider the field $K=\mathbb C(x,e^x)$. Note that $K$ is closed under taking derivatives. If $f$ is elementary integrable, then Liouville's Theorem gives elements $u_i\in K$, $\gamma_i\in\mathbb C$, $v\in K$ with
\begin{equation}
\frac{x}{e^x+1}=\sum\gamma_i\frac{u_i'}{u_i}+v'.
\end{equation}
Consider the $u_i$ and $v$ as rational functions in $e^x$ with coeffcients in $\mathbb C(x)$. By the property of the logarithmic derivative we may assume that the $u_i$ are actually distinct irreducible monic polynomials with respect to $e^x$, or elements from $\mathbb C(x)$.
Looking at poles (with respect to the `variable' $e^x$) shows that at most one of the $u_i$ is $e^x+1$, and the other $u_i$'s are in $\mathbb C(x)$. Similarly, we see that $v\in\mathbb C(x)$. So there indeed must be one index $i$ with $u_i=e^x+1$. However, $\frac{x}{e^x+1}-\gamma_i\frac{u_i'}{u_i}=\frac{x}{e^x+1}-\gamma_i\frac{e^x}{e^x+1}$ isn't in $\mathbb C(x)$, a contradiction.
Remark: The argument given here is somewhat sketchy, some routine details need to be filled in, like that $u_i'$ and $u_i$, as polynomials in $e^x$, are relatively prime. A beautiful paper about Liouville's Theorem is Rosenlicht's article Integration in finite terms. My argument somewhat follows Rosenlicht's example of finding an anti-derivative of $f(x)e^{g(x)}$, where $f$ and $g$ are rational functions.

A: Edit (6/14/14): I maintain that Peter Mueller's answer should be accepted, since he has essentially carried out the proof using Liouville's Theorem (mentioned below) to show that the integrand under question cannot be expressed in elementary functions. However, in addition to my previous unsuccessful attack, I thought I would also point to a full argument in the following source:

Bronstein, M. (1998). Symbolic integration tutorial. INRIA Sophia Antipolis ISSAC. Link.

as well as the author's self-cited:

(4) M. Bronstein. Symbolic Integration I – Transcendental Functions. Springer, Heidelberg, 1997. 2nd Ed., 2004.

In particular, see Section 3.3. Here is an excerpt (see the paper for the definition of special):

Some thoughts on this antiderivative:
Attacking $\log(\cos x)$ using integration by parts, we find:
$$\int \log(\cos x) = x\log(\cos x) + \int x \tan x dx$$
So the question has now become: how do we find an antiderivative for log(cos x)?
Next, we observe that
$$\cos x = \frac{1}{2}(e^{ix} + e^{-ix}) = \frac{1}{2}e^{ix}(1 + e^{-2ix})$$
Taking the log of this, we end up with:
$$-\log 2 + ix + \log(1 + e^{-2ix})$$
Recall that we can write
$$\log(1 + y) = \sum_{k = 1}^{\infty} \frac{(-1)^{k+1}y^{k}}{k}$$
We can now apply this with  $y = e^{-2ix}$ as above and integrate term by term.
Putting all these pieces together will give you a (nasty) way to integrate $x\tan x$.
As far as showing it's not integrable in elementary functions, I suspect your best bet would be an appeal to a theorem of Liouville. See, for example, this link.
All that said, perhaps you could ask your students some form of the following: show
$$\int x\tan^{2}x dx = x\tan x - \frac{x^2}{2} + \log(\cos x) + C$$
(You can find this latter, more tractable problem and its solution written out in nice detail here.)

A: $\int x \tan x \,dx=\frac{1}{2} i \text{Li}_2\left(-e^{2 i x}\right)+\frac{i x^2}{2}-x \log\left(1+e^{2 i x}\right)+C $
Where $\text{Li}_2$ is the dilogarithm function

A: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\down}{\downarrow}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
In general, we can consider the integral
$\ds{\int_{0}^{a}x\tan\pars{x}\,\dd x = -a\ln\pars{\cos\pars{a}} + \int_{0}^{a}\ln\pars{\cos\pars{x}}\,\dd x}$
with $\ds{\cos\pars{a} > 0}$:
\begin{align}
\int_{0}^{a}\ln\pars{\cos\pars{x}}\,\dd x&=
-\int_{1}^{\cos\pars{a}}{\ln\pars{x} \over \root{1 - x^{2}}}\,\dd x
=
-\,\half\int_{1}^{\cos^{1/2}\pars{a}}{x^{-1/2}\ln\pars{x^{1/2}} \over \root{1 - x}}\,\dd x
\\[3mm]&=
{1 \over 4}\lim_{\mu \to -1/2}\partiald{}{\mu}\int^{1}_{\cos^{1/2}\pars{a}}x^{\mu}
\pars{1 - x}^{-1/2}\,\dd x
\\[3mm]&=
{1 \over 4}\lim_{\mu \to -1/2}\partiald{}{\mu}\bracks{%
\int_{0}^{1}x^{\mu}\pars{1 - x}^{-1/2}\,\dd x
-
\int_{0}^{\cos^{1/2}\pars{a}}x^{\mu}\pars{1 - x}^{-1/2}\,\dd x}
\\[3mm]&=
{1 \over 4}\lim_{\mu \to -1/2}\partiald{}{\mu}\bracks{%
{\rm B}\pars{\mu + 1,\half} - {\rm B}_{\cos^{1/2}\pars{a}}\pars{\mu + 1,\half}}
\end{align}
where
$\ds{{\rm B}\pars{p,q} = {\Gamma\pars{p}\Gamma\pars{q} \over \Gamma\pars{p + q}}}$ and
$\ds{{\rm B}_{x}\pars{p,q}
 = {x^{p} \over q}\ _{\large 2\atop}\!{\rm F}_{1}\pars{p,1 - q;p + 1,x}}$ are the $\it Beta$  and the $\it\mbox{Incomplete Beta}$ functions, respectively.
$\ds{_{\large 2\atop}\!{\rm F}_{1}}$ is a $\it hypergeometric$ function.

\begin{align}
&\int_{0}^{a}\ln\pars{\cos\pars{x}}\,\dd x
\\[3mm]&=-\,\half\,\pi\ln\pars{2}
-
{1 \over 4}\lim_{\mu \to -1/2}\partiald{}{\mu}\bracks{%
2{\cos^{\pars{\mu + 1}/2}\pars{a}}
\ _{\large 2\atop}\!{\rm F}_{1}\pars{\mu + 1,\half;\mu + 2,\cos^{1/2}\pars{a}}}
\end{align}


text:
Q: page not centered i can load the page and it will be all the way to the left press refresh and it then loads centered! im using chrome!  http://www.soldbybillcox.com/index.html
also on http://www.soldbybillcox.com/listings.html I cant seem to get the page to be centered!
and to top it all off some how removing www. from the url determines if the scroll bar will appear in the iframe

A: Wrap the whole page in a DIV tag, like this:

    /*You page and stuff*/

Note that the '912' can change, just make it the exact same as your page's width.

A: wrap your whole content with a

All the content here...


text:
Q: XML document structures must start and end within the same entity android studio Android Studio XML document structures must start and end within the same entity android studio

A: Looks like you got an error on the activity_main.xml file.
Look for a typo, or any unclosed tag


text:
Q: How to click on element using find_elements_by_class_name() using Selenium and Python I have to following HTML that is on a website I'm trying to scrape:

        Section Title

Newsletter 1

2021 11 8

Newsletter 2

2021 11 3

This is the selenium/python code that I'm using:
driver.get("http://www.testwesbite.org/#/newsarticles")

results = driver.find_elements_by_class_name('test-section-container')
texts = []
for result in results:
    text = result.text
    texts.append(text)
    print(text)

This gives me an output off:
Newsletter 1
2021 11 8
Newsletter 2
2021 11 3

If I use the following code:
first_result = results[0]
first_result.click()

It does click into the first article but a results[1] give me an out of bounds error.
How would I go about click on the second article?

A: As you have used driver.find_elements_by_class_name('test-section-container') all the following texts:

*

*Newsletter 1

*2021 11 8

*Newsletter 2

*2021 11 3

Are within the results[0] element and results[1] desn't exists. Hence you face out of bounds error

Solution
To click on each results[0] and results[1] you can use:
driver.get("http://www.testwesbite.org/#/newsarticles")
results = driver.find_elements(By.CSS_SELECTOR, "div.test-section-container div[style*='nowrap']")
texts = []
for result in results:
    text = result.text
    texts.append(text)
    print(text)

Now you can click the individual items as:
first_result = results[0]
first_result.click()

and
second_result = results[1]
second_result.click()

Note: You have to add the following imports :
from selenium.webdriver.common.by import By


text:
Q: Encourage users to edit first posts, with a badge We should be encouraging the First Posts reviewers to improve the  posts they are reviewing. After all, that's the point of review. There are currently several options available to First Posts reviewers: commenting, voting, skipping, flagging, and editing.
As it stands, this queue drains fast, which is good. However, there is an unintended side effect: those whose reviews require time (e.g. by editing) will unintentionally be 'punished', as the queue will be drained by the time they are done. Ergo, users who do better reviews earn review badges slower. As a result, users are unintentionally encouraged to select No action needed, or other quick actions like downvoting.
I propose a badge to help alleviate this problem, and encourage users to spend more time on reviews. The text of the badge reads:

Suggested edits to or edited First Posts 150 times, 95% of which were approved.

I think this should be a silver badge. While the bar is high, this is a feasible badge for many new users, as there are plenty of first posts. This encourages users to, y'know, actually take time to improve First Posts. As has been said before, the first posts queue is rather ineffective. Theoretically, this should increase its effectiveness, as people will be encouraged to spend more time on each review..
Thoughts? (I haven't thought of a name yet, but that's just me being lazy.)

Raised concerns:
Won't users just make small edits to inflate their edit count? Most users' edits will go into the Suggested Edits review queue, where they will be rejected if they are too minor. Repeated offenses lead to an edit ban, which would ultimately discourage minor edits.
This couples with the idea that, if there is anything else wrong with a post, edits which just remove signatures should be rejected as too minor. Additionally, edits which just capitalize a word or three should also be rejected iff there is anything else to be improved.
Aren't there enough edit/review badges as is? This precludes the option that an additional badge could actually be helpful. Each suggestion should be judged based off its own merits. If this badge would be helpful, it's irrelevant how many badges currently exist. Therefore, I don't think this is a useful point to make.

A: There's already enough incentive in the review queues that people are watching them with a goal of getting a shiny badge. That's perfectly human, but that's not what the queues are meant for.
You say some of the review queues drain fast, and that's a problem because people watching these queues are "punished" when they take a while to act. That, in my opinion, is completely the wrong way to look at it. The problem is that people aren't punished enough for taking quick actions blindly just to get their badge counter up. Review audits probably help a bit, but what is needed in my opinion is more in that direction rather than more incentives to "get my stats up quickly".
The goal when reviewing should be to make the site a better place. There's a nice side-effect of earning shiny things when you do it right. And people who review in that mindset shouldn't be upset when there's nothing left to review - that's just a sign that things are running smoothly and the community is doing its job. An empty queue is no punishment.
There are eight badges related to editing. That's quite a lot already. We really do not need an influx of suggested edits that come from people just trying to get shiny stuff, or serial minor edits from people going for another milestone towards Copy Editor.
Leave editing to people who actually care about it, please.


text:
Q: Source code for Xiaolin Wu's line algorithm in C? I'm looking for a nice and efficient implementation of Xiaolin Wu's anti-aliased line drawing algorithm in C, does anyone have this code they could share with me?
Thanks

A: Wikipedia has pseudo code.
Google has many examples like this one or this one. And your question reminded me this nice article on antialiasing.
EDIT: It's time to discover Hugo Helias's website if you don't know it already.

A: Wondering if implementation here is correct, because in
ErrorAdj = ((unsigned long) DeltaX << 16) / (unsigned long) DeltaY;
      /* Draw all pixels other than the first and last */
while (--DeltaY) {
         ErrorAccTemp = ErrorAcc;   /* remember current accumulated error */
         ErrorAcc += ErrorAdj;      /* calculate error for next pixel */
         if (ErrorAcc <= ErrorAccTemp) {
            /* The error accumulator turned over, so advance the X coord */
            X0 += XDir;
         }
         Y0++; /* Y-major, so always advance Y */
         /* The IntensityBits most significant bits of ErrorAcc give us the
            intensity weighting for this pixel, and the complement of the
            weighting for the paired pixel */
         Weighting = ErrorAcc >> IntensityShift;
         DrawPixel(pDC,X0, Y0, BaseColor + Weighting);
         DrawPixel(pDC,X0 + XDir, Y0,
               BaseColor + (Weighting ^ WeightingComplementMask));
      }

condition if (ErrorAcc <= ErrorAccTemp) is always false.


text:
Q: CloudKit JS Hello World Example: No Auth Method Found I'm working through Apple's CloudKit Catalog example, and I'm just trying to get authentication to work. I want to run this JS code in a browser window (not Node JS). I have taken their code from their site like this:
<!DOCTYPE html>

But I keep getting these two errors:
cloudkit.js:14 GET https://api.apple-cloudkit.com/database/1/iCloud.com.example.CloudKitCatalog/production/public/users/caller?ckjsBuildVersion=2005ProjectDev34&ckjsVersion=2.6.1&clientId=735f8b19-3218-4493-80e4-7ab0b39041ac 401 (Unauthorized)
(anonymous) @ cloudkit.js:14

And immediately thereafter...
cloudkit.js:14 Uncaught (in promise) t {
  _ckErrorCode: "AUTHENTICATION_FAILED",
  _uuid: "3b5cf33d-d56d-414f-83a4-6f320cd915b2",
  _reason: "no auth method found",
  _serverErrorCode: "AUTHENTICATION_FAILED",
  _extensionErrorCode: undefined, …
}

I feel like this should be the easy part, but I can't even get the first setUpAuth() function to work. I've also tried my own CloudKit containerIdentifier and apiToken but I get the same error.
Does anyone know what I'm doing wrong?

A: It seems there are only like 5 people in the world who understand the CloudKit JS API, and all of them have been reassigned to work on ARKit and they ignore Stack Overflow. ;)
For the sake of posterity, I learned that I had two things wrong.
== 1 ==
You have to ignore the deprecation warning and use the version 1 JS file (ck/1/cloudkit.js):
https://cdn.apple-cloudkit.com/ck/1/cloudkit.js

== 2 ==
Despite what the documentation says, you actually can't specify the authentication button
 in your container configuration. The Sign In button started showing up for me when I changed my HTML to use the default Apple
 IDs:

I hope that helps someone else. :)

A: There seems to be some issue in cloudkit.js (when not using Node?) when it tries to save the auth cookie.  You can fake your way around that with something like this:
function MyAuth()
{
}

MyAuth.prototype.putToken = function (containerIdentifier, authToken)
{
  console.log('save cookie: ' + containerIdentifier + ' = ' + authToken);
  sessionStorage.setItem('auth.' + containerIdentifier, JSON.stringify(authToken));
}

MyAuth.prototype.getToken = function(containerIdentifier)
{
  console.log('load cookie: ' + containerIdentifier);
  return JSON.parse(sessionStorage.getItem('auth.' + containerIdentifier));
}

var gAuth = new MyAuth();

and setting up your container with:
CloudKit.configure({
  containers: [<container config>],
  services: {authTokenStore: gAuth}
});

sessionStorage will hold the cookie until the browser is closed.  The json conversion is used because when you sign out it sets the value to null which gets saved as "null" and then loaded incorrectly.  You could also store it locally in a hash, or in an actual cookie.
Also your configuration is incorrect because you've flattened out and removed the apiTokenAuth member:
CloudKit.configure({
  containers: [{
    containerIdentifier: 'iCloud.com.example.CloudKitCatalog',
    environment: 'production',
    apiTokenAuth: {
      apiToken: 'b86f0b5db29f04f45badba0366f39b7130a505f07765b5ba3a2ceb0cb3d96c0c',
      persist: true,
      signInButton: { id: 'sign-in-button', theme: 'black' },
      signOutButton: { id: 'sign-out-button', theme: 'black' }
    }
  }]
})

This works with either v1 or v2 of cloudkit.js.


text:
Q: JShell dollar variable name numbering When I enter an expression in JShell (9.0.1) it comes back with:
$22 -> <value>

Where does the 22 come from and what's happened to $1 to $21? (They are undefined.)
I seem to vaguely remember (when I started with Java 9.0) that the variables started with $1, which made more sense. Now, with 9.0.1,they all start with $22. Why?

A: They are there, just do a
/list

to find the list of all. They are there because you seem to have already consumed 1 to 21[21 snippets/statements] until you reached the $22 -> <value> snippet.
Trying to /reset and then adding snippet should set you back :-
jshell> 0+1
$1 ==> 1


text:
Q: PHP Array counting null row Tthe array does count a "false"/null row as a key, even when it returns "null" to the array, it counts as key 0.
How can I make it doesn't count when the value is null?
[...]
'scripts' => array(
        ($variable ? $object->dostuff(...) : null),
[...]

A: Run it through array_filter first, it'll empty values with a 0 or a null.


text:
Q: static int value not changing upon adding I am facing a weird issue. I have an ErrorCollector which is based on an ArrayList. I want to throw at the end of all the tests the cumulative errors that have been collected by error collector.
For that, I have written something like :
private static int noOfErrors;

@Before
public void setUp() {

    MockitoAnnotations.initMocks(this);

    this.mockMvc = MockMvcBuilders.standaloneSetup(myController).build();

    collector = new MyErrorCollector();
}

@After
public void tearDown() {

    noOfErrors = noOfErrors + collector.getErrorCount();

    for (Throwable error : collector.getErrors()) {
        System.out.println(error.getMessage());
    }
    collector = null;
}

@AfterClass
public static void finalTearDown(){
    assertEquals(noOfErrors, 0);
}

But even though in my @After method, the collected errors in non zero, assertEquals method in @AfterClass method is not failing. Upon debugging, it is showing non zero noOfErrors in tearDown methodand vice versa for finalTearDown.


text:
Q: Selecting which NAs you want to consider in a multiplication in R I've tried to find a solution to my problem in other topics but I haven't found anything yet.
I have a data frame with some columns that I want to multiply. Col1 refers to how many times per week you exercise and Col2 refers to time spent every time you exercise.
  Col1  Col2
1 0     <NA>
2 3    00:40:00
3 2    00:40:00
4 5    00:20:00
5 <NA>   NA
6 0     <NA>

The first thing I need to do is to convert that time format in minutes or seconds. The second thing and the hard issue here is that, for the rows with at least one NA, in each row, the multiplication should only happen if the NA is present only in the second column( look at row 6 in this example). The result of the multiplication should be 0. On the other hand, if there's an NA in both columns it means those observations should be considered as 'missing' and return NA.
How should I proceed?

A: Here's an approach that's similar in spirit to @akrun's solution (in comments), but using the replace function and without using an additional i1 indicator. First set up the data and do the conversion to seconds, per @akrun's pointer:
d <- data.frame(Col1 = c(0, 3, 2, 5, NA, 0),
                Col2 = c(NA, "00:40:00", "00:40:00", "00:20:00", NA, NA))
library(lubridate)
d$secs <- period_to_seconds(hms(d$Col2))

Now do the multiplication, and replace NAs in rows where Col1==0 with 0:
d$Col3 <- d$Col1 * d$secs
d$Col3 <- replace(d$Col3, d$Col1 == 0, 0)
# d$Col3[d$Col1 == 0] <- 0 # equivalent to above row

Result:
d
#   Col1     Col2 secs Col3
# 1    0     <NA>   NA    0
# 2    3 00:40:00 2400 7200
# 3    2 00:40:00 2400 4800
# 4    5 00:20:00 1200 6000
# 5   NA     <NA>   NA   NA
# 6    0     <NA>   NA    0

A: We can convert the strings to time object and then reconvert it to seconds with period_to_seconds (from lubridate).  Get the index of non-NA elements from 'Col2' ('i1'), Based on the index, create the 'Secs' column by multiplying with the corresponding elements of 'Col1' and assign values that are 0 in 'Col1' and is a NA in Col2 to 0
library(lubridate)
secs <- period_to_seconds(hms(df1$Col2))
i1 <- !is.na(df1$Col2)
df1$Secs[i1] <- secs[i1] * df1$Col1[i1]
df1$Secs[df1$Col1==0 & !i1] <- 0
df1
#  Col1     Col2 Secs
#1    0     <NA>    0
#2    3 00:40:00 7200
#3    2 00:40:00 4800
#4    5 00:20:00 6000
#5   NA     <NA>   NA
#6    0     <NA>    0

data
df1 <- structure(list(Col1 = c(0L, 3L, 2L, 5L, NA, 0L), Col2 = c(NA,
"00:40:00", "00:40:00", "00:20:00", NA, NA)), .Names = c("Col1",
"Col2"), class = "data.frame", row.names = c("1", "2", "3", "4",
"5", "6"))


text:
Q: How to iterate through a UTF-8 string correctly in OCaml? Say I have some input word like "føøbær" and I want a hash table of letter frequencies s.t. f→1, ø→2 – how do I do this in OCaml?
The http://pleac.sourceforge.net/pleac_ocaml/strings.html examples only work on ASCII and https://ocaml-batteries-team.github.io/batteries-included/hdoc2/BatUTF8.html doesn't say how to actually create a BatUTF8.t from a string.

A: The BatUTF8 module you refer to defines its type t as string, thus there is no conversion needed: a BatUTF8.t is a string. Apparently, the module encourages you to validate your string before using other functions. I guess that a proper way of operating would be something like:
let s = "føøbær"
let () = BatUTF8.validate s
let () = BatUTF8.iter add_to_table s

A: Looking at the code of Batteries, I found this of_string_unsafe, so perhaps this is the way:
open Batteries
BatUTF8.iter (fun c -> …Hashtbl.add table c …) (BatUTF8.of_string_unsafe "føøbær")`

although, since it's termed "unsafe" (the doc's don't say why), maybe this is equivalent:
BatUTF8.iter (fun c -> …Hashtbl.add table c …) "føøbær"
At least it works for the example word here.
Camomile also seems to iterate through it correctly:
module C = CamomileLibraryDefault.Camomile
C.iter (fun c -> …Hashtbl.add table c …) "føøbær"

I don't know of the tradeoffs between Camomile and BatUTF8 here, though they end up storing different types (BatUChar vs C.Pervasives.UChar).


text:
Q: How to get text from text box using protractor for Angular 7 application **var object = element(by.xpath(Locator));
  expect(object.isPresent()).toEqual(true);
  var appText = object.getText();
  appText.then(async function(text){
       console.log("appliation text: ",text);
  }**

I have mentioned above the code which I'm trying to execute. But it is returning empty value.

A: It is possible the object to be present but not displayed or not contains value in it.
  var object = element(by.xpath(Locator));
  expect(object.getText()).trimLeft().trimRight()).toNotEqual('');
  var appText = object.getText();
  appText.then(async function(text){
  console.log("appliation text: ",text);
  }


text:
Q: "Allow access to Azure services" turn off by default from ARM template Does anybody know how to setup ARM Template to keep "Allow access to Azure services" switch be turned OFF by default?

Here is what I currently have
 "resources": [
{
  "name": "[parameters('serverName')]",
  "type": "Microsoft.Sql/servers",
  "location": "[parameters('location')]",
  "apiVersion": "2014-04-01-preview",
  "properties": {
    "administratorLogin": "[parameters('administratorLogin')]",
    "administratorLoginPassword": "[parameters('administratorLoginPassword')]",
    "version": "[parameters('serverVersion')]"
  },
  "tags": {
    "deploymentVersion": "[parameters('deploymentVersion')]",
    "deploymentType": "[parameters('deploymentType')]"
  },
  "resources": [
    {
      "apiVersion": "2014-04-01-preview",
      "dependsOn": [
        "[concat('Microsoft.Sql/servers/', parameters('serverName'))]"
      ],
      "location": "[parameters('location')]",
      "name": "AllowAllWindowsAzureIps",
      "properties": {
        "endIpAddress": "0.0.0.0",
        "startIpAddress": "0.0.0.0"
      },
      "type": "firewallrules"
    }
  ]
}  ]

A: Just modify endIpAddress and startIpAddress to 255.255.255.255. Like below:
 {
                    "apiVersion": "2014-04-01-preview",
                    "dependsOn": [
                        "[concat('Microsoft.Sql/servers/', parameters('serverName'))]"
                    ],
                    "location": "[parameters('location')]",
                    "name": "AllowAllWindowsAzureIps",
                    "properties": {
                        "endIpAddress": "255.255.255.255",
                        "startIpAddress": "255.255.255.255"
                    },
                    "type": "firewallrules"
                }

A: Just remove the nested resources section. Then the sql will deploy without that checkmark. Redeploying won't remove the rule, but deploying a new sql will work.

A: My experience is when you use the name AllowAllWindowsAzureIps for a firewall resource type then it will ignore what range you specifiy in properties and just turn Allow Access to Azure Services flag on.
If you want to not have it enabled then don't include a resource with that name in your template.

A: Here is a bicep example:
resource sqlServer 'Microsoft.Sql/servers@2022-02-01-preview' = {
  name: name
  location: location
  tags: tags
  properties: {
    administratorLogin: sqlAdministratorLogin
    administratorLoginPassword: sqlAdministratorLoginPassword
    version: '12.0'
  }
}

resource allowAccessToAzureServices 'Microsoft.Sql/servers/firewallRules@2020-11-01-preview' = {
  name: 'allow-access-to-azure-services'
  parent: sqlServer
  properties: {
    startIpAddress: '0.0.0.0'
    endIpAddress: '0.0.0.0'
  }
}


text:
Q: Generating URL's for Pie Chart's Section Label using JFree Chart API How to generate URL's for labels for Pie Charts using JFree Chart package.We can extend the PieSectionLabelGenerator but i would need examples to show how.
Please advice!
Thanks in Advance!

A: Just invoke setLabelGenerator() on your PiePlot. The MessageFormat ArgumentIndex values correspond to the series name, value and percentage. You can reference them in your label generator, as shown below:
PiePlot plot = (PiePlot) chart.getPlot();
plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} {1} {2}"));

Addendum:

I am looking for a URL/Hyperlink.

Add a ChartMouseListener to your ChartPanel; you can obtain the link from the ChartEntity of the corresponding ChartMouseEvent. You can use java.awt.Desktop to open the URL in a browser.

A: Note this answer is targeted for those making urls and maps for charts used in web pages
For Making the Pie Segments Themselves URLs by using an HTML Map:
I would advise that you actually extend the StandardPieURLGenerator. Then you only need to do two things:
Add The Data
Either through constructor arguments or setters, make a way to add the data into fields within your class.
Override generateURL
generateURL will be called when the JFreeChart is wanting the generator to make a URL. If you are wanting to add parameters then I would do something like this:
public String generateURL(PieDataset dataset, Comparable key, int pieIndex)
{
  return super.generateURL(dataset, key, pieIndex) + "&" + yourParameters;
}

To Add URLs in the Label
Extend the StandardPieSectionLabelGenerator and override generateAttributedSectionLabel instead for the same steps above. Your function will now look more like this:
public String generateAttributedSectionLabel(PieDataset dataset, Comparable key)
{
  return super.generateAttributedSectionLabel(dataset, key) + "<a href="YOUR_URL_HERE" />";
}

A: static class CustomLegendGenerator
        implements PieSectionLabelGenerator {

    public String generateSectionLabel(final PieDataset dataset, final Comparable key) {
        String temp = null;
        if (dataset != null) {
            temp = key.toString();
            if (key.toString().equalsIgnoreCase("abc")) {
                temp = temp + " (abc String)";
            }
            if (key.toString().equalsIgnoreCase("xyz")) {
                temp = temp + " (xyz description)";
            }
            if (key.toString().equalsIgnoreCase("klm")) {
                temp = temp + " (Klm description)";
            }
        }
        return temp;
    }

    public AttributedString generateAttributedSectionLabel(PieDataset pd, Comparable cmprbl) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}


text: Q: current limiter with MOSFET I got a circuit from a current limiter for 12V by using a P-MOS, this is apply at the output from a DC/DC converter, I have to limit the current for 5 different voltages. I want to understand how the circuit with the PNP are working and how I can limit the current of the 12V. It would be great if somebody can help me.


text:
Q: vbScript System.Collections.ArrayList Object does not support... list.Add I am having a problem resolving the oList object with my CreateObject("System.Collections.ArrayList")
The error I get in vbscript

"Microsoft VBScript runtime error: Object doesn't support this property or method: 'list.Add'"

Based on this tutorial I know you can use COM wrapped .Net components in vbscript; so why won't this work?
Additional information:
When I am debugging in VS08 and add a watch to list, it says Children could not be evaluated.
The watch for objNode.value has a two character string value. (Which is expected behavior)
Function ProcessXML(oXML)
  STOP
  xPathExemptions= "//Exemption/@ExemptCodeWord"
  Dim xmlDoc : Set xmlDoc = CreateObject("MSXML2.DOMDocument.6.0")
  xmlDoc.Async = False
  xmlDoc.loadXML(oXML)

  Dim colNodes
  Set colNodes = xmlDoc.selectNodes(xPathExemptions)
  Dim oList
  Set oList = CreateObject("System.Collections.ArrayList")
  Dim objNode

  For Each objNode in colNodes
    oList.Add = objNode.value
  Next

  'ProcessExemptions = CStr(xmlDoc.selectNodes(xPathExemptions))

End Function

If you have any comments on my vbscript; please let me know - just started learning and don't know best practices.

A: Change:
oList.Add = objNode.value

...to:
oList.Add objNode.value

or (thanks to the guidance from @Ansgar)
Call oList.Add(objNode.value)

Here's a demonstration:
Option Explicit

Dim oList : Set oList = CreateObject("System.Collections.ArrayList")

oList.Add "Banana"
oList.Add "Apple"
oList.Add "Orange"
oList.Add "Grapes"
oList.Add "Plum"

oList.Sort

Dim oItem
For Each oItem In oList
    WScript.Echo oItem
Next

Expected Output:
Apple
Banana
Grapes
Orange
Plum

You can find more on the quirky rules of the use of parentheses with VB and VBScript in Eric Lippert's informative article.


text:
Q: WatchOS App: How to Execute in background for more than 3 minutes? Could you explain me the correct manner to manage the background mode app work more then 3 minutes.
My app is a timer-app notification. It works fine for 3 minutes and i got local notification in the background . If I set it to more then 3 minutes, it only works (in the background) for 3 minutes, then it's not get any local notification.
I know to iPhone application apple permit a 600 seconds (10 minutes) on  background task to run and Watch application apple permit a 180 seconds (3 minutes) on  background task to run.
So what i have does for application active more than 3 minutes in background?
My code is as follows:
ExtensionDelegate *del = (ExtensionDelegate *)[WKExtension sharedExtension].delegate;

del.strReminderTime = 60*15; // 15 min it's not work well.
// del.strReminderTime = 60*3; // 3 min it's work fine on background mode

ReminderTimer =  [NSTimer scheduledTimerWithTimeInterval:del.strReminderTime target:self selector:@selector(notificationReminder) userInfo:nil repeats:YES];

How to implement? It is best to use.
Appreciate if any suggestion or idea.


text:
Q: Macintosh HD drive listing as Recovery Partition and it is not available to boot I just wanted to merge 2 NTFS drives because I want to increase size of my BootCamp partition. But now, I can't boot to macOS. I can see it when I boot to Windows; its files and everything ok, but somewhy it is listed as Macintosh HD (D:) and my Recovery Partition is listed as Recovery HD (E:).
When I open Startup Menu, only my Bootcamp and Recovery partitions are avaible to select, no Macintosh HD.
Here is my Disk Management screen from Windows. My Macintosh HD (371GB) drive listed as "Recovery Partition"

How can I repair my main disk...

A: Generally, the first step, in reconstructing messed up the partition tables, is to dump the current contents.
If running High Sierra (macOS 10.13), you would need to boot to internet, internal or USB based macOS Recovery. The following commands would partially dump the contents of the GPT and MBR partition table.
gpt  -r  show  /dev/disk0
fdisk  /dev/disk0

The partition tables can then be repaired by using a variety of tools. A well known third party tool is gdisk.
Since you can only boot to Windows, the gpt and fdisk commands would be unavailable. There are third party Windows equivalents named readgpt.exe and readmbr.exe that can dump the contents of the partition tables. The syntax for executing these commands is shown below.

Note: These commands have to be run from a "Administrator: Command Prompt" window.

readgpt  -t0
readmbr  -t0

Additionally, the following command will dump the GPT attributes.
readgpt  -a0

There also a Windows version of the gdisk command. Below is the syntax for executing this command from a "Administrator: Command Prompt" window.
gdisk64  \\.\PHYSICALDRIVE0

If you have trouble using the gdisk command, you can post the partition table information in your question and ask for help.


text:
Q: ReSharper Search and Replace with Pattern I would like to re-factor various blocks of code throughout a project using ReSharper 7.1 Search / Replace with pattern.
The code blocks are similar to the following simplified example:
someControl.StatusProgressBar.IsIndeterminate = false;
someControl.StatusProgressBar.Visibility = Visibility.Visible;
someControl.StatusProgressBar.Minimum = 0;
someControl.StatusProgressBar.Maximum = 100;
someControl.StatusProgressBar.Value = percentage;

And I would like to change them to:
someControl.StatusProgressBar.Use(p =>
{
  p.IsIndeterminate = false;
  p.Visibility = Visibility.Visible;
  p.Minimum = 0;
  p.Maximum = 100;
  p.Value = percentage;
});

'Use' is an extension method
This is easy enough if all the blocks of code are setting the same number of properties. The following search and replace patterns will do the job:
SEARCH
$someControl$.$SomeProperty$.$SubProperty1$ = $val1$;
$someControl$.$SomeProperty$.$SubProperty2$ = $val2$;
$someControl$.$SomeProperty$.$SubProperty3$ = $val3$;
$someControl$.$SomeProperty$.$SubProperty4$ = $val4$;
$someControl$.$SomeProperty$.$SubProperty5$ = $val5$;

REPLACE
$someControl$.$SomeProperty$.Use(p=>
{
    p.$SubProperty1$ = $val1$;
    p.$SubProperty2$ = $val2$;
    p.$SubProperty3$ = $val3$;
    p.$SubProperty4$ = $val4$;
    p.$SubProperty5$ = $val5$;
});

However, if I also have a code block such as:
someControl.StatusProgressBar.IsIndeterminate = false;
someControl.StatusProgressBar.Visibility = Visibility.Visible;
someControl.StatusProgressBar.Minimum = 0;
someControl.StatusProgressBar.Maximum = 100;
someControl.StatusProgressBar.Value = percentage;
someControl.StatusProgressBar.Orientation = Vertical;

Is it possible, with ReSharper, to capture and replace both code blocks with one pattern? The later having one extra property setting but could easily be more than one extra or less.
I am thinking this is not possible. It would require the ability to create some kind of variable pattern and I can't see a way to do that, be it with regular expressions or otherwise.
Any ideas?


text:
Q: Is there a special name for matrices with $M[j,i] = M[i,i] - k, i \neq j$? Backgroud:
I am working on a computer science problem and arrives at a matrix $M$ with the following property:

*

*The size of Matrix $M$ is $n\times n$.

*For each row $j$, we have $M[j,i] = M[i,i] - k$, for each $i \neq j$, where $k$ is a fixed constant.

For example, $M$ can be (the constant $k = 3$ here):
$$
\mathbf{M} = \left( \begin{array}{ccccc}
5 & 12 & 1 & 6 & 7 \\
2 & 15 & 1 & 6 & 7 \\
2 & 12 & 4 & 6 & 7 \\
2 & 12 & 1 & 9 & 7 \\
2 & 12 & 1 & 6 & 10
\end{array} \right)
$$
Problem: Is there some special name for such matrices? What are the properties (in terms of matrix theory) of such matrices?


text:
Q: How to handle multiple submit buttons using mootools? In prototype you can use the following code.
 var form = control.form;
    new Ajax.Updater('result', form.action,
      { method: 'post',
        parameters: form.serialize({submit: control.name})
      }
    );

    return false;

Is there something like this in mootools? Simple but elegant ?

A: Yes, there is Form.Request
i.e.
(function($){

    new Form.Request($('formID'), $('responseID'), {
        onSuccess : function() {
          //form submitted correctly
        }
    });

})(document.id);

where $('formID') is your form, and $('responseID') is the element that will hold the response (i.e. a response message)


text:
Q: "source is not IEnumerable<>" error when using SqlQuery(Type,string,object[]).AsQueryable() Here is the problem
i am executing raw sql queries in controller as
var ctx=new DBModel();

public ActionResult Grid(string tbname,string query,object args)
{
   var obj = Activator.CreateInstance(Assembly.GetExecutingAssembly().GetType("Demo.Models." + tbname));
   dynamic queryresult;
   queryresult=ctx.Database.SqlQuery(obj.GetType(),query,args).AsQueryable();
}

I am getting the result of query in queryresult when i am using
queryresult=ctx.Database.SqlQuery(obj.GetType(),query,args);

but when when i am applying AsQueryable to it for operations like Count i am getting the error as
source is not IEnumerable<>
Please Help to solve this

A: Instead of converting queryresult to IQueryable, make it generic :
queryresult = ctx.Database.SqlQuery(obj.GetType(),query,args).Cast<object>();
var count = queryresult.Count();

IEnumerable<T> (in your case IEnumerable<object>, as you don't know which type at compile time) will allow you to perform many operations.


text:
Q: Js Dom: Find an element where the class is similar to, or includes substring I have a specific wrapper element where the class has a specific name included, alongside with a random id. Example wp-rgtayfu-fxyjzw-wrapper. The class will always contain the wrapper substring. There is only one element in the document where the class contains wrapper.
How can I find it?
(Or how can I query an element by class, using only a substring part of it?)

A: you can use this CSS Selector.

[attribute*="value"]

It will select element with a class attribute that contains the specified "value":
const targetElement = document.querySelector('[class*="wrapper"]')

A: It is better to separate the part of class you need using space. It will appear separately in classList property and document.getElementsByClassName can find it
The resulting class will be wp-rgtayfu-fxyjzw wrapper or wp rgtayfu fxyjzw wrapper
If you dont want to change the class, you can run a regex through the entire DOM, but it is really bad idea.


text:
Q: I have to click on my link twice before state is update and styling is changed i have an issue. I want the styling of my Link to change based on a state. But the issue is that, i have to click on the link twice before the styling is updated. But when i use the e.prevetndefault, the styling is applied when i click the link but I cannot go to the page.  Here is the code.
function Footer(){

    const [activeValue, setIsActive] =  useState("0")

    return(

<Link to="/peepNews"    onClick={()=>{setIsActive("1")}}        style={activeValue=="1"?{color:"#0B77BE",fontWeight:"600"}:null}    >Peep News</Link>

<Link to="/faq"         onClick={()=>{setIsActive("2")}}         style={activeValue=="2"?{color:"#0B77BE",fontWeight:"600"}:null}   >FAQ</Link>

Careers

<Link to="/legal"       onClick={()=>{setIsActive("3")}}         style={activeValue=="3"?{color:"#0B77BE",fontWeight:"600"}:null}       >Legal</Link>

Jupe Global

    );
}

EDIT:
This is when i added the useEffect hook. But the issue is that whenever the page re-render, the activeValue is set back to the default Value(0) instead of 1,2,3 etc.
function Footer(){

    const [activeValue, setIsActive] =  useState("0")

    useEffect(() => {

            setIsActive(activeValue)  ;
            alert(activeValue);

     },[activeValue])

    return(

<Link to="/peepNews"        onClick={()=>{setIsActive("1")}}    style={activeValue=="1"?{color:"#0B77BE",fontWeight:"600"}:null}    >Peep News</Link>

<Link to="/faq"         onClick={()=>{setIsActive("2")}}         style={activeValue=="2"?{color:"#0B77BE",fontWeight:"600"}:null}   >FAQ</Link>

Careers

<Link to="/legal"       onClick={()=>{setIsActive("3")}}         style={activeValue=="3"?{color:"#0B77BE",fontWeight:"600"}:null}       >Legal</Link>

Jupe Global

    );
}

A: With react-router you don't need to use the Link element to navigate to a new page, particularly if you want to functionality to be a little more complex.
You can create a history file and export a history object:
import { createBrowserHistory } from 'history';

export default createBrowserHistory();

Then import history into any file where you would like to navigate using javascript. Then in your file you can simply create a  which you can style as you please (or continue to use  with e.preventDefault()) which then navigates on the click action.

 {
        setIsActive("1");
        history.push("/peepNews");
      }}
      style={activeValue == "1" ? { color: "#0B77BE", fontWeight: "600" } : undefined} >
      Peep News


text:
Q: Spring Integration  Rabbit MQ getting disconnected We are working on a POC to use Spring integration and Rabbit MQ.
We have two modules producer module and consumer module both are runs in different JVMs.
The Producer module listen on a Folder (input folder) as soon as new files arrives,  creates a message then push to (incoming.q.in) queue and also move to process folder.
The Consumer module then pickups the messages from the incoming.q.in Queue then process the files them move to complete folder.
Both Producer and Consumer code is working fine but after some ideal item then consumer module is getting disconnecting from Rabbit MQ. We see messages in incoming.q.in queue but the consumer is not processing.
When I logged into Rabbit MQ Admin/Management tool "incoming.q.in" consumer list is empty and the message is "... no consumers ...".
  The consumer code
<int-amqp:inbound-channel-adapter channel="inBoundfile" queue-names="incoming.q.in" connection-factory="connectionFactory"
    error-channel="error.in">
</int-amqp:inbound-channel-adapter>
<int:header-enricher input-channel="inBoundfile" output-channel="serviceInbound">
    <int:header name="FILEID" expression="payload.fileID" />
</int:header-enricher>
<int:service-activator ref="routerService" method="processFile" input-channel="serviceInbound" output-channel="fileHandler.router.in" />
....

I appreciate your help.

A: Turn on DEBUG logging on the consumer side; you'll see lots of logging and reconnection attempts if/when a connection is lost.


text:
Q: Robotium test Share Link an return to app for testing I am doing testing for android app, My question is on button click i have  to open website in browser through robotium once the website is open i have to call solo.goback() or any appropriate  method so control comes back to the testing and testing proceeds further.
Can anybody tell me is there some way to do this.

A: You can't go back using Robotium, once you call an Activity outside the application under test, Robotium loses control over it. Similar questions here and here.
One thing you can do is check if your Activity has lost focus using solo.hasWindowFocus() but this method can be tricky because if your Activity has a Dialog (or another Activity) on top, this method will return false even if you still in your AuT.


text:
Q: How to read simultaneously from two files and print them line by line, bash? I want to write an script which has as arguments two files F1 and F2 and prints them alternatively; first will be written F1's first line, then F2'2 second line and so on. If one of them has less lines than the other, when we finish to print the shorter one, the script should write the longest until the end.
My idea was:
1) Check if there are not 2 arguments -> echo and exit
2) Check if F1 or F2 aren't files -> echo and exit
3) Body:
exec 3 < $1
exec 4 < $2
i=0
j=1
while read -u 3 line && ((i==0))
do
echo line; echo
 ((i++))
((j--))
    while read -u 4 line && ((j==0))
    do
        echo line; echo
 ((j++))
((i--))
   done
 done
 exit $?

Doubt: This would only work if both files have the same number of lines. How can I improve this to extend this solution to files with different size?

A: No need for a shell script.  You can do this directly with paste, which is specified by POSIX:
paste -d '\n' file1 file2

However, it doesn't handle different line counts the way you are describing.  To quote the specs:

If an end-of-file condition is detected on one or more input files, but not all input files, paste shall behave as though empty lines were read from the files on which end-of-file was detected....

I personally think it would be a mistake to make the behavior as you describe in your question.  You would be unable to tell, looking at line 24 of the output, whether it came from file1 or file2.  With the actual behavior of paste, you would know it came from file2, since it's an even line number of the output.
You can pipe the output through tr -s '\n' like so:
paste -d '\n' file1 file2 | tr -s '\n'

But, if there are actual blank lines in either file, you will not get the expected results.


text:
Q: Ionic 4 page navigation I am trying to create an application using ionic 4. Initially, I need to navigate between one screen and another (go from page 1 to page 2). But, the following error always pops up for me:
Uncaught (in promise): Error: No component factory found for Page2. Did you add it to @NgModule.entryComponents?
Error: No component factory found for Page2. Did you add it to @NgModule.entryComponents?

My page1.html:
<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Page One</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-label id="textView">Oi, Fulano!</ion-label>
  <button (click)='outraPagina();' id="btnTrocar">Trocar usuário</button>
</ion-content>

My page1.ts:
import { Component } from '@angular/core';
import { IonicPage, NavController } from 'ionic-angular';
import { Page2 } from '../page2/page2'

@IonicPage()
@Component({
  selector: 'page-page1',
  templateUrl: 'page1.html'
})
export class Page1 {
  constructor(public navCtrl: NavController) {

  }

  outraPagina() {
    this.navCtrl.push(Page2, {});
  }

}

Any ideas on how to solve?
Thank you.

A: You need to add page2 inside app.module.ts
  declarations: [
    AppComponent,
    page2
  ],
  entryComponents: [page2],


text:
Q: I cannot create the luac.cross compiler. How can I fix "undefined reference to 'strtol'"? My goal is to be able to cross-compile Lua code for my ESP8266 before uploading to the device.
 The official documentation is here.
I have the same issue as this person. At first I also had a "missing c_limits.h" error and solved it due to that post. However, unlike the original poster, I am experiencing the "strtol" error on both master and dev branches and have been unable to find a solution myself.
The error message is "undefined reference to `c_strtol'" in lobject.c, in the 'lua0_strtod' function.
strtol is defined in stdlib.h, which is in the same include folder as limits.h, so I am unclear why the definition cannot be found. I have done some hunting through the source code to see if the appropriate headers were not included in a source file but I have been unsuccessful in finding the problem.
Edit:
The exact command that produces the error is (running from the root directory of the source code):
lua tools/cross.lua

I have always run this after successfully running
make


text:
Q: Is there a way to make Internet Explorer understand this.style.setProperty? I've started using the excellent D3.js data visualisation library (http://mbostock.github.com/d3/).
The results work great in Firefox and Chrome, but not in IE. One issue seems to be the heavy use of this.style.setProperty and this.style.removeProperty by D3, which isn't recognised by IE.
I wondered if anyone knew of a workaround or shim or some such? (My JavaScript is pretty poor, BTW).

A: I have been fighting with the same bug you can simply solve it by using the following pattern when you want to change the style.
element.style("property", "value");

It's absolutely necessary that the value is always a string. Otherwise you will get a weird Character Error in IE9 as it can only handle strings.
I tested it with D3JS 3.2.8.

A: What about .classed('class', true/false)? It works perfectly well in IE9:
function mouseOver(d, i) {
    var element = d3.select(this);
    var alreadyHasClass = element.classed('className'); // boolean
    element.classed('cssClass', !alreadyHasClass); // set/remove class
}

BTW, it's faster add/remove classes to elements than appending information to "style".

A: I believe the newest version 2.1.3 solves this.  Take a look.


text:
Q: back button not reloading page test1.php has this code
(
<?php
header("Cache-Control: no-cache");
header("Pragma: no-cache");

$a=date("D M Y ; h:m:s");

echo $a;

?>

<meta http-equiv='Pragma' content='no-cache'/>
<meta http-equiv='Expires' content='-1'/>

tk

)

then when i visit test1.php and move to test2.php then on pressing back button why is it not displaying the current time instead displaying the time i last visited it.
its a simpler version of my previous problem

A: Your browser cached the previous response.


text:
Q: Flink : DataStream to Table Usecase: Read protobuf messages from Kafka, deserialize them, apply some transformation (flatten out some columns), and write to dynamodb.
Unfortunately, Kafka Flink Connector only supports - csv, json and avro formats. So, I had to use lower level APIs (datastream).
Problem: If I can create a table out of the datastream object, then I can accept a query to run on that table. It would make the transformation part seamless and generic. Is it possible to run a SQL query over datastream object?

A: If You have a DataStream of objects, then You can simply register given DataStream as Table using StreamTableEnvironment.
This would look more or less like below:
val myStream = ...
val env: StreamExecutionEnvironment = configureFlinkEnv(StreamExecutionEnvironment.getExecutionEnvironment)
val tEnv: StreamTableEnvironment = StreamTableEnvironment.create(env)
tEnv.registerDataStream("myTable", myStream, [Field expressions])

Then You should be able to query the dynamic table created from Your DataStream.


text:
Q: What's the best way to inject a yaml file into an Argo workflow step? Summary:
We have a golang application that submits Argo workflows to a kubernetes cluster upon requests. I'd like to pass a yaml file to one of the steps and I'm wondering what are the options for doing this.
Environment:

*

*Argo: v2.4.2

*K8s: 1.13.12-gke.25

Additional details:
Eventually, I would like to pass this file to the test step as shown in this example:
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: test-
spec:
  entrypoint: test
  templates:
  - name: test
    container:
      image: gcr.io/testproj/test:latest
      command: [bash]
      source: |
        python test.py --config_file_path=/path/to/config.yaml

The image used in this step would have a python script that receives the path to this file then accesses it.
To submit the Argo workflows with golang, we use the following dependencies:

*

*https://github.com/argoproj/argo-workflows/tree/master/pkg/client

*https://github.com/argoproj/argo-workflows/tree/master/pkg/apis
Thank you.

A: Option 1: pass the file as a parameter
Workflow parameters are usually small bits of text or numbers. But if your yaml file is reasonably small, you could string-encode it and pass it as a parameter.
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: test-
spec:
  entrypoint: test
  arguments:
    parameters:
    - name: yaml
      value: "string-encoded yaml"
  templates:
  - name: test
    container:
      image: gcr.io/testproj/test:latest
      command: [bash]
      source: |
        # In this case, the string-encoding should be BASH-compatible.
        python test.py --config_file_as_string="{{inputs.parameters.message}}"

Option 2: pass the file as an artifact
Argo supports multiple types of artifacts. Perhaps the simplest for your use case is the raw parameter type.
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: test-
spec:
  entrypoint: test
  templates:
  - name: test
    inputs:
      artifacts:
      - name: yaml
        path: /path/to/config.yaml
        raw:
          data: |
            this is
            the raw file
            contents
    container:
      image: gcr.io/testproj/test:latest
      command: [bash]
      source: |
        python test.py --config_file_path=/path/to/config.yaml

Besides raw, Argo supports "S3, Artifactory, HTTP, [and] Git" artifacts (among others, I think).
If, for example, you chose to use S3, you could upload the file from your golang app and then pass the S3 bucket and key as parameters.
Golang client
I'm not familiar with the golang client, but passing parameters is certainly supported, and I think passing in a raw parameter should be supported as well.


text:
Q: Google speech to text: Extra language set to "kn" but not working I am trying to use Google Speech to Text API for Kannada language and I am setting EXTRA_LANGUAGE to "kn" for the same but it is not working.
Below is the code I am using.
Locale locale = new Locale("kn");
    //Locale.setDefault(locale);
    Log.e(TAG, "Locale " + locale.getLanguage() + " present: " + isLocalePresent(locale));
    if (isLocalePresent(locale)) {
        //int randomInt = random.nextInt(allItemsLength);
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, locale.getLanguage());
        //intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Try saying \"" + mergedFinalArray.get(randomInt) + "\"");
        try {
            startActivityForResult(intent, REQ_CODE_K2E_SPEECH_INPUT);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(getApplicationContext(), R.string.missing_in_voc, Toast.LENGTH_SHORT).show();
        }
    }

Please note that the locale is present in the device. The same is working for other languages like Hindi (hi), Tamil (ta) and Japanese (ja) but not for Telugu (te), Malayalam (ml), Kannada (kn). Am I doing anything wrong?

A: After hours of research, I finally found solution.
In the below line of code, I should send "kn_IN" instead of "kn". This made it work.
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "kn_IN");

This method works for all the languages mentioned above. ("te_IN", "ml_IN")

A: Have you tried "kan"?
According to this link Locale accepts ISO 639 alpha-2 or alpha-3 and on the following list the code for Kannada language on ISO 639-2 and 3 is "kan".


text:
Q: Curl https login I'm trying to login to https://www.reporo.com/login.php using Curl. Here is code I'm using:
  <?php
function createPostString($aPostFields) {
    foreach ($aPostFields as $key => $value) {
        $aPostFields[$key] = urlencode($key . '=' . $value);
    }

    return urlencode(implode('&', $aPostFields));
}

$postFields['username'] = 'login';
$postFields['password'] = 'pass';
$postFields['submit'] = ' ';

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://www.reporo.com/login.php');
curl_setopt($curl, CURLOPT_REFERER, 'https://www.reporo.com/login.php');
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; pl; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_COOKIEFILE, dirname(__FILE__) . '/cookies.txt');
curl_setopt($curl, CURLOPT_COOKIEJAR, dirname(__FILE__) . '/cookies.txt');
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS,  createPostString($postFields));

curl_exec($curl);
header('Location: https://www.reporo.com/analytics/dashboard.php');
curl_close($curl)

?>

After using script it redirects me to http://best-payroll-services.info/adder/login.php . Where is the problem ?
After var_dump(curl_getinfo($c)) I've got:
'url' => string 'https://www.reporo.com/login.php' (length=32)
  'content_type' => string 'text/html' (length=9)
  'http_code' => int 200
  'header_size' => int 382
  'request_size' => int 192
  'filetime' => int -1
  'ssl_verify_result' => int 20
  'redirect_count' => int 0
  'total_time' => float 0.843
  'namelookup_time' => float 0
  'connect_time' => float 0.109
  'pretransfer_time' => float 0.531
  'size_upload' => float 255
  'size_download' => float 3233
  'speed_download' => float 3835
  'speed_upload' => float 302
  'download_content_length' => float 3233
  'upload_content_length' => float 255
  'starttransfer_time' => float 0.655
  'redirect_time' => float 0
  'certinfo' =>
    array
      empty
  'redirect_url' => string '' (length=0)

Greetings.

A: There are a couple of things that are wrong with this script.

*

*You need to change the relative path of cookies:
if ( file_exists( 'cookies.txt' ) )

to an absolute
if ( file_exists( dirname( __FILE__ ).'/cookies.txt' ) )

so that you're sure it's checking the right file.

*Also str_replace( '/', '', $_SERVER[ "PHP_SELF" ] ); is a return function. That means you need to store the returned value:
$redirect_url = str_replace( '/', '', $_SERVER[ "PHP_SELF" ] );
header('Location:'.$redirect_url);

I've slightly modified your code to this:
function connect( $url, $post = '' )
{
    $curl = curl_init();
    curl_setopt( $curl, CURLOPT_URL, $url );
    curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.100 Safari/534.30' );
    curl_setopt( $curl, CURLOPT_HEADER, 0 );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, 0 );
    curl_setopt( $curl, CURLOPT_POST, 1 );
    curl_setopt( $curl, CURLOPT_POSTFIELDS, $post );
    curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $curl, CURLOPT_COOKIEFILE, __DIR__.'/cookies.txt' );
    curl_setopt( $curl, CURLOPT_COOKIEJAR,  __DIR__.'/cookies.txt' );
    $result = curl_exec( $curl );
    curl_close( $curl );
    return $result;
}

$login_data[ 'username' ] = $_POST['login'];
$login_data[ 'password' ] = $_POST['password'];

foreach ( $login_data as $key => $value ) {
    $post_items[ ] = $key.'='.$value;
}
$post_string = implode( '&', $post_items );

if ( file_exists( __DIR__.'/cookies.txt' ) ) {
    // Cookies exist, point to a secured page?
    echo connect( 'https://yourhost/secure.php')
}
else {
    // Cookies don't exist post to a login page and redirect to a secured page?
    connect( 'https://yourhost/login.php', $post_string )
    $redirect_url = str_replace( '/', '', $_SERVER[ "PHP_SELF" ] );
    header( 'Location: '.$redirect_url );

}

A: I'm assuming that the website it redirects to belongs to you, because the only thing in that code that redirects is the following line:
header( 'Location: '.$_SERVER[ "PHP_SELF" ] );

I'm guessing the problem is with:
if ( file_exists( 'cookies.txt' ) )

That file doesn't appear to exist, which is why it's running:
connect( 'https://www.reporo.com/login.php', $post_string );
str_replace( '/', '', $_SERVER[ "PHP_SELF" ] );
header( 'Location: '.$_SERVER[ "PHP_SELF" ] );

A: Here's a script I wrote to login to the Reporo site and download the overall advertiser stats for a particular date (specified in the url). I'm pretty sure this is what you're looking for.
// Login & download stats in CSV format
function get_stats($login_url, $username, $password, $login_button, $csv_title, $download_url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $login_url);
    $post_fields = 'username='.urlencode($username).'&password='.urlencode($password);
    // Some sites don't send this variable, hence the check
    if(trim(urlencode($login_button)) != ''){
        $post_fields .= '&'.$login_button.'='.$login_button;
    }
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . '/cookies.txt');
    curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . '/cookies.txt');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
    curl_exec($ch);

    // Prevent the script from timing out
    set_time_limit(0);

    $fp = fopen (dirname(__FILE__) . '/'.$csv_title, 'w+');//This is the file where we save the information
    curl_setopt($ch, CURLOPT_URL, $download_url);//Here is the file we are downloading
    curl_setopt($ch, CURLOPT_TIMEOUT, 50);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
}

// Set REPORO variables
$rep__login_url = 'https://www.reporo.com/login.php';
$rep_un = 'USERNAME';
$rep_pw = 'PASSWORD';
$rep_login_butt = 'submit';
$rep_csv = 'reporo_stats.csv';
// In the url, list= YOUR CAMPAIGN IDS (comma seperated)
$rep_dl_url = 'https://www.reporo.com/analytics/data.php?type=AdvertiserEntity&start=2012-10-17&end=2012-10-17&entity=client&list=1234,5678,9101,1121,3141&format=csv';

// Call get_stats function
get_stats($rep__login_url, $rep_un, $rep_pw, $rep_login_butt, $rep_csv, $rep_dl_url);


text:
Q: Selecting specific value in row of the selected checkbox and checking for duplicates I came across a problem whose solution has led me to post it here so others may make use of it or improvise better than me.
My Problem: I have a table of results with check boxes to select rows. The requirement was to know if I was selecting(using the checkboxes) the same set of one particular column value, if so I had to do something.

A: HTML code
Considering the below being my html code for the dynamic table(CFML). The  tag has to be inside a loop to dynamically create the table content.

      StagingID
      BatchID
      AuditID
      Action
      File Name
      Card No
      Card No

    #staging_id#
    #batch_import_job_id#
    #audit_Id#
    #code#
    #source_filename#
    #card_number#

        <input type="checkbox" class="checkBoxClass cb"  name="resolveErrorsCheck" value="#row_no#">

JS Code
  //register the click event

 $(document).ready(function() {
      $(document).on('click', '.cb',enableDisableActions);

 });

  function enableDisableActions() {
var values = new Array();
           $.each($("input[name='resolveErrorsCheck']:checked").closest('td').siblings('.file_name'),
             function (){
                  values.push($(this).text());
             });
            const initial = values[0];
            const result = values.filter(src => src != initial);
            if(result.length){
               //no duplicate file_name selected
               //do something
            }else{
                //duplicate file_name selected
                //do something
            }
}


text:
Q: How to set axiosconfig using typescript? I am new in Typescript. I am converting my code from JavaScript to Typescript. My code below will work in JavaScript, but it has an error in Typescript
import axios from "axios";

const data = JSON.stringify([eventID]);

const config = {
    method: "delete",
    url: url,
    headers: {
        "Authorization": `Bearer ${elasticPrivateKey}`,
        "Content-Type": "application/json",
    },
    data: data,
};

return axios(config);

I have an error like this

I don't understand how to get and configure this AxiosRequestConfig

A: I am not sure but try this
import axios,{ AxiosRequestConfig } from 'axios';

const config:AxiosRequestConfig = {
        method: "delete",
        url: url,
        headers: {
            "Authorization": `Bearer ${elasticPrivateKey}`,
            "Content-Type": "application/json",
        },
        data: data,
    };

A: You can do this:
import axios, { AxiosRequestConfig } from 'axios'

const config: AxiosRequestConfig = {
  baseURL: 'https://api.pagar.me/core/v5',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    Authorization: `${process.env.BASIC}`
  }
}

const pagarmeApi = axios.create(config)

export default pagarmeApi


text:
Q: Java example to convert FlashAir decimal 16-bit integer to date/time format? In retrieving the file list from FlashAir 2nd gen using their command cgi as explained here: FlashAir Get List CGI Command I get decimal 16-bit integers to represent the date and time of the file.
The specification (in the link posted) explains how to understand the retrieved values, but it lacks a Java example. I tried downloading and inspecting Android sample code posted in the FlashAir Developer's Website FlashAir Tutorial for Android - Downloading Content, but they just use the file names, so they do not perform any conversions.

A: Just extract the bits as specified.
Assuming you have a short time and short date:
int seconds = (time & 31) * 2;
int minutes = (time >> 5) & 63;
int hours   = (time >> 11) & 31;
int day   = date & 31;
int month = (date >> 5) & 15;
int year  = ((data >> 9) & 127) + 1980;

Then just make a datetime out of that.
It's not clear whether the raw years can be negative. I wrote it such that they can't be, if they're supposed to be able to be negative (to represent dates before 1980) just remove the & 127.


text:
Q: Ignore Text in HTML::TreeBuilder Output Perl I need to ignore or remove all text in between all HTML elements so I can generate a blank template from a given web page.
I am parsing using the perl module HTML::TreeBuilder and HTML::Element.
I have tried the ignore_text method noted in the documentation but that doesn't provide correct results.
I have also tried using DOMXpath with PHP to do the same thing and results seemed too cumbersome to manage. Regex's might work but are a last resort to me.
This is part of my current code, very basic. Bottom is just output to file. All code is functional I just need formatting to work so I can generate template files.

my $url= "http://www.example.com";
my $page = get($url) or die $!;
my $tree = HTML::TreeBuilder->new_from_content($page);

$tree->parse_file($page);

$tree->ignore_text;
$tree->elementify;

open OUTPUT, "+>".$body;
my $output = $tree->as_HTML;
print OUTPUT $output;
close OUTPUT;

Thanks in advance for the help!
EDIT: I found the problem - the ignore text only works when you parse from a physical file. I had to save the page as a temp file to parse then output the way I wanted with no text then I just did unlink($tmp) at the bottom to delete the file. My script has since grown much more complicated with reading and writing to database and each time I need to create this temp file which is kind of annoying...
Thanks for the reply below!

A: You are very close.
It looks like you need to set ignore_text with a true value. $tree->ignore_text(1) and then make sure its set before calling parse_file.
Sorry this is a bit long but i hope it helps.
Here is quick pass at the new code, hard to test without example page:
my $tree = HTML::TreeBuilder->new;

$tree->ignore_text(1);
$tree->elementify;
$tree->parse_file( $page );

Here is my quick test script using a local file:
use strict;
use warnings;

use HTML::TreeBuilder;

my $page = 'test.html';
my $tree = HTML::TreeBuilder->new();

$tree->ignore_text(1);
$tree->parse_file($page);
$tree->elementify;

print $tree->as_HTML;

Input test.html:

  <title>title text</title>

Heading 1

paragraph text

And output:
<title></title>

Good luck

A: Maybe you should use HTML::Parser for this task. It is maybe a little bit more code, but should not to complicated.


text:
Q: Simple Python variable scope It seems to me that functions can reference variables outside of their scope but cannot set them. Is this correct? Am I understanding this right?
I also included the globals usage. I know they are bad ju-ju and will avoid them; I know how to get around this, but just wanted to be clear.
My example program:
import foo

# beginning of functions

# this one works because I look at the variable but dont modify it
def do_something_working:

    if flag_to_do_something:
          print "I did it"

# this one does not work because I modify the var
def do_something_not_working:

    if flag_to_do_something:
          print "I did it"
          flag_to_do_something = 0

# this one works, but if I do this God kills a kitten
def do_something_using_globals_working_bad_ju_ju:

    global flag_to_do_something

    if flag_to_do_something:
         print "I did it"
         flag_to_do_something = 0

# end of functions

flag_to_do_something = 1

do_something_working()
do_something_not_working()
do_something_using_globals_working_bad_ju_ju()

A: Correct. Well mostly. When you flag_to_do_something = 0 you are not modifying the variable, you are creating a new variable. The flag_to_do_something that is created in the function will be a separate link to (in this case) the same object. However, if you had used a function or operator that modified the variable in place, then the code would have worked.
Example:
g = [1,2,3]
def a():
    g = [1,2]
a()
print g #outputs [1,2,3]

g = [1,2,3]
def b():
    g.remove(3)
b()
print g #outputs [1,2]

A: Yep, pretty much. Note that "global" variables in Python are actually module-level variables - their scope is that Python module (a.k.a. source file), not the entire program, as would be the case with a true global variable. So Python globals aren't quite as bad as globals in, say, C. But it's still preferable to avoid them.


text:
Q: Improve UILabel text visibility in Swift I am showing the text on an UIImage in UITableViewCell, but UILabel text is dull. How to improve label text brightness? I have added Label on Image. I am also using Shadow image in label to make the text more visible, but the text is more dull in iPhone 6 Simulator.
How to manage it? And any other way to achieve this

A: And image or a description of what kind of "improvements" you are looking for would help to help you out better.
But the 2 most important things are probably font and color.
if you want to change the textColor. Use
myUILabel.textcolor = UIColor(red: 16/255.0, green: 177/255.0, blue: 216/255.0, alpha: 1)

Obviously changing the RGB values to something that looks good in your app.
to change the font and fontsize use something like this:
myUILabel.font = UIFont(name: "BPreplay", size: 20)

Also it's always better to test on an actual device. Gives you a much better view on how it feels on the phone.


text:
Q: delete line and the following one if condition met I have this kind of file and I use bash:
&ACLB032-06|Bos taurus|COI-5P|HM102290
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCTATTCTATATCAACACTTATTC--------
&CYTC426-12|Bos taurus|atp6
ATGAACGAAAATTTATTTACCTCTTTTACCAATTCTAGAGTTTGCAGTAGCTATAATCCAAGCCTATGTATTCACTCTCCTAGTCAGCCTATATCTGCATGACAACACA
&CYTC426-12|Bos taurus|D-loop
AACACTATTAATATAGTTCCATAAATACAAAGCGCTTTCAATACTCAATTTAGCACTCCAAACAAAGTCAATATATAAACGCAGGCCCCCCCCCCC
&CYTC426-12|Bos taurus|COII
ATGGCATATCCCATACAACTAGGATTCCAAGCGGGTCAAACCACAGTTTCATACCCATTGTCCTTGAGTTAGTCCCACTAAAGTACTTTGAAAAATGATCTGCGTCAA
&CYTC426-12|Bos taurus|COI-5P|HQ184039
CATAAAGATATTGGTACCCTTTATCTAAAAAGTCTTCAGCTGATTAGCAACACTTCATGGAGGT
&CYTC426-12|Bos taurus|CYTB
ATGACTAACATTCGAAAGTCCCACCCACTACCTAGTGCTAATACCAACGGCCGGCACAGTCGAAAACAAATTACTAAAATGA

The file might contains a million of lines
I want to keep only lines containing the string "COI-5P" as well as their following lines, which would result in this
&ACLB032-06|Bos taurus|COI-5P|HM102290
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCTATTCTATATCAACACTTATTC--------
&CYTC426-12|Bos taurus|COI-5P|HQ184039
CATAAAGATATTGGTACCCTTTATCTAAAAAGTCTTCAGCTGATTAGCAACACTTCATGGAGGT

But I have trouble to find solution.
Can you help me please?

A: You could try (assuming GNU grep):
grep -A1 --no-group-separator 'COI-5P' file

The grep man page says:

Context Line Control
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching  lines.   Places  a  line  containing
  a  group
             separator  (--) between contiguous groups of matches.  With the -o or --only-matching option, this
             has no effect and a warning is given.
--no-group-separator
Use empty string as a group separator.

Tests:
$ cat file
&ACLB032-06|Bos taurus|COI-5P|HM102290
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCTATTCTATATCAACACTTATTC--------
&CYTC426-12|Bos taurus|atp6
ATGAACGAAAATTTATTTACCTCTTTTACCAATTCTAGAGTTTGCAGTAGCTATAATCCAAGCCTATGTATTCACTCTCCTAGTCAGCCTATATCTGCATGACAACACA
&CYTC426-12|Bos taurus|D-loop
AACACTATTAATATAGTTCCATAAATACAAAGCGCTTTCAATACTCAATTTAGCACTCCAAACAAAGTCAATATATAAACGCAGGCCCCCCCCCCC
&CYTC426-12|Bos taurus|COII
ATGGCATATCCCATACAACTAGGATTCCAAGCGGGTCAAACCACAGTTTCATACCCATTGTCCTTGAGTTAGTCCCACTAAAGTACTTTGAAAAATGATCTGCGTCAA
&CYTC426-12|Bos taurus|COI-5P|HQ184039
CATAAAGATATTGGTACCCTTTATCTAAAAAGTCTTCAGCTGATTAGCAACACTTCATGGAGGT
&CYTC426-12|Bos taurus|CYTB
ATGACTAACATTCGAAAGTCCCACCCACTACCTAGTGCTAATACCAACGGCCGGCACAGTCGAAAACAAATTACTAAAATGA

$ grep -A1 --no-group-separator 'COI-5P' file
&ACLB032-06|Bos taurus|COI-5P|HM102290
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCTATTCTATATCAACACTTATTC-----------
&CYTC426-12|Bos taurus|COI-5P|HQ184039
CATAAAGATATTGGTACCCTTTATCTAAAAAGTCTTCAGCTGATTAGCAACACTTCATGGAGGT

A: I found the solution with this code :
awk '/COI-5P/{nr[NR]; nr[NR+1]}; NR in nr' oldfile > newfile

where

*

*/COI-5P/{nr[NR]; nr[NR+1]} record matching line and following

*NR in nr select and implicitly print recorded lines.


text:
Q: Drop-down menu in iOS alert I'm trying to set labels to certain areas of an app dynamically so that some of them show while others are hidden. I have an alert that prompts for text to fill these labels with, but I know the options in advance and would like to only allow the user to choose certain options.
Is there a way to have a drop-down menu of options in an iOS alert rather than a simple text input? Any help would be appreciated greatly.

A: You can't have a dropdown menu but you can have multiple buttons, one for every option.
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle: @"title" message: @"message"
delegate: self cancelButtonTitle: @"Cancel" otherButtonTitles: @[@"option1", @"option2",
@"option3"], nil];

A: You don't need:
@[@"option1", @"option2", @"option3"], nil
Use simple strings instead:
@"option1", @"option2", @"option3", nil


text:
Q: TextView ontouch I have two lines in a TextView... When I touch the first line an action to be performed and when I touch the second line a different action needs to be performed.
Could you please help?

A: You will have to set a custom ontouchlistener to  your TextView and depending upon co-ordinates recieved you need to initiate differnt action


text:
Q: PostgreSQL replica where I can create triggers? I have some PostgreSQL triggers I'd like to write which use a reasonable amount of CPU and then NOTIFY if a complex pattern has happened.  These triggers are created dynamically by my app.  (The function it invokes doesn't have to be dynamic, though; just the arguments passed to the trigger.)
Is it possible to set up PostgreSQL streaming replication so that there is a master server where I do all my "normal" writes, and a set of read replicas which I connect to almost entirely to do reads... but where I can also create triggers that run on the read replica only?  ie, this would move the CPU load of the trigger from the master to the potentially large number of replicas.  (I would potentially use pg_temp for the function as described at this answer.)
When I try this with, eg, Amazon RDS read replicas, any attempt to create even pg_temp.* functions on the read replica unsurprisingly fails with cannot execute CREATE FUNCTION in a read-only transaction, but maybe there's some other way to configure streaming replication so that this is possible?

A:
Is it possible to set up PostgreSQL streaming replication so that there is a master server where I do all my "normal" writes, and a set of read replicas which I connect to almost entirely to do reads... but where I can also create triggers that run on the read replica only?

No, it isn't. Streaming replication is done at the block level. It has no idea what statements changed which rows, where. It's also strictly read-only. Really strictly - you can't do anything that changes the system catalogs like pg_class or pg_proc even transiently.
You might want to look into Londiste. If you create a trigger then make it ENABLE REPLICA it can fire on writes replicated by Londiste from the master.
The BDR project can also be used for read-replicas. It doesn't yet support firing triggers on downstream row writes, but it's practical to implement, it just hasn't been a development priority.


text:
Q: Basilisk petrification in Harry Potter; what happens? In Harry Potter the fearsome Basilisk had the ability to instantly kill anyone unfortunate enough to directly glimpse its eyes. But in the event that you were to gaze indirectly into its eyes you would be afflicted with complete petrification.
In the world of science, petrification is

the process by which organic material is converted into stone through the replacement of the original material and the filling of the original pore spaces with minerals.

However, in the magical world of Harry Potter, I doubt that such a mundane process is what happens when caught by a Basilisk's stare.
So what then is it that happens to these petrified people?
Is there an actual physical change that takes place (taking on the physical aspects of stone: hardness, brittleness, coldness etc), or is the effect more psychosomatic (physically the person is fine, but they become so terrified that they are mentally locked into inaction)?

A: No, the body is most certainly NOT merely psychoanalytically inactive.
They are rigidly held in their position, for example Hermione's wrist curled around the note that Harry and Ron had to extricate from it when she was found.

A: First, let's examine what the books tell us.
In Chamber of Secrets chapter 9, Argus Filch describes his cat as "all stiff and frozen" when she is Petrified.
In chapter 10, Harry meets the Petrified Colin Creevey in the hospital wing.

Harry's stomach gave a horrible lurch.  Slowly and carefully, he raised himself a few inches so he could look at the statue on the bed.  A ray of moonlight lay accross its staring face.
It was Colin Creevey.  He eyes were wide and his hands were stuck up in front of him, holding his camera.
[…]
[…] Then Dumbledore leaned forward and prised the camera out of Colin's rigid grip.

In chapter 11, Harry finds two victims Petrified:

Justin Finch-Fletchey was lying on the floor, rigid and cold, a look of shock frozen on his face, his eyes staring blankly at the ceiling.  And that wasn't all.  Next to him was another figure, the strangest sight Harry had ever seen.
It was Nearly Headless Nick, no longer pearly-white and transparent, but black and smoky, floating immobile and horizontal, six inches off the floor.

In chapter 14, when Hermione and Penelope are petrified

Hermione lay utterly still, her eyes open and glassy.

In chapter 16, we learn a bit more when Harry and Ron visit the Petrified Hermione in the hospital wing.

Madam Pomfrey let them in, but reluctantly.
'There's just no point talking to a Petrified person,', she said, and they had to admit she was right when they'd taken their seat next to Hermione.  It was plain that Hermione didn't have the faintest inkling that she had visitors, and that they might just as well tell her bedside cabinet not to worry for all good it would do.
[…]
[…] Hermione's hand was clamped so tightly around the paper that Harry was sure he was going to tear it.

This suggests that Hermione wasn't aware of her surroundings, though I'm not sure how Harry would be able to tell this about a person who's magically paralyzed.  This appears different from the paralysis spell (Petrificius Totalus): when Malfoy casts that on Harry in Prince chapter 7, Harry is aware of his surroundings.  (Hermione casts the same spell on Neville in Stone chapter 16, but the situation is less clear.)
Based on the meeting with Hermione alone, I could imagine that the Basilisk's Petrification effect only paralyzes you on your entire body just like this spell, but Madam Pomfrey magically makes the victims unconscious for it would be very inconvenient to them to be paralyzed and conscious for months.  However, the description of Justin's attack makes it clear that Justin's body was cold, so the basilisk's stare can't be just an ordinary paralysis effect, there is a physical change.
In summary, a Petrified person becomes paralyzed on his whole body, including his head, his body becomes rigid and cold, and the person becomes unconscious.


text:
Q: What is wrong with this code (Simple LinkedList) So, I have been studied about linked list and had created this insert method.
private void insert(Node head, int data)
    {
        Node node = new Node(data);

        Node first = head;

        if(first == null)
        {
            head = node;
        }
        else
        {
            node.nextLink = first;
            head = node;
            //System.out.println(node.data);
        }
    }

and this traverse method
public void traversingLinkedList(Node head)
    {
        Node current = head;

        while(current != null)
        {
            int data = current.data;
            System.out.println(data);
            current = current.nextLink;
        }

    }

But it is not showing the node when I am inserting it.
The node data shows when I uncomment the print line in method insert.
for example,
LinkedList present is 10 -> 20 -> 30
after using insert(head,4)
I still get 10 -> 20 -> 30
though in the method insert when I uncheck the print method
it is showing first node data as 4
but when traversing it is not showing!
Why?

A: head is a local variable, so assigning values to it inside your insert(Node head, int data) doesn't affect the Node passed to the method.
If your insert method is part of some LinkedList class, that class should hold a reference to the head of the list, and insert should assign to that reference. In that case you won't need to pass Node head as argument to insert.
The only way you can modify the list by using the passed Node argument is if the method would change the nextLink of that Node.

A: When calling a method in Java, the variables are copied, not referenced. This means that in your case, the variable head inside the insert method is only local and its modifications will not be visible outside the method.
Thus, since you are inserting elements at the front, the new head after the insertion is the node you have created (not the previous one) and you need to return it to update the next calls. Moreover, you could simplify the code of your insert method since you will always update the head value and the only conditional part is if there are more elements in the list or not.
private Node insert(Node head, int data)
{
    Node node = new Node(data);

    if (head != null) {
        node.nextLink = head;
    }

    head = node;

    return head;
}

In this case your main method should look like:
// LinkedList 10->20->30
head = new Node(30);
head = insert(head, 20);
head = insert(head, 10);

// Add the new 4 head: 4->10->20->30
head = insert(head, 4);
// Traversing
traversingLinkedList(head);