text:
Q: How to draw a triangle is insribed in a circle so that the vertices divide the circle into three arcs of lengths 3, 4 and 5? I want to draw a triangle circle is insribed in a circle so that the vertices divide the circle into three arcs of lengths 3, 4 and 5. I tried with Geogebra.
\documentclass[12pt]{standalone}
\usepackage{pgf,tikz}
\usepackage{mathrsfs}
\usetikzlibrary{arrows}
\pagestyle{empty}
\begin{document}
\begin{tikzpicture}[line cap=round,line join=round,>=triangle 45,x=1.0cm,y=1.0cm]
\clip(-0.5,-0.5) rectangle (4.5,4.298548095909735);
\draw(2.,2.) circle (2.cm);
\draw (0.64845913365678,3.4742242999639563)-- (0.5257757000360437,0.64845913365678);
\draw (0.5257757000360437,0.64845913365678)-- (3.907580874488035,1.3990547385264929);
\draw (3.907580874488035,1.3990547385264929)-- (0.64845913365678,3.4742242999639563);
\draw (-0.4,2.1844051666973288) node[anchor=north west] {3};
\draw (2.0939306358381504,0) node[anchor=north west] {4};
\draw (3,4.2) node[anchor=north west] {5};
\draw [fill=black] (2.,2.) circle (1.5pt);
\draw[color=black] (2,1.6) node {$I$};
\draw [fill=black] (0.64845913365678,3.4742242999639563) circle (1.5pt);
\draw[color=black] (0.6,3.8) node {$A$};
\draw [fill=black] (0.5257757000360437,0.64845913365678) circle (1.5pt);
\draw[color=black] (0.49,0.2) node {$B$};
\draw [fill=black] (3.907580874488035,1.3990547385264929) circle (1.5pt);
\draw[color=black] (4.15,1.377692733182069) node {$C$};
\end{tikzpicture}
\end{document}

How can I draw that picture by using tikz (or pstricks) with nice code?

A: You can decorate the circle with the markings that accept distances on the path. Then you can rotate or label so on as you wish.
\documentclass[tikz]{standalone}
\usetikzlibrary{decorations.markings}
\begin{document}
\begin{tikzpicture}
\pgfmathsetmacro\myradi{12/2/pi}
\draw[decoration={markings,
mark=at position 3cm with \coordinate (c3);,
mark=at position 7cm with \coordinate (c4);,
mark=at position 12cm with\coordinate(c5);% Redundant
}, postaction={decorate}]
circle [radius=\myradi cm];
\draw (c3) -- (c4) --(c5) --cycle;
\end{tikzpicture}
\end{document}

A: Define a circle with 3+4+5=12 degrees:
\documentclass[pstricks]{standalone}
\usepackage{pstricks}
\begin{document}
\begin{pspicture}(-3,-3)(3,3)
\degrees[12]
\pspolygon[showpoints](2;1)(2;4)(2;8)
\pscircle[showpoints](0,0){2}
\uput[1](2;1){A}\uput[4](2;4){B}\uput[8](2;8){C}
\rput(1.7;2.5){3}\rput(1.5;6){4}\rput(1.25;11){5}
\end{pspicture}
\end{document}

A: Here is another variant (via TikZ) with a random starting angle (each compilation gives a different result):

\documentclass[tikz,margin=2mm]{standalone}
\usetikzlibrary{calc,positioning}
\pgfmathsetseed{\pdfuniformdeviate 10000000}
\begin{document}
\begin{tikzpicture}
  % constants
  \pgfmathsetmacro\unit{360/(3+4+5)}
  \pgfmathsetmacro\radius{2cm}
  \pgfmathsetmacro\labeldist{3mm}
  % random starting angle
  \pgfmathsetmacro\angleinit{rnd*360}
  % center
  \fill circle(2pt) coordinate (I);
  \node at ($(I) + (\angleinit:3mm)$) {I};
  % circle
  \draw circle(\radius pt);
  % triangle
  \draw ({\unit*0+\angleinit}:\radius pt) coordinate (A)
     -- ({\unit*(3)+\angleinit}:\radius pt) coordinate (B)
     -- ({\unit*(3+4)+\angleinit}:\radius pt) coordinate (C)
     -- cycle;
  % The vertices and their names
  \foreach \point in {A,B,C}{
    \fill (\point) circle (2pt);
    \node at ($(I)!\radius pt+\labeldist pt!(\point)$) {\point};
  }
  % the relative angular distances
  \node at ($(I)!\radius pt+\labeldist pt!($(A)!.5!(B)$)$) {3};
  \node at ($(I)!\radius pt+\labeldist pt!($(B)!.5!(C)$)$) {4};
  \node at ($(I)!\radius pt+\labeldist pt!($(C)!.5!(A)$)$) {5};
\end{tikzpicture}
\end{document}

Edit:
New version with labels formated in italic and segments IA, IB and IC.

\documentclass[tikz,margin=2mm]{standalone}
\usetikzlibrary{calc,positioning}
\pgfmathsetseed{\pdfuniformdeviate 10000000}
\begin{document}
\begin{tikzpicture}
  % constants
  \pgfmathsetmacro\unit{360/(3+4+5)}
  \pgfmathsetmacro\radius{2cm}
  \pgfmathsetmacro\labeldist{3mm}
  % random starting angle
  \pgfmathsetmacro\angleinit{rnd*360}
  % center
  \fill circle(2pt) coordinate (I);
  \node at ($(I) + (\angleinit+50:3mm)$) {$I$};
  % circle
  \draw circle(\radius pt);
  % triangle
  \draw ({\unit*0+\angleinit}:\radius pt) coordinate (A)
     -- ({\unit*(3)+\angleinit}:\radius pt) coordinate (B)
     -- ({\unit*(3+4)+\angleinit}:\radius pt) coordinate (C)
     -- cycle;
  % vertices, labels and segments
  \foreach \point in {A,B,C}{
    \fill (\point) circle (2pt);
    \node at ($(I)!\radius pt+\labeldist pt!(\point)$) {$\point$};
    \draw (I) -- (\point);
  }
  % relative angular distances
  \node at ($(I)!\radius pt+\labeldist pt!($(A)!.5!(B)$)$) {3};
  \node at ($(I)!\radius pt+\labeldist pt!($(B)!.5!(C)$)$) {4};
  \node at ($(I)!\radius pt+\labeldist pt!($(C)!.5!(A)$)$) {5};
\end{tikzpicture}
\end{document}

Last edit:
Examples with different polygons:

\documentclass[tikz,margin=2mm]{standalone}
\usetikzlibrary{calc,positioning}
\pgfmathsetseed{\pdfuniformdeviate 10000000}
\begin{document}
\foreach \p in {{A/1,B/2,C/4,D/5},{A/2,B/3,C/4,D/6,E/9}}{
  \begin{tikzpicture}
    \pgfmathsetmacro\r{2cm} \pgfmathsetmacro\ld{3mm}
    \foreach \l/\v[evaluate=\v as \s using \s + \v,remember=\s as \s (initially 0),
    remember=\l as \ls,remember=\v as \lv] in \p{}
    \pgfmathsetmacro\unit{360/\s} \pgfmathsetmacro\ai{rnd*360}
    \fill circle(2pt) coordinate (I); \draw circle(\r pt);
    \draw (\ai:\r pt)
    \foreach \l/\v[evaluate=\v as \s using \psum + \v, remember=\s as \psum (initially 0)]
    in \p {-- ({\unit*\psum+\ai}:\r pt) coordinate (\l)} -- cycle;
    \foreach \l/\v in \p {
      \draw (I) -- (\l); \fill (\l) circle (2pt);
      \node at ($(I)!\r pt+\ld pt!(\l)$) {$\l$};
    }
    \node[circle,inner sep=1pt,fill=white] at ($(I) + (\ai:5mm)$) {$I$};
    \foreach \l/\v[remember=\l as \pl (initially \ls),remember=\v as \pv (initially \lv)]
    in \p {\node at ($(I)!\r pt+\ld pt!($(\pl)!.5!(\l)$)$) {\pv};}
  \end{tikzpicture}
}
\end{document}

A: As an alternative, here's some nice code for you in Metapost:
prologues := 3;
outputtemplate := "%j%c.eps";
beginfig(1);
for i=0 upto 11: z[i] = 60 right rotated 30i; endfor
draw for i=0 upto 11: z[i] .. endfor cycle withcolor .67 red;
draw z0--z3--z7--cycle;
label.rt (btex $A$ etex, z0);
label.top(btex $B$ etex, z3);
label.lft(btex $C$ etex, z7);
dotlabel.top(btex $I$ etex, origin);
for i=0 upto 11: draw z[i] withpen pencircle scaled 3; endfor
endfig;end.

A: And here's a solution in Asymptote.
unitsize(1cm);
real L1 = 3.0;
real L2 = 4.0;
real L3 = 5.0;
real diameter = (L1 + L2 + L3) / pi;
path circle = scale(diameter/2)*unitcircle;
pair A = arcpoint(circle,0.0);
pair B = arcpoint(circle,L1);
pair C = arcpoint(circle,L1 + L2);
draw(circle, blue);
draw(A--B--C--cycle, red);
dot(Label("$A$"), A, dir(A));
dot(Label("$B$"), B, dir(B));
dot(Label("$C$"), C, dir(C));
pair L1mid = arcpoint(circle,L1/2.0);
pair L2mid = arcpoint(circle,L1+L2/2.0);
pair L3mid = arcpoint(circle,L1+L2+L3/2.0);
label(string(L1), L1mid, dir(L1mid));
label(string(L2), L2mid, dir(L2mid));
label(string(L3), L3mid, dir(L3mid));

A: This time with the mfpic package. At the basis, the same idea as proposed by Herbert and Thruston. Not the same implementation of course.
\documentclass{scrartcl}
\usepackage[metapost, mplabels, truebbox]{mfpic}
\mfpverbtex{%&latex
  \documentclass{scrartcl}
  \begin{document}}
\setlength{\mfpicunit}{1cm}
\opengraphsfile{\jobname}
\begin{document}
  \begin{mfpic}{0}{1}{0}{1}
      \draw[red]\circle{origin, 3}
      \fdef{r}{t}{3dir(90-30t)}
      \mfpfor{t = 0 upto 11}\point[3bp]{r(t)}\endmfpfor
      \polygon{r(0), r(3), r(7)}
      \tlpointsep{3bp}
      \tlabels{[bc]{r(0)}{$A$} [cl]{r(3)}{$B$} [tr]{r(7)}{$C$}}
  \end{mfpic}
  \closegraphsfile
\end{document}

To be processed in three steps: LaTeX, MetaPost, and LaTeX again.


text:
Q: Complexity of inversion counting .
Let $X \in \mathbb{Z}^n$.  I need to find the number of pairs  $ (i, j)$ with $ 0 < i < j \le n$ such that $ X_i>X_j$ as well as the number of pairs $ (i, j),\ 0 < i < j \le n$, such that $ X_i=X_j$.
I know how to calculate in $O(n \log(n))$ time complexity.
How to prove that a comparison-based algorithm with better complexity does not exist (check "update" section on the bottom)?

An algorithm with  $O(n log(n))$ time complexity (one of the known methods):
We store:
1)  2 accumulators for the first and for the second value.  (both of them initially 0)
2) Balanced search tree (AVL, for example) with the size of subtree at each vertex (operation  "add element"  is $O(\log \text{size})$ cost).  Elements in this tree are 2-tuples $((-\infty\cup\mathbb{Z}\cup\infty), \mathbb{Z}   )$, comparison is done by first element, if first elements are equal - by the second element.  Initially this tree is empty.
Subprocedure - find the number of elements in the tree that lay in the interval $[X, Y]$ - with the time cost $O(\log n)$ (trivial)
Call this procedure as count$(X, Y)$
So, for $i$ from $1$ to $n$:

