text:
Q: How to use/cite "in the place cited"/"loco citato" in numeric citation style in biblatex? BibLaTex knows ibid and I've also found loco citato as loccit in the text.
So now I want to combine that.
So this is yet another follow-up of how to force ibit-like things in the numeric style – and I still consider it a missing feature in biblatex in general.
Now I want to force it not only to use ibid properly as it is defined, but also l.c.. I.e., I want both, as proper citation guidelines suggest.
To illustrate, again this example:

They say, "LaTeX is powerful"[96, p. 3], but state on the same page "WordTEX may be better"[96, p. 3]. On then next page, they talk about "trains driving backwards"[96, p. 4].

With the solution, I want:

They say, "LaTeX is powerful"[96, p. 3], but state on the same page "WordTEX may be better"[ibid]. On then next page, they talk about "trains driving backwards"[l.c., p. 4].

l.c. is just one – very short –  possibility I have seen how that can be abbrevated or called. "Loc. cit." is another one and in German that is e.g. called "a. a. O." ("am angegebenen Ort").
As per their definition, ibid may only be used if everything is exactly the same and "in the place cited" only applies when the page or so may be different, but the source is still the same.
I've already found out that it is defined in biblatex and the old solution also makes use of it.
So I've tried to adapt it but my solution fails and now does not print the postnote (the optional part of the citation) anymore at all:
% ATTENTION: BROKEN EXAMPLE!

