text:
Q: Required Field conditional on button pressed I may be having a blonde moment here.
I have a data entry form with the usual "Save" and "Cancel" buttons.  In addition to these two I have another button "Approve".  If the user clicks the "Approve" button I have an additional field (Approver) that must hold data.  Is it possible to have a required field validator that is active on one button press but not another?

A: Yes This is possible :
You can Define multiple Validation group and decide witch group to validate depending on the clicked button, for that you should call javascript function onClientClient in order to validate the inputs :
See example bellow:
Triggering multiple validation groups with a single button

A: I think you will have to create a custom validator or just use javascript or jquery.
You can use the OnClientClick property of the buttons and add some javascript on there.
function CheckSave() {
  if (/*text1 is filled*/) return true;
}

function CheckApprove() {
  if (/*text1 is filled and text2 is filled*/) return true;
}

<asp:button id='btnSave' OnClientClick='return CheckSave()' OnClick='btnSave_Click' />
<asp:button id='btnApprove' OnClientClick='return CheckApprove()' OnClick='btnAprove_Click' />

you need the return in order for it to work


text:
Q: How do I reference a custom counter that shows the section number? I am trying to use the proof environment that comes with the amsthm package. And I would like the proof environment to be numbered, such as the theorem environment for the sake of adding a label, so I have added a custom counter in the preamble and changed the embedded \proofname in the proof environment. It all works well and displays my counters correctly in the text. However, when I try to reference my proofs, only the proof counter gets displayed instead of the full counter.
My code is below:
\documentclass[12pt,letterpaper]{article}

\usepackage{amsthm}
\usepackage{hyperref}

\newcounter{proof}[section] % adds a new counter for the proof environment included in the amsthm package that restarts for every new section
\renewcommand{\theproof}{\thesection.\arabic{proof}} % adds the section number before your proof counters
\renewcommand{\proofname}{\refstepcounter{proof}Proof \theproof} % the \proofname was embedded in your proof environment to output the italicized 'Proof', which is displayed at the beginning of every proof. This changes the \proofname to print 'Proof' and \theproof, which we defined as the section-proof counter above. This adds a counter to your proofs so you can hyperref them.

\newtheorem{definition}{Definition}[section]

\begin{document}
\section{One}
\begin{proof}
\label{p1}
this is proof one.
\end{proof}

This should reference proof \ref{p1}, which should display as proof 1.1.
\begin{definition}
\label{d1}
this is definition one.
\end{definition}
As we can see, this is not a problem when I reference definition \ref{d1}.

\section{Two}
\begin{proof}
\label{p2}
this is proof two.
\end{proof}
This should reference proof \ref{p2}, which should display as proof 2.1.

\begin{definition}
\label{d2}
this is definition two.
\end{definition}
As we can see, this is not a problem when I reference definition \ref{d2}.

\end{document}

But this is the result I get:

A: You can manually set the label value by defining \@currentlabel at the start of the proof environment.
Adding something to the start of a command can be done using the xpatch package which provides the \xpretocmd (xpatch pre to command) macro. This works the same for environments, an environment like proof defines two commands, one that is executed with \begin{proof} which is internally called \proof, and one that is executed with \end{proof} which is internally called \endproof.
Patching the environment allows you to use the normal \label command instead of a newly defined labelling command.
Because \@currentlabel has an @ symbol in the name the redefinition should be enclosed in \makeatletter and \makeatother.
MWE:
\documentclass[12pt,letterpaper]{article}

\usepackage{amsthm}
\usepackage{xpatch}
\usepackage{hyperref}
\makeatletter
\xpretocmd{\proof}{\def\@currentlabel{\theproof}}{}{}
\makeatother

\newcounter{proof}[section] % adds a new counter for the proof environment included in the amsthm package that restarts for every new section
\renewcommand{\theproof}{\thesection.\arabic{proof}} % adds the section number before your proof counters
\renewcommand{\proofname}{\refstepcounter{proof}Proof \theproof} % the \proofname was embedded in your proof environment to output the italicized 'Proof', which is displayed at the beginning of every proof. This changes the \proofname to print 'Proof' and \theproof, which we defined as the section-proof counter above. This adds a counter to your proofs so you can hyperref them.

\newtheorem{definition}{Definition}[section]

\begin{document}
\section{One}
\begin{proof}
\label{p1}
this is proof one.
\end{proof}

This should reference proof \ref{p1}, which should display as proof 1.1.
\begin{definition}
\label{d1}
this is definition one.
\end{definition}
As we can see, this is not a problem when I reference definition \ref{d1}.

\section{Two}
\begin{proof}
\label{p2}
this is proof two.
\end{proof}
This should reference proof \ref{p2}, which should display as proof 2.1.

\begin{definition}
\label{d2}
this is definition two.
\end{definition}
As we can see, this is not a problem when I reference definition \ref{d2}.

\end{document}

Result:

A: Your \refstepcounter is issued inside the optional argument to \item and the corresponding value of \@currentlabel gets forgotten as soon as \item is processed, so you actually get references to the section number. You can check it by clicking on the reference.
A possible solution is to patch \proof (the command executed upon entering the proof environment) to issue \refstepcounter after \trivlist and before \item.
\documentclass[12pt,letterpaper]{article}

\usepackage{amsthm}
\usepackage{xpatch}
\usepackage{hyperref}

\newcounter{proof}[section]
\renewcommand{\theproof}{\thesection.\arabic{proof}}
\renewcommand{\proofname}{Proof \theproof}

\xpatchcmd{\proof}{\trivlist}{\trivlist\refstepcounter{proof}}{}{}

\newtheorem{definition}{Definition}[section]

\begin{document}
\section{One}
\begin{proof}
\label{p1}
this is proof one.
\end{proof}

This should reference proof \ref{p1}, which should display as proof 1.1.
\begin{definition}
\label{d1}
this is definition one.
\end{definition}
As we can see, this is not a problem when I reference definition \ref{d1}.

\section{Two}
\begin{proof}
\label{p2}
this is proof two.
\end{proof}
This should reference proof \ref{p2}, which should display as proof 2.1.

\begin{definition}
\label{d2}
this is definition two.
\end{definition}
As we can see, this is not a problem when I reference definition \ref{d2}.

\end{document}

You can also define a proof* environment for unnumbered proofs by saving a copy of \proof before patching it.
\documentclass[12pt,letterpaper]{article}

\usepackage{amsthm}
\usepackage{xpatch}
\usepackage{hyperref}

% save \proof
\let\unnumberedproof\proof
\newenvironment{proof*}
 {\renewcommand\proofname{Proof}\unnumberedproof}
 {\endproof}

\newcounter{proof}[section]
\renewcommand{\theproof}{\thesection.\arabic{proof}}
\renewcommand{\proofname}{Proof \theproof}

\xpatchcmd{\proof}{\trivlist}{\trivlist\refstepcounter{proof}}{}{}

\newtheorem{definition}{Definition}[section]

\begin{document}
\section{One}
\begin{proof}
\label{p1}
this is proof one.
\end{proof}

This should reference proof \ref{p1}, which should display as proof 1.1.
\begin{definition}
\label{d1}
this is definition one.
\end{definition}
As we can see, this is not a problem when I reference definition \ref{d1}.

\section{Two}
\begin{proof}
\label{p2}
this is proof two.
\end{proof}
This should reference proof \ref{p2}, which should display as proof 2.1.

\begin{definition}
\label{d2}
this is definition two.
\end{definition}
As we can see, this is not a problem when I reference definition \ref{d2}.

\begin{proof*}
An unnumbered proof.
\end{proof*}

\end{document}