*

*add to first accumulator count( ($-\infty,1$),($X_i -1, i$))

*add to second accumulator count (($X_i -1, -1$), ($X_i -1, i-1$))

*add to balanced tree ($X_i, i$)

So, $n$ steps with $O (\log{n})$ cost
Update:
It cannot be calculated faster than $O(n)$ complexity:
The second count can be calculated with $O(n)$ time complexity (with the simple hash tables), so I need to prove the time complexity lower bound only for counting the pairs  $ (i, j),\ 0 < i < j \le n$ such that $X_i>X_j$

A: I found a proof
Get the subcase of this task - set what all $X_i$ are distinct.
Let exist an algorithm F with time complexity O(f(n)), $n \le f(n) \le nlog(n)$
Now we create a new array Y of pairs $(X_i, i)$ and cast with algo to Y.
At any comparizon in F  put into log pair (i, j), where $X_i<X_j$ and F was compare this values.
Where are O(f(n)) values in the log.
See it as a graph G with n vertices, where pairs are directed edges.  G contains no cycles
Lemma 1.
The time complexity of topological sorting of graph G with n vertices and m edges is no more $O(n+m)$
Lemma 2.
If graph G contains two different topological orders,then  G contains two different topological orders, difference between them is permutation of two adjanced elements.
Both lemmas are proved by the trivial algorithm.
http://codepad.org/fLDdQjpt  - where is a simple java implementation
So, fix orders $Y_1$ and $Y_2$
Create  by them two start arrays $X_1$ and $X_2$, difference beetween them is permutation of 2 elements => $X_1$ and $X_2$ have different inversions count, but F must works equally.
So, we can sort X with $O(n) + O(f(n)) + O(f(n) +n) = O(f(n))$  time complexity (third is a time complexity of the topological sorting of G)
So, $n*log(n) < f(n)$ asymptotically => $f(n)  = O(n*log(n))$

A: Inversion counting is a problem with a long history, and of great importance even today (particularly in e.g. streaming models).
It is natural to see its connection to sorting, since sorting effectively "erases" inversions; and in fact, it is straightforward to see how one can "piggyback" inversion counting on MergeSort without asymptotically increasing its complexity: what happens when I have already sorted two halves of an array, and I am merging them, and I pick an element of from the second half while $j$ elements from the first still remain unmerged?
In fact, if we restrict ourselves to comparison-based counting, i.e. the only way to access our array $x_1,...x_n$ is by asking for given any pair $(i,j)$ whether $x_i< x_j$, inversion counting requires at least as many comparisons as sorting, making its complexity $\Omega(n\lg(n))$. To see it, note that any set of comparisons defines implicitly a directed acyclic graph $G$ whose nodes correspond to $x_1,...,x_n$, and whose arcs correspond to comparisons made; and any in-order visit of $G$ (one that does not visit $x_i$ before $x_j$ if there is an arc from $x_j$ to $x_i$, i.e. if $x_j<x_i$) defines a total ordering of $x_1,...,x_n$ compatible with all the comparisons made. If $G$ is not a line, i.e. does not admit a unique total ordering, then there is at least a point in a visit when the next element of the visit can be either of two elements $x_i$ or $x_j$. But if I choose either one, I can choose the other as the following element, and then continue my visit of $G$ independently of my choice. This induces two total orderings that are both compatible with all comparisons made so far, and differ by exactly one inversion ($x_j$ with $x_j$), meaning that the parity of their inversion counts is different.
NOTE: I believe this is the same argument given above by kotomord, but I hope it's clearer written this way - because I for one was confused.
This connection with sorting is double-edged, however, in the sense that just like the complexity of sorting varies between $\Theta(n)$ and $\Theta(n \lg(n))$ depending on the machine model one is using, so does the complexity of inversion counting. For example, in the popular and reasonable Word RAM model (in which sorting can be done in time $O(n\lg\lg(n))$), inversion counting can be done in time $O(n\sqrt{\lg(n)})$ (check the tech report here, which also sports a fair bibliography on the topic).
Note that in the Word RAM model the bound for inversion counting is worse than that for sorting, showing that in general you can't reduce inversion counting to sorting. Nor is the converse true: note that the argument on inversion counting requiring at least as many comparisons as sorting, above, does not hold in general if one considers cases when both sorting and inversion counting have the same side-information - e.g. if one knows that the permutation holds exactly $1$ inversion! One can, however, always reduce inversion counting to (2D) dominance counting, and that's how many people approach it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Newton's second law - infinite velocity? Given the equation
$$F_{\text{net}} = ma$$
Does this not imply that if the net force on a certain object is positive, its acceleration will also be positive, and theoretically this object would accelerate forever to an infinite velocity?
i.e
envision a block on a surface. If a person were to apply a force (push) on this block that exceeds friction, ad continuously applies this force, this block should technically accelerate infinitely?

A: Yes. Your analysis is completely true on the basis of Newtonian Mechanics. But upon observation of the universe this turns out to be wrong, as once the objects in consideration approach the speed of light, we have to apply Relativistic Mechanics. So, as far as Newtonian Mechanics is concerned, objects can have infinite velocity and momentum. But they can't in the real world.

A: ...and infinite acceleration still applies, just not an infinite coefficient of velocity. As one approaches the speed of light a smaller and smaller speed gain is realized for the same input of force. So even though the force remains constant, the increase in speed decreases so that the object under acceleration approaches the speed of light asymptotically.


text:
Q: How to access instance in vue3 composition API lifecycle hooks I stumbled into a totally unexpected problem while refactoring my code to composition API: there doesn't seem to be any (documented) way of accessing current instance from the lifecycle hooks.
sample code:
import { defineComponent, onMounted } from 'vue';

export default defineComponent({
  setup() {
    onMounted(() => {
      console.log(this);  // <-- will be undefined
    });
  },
  mounted() {
    console.log(this);  // <-- will be the component
  },
}

I've spent hours trying to find a solution to this and ultimately just used the old options API to get what I want. None of examples, tutorials or documentation - that I read - use this in the hooks.
But I find it unbelievable that only undocumented getCurrentInstance would be the way to get the current instance from the hook.
So, which doc did I miss?

A: UPDATE
Here is the same example with a component

const { createApp, ref, onMounted } = Vue;

const MyComponent = {
  setup() {
    const id = ref(Math.round(Math.random() * 100000));
    const count = ref(0);
    const plus = () => { count.value++; }
    const minus = function() { count.value--; }

    onMounted(() => {
      count.value = Math.round(Math.random() * 10)
    });

    return {id, count, plus, minus }
  },
  template: `id: {{id}}   <button type="button" @click="minus()">-1</button>
     {{count}}
    <button type="button" @click="plus()">+1</button>
`
}

const App = {
  components: {
    MyComponent
  }
}

const app = createApp(App)
app.mount('#app')

   <my-component v-for="i in 5" />

What for do you need this in the component?
If you create your component with Composition API, then you can access all the properties directly, without using this.
Here is a very basic example:

const { createApp, ref, onMounted } = Vue;

const App = {
  setup() {

    const count = ref(0);
    const up = () => { count.value++; }
    const down = function() { count.value--; }

    onMounted(() => {
      count.value = 10
    });

    return {count, up, down }
  }
}

const app = createApp(App)
app.mount('#app')

    <button type="button" @click="down()">-1</button>
    {{count}}
    <button type="button" @click="up()">+1</button>


text:
Q: Prove that Tr$[x,y]^m=0$ for $m \ge 1$ $V$ is a complex vector space and $x,y \in gl(V)$ are linear maps such that $[x,y]$ commutes with both $x$ and $y$. Let $z=[x,y]$. Show that tr$z^m=0$ for all $m\ge 1$.
I have thought about this question for a long time, but I don't know how to use the condition that $z$ commutes with $x$, $y$. Can somebody give me some hints? Thank you.By the way, we haven't learnt Engel's Theorem or Lie's Thm at this point, so I cannot use that.

A: We have$\def\tr{\mathop{\rm tr}}$
\begin{align*}
  \tr([x,y]^{m}) &= \tr\bigl((xy-yx)[x,y]^{m-1}\bigr)\\
          &= \tr(xy[x,y]^{m-1}) - \tr(y[x,y]^{m-1}x) & \text{as $x[x,y]^{m-1}=[x,y]^{m-1} x$}\\
          &= \tr(xy[x,y]^{m-1}) - \tr(xy[x,y]^{m-1}) & \text{property of the trace}\\
          &= 0
\end{align*}


text:
Q: MonoTouch "unrecognized selector sent to instance" not working on iOS5 (but does on iOS6) I am getting the following error linking against the Aviary SDK using MonoTouch.

-[__NSArrayM objectAtIndexedSubscript:]: unrecognized selector sent to instance 0x9b0f1d0

The problem occurs when I try to push the linked controller.
PresentViewController(photoEditor, true, new NSAction(() => {}));

I have pushed/shared my project to https://github.com/theonlylawislove/MonoTouch.Aviary where you can reproduce the problem.
My Demo application works on iOS 6 simulator, but the mentioned error happens on iOS 5 simulator (and device).
I took all the content (.a/bundles) straight from the latest Aviary SDK 3.0. The demo application provided by them (with same .a lib) works on iOS 5 so the problem must be with MonoTouch and the linking.
Here is my linking flags.
[assembly: LinkWith ("libAviarySDK.a",
                     LinkTarget = LinkTarget.ArmV7 | LinkTarget.Simulator,
                     ForceLoad = true,
                     IsCxx = true,
                     Frameworks="Accelerate CoreData CoreText Foundation MessageUI OpenGLES QuartzCore StoreKit SystemConfiguration UIKit",
                     WeakFrameworks="AdSupport",
                     LinkerFlags="-ObjC -all_load -fobjc-arc -lz -lsqlite3.0")]

Any ideas? Thanks in advance! I am hoping to get the solution working to share it with the community since Aviary doesn't provide MonoTouch bindings.

A: Complementing @Poupou's answer, it's easy to make that selector available in iOS 5 all you need is to link against libarclite.a.
Here is a sample of a Xamarin.iOS binding using it also if you want you can grab libarclite.a from there.
Just add libarclite.a to your binding project and you should be good to go.
Hope this helps
Alex

A: Well the error is correct in the sense that the objectAtIndexedSubscript: selector is not available in iOS5. See: Is objectAtIndexedSubscript available in IOS5?

the demo application provided by them (with same .a lib) works on iOS 5

That does not mean your demo hits the same code path as the original demo. You're likely executing something that the original demo works around.
If this comes from the Aviary SDK (and not from your code) then you'll need:

*

*a fix from them; or

*some clue on how to avoid the code path that use this selector (there must be one if their demo works on iOS5 and does what you want); or

*an older version is still compatible with iOS5.


text:
Q: Origin of image in jquery animation (height and width) working on another site, and find a problem I cant figure out
I have a picture inside a div. on click I use animate(width, height).
Problem is that effect working from top left corner, but I need it to work from bottom middle.
Search the web, but without a luck.
It's must be a simple task, but I cannot figure it out.
jsfiddle
Thanks in advance
Alexei

<meta charset="UTF-8">
<title></title>

A: Try this Fiddle

If this solution does not suit your needs, i apologize for making you lose time.


text:
Q: how to extract a number from a line in a file where the number is connected to other charchter in python? i am new to python and trying to write a simple code that reads lines from a given file,
i am having a problem extracting a hexadecimal number from a line :
for example i have the following file lines:
# Program start at address 0, after reset.
I@0x00000000

D@0x000032A0

i want to extract the two hexadecimal numbers (they represent the start of instruction and data addresses)
i wrote the following code and the method "get_start" is supposed to extract the first integer which is zero but instead i get the following output:
  ['0', '00000000']
my code :
import sys
import re

class Memory:
    def __init__(self):
        self.progStart=0
        self.data_start=0

    def get_start(self, line):
        patterns = [r'\d+']
        for p in patterns:
            match = re.findall(p, line)
            print(match)
            return match

    def sim_mem_reset(self, memFileName):
        with open(memFileName, 'r+') as fileName:
            for line in fileName:
                if line[0] == '#' or len(line.strip()) == 0:
                    continue
                if line[0] == 'I' and line[1] == '@':
                    self.progStart = self.get_start(line)
                    print(self.progStart)
                if line[0] == 'D' and line[1] == '@':

# main
memory = Memory()
file_name = sys.argv[1]
print("Loading memory image file:", file_name)
memory.sim_mem_reset(file_name)

A: You don't need regexes. It's very simple to solve using str.strip and the int class:
def get_start(self, line):
    '''
    Assumes `line` looks like: I@0x01234567
    '''
    return int(line.strip()[2:], 16)

A: The number is hexadecimal, and you can extract it by using str.split():
s = 'I@0x00000000'
num = int(s.split('@')[1], 16)

This will extract the hexadecimal number after the '@' character.


text: Q: Why aren't semiconductor wafers diced into triangles? Semiconductor wafers are circular, and usually they are divided into squares or rectangles. However it's more efficient to pack triangles into circles than it is rectangles, so less wafer area would be wasted. Unlike hexagons, the lines in a triangular tiling extend to infinity, so the saw would be able to pass all the way through the die without stopping. Plus, some packages like SOT-23 are (if you squint) kinda triangular already. Is there any reason I haven't been able to find anything about triangular dicing of wafers?


text:
Q: functional equation uniqueness $f(x^{2})= f(x)^{2} $ in $\mathbb{C}$ and $f(x)+f''(x) = 0 $ in $\mathbb{C}$ This is an exercise from a book I tried:

One would like to find all holomorphic equations  that satisfy:$$i) \ f(z)+f''(z) = 0 \text{ in } \mathbb{C} $$$$ii)\ f(z^{2})=f(z)^{2} \text{ in } \mathbb{C}$$