% consider all postnotes for check-if-previous-postnote-was-the-same
\def\blx@loccit@stricttracker#1{%
  \global\csundef{blx@lastnote@#1@\abx@field@entrykey}%
  \blx@imc@iffieldundef{postnote}
    {}
    {\blx@ifcitesingle
       {\global\cslet{blx@lastnote@#1@\abx@field@entrykey}\abx@field@postnote
           \xifinlistcs\abx@field@entrykey{blx@trackkeys@#1}
             {}
             {\listcsxadd{blx@trackkeys@#1}\abx@field@entrykey}}
       {}}}

\def\blx@loccit@numcheck#1{%
  \blx@imc@iffieldundef{postnote}
    {\@secondoftwo}
    {\blx@imc@iffieldequalcs{postnote}{blx@lastnote@#1@\abx@field@entrykey}}}

% ibid for postnote, but repeat number, if you subsequently use different pages/postnotes
% https://tex.stackexchange.com/a/554363/98645
\makeatletter
\newtoggle{cbx:loccit}

\renewbibmacro*{cite:comp}{%
  \global\togglefalse{cbx:loccit}%
  \addtocounter{cbx@tempcntb}{1}%
  \iffieldundef{shorthand}
    {\ifthenelse{\ifciteibid\AND\ifloccit\AND\NOT\iffirstonpage}
       {\usebibmacro{cite:ibid}}
       {\ifbool{bbx:subentry}
          {\iffieldundef{entrysetcount}
             {\usebibmacro{cite:comp:comp}}
             {\usebibmacro{cite:comp:inset}}}
          {\usebibmacro{cite:comp:comp}}}}
    {\ifthenelse{\ifciteibid\AND\NOT\ifloccit\AND\NOT\iffirstonpage}
       {\usebibmacro{cite:loccit}}
       {\ifbool{bbx:subentry}
          {\iffieldundef{entrysetcount}
             {\usebibmacro{cite:comp:comp}}
             {\usebibmacro{cite:comp:inset}}}
          {\usebibmacro{cite:comp:comp}}}}
    {\usebibmacro{cite:comp:shand}}
}

\providecommand*{\mkibid}[1]{#1}
\newbibmacro*{cite:ibid}{%
  \printtext[bibhyperref]{\bibstring[\mkibid]{ibidem}}%
  \global\toggletrue{cbx:loccit}}

\letbibmacro*{orig:postnote}{postnote}
\renewbibmacro*{postnote}{%
  \iftoggle{cbx:loccit}
    {}
    {\usebibmacro{orig:postnote}}}
\makeatother

\ExecuteBibliographyOptions{ibidtracker=constrict, loccittracker=constrict}

So my LaTeX coding "skills" fail here.
For a MWE refer to the example in the previous solutions.
It would be great, if you could add how to use loccit now here?

A: It's not too difficult to build this into the solutions shown in Getting ibid for numeric citations while comparing optional arguments/postnotes from biblatex. Most of it is already there.
But as mentioned in the comments I would advise against using these unusual Latin abbreviations. I have my doubts that they make your prose easier to parse.
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[british]{babel}
\usepackage{csquotes}
\usepackage[style=numeric-comp, backend=biber]{biblatex}

\addbibresource{biblatex-examples.bib}

\makeatletter
\def\blx@loccit@check#1{%
  \blx@imc@iffieldundef{postnote}
    {\ifcsempty{blx@lastnote@#1@\abx@field@entrykey}}
    {\blx@imc@iffieldequalcs{postnote}{blx@lastnote@#1@\abx@field@entrykey}}}

\let\blx@loccit@numcheck\blx@loccit@check

\def\blx@loccit@stricttracker#1{%
  \global\csundef{blx@lastnote@#1@\abx@field@entrykey}%
  \blx@imc@iffieldundef{postnote}
    {\global\cslet{blx@lastnote@#1@\abx@field@entrykey}\@empty}
    {\blx@ifcitesingle
       {\expandafter\blx@imc@ifpages
        \expandafter{\abx@field@postnote}
          {\global\cslet{blx@lastnote@#1@\abx@field@entrykey}\abx@field@postnote
           \xifinlistcs\abx@field@entrykey{blx@trackkeys@#1}
             {}
             {\listcsxadd{blx@trackkeys@#1}\abx@field@entrykey}}
          {}}
       {}}}

\newtoggle{cbx:loccit}

\renewbibmacro*{cite:comp}{%
  \global\togglefalse{cbx:loccit}%
  \addtocounter{cbx@tempcntb}{1}%
  \iffieldundef{shorthand}
    {\ifthenelse{\ifciteibid\AND\NOT\iffirstonpage}
       {\ifloccit
          {\usebibmacro{cite:ibid}}
          {\usebibmacro{cite:loccit}}}
       {\ifbool{bbx:subentry}
          {\iffieldundef{entrysetcount}
             {\usebibmacro{cite:comp:comp}}
             {\usebibmacro{cite:comp:inset}}}
          {\usebibmacro{cite:comp:comp}}}}
    {\usebibmacro{cite:comp:shand}}}

\providecommand*{\mkibid}[1]{#1}
\newbibmacro*{cite:ibid}{%
  \printtext[bibhyperref]{\bibstring[\mkibid]{ibidem}}%
  \global\toggletrue{cbx:loccit}}

\newbibmacro*{cite:loccit}{%
  \printtext[bibhyperref]{\bibstring[\mkibid]{loccit}}}

\letbibmacro*{orig:postnote}{postnote}
\renewbibmacro*{postnote}{%
  \iftoggle{cbx:loccit}
    {}
    {\usebibmacro{orig:postnote}}}
\makeatother

\ExecuteBibliographyOptions{ibidtracker=constrict, loccittracker=constrict}

\begin{document}
  \autocite[3]{sigfridsson}
  \autocite[3]{sigfridsson}
  \autocite[4]{sigfridsson}

  \autocite{worman}

  \autocite{sigfridsson}
  \autocite{sigfridsson}

  \printbibliography
\end{document}


text:
Q: Connect MongoDB container with nodejs app I have two docker container one with my nodejs webapp and one with a mongo db running.
I build a authentication in my mongo db container and now i get this error message:
    mongo    | 2018-08-22T13:48:24.102+0000 I ACCESS   [conn1] SASL SCRAM-SHA-1 authentication failed for blub on admin from client XXXXX; UserNotFound: Could not find user blub@admin
    mongo    | 2018-08-22T13:48:24.105+0000 I NETWORK  [conn1] end connection XXXXX (0 connections now open)
 app      | (node:16) UnhandledPromiseRejectionWarning: MongoError: Authentication failed.

I build both container with this docker-compose.yml
version: "2"
services:
 app:
   container_name: app
   restart: always
   build: .
   ports:
     - "3000:3000"
   links:
     - mongo
 mongo:
   container_name: mongo
   image: mongo
   volumes:
     - ./data:/data/db
   ports:
     - "27017:27017"
   environment:

     - MONGODB_INITDB_ROOT_USERNAME=blub
     - MONGODB_INITDB_ROOT_PASSWORD=pass

My app connects with the mongodb like this:
mongoose.connect("mongodb://blub:pass@mongo:27017/");

A: I found a solution:
My docker-compose:
version: '2'
services:
 app:
   container_name: app
   restart: always
   build: .
   ports:
     - 3000:3000
   links:
     - mongodb
 mongodb:
   container_name: mongodb
   image: mongo:3.4
   ports:
     - 27017:27017
   volumes:
      - ./data:/data/db
   environment:
     - MONGO_INITDB_ROOT_USERNAME=admin
     - MONGO_INITDB_ROOT_PASSWORD=admin123456
   command: mongod

the connection in the nodejs app: mongoose.connect("mongodb://admin:admin123456@mongodb:27017/");
But i actually can´t figure out, why it isn't working on my first try.

redpajama_set_name: RedPajamaStackExchange


text:
Q: merge statement for update and insert I am trying to use merge to combine an update and insert statement, although i am getting some error and im not quite sure its right. The merge statement is within a stored proc. Following is the merge statement.
MERGE dbo.seg AS TARGET
USING (SELECT segCreateDate
        , segDesc
        , modifiedDate
        , modifiedBy
    FROM [update].[dbo].[seg] s
    ) AS source (segCreateDate
                , segDesc
                , modifiedDate
                , modifiedBy)
        ON  (dbo.[seg].segID = s.segID
            AND (
                 dbo.[seg].segCreateDate > s.segCreateDate
                 OR dbo.[seg].segDesc <> s.segDesc
                )
    )

WHEN MATCHED THEN
UPDATE dbo.seg SET
  target.segCreateDate = source.segCreateDate
  AND target.segDesc = source.segDesc
  AND target.modifiedDate = source.modifiedDate
  AND target.modifiedBy = source.modifiedBy

WHEN NOT MATCHED THEN
INSERT (segID
        , segCode
        , segDesc
        , segCreateDate
        , createdDate
        , createdBy
        , modifiedDate
        , modifiedBy
        )
VALUES (SELECT  segID
                ,segCode
                ,segDesc
                ,segCreateDate
                ,createdDate
                ,createdBy
                ,modifiedDate
                ,modifiedBy
         FROM [update].[dbo].[seg]);

Its the first time i am using merge so hope can get some help.
Thanks all

A: There were several problems with your merge statement. This is what you probably wanted.
merge dbo.seg as TARGET
using
    (
     select segCreateDate,
            segDesc,
            modifiedDate,
            modifiedBy
     from   [update].dbo.seg s
    ) as source (segCreateDate, segDesc, modifiedDate, modifiedBy)
on (
    TARGET.segID = source.segID
    and (
         TARGET.segCreateDate > source.segCreateDate
         or TARGET.segDesc <> source.segDesc
        )
   )
when matched then
    update set TARGET.segCreateDate = source.segCreateDate,
               TARGET.segDesc = source.segDesc,
               TARGET.modifiedDate = source.modifiedDate,
               TARGET.modifiedBy = source.modifiedBy
when not matched then
    insert (
            segID,
            segCode,
            segDesc,
            segCreateDate,
            createdDate,
            createdBy,
            modifiedDate,
            modifiedBy
           )
    values (
            source.segID,
            source.segCode,
            source.segDesc,
            source.segCreateDate,
            source.createdDate,
            source.createdBy,
            source.modifiedDate,
            source.modifiedBy
           );

Note that (1) when updating a table you don't write and after each column but merely add a comma. (2) If you are using Source and Target as the table alias then you should stick to them and don't change in the middle to s instead of source.
Still the above code will probably not work because (at the end of the code) it is trying to insert into the target table more columns than there are in the source table. At first you are saying that the source table consists of segCreateDate, segDesc, modifiedDate, and modifiedBy. But at the end you are also trying to insert into target the columns segID, segCode, createdDate, and createdBy.
This leads me to the second problem why the above code cannot work: you are trying to join source and target on segID. I cannot tell if this column exists in the target table dbo.seg. But this column is certainly not contained in the source table as defined above.


text:
Q: Mouse Dragging problem i'm having the problem of capturing all the coordinate value of pixels while dragging with the mouse using mousedragged event in java
while i'm dragging slowly i'm able to get all the coordinate value of pixels
but when i'm doing it fast i'm getting only one third of the pixel coordinate values
for example if i drag it slowly i'm getting 760 pixel values but when i'm doing it fast i'm getting only 60 pixel coordinate values
please help me
I need all the points because i'm going to use all those points for the signature comparision...
Project Description :
User will put the sign using mouse in log in page, this sign will be compared with the sign which the user already put in sign up page...
I'm going to compare the sign using the pixel values, so by getting all the coordinate values only i can compare the sign...
pls help me...

A: Windows is not going to give you this, its up to the refresh rate of the Mouse, its DPI and the rate at which windows polls for the Mouse event. You are not going to get all pixels so you will need to make room for some ambiguity.
(It doesn't matter which language you use Java or C#)

A: Mouse movement events occur every few milliseconds, not for every pixel movement, so when the mouse is moving rapidly, some pixels will be missed out. If you want every single pixel, you'll have to interpolate between pixels if the new location is not adjacent to the previous one. One way to interpolate the pixels between two coordinates is Bresenham's line algorithm: http://en.wikipedia.org/wiki/Bresenhams_line_algorithm
Edit: Fixed link.


text:
Q: Reynolds transport theorem: link with the Lie derivative? In this Wikipedia article (see "Higher dimensions") there seems to be a connection between the Reynolds transport theorem (here) and the Lie derivative:
$$\frac{d}{dt}\int_{\Omega(t)}\omega=\int_{\Omega(t)} i_{\vec{\textbf v}}(d\omega)+\int_{\partial \Omega(t)} i_{\vec{\textbf v}} \omega+\int_{\Omega(t)}\dot{\omega} \qquad(1)$$
were $\omega$ is a p-form and the domain is time-varying. The symbol $i_X$ denotes the contraction with the vector field $X$.
By using the Cartan magic formula
$L_{X} \omega = d (i_X \omega) + i_X (d \omega)$, it seems that
$$\frac{d}{dt}\int_{\Omega(t)}\omega=\int_{\Omega(t)} i_{\vec{\textbf v}}(d\omega)+\int_{\Omega(t)} d(i_{\vec{\textbf v}} \omega)+\int_{\Omega(t)}\dot{\omega} \, ,$$
namely
$$\frac{d}{dt}\int_{\Omega(t)}\omega
=
\int_{\Omega(t)} L_{\vec{\textbf v}}\omega+\int_{\Omega(t)}\dot{\omega} \, .$$
It is clear that the Reynolds transport theorem is equivalent to the conservation of mass in hydrodynamics:
$$\frac{d}{dt}\int_{\Omega(t)}\rho
=
\int_{\Omega(t)} div(\rho \vec{\bf{v}}) +\int_{\Omega(t)}\dot{\rho} \, .$$
What is the relation between the two formulations? Clearly $\omega =\rho$ is not the correct thing to do: we can only integrate 3-forms and $\rho$ is a 0-form (the domain $\Omega(t)$ is three dimensional). How to derive the mass conservation from equation (1)?

A: Instead of $\rho$, think about the three form $\rho ~\mathrm{d}x$. (Like I tell my calculus students, you should always write the integration element in an integral.) Here $\mathrm{d}x$ is the standard volume form.
By definition of the divergence of a vector field you have that
$$ \mathrm{div}(\rho \vec{v}) ~\mathrm{d}x = \mathrm{d}( \iota_{\rho\vec{v}} ~\mathrm{d}x ) = \mathrm{d} (\iota_{\vec{v}} \rho ~\mathrm{d}x ) = L_{\vec{v}} \left(\rho~\mathrm{d}x\right) $$
which is what you expect.

A: Edit: I wrote this answer a long time ago. Coming back, I realised there were a lot of things that could have been much clearer. I hope it's better now.
There is a connection, indeed. Recall the definition of the Lie derivative for a $k$-form $\omega$ along a vector field $X$. If $\chi$ is the one-parameter family of diffeomorphisms defined (at least locally) by $X$, then
$$L_X\omega = \left.\frac{d}{d\tau}\right|_0(\chi_{\tau}^{*}\omega)$$
Integrating over some $k$-submanifold $\Omega$, we get
$$ \int_\Omega L_X\omega = \int_{\Omega}\left.\frac{d}{d\tau}\right|_0(\chi_{\tau}^{*}\omega)
= \left.\frac{d}{d\tau}\right|_0\int_{\Omega}\chi_{\tau}^{*}\omega
= \left.\frac{d}{d\tau}\right|_0\int_{\chi_\tau[\Omega]}\omega $$
Note that we first used the Leibniz integral rule in one variable, and then the fact that diffeomorphisms preserve the integral. I claim Reynold's transport theorem is a special case of the formula
$$\left.\frac{d}{d\tau}\right|_0\int_{\chi_\tau[\Omega]}\omega = \int_\Omega L_X\omega \tag{1}$$
we just obtained.
Say your space is an $n$-dimensional manifold $M$, and consider an interval $I\subseteq \mathbb R$ (say with $0\in I$) which for us will represent time.
In the context of Reynold's transport theorem you have a submanifold $\Omega$ of $M$ (say of dimension $k$) which "varies (smoothly) over time".
To formalize this, take a $k$-dimensional manifold $\Omega$ and an embedding $i:I\times\Omega\to I\times M$ where the first component is the identity. Then the submanifold $\Omega_t=i[\{t\}\times \Omega]\subseteq \{t\}\times M$ is the "position of $\Omega$ inside $M$ at time $t$".
Now we want to get the "spacetime velocity" of $\Omega$, which will be a vector field defined on the submanifold $i[I\times \Omega]$ (the "worldsheet" of $\Omega$).
To do this, observe that for every $x\in\Omega$ we get a smooth curve $\gamma_x:I\to I\times M$ given by $\gamma_x(t)=i(t,x)$. The vectors tangent to this family of curves give us a vector field $X$ defined by
$$\tilde X_{i(t,x)}=\gamma'_x(t)$$
This is the spacetime velocity we wanted. Using the extension lemma for vector fields on submanifolds, we get a vector field $X$ on $I\times M$ which agrees with $\tilde X$ on $i[I\times \Omega]$.
Its spacelike part $V=\text{proj}_{TM}X$ is the vector field that appears in Reynold's transport theorem, and we have $X=\frac{\partial}{\partial t}+V$.
Now a time-dependent $k$-form $\omega$ on $M$ can be regarded as a $k$-form on $I\times M$
such that $\iota_{v}\omega=0$ for any "purely timelike" vector $v\in T(I\times\{x\})$.
Note that we may (and will) always choose charts where the projection $t:I\times M\to I$ is a coordinate, so that $\omega$ has no $dt$ component.
Now we have all the pieces.
Let $\chi$ be the one-parameter family of diffeomorphisms induced by $X$ (we only need $\chi$ to be defined in a neighbourhood of $\Omega_0$). Applying formula (1) to the submanifold $\Omega_0$, we have
$$\left.\frac{d}{dt}\right|_0\int_{\chi_t[\Omega_0]}\omega = \int_{\Omega_0} L_X\omega .$$
Since $X$ at time $t$ is the velocity of $\Omega_t$, we have $\chi_t[\Omega_0]=\Omega_t$. Also, by Cartan's magic formula, we have $L_X\omega = d(\iota_X\omega) + \iota_X(d\omega)$. Hence
$$\left.\frac{d}{dt}\right|_0\int_{\Omega_t}\omega = \int_{\Omega_0} d(\iota_X\omega) + \int_{\Omega_0}\iota_X(d\omega) \tag{2}$$
Now lets treat the two integrals on the right hand side of (2) separately.
For the first integral,
since $V$ is the spatial part of $X$, we have $X=\frac{\partial}{\partial t}+V$ and hence $\iota_X\omega=\iota_V\omega$. On the other hand, since the tangent space of $\Omega_0$ is contained in $\{0\}\times M$, it is annihilated by $dt$. These two observations give the first two equalities in
$$\int_{\Omega_0} d(\iota_X\omega)=\int_{\Omega_0} d(\iota_V\omega)=\int_{\Omega_0} d_M(\iota_V\omega)=\int_{\partial\Omega_0}\iota_V\omega \tag{3}$$
and the third one comes from Stokes' theorem.
Now let's look at the second integral on the right hand side of (2).
Since $\omega=\omega_Idx^I$ (where $I$ is a multiindex where $t$ does not appear) we have
$$\begin{aligned}
d\omega
&=\partial_t\omega_Idt\wedge dx^I+\sum_i \partial_i\omega_Idx^i\wedge dx^I \\
&=\partial_t\omega_Idt\wedge dx^I+d_M\omega
\end{aligned}$$
and since $X=\frac{\partial}{\partial t}+V$, the second integral on the right hand side becomes
$$\begin{aligned}
\int_{\Omega_0}\iota_X(d\omega)
&= \int_{\Omega_0}\iota_{\frac{\partial}{\partial t}+V}(\partial_t\omega_Idt\wedge dx^I+d_M\omega) \\&= \int_{\Omega_0}\partial_t\omega_Idx^I+\iota_V(d_M\omega) \\
&= \int_{\Omega_0}\dot\omega+\int_{\Omega_0}\iota_V(d_M\omega)
\end{aligned} \tag{4}$$
The the crossed terms of the interior product vanish because they match $dt$ with $V$ and purely spatial basis forms with $\frac{\partial}{\partial t}$.
At last, plugging (3) and (4) into (2), we have
$$\left.\frac{d}{dt}\right|_0\int_{\Omega_t}\omega = \int_{\partial\Omega_0}\iota_V\omega+\int_{\Omega_0}\dot\omega+\int_{\Omega_0}\iota_V(d_M\omega)$$
as desired.


text:
Q: Prove that the set $U_1 =\{(123),(124),.....,(12n)\}$ generates $A_n$ Here $A_n$ = the alternating group on n symbols.
We are given a hint:
$(abc) = (1ca)(1ab)$
$(1ab)=(1b2)(12a)(12b)$
$(1b2)=(12b)^2$
I am unsure where to start. Can someone give me a jump start?

A: I think we need $n \geq 3$. Note that $\langle U_1 \rangle \leq A_n$.

Recall that $A_n$ consists of all permutations which can be written as an even product of transpositions

So, you can see that $A_n$ is generated by the set of all products of two distinct 2-cycles. Each product $\sigma$ of two 2-cycles has one of two forms.
$$\sigma = (ab)(cd) = (acb)(acd) \in \langle U_1 \rangle,$$
$$\sigma = (ab)(ac) = (acb) \in \langle U_1 \rangle.$$
So, $A_n \leq \langle U_1 \rangle$. We got the conclusion.


text:
Q: Converting an image into a font to label point features How do you convert an image (ex: company logo) into a font and store it within arcmap so that it can be called upon to label point features with?

A: Convert the font or image into an EMF vector graphic in graphic software such as Adobe Illustrator then use it as the picture marker symbol and it will be rendered as vector. You can also add any EMF vector (i.e. logo) to map layour as image and it will also render as vector. You can introduce 100% transparency to remove backround but only solid and 100% transperent properties will be honoured, semi-transparent will render as solid.

A: Have a look at EUDCEDIT. It's a "hidden" program that is included in most windows versions that can be used to edit and create fonts. I have used it do do exactly what you are trying to achieve. Once you create your font, it will appear under the name "EUDC" in your list of fonts available through the "Character Marker Symbol" type in the "Symbol Property Editor" dialogue in ArcMap.


text:
Q: What happens to pipe length when the pipe diameter changes? Intuitively, when the diameter of pipe is decreased, there will be more friction loss, more water pressure, and a higher flow rate. Is there a direct relationship/equation derived to see the affect of the pipe lengths?
Deriving from Hagen-Poiseuille's equation, we get:
$$\ Q = \frac{\Delta P\pi r^4}{8\mu L} $$
where :
$Q =$ flow rate
$\Delta \ P =$ change in fluid pressure
$r =$ radius of pipe,
$\mu =$ dynamic viscosity of fluid,
$L =$ length of pipe
To keep similar flow rates, are we able to use Poiseuille's derived formula to find the new lengths of pipe with a change in $r$ (pipe radius)?

A: If you want to keep flow rate and pressure drop the same, because your engineering task requires it, you just have to rearrange the Hagen-Poiseuille law so that everything that is known is on the right hand side, and everything that is unknown is on the left hand side:
$$\frac{L}{r^4} = \frac{\pi\Delta P}{8\mu Q}=:C$$
Usually, you would know $C$ because you know $\Delta P$ and $Q$, and thus, you could just calculate for example the length $L$ of the pipe if you provide a reasonable pipe radius $r$.
But if you just want to know how $L$ changes if $r$ changes, in general, you can provide an 'initial guess' $(L_1,r_1)$ and eliminate the constant $C$ by equating it to a 'final set of design parameters' $(L_2,r_2)$:
$$\frac{L_2}{r_2^4}=\frac{L_1}{r_1^4}$$
Hence, if you rearrange that once again, you obtain
$$L_2=L_1\cdot\frac{r_2^4}{r_1^4}$$
In more simple words, the length of the pipe behaves like the fourth power of pipe radius, if pressure drop and current shall stay the same.
By the way, this is all reasonable and a typical engineering question. Say, you want to build a ventilation system for a building, and you need an airflow $Q$ for convenient air quality and you have found an affordable fan that provides a certain pressure drop $\Delta P$ at its maximum fan speed. Now suppose you have chosen a pipe with diameter $r$, but as soon as you calculate the length of the pipe that is compatible with your fan and ventilation requirements (like with the first equation), you notice that this pipe is not long enough (say it is 20% too short) to connect the interior of the ventilated room through the building with the outside air. Now you might well ask the question: if I increase the radius of the pipe, how much length will this gain me.
For small changes of the respective quantities, as a rule of thumb (Taylor's theorem, first order), an increase of the pipe radius of 1% will result in a permissible length increase of 4%. This is due to the power of 4 on the radius, because
$$(101\%)^4=(1.01)^4\approx 1.041\approx 104\%$$
In the example above, where the length is 20% too short, you would have to increase the pipe radius by approximately 5%. That is a pretty quick way of estimating what you need.
But of course, this is still all subject to the assumption of Hagen-Poiseuille flow.
Another caveat (if you ever have to design a ventilation system): real fans don't just offer a defined pressure drop at a certain fan speed, but the pressure drop also depends on the flow conditions around the fan, namely, if it is free blowing, or if it is placed inside a duct (which is how normally a fan is used).

A: Usually, pipe length in the equation for Q is something which is independent from the diameter. Meaning you can change the diameter and the length of the pipe stays the same as it is bound to the stable solid of the pipe material. Therefore, if you change the diameter, the flow rate changes following your equation - but the length stays what it is.
It's really hard to imagine an experiment where the flow Q and the pressure are forced to be constant, then the diameter is changed and the length is made variable. Which material should that pipe be of? How do you plan to force the flow and the pressure to be constant? Impossible from my point of view.


text:
Q: POST a XML file content to a HTTPS url I want to send a xml file through POST request to a HTTPS server.
I think i have to read the content of the XML file and save it to a String, then send POST it to the server.
Sorry, but i don't have any code to demonstrate my workings. Can someone help me to do a Sample code or tutorial to start with this task ?
Note : I am using Java

A: Using java, You can open this XML file in READ mode and start reading and printing contents in browser.


text:
Q: What prompts Confirm Form Resubmission? I have two <input type ="submit"> with formaction inside a <form method="post" action=""> and these suckers prompt the Confirm Form Resubmission on refresh:
<form method = "post" action="">
  <input class = "button" type="submit" name="dhcp" value="DHCP IP" title="Redirect to DHCP IP Config page" formaction="/dhcp_ip.php">
  <input class = "button" type="submit" name="static" value="Static IP" title="Redirect to Static IP Config page" formaction="/static_ip.php">
</form>

I was led to believe that <form method="post"> or any POST method prompts Confirm Form Resubmission so I have eliminated the form and replaced it with two button elements:
<button class="button" onclick="goDHCP()">DHCP IP</button>
<button class="button" onclick="goStatic()">Static IP</button>
<script>
    function goDHCP() {
        window.location.replace("/dhcp_ip.php");
    }
    function goStatic() {
        window.location.replace("/static_ip.php");
    }
</script>

But this also prompts Confirm Form Resubmission on refresh.
What element prompts it ? And how can I not prompt it ? Because I also have some <input type="text">, on other pages, which do not prompt Confirm Form Resubmission on refresh, unless the user starts typing something in them.

A: Confirm Form Resubmission means that you are trying to refresh a page where data was sent to.
If you don't want to have this popup, click the URL bar and hit enter to revisit the same page without sending data.
As to your form...
<?php
if (!empty($_POST['submit'])) {
   echo '
      <script type="text/javascript">
         window.location.replace("/'.$_POST['direction'].'.php");
      </script>
   ';
}
?>
<form method="post" action="">
   <select name="direction">
      <option value="dhcp_ip">Redirect to DHCP IP Config page</option>
      <option value="static_ip">Redirect to the Static IP Config page</option>
   </select>
   <button type="submit" name="submit" value="submit">
     Visit page
   </button>
</form>

If you need any explanations, please let me know.


text:
Q: On the Rademacher complexity of a set. Given a sequence $\{ \theta_j \}_{j=1}^{\infty} \in l^2(N)$, i.e., such that $\sum_{j=1}^{\infty} \theta_j^2 \le \infty$.
Given a strictly positive sequence $\{ \mu_j \}_{j=1}^{\infty}$ we define
$$T := \left \{ \{ \theta_j \}_{j=1}^{\infty} \in l^2(N) \ | \ \sum_{j=1}^{\infty} \frac{\theta_j^2}{\mu_j} \le 1 \right \} $$
We define the Rademacher complexity of this set as
$$ E_{\epsilon} \left[ \sup_{\theta \in T} \sum_{j=1}^{\infty} \epsilon_j \theta_j  \right] $$
where the $\epsilon_j$ are Rademacher random variables.
Why is
$$ E_{\epsilon} \left[ \sup_{\theta \in T} \sum_{j=1}^{\infty} \epsilon_j \theta_j  \right] = \sup_{\theta \in T} \sum_{j=1}^{\infty} | \theta_j |$$
?

A: For a given sequence $\epsilon: \mathbb{N} \to \{-1, +1\}$, define $f_{\epsilon}: T \to T$ by $(f_{\epsilon} \theta)_j = -\theta_j$ if $\epsilon_j \theta_j < 0$ and $(f_{\epsilon} \theta)_j = \theta_j$ otherwise. Then $\sum_{j= 1}^{\infty} \epsilon_j (f_{\epsilon}
 \theta)_j = \sum_{j=1}^{\infty} |\theta_j| \geq \sum_{j= 1}^{\infty} \epsilon_j \theta_j$. Define the set $T_{\epsilon} = \{ \theta \in T: f_{\epsilon} \theta = \theta \}$, i.e. the set of all $\theta \in T$ with $\epsilon_j \theta_j = |\theta|_j$ for all $j$. Clearly
$$\sup_{\theta \in T} \sum_{j= 1}^{\infty} \epsilon_j \theta_j = \sup_{\theta \in T_{\epsilon} } \sum_{j= 1}^{\infty} \epsilon_j \theta_j = \sup_{\theta \in T_{\epsilon} } \sum_{j= 1}^{\infty} |\theta_j| = \sup_{\theta \in T} \sum_{j= 1}^{\infty} |\theta_j|$$
Since equality holds for each Rademacher sequence $\epsilon$, it must hold for the expectation over all $\epsilon$.


text:
Q: Customize Landing pages I am using SOAP API to send the envelopes. I see that once the signing is complete, the user gets redirected to the URL specified under Branding -> Sign Complete.
Is there a way to customize the "You have completed your documents" popup which shows up on the DocuSignComplete.aspx page. We do not want our users to see the Docusign sign up form on this popup. We would like to display our company related information which does not come up until the user clicks on the "X" button on this popup.
Let us know if we should contact Account Manager to process this request.
Thanks
Naresh

A: Update (prepended to original Answer):
[My apologies -- I should have included this information in my original answer. Information in my original answer still applies, but the setting described here addresses another part of your question.]
To remove the "create an account or login" form (and related content) that's displayed in the "Signing Complete" popup window, login to DocuSign as an Administrator, navigate to Preferences >> Features, and uncheck this box:

Original Answer:
In general, many components of the "Signing Complete" popup window can be customized by modifying the Signing Resource file.  That being said though, customizations are for the most part limited to things like hiding/showing certain elements, and changing string values that appear in certain places within that window.  For example:

*

*<data name="DocuSignComplete_ShowSocialNetworks">true</data> --> this element determines whether or not the Social Media content is displayed in the right pane of the window.

*<data name="DocuSignComplete_Success">You have completed your documents</data> --> This element can be used to customize the string value that appears within the window.
So, while customization of this window is possible, you're fairly limited as to the types of things you can customize.  See the Account Branding guide for information about how/where to access Resource files: http://www.docusign.com/sites/default/files/Quick%20Start%20-%20Account%20Branding.pdf.


text:
Q: Why doesn't my Angular directive work if set inside dialog? I have directive for change background color but when set inside dialog no work.
inside dialog:

Users

and inside directive:
  @Input() count!: number;
  @Input() highlightColor!: string;

  console.log("highlightColor", this.highlightColor);
  this.formSelector.nativeElement.style.backgroundColor = this.highlightColor;

NO work..
But when set inside component which is not dialog work...
How to fix this ?


text:
Q: Erro no JavaScript Alguém poderia me dizer como fazer o JOIN para preencher os dados automaticamente a partir do campo descrição. Acusa este erro Notice: Trying to get property of non-object in C:\xampp\htdocs\PhpProject1\function.php on line 9
{"codigo_produto":"","barcode":"","porcao":""} no caso a linha 9 é esta if($resultado->num_rows){
index.php

                Descrição:
                <input type="text" required class="form-control" maxlength="13" name="descri">

                Código do Produto:
                <input type="text" required class="form-control" maxlength="13" name="codigo_produto">

                Código EAN:
                <input type="text" required class="form-control" maxlength="13" name="barcode">

                Tipo:
                <input type="text" class="form-control" name="codigo_tipo" value="">

                Porção:
                <input type="text" class="form-control" maxlength="20"  name="porcao">

function.php
   function retorna($descricao, $conn){

        $result = "SELECT a.descricao, a.codigo_produto, a.barcode, b.codigo_tipo, c.porcao FROM CADPRO A
            LEFT OUTER JOIN TIPOPROD B ON (A.CODIGO_PRODUTO = B.CODIGO_PRODUTO)
            LEFT OUTER JOIN INFOPROD C ON (B.CODIGO_PRODUTO = C.CODIGO_PRODUTO) WHERE descricao =";
        $resultado = mysqli_query($conn, $result);

        if(!is_null($resultado)){
            $row = mysqli_fetch_assoc($resultado);
                $valores['codigo_produto'] = $row['codigo_produto'];
                $valores['barcode'] = $row['barcode'];
                $codigo_produto = $row['codigo_produto'];
                $valores['codigo_tipo'] = $row['codigo_tipo'];
                $valores['porcao'] = $row['porcao'];
        } else {
                $valores['codigo_produto'] = '';
                $valores['barcode'] = '';
                $valors['tipo'] = '';
                $valores['porcao'] = '';
        }

        return json_encode($valores);
    }
    if(isset($_GET['descricao'])){
        echo retorna($_GET['descricao'], $conn);
    }
    ?>

A: Tenta colocar desta forma:
$resultado = mysqli_num_rows($resultado);

if(!is_null($resultado)){
     ...

Assumindo que você não instanciou a classe mysqli. Veja o exemplo nesta página, interpretando seu código, aparentemente está fazendo de forma procedural.
Desta forma não poderia utilizar nenhum tipo de objeto.

A: Isso não tem sentido:
if(!is_null($resultado)){

O mysqli_query nunca vai retornar NULL, ele sempre vai cair no mesmo if, mesmo que dê erro, no caso ele retornou false e como false não é null ele entra no primeiro if de qualquer jeito, mas o mysqli_fetch_assoc sempre espera um "objeto".
Pra evitar isso é só sempre usar a documentação pra ter certeza de como a função funciona e vai ver http://php.net/manual/en/mysqli.query.php#refsect1-mysqli.query-returnvalues.
Veja a documentação dize que ele retorna FALSE se falhar ou um objeto mysqli_result se tiver sucesso.
Mude o código para:
if($resultado){
    $row = mysqli_fetch_assoc($resultado);
        $valores['codigo_produto'] = $row['codigo_produto'];
        $valores['barcode'] = $row['barcode'];
        $codigo_produto = $row['codigo_produto'];
        $valores['codigo_tipo'] = $row['codigo_tipo'];
        $valores['porcao'] = $row['porcao'];
} else {

Outra sugestão é criar um JSON de erro, assim:
if($resultado){
    $row = mysqli_fetch_assoc($resultado);
        $valores['codigo_produto'] = $row['codigo_produto'];
        $valores['barcode'] = $row['barcode'];
        $codigo_produto = $row['codigo_produto'];
        $valores['codigo_tipo'] = $row['codigo_tipo'];
        $valores['porcao'] = $row['porcao'];
} else {
       return json_encode(array( 'error' => mysqli_error($conn) ));
}

Outro de importante, você não declarou a variavel $valores, mas declarou a variavel $codigo_produto = $row['codigo_produto'];, mas você não esta usando ela, talvez o código deva ficar assim:
function retorna($descricao, $conn){

    $result = "SELECT a.descricao, a.codigo_produto, a.barcode, b.codigo_tipo, c.porcao FROM CADPRO A
        LEFT OUTER JOIN TIPOPROD B ON (A.CODIGO_PRODUTO = B.CODIGO_PRODUTO)
        LEFT OUTER JOIN INFOPROD C ON (B.CODIGO_PRODUTO = C.CODIGO_PRODUTO) WHERE descricao =";
    $resultado = mysqli_query($conn, $result);

    // DECLARA A VARIAVEL
    $valores = array();

    if(!is_null($resultado)){
        $row = mysqli_fetch_assoc($resultado);
        $valores['codigo_produto'] = $row['codigo_produto'];
        $valores['barcode'] = $row['barcode'];
        $codigo_produto = $row['codigo_produto'];
        $valores['codigo_tipo'] = $row['codigo_tipo'];
        $valores['porcao'] = $row['porcao'];
    } else {
        return json_encode(array( 'error' => mysqli_error($conn) ));
    }

    return json_encode($valores);
}


text:
Q: How is the better way to do a "fetchall" to statement in java, for convert after in a json response? I have a sql query, works fine, but I want to show a JSON response, with the result, like fetchall in python, I can the result with a "while" but, there a "fetchall" for java?
This is my code, I want to show the query result in a JSON response:
    @RequestMapping(value="/parity/{date}", method=RequestMethod.GET,
produces = "application/json")
    public ResponseEntity parity(@PathVariable String date) throws SQLException {

        String[] a = date.split("-");
        date = a[0].substring(2) + a[1] + a[2];

        Connection connection = ConnectionS.getInstance().getConnection(env);

        String selectSql = "SELECT EX FROM TS1.EXC WHERE EXT = '"+ date +"' AND EXR=1";
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(selectSql);
        //the fetchall here for translate a JSONresponse below

        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new JsonResponse("ok"));
}

A: Since you're using Spring, use JdbcTemplate and the queryForList method.
String sql = "SELECT EX FROM TS1.EXC WHERE EXT = ? AND EXR=1";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, date);

To learn more, read the Spring Documentation.


text:
Q: Error while executing Merge through shell script I am trying to execute a script which calls Merge statement through sqlplus.
The merge statement is executing fine but when I am executing it through shell script, it's giving an error :
current_time=`date`
echo "FSG_PRCB_PRVD_FAC_SEQ table UPDATE STARTED at $current_time"
Result=`sqlplus -s $TgtUsrID/$TgtPswd@$TgtServer <<eof
whenever sqlerror exit sql.sqlcode;
merge into FSG_WRK.FSG_PRCB_FAC_REF_DATA T1
   using
    (select NUM_ID, ALPHA_NUM_ID from FSG.FSG_PRCB_ADDRESS_CROSSWLK) T2
  ON (T1.ADDR_TYPE=T2.ALPHA_NUM_ID)
when matched then
     update set T1.ADDR_TYPE_N = T2.NUM_ID ;
eof
`

ERRORCODE=$?

#Check the return code from SQL Plus
if [ $ERRORCODE != 0 ]
then
  echo "********************"
  echo "ERROR: Updating Status Failed. ErrorCode: $ERRORCODE"
  exit -1
else
  echo "********************"
  echo "UUpdating Status  returns $Result"
       current_time=`date`
       echo "Updating Status Query finished at $current_time"
fi

Output :

updating status failed.Errorcode:174

I am not sure what went wrong.

A: Using exit sql.sqlcode can be misleading, or even dangerous.
From The Linux Documentation Project:

Out of range exit values can result in unexpected exit codes. An exit value greater than 255 returns an exit code modulo 256. For example, exit 3809 gives an exit code of 225 (3809 % 256 = 225).

You're seeing the exit code reported as 174, but the original error code could have been anything where mod(<actual code>, 256) evaluates to 174. You'll be able to see the actual error code and message in your $Result variable.
A likely candidate is an ORA-00942 error (as mod(942, 256) is 174) - and as you've said the merge works standalone, you'll probably find that the user you're connecting to and running the merge as, represented by $TgtUsrID, does not have the necessary privileges on the tables owned by FSG and/or FSG_WRK.
This shows that the reported exit code can be confusing or misleading. The potentially dangerous part if if you get a real error code which is an exact multiple of 256, such as the plausible ORA-01536 "space quota exceeded for tablespace %s'. As mod(1536, 256) is zero, $ERRORCODE will be zero too, so your check:
if [ $ERRORCODE != 0 ]

will be false even though an error did occur.
It will probably be simpler to change your SQL to have whenever sqlerror exit failure (maybe with the addition of rollback?), and then your check for non-zero will work; and you can use $Result to see/report what was actually wrong.


text:
Q: Showing a set is open with respect to multiple metrics? I've proven that for $1 \leq p < q \leq \infty$, then $\|x\|_q \leq \|x\|_p \leq n^\frac{1}{p}\|x\|_q$. How can I use this to show that if a set $A\subseteq\mathbb{R}^n$ is open with respect to the $d_2$ metric if and only if it is open with respect to the $d_p$ metric for $1 \leq p \leq \infty$?
One idea I have is to compare two balls in $A$: $B^2_r(a) = \{x\in A|d(x,a) < r_2\}$ (for the $d_2$ metric), and $B^p_r(a) = \{y\in A|d(y,a) < r_p\}$ (for the $d_p$ metric). I'm not sure where to go from here, though; should I try to show that for $p > 2, B^2_r(a) \subseteq B^p_r(a)$ and vice-versa for $p \leq 2$? Or perhaps I should compare the radii $r_2$ and $r_p$? I'm starting to think it's not so helpful to compare two balls centered around the same point...

A: My proof is for normed spaces although you claim this is a metric space problem, you seem to be working with norms.
Let $1 \le p < q < \infty$. And we assume to be familiar with $\lVert x \rVert_q \le \lVert x \rVert_p  \le n^{\frac{1}{p}} \lVert x \rVert_q $
Now on the one hand, if $A \subset \mathbb{R}^n$  is open in the $p$ norm then for $a\in A$ there exists $\varepsilon >0$ such that the $p-$Ball is a subset of $A$.
$$B_\varepsilon^{(p)} (a) =\{x\in X : \lVert x-a \rVert_p < \varepsilon \} \subset A$$
It clearly follows that  $B_\varepsilon^{(q)}(a) = \{x\in X : \lVert x-a \rVert_q <\lVert x-a \rVert_p < \varepsilon \}\subset B_\varepsilon^{(p)} (a) \subset A$
On the other hand, if for all $a\in A$ there exists $\epsilon >0$ such that $B_\epsilon^{(q)} (a) \subset A$ then just set $\epsilon'= \sup_{x\in A } \lVert x-a\rVert_q n^{\frac{1}{p}} $.  Clearly $B_{\epsilon'}^{(p)} =\{x\in X : \lVert x-a \rVert_p < \epsilon' \} \subset A$


text:
Q: Getting the cell reference for a cell that's found by looping through an array? I'm building a macro that needs to find a row based on the value in one column, then find the start of the data in that row, then cut that information and paste it onto a different sheet. I'm falling at the first hurdle because although I can get my array to loop through the column and find instances of the value, I can't seem to then get the cell reference of the value.
I've tried using the Range.Address function but that gets me a runtime error 424 Object required error. I'm not sure how to get the address. The code has found the value in the array, so it must know where that value is stored. Here's what I have so far
Dim element As Variant
Dim checker As Boolean
Dim elementAddr As String

MyArray = Range("S2:S10").Value2

For Each element In MyArray
    If element = "Completed." Then
    elementAddr = element.Address
    Worksheets("Test").Range("A1").Value = elementAddr
    Exit For
    End If
Next element

End Sub

So other than the error when trying to get the reference, the array loop works perfectly. Once the loop has found a cell in the array that says "Completed.", how can I then grab the reference of that cell as a string?

A: As BigBen notes you can use Match():
Dim m

With Range("S2:S10")
    m = Application.Match("Completed.",.cells, 0)
    If Not IsError(m) Then Range("A1").value = .Cells(m).Address
End With

or Find():
Dim f As Range

Set f = Range("S2:S10").Find("Completed.", lookat:=xlWhole)
If Not f Is Nothing Then Range("A1").value = f.Address


text:
Q: How to tell the UITableView to bounce into place programatically? My goal is pretty straightforward:
The user should be able to move cells in the UITableView up and down by using the provided buttons. I want the new selected cell to appear exactly where the old selected cell was with the exception of the scrolling being at the the beginning of end of the tableview.
I tried using
[table selectRowAtIndexPath:newIndexPath animated:false scrollPosition:UITableViewScrollPositionMiddle];

But the problem is that the row is always moved to the same position near the center of the screen which I don't want.
I want to center the
table.contentOffset.y

exactly where I am programmatically placing it. However, when I set this with
[table setContentOffset:CGPointMake(0, newVerticalContentOffset)];

so I did exactly that. Now I have the problem of the scrolling going way outside the the table and even the normal bounce range. The only way to get it to 'bounce' back is if the user scroll touches the list.
I also tried programmatically setting the offset to the 'min' and 'max' of it happened to go out of those bounds. However, I realized that this was complicated because I have to add the height of the navigation bar and the status bar to get the top coordinates and get the content size to determine the bottom. I think it would be easier if there was simply a way to programmatically 'bounce' or 'release' the tableview back into place. I tried calling the table's delegate with flags like
scrollViewDidScroll

This crashes my application. I realized that even if I did perform one of these last two solutions, that the action would still not represent my goal. If I move a cell down from the top, the view scrolls with it. I do not want that to happen because it is very close to the top. In this case, I wouldn't mind it making its way to the middle before scrolling the view.
The best idea I have so far is somehow attempting to center scroll the cell and if it is able to be centered (meaning it is not near the top or bottom), not to actually center it.
I thought about performing a centering then checking if the y coordinate changed by exactly 1 cell and leaving it if it did, otherwise using the old position. However, I imagine that the user may be somewhere near the middle of the list and happens to be exactly 1 cell away from the middle. When he moves the cell, it will move 'unexpectedly' which is not what I want.


text:
Q: Why doesnt my stack trace include the page that it was originally called from? As I understand asp.net exceptions. If I have a page that calls some code that in turns calls another bit of code. If the last bit of code (say its in a different dll) throws an exception, and its handled nowhere then I should get the page throw an error out on a YSOD that has the stack trace which shows in reverse chronological order what happened. So i will get at the bottom of the stack trace the first bit of code that was executed then above it the next flowing all the way to the top where is the actual error happened.
This in mind I have an application that is not showing the aspx page in the stack trace. Also its not showing the usual initial calls to the asp.net stack like:

at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp,
  Object o, Object t, EventArgs e) at
  System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender,
  EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at
  Community.Support.BasePage.OnLoad(EventArgs e) in
  C:\Projects\Unilever\BinaryFiles\Support\BasePage.cs:line 389 at
  System.Web.UI.Control.LoadRecursive() at
  System.Web.UI.Page.ProcessRequestMain(Boolean
  includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

I cant really see why. The only hint im getting is that reflection is being used and I'm wondering is this why?

A: Since you are using a BasePage class, a great way to get detailed information is to override the OnError method; this method fires for all unhandled errors in the page. Then, collect information about the page and add it to the error, or add it to the logged statement.
HTH.


text:
Q: Docker fails to build - Create React App + Tailwind /bin/sh: craco: not found I've been stuck with this problem for a couple of days now. I am trying to dockerize a django REST API + react (create-react-app) application. The react application uses craco for building since I am using tailwindcss. I followed the this guide to integrate Tailwind with the React app and it's working when I run yarn start locally.
Guide: https://tailwindcss.com/docs/guides/create-react-app
The problem is it is throwing /bin/sh: craco: not found error when I run it using docker-compose. I even tried adding RUN yarn add @craco/craco -g after RUN yarn in the frontend Dockerfile but it is showing the same error.
Error when running docker-compose up --build:
...
Step 8/9 : COPY . /app/frontend/
 ---> 19e0247cde64
Step 9/9 : EXPOSE 3000
 ---> Running in 43f7d970d460
Removing intermediate container 43f7d970d460
 ---> a20ae2148d4b

Successfully built a20ae2148d4b
Successfully tagged react_frontend:latest
Creating react_frontend_container ... done
Attaching to react_frontend_container
yarn run v1.22.15
$ craco start
frontend_1  | /bin/sh: craco: not found
error Command failed with exit code 127.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
react_frontend_container exited with code 127

Frontend Dockerfile:
FROM node:16-alpine

WORKDIR /app/frontend

COPY package.json .
COPY yarn.lock .

RUN yarn

COPY . /app/frontend/
EXPOSE 3000

docker-compose.yml:
version: '3.8'

services:
  ... (postgres db and django api services)

  frontend:
    build: ./frontend
    command: ["yarn", "start"]
    stdin_open: true # docker run -i
    tty: true        # docker run -t
    volumes:
      - ./frontend:/app/frontend
      - node-modules:/app/frontend/node_modules
    container_name: react_frontend_container
    ports:
      - "3000:3000"

volumes:
  node-modules:

package.json:
{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@craco/craco": "^6.4.3",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "autoprefixer": "^9",
    "postcss": "^7",
    "tailwindcss": "npm:@tailwindcss/postcss7-compat"
  }
}

A: The issue is that you map your host directory and volume onto the directories in the image that contain the node modules and the app files.
Try removing this section in the docker-compose file. That way you won't overwrite what's in the image and craco will be available.
volumes:
  - ./frontend:/app/frontend
  - node-modules:/app/frontend/node_modules

One thing to be aware of when you use docker-compose to both build and run your image, is that the volumes are only mapped during the run phase and not during the build.

A: @Hans Kilian answer solves the problem but when you edit, your code changes don't reflect.
With the anonymous volume ('/app/frontend/node_modules'), the node_modules directory wouldn't be overwritten by the mounting of the host directory at runtime
By changing your volumes section, you solve your issue and keep the fast development feedback loop
volumes:
  - ./frontend:/app/frontend
  - /app/frontend/node_modules

You can read more here
I had the same issue and solved by doing above ^


text:
Q: z3c.form and Plone - add custom css file to a form without using a custom template In a project I'm working on we've defined a simple z3c.form, it looks like this.
class IImportCandidateForm(Interface):
    csv_file = NamedFile(title=_(u'CSV file'))

class ImportForm(form.Form):
    fields = field.Fields(IImportForm)
    ignoreContext = True

    def updateWidget(self):
        super(ImportForm, self).updateWidget()

    ... snip ...

    @button.buttonAndHandler(u'Import')
    def handleImport(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorMessage
            return
        file = data["csv_file"].data

Is there a way to associate a custom css file with this form without first wrapping it in a custom page template with the form?

A: No, there isn't. Unless you use a form wrapper, the form's template renders only the form and not the entire page.

A: In you are using this form in a custom view, you have a class style added to the body class (something like template-yourviewname). So you can add you CSS rules to a main CSS resource, loaded in every page, but prefix every rule with .template-yourviewname.


text:
Q: css flex ul with first and last fixed li Ok, I am now starting to use flexbox a bit more, but it is not very logic to me as an old man,
I  have an unsorted horizontal list (ul) with  +/- 10 items (li) That consist out only 1 row, no word wrap etc.   What I want is that the first and the last one are always visible, and the others can have a 'display:none' if there is not enough screen space. The li;s can have different widths on every page. I have now this code, and it sort of works, but a list item is now half visible if the screen or browser is not wide enough. They should go completely not visible,
how can I achieve this?  I have tried many things ....

ul{
list-style: none;

width: 100%;
display: flex;
flex-direction: row;
flex-wrap: nowrap ;
overflow: hidden;
white-space: nowrap;
position: relative

}
ul li{
flex: auto;
display:  inline-block;
line-height: 30px;
float: left;
margin-right: 0px;

}
ul li.b{
background:#ccc;
position: absolute;
right: 0
}

ul li a{
display: inline-block;
margin-right: 0px;
padding: 0 10px 0 10px
}

fixed

2 test

3 test

4 test

5 test

6 test

7 test

8 test

9 test

last fixed

A:
"Make become invisible if they are shown only partially"

Unfortunately this isn't possible using flex-boxes.
But, this is possible using display: block; float: left; and overflow: hidden;
See example here: https://jsfiddle.net/q4m2grnz/
However I advise agains't this method, and any others that don't use media query's.
Media Queries are the standard for any dynamic functionality based on screen size.

A: Try getting rid of position: absolute for the last li and add justify-content: space-between to the flex container (ul), which will seperate the remaining two elements when the others are hidden.
Also the 'ul' comes width a padding so you have to set padding: 0 to reset that.
One other thing is that you are using flex: auto on li items which expands them if you remove that part everything should be in place.


text:
Q: How do you go from $E[X]$ equation to $Var(x)$ equation in the picture? On the following picture, how do you go from equation 4 to 6? I just don't get how variance can be derived from expected value.
Thank you so much

A: You should state that the random variables $\{D_{t}\}$ is i.i.d, and is independent to the random variable $L$, then we can get the following deduction:
\begin{align*}
Var(X) &=E[X^2]-E[X]^2=E\left[(\sum^{L}_{t=1}D_t)^2\right]-E[X]^2 \\
&=E\left[\sum^{L}_{t=1}D^2_t+\sum^{L}_{i=1}\sum^{L}_{j=1,j\neq i}D_iD_j\right]-l^2d^2 \\
&=E[L]E[D^2_t]+E(D_i)E[D_j]E[L(L-1)]-l^2d^2 \\
&=l(d^2+\sigma^2_D)+d^2(l^2-l+\sigma^2_L)-l^2d^2 \\
&=l\sigma^2_D+d^2\sigma^2_L.
\end{align*}

A: $$\begin{align}&\mathsf E(X)
\\[2ex]=~&\mathsf E(\mathsf{Var}(X\mid L))+\mathsf{Var}(\mathsf E(X\mid L))&&\text{Law of Total Variance}
\\[2ex] =~&\mathsf E(\mathsf {Var}(\sum_{t=1}^LD_t\mid L))+\mathsf{Var}(\mathsf E(\sum_{t=1}^L D_t\mid L))&&X=\sum_{t=1}^LD_t
\\[2ex] =~&\mathsf E(\sum_{t=1}^L\mathsf {Var}(D_t\mid L))+\mathsf{Var}(\sum_{t=1}^L\mathsf E( D_t\mid L))&&{\text{Linearity of Expectation,}\\\text{ Bilinearity of Covariance}\\\text{ and uncorrelation of all $D_t$}}
\\[2ex] =~&\mathsf E(\sum_{t=1}^L~\mathsf{Var}(D_t))+\mathsf{Var}(\sum_{t=1}^L~\mathsf E(D_t))&&\text{independence of $L$ and $D_t$}
\\[2ex]=~&\mathsf E(L~\mathsf{Var}(D_1))+\mathsf{Var}(L~\mathsf E(D_1))&&\text{identical distribution of all $D_t$}
\\[2ex]=~&\mathsf E(L)~\mathsf{Var}(D_1)+\mathsf{Var}(L)~\mathsf E(D_1)^2&&{\text{expectation, and variance,}\\\text{ of a scalar product of a RV}}\end{align}$$


text:
Q: Redirect to different page using a variable from the current page url in razor I've inherited a project that used to use razor (cshtml) to render pages. Users have bookmarked the old workflow that uses razor and I need to redirect them to the same page in the new workflow. The urls for the current pages use an id to indicate what entity is being shown. Like so:
https://mywebsite.com/oldworkflow/253432
where 253432 is the id of the entity they are viewing in the old workflow.
How do I grab that Id on the end and use it to redirect to the new workflow?
https://mywebsite.com/newworkflow/253432


text:
Q: How to decrypt multiple pdf files using qpdf? I have some n number of pdf files which are SECURED( i.e not password secured, but owner secured). I was able to decrypt single pdf at a time using _
"qpdf --decrypt Input.pdf Output.pdf" from Cmd Promt in Windows.
can you help me to do the same with multiple pdf's using batch file or from cmd prompt.

A: If you just want to run the command from the shell (cmd.exe), you can do something like this from the directory containing the PDFs:
for %a in ("*.pdf") do "c:\Programs\qpdf\bin\qpdf.exe" --decrypt "%a" "%~dpna.decrypted.pdf"

A: @echo off

    setlocal enableextensions disabledelayedexpansion

    if not exist output\ md output
    for %%a in (*.pdf) do qpdf --decrypt "%%~fa" "output\%%~nxa"

Create an output folder under current directory. Then for each pdf in current folder call qpdf to decrypt, passing as argument the full path of the input file (%%~fa) and the output file, that is, the output folder followed by the name and extension of the file being processed (%%~nxa)

A: #!/bin/bash
# unprotect multiple pdf files in a directory with qpdf 10Jan20
# run the script from the same directory as the files
if [ -d output ];
then
    echo "output directory exists"
else
    mkdir output
fi

yourfilenames=`ls *.pdf`
#echo yourfilenames
for eachfile in $yourfilenames
do
   echo $eachfile
    qpdf --decrypt $eachfile    output/$eachfile
done

A: Try this: Place all the pdfs in one folder and navigate with cmd prompt to that folder.
Execute the following commands:
mkdir output
qpdf --decrypt *.pdf output/*.pdf


text:
Q: How could I make this EF Core query better? I need to fetch from the database this:

*

*rack

*it's type

*single shelf with all its boxes and their box types

*single shelf above the previous shelf without boxes and with shelf type

Shelves have VerticalPosition which is in centimeters from the ground - when I am querying for e.g. second shelf in rack, I need to order them and select shelf on index 1.
I have this ugly EF query now:
var targetShelf = await _warehouseContext.Shelves
    .Include(s => s.Rack)
        .ThenInclude(r => r.Shelves)
            .ThenInclude(s => s.Type)
    .Include(s => s.Rack)
        .ThenInclude(r => r.Type)
    .Include(s => s.Rack)
        .ThenInclude(r => r.Shelves)
    .Include(s => s.Boxes)
        .ThenInclude(b => b.BoxType)
    .Where(s => s.Rack.Aisle.Room.Number == targetPosition.Room)
    .Where(s => s.Rack.Aisle.Letter == targetPosition.Aisle)
    .Where(s => s.Rack.Position == targetPosition.Rack)
    .OrderBy(s => s.VerticalPosition)
    .Skip(targetPosition.ShelfNumber - 1)
    .FirstOrDefaultAsync();

but this gets all boxes from all shelves and it also shows warning
Compiling a query which loads related collections for more than one collection navigation, either via 'Include' or through projection, but no 'QuerySplittingBehavior' has been configured. By default, Entity Framework will use 'QuerySplittingBehavior.SingleQuery', which can potentially result in slow query performance.

Also I would like to use AsNoTracking(), because I don't need change tracker for these data.
First thing: for AsNoTracking() I would need to query Racks, because it complains about circular include.
Second thing: I tried conditional include like this:
.Include(r => r.Shelves)
    .ThenInclude(s => s.Boxes.Where(b => b.ShelfId == b.Shelf.Rack.Shelves.OrderBy(sh => sh.VerticalPosition).Skip(shelfNumberFromGround - 1).First().Id))

but this won't even translate to SQL.
I have also thought of two queries - one will retrieve rack with shelves and second only boxes, but I still wonder if there is some single call command for this.
Entities:
public class Rack
{
    public Guid Id { get; set; }
    public Guid RackTypeId { get; set; }

    public RackType Type { get; set; }
    public ICollection<Shelf> Shelves { get; set; }
}

public class RackType
{
    public Guid Id { get; set; }

    public ICollection<Rack> Racks { get; set; }
}

public class Shelf
{
    public Guid Id { get; set; }
    public Guid ShelfTypeId { get; set; }
    public Guid RackId { get; set; }
    public int VerticalPosition { get; set; }

    public ShelfType Type { get; set; }
    public Rack Rack { get; set; }
    public ICollection<Box> Boxes { get; set; }
}

public class ShelfType
{
    public Guid Id { get; set; }

    public ICollection<Shelf> Shelves { get; set; }
}

public class Box
{
    public Guid Id { get; set; }
    public Guid ShelfId { get; set; }
    public Guid BoxTypeId { get; set; }

    public BoxType BoxType { get; set; }
    public Shelf Shelf { get; set; }
}

public class BoxType
{
    public Guid Id { get; set; }

    public ICollection<Box> Boxes { get; set; }
}

I hope I explained it good enough.

A: Query Splitting
First, I'd recommend benchmarking the query as-is before deciding whether to attempt any optimization.
It can be faster to perform multiple queries than one large query with many joins. While you avoid a single complex query, you have additional network round-trips if your DB isn't on the same machine, and some databases (e.g. SQL Server without MARS enabled) only support one active query at a time. Your mileage may vary in terms of actual performance.
Databases do not generally guarantee consistency between separate queries (SQL Server allows you to mitigate that with the performance-expensive options of serializable or snapshot transactions). You should be cautious using a multiple-query strategy if intervening data modifications are possible.
To split a specific query, use the AsSplitQuery() extension method.
To use split queries for all queries against a given DB context,
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder
        .UseSqlServer(
            @"Server=(localdb)\mssqllocaldb;Database=EFQuerying;Trusted_Connection=True;ConnectRetryCount=0",
            o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
}

Reference.
Query that won't translate
.Include(r => r.Shelves)
    .ThenInclude(s => s.Boxes.Where(b => b.ShelfId == b.Shelf.Rack.Shelves.OrderBy(sh => sh.VerticalPosition).Skip(shelfNumberFromGround - 1).First().Id))

Your expression
s.Boxes.Where(b => b.ShelfId == b.Shelf.Rack.Shelves.OrderBy(sh => sh.VerticalPosition).Skip(shelfNumberFromGround - 1).First().Id

resolves to an Id. ThenInclude() expects an expression that ultimately specifies a collection navigation (in other words, a table).

A: Ok, from your question I'm assuming you have a method where you need these bits of information:

*

*single shelf with all its boxes and their box types

*single shelf above the previous shelf without boxes and with shelf type

*rack and it's type

Whether EF breaks up the queries or you do doesn't really make much of a difference performance-wise. What matters is how well the code is later understood and can adapt if/when requirements change.
The first step I would recommend is to identify the scope of detail you actually need. You mention that you don't need tracking, so I would expect you intend to deliver these results or otherwise consume the information without persisting changes. Project this down to just the details from the various tables that you need to be served by a DTO or ViewModel, or an anonymous type if the data doesn't really need to travel. For instance you will have a shelf & shelf type which is effectively a many-to-one so the shelf type details can probably be part of the shelf results. Same with the Box and BoxType details. A shelf would then have an optional set of applicable box details. The Rack & Racktype details can come back with one of the shelf queries.
[Serializable]
public class RackDTO
{
    public int RackId { get; set; }
    public int RackTypeId { get; set; }
    public string RackTypeName { get; set; }
}

[Serializable]
public class ShelfDTO
{
    public int ShelfId { get; set; }
    public int VerticalPosition { get; set; }
    public int ShelfTypeId { get; set; }
    public string ShelfTypeName { get; set; }
    public ICollection<BoxDTO> Boxes { get; set; } = new List<BoxDTO>();
    public RackDTO Rack { get; set; }
}

[Serializable]
public class BoxDTO
{
    public int BoxId { get; set; }
    public int BoxTypeId { get; set; }
    public string BoxTypeName { get; set; }
}

Then when reading the information, I'd probably split it into two queries. One to get the "main" shelf, then a second optional one to get the "previous" one if applicable.
ShelfDTO shelf = await _warehouseContext.Shelves
    .Where(s => s.Rack.Aisle.Room.Number == targetPosition.Room
        && s.Rack.Aisle.Letter == targetPosition.Aisle
        && s.Rack.Position == targetPosition.Rack)
    .Select(s => new ShelfDTO
    {
        ShelfId = s.ShelfId,
        VerticalPosition = s.VerticalPosition,
        ShelfTypeId = s.ShelfType.ShelfTypeId,
        ShelfTypeName = s.ShelfType.Name,
        Rack = s.Rack.Select(r => new RackDTO
        {
            RackId = r.RackId,
            RackTypeId = r.RackType.RackTypeId,
            RackTypeName = r.RackType.Name
        }).Single(),
        Boxes = s.Boxes.Select(b => new BoxDTO
        {
            BoxId = b.BoxId,
            BoxTypeId = b.BoxType.BoxTypeId,
            BoxTypeName = b.BoxType.Name
        }).ToList()
     }).OrderBy(s => s.VerticalPosition)
    .Skip(targetPosition.ShelfNumber - 1)
    .FirstOrDefaultAsync();

ShelfDTO previousShelf = null;
if (targetPosition.ShelfNumber > 1 && shelf != null)
{
    previousShelf = await _warehouseContext.Shelves
        .Where(s => s.Rack.RackId == shelf.RackId
            && s.VerticalPosition < shelf.VerticalPosition)
        .Select(s => new ShelfDTO
        {
            ShelfId = s.ShelfId,
            VerticalPosition = s.VerticalPosition,
            ShelfTypeId = s.ShelfType.ShelfTypeId,
            ShelfTypeName = s.ShelfType.Name,
            Rack = s.Rack.Select(r => new RackDTO
            {
                RackId = r.RackId,
                RackTypeId = r.RackType.RackTypeId,
                RackTypeName = r.RackType.Name
        }).Single()
     }).OrderByDescending(s => s.VerticalPosition)
    .FirstOrDefaultAsync();
}

Two fairly simple to read queries that should return what you need without much problem. Because we project down to a DTO we don't need to worry about eager loading and potential cyclical references if we wanted to load an entire detached graph.  Obviously this would need to be fleshed out to include the details from the shelf, box, and rack that are relevant to the consuming code/view.  This can be trimmed down even more by leveraging Automapper and it's ProjectTo method to take the place of that whole Select projection as a one-liner.

A: In SQL raw it could look like
WITH x AS(
    SELECT
      r.*, s.Id as ShelfId, s.Type as ShelfType
      ROW_NUMBER() OVER(ORDER BY s.verticalposition) as shelfnum
    FROM
      rooms
      JOIN aisles on aisles.RoomId = rooms.Id
      JOIN racks r on r.AisleId = aisles.Id
      JOIN shelves s ON s.RackId = r.Id
    WHERE
      rooms.Number = @roomnum AND
      aisles.Letter = @let AND
      r.Position = @pos
)

SELECT *
FROM
  x
  LEFT JOIN boxes b
  ON
    b.ShelfId = x.ShelfId AND x.ShelfNum = @shelfnum
WHERE
  x.ShelfNum BETWEEN @shelfnum AND @shelfnum+1

The WITH uses room/aisle/rack joins to locate the rack; you seem to have these identifiers. Shelves are numbered in increasing height off ground. Outside the WITH, boxes are left joined only if they are on the shelf you want, but two shelves are returned; the shelf you want with all it's boxes and the shelf above but box data will be null because the left join fails

A: As an opinion, if your query is getting this level of depth, you might want to consider either using views as a shortcut in your database or use No-SQL as a read store.
Having to do lots of joins, and doing taxing operations like order by during runtime with LINQ is something I'd try my best to avoid.
So I'd approach this as a design problem, rather than a code/query problem.

A: In EF, All related entities loaded with Include, ThenInclude etc. produce joins on the database end. This means that when we load related master tables, the list values will get duplicated across all records, thus causing what is called "cartesian explosion". Due to this, there was a need to split huge queries into multiple calls, and eventually .AsSplitQuery() was introduced.
Eg:
 var query = Context.DataSet<Transactions>()
.Include(x => x.Master1)
.Include(x => x.Master2)
.Include(x => x.Master3)
.ThenInclude(x => x.Master3.Masterx)
.Where(expression).ToListAsync();

Here we can introduce splitquery
 var query = Context.DataSet<Transactions>()
.Include(x => x.Master1)
.Include(x => x.Master2)
.Include(x => x.Master3)
.ThenInclude(x => x.Master3.Masterx)
.Where(expression).AsSplitQuery.ToListAsync();

As an alternate to include this to all existing queries, which could be time consuming, we could specify this globally like
services.AddDbContextPool<EntityDataLayer.ApplicationDbContext>(options =>
{
  options.EnableSensitiveDataLogging(true);
  options.UseMySql(mySqlConnectionStr,
  ServerVersion.AutoDetect(mySqlConnectionStr), x =>
  x.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)
  x.EnableRetryOnFailure(
      maxRetryCount: 10,
      maxRetryDelay: TimeSpan.FromSeconds(30),
      errorNumbersToAdd: null));
});

This will ensure that all queries are called as split queries.
Now in case we need single query, we can just override this by stating single query explicitly in individual queries. This may be done vice-versa though.
var data = await query.AsSingleQuery().ToListAsync();


text:
Q: i able to not display breadcrumbs full path as per provided info? I using breadcrumbs but page title show in last
like: Home>category>sub category> Page title
I can display only Like: Home>category>sub category
don't display page title in website


text:
Q: Remove select all from library view How can I remove the check box select all in a library view?
I'm using SP2010 Enterprise.
Thanks

A: The following steps will help you remove the checkbox:

Uncheck the option "Allow individual item checkboxes"


text:
Q: Check each column in orderly way if a specified value is present My table have 3 columns namely:

*

*Actual Key

*Confirmed Key

*Present Key
I am trying to get or query the table with the condition that if "X" value is present or is the value of any of those columns but in a hierarchical order, then return those data.
It is identified in this order:
1.Actual Key
2.Confirmed Key
3.Present Key

Example:
Checking 1: If X is present ONLY in Actual Key column then return that row. Else, proceed to checking # 2
Checking 2: If X is present ONLY in Confirmed Key column then return that row. Else, proceed to checking # 3
Checking 3: If X is present ONLY in Present Key column then return that row. Else, proceed to checking # 4
Checking 4: If X is not present in ANY of those 3 columns then return no data
I am trying to use SQL CASE Statements (https://www.w3schools.com/sql/sql_case.asp)  but I am not quite sure how to work with it.
I'm using Microsoft SQL Server Management Studio 18
Microsoft SQL Server 2019 (RTM-GDR) (KB4583458) - 15.0.2080.9 (X64)
Thanks for the help.

A: Your solution is something like this.
WHERE
(ActualKey = x and ConfirmedKey != x and PresentKey != x) or
(ActualKey != x and ConfirmedKey = x and PresentKey != x) or
(ActualKey != x and ConfirmedKey != x and PresentKey = x)

A: You can go for COALESCE Clause.
DECLARE @table table(Actualkey char(1), confirmedkey char(1), presentkey char(1))

insert into @table
values ('x',null,null), (null,'x',null),(null,null,'x'),(null,null,null)

SELECT * FROM @table where coalesce(actualkey, confirmedkey, presentkey) = 'x'

Actualkey
confirmedkey
presentkey

x
NULL
NULL

NULL
x
NULL

NULL
NULL
x

A: You want to use select top with order by:
select top (1) t.*
from t
where @x in (ActualKey, ConfirmedKey, PresentKey)
order by (case when @x = ActualKey then 1
               when @x = ConfirmedKey then 2
               when @x = PresentKey then 3
          end);


text:
Q: Should I create a (new) project for shared UserControls? Context: I'm creating some applications to help me on my daily tasks, it does not connect anywhere and the only "data" it has to deal with is the parameters that I enter on the input fields.
This is how I structured my solution:
|- Helpers (Folder + Class Library)
|- Core (Folder + Class Library)
|- Shared (Folder + Shared project)
|- Apps (Folder + WPF Projects)
|---- App1 (WPF Project)
|---- App2 (WPF Project)
|---- App3 (WPF Project)
While developing the first application (App1) I've created a few UserControls. Now I want to use those user controls on the second application (App2).
Question is: Should I create a new project to hold all these UserControls and reference it from App1, App2 and App3? Should it be a WPF Project?
If not, what should I do?
Additional info: I'm using MVVM.
Thank you!

A:
Should I create a new project to hold all these UserControls and reference it from App1, App2 and App3?

That's the general idea, yes. Anytime you have functionality that is common to several projects, the way you prevent code duplication is by putting the common functionality into its own assembly.

A: Yes you should, if you know you will use something on multiple projects you want to make it easily portable. From my previous experiences, you really want to give you easy access to things you have already done in order to avoid duplication.


text:
Q: hardening graphite (Carbon) I would like to use graphite to collect metrics from different servers.
By default, carbon listens on 2003 on all interfaces, which is fine with me.
Now anyone could theoretically send metric data there. Is there a standard way to prevent this from happening (similar to http base auth ) or do I need to mess with IP based restrictions on the physical interface?

A: It depends on how much you want to "harden" any Graphite nodes ("Graphite" being whatever mixture topology of carbon-relays, carbon-caches, storage backend, and potentially graphite-web/api).
If you know which hosts in your network should be sending metrics to Graphite (typically relays), you can modify your Graphite host firewall rules to expect either from an explicit list of host IPs or range for the applicable ports. Or you could do something similar at the edge network from firewall or router - I have no advice there as your question doesn't give a fuller scope of what your topology looks like.
An alternative approach would be to use the AMQP support to instead have your nodes publish their metrics to a broker as an authenticated user and then have your Graphite host(s) modify host firewall to only accept TCP 2003 from the broker metrics are being received. The upside here is your Graphite node(s) only need to know what broker metrics will be coming to it from, which drastically simplifies any host firewall rules. Having nodes publish metrics through a lightweight service secures things a bit better in that the "trust" concern you have is taken care of at the top of the flow rather than the eventuality of metrics - legit or not - arriving at your Graphite host(s). RabbitMQ is OSS and pretty simple to get up and going without needing to mess around too much with configuration if you pull in the Management Plugin. Most of its config is opening necessary ports for operation.
However, this makes a simple metric publisher to Graphite topology a bit more complex for the task and firmly establishes a pub/sub model for how your metrics get to Graphite (but does come with a nice side benefit of allowing metrics in transit to not be lost potentially). It also adds yet another host to secure within operational reason.
To go way further, you could implement a log monitoring system to watch carbon-relay's listener.log file as it will write a line for every metric received and processed. At a high level you'd watch that log looking for exceptions to metrics you expect. Like if you have a server.cpu.load metric, you'd expect to see those getting processed, but a metric posted called foo.bar.value is not valid. As a response to such an event, you could simply wipe the corresponding directory Whisper creates for the invalid namespace (if you use Whisper for storage).
Hardening Graphite's carbon-relay and carbon-cache are fine and a smart thing to do, but do not forget it's just as concerning over who can access your Graphite webapp or graphite-api to get those metrics out.


text:
Q: Asp.net Intranet Application in local Networks with out IP I developed an asp.net (2.0) intranet Application  for local network in an organisation..
so we have 10 systems every one should access that site by ://192.xxx.x.xx/xyz(website name) ...
so now their requirement is not to type total ip adress.they need just by typing ://xyz they have to  browse the intranet application..how to solve this issue..?
Thanks
Veduru

A: Go to every one of this 10 computers, and in this directory
c:\WINDOWS\system32\drivers\etc\

find the host file and add the conversion of ip to name as
192.168.1.10  xyz

etc
and then you can access the site as http://xyz

A: Talk to your network admin about setting up a DNS entry for your application in the local DNS server.  If you have multiple web sites running on your web server, look into configuring IIS host headers to ensure the users get directed to the proper web application.
Please do not manually edit the hosts file on each machine unless it is absolutely, positively necessary, and only do so as a last resort.  When your 10-machine application expands to 100, or if your server IP ever changes, you will thank me later :)


text:
Q: json_decode is not working on a string with \ in it I have a  a ajax call in which I am sending json_string as a post variable.   which I am decoding using json_decode at server,  but  it fails  when the string contains  \ in it.
    $arr = array("data-0"=>'{"id":"Ch35ZWIjfMwG5EUWlVJvGJGWeZi+j+v27AGX+qtUZ14=","pos_x1":"0","pos_y1":"0"}',
                "data-1"=>'{"id":"h+ZjS3+FBoEebtxsHGmgbr\Dy8zTmgrLjhcZH8z3enpw=","pos_x1":"1","pos_y1":"152"}');

foreach($arr as $key=>$val)
print_r(json_decode($val,true));

When I  try running the above,  The second value is not being decoded.
The "id" value is encrypted text, so have no control on it.
Tried addslashes, but no use.

A: That's because \D is not a valid escape sequence. addslashes will put slashes before all the "s, which will just make it worse.
Instead, consider fixing your JSON source - I know you said it's encrypted text, but that doesn't mean you can't properly json_encode it in the first place to get your data.


text:
Q: Is the OpenCV 2 framework available for armv6? I'm using OpenCV for one of my project for which I cannot afford to drop the armv6 devices. For some reason, the official framework built for iOS seems to only support armv7 and x86. Would it be possible to build this lib for armv6 + armv7?
Thanks in advance for any hints or help.

A: Official distribution does not support armv6. But it should be possible to hack and rebuild the framework with armv6 support.

A: As Andrey mentioned there is no official ARMv6 support.
But take a look at this blog post (it's pretty old): Computer vision with iOS Part 1: Building an OpenCV framework, which will give you a good starting point. Also check out an older Version of the buildscript to see what has changed since ARMv6 support was dropped.
Another thing you should take into account is your deployment target, because iOS 4.3+ requires ARMv7. Should that be the case just go with the official build.
ARMv7s = iPhone 5
ARMv7  = iPhone 3GS, iPhone 4, iPhone 4S, iPod 3G/4G/5G, iPad, iPad 2, iPad 3
ARMv6  = iPhone 2G/3G, iPod 1G/2G


text:
Q: Inserir botão de como chegar num mapa preciso inserir um botão no meu site para que ao clicar uma rota seja estabelecida pegando a localização do cliente até o endereço que já estará estabelecido na página do site.
Aqui vai a página com o mapa e o local que a pessoa pode querer visitar.
http://pousadadasrosas.com/pdr-local.php?ponto_turistico=centro-de-miguel-pereira
Obrigado!

A: Se você usa HTML5 no seu código, é uma tarefa bem simples que você precisa executar.
Antes de mais nada, é necessário obter a localização da empresa. Ela será facilmente obtido através da seguinte função:

function addEmpresaMarker(latitude, longitude, marcadorEmp) {
  var coords = new google.maps.LatLng(latitude, longitude);
  marcadorEmp = new google.maps.Marker {
    map: map,
    position: coords
  };
}

Em seguida, você precisa saber a localização do seu usuário. Existe uma função do HTML5 que permite que você saiba a localização do usuário (Use com moderação). Execute-a e já adicione as coordenadas num novo marcador. Segue função abaixo.

function findUserLocation(marcadorUsu) {
  // Mapa e opções do mapa já estão definidos previamente
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var posicao = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      console.log(posicao); // Confira se a localização está correta
      marcadorUsu = new google.maps.Marker {
        map: map,
        position: posicao
      };
    });
  } else {
    // Browser não suporta Geolocalização ou o usuário impediu o uso
    alert('Falha na tentativa de localização do usuário');
  }
}

Agora, você precisa calcular a rota entre o usuário e a empresa. Para isso, você vai precisar da Google Maps Directions API, que irá calcular distância e mostrar a rota, obviamente. Note que, para calcular a rota, ele precisa de referências dos marcadores de origem e destino. Observe bem a função:

function mostrarCaminho (pointA, pointB) {
  // Aciona a Directions API
  var directionsService = new google.maps.DirectionsService;
  var directionsDisplay = new google.maps.DirectionsRenderer({
      map: mapa,
      suppressMarkers: true, // Não exibe os marcadores da rota, porque senão, pode confundir o usuário
  });
  directionsService.route({
    origin: pointA,
    destination: pointB,
    travelMode: google.maps.TravelMode.DRIVING
  }, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) { // Se deu tudo certo
      directionsDisplay.setDirections(response);
    } else {
      window.alert('Não foi possível exibir o trajeto devido ao seguinte erro: ' + status);
    }
  });
}

Agora é só juntar os comandos que você criou numa única função que será executada quando o botão 'Como chegar' for clicado. A função deve ficar mais ou menos assim:

// AddEmpresaMarker()

var coordsEmp = new google.maps.LatLng(latitude, longitude);
marcadorEmp = new google.maps.Marker {
  map: map,
  position: coordsEmp
};

// FindUserLocation()
// Mapa e opções do mapa já estão definidos previamente

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    var posicao = {
      lat: position.coords.latitude,
      lng: position.coords.longitude
    };
    console.log(posicao); // Confira se a localização está correta
    marcadorUsu = new google.maps.Marker {
      map: map,
      position: posicao
    };
  });
} else {
  // Browser não suporta Geolocalização ou o usuário impediu o uso
  return alert('Falha na tentativa de localização do usuário'); // Esse return é pra finalizar a função. De nada adianta executar toda a função se você não tem uma das posições
}

// MostrarCaminho()
// Aciona a Directions API

var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
  map: mapa,
  suppressMarkers: true, // Não exibe os marcadores da rota, porque senão, pode confundir o usuário
});
directionsService.route({
  origin: pointA,
  destination: pointB,
  travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
  if (status == google.maps.DirectionsStatus.OK) { // Se deu tudo certo
    directionsDisplay.setDirections(response);
  } else {
    alert('Não foi possível exibir o trajeto devido ao seguinte erro: ' + status);
  }
});

Pode ser que tenha algum erro de sintaxe aí no meio, mas é bem tranquilo corrigir.
Qualquer dúvida, comente. Eu vou deixar alguns links que podem te ajudar nesse processo:
Marcadores: https://developers.google.com/maps/documentation/javascript/markers?hl=pt-br
Localização do usuário: https://www.w3schools.com/html/html5_geolocation.asp
Rotas: https://developers.google.com/maps/documentation/directions/intro?hl=pt-br

A: Cara é uma gambiarra, mas funciona.
Eu copiei o link que está no botão e alterei o destino:

COMO CHEGAR

É exatamente o que o cliente quer, é uma gambiarra mas funciona


text:
Q: Why does (6-3x)/2 fail to render here? I have the following code:
$$f_ {Y\mid X}(y\mid x)=\frac{f_ {X,Y}(x,y)}{f_ {X}(x)}=\left\{  \begin{array}{ll} {\displaystyle \frac{1/2}{x/2}=\frac{1}{x}}, &\text{if}~0\leq x\leq 1~\text{and}~0\leq y\leq x, \\ {\displaystyle \frac{3/2}{6−x/2}=\frac{1}{x}}, &\text{if}~1<x\leq 2~\text{and}~0\leq y\leq 2−x. \end{array}$$

with which I actually want to see (6-3x)/2 in the second line of the bracket.

However, it fails to render if I put (6-3x)/2 there.  I have to use this instead:
$$f_ {Y\mid X}(y\mid x)=\frac{f_ {X,Y}(x,y)}{f_ {X}(x)}= \   \left\{  \begin{array}{ll} \frac{1/2}{x/2}=\frac{1}{x}, &  \mbox{if $0 \leq x \leq 1$ and $0 \leq y \leq x$}, \\ \frac{3/2}{\frac{6−3x}{2}}=\frac{1}{x}, &  \mbox{if $1 < x \leq 2$ and $0 \leq y \leq 2−x$}. \end{array} \right.$$

which gives me:

I would like to ask how I can achieve what I want, and why my method fails in the first place.  Thanks.
I also have problem with 2-x not rendered properly if put in the same place.  However, this code works just fine:
$$f_ {Y\mid X}(y\mid x)=\left\{\begin{array}{ll} \frac{1}{x}, &  \mbox{if $0\leq x\leq 1$ and $0\leq y\leq x$}, \\ \frac{1}{2−x}, &  \mbox{if $1< x\leq 2$ and $0\leq y\leq 2−x$}. \end{array} \right.$$

I got:

Why does it work when it's simple, but not in that complicated case?

A: I do not know anything about auto-LaTeX on Google Docs but:

*

*The problem comes from a non-ASCII character, which is supposed to render a minus, but is not an ASCII character. With the naked eye, it is hard to distinguish it from a minus, even for a cat. One way to find these characters is to use this tool, but there are many others. A second instance of this character occurs in 2-x.

*If this is to go into a LaTeX document, you may want to use a more modern syntax.

\documentclass{article}
\usepackage{mathtools}
\begin{document}
\[
f_{Y\mid X}(y\mid x)=\frac{f_ {X,Y}(x,y)}{f_ {X}(x)}=
\begin{dcases}
 \frac{1/2}{x/2}=\frac{1}{x}, &\text{if}~0\leq x\leq 1~\text{and}~0\leq y\leq x,
 \\
 \frac{3/2}{6-x/2}=\frac{1}{x}, &\text{if}~1<x\leq 2~\text{and}~0\leq y\leq 2-x.
\end{dcases}\]
\end{document}


text:
Q: Windows 7 "Not genuine" after imaging Z200 computers We created images from Windows 7, loaded on a HP Z200 workstation. We have added all our software we need on this image and then, sysprep'ed it. So now, when I push the image thru Zenworks on my 5 other Z200, I get the error message that my copy is not genuine... Normal since it has been imaged with the first PC's PID and Key.
But now I'm wondering how I can modify the information on the imaged computers. Here is what I've done so far.

*

*I can't change the information in the System Information page. It's Not available. -- The Software Protection Service is set as Startup (Delayed)

*I successfuly changed the CD Key from the command prompt (slmgr.vbs -ipk (CDKEY)) -- That was when I was not joined on my domain because I got the error message: Need elevated privileges even if I'm domain admin... ¿¿??¿¿

*I can't activate it using slmgr.vbs -ato.
So basicaly I'm trying to find a way to activate Windows 7 Pro on my 5 other Z200 with the CK Key that is attached with the OEM sticker on the computer. Is there any tools that can give me a hand? A registry key that I need to mod/del/add?
Thank you very much in advance!
David.

A: To install Windows this way you need a volume license not individual licences tied to each machine.
By doing it this way you are cloning a specific installation, which is against Microsoft's license terms. There is a utility you could get for XP which allowed you to enter a new Windows key.
The tool is called "KeyUpdateTool.exe" and can be downloaded directly from Microsoft using this download link. I have no idea whether it works for Windows 7.


text:
Q: How do you restore the special folder icons in Vista? Problem:
The desktop and documents folder appear with normal icons.
Attempted Solutions:

*

*Restoring desktop.ini

*Clearing the icon cache

*Rebooting

*Restoring the documents icon to default (via Control Panel)

A: Check this page out: "Shell folders are displayed with the standard folder icon in Windows Vista" - it sounds like what you're running into.
Blurb from page:

Symptom:
When you open Windows
Explorer, the shell folders such as
Documents and Pictures may be
displayed with a standard folder icon
rather than the special folder icons.
Resolution:
This behavior can occur
when the desktop.ini file in the shell
folder is missing or incorrect, or it
has no attributes set. The default
contents of the desktop.ini file for
various shell folders in Windows Vista
are given below. In each shell folder
that's missing the special icon,
create a file named desktop.ini and
paste the content corresponding to the
shell folder.

It then goes on to give you code for the Shell folders' specific desktop.ini settings.
Documents
[.ShellClassInfo]
LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21770
IconResource=%SystemRoot%\system32\imageres.dll,-112
IconFile=%SystemRoot%\system32\shell32.dll
IconIndex=-235

Desktop
[.ShellClassInfo]
LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21769
IconResource=%SystemRoot%\system32\imageres.dll,-183

A: The answer is to assign the read-only attribute to the folder.
eg.
attrib +r %userprofile%\Desktop

A: I wish I could mark one of the answers as "accepted" but reality proved to be even stranger.
Shortly after I asked this question, my laptop was stolen. Consequently, in the interest of increasing my acceptance rate, my 'official accepted answer' is:
Buy a new laptop.
:)

A: Here is another way to restore your shell folder default icon in Vista - you may want to backup your information first:

*

*Go to the folder you want to restore. For example, main music or picture folder.

*Hightlight the folder.

*Single right click

*Click properties.

*Click customize.

*Click choose file.

*Go to organize and click.

*Repeat steps 4 and 5.

*In folder icons click Change Icon.

*Click restore default and click OK if you have to, then close all open windows.

*Restart your computer. (I didn't restart, I just reopened my main user folder and refreshed the window about 3 times)


text:
Q: How can we connect AWS userpool with DynamoDb? I am currently using AWS cognito for user authentication. Now i want to store partial information of the users in the user pool to DynamoDb table. Is there a way to relate Userpool data with DynamoDb ?

A: You can federate user pool with Cognito identity and get the scoped temporary credentials, you can use these credentials to connect to DynamoDB. This part of developer guide talks about this integration. integrating user pools with identity pools


text:
Q: Getting JSON from Flask to Angular So i started to try out Angular 4 days ago.
Now im so far that I want to get some juicy JSON data from my Backend Flask Server to my Frontend Angular.
Problem is that

*

*The JSON data is not saved into my variable

*It cannot be iterated over

I don't know what im doing wrong and seek your help now.
The JSON File has this structure.
{"id":[1,2,3],"name":["Test 1","Test 2","Test 3"]}

In my browser it shows.
Error: "Error trying to diff 'Test 1,Test 2,Test 3'. Only arrays and iterables are allowed"

In the question I asked before the commentors pointed out that it is not an array that Im using so i can not iterate over tests.

          {{test.id}} {{test.name}}

But when this code is changed to

          {{test.id}}

An error shows up when trying to build. Saying error TS2339: Property 'id' does not exist on type 'Test[]'.
But the interface has defined these (id and name), so the only thing that I conclude from this is that tests must be empty.
My tests.service.ts should get an Observable array of Type Test
...
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class TestService {

private testUrl = 'http://my.server/tests';

constructor(
  private http: HttpClient
  ) { }

getTests(): Observable<Test[]> {
        return this.http.get<Test[]>(this.testUrl);
        }
...

And with this one it is planned to subscribe to the service in my tests.component.ts
...
@Component({
  selector: 'app-tests',
  templateUrl: './tests.component.html',
  styleUrls: ['./tests.component.css']
})
export class TestsComponent implements OnInit {
  tests: Test[];

  getTests(): void {
        this.testService.getTests()
                .subscribe(tests => this.tests = tests);

  }

  constructor(private testService: TestService) { }

  ngOnInit(): void {
  this.getTests();
  }

}

Test interface that gets used.
export interface Test {
   id: number;
   name: string;
}

Console.log(tests) returns empty.
Maybe someone of you can be so helpful and point out where this thing goes wrong.
Cheers!
Edit:
Added test interface.

A: If you have an array of test, the code has an error:

          {{test.id}}

Must be:

          {{test.id}}

Because each test has the property id. And if the file has this structure:
{"id":[1,2,3],"name":["Test 1","Test 2","Test 3"]} based of your code the response, must be:
[
   {'id': 1, name: 'Test 1'},
   ...
]

You need to transforme the file of process the return when service return the data.
You can process your response:
a.id.map( item => {return {"id": item, "name": a.name[item - 1]}} )
0: Object { id: 1, name: "Test 1" }
1: Object { id: 2, name: "Test 2" }
2: Object { id: 3, name: "Test 3" }


text:
Q: Read from configuration kafkalistener I have a spring boot application which has the listener as follows:
@KafkaListener(id = "demo", topics = "demo",
            containerFactory = "retryKafkaListenerContainerFactory")
    public void receive(ConsumerRecord<String, String> consumerRecord, Acknowledgment acknowledgment) throws Exception {

}

I have apache configuration object which I want to use to read topics from properties. I know that I can use property placeholders to do that. But the configuration I use has some logic inside so want to read only from that configuration object. It is as follows:
@Inject
private Configuration configuration

I can get topics as configuration.getString("kafka.consumer.topic"). I tried using like this: topics = "#{configuration.getString('kafka-generic.consumer.topics')}" in topics field of KafkaListener annotation but getting the following errors.
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'configuration' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:224)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:94)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:81)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:51)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:87)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:120)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:242)
    at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:161)
    ... 23 common frames omitted

Can someone tell me how to use configuration.getString("kafka.consumer.topic") in topics field of KafkaListener annotation?

A:
getting errors.

That is never enough for for a question like this; you have to show the actual error.
You can use SpEL topics = "#{@somebean.someProperty}" ortopics = "#{@somebean.getString('...')}".


text:
Q: How can I compare a decimal with a hardcoded value? Never needed to do this before till now.
trying to make sure the chargeAmount (which is type decimal) does not go below 1 cent:
 if (chargeAmount < 0.01)
                throw new ArgumentOutOfRangeException("chargeAmount");

I tried 0.01D but obviously I am not sure how you format this.

A: A decimal literal does not use D (that's for Double) - it uses M (for Money):
if (chargeAmount < 0.01M)
  throw new ArgumentOutOfRangeException("chargeAmount");

A: You mean you want it to be a decimal literal rather than double?
if (chargeAmount < 0.01m)