A: Here is an approach that works, but I am not sure what is going on behind the scenes. I adapted the accepted answer from this question, though copying it verbatim increased the counter proof once when the environment began, and once when the label was defined, resulting in offset numbering, so I just decreased the counter every time the label is called.
After you define the counter proof, add the the following line:
\newcommand{\prooflabel}[1]{\addtocounter{proof}{-1}\refstepcounter{proof}\label{#1}}

Then whenever you have a proof, instead of \label, use \prooflabel as below.
\section{One}
\begin{proof}
\prooflabel{p1}
this is proof one.
\end{proof}

This should reference proof \ref{p1}, which should display as proof 1.1.

This is the result:

Perhaps someone more knowledgeable than me can adjust the \prooflabel and other definitions so that there isn't this back and forth couting, but it seems to work as you would like it to work.

A: Looking at the code of the proof-environment reveals that \proofname is carried out only in case no optional argument is given. In this case \proofname gets carried out as part of the optional argument of a \trivlist's \item. Thus \proofname gets carried out within a local scope. \refstepcounter coming from carrying out \proofname will redefine \@currentlabel but that redefinition will also be restricted to
that local scope.
I strongly recommend not to redefine \proofname as packages and LaTeX-infrastructure rely on it holding only the words used for introducing a proof.
I suggest redefining the proof-environment so that default for the optional argument will not be \proofname but another macro which in turn does both call the unmodified \proofname and call \refstepcounter and afterwards "globalize" \@currentlabel.
If you do it this way, passing an optional argument to the proof-environment will still not trigger the incrementing of the counter.
You can use \proofname as optional argument in order to get unnumbered proofs as usual.
\documentclass[12pt,letterpaper]{article}
\usepackage{xpatch}
\usepackage{amsthm}
\usepackage{hyperref}

\makeatletter
\newcounter{proof}[section]%
\renewcommand{\theproof}{\thesection.\arabic{proof}}%
\DeclareRobustCommand\prooflabel{%
  \refstepcounter{proof}%
  \global\let\@currentlabel\@currentlabel
  \lowercase\expandafter{%
    \expandafter\protected@xdef
    \expandafter\@currentlabelname\expandafter{\proofname\protect\nobreakspace\theproof}%
  }%
  \proofname~\theproof
}%
\xpatchcmd{\proof}{\itshape}{\itshape\gdef\@currentlabelname{#1}\csname phantomsection\endcsname}{}{}%
\expandafter\def\expandafter\proof\expandafter{%
  \expandafter\@protected@testopt\expandafter\proof\csname\string\proof\endcsname{\prooflabel}%
}%
\DeclareRobustCommand\LcUcfork[1]{#1}
\makeatother

\newtheorem{definition}{Definition}[section]

\begin{document}

\section{One}
\begin{proof}
\label{p1.1}
This is proof one.
\end{proof}

\begin{proof}[\LcUcfork{M}y special proof]%
\label{special}%
This is my special proof.
\end{proof}

\begin{proof}[\proofname]%
This proof is not numbered.
\end{proof}

\begin{proof}
\label{p1.2}
This is proof two.
\end{proof}

This should reference proof \ref{p1.1}, which should display as proof 1.1.

This should reference \nameref{p1.1}, which should display as proof 1.1.

This should reference {\let\LcUcfork=\lowercase\nameref{special}}, which should display as my special proof.

\begin{definition}
\label{d1.1}
This is definition one.
\end{definition}
As we can see, this is not a problem when I reference definition \ref{d1.1}.

\section{Two}
\begin{proof}
\label{p2.1}
This is proof two.
\end{proof}
This should reference proof \ref{p2.1}, which should display as proof 2.1.

This should reference \nameref{p2.1}, which should display as proof 2.1.

\begin{definition}
\label{d2.1}
This is definition two.
\end{definition}
As we can see, this is not a problem when I reference definition \ref{d2.1}.

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use XSLT when xmlns attribute is present? I'm trying to use XSLT to transform an XML document into a CSV. The problem I'm running into is that having an "xmlns" attribute makes certain things difficult to impossible to work with.
Here is a simplified example of what works, first.
XML:

  B
  <c>
    <d>D1</d>
    <d>D2</d>
  </c>

XSL:
<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="utf-8"/>

<xsl:template match="/a">

    <xsl:for-each select="c/d">
        <xsl:value-of select="../../b"/>,<xsl:value-of select="."/>
        <xsl:text>
</xsl:text>
    </xsl:for-each>

</xsl:template>
</xsl:stylesheet>

results in the correct output
B,D1
B,D2

However, merely adding the xmlns attribute at the top

  B
  <c>
    <d>D1</d>
    <d>D2</d>
  </c>

results in the default behavior of just printing out the leaf node contents (which happens when no matching succeeds), rather than producing the CSV as intended.
I was able to get partial success like so
<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="utf-8"/>

<xsl:template match="*[local-name() = 'a']">

    <xsl:value-of select="*[local-name() = 'b']"/><xsl:text>
</xsl:text>

    <xsl:for-each select="*[local-name() = 'c/d']">
        <xsl:value-of select="."/>
        <xsl:text>
</xsl:text>
    </xsl:for-each>

</xsl:template>
</xsl:stylesheet>

however as the comment indicates the for-each doesn't match at all, this just prints "B".
I cannot change the XML. In theory I could use sed or something to remove the xmlns attribute, but I'd ideally like to avoid that as the input XML file is many gigabytes.
How can I adapt my simplified code to work when the xmlns attribute is present?

A: You need to declare the default namespace in your xslt. See this:
XSLT with XML source that has a default namespace set to xmlns


text:
Q: When is the derivative of $f(g(x))$ equal to $g(f'(x))$? By the chain rule, we know that the derivative of $f(g(x))$ is $f'(g(x))g'(x)$.

Question: When is the derivative of $f(g(x))$ equal to $g(f'(x))$?

Trivial solutions include the following:

*

*Let $f$ be any differentiable function and $g$ be the identity function ($g(x)=x$) or the zero function ($g(x)=0$).

*Let $f$ be any constant function and $g$ be any differentiable function that fixes zero.

On the other hand,  $f(x)=x^2$ and $g(x)=\sin x$ form a nontrivial solution (by the double angle formula for sine).
If $g(x)=x+a$, where $a$ is a constant, then $f'(x+a)=f'(x)+a$, so $f(x)=\frac{1}{2}x^2+bx+c$ would work for any two constants $b$ and $c$.
Finally, if $f(x)=mx+b$, where $m$ and $b$ are constants, then $mg'(x)=g(m)$, so $g'(x)=\frac{g(m)}{m}$ and $g(x)=\frac{g(m)}{m}x+c$ for some constant $c$. But this must in particular be true for $x=m$, so $c$ must be zero and $g(x)=nx$ would then work for any constant $n$.
But I do not know any other solutions. Can anyone help find one?
Note that $f$ may be replaced by any other function with the same derivative (i.e. differing from $f$ by a constant) without changing the validity of the equation, so we may assume without lost of generality that $f$ fixes zero (assuming, of course, that zero is in the domain of $f$).

A: Not an answer, but too long for a comment: Let $F(x) = f'(x)$. Then you are trying to solve $$F(g(x))g'(x) = g(F(x))$$
Let $g(x)$ be any differentiable function. This becomes a functional equation for $F(x)$. For $g(x) = x^n$, where $n > 0$, it is $$F\left(x^n\right)nx^{n-1} = F(x)^n$$
The solution (found using Mathematica) is $$F(x) = n^{\frac{1}{n-1}}x^{c - \frac{(n-1)\ln(\ln(x))}{n\ln(n)}}$$
$f(x)$ would then be the integral of $F(x)$.
I think it may be possible to show that given "sufficiently nice" $g$, an $F$ exists that solves the functional equation. I'm not sure how to go about this though.


text:
Q: How to map one album in Photos? In Photos, I can press the 'Places' button and see a map with all my photos.
How do I get the map to show the photos of only one album?

A: In Photos for Mac OS:

*

*Visit the album you'd like a Places map for.

*Click Show as memory at the top of the main window (located directly under the name of the album).

*Scroll down, and you'll see a Places map with only the photos of the active album.


text:
Q: Get CPU process usage history with log analytics I'm trying to build a query to use in log analytics that let's me see the history of CPU usage with every process being run on the server.
Something like this:
Example


text:
Q: Expressions like "They may be a-holes, but they are our a-holes" I remember coming across a line "They may be a-holes, but they are our a-holes." It's used to describe something you don't like, but also don't want others to take away. One example is big global corporations. Americans might hate them, but Americans also don't want to see them move out.
I googled this phrase and saw some sporadic usages. But it doesn't seem very popular. Is there a more popular version that expresses the same sentiment? I don't mind some vulgarity -- I think it actually makes this phrase rather powerful!

A: I may call my brother an A-hole but that privilege is not open to others. To them I will take exception and, within limits, a violent correction. That "They may be terrible people but they are our terrible people" tells the same story. We excuse though denigrate our own in comparison to other families/groups that have other terrible people. Our local limitations are somewhat more lenient than our global expectations. Except for Frank, the international A-hole.


text:
Q: SpringBootTest Integration Tests Fail (403 Forbidden) after upgrade from 1.3.2 to 1.5.3 I am in the process of upgrading several apps from SpringBoot 1.3.2.RELEASE to 1.5.3, using springCloudVersion = 'Dalston.RELEASE'
As a part of this upgrade process, the annotations in my existing integration tests changed:
Old, deprecated way:
@RunWith(SpringJUnit4ClassRunner.class)
@Unroll
@WebAppConfiguration
@WebIntegrationTest(randomPort = true)
@SpringApplicationConfiguration(classes = TokenServerApplication)

New, upgraded way:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = TokenServerApplication)
@EnableWebSecurity
@Unroll

This seems to compile just fine, but I noticed a variety of my tests began breaking, giving a 403 Forbidden response.
These tests that are failing should require sending a request with a valid 'x-auth-token' header. The response from my service should give a 403 "Not authenticated", but the message I am getting does not contain the "Not authenticated" message (it is more generic), and further, tests that should pass with valid tokens are also getting 403'd.
I am using the following to construct my requests:
@Autowired TestRestTemplate restTemplate

And the tests are all roughly set up the same:
  @Test
  void "test valid token"() {
    HttpHeaders headers = new HttpHeaders()
    headers.set("x-auth-token", tokenIngestExternal)
    HttpEntity<String> entity = new HttpEntity<String>(headers)
    ResponseEntity<Map> result = restTemplate.exchange("/authenticate", HttpMethod.GET, entity, Map.class)
    assertTrue(result.getStatusCode() == HttpStatus.OK)
    Map map = result.getBody()
    assertTrue map.get('iss').equals("A")
    assertTrue map.get('sub').equals("B")
    assertTrue map.get('aud').equals("C")
    assertTrue map.get('roles').equals("D")
  }

This same basic methodology worked just fine before the upgrade to 1.5.3 and using the latest annotations for the integration test.
Am I missing an annotation or parameter or something? What's the dealio?


text:
Q: Extra blank page on print I have an image to print on a web form. The image control loads the image dynamically at runtime. There is a print button on the page which gives me print to pdf option. The pdf which gets created generates an extra page along with the image to print
The size of the image is 649*602 in px.
the javascript code for print is as follows
 function printDiv(divName) {
            var title = document.title;
            document.title = '';
            var printContents = document.getElementById(divName).innerHTML;

            var originalContents = document.body.innerHTML;

            document.body.innerHTML = printContents;
            window.print();

            document.body.innerHTML = originalContents;
            document.title = title;
            return false;
        }

The aspx page contains the following

    <form id="form1" runat="server">

        <asp:Image ID="imgInstructionSheet" runat="server" />

        <asp:ImageButton runat="server" ID="imgBtnPrint" SkinID="Print" OnClientClick="return printDiv('divInstructions')"
            ToolTip="Print" />

            <%-- <asp:ImageButton runat="server" ID="imgBtnPrint" SkinID="Print" OnClientClick="return window.print();"
            ToolTip="Print" />--%>

        Display Instructions

                            For Proper Printout Follow The Instructions:

Click on File Menu Goto Page Setup.

In Page Setup Dialog Box.

Set Paper Size To Letter (8.5x11").

Set Left Margin as 0.5 and Right Margin as 0.5.

    </form>

Is there any way I can eliminate the extra blank page?
I tried reducing the image size but no effect.
the rendered html is
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>
    Instruction Sheet
</title>

<link href="../App_Themes/default/1.9.1-jquery-ui.css" type="text/css" rel="stylesheet" /><link href="../App_Themes/default/Default.css" type="text/css" rel="stylesheet" /><link href="../App_Themes/default/form-field-tooltip.css" type="text/css" rel="stylesheet" /><link href="../App_Themes/default/InquiryStyles.css" type="text/css" rel="stylesheet" /><link href="../App_Themes/default/iqbackoffice.css" type="text/css" rel="stylesheet" /><link href="../App_Themes/default/IQGLInputControl.css" type="text/css" rel="stylesheet" /><link href="../App_Themes/default/jquery.ui.autocomplete.css" type="text/css" rel="stylesheet" /><link href="../App_Themes/default/jquerydcss.css" type="text/css" rel="stylesheet" /><link href="../App_Themes/default/popup.css" type="text/css" rel="stylesheet" />

    <form name="form1" method="post" action="InstructionsSheet.aspx?CompanyId=evh&CheckRequestType=CHECKREQUESTFAX" id="form1">

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MjQwOTYzMTgPZBYCAgMPZBYCAgEPDxYCHghJbWFnZVVybAUqQ2hlY2tSZXF1ZXN0SW1hZ2UvQ2hlY2tSZXF1ZXN0SW5zdF92ZWcuanBnZGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFC2ltZ0J0blByaW50Ibf/odbg0lrXs/vlUgzr3pUnWxPgOvUSkGEiBBhsVNk=" />

    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAAIycRPb8aWzu8amhADzp9D7vxA7O73wp6e8dR9A7rKNQ6U+XW+JbgNalutolAAvvabl2zSBHocsK8wmZxrQUUtL" />

        <input type="image" name="imgBtnPrint" id="imgBtnPrint" title="Print" class="Buttons" onmouseout="this.src=window.location.protocol + '//' + window.location.host + '/' + 'ClientWeb/Images/Print_over.png';" onmouseover="this.src=window.location.protocol + '//' + window.location.host + '/' + 'ClientWeb/Images/Print_on.png';" onfocus="this.src=window.location.protocol + '//' + window.location.host + '/' + 'ClientWeb/Images/Print_on.png';" onblur="this.src=window.location.protocol + '//' + window.location.host + '/' + 'ClientWeb/Images/Print_over.png';" src="../Images/Print_over.png" alt="Print" onclick="return printDiv('divInstructions');" style="border-width:0px;" />

        Display Instructions

                            For Proper Printout Follow The Instructions:

Click on File Menu Goto Page Setup.

In Page Setup Dialog Box.

Set Paper Size To Letter (8.5x11").

Set Left Margin as 0.5 and Right Margin as 0.5.

    </form>


text:
Q: ПОМОГИТЕ. Неделю не могу решить вопрос обхода блоков Проблема следующая. Есть canvas который на заднем фоне расходится дымчатой краской при движении курсора, но при на ведении на блок, к примеру надпись, перестает работать, только вокруг.  Как сделать, чтобы игнорировать блок, т.е. чтобы краска продолжала следовать за мышкой позади блока непрерывно?
jsfiddle
HTML
    <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="main.css">
    <title>Document</title>

<canvas id="pretty-bg"></canvas>

Как обойти блок

CSS
#pretty-bg {
  position: absolute;
  width: 100%;
  height: 660px;
  top: 0;
  left: 0;
  z-index: 1;
}

.text-take {
  text-align: center;
  position: relative;
  z-index: 9;
  font-size: 80px;
}

JS
"use strict";const canvas=document.getElementById("pretty-bg");if(canvas){canvas.width=canvas.clientWidth,canvas.height=canvas.clientHeight;let e={SIM_RESOLUTION:128,DYE_RESOLUTION:512,DENSITY_DISSIPATION:.99,VELOCITY_DISSIPATION:.98,PRESSURE_DISSIPATION:.8,PRESSURE_ITERATIONS:20,CURL:20,SPLAT_RADIUS:.3,SHADING:!0,COLORFUL:!0,PAUSED:!1,BACK_COLOR:{r:0,g:0,b:0},TRANSPARENT:!0};function pointerPrototype(){this.id=-1,this.x=0,this.y=0,this.dx=0,this.dy=0,this.down=!1,this.moved=!1,this.color=[30,0,300]}let n=[],r=[];n.push(new pointerPrototype);const{gl:t,ext:i}=getWebGLContext(canvas);function getWebGLContext(e){const n={alpha:!0,depth:!1,stencil:!1,antialias:!1,preserveDrawingBuffer:!1};let r=e.getContext("webgl2",n);const t=!!r;let i,o;t||(r=e.getContext("webgl",n)||e.getContext("experimental-webgl",n)),t?(r.getExtension("EXT_color_buffer_float"),o=r.getExtension("OES_texture_float_linear")):(i=r.getExtension("OES_texture_half_float"),o=r.getExtension("OES_texture_half_float_linear")),r.clearColor(0,0,0,1);const a=t?r.HALF_FLOAT:i.HALF_FLOAT_OES;let u,v,l;return t?(u=getSupportedFormat(r,r.RGBA16F,r.RGBA,a),v=getSupportedFormat(r,r.RG16F,r.RG,a),l=getSupportedFormat(r,r.R16F,r.RED,a)):(u=getSupportedFormat(r,r.RGBA,r.RGBA,a),v=getSupportedFormat(r,r.RGBA,r.RGBA,a),l=getSupportedFormat(r,r.RGBA,r.RGBA,a)),{gl:r,ext:{formatRGBA:u,formatRG:v,formatR:l,halfFloatTexType:a,supportLinearFiltering:o}}}function getSupportedFormat(e,n,r,t){if(!supportRenderTextureFormat(e,n,r,t))switch(n){case e.R16F:return getSupportedFormat(e,e.RG16F,e.RG,t);case e.RG16F:return getSupportedFormat(e,e.RGBA16F,e.RGBA,t);default:return null}return{internalFormat:n,format:r}}function supportRenderTextureFormat(e,n,r,t){let i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,n,4,4,0,r,t,null);let o=e.createFramebuffer();return e.bindFramebuffer(e.FRAMEBUFFER,o),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,i,0),e.checkFramebufferStatus(e.FRAMEBUFFER)==e.FRAMEBUFFER_COMPLETE}function clamp01(e){return Math.min(Math.max(e,0),1)}function isMobile(){return/Mobi|Android/i.test(navigator.userAgent)}isMobile()&&(e.DYE_RESOLUTION=128,e.SHADING=!1),i.supportLinearFiltering||(e.SHADING=!1);class o{constructor(e,n){if(this.uniforms={},this.program=t.createProgram(),t.attachShader(this.program,e),t.attachShader(this.program,n),t.linkProgram(this.program),!t.getProgramParameter(this.program,t.LINK_STATUS))throw t.getProgramInfoLog(this.program);const r=t.getProgramParameter(this.program,t.ACTIVE_UNIFORMS);for(let e=0;e<r;e++){const n=t.getActiveUniform(this.program,e).name;this.uniforms[n]=t.getUniformLocation(this.program,n)}}bind(){t.useProgram(this.program)}}function compileShader(e,n){const r=t.createShader(e);if(t.shaderSource(r,n),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw t.getShaderInfoLog(r);return r}const a=compileShader(t.VERTEX_SHADER,"\n    precision highp float;\n\n    attribute vec2 aPosition;\n    varying vec2 vUv;\n    varying vec2 vL;\n    varying vec2 vR;\n    varying vec2 vT;\n    varying vec2 vB;\n    uniform vec2 texelSize;\n\n    void main () {\n        vUv = aPosition * 0.5 + 0.5;\n        vL = vUv - vec2(texelSize.x, 0.0);\n        vR = vUv + vec2(texelSize.x, 0.0);\n        vT = vUv + vec2(0.0, texelSize.y);\n        vB = vUv - vec2(0.0, texelSize.y);\n        gl_Position = vec4(aPosition, 0.0, 1.0);\n    }\n"),u=compileShader(t.FRAGMENT_SHADER,"\n    precision mediump float;\n    precision mediump sampler2D;\n\n    varying highp vec2 vUv;\n    uniform sampler2D uTexture;\n    uniform float value;\n\n    void main () {\n        gl_FragColor = value * texture2D(uTexture, vUv);\n    }\n"),v=compileShader(t.FRAGMENT_SHADER,"\n    precision mediump float;\n\n    uniform vec4 color;\n\n    void main () {\n        gl_FragColor = color;\n    }\n"),l=compileShader(t.FRAGMENT_SHADER,"\n    precision highp float;\n    precision highp sampler2D;\n\n    varying vec2 vUv;\n    uniform sampler2D uTexture;\n    uniform float aspectRatio;\n\n    #define SCALE 25.0\n\n    void main () {\n        vec2 uv = floor(vUv * SCALE * vec2(aspectRatio, 1.0));\n        float v = mod(uv.x + uv.y, 2.0);\n        v = v * 0.1 + 0.8;\n        gl_FragColor = vec4(vec3(v), 1.0);\n    }\n"),f=compileShader(t.FRAGMENT_SHADER,"\n    precision highp float;\n    precision highp sampler2D;\n\n    varying vec2 vUv;\n    uniform sampler2D uTexture;\n\n    void main () {\n        vec3 C = texture2D(uTexture, vUv).rgb;\n        float a = max(C.r, max(C.g, C.b));\n        gl_FragColor = vec4(C, a);\n    }\n"),c=compileShader(t.FRAGMENT_SHADER,"\n    precision highp float;\n    precision highp sampler2D;\n\n    varying vec2 vUv;\n    varying vec2 vL;\n    varying vec2 vR;\n    varying vec2 vT;\n    varying vec2 vB;\n    uniform sampler2D uTexture;\n    uniform vec2 texelSize;\n\n    void main () {\n        vec3 L = texture2D(uTexture, vL).rgb;\n        vec3 R = texture2D(uTexture, vR).rgb;\n        vec3 T = texture2D(uTexture, vT).rgb;\n        vec3 B = texture2D(uTexture, vB).rgb;\n        vec3 C = texture2D(uTexture, vUv).rgb;\n\n        float dx = length(R) - length(L);\n        float dy = length(T) - length(B);\n\n        vec3 n = normalize(vec3(dx, dy, length(texelSize)));\n        vec3 l = vec3(0.0, 0.0, 1.0);\n\n        float diffuse = clamp(dot(n, l) + 0.7, 0.7, 1.0);\n        C.rgb *= diffuse;\n\n        float a = max(C.r, max(C.g, C.b));\n        gl_FragColor = vec4(C, a);\n    }\n"),s=compileShader(t.FRAGMENT_SHADER,"\n    precision highp float;\n    precision highp sampler2D;\n\n    varying vec2 vUv;\n    uniform sampler2D uTarget;\n    uniform float aspectRatio;\n    uniform vec3 color;\n    uniform vec2 point;\n    uniform float radius;\n\n    void main () {\n        vec2 p = vUv - point.xy;\n        p.x *= aspectRatio;\n        vec3 splat = exp(-dot(p, p) / radius) * color;\n        vec3 base = texture2D(uTarget, vUv).xyz;\n        gl_FragColor = vec4(base + splat, 1.0);\n    }\n"),m=compileShader(t.FRAGMENT_SHADER,"\n    precision highp float;\n    precision highp sampler2D;\n\n    varying vec2 vUv;\n    uniform sampler2D uVelocity;\n    uniform sampler2D uSource;\n    uniform vec2 texelSize;\n    uniform vec2 dyeTexelSize;\n    uniform float dt;\n    uniform float dissipation;\n\n    vec4 bilerp (sampler2D sam, vec2 uv, vec2 tsize) {\n        vec2 st = uv / tsize - 0.5;\n\n        vec2 iuv = floor(st);\n        vec2 fuv = fract(st);\n\n        vec4 a = texture2D(sam, (iuv + vec2(0.5, 0.5)) * tsize);\n        vec4 b = texture2D(sam, (iuv + vec2(1.5, 0.5)) * tsize);\n        vec4 c = texture2D(sam, (iuv + vec2(0.5, 1.5)) * tsize);\n        vec4 d = texture2D(sam, (iuv + vec2(1.5, 1.5)) * tsize);\n\n        return mix(mix(a, b, fuv.x), mix(c, d, fuv.x), fuv.y);\n    }\n\n    void main () {\n        vec2 coord = vUv - dt * bilerp(uVelocity, vUv, texelSize).xy * texelSize;\n        gl_FragColor = dissipation * bilerp(uSource, coord, dyeTexelSize);\n        gl_FragColor.a = 1.0;\n    }\n"),d=compileShader(t.FRAGMENT_SHADER,"\n    precision highp float;\n    precision highp sampler2D;\n\n    varying vec2 vUv;\n    uniform sampler2D uVelocity;\n    uniform sampler2D uSource;\n    uniform vec2 texelSize;\n    uniform float dt;\n    uniform float dissipation;\n\n    void main () {\n        vec2 coord = vUv - dt * texture2D(uVelocity, vUv).xy * texelSize;\n        gl_FragColor = dissipation * texture2D(uSource, coord);\n        gl_FragColor.a = 1.0;\n    }\n"),g=compileShader(t.FRAGMENT_SHADER,"\n    precision mediump float;\n    precision mediump sampler2D;\n\n    varying highp vec2 vUv;\n    varying highp vec2 vL;\n    varying highp vec2 vR;\n    varying highp vec2 vT;\n    varying highp vec2 vB;\n    uniform sampler2D uVelocity;\n\n    void main () {\n        float L = texture2D(uVelocity, vL).x;\n        float R = texture2D(uVelocity, vR).x;\n        float T = texture2D(uVelocity, vT).y;\n        float B = texture2D(uVelocity, vB).y;\n\n        vec2 C = texture2D(uVelocity, vUv).xy;\n        if (vL.x < 0.0) { L = -C.x; }\n        if (vR.x > 1.0) { R = -C.x; }\n        if (vT.y > 1.0) { T = -C.y; }\n        if (vB.y < 0.0) { B = -C.y; }\n\n        float div = 0.5 * (R - L + T - B);\n        gl_FragColor = vec4(div, 0.0, 0.0, 1.0);\n    }\n"),p=compileShader(t.FRAGMENT_SHADER,"\n    precision mediump float;\n    precision mediump sampler2D;\n\n    varying highp vec2 vUv;\n    varying highp vec2 vL;\n    varying highp vec2 vR;\n    varying highp vec2 vT;\n    varying highp vec2 vB;\n    uniform sampler2D uVelocity;\n\n    void main () {\n        float L = texture2D(uVelocity, vL).y;\n        float R = texture2D(uVelocity, vR).y;\n        float T = texture2D(uVelocity, vT).x;\n        float B = texture2D(uVelocity, vB).x;\n        float vorticity = R - L - T + B;\n        gl_FragColor = vec4(0.5 * vorticity, 0.0, 0.0, 1.0);\n    }\n"),h=compileShader(t.FRAGMENT_SHADER,"\n    precision highp float;\n    precision highp sampler2D;\n\n    varying vec2 vUv;\n    varying vec2 vL;\n    varying vec2 vR;\n    varying vec2 vT;\n    varying vec2 vB;\n    uniform sampler2D uVelocity;\n    uniform sampler2D uCurl;\n    uniform float curl;\n    uniform float dt;\n\n    void main () {\n        float L = texture2D(uCurl, vL).x;\n        float R = texture2D(uCurl, vR).x;\n        float T = texture2D(uCurl, vT).x;\n        float B = texture2D(uCurl, vB).x;\n        float C = texture2D(uCurl, vUv).x;\n\n        vec2 force = 0.5 * vec2(abs(T) - abs(B), abs(R) - abs(L));\n        force /= length(force) + 0.0001;\n        force *= curl * C;\n        force.y *= -1.0;\n\n        vec2 vel = texture2D(uVelocity, vUv).xy;\n        gl_FragColor = vec4(vel + force * dt, 0.0, 1.0);\n    }\n"),T=compileShader(t.FRAGMENT_SHADER,"\n    precision mediump float;\n    precision mediump sampler2D;\n\n    varying highp vec2 vUv;\n    varying highp vec2 vL;\n    varying highp vec2 vR;\n    varying highp vec2 vT;\n    varying highp vec2 vB;\n    uniform sampler2D uPressure;\n    uniform sampler2D uDivergence;\n\n    vec2 boundary (vec2 uv) {\n        return uv;\n        // uncomment if you use wrap or repeat texture mode\n        // uv = min(max(uv, 0.0), 1.0);\n        // return uv;\n    }\n\n    void main () {\n        float L = texture2D(uPressure, boundary(vL)).x;\n        float R = texture2D(uPressure, boundary(vR)).x;\n        float T = texture2D(uPressure, boundary(vT)).x;\n        float B = texture2D(uPressure, boundary(vB)).x;\n        float C = texture2D(uPressure, vUv).x;\n        float divergence = texture2D(uDivergence, vUv).x;\n        float pressure = (L + R + B + T - divergence) * 0.25;\n        gl_FragColor = vec4(pressure, 0.0, 0.0, 1.0);\n    }\n"),R=compileShader(t.FRAGMENT_SHADER,"\n    precision mediump float;\n    precision mediump sampler2D;\n\n    varying highp vec2 vUv;\n    varying highp vec2 vL;\n    varying highp vec2 vR;\n    varying highp vec2 vT;\n    varying highp vec2 vB;\n    uniform sampler2D uPressure;\n    uniform sampler2D uVelocity;\n\n    vec2 boundary (vec2 uv) {\n        return uv;\n        // uv = min(max(uv, 0.0), 1.0);\n        // return uv;\n    }\n\n    void main () {\n        float L = texture2D(uPressure, boundary(vL)).x;\n        float R = texture2D(uPressure, boundary(vR)).x;\n        float T = texture2D(uPressure, boundary(vT)).x;\n        float B = texture2D(uPressure, boundary(vB)).x;\n        vec2 velocity = texture2D(uVelocity, vUv).xy;\n        velocity.xy -= vec2(R - L, T - B);\n        gl_FragColor = vec4(velocity, 0.0, 1.0);\n    }\n"),x=(()=>(t.bindBuffer(t.ARRAY_BUFFER,t.createBuffer()),t.bufferData(t.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,t.createBuffer()),t.bufferData(t.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,0,2,3]),t.STATIC_DRAW),t.vertexAttribPointer(0,2,t.FLOAT,!1,0,0),t.enableVertexAttribArray(0),e=>{t.bindFramebuffer(t.FRAMEBUFFER,e),t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)}))();let E,S,D,y,A,_,F,b,U;const L=new o(a,u),w=new o(a,v),C=new o(a,l),I=new o(a,f),B=new o(a,c),P=new o(a,s),N=new o(a,i.supportLinearFiltering?d:m),O=new o(a,g),M=new o(a,p),G=new o(a,h),X=new o(a,T),z=new o(a,R);function initFramebuffers(){let n=getResolution(e.SIM_RESOLUTION),r=getResolution(e.DYE_RESOLUTION);E=n.width,S=n.height,D=r.width,y=r.height;const o=i.halfFloatTexType,a=i.formatRGBA,u=i.formatRG,v=i.formatR;A=createDoubleFBO(2,D,y,a.internalFormat,a.format,o,i.supportLinearFiltering?t.LINEAR:t.NEAREST),_=createDoubleFBO(0,E,S,u.internalFormat,u.format,o,i.supportLinearFiltering?t.LINEAR:t.NEAREST),F=createFBO(4,E,S,v.internalFormat,v.format,o,t.NEAREST),b=createFBO(5,E,S,v.internalFormat,v.format,o,t.NEAREST),U=createDoubleFBO(6,E,S,v.internalFormat,v.format,o,t.NEAREST)}function getResolution(e){let n=t.drawingBufferWidth/t.drawingBufferHeight;n<1&&(n=1/n);let r=Math.round(e*n),i=Math.round(e);return t.drawingBufferWidth>t.drawingBufferHeight?{width:r,height:i}:{width:i,height:r}}function createFBO(e,n,r,i,o,a,u){t.activeTexture(t.TEXTURE0+e);let v=t.createTexture();t.bindTexture(t.TEXTURE_2D,v),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,u),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,u),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texImage2D(t.TEXTURE_2D,0,i,n,r,0,o,a,null);let l=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,l),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,v,0),t.viewport(0,0,n,r),t.clear(t.COLOR_BUFFER_BIT),{texture:v,fbo:l,texId:e}}function createDoubleFBO(e,n,r,t,i,o,a){let u=createFBO(e,n,r,t,i,o,a),v=createFBO(e+1,n,r,t,i,o,a);return{get read(){return u},get write(){return v},swap(){let e=u;u=v,v=e}}}initFramebuffers();let H=Date.now();function update(){resizeCanvas(),input(),e.PAUSED||step(.016),render(null),requestAnimationFrame(update)}function input(){r.length>0&&multipleSplats(r.pop());for(let e=0;e<n.length;e++){const r=n[e];r.moved&&(splat(r.x,r.y,r.dx,r.dy,r.color),r.moved=!1)}if(e.COLORFUL&&H+100<Date.now()){H=Date.now();for(let e=0;e<n.length;e++){n[e].color=generateColor()}}}function step(n){t.disable(t.BLEND),t.viewport(0,0,E,S),M.bind(),t.uniform2f(M.uniforms.texelSize,1/E,1/S),t.uniform1i(M.uniforms.uVelocity,_.read.texId),x(b.fbo),G.bind(),t.uniform2f(G.uniforms.texelSize,1/E,1/S),t.uniform1i(G.uniforms.uVelocity,_.read.texId),t.uniform1i(G.uniforms.uCurl,b.texId),t.uniform1f(G.uniforms.curl,e.CURL),t.uniform1f(G.uniforms.dt,n),x(_.write.fbo),_.swap(),O.bind(),t.uniform2f(O.uniforms.texelSize,1/E,1/S),t.uniform1i(O.uniforms.uVelocity,_.read.texId),x(F.fbo),L.bind();let r=U.read.texId;t.activeTexture(t.TEXTURE0+r),t.bindTexture(t.TEXTURE_2D,U.read.texture),t.uniform1i(L.uniforms.uTexture,r),t.uniform1f(L.uniforms.value,e.PRESSURE_DISSIPATION),x(U.write.fbo),U.swap(),X.bind(),t.uniform2f(X.uniforms.texelSize,1/E,1/S),t.uniform1i(X.uniforms.uDivergence,F.texId),r=U.read.texId,t.uniform1i(X.uniforms.uPressure,r),t.activeTexture(t.TEXTURE0+r);for(let n=0;n<e.PRESSURE_ITERATIONS;n++)t.bindTexture(t.TEXTURE_2D,U.read.texture),x(U.write.fbo),U.swap();z.bind(),t.uniform2f(z.uniforms.texelSize,1/E,1/S),t.uniform1i(z.uniforms.uPressure,U.read.texId),t.uniform1i(z.uniforms.uVelocity,_.read.texId),x(_.write.fbo),_.swap(),N.bind(),t.uniform2f(N.uniforms.texelSize,1/E,1/S),i.supportLinearFiltering||t.uniform2f(N.uniforms.dyeTexelSize,1/E,1/S),t.uniform1i(N.uniforms.uVelocity,_.read.texId),t.uniform1i(N.uniforms.uSource,_.read.texId),t.uniform1f(N.uniforms.dt,n),t.uniform1f(N.uniforms.dissipation,e.VELOCITY_DISSIPATION),x(_.write.fbo),_.swap(),t.viewport(0,0,D,y),i.supportLinearFiltering||t.uniform2f(N.uniforms.dyeTexelSize,1/D,1/y),t.uniform1i(N.uniforms.uVelocity,_.read.texId),t.uniform1i(N.uniforms.uSource,A.read.texId),t.uniform1f(N.uniforms.dissipation,e.DENSITY_DISSIPATION),x(A.write.fbo),A.swap()}function render(n){null!=n&&e.TRANSPARENT?t.disable(t.BLEND):(t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.enable(t.BLEND));let r=null==n?t.drawingBufferWidth:D,i=null==n?t.drawingBufferHeight:y;if(t.viewport(0,0,r,i),!e.TRANSPARENT){w.bind();let r=e.BACK_COLOR;t.uniform4f(w.uniforms.color,r.r/255,r.g/255,r.b/255,1),x(n)}null==n&&e.TRANSPARENT&&C.bind(),e.SHADING?(B.bind(),t.uniform2f(B.uniforms.texelSize,1/r,1/i),t.uniform1i(B.uniforms.uTexture,A.read.texId)):(I.bind(),t.uniform1i(I.uniforms.uTexture,A.read.texId)),x(n)}function splat(n,r,i,o,a){t.viewport(0,0,E,S),P.bind(),t.uniform1i(P.uniforms.uTarget,_.read.texId),t.uniform1f(P.uniforms.aspectRatio,canvas.width/canvas.height),t.uniform2f(P.uniforms.point,n/canvas.width,1-r/canvas.height),t.uniform3f(P.uniforms.color,i,-o,1),t.uniform1f(P.uniforms.radius,e.SPLAT_RADIUS/100),x(_.write.fbo),_.swap(),t.viewport(0,0,D,y),t.uniform1i(P.uniforms.uTarget,A.read.texId),t.uniform3f(P.uniforms.color,a.r,a.g,a.b),x(A.write.fbo),A.swap()}function multipleSplats(e,n=!1){for(let a=0;a<e;a++){const e=generateColor();e.r*=10,e.g*=10,e.b*=10;var r=canvas.width*Math.random(),t=canvas.height*Math.random(),i=1e3*(Math.random()-.5),o=1e3*(Math.random()-.5);n&&(r=canvas.width/2,t=canvas.height/2,i=1e3*(Math.random()-.5),o=1e3*(Math.random()-.5)),splat(r,t,i,o,e)}}function resizeCanvas(){canvas.width==canvas.clientWidth&&canvas.height==canvas.clientHeight||(canvas.width=canvas.clientWidth,canvas.height=canvas.clientHeight,initFramebuffers())}update();var my_dx=0,my_dy=0,my_color=generateColor();function generateColor(){let e=HSVtoRGB(Math.random(),1,1);return e.r*=.15,e.g*=.15,e.b*=.15,e}function getRandomInt(e,n){return e=Math.ceil(e),n=Math.floor(n),Math.floor(Math.random()*(n-e+1))+e}function HSVtoRGB(e,n,r){let t,i,o,a,u,v,l,f;switch(v=r*(1-n),l=r*(1-(u=6*e-(a=Math.floor(6*e)))*n),f=r*(1-(1-u)*n),a%6){case 0:t=r,i=f,o=v;break;case 1:t=l,i=r,o=v;break;case 2:t=v,i=r,o=f;break;case 3:t=v,i=l,o=r;break;case 4:t=f,i=v,o=r;break;case 5:t=r,i=v,o=l}return{r:t,g:i,b:o}}canvas.addEventListener("mousemove",e=>{splat(e.offsetX,e.offsetY,5*(e.offsetX-my_dx),5*(e.offsetY-my_dy),my_color),my_dx=e.offsetX,my_dy=e.offsetY}),setInterval(function(){my_color=generateColor()},500),canvas.addEventListener("touchmove",e=>{e.preventDefault();const r=e.targetTouches;for(let e=0;e<r.length;e++){let t=n[e];t.moved=t.down,t.dx=8*(r[e].pageX-t.x),t.dy=8*(r[e].pageY-t.y),t.x=r[e].pageX,t.y=r[e].pageY}},!1),canvas.addEventListener("touchstart",e=>{e.preventDefault();const r=e.targetTouches;for(let e=0;e<r.length;e++)e>=n.length&&n.push(new pointerPrototype),n[e].id=r[e].identifier,n[e].down=!0,n[e].x=r[e].pageX,n[e].y=r[e].pageY,n[e].color=generateColor()}),window.addEventListener("mouseup",()=>{n[0].down=!1}),window.addEventListener("touchend",e=>{const r=e.changedTouches;for(let e=0;e<r.length;e++)for(let t=0;t<n.length;t++)r[e].identifier==n[t].id&&(n[t].down=!1)}),window.addEventListener("keydown",n=>{"p"===n.key&&(e.PAUSED=!e.PAUSED)})}