I attempted this:
For i) one can use the Ansatz: $A\sin(bx)+C\cos(bx)$  and this also turns out to be the solution. How to show that these are all equations that satisfy the equation?
For ii) all terms of the form $x,x^2, x^3,\ldots, x^n$ satisfy the functional equation. I don't see  any other, so I assume that these are the only ones.
How to show that these are all possible equations that satisfy the functional equations?

A: To (potentially) cut down on the number of unanswered questions, I'll post GEdgar's answer from the comments as a Community Wiki answer.
Since we're assuming $f$ is holomorphic, then $$f(z)=\sum_{n=0}^\infty a_nz^n$$ holds for all $z\in\Bbb C$, where each $a_n\in\Bbb C$. Since differentiation of a power series is done termwise, then $$f''(z)=\sum_{n=0}^\infty\frac{d^2}{dz^2}[a_nz^n]=\sum_{n=2}n(n-1)a_nz^{n-2}=\sum_{n=0}^\infty(n+2)(n+1)a_{n+2}z^n,$$ so since $f+f''$ is identically zero on $\Bbb C$, then $a_n=-(n+2)(n+1)a_{n+2}$ for all $n\geq 0$.
Let's set $C=a_0$ and $A=a_1$. Since $a_n=-(n+2)(n+1)a_{n+2}$ for all $n\geq 0$, then quick inductive arguments show that for all $k\geq 0$ we have $$a_{2k}=\frac{(-1)^kC}{(2k)!}$$ and $$a_{2k+1}=\frac{(-1)^kA}{(2k+1)!}.$$ Consequently, we have
$\begin{eqnarray*}
f(x) & = & \sum_{n=0}^\infty a_nz^n\\
& = & \sum_{k=0}^\infty a_{2k+1}z^{2k+1}+\sum_{k=0}^\infty a_{2k}z^{2k}\\
& = & A\sum_{k=0}^\infty\frac{(-1)^k}{(2k+1)!}z^{2k+1}+C\sum_{k=0}^\infty\frac{(-1)^k}{(2k)!}z^{2k}\\
& = & A\sin z+C\cos z.
\end{eqnarray*}$

As an addendum, your ansatz $A\sin(bz)+C\cos(bz)$ is not a solution to the differential equation, in general. We may as well assume that $b$ isn't a negative number. Otherwise, we can use odd/even properties of sine and cosine to rewrite it as $A_0\sin(b_0z)+C_0\cos(b_0z)$, where $A_0=-A,C_0=C,b_0=-b$. Note that if $g(z)=A\sin(bz)+C\cos(bz)$ for some $A,C,b\in\Bbb C$, then $$g(z)+g''(z)=(1-b^2)g(z).$$ Consequently, if $g$ isn't identically zero (that is, if $A,C$ not both zero), then $g+g''=0$ if and only if $b=1$ (since $b=1$ is the only nonnegative solution to $1-b^2=0$).


text:
Q: Too many image requests on single page making other requests slow I am working on a page where customer order the products and on same page there are images needed to show of the product and all images are in binary and I am using a handler that process the request and write the image in context.request.
Issue is there are too many images that I needed to show about 25-30 products and request is asynchronous request means images are being load as browser get the data and it sends about 25-30 request and that make the other request too much slow.
while placing an order servers receives the request after too much time and sends the response after taking time too.
How, I can solve the problem. please tell the solution
Thanks in advance!

A: Try using
<%@ OutputCache duration="60" varybyparam="None" %>

on the page that process and serves the images.

A: There are several ways of resolving this image.

*

*Caching

*Using CSS Sprites.

You can use anyone or both of the above based on your preference.


text:
Q: WordPress Menus - Don't Show Sub-Pages I've created a custom side menu using the Wordpress > Appearance > Menu options.  Here is the structure:
About Us
Our Leadership Team
    Name #1
    Name #2
    Name #3
Our Staff and Advisory Board
    Name #1
    Name #2
    Name #3
    Name #4

The menu shows on the pages that I want it to -- but it is showing completely expanded.  The way I would like it to work :  If I'm on "About Us" -- then only the top level sub-options are shown.  (About Us, Our Leadership Team, Our Staff and Advisory Board)
If I click on "Our Leadership Team" then the three names under it are shown.  Hope this makes sense.
This is the code I am using to call this menu from multiple pages:
                            <?php if( is_page(array(11,354,304,302,297,232,319,317,311,309)) ) :?>
                                <? wp_nav_menu( array('menu' => 'main-about' )); ?>
                            <?php endif;?>

Any help would be appreciated.

A: I just finished a website where it was requred to have a main menu and a sub-menu in the sidebar
How I completed the task was to have the main menu where it was with a depth of 1 (only display the parent items). Note, change the 'menu' to your menu ID.
<?php wp_nav_menu( array( 'container_class' => 'menu', 'theme_location' => 'primary', 'depth' => '1', 'menu' => '3' ) ); ?>

Then all I had to do was post the child items. Instead of creating a menu, I had to dynamically generate the menu. So instead of having if or switch statements for each individual sub menus, this is the following piece of code I used. And it can be outside of the loop.
NOTE: This code was taken from the internet and modified, I don't know the original author.
<?PHP
// Get the parent's title (For display purpose)
$str_parenttitle = get_the_title($post->post_parent);

// This will display the child items of the parent
// And if it's a child item, display it's siblings
if($post->post_parent)
    $children = wp_list_pages("title_li=&sort_column=menu_order&child_of=".$post->post_parent."&echo=0&depth=1&exclude=73");
else
    $children = wp_list_pages("title_li=&sort_column=menu_order&child_of=".$post->ID."&echo=0&depth=1&exclude=73");
?>

Then display the menu
<?PHP if ($children && is_page()): ?>

        <li <?php if ( is_page() && $post->post_parent ) {} else { ?>class="current_page_item"<?php } // Shows the parent item on the sub menu ?>>
            <a href="<?php echo get_permalink($post->post_parent) ?>"><?php echo $str_parenttitle;?>

        <?php echo $children; ?>

<?PHP endif; ?>

I hope this at least helps.


text:
Q: make document.getElementById into a var Is there any way you can make "document.getElementById" into a variable?
I want to be able to write
myVariable("id").innerHTML = (blabla);
instead of
document.getElementById("id").innerHTML = (blabla);
Pardon me if this has been answered. I've sought and found nil! newbie

A: You can wrap the output into another function
var shortID = function(id) {
    return document.getElementById(id);
}
shortID('myID').innerHTML = "...";

A: To provide a simpler way to call common code, you can just define your own function like migvill suggests.
To answer the question directly though, you can point to the document.getElementById function (or any other function) using a variable. This is as obvious as you could imagine:
var myVariable = document.getElementById;

The problem with this is that the function itself (the object that myVariable now points to) is not intrinsically linked to the document object that it is designed to work with. When you write document.getElementById("id"), the document is automatically given to the function, but with myVariable you would need to specify it. This can be done using the call function:
myVariable.call(document, "id").innerHTML = "blabla";

And finally, the bind function can be used to create a new function that automatically links the given object (this has essentially the same effect as defining your own wrapper function):
var newFunc = myVariable.bind(document);

newFunc("id").innerHTML = "blabla";


text:
Q: A puzzle on data structure I faced this puzzle question[related to data structure] in a coding competition.
There is a planet of trees (real trees not tree data structure!!). It has billions or even trillions of trees. The king orders to find the median of ages (in years and integers) of all the trees using say carbon dating. (Method does not matter.)
Note: The Median is the "middle number" in a sorted list of numbers.
Constraints:
1. The oldest tree is known to be 2000 years old.
2. They have single machine which can store integers in range from -infinity to +infinity.
3. But the number of such integers that can be stored in memory at a time is 1 million.
so, once you store 1 million integers to store next one you must delete already stored one.
So somehow they have to keep track of median as they go on counting the ages of trees.
How can they do this?
My approach
Use a variant of external sort to sort the ages in chunks & write them in file.
Apply k-way merging[for the chunks].
The problem with above approach is that it needs two scan of the file.
I can think of another approach which uses the information The oldest tree is known to be 2000 years old.
Cannot we take a count array [as range of ages of tree is fixed]?
I want to know is there any better approach?
Does there exist any method where we do not need to store the data in the file?[where only main memory is sufficient?]

A: You can do this by storing just 2001 integers. Create an array of different possible ages
ages[2001] // [0..2000]

when you count a tree
ages[thisAge]++

Then computing the median is trivial.
You seem to have hit on this solution in the second approach you mention, but then you say
I want to know is there any better approach?

Does there exist any method where we do not need to store the data in
  the file?[where only main memory is sufficient?]

I don't undertstand why you ask if there exists any method where main memory is sufficient. Doesn't an array of 2001 integer fit in main memory?
Using the approach above, you can fill your array of counts, and then calculate the median by iterating through the counts, keeping a sum total as you go. When your sum reaches half the total number of trees, you have the median. This requires one pass through all the trees to count, plus a pass through part of the count array of some number <=2001. So this is O(n). You could, instead, keep track of the median with this array as you go, but it would not really improve on the solution.