A: .text-take {
  text-align: center;
  position: relative;
  z-index: 9;
  font-size: 80px;
  pointer-events: none;  <---
}


text:
Q: Swift: Why aren't my UITextFieldDelegate methods being called? I am trying to programmatically create a UITextView and create a delegate to handle the events. I am able to create add and the UITextView just fine, but none of the UITextFieldDelegate methods are bing added.
Why would this be?
    let myTextField = UITextField()
    myTextField.frame = CGRect(x:0, y: 100, width: 300, height: 30)
    myTextField.text = "Example Text"

    class MyTextFieldDelegate : NSObject, UITextFieldDelegate {
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            // Hide the keyboard.
            print("should return!\n")
            textField.resignFirstResponder()
            return true
        }

        func textFieldDidEndEditing(_ textField: UITextField) {
            print("yay!\n")
            print(textField.text! + "\n")
        }

        func textFieldDidBeginEditing(_ textField: UITextField) {
            print("yay begin!\n")
            print(textField.text! + "\n")
        }

    }

    let myTextFieldDelegate = MyTextFieldDelegate()
    myTextField.delegate = myTextFieldDelegate
    scrollView.addSubview(myTextField)

A: In UITextField, delegate is declared as a weak property.
weak var delegate: UITextFieldDelegate? { get set }

This means that it doesn't retain the delegate instance and will be set to nil when the delegate is freed.
You are creating the delegate and assigning it to a local variable myTextFieldDelegate.  That variable will be freed at the end of the function, so even though you assigned myTextFieldDelegate to the myTextField.delegate, it is freed and myTextField.delegate gets set to nil because it is weak.
To fix this, create a property in your ViewController to hold the delegate object:
var myTextFieldDelegate: MyTextFieldDelegate?

A: because no one retains the myTextfieldVariable... one way would be a to have an instance variable to keep a strong reference to it

A: By convention, a delegate reference is weak. That prevents a retain cycle.
Thus, when you say
myTextField.delegate = myTextFieldDelegate

The text field does NOT hold an owning reference to the delegate.
If your code the creates the myDelegate object is inside a method:
func someFunction() {
    let myTextFieldDelegate = MyTextFieldDelegate()
    myTextField.delegate = myTextFieldDelegate
    scrollView.addSubview(myTextField)
}

Then the variable myTextFieldDelegate holds a strong reference to your newly created MyTextFieldDelegate object. However, the variable myTextFieldDelegate goes out of scope as soon as the function returns.
There are no longer any strong references to the MyTextFieldDelegate object, and so it gets deallocated.
as vacawama suggests in his comment, you need your view controller to have an instance variable that holds a strong reference:
class MyViewController: UIViewController {