A: The approach you recommended (an array of 2001 years) is O(n), with one fast operation per tree, so that is optimal.
Well, almost optimal.  At some point during the count the number of remaining trees will be insufficient to change the result.   For example, if I count half + 1 of the trees, and all are exactly 100 years old, then I have my answer: 100 years.
But if the trees are well-scattered in age, then the number of required trees will be close to the total number.


text:
Q: PowerBI- How to increment a column for an hourly basis? So, I have a table with many columns and what I am trying to do is increment the number of sales that have been in that hour and then reset it after after the next hour. I have tried to use summarize key word, but it doesn't seem to be letting me accumulate it. At the moment my data is in 15min bands so the data shows sales in that 15 minute time period. But I would like to accumulate it into next hour.
This is what I have now
15minperiod.    Sales
09:00:00.        10
09:15:00.        10
09:30:00.        10
09:45:00.        10
10:00:00.        10
10:15:00.        9
10:20:00.        13

This is what I would like to get:
15minperiod.       Sales          Sales in hour
    09:00:00.        10.              10
    09:15:00.        10               20
    09:30:00.        10               30
    09:45:00.        10               40
    10:00:00.        10               10
    10:15:00.        9                19
    10:20:00.        13               32

A: Yes, this can be done with a calculated column like this:
Sales in an hour =
var currentTime = [15minperiod]

return
CALCULATE(
    SUM('Data'[Sales]);
    FILTER(
        ALL('Data');
        'Data'[15minperiod] <= currentTime && HOUR('Data'[15minperiod]) = HOUR(currentTime)
    )
)


text:
Q: How to populate Nestjs mongoose schema records I want to get then enteries from paris air quality, but the thing is that the mongoose schema is nested and I tried to make multiple schemas separated but I don't know wheter it's correct or not.
This is the schema file schemas/air-quality.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type AirQualityDocument = AirQuality & Document;

@Schema()
export class Pollution {
  @Prop()
  ts: string;

  @Prop()
  aqius: number;

  @Prop()
  mainus: string;

  @Prop()
  aqicn: number;

  @Prop()
  maincn: string;
}

@Schema()
export class Result {
  @Prop({ type: Pollution })
  pollution: Pollution;
}

@Schema()
export class AirQuality {
  @Prop({ type: Result })
  result: Result;

  @Prop()
  datetime: string;
}

export const AirQualitySchema = SchemaFactory.createForClass(AirQuality);

And the result I am getting from mongo is this
PS: it contains multiple entries of the same schema
[
    {
        "_id": "62dd1b2e744e6bf8cdbcfabd",
        "result": {
            "_id": "62dd1b2e744e6bf8cdbcfabe"
        },
        "datetime": "24/07/2022, 11:13:02",
        "__v": 0
    },
    ...
]

I don't if the mistake is with the schema or I just need to use autopopulate or something


text:
Q: .NET 6.0 app on Azure App Service (Linux) can't find connection string Azure first-timer here trying to deploy a .NET 6.0 app to App Service (Linux OS).
In my app, I have a line as follows:
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");

This exception gets thrown on app startup, despite the fact that I'm setting the "DefaultConnection" connection string in the app config in Azure as follows:

What am I missing?

A: Looks like the problem was that I'm using Postres, and right now there is a bug/deficiency that prevents .NET from exposing Postgres connection strings to the app.
I didn't think it was even relevant that is a was a Posgres connection string, but here we are.
The fix ended up being to mark the connection string as a "Custom" type in Azure App Service configuration. See here: https://stackoverflow.com/a/62198728/363789
Here is a related Github issue: https://github.com/MicrosoftDocs/azure-docs/issues/95890


text:
Q: ValueError at /author/admin/ in Django I have the following blog project :
urls.py conf :
  url(r'^author/(?P<author>\w+)/$', views.getAllPosts, name='grabAuthorPosts')

posts/models:
class Post(models.Model):
    title = models.CharField(max_length=200)
    summary = models.CharField(max_length=500, default = True)
    body = models.TextField()
    pub_date = models.DateTimeField(default=timezone.now)
    category = models.ManyToManyField('Category')
    author = models.ForeignKey(User, default=True)
    slug = models.SlugField(max_length=100, unique=True, blank=True)

    def __str__(self):
        return self.title

    def slug(self):
        return slugify(self.title)

posts/views:
def getAllPosts(request, author=False):
    latest_posts = Post.objects.all().order_by('-pub_date')
    comments = Comment.objects.all().order_by('-pub_date')
    author_posts = User.objects.get(id=author)
    author_posts = author_posts.post_set.all()

    context = {
        'latest_posts':latest_posts,
        'comments':comments,
        'author_posts':author_posts
    }
    return render(request, 'posts/getAllPosts.html', context)

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)

templates/posts/getAllPosts:

{{post.author}}

I am trying to make it so that when the post.author link is clicked, the user will be taken to a page consisting of posts related to that particular author. The link formulation itself seems ok, as when clicked on a post created by admin, the url reads localhost/author/admin/
I believe my problem is in getting the context variable author_posts to work. I'm new to Django so any explanation greatly appreciated.
latest_posts, as well as author=False is used elsewhere in the template to get all posts regardless of author, which works fine.
The error is :
ValueError at /author/admin/
invalid literal for int() with base 10: 'admin'


text:
Q: How to calculate thermal noise contributed by an LNA? I've written a thermal noise simulation for a piece of equipment which produces the oscilloscope trace one would expect to see coming out of the instrument.
Now, I'd like to take into consideration contributions made by an Amplifier (LNA) which is part of the instrument.

A: You just need to determine the noise level at the input of the LNA.
The LNA has 60 dB Power gain so at the output the signal has a 60 dB higher power level.
If the LNA was noiseless, then the noise would also be amplified by 60 dB (same as the signal). However, the LNA isn't noiseless, it has a NF of 1.5 dB that means that it adds 1.5 dB to the noise level. So the noise level at the input of the LNA will be amplified by 60 dB + 1.5 dB = 61.5 dB.
Example:
At input of LNA:
Signal = -60 dBm, noise = -100 dBm
S/N ratio = 40 dB
At output of LNA:
Signal: Signal level + 60 dB = -60 dBm + 60 dB = 0 dBm
Noise: Noise level + 60 dB + 1.5 dB = -100 dBm + 61.5 dB = -38.5 dBm
S/N ratio = 38.5 dB (1.5 dB worse due to NF = 1.5 dB).


text:
Q: Convert list of strings into list of integers I need to convert a string of 2 items (separated by a comma) to integers.
from:
[['(0,3)', '(1,2)', '(2,2)'], ['(0,3)', '(1,2)', '(2,2)']]

to:
[[(0,3), (1,2), (2,2)], [(0,3), (1,2), (2,2)]]

A: You can use ast.literal_eval for the task:
from ast import literal_eval

lst = [["(0,3)", "(1,2)", "(2,2)"], ["(0,3)", "(1,2)", "(2,2)"]]

lst = [[literal_eval(v) for v in l] for l in lst]
print(lst)

Prints:
[[(0, 3), (1, 2), (2, 2)], [(0, 3), (1, 2), (2, 2)]]

EDIT: Another approach (thanks @S3DEV):
out = [list(map(literal_eval, sub_list)) for sub_list in lst]

Quick benchmark:
from timeit import timeit
from ast import literal_eval

lst = [["(0,3)", "(1,2)", "(2,2)"], ["(0,3)", "(1,2)", "(2,2)"]]

def fn1():
    return [[literal_eval(v) for v in l] for l in lst]

def fn2():
    return [list(map(literal_eval, sub_list)) for sub_list in lst]

assert fn1() == fn2()

t1 = timeit(lambda: fn1(), number=1_000)
t2 = timeit(lambda: fn2(), number=1_000)

print(t1)
print(t2)

Prints on my machine (AMD 3700X, Python 3.9.7):
0.040873110003303736
0.04002662200946361

A: If you input always in the pattern.
lst = [['(0,3)', '(1,2)', '(2,2)'], ['(0,3)', '(1,2)', '(2,2)']]

new_lst = list(map(lambda i:[eval(a,{}) for a in i],lst))
# OR

# new_lst = list(map(lambda i:list(map(lambda a:eval(a,{}),i)),lst))
print(new_lst)

OUTPUT
[[(0, 3), (1, 2), (2, 2)], [(0, 3), (1, 2), (2, 2)]]

lst = [['(0,3)', '(1,2)', '(2,2)'], ['(0,3)', '(1,2)', '(2,2)']]
new_lst = []
for a in lst:
    l = []
    for i in a:
        i = i[1:-1].split(',')
        t = []
        for num in i:
            t.append(int(num))
        l.append(tuple(t))

    new_lst.append(l)

print(new_lst)

output
[[(0, 3), (1, 2), (2, 2)], [(0, 3), (1, 2), (2, 2)]]

OR Using Map Function
lst = [['(0,3)', '(1,2)', '(2,2)'], ['(0,3)', '(1,2)', '(2,2)']]

new_lst = [list(map(lambda e:tuple(map(lambda a:int(a),e[1:-1].split(','))),i)) for i in lst]
print(new_lst)

[[(0, 3), (1, 2), (2, 2)], [(0, 3), (1, 2), (2, 2)]]


text:
Q: 'TextCtrl' object has no attribute 'Value' I am learning to pogram with python and
I am interested in creating a GUI by using the wxGlade.
I've created a simple application which add 2 values entered by the user.
user will enter the first value into a text box called text_ctrl_1 and the second value into the second text box called text_ctrl_2
by clicking the add button, the application will add the values and show it on another button.
below is the code defining the function of the add button
def sum(self, event):  # wxGlade: MyFrame.<event_handler>
    c = self.text_ctrl_1.Value + self.text_ctrl_2.Value
    self.button_2.SetLabel(c)
    event.Skip()

my problem is that after entering value to both of the text box, when i click on the add button,
python told me that there is an attribute error : 'TextCtrl' object has no attribute 'Value'
still a newbies in programming
thanks alot for the help

A: You want to use the GetValue method on the TextCtrl class, like so:
def sum(self, event):  # wxGlade: MyFrame.<event_handler>
    c = self.text_ctrl_1.GetValue() + self.text_ctrl_2.GetValue()
    self.button_2.SetLabel(c)
    event.Skip()


text:
Q: colorbox option to display instance variable I was implementing the colorbox modal for my web application. I am stuck in displaying an instance variable in my colorbox.
I could not find an option in the colorbox website to do such a thing.
This is my code.
$.ajax({
type: 'GET',
url:'/leave',
async: false,
data:{ foo1:currentCellText
},
success:function(data){
$.colorbox({html: "<%= @cook%>",  width:"25%",height:"200px"});
},
error:function(data){
alert("Failure");
}
});

My instance variable @cook has an array. How can I display the array contents in colorbox?
Hope someone can help me out.
Regards,
Nikhil

A: Your question is a little vague....
If you want to display the complete array in one instance of the plugin, consider using ColorBox to open its content in an iFrame. That way, inside the frame you'll have a complete DOM environment (as a child to the calling window) in which to do anything you need to.
In side of that environment you'll need to work out how to extract the individual array elements and display them.
If you want to display each array element in its own ColorBox, that's a different story. For that you'll need to work out how to apply the plugin to each array element and a method by which the lightbox is triggered.


text:
Q: spring mvc project with maven using STS I am creating Spring MVC project with maven using STS. But in my pom.xml I have following error:

Failure to transfer org.codehaus.plexus:plexus-interpolation:pom:1.6 from http://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.codehaus.plexus:plexus-interpolation:pom:1.6 from/to central (http://  repo.maven.apache.org/maven2): null to http://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-interpolation/1.6/plexus-interpolation-1.6.pom