  //myTextFieldDelegate is now an instance variable.
  //It will hold a strong reference.
  var myTextFieldDelegate: MyTextFieldDelegate?

  func someFunction() {
      myTextFieldDelegate = MyTextFieldDelegate()
      myTextField.delegate = myTextFieldDelegate
      scrollView.addSubview(myTextField)
  }
}


text:
Q: Imported Workflow Error -Path needs to point to valid I imported a SharePoint Designer 2013 workflow into Visual Studio 2013. Once imported I got this error on all my activities Path needs to point to valid.
Anyone know how to fix this?


text:
Q: Check if multiple dates are the same in foreach I have an "Events" table in MySQL :
EventsDate('id','event','start_date','end_date')
I'd like to check if multiple events have the same start date to show it differently in my HTML template.
My SQL request is :
SELECT * FROM EVENTSDATE where event='$id' and  start_date>='$today' order by start_date asc
Now my foreach :
foreach ($upcomingDates as $value) { //$upcoming is the array with my sql request

        }

How can I say : "if you find two rows with the same start_date, echo something"

A: I have a slightly different approach.
// Array to contain all values
$container = array();

// Loop through your existing array
foreach ($upcomingDates as $key => $value) {
    // Check if the value is already in the container array
    // If this is the case, its a duplicate.
    if (array_key_exists($value['start_date'], $container)) {
        $container[$value['start_date']]++;
        echo $value.' is a duplicate with key '.$key;
    }

    // Add each value to the array
    $container[$value['start_date']] = 1;
}

Another method is to use array_count_values()
foreach(array_count_values($upcomingDates) as $value => $c) {
    if ($c > 1) {
        echo $value.' is a duplicate';
    }
}

Note that the second option won't work if your $upcomingDates is an array of arrays.

A: You can make an empty array before the for loop, and add each value in as a key. Then, on each iteration you can check that array for the key, like so:
$values = [];
foreach ($upcomingDates as $value) { //$upcoming is the array with my sql request
    if(isset($values[$value])) //duplicate value found
        //do something here
    $values[$value] = 1;
}

A: Since you're ordering your events by start_date:
for ($i = 0, $length = count($upcomingDates); $i < $length; $i++) {
    $date = $upcomingDates[$i];

    if (isset($upcomingDates[$i + 1]) &&
        $upcomingDates[$i + 1]['start_date'] == $date['state_date']) {
        echo 'this and the next date are equal';
    }
}

A: Try out GROUP BY
look here: GROUP BY

A: if you want to find duplicates, then you can directly get it from database
ex.
SELECT * FROM EVENTSDATE where event='$id' and  start_date>='$today' GROUP BY start_date having count(start_date) > 1 order by start_date asc

or you can find duplicates from resulting array
return only duplicated entries from an array


text:
Q: Final speed of a two block system Suppose a large block $M$ is moving in a smooth surface with speed $v_o$. Then a smaller block $m$ is carefully placed on it. Find the final speed
I tried two methods which gave two different answers

*

*Kinetic energy conservation (Assuming no heat loss)

*Linear momentum conservation, since net force on the system is zero.

Kinetic energy:
Initially smaller block $m$ is at rest, block $M$ has speed $v_o$
Finally both move with speed $v$
$$\frac{1}{2}M v_o^2 = \frac{1}{2}(M+m) v^2$$
$$v=\sqrt{\frac{M}{M+m}}v_o$$
Linear momentum:
$$Mv_o=(M+m)v$$
$$v=\frac{M}{M+m}v_o$$
What did I do wrong to have two different results?

A: Why would you assume that kinetic energy was conserved? If the blocks stick together and move with a final speed of $v$, it follows naturally that there was friction involved between the two blocks. The internal energy of the system would increase (by a magnitude $f_kd$) becuase there is an increase in temperature of the two blocks (This effect is not negligible ; neglecting it is equivalent to assuming that the friction was absent, and consequently the block wouldn't stick to it)
This does not mean that the conservation of energy is violated. You will have to include the transfer of energy by heat and simply kinetic energy alone is not conserved. This however is impossible to calculate from the information given
The isolated system for momentum only works in the x direction because there are no external forces acting in the x direction:

*

*Friction was internal to the system

*The only external force was possibly while putting the upper block on the lower one. It acts in the y-direction and will not affect the momentum in the x direction.

Hope this helps


text:
Q: accessing uncleaned form data in form.py in django using clean() method My question may be uncleared. So please read example also. I am using python 3.4 and django 1.7
I am receiving a foreign key from a form selection field. Uncleaned data gives me id of foreign element but cleaned data gives me the str() i.e. name of foreign element.
I want foreign element's object to verify its another property by comparing with form's another cleaned data.
For example, I have a Institute model which contains a private_key( CharField ).
Now, I have a teacher model which contains Institute as ForeignKey and need to verify that private_key during registration.
NOTE: private_key is the variable name of type CharField
In form for registration for teacher, Institute is coming as ForeignKey along with a Charfield which contains private_key input given by user.
I have to check that user's private_key input and private_key stored in selected Institute's model.If they are not same then raise "invalid private key" error.
I am using clean() method in form.py (in the class in which I have customize registration form ). But there, I have cleaned data only. Clean data gives me name of the institute instead of id of institute.
How can do it?
If my question is not good than please give answer/comment with reason instead of only down voating it.

A: If you use ModelForm, then you should directly get the object which is related by the foreignkey. So what you can do in cleaned data is:
def clean(self):
    p_key= self.cleaned_data['private_key']
    institute= self.cleaned_data['institute']
    if p_key == institute.private_key :
        return super().clean()
    else:
        raise ValidationError('Invalid key')

If you are using Form, then you should get institute id in your cleaned data.


text:
Q: ClassCastException: uirepeat index in setting the boolean array value jsf The array size is depend on the student size on runtinme. I am able to display the boolean effectively on the selectBooleanCheckbox in JSF based on the array boolean. However, in setting the value, the ClassCastException occur.
java.lang.ClassCastException
    at javax.el.ArrayELResolver.setValue(ArrayELResolver.java:260)
In Managed Bean:
enrollarr = new boolean[this.student.size()];

 public boolean[] getEnrollarr() {
    return enrollarr;
}

public void setEnrollarr(boolean[] enrollarr) {
    this.enrollarr = enrollarr;
}

In JSF:
    <ui:repeat var="value" value="#{adminController.student}" varStatus="myvar" >

                    #{value.name}
                    #{value.TP}
                    #{value.gender}
                    <h:selectBooleanCheckbox value="#{adminController.enrollarr[myvar.index]}" />

    </ui:repeat>

A: You got some different Problems in your question.
First of all: The size of an array cant never be set at runtime. An array has to allocate memory before runtime. This means your:
 enrollarr = new boolean[this.student.size()];

will never work. You try to allocate memory during your runtime.
For this case i suggest to use an ArrayList an fill it with booleans like that.
 List<boolean> enrollList = new ArrayList<>;

..and add vaules with his funtion.
enrollList.add(new boolean(true));

This maybe won't avoid the classCast case.
So second: I guess your class cast is thrown here:
<h:selectBooleanCheckbox value="#{adminController.enrollarr[myvar.index]}" />

You try to call adminController.(get/set)enrollarr[myvar.index]... But this function doesnt exists.
"Translated" the frontEnd tries to call adminController.setEnrollarr(true) and as we can see: there is no function like .setEnrollarr(boolean) only
.setEnrollarr(boolean[])].
Third: But in general i think you construction is a little bit confused. It would be much easier to move you enroll- boolean to the Student class. Then you can call it like the other varibles:
 <ui:repeat var="value" value="#{adminController.student}" varStatus="myvar" >

                #{value.name}
                #{value.TP}
                #{value.gender}
                <h:selectBooleanCheckbox value="#{value.enroll}" />

</ui:repeat>

And here the addtion to your Stundent class. Be aware: Boolean getter start with "is".
 public class Student{

    public boolean enroll;

    public boolean isEnroll() {
        return enroll;
    }

    public void setEnroll(boolean enroll) {
        this.enroll = enroll;
    }

 }

Hope my answear could bring some clearification and helped you to go further!


text:
Q: Disks not appearing in Debian installer? I'm working with the latest Debian Stretch netboot.
No disks appear in the partition manager. If I go into tty2 and run lspci (lsblk is not available in the Debian installer), the disk doesn't appear at all. The disk appears in BIOS and is bootable, it simply isn't recognized by the Debian installer.
Of the three identical machines I've tried this on, one produced a bootable install the first time - but when I tried again without changing anything, it presented this problem. The other two never made it that far.
What is causing this, and how do I fix it?