text:
Q: Linking libz.dylib and libsqlite3.dylib in Xamarin iOS Project I created a Xamarin iOS binding project that requires the following frameworks:
SystemConfiguration.framework
CoreTelephony.framework
libz.dylib
libsqlite3.dylib

I added the following line in my iOS binding project to the linkwith.cs file:
Frameworks = "SystemConfiguration CoreTelephony"

This seems to work correctly and tells that project to include these frameworks when binding. From what I have read, it sounds like the remaining 2 libraries need to be added as linker flags in the project referring to the DLL generated from my iOS binding project. So I created a test app, imported the DLL, and now need to add the linker flags but my project cannot find the right libraries.
My linker flags in Xamarin Studio are as follows:
-gcc_flags "-lz -lsqlite3.0"

When I build my Xamarin test app I get a few errors regarding the frameworks that cannot be found. Are there additional flags that need to be linked or do I need to do some additional configuration in my iOS binding project?

A: I found a great resource: http://ipixels.net/blog/specify-extra-gcc-flags-for-native-library-binding-in-xamarin-ios/
I needed to add LinkerFlags = "-lz -lsqlite3.0" to my .linkwith.cs file. I then rebuilt the library to generate a new DLL and added this to my test app. The test app builds correctly then.

A: If you are creating your bindings for a cocoapod using sharpie:
sharpie pod init ios nameOfCocoaPod
sharpie pod bind

you get a nameOfCocoaPod.framework file and .cs-binding files.
The nameOfCocoaPod.framework file should be added to your binding project under Native References. To change e.g. Frameworks or LinkerFlags, right-click and open properties.


text:
Q: Validations not working in YII This is my code:
public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(

            array('ScriptName,TestSystem_id', 'required'),

            array('TestSystem_id, TmatsUser_id, Active', 'numerical', 'integerOnly'=>true),
            array('ScriptName, TestObjective,  ScriptFormat, ComponentImpact', 'length', 'max'=>120),
            array('Description, ScriptCode, ProvisionReq', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, TestSystem_id, TmatsUser_id, ScriptCode, ProvisionReq, ScriptName, Description, ScriptFormat, Active', 'safe', 'on'=>'search'),
        );
    }

But the validations doesnt work. It gives the following error
CDbException
CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'TestSystem_id' cannot be null

it doesnt validate the ScriptName at all.
In database both are given as NOT NULL.
The validations in other forms works fine.
Any help is appreciated.

A: That error means that you have some table in database which stores primary keys of foreign keys you are storing in the table...And you are trying to store some value in the column of foreign key which is not present in the column of primary key in the another table..Hence the database Integrity constraint violation happened...
Either remove database constrains from database because we have them with models so they are not required...
And make sure you are storing data which is present in parent table primary key column..


text:
Q: Skewed distribution based on a Normal distribution Let us assume the intelligence quotient of a human being is modelled by ~N(100,15^2). We have country X with average of 103 (this is the only information we have). How can we then estimate the IQ of a random person in the top 1% of people in country X?

A: You have no basis for estimating the standard deviation of IQs in Country X. So maybe you just want to assume that in Country X IQ scores have the 'customary' standard deviation $\sigma = 15.$  Then maybe you'd want the 99th percentile of $\mathsf{Norm}(\mu = 103, \sigma = 15),$ which is just below IQ $138,$ according
to R.
qnorm(.99, 103, 15)
[1] 137.8952

With so little information provided, there must be a dozen or so answers that are
equally good---perhaps except for simplicity.


text:
Q: how to efficiently convert a nested SQL in Query builder I've a nested sql query
SELECT
   city_id,
   town_id,
   SUM(IF(total_visit >= 2, 1, 0)) visited_twice,
   SUM(IF(total_visit >= 3, 1, 0)) visited_thrice
FROM
   (
      SELECT
         c.city_id,
         c.town_id,
         c.id,
         COUNT(v.id) AS total_visit
      FROM
         VISITS v
         LEFT JOIN
            CUSTOMERS c
            ON v.customer_id = c.id
      WHERE
         c.customer_type = 1
         AND MONTH(v.visit_date) = 6
         AND YEAR(v.visit_date) = 2021
      GROUP BY
         c.town_id,
         c.id,
         MONTH(v.visit_date),
         YEAR(v.visit_date)
      HAVING
         total_visit > 1
   )
GROUP BY
   town_id

How can I convert into Query builder pattern to make the code bit readable?
I've tried converting to query builder for normal queries, but looking for advices for a nested query.
EDIT
$visitTable = Visit::$TABLE_NAME;
$customerTable = Customer::$TABLE_NAME;

$sub = Visit::with($with)
    ->selectRaw("$customerTable.city_id, $customerTable.town_id,
                     $customerTable.id, COUNT($visitTable.id) total_visit")
    ->leftJoin("$customerTable", "$customerTable.id", '=', "$visitTable.customer_id")
    ->where("$customerTable.customer_type_id", 1)
    ->whereMonth("$visitTable.visit_date", $month)
    ->whereYear("$visitTable.visit_date", $year)
    ->groupBy("$customerTable.town_id, MONTH($visitTable.visit_date), YEAR($visitTable.visit_date)")
    ->havingRaw('total_visit > 1');

$query = DB::table( DB::raw("({$sub->toSql()}) as sub") )
    ->selectRaw("city_id, town_id,
                SUM(IF(total_visit >= 2, 1, 0)) visited_twice, SUM(IF(total_visit >= 3, 1, 0)) visited_thrice ")
    ->mergeBindings($sub->getQuery())
    ->groupBy("town_id");

But ending up with this
"connection": {},
    "grammar": {},
    "processor": {},
    "bindings": {
        "select": [],
        "join": [],
        "where": [
            1,
            "6",
            "2021"
        ],
        "having": [],
        "order": [],
        "union": []
    },
    "aggregate": null,
    "columns": [
        {}
    ],

A: You can easily query from subquery tables by using any of the following syntax options

*

*DB::table(Closure, alias)

*DB::table(Builder, alias)

*DB::query()->from(Closure, alias)

*DB::query()->from(Builder, alias)
Here, I'm using the second option.
// Build the subquery first (without getting the results)
$visits_sub = DB::table('VISITS', 'v')
    ->select('c.city_id', 'c.town_id', 'c.id')
    ->selectRaw('count(v.id) as total_visit')
    ->leftJoin('CUSTOMERS as c', 'v.customer_id', 'c.id')
    ->where('c.customer_type', 1)
    ->whereMonth('v.visit_date', 6)
    ->whereYear('v.visit_date', 2021)
    ->groupByRaw('c.town_id, c.id, month(v.visit_date), year(v.visit_date)')
    ->having('total_visit', '>', 1);

// Use the built subquery as the table
$query = DB::table($visits_sub, 'visits')
    ->select('city_id', 'town_id')
    ->selectRaw('sum(if(total_visits >= 2, 1, 0) as visited_twice')
    ->selectRaw('sum(if(total_visits >= 3, 1, 0) as visited_thrice')
    ->groupBy('town_id');

// you can verify the sql by dumping the query
$query->dump();

$results = $query->get();

If you want to force the results to be Visit models, you need to go with the ->query()->from(...) syntax.
$query = Visit::query()
    ->from($visits_sub, 'visits')
    // rest should be the same.


text:
Q: Is it possible to round the edges of a row in jetpack? This is what I'm trying to achieve:

So I have created 2 rounded buttons in a row and gave different background colors depending whether they're selected or not. The goal is to create a kind of an illusion of a tab/toggle.
The unselected button will have the same color as the row's background color. Unfortunately, since a row is a rectangle shape there comes a residue space at the corners that still shows the background color .

This is my code for the buttons
val cornerRadius = 20.dp

var selectedIndex by remember { mutableStateOf(0)}

val configuration = LocalConfiguration.current
val screenWidth = configuration.screenWidthDp.dp

val items = listOf(

    OutlinedButton(onClick = { /*TODO*/ }) {

    },

    OutlinedButton(onClick = { /*TODO*/ }) {

})

Row(
    modifier = Modifier

        .padding(top = 8.dp)
        .wrapContentHeight()

        .width(screenWidth).background(color = Color.Gray).clip(shape = RoundedCornerShape(20.dp))
) {
  //  Spacer(modifier = Modifier.weight(1f))

        items.forEachIndexed { index, item ->

            OutlinedButton(modifier = Modifier
                .wrapContentHeight()
                .width(screenWidth/2),

                shape = when (index) {
                    // left outer button
                    0 -> (if (selectedIndex == index) {
                        RoundedCornerShape(
                            topStart = cornerRadius,
                            topEnd = cornerRadius,
                            bottomStart = cornerRadius,
                            bottomEnd = cornerRadius
                        )
                    } else {
                        RoundedCornerShape(
                            topStart = cornerRadius,
                            topEnd = cornerRadius,
                            bottomStart = cornerRadius,
                            bottomEnd = cornerRadius
                        )
                    })

                    //rightouterbutton

                    else -> (if (selectedIndex == index) {
                        RoundedCornerShape(
                            topStart = cornerRadius,
                            topEnd = cornerRadius,
                            bottomStart = cornerRadius,
                            bottomEnd = cornerRadius
                        )
                    }
                            else{RoundedCornerShape(
                        topStart = 0.dp,
                        topEnd = cornerRadius,
                        bottomStart = 0.dp,
                        bottomEnd = cornerRadius
                    )})
                },
                border = BorderStroke(
                    1.dp, if (selectedIndex == index) {
                      Color.Transparent
                    } else {
                        Color.Transparent
                    }
                ),
                colors = if (selectedIndex == index) {
                    // colors when selected
                    ButtonDefaults.outlinedButtonColors(
                        backgroundColor = Color.Yellow,
                        contentColor = Color.Black
                    )
                } else {
                    // colors when not selected
                    ButtonDefaults.outlinedButtonColors(
                        backgroundColor = Color.Gray,
                        contentColor = Color.Black
                    )
                },

                onClick = { selectedIndex = index },

                ) {
                if (index == 0) {

                    Text(
                        text = "In progress",
                        color = if (selectedIndex == index) {
                            Color.Black
                        } else {
                            Color.DarkGray.copy(alpha = 0.9f)
                        },
                        modifier = Modifier.padding(horizontal = 8.dp)
                    )
                } else {

                    Text(
                        text = "Completed",
                        color = if (selectedIndex == index) {
                            MaterialTheme.colors.primary
                        } else {
                            Color.DarkGray.copy(alpha = 0.9f)
                        },
                        modifier = Modifier.padding(horizontal = 8.dp)
                    )
                }
            }
        }
    }

A: Modifier.clip applied after the Modifier.background has no effect in your case, you need to reverse the order. Read more about why the order of modifiers matters in this answer
.clip(shape = RoundedCornerShape(20.dp))
.background(color = Color.Gray)

Another option in the case of Modifier.background is that you can apply the shape specifically to the background color. Note that this solution will not clip other view content to the shape as Modifier.clip does, but in your case it fits.
.background(color = Color.Gray, shape = RoundedCornerShape(20.dp))


text:
Q: How to let std::thread delete the object automatically after excuting its member function I want want to implement a cmmand class which does some work in an another thread, and I don't want to let users to delete that object manually.My command class like this:
class Cmd {
 public:
  void excute() {
    std::cout << "thread begins" << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(2));  // do some work
    std::cout << "thread ends" << std::endl;
  }

  void run() {
    // I want std::unique_ptr to delete 'this' after work is done,but does't work
    std::thread td(&Cmd::excute, std::unique_ptr<Cmd>(this));
    td.detach();
  }

  // test if this object is still alive
  void ok() { std::cout << "OK" << std::endl; }
};

I use it like this:
int main() {
  Cmd *p = new Cmd();
  p->run();

  // waiting for cmd thread ends
  std::this_thread::sleep_for(std::chrono::seconds(3));

  p->ok();  // I thought p was deleted but not

  return 0;
}

As in the comments, the object is still alive after cmd thread finishes, I want to know how to implement such funtionality.
EDIT
users of cmd does't know when cmd will finish, so the flowing use case will leads to UB.
std::unique_ptr<Cmd> up(new Cmd);  // or just Cmd c;
up->run();
// cmd will be deleted after out of scope but cmd::excute may still need it

CLOSED
I made a mistake about test, in fact the object is deleted after the thread ends.It is more clear with following test with a additional member variable int i.
#include <functional>
#include <iostream>
#include <stack>
#include <thread>

using namespace std;

class Cmd {
 public:
  ~Cmd() { std::cout << "destructor" << std::endl; }

  void excute() {
    std::cout << i << " thread begins" << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(2));  // do some work
    std::cout << i << " thread ends" << std::endl;
  }

  void run() {
    // I want std::unique_ptr to delete 'this' after work is done,but it seems
    // not working
    std::thread td(&Cmd::excute, std::unique_ptr<Cmd>(this));
    td.detach();
  }

  // test if this object is still alive
  void ok() { std::cout << i << " OK" << std::endl; }

  int i;
};

int main() {
  Cmd *p = new Cmd();
  p->i = 10;
  p->run();

  // waiting for cmd thread ends
  std::this_thread::sleep_for(std::chrono::seconds(3));

  p->ok();  // I thought p was deleted but not

  return 0;
}

The flowwing outputs proved the object is deleted.
10 thread begins
10 thread ends
destructor
-572662307 OK

But just as some kind guys suggests, this is not a good design, avoid it as you can.

A: Instead of thread, you can use std::future to signal the state. You can then either wait for the task to finish, or ignore the future completely.
#include <future>
#include <chrono>
#include <mutex>
#include <iostream>

class Cmd {
public:
    std::future<void> run() {
        std::lock_guard<std::mutex> lock(startMutex);
        if (started) {
            throw std::logic_error("already started");
        }
        started = true;

        // Take copies here, so that it doesn't matter if Cmd is destroyed
        int i_ = i;
        return std::async(std::launch::async, [i_]() {
            std::this_thread::sleep_for(std::chrono::seconds(2));
            std::cout << i_ << std::endl;
        });
    }

    int i = 0;

private:
    std::mutex startMutex;
    bool started = false;
};

int main() {
    auto p = std::make_unique<Cmd>();
    p->i = 10;
    auto f = p->run();
    p.reset();

    // Do some other work

    // Wait for the task to finish (or use f.get() if there is no need to
    // do some other work while waiting)
    if (f.valid()) {
        std::future_status operation;
        do {
            // Do some other work

            operation = f.wait_for(std::chrono::milliseconds(1));
        } while (operation != std::future_status::ready);
    }
}

A: There are two ways to automatically delete the memory created dynamically.

*

*In client code(main function), you should use some smart pointer like unique_pointer, so that once the object goes out of the scope, automatically it will be freed in unique_poiter destructor

*You can create your own smart pointer, it will be kind of wrapper around Cmd class. And has to overload a few operators. This smart pointer will also be taking care of dynamically allocated memory in the destructor. Client code should use this smart pointer while creating Cmd object dynamically.


text:
Q: I have two tables in MySQL that have identical columns. Is there a way to detect changes between them? I have the following tables:
movie

*

*title - VARCHAR (255)

*year - VARCHAR (4)

*format - VARCHAR (255)

movie_custom

*

*title - VARCHAR (255)

*year - VARCHAR (4)

*format - VARCHAR (255)

*username_id - INT (11)

Each table has different data, but I want to ensure that there are no changes to some of the column names. For example, if I changed format  - VARCHAR (255) to distribution_type - VARCHAR (30) on movie, I'd also want to make sure the same change gets made on movie_custom.
Is there any way to ensure this in MySQL? Somehow couple two columns together in some way?

A: This is too long for a comment.
It sounds like you have a lousy data model.  If you fix the data model, you'll fix your problem.
You should have a movie database with a primary key:
create table movies (
    movieId int primary key auto_increment,
    . . .
);

Then, the second table should have three columns:
create table moviesCustom (
    movieCustomId int primary key auto_increment,
    movieId int not null,
    username_id int,
    constraint foreign key (movieId) references movies(movieId)
);

Then, when you want information in both tables, use a join.

A: Plan A
For title create a normalization table.  Then, instead of VARCHAR(...), have MEDIUMINT UNSIGNED to link to that table.
Then when adding any title from anywhere (base or custom), look up the name in that table to get the id (or create a new id).
This is probably the only way to keep the datatype if title in a single location (and appease Gordon).
However, excessive use of this (ie, multiple columns done this way) will cost something in performance.
Suggestion:  Change year VARCHAR(4) to year YEAR, since there is such a datatype.
Plan B
Combine the two tables; use a special username (perhaps NULL) as the 'base' entry.


text:
Q: "Complicated" or "complicating" Can anyone tell me why sentence (A) is wrong, and (B) is correct?

(A) "The topic of landmines is very heavy and complicating."
(B) "The topic of landmines is very heavy and complicated."

To me, both seem to make sense.  In my understanding, 'complicating' in sentence (A) is equivalent to 'confusing,' while 'complicated' in sentence (B) is synonymous with 'complex.'
I did some research and there is no such word as "complicating" in my dictionary; there are only "complicate" and "complicated."  I am assuming it is because "complicating" cannot be used as an adjective - it can only be used as the present progressive form of the verb "complicate."  And if this is the case, can sentence (C) below be grammatically and idiomatically correct?

(C) "The topic of landmines is very heavy and complicating the
  peace talks."

Thanks for your help!

A:
I am assuming it is because "complicating" cannot be used as an
  adjective - it can only be used as the present progressive form of the
  verb "complicate."

Exactly right. The word "confusing" has the form of the present-progressive, but it can also be used as an adjective (Source: Oxford Learner's Dictionaries). This is just a fact about the specific word, so looking up in the dictionary like you did is the correct course of action here.
Because "heavy" is an adjective and "complicating" is a present participle, your sentence C) seems a bit odd to me. There's a kind of "zeugma" where you're making "is" serve two roles: as a copular verb and as an auxiliary verb. (These grammatical roles are usually differentiated; see "Is "am" in "I am right" an auxiliary verb?". But, keep in mind that some people refer to "be" as an "auxiliary verb" in all of its uses, whether or not it is "helping" a lexical verb.)
To avoid this, I would add a few more words to change the structure:

(C2) "The topic of landmines is very heavy, and it is complicating the
  peace talks."