A: I figured it out. For whatever reason the Stretch installer (or my preseed, but I haven't changed anything regarding disks or partitioning from my Jessie preseed, which does not have this problem) is skipping the "Detect Disks" step, so of course none show up for partitioning.
When the partitioner comes up with no disks, press TAB to select "Go Back", then select the "Detect Disks" step. It will then detect the disk and allow you to partition as normal.


text:
Q: Why isn't this code compiling? I'm writing a method to generate a DataTable taking as datasource a generic IEnumerable. I am trying to set a default value on the field if theres no value, with the code below:
private void createTable<T>(IEnumerable<T> MyCollection, DataTable tabela)
        {
            Type tipo = typeof(T);

            foreach (var item in tipo.GetFields() )
            {
                tabela.Columns.Add(new DataColumn(item.Name, item.FieldType));
            }

            foreach (Pessoa recordOnEnumerable in ListaPessoa.listaPessoas)
            {
                DataRow linha = tabela.NewRow();

                foreach (FieldInfo itemField in tipo.GetFields())
                {
                    Type typeAux = itemField.GetType();

                    linha[itemField.Name] =
                        itemField.GetValue(recordOnEnumerable) ?? default(typeAux);

                }
            }
        }

It's throwing this error:

The type or namespace name 'typeAux', could not be found (are you missing a using directive or an assembly reference?)

Why? Shouldn't the function "Default(Type)" return a default value for that type?

A: How about returning null for reference types and Activator.CreateInstance for value types
public static object GetDefault(Type type)
{
   if(type.IsValueType)
   {
      return Activator.CreateInstance(type);
   }
   return null;
}

Reference: Programmatic equivalent of default(Type)

A: The default statement doesn't work with System.Type.
That being said, it seems more appropriate to leave that out, and use DBNull directly:
linha[itemField.Name] = itemField.GetValue(recordOnEnumerable) ?? DBNull.Value;

If the value is null, setting the result to null (which, in a DataRow, is DBNull.Value) seems appropriate.


text:
Q: How to get the Start Date of the Week, if I have the Week number of the year in SSRS Report Builder 3.0? I used the following expression to get the week number of the year:
=DATEPART("ww", Fields!Date.Value)

How to get the start date of that week number in SSRS Report.I have this in my report
And I want it to achieve this.

A: Your expression should look like this:
= DATEADD("d", - DATEPART(DateInterval.Weekday,Fields!Date.Value) +1,Fields!Date.Value)

Explanation:
From the date field, subtract the day of week number to get the first date of week


text:
Q: Let Linearlayout width be 650dp if parent is over 650dp, otherwise match parent I'm creating a LinearLayout inside a FrameLayout, the LinearLayout needs to be centered inside FrameLayout, but the width of LinearLayout needs to change as follows:
If parent FrameLayout is over 650dp, then set LinearLayout width to 650dp, this leaves some margin at left and right of linear layout.
If parent FrameLayout is under 650dp, then set Lineralyout width to match parent.
Parent FrameLayout width will change on orientation change, I tried to use OnLayoutChangeListener, OnGlobalLayoutListener, OnAttachStateChangeListenerto detect the width after screen rotates, but none of them works.
Am I on the right track by trying to find the width of parent view?
Or is it possible to use parent view as ConstraintLayout and make the LinearLayout inside comply 650 when possible and expand to parent when width is not enough?
(Note I can't use different values under different layout res folders like sw600 or sw600-land, as the parentview is not necessarily occupying the entire screen, it might just be one of the two columns on the screen)

A: The appropriate way to handle this is to create another layout file under layout-land and use a 650dp width for that. And for more description on supporting different screens see the official training here.

A: For any one interested, I solved it with a ConstraintLayout per Eugen's comment. This will make sure the LinearLayout's width matches parent on smaller screens(<650dp) and cap the width to 650dp on bigger screen sizes
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

  <LinearLayout
      android:id="@+id/row_content"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:orientation="horizontal"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintWidth_max="650dp"/>
</android.support.constraint.ConstraintLayout>

A: <LinearLayout
    android:layout_width="300dp"
    android:layout_height="100dp"
    android:background="#f00"
    >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:maxWidth="200dp"
        android:minWidth="200dp"
        android:background="#00f"
        >
    </LinearLayout>
</LinearLayout>

Result when parent width = 150dp


text:
Q: How to run a nuxt generated website from filesystem? When I run a nuxt generated vue website from file system, with no server, I get GET file:///_nuxt/... with status (failed)
How to run a nuxt generated vuejs app from filesystem?

A: module.exports = {
  ...
  mode: 'spa',
  router: {
    ...
    mode: 'hash'
  },
  build: {
    extend (config) {
      ...
      config.output.publicPath = './_nuxt/'

Update: let me explain this step by step.
1) mode: 'spa' -- no server-side rendering (only client-side navigation).
2) router mode: 'hash' -- switch from history mode, that requires a server to fake filesystem calls, to totally client based approach where all urls prefixed with #.
3) config.output.publicPath -- this changes the assumption, that all assets are stored at the root. Which is actually the root cause of the file:///_nuxt/... error.


text:
Q: Show close reason descriptive text on question Problem: Many of the close reasons are self-explanatory, but a few would benefit from having the descriptive text shown when viewing closed questions.  (For example, my recent comment on "Not A Real Question".)
Proposed solution: Simply sticking it in a normal size font in a paragraph below "closed as ..." seems the appropriate place.
NARQ would probably benefit disproportionately more from this than the other reasons.  (Or have I misunderstood NARQ?)  However, it seems like it would be helpful to new users that get their questions closed and would otherwise have to search meta or discover the title text for the close reason.  (Though many 3k rep users seem to not realize these descriptions exist either. I didn't notice the text till around 6k rep, I think.)
And yes, the text is already retrieved and sent along with the page, but it's completely non-obvious you can find it the title text IMHO.

A: I totally agree, sometimes people feel a little begrudged because their question got closed
Off course we could leave a comment explaining why it was closed, but it would be a lot clearer if this explanation was highlighted.
While this is only required these borderline cases, it's better to prevent confusion than having to solve it later on
@Jeff: Should we leave a comment with further explanations or would it be possible to manually edit the message with something relevant for that question?


text:
Q: The size of the train_data (1) couldn't be smaller than batch_size (32) my structure asset to training (tflite)
!ls  /root/.keras/datasets/model_test/
!ls  /root/.keras/datasets/model_test/abrasive/

abrasive  adhesive
'abrasive (1).jpg'  'abrasive (2).jpg'  'abrasive (3).jpg'

init ImageClassifierDataLoader
data = ImageClassifierDataLoader.from_folder(image_path)
train_data, test_data = data.split(0.3)

INFO:tensorflow:Load image with size: 6, num_label: 2, labels: abrasive, adhesive.
INFO:tensorflow:Load image with size: 6, num_label: 2, labels: abrasive, adhesive.

when i try to customize model with
model = image_classifier.create(train_data)

i got
ValueError: The size of the train_data (1) couldn't be smaller than batch_size (32). To solve this problem, set the batch_size smaller or increase the size of the train_data.

what does that mean? the data test must be > 32 ??
where is batch_size ?
I found the same thing, but quite different and I didn't get it (not simple ) Increasing batch_size of dataset for Pytorch neural network

A: Don't use batch size as batch size is used when the dataset is very large and you want to train your data by splitting it into batches to improve the training process

A: When you create your model, the create() function offers the possibility to define batch_size (default is 32). To reuse your example, you may write:
model = image_classifier.create(train_data, batch_size=1)

See also Change the training hyperparameters


text:
Q: Apache Strange Error Message 'Broken pipe' Always getting "(32)Broken pipe: core_output_filter: writing data to the network" message on Apache error.log.
In apache.conf setted up EnableSendfile Off, EnableMMAP Off but its still same.
OS: Debian etch
Apache ver: Apache/2.2.3
Enabled apache modules: ctions alias auth_basic authn_file authz_default authz_groupfile authz_host authz_user autoindex cgi dir env fcgid include mime negotiation perl php5 rewrite setenvif ssl status suexec userdir.
Thanks.

A: Since you've already turned off EnableSendfile and EnableMMAP, it looks like you've done your homework. The general cause of this error is that Apache got SIGPIPE, which happens when Apache tries to write to a socket that the other end has closed (described here, look at the last post). The post suggests that the user on the far end can trigger this by pressing their Stop or Reload button. However, if you're seeing flurries of these entries all the time, I think the following is more likely:

*

*Client connected to Apache at some point, and established a bunch of parallel connections. Most clients will do this so they can download multiple files/images/etc. at the same time to make the page load faster.

*Client went idle but kept the sockets open.

*At some point, all those sockets timed out on the client end. Possibly a firewall or NAT device killed them, so you never get a TCP RST or FIN on your end.

*The next time the Apache checks up on far end for TCP_KEEPALIVE, the kernel sees the socket is busted and returns SIGPIPE to Apache.

If you have a busy server, I'd imagine this is actually the usual and expected behavior. In fact, even the Apache folks themselves don't seem to concerned about it, as they apparently set the LogLevel for apache.org to warn so they don't even see these messages (noted here). This message is apparently only seen at level info, so changing it to notice or higher should prevent them from being logged.


text:
Q: "Driven from" sentence
These countries will have a vast number of experienced and productive
  older workers who, as things stand, will be driven from the workforce
  upon reaching the age of sixty-five by the widespread practice of
  requiring workers to retire at that age.

I know all the vocabularies in the sentence, but having problem understanding the sentence as a whole (especially because of the bold part). Can someone explain what this sentence means?

A:
driven from the workforce upon reaching the age of sixty-five

These people will no longer be able to work when they reach 65.

by the widespread practice of requiring workers to retire at that age

A practice is a standard way of doing things
requiring means telling somebody that they must do something, for example retire when they reach 65.
widespread means that a lot of companies follow this practice.


text:
Q: Rails + Multiple DataTables + UI nested accordion I'm using multiple similar dataTables within a nested UI accordion. While I've had no problem initializing multiple dataTables using the class-level selector, I'm having a problem getting the header and footer of any given table to align correctly.
I assume this is the same problem as a dataTable in a tab: the table (or header) needs to be redrawn once the accordion pane is displayed.
With initialization of a single table, or id-based initialization, I've had no problem using fnDraw or fnAdjustColumnSizing in a function to redraw a table on display. However, using mass-initialization, this approach doesn't work, because the specific displayed table can't be easily targeted.
I've tried to find a way of targeting only the currently displayed table for redraw, but haven't been successful.
Has anyone else dealt with this issue successfully? Thanks for any ideas....

A: I'm sure this is super-hacky, but the only way I could set it up so I could create a dynamic, multi-level accordion with a dataTable nested within each, was to actually nest the dataTable initialization within the accordion activation (at the level of the table), then mark the table div as initialized so it could be re-opened. Here's my js code:
$(document).ready(function(){

    $(function() {
        $('.accordion.second-level').bind('accordionactivate', function (event, ui) {

              if (ui.newPanel.length) {
                 thisPanel = ('#'+ ui.newPanel.attr('id'));
                 if ($(thisPanel).hasClass('not_activated')) {
                     $(thisPanel + ' .dataTables_types').dataTable({
                            "bAutoWidth": false,
                            "bPaginate": false,
                            "bScrollCollapse": true,
                            "sScrollY": "295px",
                            "aaSorting": [[ 1, "desc" ]],
                            "sDom": "<'row'<'span10'f>>t<'row'<'span10'i>>",
                             "aoColumns": [
                                            { "bSortable": false },
                                            null,
                                            null,
                                            { "iDataSort": 4 },
                                            {'bVisible': false},
                                            {'bVisible': false},
                                            null
                                          ],
                            "fnFooterCallback": function ( nRow, aaData, iStart, iEnd, aiDisplay ) {
                                           /* Calculate the total transactions on this page */
                                          var total = 0;
                                           for ( var i=iStart ; i<iEnd ; i++ )
                                          {
                                            total += aaData[ aiDisplay[i] ][5]* 1;
                                           }
                                           var nCells = nRow.getElementsByTagName('th');
                                           nCells[1].innerHTML = total;
                                           $(nCells[1]).formatCurrency({negativeFormat:'%s-%n'});
                            }
                    });
                   $(thisPanel).removeClass('not_activated');
                 }
                }
        });
    });
});

I'd still love to know if there's a better/more efficient way to do this, but this does work.


text:
Q: fix nextjs component level scss issue I'm converting normal react app to next js,
previously I just imported scss file using
import from '.componentName.scss'

But now I have to import using
import style from 'componentName.module.scss

therefore I have to change lot of code since this is previously completed project,
is there any way to configure nexjs that allow to import scss as before

A: I have no idea if it'll work but you can use https://nextjs.org/docs/api-reference/next.config.js/custom-webpack-config to create a custom webpack config in nextjs.  Along with that you can define a rule for styles.
...
rules: [
  {
    test: /\.s?css$/,
    use: [
      'style-loader',
      {
        loader: 'css-loader',
        options: {
          modules: true
        }
      },
      'sass-loader',
    ],
    include: /\.s?css$/
  },
],

Using that I'm pretty sure you should be able to override the way it's searching for *.module files and including them in the css bundle.
Note don't just copy that code directly, make sure it'll actually work and configure it to your needs, it's just for frame of reference.


text:
Q: Is it considered bad practice to change the value of __proto__ of an object? I was trying to reproduce this piece of code from a tutorial website
let animal = {
  eat() {
    this.full = true;
  }
};

let rabbit = {
  __proto__: animal
};

rabbit.eat();

I got this error "The 'proto' property is deprecated". I have done a lot of research to find an alternative for 'proto', but I end up thinking it is bad practice to do it. Here are my thoughts:

*

*the example above is not good in real life. Animal and rabbit should be classes instead of objects. Am I right?

*if the example was bad, what would be a good example in real life that needs to get/set proto?

A: Read all the reasons why this is bad practice here.

Warning: Changing the [[Prototype]] of an object is, by the nature of how modern JavaScript engines optimize property accesses, a very slow operation, in every browser and JavaScript engine...
Warning: While Object.prototype.proto is supported today in most browsers, its existence and exact behavior has only been standardized in the ECMAScript 2015 specification as a legacy feature...

And like you mentioned yourself, it's a deprecated feature. If you are learning ES6 then classes are indeed the way to go here:
class Animal {
  eat() {
    this.full = true;
  }
}

class Rabbit extends Animal {}

const rabbit = new Rabbit();
rabbit.eat();

The Rabbit extends the Animal.prototype, which in itself always extends the Object.prototype.


text:
Q: Unable to resolve activity for: Intent when instrumentation-testing android activities I'm getting errors when I'm trying to run insturmentation tests on android. I've written an Activity, called AudioPlayerActivity that lies in the package com.mycompany.mobile.android.gui, and now I'm trying to test the GUI of that project and I'm running in the following error:

java.lang.RuntimeException: Unable to resolve activity for: Intent { act=android.intent.action.MAIN flg=0x10000000 cmp=com.mycompany.mobile.android.gui/.AudioPlayerActivity }

I have read this question, and followed the advice there, but to no avail. I also googled for the error, but did not find any help.
This is how my AndroidManifest.xml for the test project looks like:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mycompany.mobile.android.gui"
    android:versionCode="1"
    android:versionName="1.0" >

    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.mycompany.mobile.android.gui" />
    <application>
        <uses-library android:name="android.test.runner" />
    </application>

    <uses-sdk android:targetSdkVersion="7" />
    <supports-screens android:anyDensity="true" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

And here's my Instrumentation test.
package com.mycompany.mobile.android.gui;
import android.test.ActivityInstrumentationTestCase2;

import com.mycompany.mobile.android.gui.AudioPlayerActivity;

public class TestMusicPlayerActivityTest extends ActivityInstrumentationTestCase2<AudioPlayerActivity> {
    public TestMusicPlayerActivityTest() {
            super("com.mycompany.mobile.android.gui", AudioPlayerActivity.class);
    }

    public TestMusicPlayerActivityTest(String name) {
        super("com.mycompany.mobile.android.gui", AudioPlayerActivity.class);
    }

    public TestMusicPlayerActivityTest(String pkg, Class<AudioPlayerActivity> activityClass) {
        super("com.mycompany.mobile.android.gui", AudioPlayerActivity.class);
    }

    public void testSomething() {
        System.out.println("Nothing works :(");
        System.out.println(getActivity());
    }
}

We are running the entire process via maven, but that should not be a part of the problem.
The tested Activity, as you can see, also lies in the same package. I don't call the super constructor with the activity's instead of the package name, as most people having this issue do.
For your interest, this is the AndroidManifest.xml describing the tested activity:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mycompany.mobile.android.gui"
    android:versionCode="1"
    android:versionName="1.0" >

    <!-- omitted Uses permission + Uses SDK -->
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:debuggable="true"
        android:theme="@style/NoTitleBar"
    >
    <!-- omitted other activities -->
        <activity
            android:name="com.mycompany.mobile.android.gui.AudioPlayerActivity"
            android:screenOrientation="portrait" ></activity>
    </application>
</manifest>

I also added the activity to the AndroidManifest.xml, but this didn't change anything. I also tried adding the MAIN/LAUNCHER intent filter for the desired activity, but to this didn't change the outcome of the test. I have tried starting the activity with extras and without them, that also didn't change the outcome.

A: <?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.mycompany.mobile.android.gui"
... ...

Are you using the same package name for both your Android project and Android test project? This could be a problem, though I am not sure if it causes your java.lang.RuntimeException.
According to the official dev guide here, Your test project must have a different package name  from you tested project:

An Android package name is a unique system name for a .apk file, set by the "android:package" attribute of the  element in the package's manifest. The Android package name of your test package must be different from the Android package name of the application under test. By default, Android tools create the test package name by appending ".test" to the package name of the application under test.

Try using package name com.mycompany.mobile.android.gui.test for your test project.

A: There are two possible solutions.

*

*Add activity definition in the android manifest and mark it as exported.

If you forgot to define activity in your android manifest, you would get "Unable to resolve activity error". If you are creating separate test activity in your android test project, create a separate test sub package and create your activity there. After that include it in your android manifest and mark it as exported.
# folder structure
└── src
    └── androidTest
        └── java
            └── com
                └── example
                    └── test
                        └── TestActivity.kt

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.test">
  <application>
     <activity
       android:name=".TestActivity"
       android:exported="true" />
  </application>
</manifest>

By default the android Gradle plugin appends .test to the applicationId and namespace of the test app. So that you need to put all your classes in a separate test package.

*Change android test namespace and the applicationId.

You can define namespace and applicationId of the test app in module level build.gradle file. Set it to match your test app's package name.
android {
  testNamespace 'com.example.app'
  defaultConfig {
     testApplicationId 'com.example.app'
  }
}

It is recommended to use same values for the namespace and the applicationId. If you use different values, the android Gradle plugin will copy applicationId in place of namespace in the android manifest.

A: You are running it as an Android Project, try running it as a Android Test Project
adb shell am instrument -e package <java package> -w <test apk package>/android.test.InstrumentationTestRunner


text:
Q: Bibliography warning messages for entries of type @inbook I have issues with these bibliography entries but don't know how to fix them (highlighted in yellow):

 @InBook{Houseman2002,
  chapter   = {Model Systems for Studying Polyvalent Carbohydrate Binding Interactions},
  pages     = {1-44},
  title     = {Host-Guest Chemistry: Mimetic Approaches to Study Carbohydrate Recognition},
  publisher = {Springer Berlin Heidelberg},
  year      = {2002},
  author    = {Houseman, B T and Mrksich, M},
  editor    = {Soledad Penad{\'e}s},
  volume    = {218},
}

@Article{Steinmeyer2017,
  author   = {Steinmeyer, Jeannine and R\"{o}nicke, Franziska and Schepers, Ute and Wagenknecht, Hans-Achim },
  title    = {Synthesis of Wavelength-Shifting Fluorescent DNA and RNA with Two Photostable Cyanine-Styryl Dyes as the Base Surrogate Pair},
  journal  = {ChemistryOpen},
  year     = {2017},
  issn     = {2191-1363},
  doi      = {10.1002/open.201700059},
  keywords = {chromophores, energy transfer, fluorescence, imaging, oligonucleotides},
  url      = {http://dx.doi.org/10.1002/open.201700059},
}

@InBook{Lindhorst2002,
  chapter   = {Artificial Multivalent Sugar Ligands to Understand and Manipulate Carbohydrate-Protein Interactions},
  pages     = {201-235},
  title     = {Host-Guest Chemistry: Mimetic Approaches to Study Carbohydrate Recognition},
  publisher = {Springer Berlin Heidelberg},
  year      = {2002},
  author    = {Lindhorst, Thisbe K},
  editor    = {Penad{\'e}s, Soledad},
  volume    = {218},
  address   = {Berlin, Heidelberg},
  isbn      = {978-3-540-45010-8},
  booktitle = {Host-Guest Chemistry: Mimetic Approaches to Study Carbohydrate Recognition},
  doi       = {10.1007/3-540-45010-6_7},
  url       = {http://dx.doi.org/10.1007/3-540-45010-6_7},
}

@InBook{Schwechheimer2016,
 author    = {Schwechheimer, Christian and Merkel, Marcus and Bohl{\"a}nder, Peggy R and Wagenknecht, Hans-Achim},
 chapter   = {Synthetic Wavelength-Shifting Fluorescent Probes of Nucleic Acids},
  pages     = {83-100},
  title     = {Modified Nucleic Acids},
  publisher = {Springer International Publishing},
  year      = {2016},
  editor    = {Nakatani Kazuhiko and Tor Yitzhak},
  volume    = {31},
  address   = {Cham},
  isbn      = {978-3-319-27111-8},
  booktitle = {Modified Nucleic Acids},
  doi       = {10.1007/978-3-319-27111-8_4},
  url       = {http://dx.doi.org/10.1007/978-3-319-27111-8_4},
}

@InBook{Flimbook,
  chapter   = {Fluorescence lifetime imaging techniques: Time-correlated single photon counting},
  pages     = {203-232},
  title     = {Fluorescence lifetime spectroscopy and imaging},
  publisher = {Taylor \& Francis Group},
  year      = {2015},
  author    = {Wolfgang Becker},
  editor    = {Marcu, Laura and French, Paul M W and Elson, Daniel S },
}

`

A: You are misusing the entry type @inbook for four of the entries you posted. You should be using the entry type @incollection instead.
Moreover, in all four of these entries, you should (a) change the field title to booktitle and (b) change the field chapter to title. The field chapter, if present, should contain a number, not the title of the chapter.
With these changes in place, you'll notice that the entries with keys Lindhorst2002 and Schwechheimer2016 have two, identical booktitle fields -- get rid of the duplicate fields.
Here's how I would write the four entries:
@incollection{Flimbook,
  title        = "Fluorescence lifetime imaging techniques:
                  Time-correlated single photon counting",
  pages        = "203-232",
  booktitle    = "Fluorescence lifetime spectroscopy and
                  imaging",
  publisher    = "Taylor \& Francis Group",
  address      = "London",
  year         = "2015",
  author       = "Wolfgang Becker",
  editor       = "Marcu, Laura and French, Paul M. W. and Elson,
                  Daniel S. ",
}

@incollection{Houseman2002,
  title        = "Model Systems for Studying Polyvalent
                  Carbohydrate Binding Interactions",
  pages        = "1-44",
  booktitle    = "Host-Guest Chemistry: Mimetic Approaches to
                  Study Carbohydrate Recognition",
  publisher    = "Springer",
  address      = "Berlin \& Heidelberg",
  year         = "2002",
  author       = "Houseman, B. T. and Mrksich, M.",
  editor       = "Soledad Penad{\'e}s",
  volume       = "218",
}

@incollection{Lindhorst2002,
  title        = "Artificial Multivalent Sugar Ligands to
                  Understand and Manipulate
                  Carbohydrate-Protein Interactions",
  pages        = "201-235",
  booktitle    = "Host-Guest Chemistry: Mimetic Approaches to
                  Study Carbohydrate Recognition",
  publisher    = "Springer",
  address      = "Berlin \& Heidelberg",
  year         = "2002",
  author       = "Lindhorst, Thisbe K.",
  editor       = "Penad{\'e}s, Soledad",
  volume       = "218",
  isbn         = "978-3-540-45010-8",
  doi          = "10.1007/3-540-45010-6_7",
  url          = "http://dx.doi.org/10.1007/3-540-45010-6_7",
}

@incollection{Schwechheimer2016,
  author       = "Schwechheimer, Christian and Merkel, Marcus
                  and Bohl{\"a}nder, Peggy R and Wagenknecht,
                  Hans-Achim",
  title        = "Synthetic Wavelength-Shifting Fluorescent
                  Probes of Nucleic Acids",
  pages        = "83-100",
  publisher    = "Springer",
  address      = "Cham",
  year         = "2016",
  editor       = "Nakatani, Kazuhiko and Tor, Yitzhak",
  volume       = "31",
  isbn         = "978-3-319-27111-8",
  booktitle    = "Modified Nucleic Acids",
  doi          = "10.1007/978-3-319-27111-8_4",
  url          = "http://dx.doi.org/10.1007/978-3-319-27111-8_4",
}


text:
Q: Boolean operations in lucene query WIll Lucene boolean operators works like java or C? If my query is to search for string1 AND string2, will Lucene first searches for string1 and then string2? And if string1 is not found in the index, will it search for string2?

A: No, there is no short-circuiting in lucene queries. One reason for this is that search results are not a simple binary yes or no, but must be scored based on how strongly they match each of the terms.


text:
Q: Write EPIPE error when using ffmpeg with copy option with ytdl-core Using the following code i get a write EPIPE error. This is caused by the copy option as when i remove that option it works just takes forever. Any idea what would be the fix to this?
const audio = ytdl(videoURL, { quality: 'highestaudio', filter: 'audioonly', highWaterMark: 1 << 25 })
            .on('progress', (_, downloaded, total) => {
                tracker.audio = { downloaded, total };
            });
const video = ytdl(videoURL, { quality: 'highestvideo' })
  .on('progress', (_, downloaded, total) => {
      tracker.video = { downloaded, total };
   });

const ffmpegProcess = cp.spawn(ffmpeg, [
            '-loglevel', '8', '-hide_banner',
            '-progress', 'pipe:3',
            '-i', 'pipe:4',
            '-i', 'pipe:5',
            '-map', '0:a',
            '-map', '1:v',
            '-c:v', 'copy',
            'out.webm',
        ], {
            windowsHide: true,
            stdio: [
                'inherit', 'inherit', 'inherit',
                'pipe', 'pipe', 'pipe',
            ],
        });
        ffmpegProcess.on('close', () => {
            console.log('done');
        });

        ffmpegProcess.stdio[3].on('data', chunk => {
            if (!progressbarHandle) progressbarHandle = setInterval(showProgress, progressbarInterval);
            const lines = chunk.toString().trim().split('\n');
            const args = {};
            for (const l of lines) {
                const [key, value] = l.split('=');
                args[key.trim()] = value.trim();
            }
            tracker.merged = args;
        });
        audio.pipe(ffmpegProcess.stdio[4]);
        video.pipe(ffmpegProcess.stdio[5]);

A: I fixed the issue it seems that ffmpeg doesnt like the output file to be webm so i just changed it to an mp4


text:
Q: How to escape the null character in here-document?(bash and/or dash) I want to perform shuf --zero-terminated on multi-line strings with here-document.

A: Here-documents in Bash and dash don't support this. You can't store a null in a variable, they are removed from command substitutions, you can't write one in literally, and you can't use ANSI-C quoting inside the here-document. Neither shell is null-friendly and they are generally treated as (C-style) string terminators if one does get in.
You have a few options: use a real file, use zsh, use process substitution, or use standard input.

You can do exactly what you want in zsh, which is much more null-friendly.
zsh% null=$(printf '\x00')
zsh% hexdump -C <<EOT
heredoc> a${null}b${null}
heredoc> EOT
00000000  61 00 62 00 0a                                    |a.b..|
00000005

Note though that heredocs have an implicit terminating newline, which may not be desirable (it'll be an extra field for shuf after the final null).

For Bash, you can use process substitution almost equivalently to your heredoc in combination with printf or echo -e to create nulls inline:
bash$ hexdump -C < <(
printf 'item 1\x00item\n2\x00'
)
00000000  69 74 65 6d 20 31 00 69  74 65 6d 0a 32 00        |item 1.item.2.|
0000000e

This is not necessarily entirely equivalent to a here-document, because those are often secretly put into real files by the shell (which matters for seekability, among other things).
Since you probably want to suppress terminating newlines, you can't even use a heredoc internally within the commands there - it has to be printf/echo -ne if safe to get fine-grained control over the output.

You can't do process substitution in dash, but in any shell you could pipe in standard input from a subshell:
dash$ (
printf 'item 1\x00'
printf 'item\n2\x00'
) | hexdump -C
00000000  69 74 65 6d 20 31 00 69  74 65 6d 0a 32 00        |item 1.item.2.|
0000000e

shuf is happy to read from standard input by default, so that should work for your concrete use case as I understand it. If you have a more complex command, being on the right-hand side of a pipeline can introduce some confounding elements with scoping.

Finally, you could write your data into a real file using printf and use that instead of a here-document. That option has been covered in the other answer. You'll need to make sure you clean up the file afterwards, and may want to use mktemp or similar if available to create a safe filename if there are any live security concerns.

A: Thank you all.
Let I post one answer base on you all and maybe best for me.
This script works nicely in bash and dash, no require real file or process substitution in bash, no require an extra slow external program call, even you don't need to worry about any escape problem in entities as %s in C printf, but you should still take care to string escape in your shell itself.
#!/bin/sh
printf '%s\0' "[tag1]
key1=value1
key2=value2
[/tag1]
" "[tag2]
key3=value3
key4=value4
[/tag2]
" | shuf --zero-terminated
#also see man printf(1)

For shuf only(not intent to general here-document alternative):
shuf --echo "[tag1]
key1=value1
key2=value2
[/tag1]" "[tag2]
key3=value3
key4=value4
[/tag2]"

A: I do not think you can do what you want in a heredoc. However it is trivial to do using echo as the following example shows:
$ cat demo
#!/bin/bash

echo -ne "one\0" > outfile
echo -ne "two\0" >> outfile
echo -ne "three\0" >> outfile

$ ./demo
$ od -a outfile
0000000   o   n   e nul   t   w   o nul   t   h   r   e   e nul
0000016
$

A: I ended up using a "trick"
cat <<EOS | cat - <(echo -e "\0") | most
{
  "version":"1.1",
  "gelf-toekn":"SOMETHIN",
  "host": "api.ivsdev.net",
  "short_message": "foo",
   "full_message": "bar",
   "level": 1
}
EOS

The first heredoc cat is piped into a second one who concatenate it with a null byte.


text:
Q: Scala: Unspecified value parameter error when trying to create binary tree using fold on sequence of elements I am trying to write a binary tree in scala. Here are my definitions
sealed trait Tree[+T]
final object Empty extends Tree[Nothing]
final case class Leaf[A](value: A) extends Tree[A]
final case class Branch[A](elem: A, left: Tree[A], right: Tree[A]) extends Tree[A]

object BinaryTree {

  def insert[ A : Ordering] (t : Tree[A])(implicit elem : A): Tree[A] = {
    val order = implicitly[Ordering[A]]
    t match {
      case Empty => Leaf(elem)
      case Leaf(x) if (elem == x) => t
      case Leaf(x) if (order.lt(elem, x)) => new Branch(elem, Empty, new Leaf(x))
      case Leaf(x)  => new Branch(elem, new Leaf(x), Empty)
      case Branch(x, left, right) if (elem == x) => t
      case Branch(x, left, right) if (order.lt(elem, x)) => new Branch(x, insert(left), right)
      case Branch(x, left, right) =>   new Branch(x, left, insert(right))
    }
  }

  def apply[A: Ordering](as: A*): Tree[A] =
    as.tail.foldLeft[Tree[A]](Leaf(as.head))((t, elem) => BinaryTree.insert(t)(elem))
}

In my BinaryTree.apply method I get the following error
"Unspecified value parameters: elem : A"

Not sure what that is supposed to mean or what I am missing. Can anyone please help me out

A: If you use context bound and implicit parameters, all the parameters including context bound forms single set of params, the set being in the end.
So your insert signature:
def insert[A: Ordering] (t: Tree[A])(implicit elem: A)

is similar to:
def insert(t: Tree[A])(implicit o: Ordering[A], elem: A)

It means that you should either not pass o and elem parameters when calling insert or pass them both.


text:
Q: Entity Framework Seed Deployment SQL Script error As part of my Entity Framework deployment I'm trying to deploy some scripts onto a newly created database, however I got the following error;

ALTER DATABASE statement not allowed within multi-statement transaction.

My Code;
internal sealed class Configuration : DbMigrationsConfiguration<DBContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(DBContext context)
    {
        context.Database.ExecuteSqlCommand(
            @"ALTER DATABASE MyDB SET ENABLE_BROKER
            CREATE QUEUE NewCarShareQueue;
            CREATE SERVICE NewCarShareService ON QUEUE NewNewCarShareQueue
               ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]);");
    }
}

I've tried the following as well, making sure only one transaction is going through at once, and not shown here but disposing the current context and recreating it;
internal sealed class Configuration : DbMigrationsConfiguration<DBContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(DBContext context)
    {
        context.SaveChanges();
        context.Database.ExecuteSqlCommand(
           @"ALTER DATABASE MyDB SET ENABLE_BROKER");
    }
}

A: The Seed command is run after every successful migration run. It actually runs even if no migrations were pending. So it is a bad place to do any altering of the DB structure.
It is better to create a migration and do the ALTERs in there. When your model and migrations are in sync, run add-migration EnableQueue in the PM console. That will give you an empty migration that you can now add your own statements to.
Anyways, running SQL statements in a separate transaction in the Seed method is an interesting problem. Something like this should work (haven't compiled it myself, so there's probably a few typos in it):
protected override void Seed(DBContext context)
{
  using(var tx = new TransactionScope(TransactionScopeOption.RequiresNew))
  using(var conn = new SqlConnection(context.Database.Connection.ConnectionString))
  {
    conn.Open()
    var command = conn.CreateCommand();
    command.CommandText = "ALTER DATABASE WHATEVER YOU WANT TO DO";
    command.ExecuteNonQuery();

    tx.Complete();
  }
}


text:
Q: Expectation of square root of binomial r.v. Let $X\sim B(n,p)$ denote a binomial random variable.  Is there any approximation available for the quantity $E(\sqrt{X})$?  Clearly Jensen's inequality holds, but rudimentary tooling around with Maple hasn't turned up anything more substantial.

A: $\newcommand{\E}{\mathbf{E}}$
$\renewcommand{\P}{\mathbf{P}}$
$\DeclareMathOperator{\var}{Var}$
If we use Taylor expansion (as Anthony suggested) for $\sqrt{x}$ around 1, we get:
$$\sqrt{x}\approx 1 + \frac{x-1}{2} - \frac{(x-1)^2}{8}  .$$
We can use this to get an approximation of
$$\E(\sqrt{X})\approx 1-\frac{\var(X)}{8} ,$$
which should be valid for any RV concentrated around an expectation of 1. Equivalently,
$$\E(\sqrt{X})\approx \sqrt{\E(X)}\bigg(1-\frac{\var(X)}{8\E(X)^2}\bigg) ,$$
for any RV concentrated around its mean.
As you noted, we can use Jensen inequality to get $\E(\sqrt{X})\le \sqrt{\E(X)}$ for any nonnegative RV. We can tweak the Taylor expansion to get a lower bound, by noticing that
$$ 1 + \frac{x-1}{2} - \frac{(x-1)^2}{2} \le \sqrt{x} \ .$$
Hence, we get
$$\sqrt{\E(X)}\bigg(1-\frac{\var(X)}{2\E(X)^2}\bigg) \le \E(\sqrt{X}) ,$$
for any nonnegative RV.
In the case of $X\sim Bin(n,p)$ we get
$$ \sqrt{np}-\frac{1-p}{2\sqrt{np}} \le \E(\sqrt{X})\le \sqrt{np} .$$