A: While there are exceptions, normally when you want to turn a verb into an adjective, you use the past tense. complicated is the past tense of complicate, and can be used to describe something. complicating is the present tense, so is not generally used as an adjective.
In (C), you're not using complicating as an adjective, it's being used as a verb, to refer to what the topic of landmines is doing (it's causing the peace talks to become more complex).

A:
(A) "The topic of landmines is very heavy and complicating."

To me, 'complicating' means something that complicates a situation, so you could say 'adding that divide to that already complex maths equation is complicating it further'.
'Confusing' is not synonymous with 'complicating' because 'confusing' means something that confuses somebody. You can't 'complicate' somebody, though.

(B) "The topic of landmines is very heavy and complicated."

To me, 'complicated' is the past tense of 'complicate', so this makes sense because 'The topic of landmines' has been through a process of complication, thus is now complicated. It is not however currently in a process of 'complicating' other things, which is why the first quote does not make sense.


text:
Q: Tick checkbox if page is visited via button Looking for some help figuring out how I could add the following functionality:
I've got a contact page on my WP website which has a contact 7 form and a checkbox to Sign Up for the newsletter.
The contact page is accessible in 2 ways - obviously via the menu, but there is also a "Sign Me Up for the newsletter" button on homepage which when clicked currently takes the user to the contact page too. I would like to make it so that when user clicks the button on the homepage, it not only takes him/her to the contact page but also automatically ticks the checkbox that's on there. I do not want the checkbox to be ticked automatically if the user visits the contact page via the menu or any other means.
I guess I'm looking for some php logic, but any thoughts are appreciated.

A: Add PHP GET string to button link then read that on other side and make logic like:
if page is contact-page.php, then on button add link contact-page.php?button=true
on contact-page.php read that ?button=true with PHP:
if (isset($_GET["button"])) {
   //echo that checkbox checked
}else{
   //echo that checkbox not checked
}

or in JS:
if (window.location.href.indexOf("button") > -1) {
      //check checkbox with JS
  }

Other option is that you use JS localStorage , when you click a button set localStorage button: true, then read that on contact-page.php and if its true check checkbox with JS


text:
Q: Can I print to USB printer from Java on a Raspberry PI? I am looking at creating a simple time clock. It will read barcoded id badges from an HID USB scanner. Most of it is simple to implement. Where I am stuck is when I consider writing the application in C# .net and using an old PC, or writing it for the Raspberry PI in Java. (I do not have any Java experience, but I am taking a semester class next month.)
I would prefer the Raspberry PI as the host for a number of reasons. The sticking point is, where on a Windows PC using .net there are printing facilities, I have had very little luck searching out the method where I could print the time sheets to a USB printer from the Raspberry PI using Java. (CUPS would be installed on a Raspbien OS.)
Now my question to the learned masses ...
Have you successful printed from a Java application to a USB printer connected to a Raspberry PI?  Do I study and use the same code on the Raspberry PI as I would use to print from Java on my Windows desktop, or does it need some other magic?

A: I have found through other sources that with CUPS properly installed, printing from Java is fully functional using the same methods as on a Windows platform;  java.awt.print and javax.print.
That means I can use the Raspberry Pi for my barcode time clock project as soon as I learn enough Java.
KK

A: Sometimes, the JRE won't find the printer on a raspberry pi. Go to terminal on your raspberry pi with the printer connected and type lpstat -a and copy the printer's name that you are looking for. Then use this in your program:
String destination = "Your printer's name";
String path = "Your path to pdf";
String[] command = { "lp", "-d", destination, path};
Process proc = new ProcessBuilder(command).start();

The path to the pdf is relative to your current directory.
This program executes a command on your linux system to print your desired pdf through ProcessBuilder. It will only run on a linux system (raspberry pi).


text:
Q: Argument #1 ($connection) must be of type Doctrine\MongoDb\Connection, Doctrine\ODM\MongoDB\Configuration given In doctrine/mongodb-odm 1.x i can get a Connection object like thus:-
$db = Zend_Registry::get('DocumentManager')->getConnection();

object(Doctrine\MongoDB\Connection)#38 (6) {
  ["mongoClient":protected]=>
  NULL
  ["server":protected]=>
  string(9) "localhost"
  ["options":protected]=>
  array(1) {
    ["ssl"]=>
    bool(false)
  }
  ...

In doctrine/mongodb-odm 2.x this has been removed. How can I get the equivalent in 2.x ?
I'm trying:-
$db = Zend_Registry::get('DocumentManager')->getConfiguration();
$db = Zend_Registry::get('DocumentManager')->getClient();
$db = Zend_Registry::get('DocumentManager')->getDocumentDatabase('Model\User');

but none of these are the correct objects and I don't see anything similar to Doctrine\MongoDB\Connection in the mongodb-odm packages dir for 2.x.


text:
Q: TRIGGER MYSQL NOT EXIST I created this trigger:
    CREATE TABLE `Invitations`
( `userId` varchar(255) NOT NULL, `name` varchar(255) DEFAULT NULL,
    `status` varchar(1) DEFAULT NULL, `userId_inv` varchar(255) NOT NULL,
    PRIMARY KEY (`userId`,`userId_inv`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1

CREATE TRIGGER `Invitation_001_after_trig` AFTER INSERT ON `invitation_001`
FOR EACH ROW
BEGIN
    IF ((new.userId,'001') NOT EXISTS (SELECT `userId`,`userId_inv` FROM `Invitations`
    WHERE `userId`= new.userId AND `userId_inv` = '001' LIMIT 1))
    THEN
    INSERT INTO `Invitations`(`userId`, `name`,`status`,`userId_inv`)
    values (new.userId, new.name,new.status,'001');
    DELETE FROM `invitation_001` WHERE `status` = 'a';
    END IF;
END;

It did not work. I had this error:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'EXISTS (SELECT userId,userId_inv FROM Invitations WHERE
  userId= new.user' at line 1

So could you help me.
I resolved the problem with this trigger:
CREATE TRIGGER `Invitation_001_after_trig` AFTER INSERT ON `invitation_001`
FOR EACH ROW
BEGIN
INSERT INTO `Invitations` (`userId`, `name` ,`status` ,`userId_inv`) SELECT * FROM
invitation_001 iv WHERE
NOT EXISTS (SELECT 1 FROM `Invitations` ivs WHERE ivs.`userId` = iv.`userId` AND
ivs.`userId_inv` = iv.`userId_inv`) AND iv.`userId_inv`='001';END;

Now I've an other issue. I would like to execute a query from a Concat String in a trigger but until now I did not succeed so here is my code:
CREATE TRIGGER `InvitationS_after_trig` AFTER INSERT ON `Invitations`
FOR EACH ROW
BEGIN

    if(new.status ='c' OR new.status ='r')
    BEGIN
        SET @query = CONCAT("INSERT INTO", Invetations.userId,"values(new.userId,new.name,new.status,new.userId_inv);");
        PREPARE stmt1 FROM @query;
        EXECUTE stmt1;
        DEALLOCATE PREPARE stmt1;
    END IF;
END;

I resolved the syntax problem but I now have an other one:

Dynamic SQL is not allowed in stored function or trigger

I'm using MySQL version 5.1.69.
Finally  I give up, I will resolve this problem using java Fonction


text:
Q: ionic zip - Adding data from multiple binary files to a single ZIP .NET 4.6.2
I read some (I know they are valid) files from a database and then try to combine them into a single ZIP file using the following function:
    public static byte[] CompressData(IList<ZipFileData> zipFileDatas)
    {
        var buffer = new byte[(int)zipFileDatas.Sum(z => z.Length)];

        using (var ms = new MemoryStream(buffer))
        {
            using (var zip = new ZipFile())
            {
                foreach (var zipFileData in zipFileDatas)
                    zip.AddEntry($"{zipFileData.FileName}.{zipFileData.FileType}", zipFileData.Data);

                zip.Save(ms);
            }

            return ms.ToArray();
        }
    }

The parameter is a collection of these:
public class ZipFileData
{
    public string FileName { get; set; }
    public string FileType { get; set; }  // Eg: PDF, JPG, XSLX
    public byte[] Data { get; set; }
    public long? Length { get; set; } // Length of the data
}

The function appears to work correctly, but later when I save the returned byte[] as "my.zip" and try and open it (from Windows 10), I get the error "The Compressed (zipped) Folder C:...\my.zip is invalid.
I'm trying to determine if this function (or some other code) is the cause of the issue.
Has anyone done something similar before or could verify that the function is (in)correct?

A: You allocate a buffer too small:
var buffer = new byte[(int)zipFileDatas.Sum(z => z.Length)];

A non compressed zip file will be slightly larger that the sum of files inside: each zip entry has a header (sometimes a footer) and there is a "table of content" at the end of the zip file (the central directory).
var ms = new MemoryStream(buffer)

will create a non-resizable memory stream a bit too small. Unfortunately for you, the last bytes you miss are the most important ones: That's where you find the offset of the central directory. Without it, you have a corrupted zip file.
To fix this, use a resizable memory stream:
var ms = new MemoryStream()


text:
Q: Removing the onsubmit value from a form with javascript I have some forms with onsubmit="return false;", example:
<form id="form-nr-56" action="" method="post" onsubmit="return false;">
formstuff
</form>

If certain conditions are met, i will submit the form by javascript
$('#form-id').submit();

But i need to remove the onsubmit="return false;" from the form in question first.
How to do that?
EDIT: Im not using javascript check in the onsubmit because the form verification is using alot of ajax requests and also a setTimeout, so it would always return false.

A: Look here on jquery.com docs: http://api.jquery.com/removeAttr/
That answer's your technical question. Some of the other replies on here answer it on a more logical approach, other ways that may be better to achieve what you are trying to do.

A: <script>
    if(//your codition here)
    {
       $('#form-id').submit();
       return false;
    }
</script>

A:     <script>

    //write your conditions and return false if not valid other wise otherwise

   function example()
   {
       if your condition false
        return false;

       $('#form-id').submit();

   }

    </script>

A: $('#form').on('submit', function(e)
{
    e.preventDefault();
    // Do what you want before the form submits
}

Try this & check.

A: You could use jQuery to stop the submit, then add your logic.
$('#form-id').on('submit', function(event) {
    event.preventDefault();
});

A: You do not need to add onSubmit = "return false;"
You can do it as below,
$('#form-id').submit(function(e)
{
    e.preventDefault();
    var isTrue = false;

    //conditions.
    //set isTrue = true on all conditions validation.
    //and then return isTrue.
    return isTrue;

});


text:
Q: How to retrieve Skype status - SharePoint Framework webpart We have this requirement to show a user's presence status in a SharePoint Framework webpart and am wondering what would be the best way to achieve this.

A: Check this.....
React Skype Status WebPart
This sample demonstrates how to use the UCWA JS SDK for skyp....
https://github.com/SharePoint/sp-dev-fx-webparts/tree/master/samples/react-skype-status


text:
Q: Dompdf - how to display table and graph sidebyside? I have a question regarding dompdf as what I am trying to do is print everything in one line so 4 html different portion on one line:
like this working fine screenshot 1:

but if I have first table as long table then it breaks everything and I couldn't get the output same as the first screenshot.

My Code is very simple and I know it's must be some quick html/css fix but what I have no idea or can I set pointer of print back on top so it manage screenshot- 1 even after printing the first long table?

       Report

	Source	Service Number	Date	Time	Place Called	Number Called	Usage Type

                            23:57:00
                            Calls and Services

                            20:19:00
                            Calls and Services

                            19:52:00
                            Calls and Services

                            19:50:00
                            Calls and Services

                            19:36:00
                            Calls and Services

                            19:34:00
                            Calls and Services

                            19:29:00
                            Calls and Services

                            19:14:00
                            Calls and Services

                            18:47:00
                            Calls and Services

                            18:30:00
                            Calls and Services

                            18:21:00
                            Calls and Services

                            23:52:00
                            Calls and Services

                            18:20:00
                            Calls and Services

                            18:10:00
                            Calls and Services

                            18:05:00
                            Calls and Services

                            17:57:00
                            Calls and Services

                            17:37:00
                            Calls and Services

                            17:28:00
                            Calls and Services

                            17:13:00
                            Calls and Services

                            17:06:00
                            Calls and Services

                            17:05:00
                            Calls and Services

                            17:02:00
                            Calls and Services

                            23:39:00
                            Calls and Services

                            16:57:00
                            Calls and Services

                            16:55:00
                            Calls and Services

	Username	First Name	Last Name

                            2004
                            7.80

                            2010
                            10.40

                            2010
                            9.10

                            2010
                            9.10

                            2010
                            9.10

                            2010
                            9.10

                            2011
                            20.50

                            2011
                            9.10

                            2011
                            9.10

                            2011
                            9.10

Hi Friends, please help me in this issue as I am trying to figure out from so long now or at least if anyone have an idea that how I can put printer printing pointer of dompdf to put again on first page to print rest of the next element to the long html table.

A: This is due to a limitation in how dompdf renders content. You're styling these elements with display: inline-block;, but this note regarding floats on the support forum applies:

dompdf renders page elements serially. What this means practically is that the floated element must be fully rendered before the next element. If a page breaks is encountered then the following element will be rendered after the page break.

You should be able to work around the issue if it's the case that your first table will always be the one that's longer than the page size. Instead of styling your elements as inline-block you might try floating them instead, e.g.

Or, even, absolutely positioning the right three columns and leaving the left-most column as above.


text:
Q:  How to add input element by clicking button? how can i add input element to add user?
if the + button clicked, add 1 input element like <input name=user1 ~~>
<input name=user2 ~~>
I want to receive the user and save it in the redux-store.
in this case, should i add user2, user3, user4... in DEFAULT_STATE in reducer.js too ?
or there is a way to add automatically ?
round.js >
 const handlerChange = (e) => {
    const { name, value } = e.target;
    dispatch(updateRoundData(name, value));
};
.
.
.

    USER

        <input
             name="user"
             onChange={handlerChange}
        ></input>
         <button onClick={addUser}>+</button>

};

reducer.js >
export const DEFAULT_STATE = {
country: "",
location: "",
user1: "",
user2: "",
user3: "",
user4: "",
};

ReducerRegistry.register("features/round", (state = DEFAULT_STATE, action) => {
switch (action.type) {
    case SET_ROUND_DATA:
        var { name, value } = action.data;
        return {
            ...state,
            [name]: value,
        };

    default:
        return state;
}

});


text:
Q: Proximal Operator of the Nuclear Norm with Non Negativity Constraints Let $L$ and $R$ be $n \times n$ matrices. Consider the following minimization problem
\begin{equation}
\mathbf{L} = \min_{L \geq \mathbf{0}}  \mu\|\mathbf{L}\|_* + \dfrac{1}{2\lambda}\|\mathbf{L-R}\|_F^2
\end{equation}
By $\mathbf{L}$ $\geq$ 0 , i mean that i want the entries of $\mathbf{L}$ to be non negative.
I know the solution can be obtained using the singular value thresholding of $\mathbf{R}$ when the non-negativity constraint on $\mathbf{L}$ is not present. But I can't figure out the change needed in order to satisfy the non-negativity constraint on $\mathbf{L}$.
Will simply setting the negative entries of $\mathbf{L}$ to zero work?
I have checked this link How to solve this minimization problem involving the nuclear norm? which is about $\mathbf{L}$ being positive definite; however my question is about the entries of $\mathbf{L}$ being non-negative. Can someone please answer this?

A: You could use the Douglas-Rachford method, which minimizes $f(L) + g(L)$, where $f$ and $g$ are closed convex functions with proximal operators that can be evaluated efficiently. For this problem, you can take $f(L) = \mu \|L\|_*$ and $g(L) = I(L) + \frac{1}{2\lambda} \| L - R \|^2_F$, where $I(L) = 0$ if $L \geq 0$ and $I(L) = \infty$ otherwise.


text:
Q: Auto-Create User Login from Wordpress to Perfex CRM I go straight to the Problem:

*

*User creates an account on my WordPress Website

*User decides to use the Support-Center (Perflex CRM)

*User gets redirected to the Support Website

*-> Problem: User will have to create an EXTRA account for the Support System

Question:
Is there any way to create automaticly an account for him with his Wordpress Credentials (Username, Email and Password)?
And/Or Additionally skip entering credentials (maybe with cookies?) and let him Log in straight into the just created account?
How would I archieve this in a safe/secure matter, is it even possible with the Perfex .php script?

Additional Infos:
Login Options on my WP Site: Standart method (Email/Pass), Google or Facebook.

A: It is quite easy, just install or write a module for Perfex to allow add a custom script to the frontend,or find in web "Custom JavaScript module for Perfex",
Ad Redirection link from WordPress site with  email and password for example :
// https://your.project.com/authentication/login?email=test@test.com&password=securePass

Warning: Remember about security issue if you send a plain password:
Apply this code to module :
<script>
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const email = urlParams.get('email');
const password = urlParams.get('password');
document.querySelector('#email').value = email;
document.querySelector('#password').value = password;
// call function once
let clickButton = (function() {
    let executed = false;
    return function() {
        if (!executed) {
            executed = true;
           document.querySelector(".btn").click();
        }
    };
})();
clickButton()
</script>


text:
Q: Fourier coefficient of $f \in L^1([a,b])$ If $f \in L^1([- \pi , \pi])$, by definition, the Fourier coefficients of $f$ are given by
$$
c_k = \frac{1}{2 \pi} \int_{- \pi}^{\pi} f(t) e^{- i k t} \, dt
$$
for all $k \in \mathbb{Z}$. Is there any definition for Fourier coefficients of $g \in L^1([a , b])$?

A: There are other conventions, but one is that, with $L = b-a$, the Fourier coefficients of $g$ are
$$ c_k = \frac{1}{L} \int_a^b g(t) e^{-2\pi i k t/L}\; dt $$


text:
Q: How to efficiently use the result of a Hasura query for another query? I am currently querying my Hasura database using userId to get location.
users(where: {id: {_eq: 1528}}) {
    location
}

I then use location to query users near that one user.
    users(
      where:
        { location: {_st_d_within: {distance: 20000, from: $point }}},
    ) {
      firstName
      city
      region
    }
  }

Is there a way to efficiently combine these two queries such that I only query once?

A: You can not combine these two queries into one.
What you can do is create a Postgres function and query that function instead as described in Hasura's documentation:
https://hasura.io/docs/1.0/graphql/manual/schema/custom-functions.html#example-postgis-functions


text: Q: Windows -- how to find the maximum number of processes of a single image name I am trying to figure out how many processes I can create of a single image name (i.e. "something.exe"). I see that when I practically try to create as many as I can, I get to around 150 (far less than the total overall processes that can be run by my machine). Figuring out the number by actual experimentation this way, however, is resource intensive and slow. I've searched all that I can on the subject and I can't seem to find anyone addressing this issue. A command line call or something of the sort would be great.


text:
Q: Php mail() function mail is getting rejected I have switched my old project to a new server in which i am using mail to sent mails sendmail is my mail server I am using php mail() function but it is not working properly
The php code which i am testing is this.
<?php
    ini_set( 'display_errors', 1 );
    error_reporting( E_ALL );
    $from = "noreply@xyz.com";
    $to = "panel1@mailinator.com";
    $subject = "PHP Mail Test script";
    $message = "This is a test to check the PHP Mail functionality";
    $headers = "From:" . $from;
    $val = mail($to,$subject,$message, $headers);
    echo "Test email sents";
    echo $val;
?>

The mail is getting recived but it is getting deliverd from another address which is like this.
noreply@xyz.interactivedns.com

And the mail log is this
Oct 23 18:43:51 xyz2 sendmail[14831]: w9NIhp9R014831: from=www-data, size=177, class=0, nrcpts=1, msgid=<201810231843.w9NIhp9R014831@xyz.com>, relay=www-data@localhost
Oct 23 18:43:51 xyz2 sm-mta[14832]: w9NIhpIF014832: from=<www-data@xyz.com>, size=396, class=0, nrcpts=1, msgid=<201810231843.w9NIhp9R014831@xyz.com>, proto=ESMTP, daemon=MTA-v4, relay=www.xyz.com [127.0.0.1]
Oct 23 18:43:51 xyz2 sendmail[14831]: w9NIhp9R014831: to=panel1@mailinator.com, ctladdr=www-data (33/33), delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=30177, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (w9NIhpIF014832 Message accepted for delivery)
Oct 23 18:43:53 xyz2 sm-mta[14835]: w9NIhpIF014832: to=<panel1@mailinator.com>, ctladdr=<www-data@xyz.com> (33/33), delay=00:00:02, xdelay=00:00:02, mailer=esmtp, pri=120396, relay=mail.mailinator.com. [23.239.11.30], dsn=2.0.0, stat=Sent (Ok)

If i use gmail id the mail is not at all getting delivered not even in spam box
What can i do here?

A: To answer your question...
It looks like you are missing some headers I used on a similar project a while ago. Try replacing your $header line with the following:
$message = wordwrap($message , 70);
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: ' . $from . "\r\n";

Now, a word of advice...
I struggled with the native PHP mail() function for a loooong time while stubbornly resisting other options. Believe me, you will save yourself a lot of time and trouble using something like PHPMailer. When I finally gave in and implemented it (which was way easier than I imagined), all of the problems I was fighting through with mail() vanished. Unless you are willing to write your own complex mailing libraries, please consider PHPMailer or a similar tool.


text:
Q: Possible to use Windows.Devices namespace in a console app? I am wondering if it is possible to use the Windows.Devices namespace in a regular console app with .net 6.
I get this error message when I try to include them, though I read that they are meant for UWP applications...
Is there perhaps a workaround for making them functional in console apps?
I am quite new to C#, so many thanks in advance for any and all help!


text:
Q: Basic LISP Issue So (car '(2 3)) -> 2
(cdr '(2 3)) -> (3)

Which function should I use to be able to get something to yield 3?
(function-name '(2 3)) -> 3

A: It should be fine to simply do:
(car (cdr '(2 3)))

Which is the same as:
(cadr '(2 3))

This works because "car" gets the first element in the expression, whereas cdr returns the remainder of the list, without the first element.  You've already shown that "(cdr '(2 3))" returns a list of "(3)".  Therefore, the "car" of this is the element (not the list), "3".  By the way, the "(cdr (cdr ('2 3)))" is the "(cdr (3))", which is "()".
Isn't LISP fun?

A: Hints:
car refers to the first element in the list.
cdr refers to the remainder of the list, and is itself a list.
So what you need is a function that returns the first element from a list containing the last element.

A: You could also use (second '(2 3)).  second is another name for cadr.


text:
Q: python click accept on a website in selenium I try to click this button in selenium python
website : nbsklep.pl

i try like this :
  element = self.driver.find_element_by_xpath("/html/body/reach-portal[2]/div[2]/div[2]/div/div[2]/button[2]")
  element.click()

Everythingthing is correct.. Path is good i don't know why it dont clicks it. Using the newest chromedriver v100~.

A: from selenium import webdriver
import time

driver = webdriver.Chrome("chromedriver")
driver.get("https://nbsklep.pl/")
time.sleep(2)
driver.find_element_by_css_selector("body > reach-portal:nth-child(7) > div.CookieInfo_modal__8bL4N > div.CookieInfo_content__h3sZ5 > div > div.CookieInfo_settingsActions__i_8lc > button:nth-child(3) > span").click()
time.sleep(2)

A: You can use the following CSS selector to interact with the desired web element.
button[class='Button_button__Nw3FH Button_buttonSizeLarge__68E7y']


text:
Q: Check if value 'abc' and not 'abc aze' contained in textbox I want to know if the value 'Type de prise' exists in MySQLBDDColumns.Text
I get the value I want to know if it is contained in Texte_Caractéristiques.Text
But only I have the value 'Type de prise' and the value 'Type de prise du chargeur' so if 'Type de prise du chargeur' was created before when it will try to know if 'Type de prise' exists. say yes while I would like it to be no.
Here is my code:
for (y = 0; y <= (Texte_Caractéristiques.Lines.Length - 1); y = y + 2)
{
    if (MySQLBDDColumns.Text.Contains(EnleverAccent(Texte_Caractéristiques.Lines[y])))
    {
        if (y == Texte_Caractéristiques.Lines.Length - 2)
        {
            Sauvegarde_Dans_BDD();
        }
    }
    else
    {
        CreateColumnsIfNotExists(EnleverAccent(Texte_Caractéristiques.Lines[y]));
        Get_ColumnsBDD();

    }
}

So I would like to have a method that would allow me to know if MySQLBDDColumns.Text contains the value 'Type de prise' without which I return a true value if 'Type de prise du chargeur' exists or another value that can contain the same text
I have also tried with Regex, IndexOf and equals but I can not find any solutions for the moment.

A: If you only want an exact match, does comparing equal work?
string.Equals(MySQLBDDColumns.Text, EnleverAccent(Texte_Caractéristiques.Lines[y]), StringComparison.CurrentCultureIgnoreCase)

I've also added the condition of ignoring case to the comparison, but this can be removed as needed.


text:
Q: Can't seem to turn off a device using dev.off() in R I'm using Jupyter notebooks running an R kernel (3.2.2) in OSX, working through some basic stats exercises. A few days ago I played with ggplot for the first time, and ran some commands from a notebook cell experimenting with printing to pdf files, in other words using something like the following: pdf("file.pdf"); plot(x, y); dev.off()  I didn't keep any of those cell contents, so I can't see exactly what I ran but I imagine it is possible I create some pdfs and didn't include a dev.off() command?
My problem is, since that session, now every cell I run in any notebook (including new blank ones) generates an unwanted pdf file. If that code involves plotting a figure, the pdf contains that figure, if the code is anything else, the pdf created is unable to be opened. I can't find any way, elegant or brutish, to stop these pdfs from being created.
If I go to a new blank notebook:
running dev.list() returns pdf: 2
running dev.cur() returns pdf: 2
running dev.off() returns null device: 1
but then, if immediately after, I run either dev.list() or dev.cur() again, they again return pdf: 2
I am able to open additional new devices, and dev.off() succeeds in closing them. But this pdf: 2 device won't go away. I tried terminating all my sessions, rebooting my machine, etc., to no avail; Suggestions?
Additionally, If I run a pdf() command from a console in Terminal (i.e., not from a notebook), my plots show as being generated by Quartz; I understand this might be a Quartz problem and not an R problem, but my question remains, how do I close this device, or otherwise stop all these pdfs from being created?

A: This may be a problem when a sink() has been opened but not closed, perhaps because an error occurred before the closing code was reached.
Try this to plug an open sink:
sink(NULL)
ht @mdsumner

A: graphics.off()

should forcefully close all devices. Check out this page for more useful information.


text:
Q: How to import two classes with the same name in different packages? I want to import these two classes, both named Query - one a JDO class, the other a JPA class, to use in different methods in the same class.
import javax.jdo.Query;
import javax.persistence.Query;

Is there a way to globally import both of them at the same time at the top of the file?

A: The existing answers are correct. I'd like to show you how class name conflicts can be handled in Kotlin (docs).
If there is a name clash, we can disambiguate by using as keyword to locally rename the clashing entity:
import javax.jdo.Query // Query is accessible
import javax.persistence.Query as jpaQuery // jpaQuery stands for 'javax.persistence.Query'

That's +1 reason why you should consider Kotlin for your next project.

A: The only purpose of an import statement is to establish a shorthand alias for a fully-qualified name. If you were allowed to imported both, you'd create an ambiguity that would require type inference to resolve, and make your code extremely difficult to read.

A: I'm afraid, no. But you don't have to import class to use it: just reference one of the classes by its full name, like
javax.jdo.Query query = getJDOQuery();
query.doSomething();

Then you can import another without name collisions.
BTW, sometimes if you start getting lots of such name such collisions in your class, it's a subtle hint for refactoring: splitting functionality of one big class between several small ones.