Monday, January 31, 2022

OSCHINA 社区最新讨论话题

OSCHINA 社区最新讨论话题


什么时候修复搜索功能?

Posted: 30 Jan 2022 07:35 PM PST

什么时候能修复个人博客搜索? 自己的博客搜不出来,还要一个一个找,这就是偌大的开源中国博客的搜索能力?

Recent Questions - Mathematics Stack Exchange

Recent Questions - Mathematics Stack Exchange


Laplace transform of 3, simple but what happens to $e^{st}$ term?

Posted: 31 Jan 2022 09:08 AM PST

I want to find the Laplace transform of f(t)=3, simply it is calculated by the integration procedure:

\begin{equation} \int_{-\infty}^{\infty}f(t)e^{-st}dt=3\int_{-\infty}^{\infty}e^{-st}dt=\bigg[\frac{3}{s}e^{-st}\bigg]_{\infty}^\infty=\bigg(\frac{3}{s}e^{-s\infty}+\frac{3}{s}e^{s\infty}\bigg)=\frac{3}{s}\bigg(e^{-s\infty}+e^{s\infty}\bigg) \end{equation}

But here the last term in the brackets is certainly not 1, in fact it evolves towards infinity, as given here.

But wolfram suggests on $f(s)=\frac{3}{s}$. What happened with $e^{-st}$ terms then?

Thanks

Very basic trig question: how to calculate an angle given a slope (an angle from a ratio of sides)

Posted: 31 Jan 2022 09:07 AM PST

I am trying to write a very basic trig primer, from scratch. I asked a basic question on Mathematics Educators, but they suggest to ask here. Here it is.

Say I discuss slopes (say, the slope of a line through the origin), and wish to give the 'right' hints on how the slope of a line is related to the angle of the line with the x-axis.

It would be nice to show how to calculate the angle, given the slope. I am looking for easy examples, say for lines with slopes 1,1/2,1/3,1/4,...; or any suitable family of lines.

I am not completely sure, but my question seems to be something like: how do I design an algorithm (and/or a geometric construction) to determine the angle from the slope (i.e, from the ratio of sides).

Sorry to be quite vague.

Convergence in the operator norm

Posted: 31 Jan 2022 08:58 AM PST

Given the following operator: $T:\ell^2\to\ell^2$, which acts in the following way on the standard basis vectors: $$Te_{2k-1}=\frac{1}{k}(e_{2k-1}-ie_{2k})$$ $$Te_{2k}=\frac{1}{k}(ie_{2k-1}+e_{2k})$$ I need to prove that this operator is compact by showing that it is the limit of finite rank operators. My attempt:

Define $(T_nx)_j=(Tx)_j$, for $j\le 2n$, and for $j\gt 2n: (T_nx)_j = 0$. Intuitively this should converge to $T$ In the operator norm and all these operators $(T_n)_{n\ge1}$ are of finite rank thus $T$ is compact!

Let us try and show that $\|T-T_n\|\to0$, for $n\to \infty$. $$\|T-T_n\|=\sup_{\|x\|=1}\|(T-T_n)x\|$$, but from here I am lost I don't see how this expression goes to $0$. Can anyone show me how it works?

Boolean Algebra; comprehending a given solution

Posted: 31 Jan 2022 08:52 AM PST

I am reading a text on Boolean Algebra. Right after the definition of the disjunctive normal form and the conjunctive normal form the author gives an example. Unfortunately I am not able to understand a transformation, that is needed to find the CNF of the given Boolean expression using the four Axioms. (The DNF was easy to find, so I know that there are probably no mistakes in the text.)

Let $z(x'y'+xy)'+x'y$ be a Boolean expression. Using De Morgan's laws we have $$z(x+y)(x'+y')+xy'.$$ That was easy. The author then goes on stating:

It follows immediately that $$z(x+y)(x'+y')+xy'=(z+xy')(x+y+xy')(x'+y'+xy')$$ $$=(x+z)(y'+z)(x+y)(x'+y').$$

I do not understand what is happening in these two lines, so I would be grateful if someone could tell me in detail what is going on.

If you are interested, the "final" CNF supposedly is $$(x+y'+z)(x+y+z)(x'+y'+z)(x+y+z')(x'+y'+z')$$

Area of Triangle and Diophantine Equations

Posted: 31 Jan 2022 08:56 AM PST

We are given some arbitrary solution $(x_0, y_0)$ to $ax-by=1$ and another point $(b,a)$. We are asked to prove that the area of the triangle with vertices at $(0,0)$, $(b,a)$, and $(x_0, y_0)$ is $\frac{1}{2}$. I figured that I should use the equation for a right triangle, and apply some substitution as follows:

$\frac{1}{2}\sqrt{x_0^2+y_0^2}\sqrt{(b-x_0)^2+(a-y_0)^2}$

plugging in $x_0$ and $y_0$ in terms of the diophantine equation doesn't seem to cancel out any terms and the algebra is messy.

Derivative of a matrix w.r.t to another?

Posted: 31 Jan 2022 08:46 AM PST

What's the general formula for taking the derivative of a matrix w.r.t to another matrix? For example, what's $\frac{\partial A}{X}$, $\frac{\partial A}{X^\top}$, $\frac{\partial A}{\tilde{X}}$, $\frac{\partial A}{\tilde{X}^\top}$ for $A = X\tilde{X}^\top$, $A = X\tilde{X}$, $A = X^\top\tilde{X}$, and $A = X^\top\tilde{X}^\top$.

Or how about $\frac{\partial A}{X}$, $\frac{\partial A}{X^\top}$ for $A = XX^\top$, $A = X^2$, $A = X^\top X$

I struggle to derive these generally, are there known formulas for these? How do I in general go about deriving these? There are also more complicated cases of $\frac{\partial X\tilde{X}}{X^\top \tilde{X}}$ and so on.

Confusion about the necessity of the axiom of choice for infinite sets [duplicate]

Posted: 31 Jan 2022 08:46 AM PST

Given a family $(X_i)_{i \in I}$ of non-empty sets, why cannot one introduce a function $f : I \to \bigcup_{i \in I} X_i$ as follows :

for all $i \in I$, there exists $x \in X_i$ — let $f(i) := x$,

thus producing a "choice function" ?

Why isn't the above construction valid in $\sf {ZF}$ ?

Solve the complex number equation $|z|-\bar{z}=i$

Posted: 31 Jan 2022 08:39 AM PST

Solve the complex number equation $|z|-\bar{z}=i$.

The following was my thought process:

$$|z|=i+\bar{z}$$ Given that $Im(|z|)=0$, $Im(\bar{z})=-i$. Hence, $\bar{z}=a-i$ and $z=a+i$.

$$|z|=i+(a-i)$$

$$|z|=a$$

But since $z=a+i$, $|z|=\sqrt{a^2+1}$ and hence I've reached a contradiction, as $\sqrt{a^2+1}\neq a$.

Hence, there is no solution for $|z|-\bar{z}=i$, for $z\in\mathbb{C}$.

How do we calculate the inverse Laplace transform of $F(s)=\frac{s^2+1}{(s+1)(s-1)}$?

Posted: 31 Jan 2022 08:43 AM PST

We have

\begin{equation} F(s)=\frac{s^2+1}{(s+1)(s-1)} \end{equation}

which I want to use Heavisde method to find the fractions.

We start

\begin{equation} F(s)=\frac{s^2+1}{(s+1)(s-1)}=\frac{A}{(s+1)}+\frac{B}{(s-1)} \end{equation}

By Heaviside method, we multiply both sides by the denumerator of A, ($s+1$)

\begin{equation} (s+1)\frac{s^2+1}{(s-1)}=A+\frac{B(s+1)}{(s-1)} \end{equation}

We insert for the pole of the A-fraction, for s, that is $s=-1$ and we obtain

\begin{equation} (-1+1)\frac{s^2+1}{(s-1)}=A+\frac{B(0)}{(-2)} \end{equation}

which gives the incorrect results, that $A=0$

What should I do here to prepare the fractions correctly for the Heaviside method to be applied?

Thanks

Update, I devise the method suggested below in the accepted solution, and try the Heaviside method on that.

\begin{equation} F(s)=\frac{s^2+1}{(s+1)(s-1)}=\frac{(s^2-1)+2}{(s+1)(s-1)} \end{equation}

\begin{equation} F(s)=\frac{(s^2-1)+2}{(s+1)(s-1)}=\frac{(s+1)(s-1)+2}{(s+1)(s-1)} \end{equation}

\begin{equation} F(s)=\frac{(s+1)(s-1)+2}{(s+1)(s-1)}=\frac{(s+1)(s-1)}{(s+1)(s-1)}+\frac{2}{{(s+1)(s-1)}} \end{equation}

\begin{equation} F(s)=1+\frac{2}{{(s+1)(s-1)}} \end{equation}

So from here we treat the last fraction with the Heaviside method:

\begin{equation} F(s)=\frac{2}{{(s+1)(s-1)}}=\frac{A}{(s+1)}+\frac{B}{(s-1)} \end{equation}

Find A by multiplying with $(s+1)$ on both sides and obtain

\begin{equation} (s-1)=A+\frac{B(s+1)}{(s-1)} \end{equation}

Insert for the pole of the A-fraction, $s=-1$

\begin{equation} (-1-1)=A+\frac{B(-1+1)}{(s-1)} \end{equation}

This yields that $A=-2$. We do the same for B,

\begin{equation} (s+1)=\frac{A(s-1)}{(s+1)}+B \end{equation}

Insert for $s=1$, and get that $B=2$, hence:

\begin{equation} F(s)=1+\frac{2}{(s-1)}-\frac{2}{(s+1)} \end{equation}

Inverse transform of F(s):

\begin{equation} \mathscr{L}^{-1}\{1+\frac{2}{(s-1)}-\frac{2}{(s+1)}\}=\delta(t)+2e^{t}-2e^{-t} \end{equation}

Hard Integral without Partial Fraction Decomposition

Posted: 31 Jan 2022 08:48 AM PST

So I was trying to use partial fraction decomposition on this problem, and I realized that it didn't work, as it is already in partial fraction decomposition form.

$\int{\frac{3x+4}{(x^2+5)^2}dx}=$

Well, $\frac{3x+4}{(x^2+5)^2}=\frac{Ax+B}{x^2+5}+\frac{Cx+D}{(x^2+5)^2}$

$(x^2+5)^2[\frac{3x+4}{(x^2+5)^2}]=(x^2+5)^2[\frac{Ax+B}{x^2+5}+\frac{Cx+D}{(x^2+5)^2}]$

$3x+4=(Ax+B)(x^2+5)+(Cx+D)$

$3x+4=Ax^3+5Ax+Bx^2+5B+Cx+D$

$3x+4=(A)x^3+(B)x^2+(5A+C)x+(5B+D)$

So, $A=0$, $B=0$, $5A+C=3$, and $5B+D=4$

So, $A=0$, $B=0$, $C=3$, and $D=4$

$\int{\frac{3x+4}{(x^2+5)^2}dx}=\int{\frac{(0)x+(0)}{x^2+5}+\frac{(3)x+(4)}{(x^2+5)^2}}dx$

$\int{\frac{3x+4}{(x^2+5)^2}dx}=\int{\frac{3x+4}{(x^2+5)^2}}dx.$

As this clearly doesn't work, I am wondering what the integral would be. WolframAlpha tells me that the integral is as follows:

$\int{\frac{3x+4}{(x^2+5)^2}dx}=\frac{1}{50}(\frac{5(4x-15)}{x^2+5}+4\sqrt{5}\tan^{-1}(\frac{x}{\sqrt{5}}))+c$

I am not sure how to get here. Any help would be greatly appreciated.

Prove Linearity

Posted: 31 Jan 2022 08:54 AM PST

Given the following time varying model: $Z(t) = \alpha*t*z(t-1)$, how do I go about proving linearity? The issue I keep running into with a number of approaches is that because Z(t) is dependent on Z(t-1), I always end up with some inscrutable function within the function.

For transparency this is homework, some I'm happy for general guidance over a full solution.

Edit: The question explicitly says "Prove linearity" not "prove or disprove linearity." And the professor has used these homework's for years. So... take that for what it's worth. This is in the context of time series.

If $x\in X$ and $r > 0$, then for every $y\in Y\cap B^{X}_{r}(x)$ there is $s > 0$ such that $y\in B^{Y}_{s}(y)\subset Y\cap B^{X}_{r}(x)$.

Posted: 31 Jan 2022 08:47 AM PST

Exercise

If $x\in X$ and $r > 0$, then for every $y\in Y\cap B^{X}_{r}(x)$ there is $s > 0$ such that $y\in B^{Y}_{s}(y)\subset Y\cap B^{X}_{r}(x)$.

My attempt

So far it has not been discussed the characterization of open sets as sets that each point is contained in an open ball contained in the set. Having said, could anyone give me some hint to solve such exercise? It is not homework. I am really interested in understanding the theory properly.

Notation

The notation $B^{X}_{r}(x)$ represents the open ball centered in $x$ with radius $r > 0$ within the set $X$.

Verifying continuity by topology

Posted: 31 Jan 2022 08:46 AM PST

I want to show that sum of two continuous functions is continuous using the topological definition only .

I know the question could be answered by composing two continuous functions $(.,.):X\to\mathbb{K}^2$ and $+:\mathbb{K}^2\to\mathbb{K}$ over some infinite field $\mathbb{K}$ , and that has been answered several times in this site as well . But if I would want to use the basic open set definition , what would be the correct approach ?

Here's what I tried . Consider two continuous maps $f:X\to\mathbb{K}$ and $g:X\to\mathbb{K}$ where $X$ is some topological space . Then for all open sets $U$ in $\mathbb{K}$ , we have $f^{-1}(U)=\{x\in X:f(x)\in U\}$ and $g^{-1}(U)=\{x\in X:g(x)\in U\}$ are open in $X$ . We need to show $(f+g)^{-1}(U)=\{x\in X:(f+g)(x)\in U\}=\{x\in X:f(x)+g(x)\in U\}$ is open in $X$ . But how to relate the $f^{-1}(U),g^{-1}(U)$ with $(f+g)^{-1}(U)$ I don't understand . I have a feeling that the fact union of two open sets is open might be useful here .

Any help is appreciated .

Given a flow network and a max flow f on it, Determine whether there are at least 4 different max flows.

Posted: 31 Jan 2022 09:02 AM PST

I'm having trouble solving this one and would really appreciate any help. thank you in advance!

so, the problem is:

given a flow network with integer capacities on the edges and a max flow f on that network, I need to write an algorithm that determine whether there are at least 4 more different max flows on that given network.

thanks again!

Solving second order differential equations for forced oscillation

Posted: 31 Jan 2022 09:05 AM PST

please refer to this image

Please refer to this image

I have several doubts regarding the stapes involved in solving this Differential equations

  1. Why the $-\delta$ term is interduced in $x_{c}(t)=A e^{i(\omega t-\delta)}$? what is the intuition behind this ? is it still mathematicaly currect all though we have altered the Equation ?

2.How we reached $A(\omega)=\frac{1}{\sqrt{\left(\omega_{0}^{2}-\omega^{2}\right)^{2}+\gamma^{2} \omega^{2}}}$ (Please give some detailed Solution)

Please someone help

Show that two random variables have equal distribution

Posted: 31 Jan 2022 08:49 AM PST

Let $(X, \{\mathbb{P}_\vartheta; \vartheta \in (0,1)\})$ be a statistical model whith the density of $X$ given as $$ f_\vartheta(x) = \frac{\vartheta^{-1}}{2}\mathbb{1}_{[0,\vartheta]}(x) + \frac{(1 - \vartheta)^{-1}}{2}\mathbb{1}_{(\vartheta,1]}(x). $$

  1. Let $U,V$ ~ $U([0,1])$ independent. Show that $X$ is equally distributed as the random variable $\vartheta V\mathbb{1}_{U \leq 1/2}+(1-(1-\vartheta)V)\mathbb{1}_{U>1/2}$.
  2. Show that $\mathbb{E}_\vartheta[X] = \frac{1}{2}\vartheta + \frac{1}{4}$
  3. Let $((X_1,\dots,X_n), (\mathbb{P}_{\vartheta)\in(0,1)})$ be such that $X_1,\dots,X_n$ are independent and identically distributed with density $f_\vartheta$. Find an unbiased and consistent estimator for $\vartheta$ and proof unbias and consistent.

I tried this exercise for a very long time and didn't get any further so some help would be nice.

What is the largest $n\times n$ square lattice that can be $k$-colored such that no rectangles with same-colored vertices exist?

Posted: 31 Jan 2022 09:06 AM PST

It is fairly well known that for any $k$-coloring of $\mathbb{Z}^2$, it is impossible to color the vertices such that you never get a rectangle with axes parallel to the x and y-axis with vertices of the same color. In fact, it is known that you cannot color an $(k+1) \times (\frac{k^2(k+1)}{2}+1)$ lattice of points that meets this criterion. For example, you cannot 2-color the $3\times 7$ lattice in this manner. You can, however, color the $(k+1) \times (\frac{k^2(k+1)}{2})$ lattice in this way. One such successful 2-coloring of the $3\times 6$ lattice is below.

![enter image description here

So, if the $3\times 6$ lattice is 2-colorable in this fashion, it is a natural question to ask, "what about the $6\times 6$ lattice?". As it turns out, the answer to this is "no". We can prove this by first showing you cannot 2-color the $5\times 6$ lattice.

After some experimentation, one sees that the only successful 2-coloring of the $4\times 6$ lattice is some permutation of the rows and columns of the below.

enter image description here

If one adds a column to the right, it becomes apparent that the top-right vertex can neither be red nor blue: in the case of the former, we eventually see that the fourth-row vertex cannot be red or blue, and in the case of the latter, we see the same for the third-row vertex. Therefore, the $6\times 6$ lattice cannot be colored like this - QED.

However, what about the $5\times 5$ lattice? It becomes clear that we essentially have six unique ways to color in the first three rows, seen below (again, barring permutations of the rows and columns). I know that out of these six, you cannot 2-color the top-left one successfully. I have yet to try the others, but would not be surprised to find you cannot achieve this for any configuration.

enter image description here

For what it is worth, it can be shown that yes, the $4\times 4$ lattice can be successfully colored like this, which will be shown at the end. However, this is only for 2-coloring. What about 3-coloring, or 4-coloring? What about $n$-coloring in general? If I had to make a conjecture, the most I would be willing to say is that you can never make a $(\frac{k^2(k+1)}{2})\times (\frac{k^2(k+1)}{2})$ lattice that can be colored like this, but even for that I don't know where to start proving it, and I don't know how to move that upper bound any lower. Any thoughts?

enter image description here

Prove that $X_t = W_t \mathbb{1}(\tau > t) + (2W_{\tau} - W_t) \mathbb{1}(\tau \le t)$ is a martingale.

Posted: 31 Jan 2022 09:04 AM PST

Consider $W_t$ is a standard Wiener process. Assume $\tau = \inf\{t : W_t = a\}$. Consider $X_t = W_t \mathbb{1}(\tau > t) + (2W_{\tau} - W_t) \mathbb{1}(\tau \le t)$. We want to show that $(X_t, \mathcal{F}_t)$ is a martingale, where $\{\mathcal{F}_t\}$ is natural filtration of the Wiener process.

I know that it's possible to show that the process is also Wiener, but it's much more complicated (since we use strong Markov property). Here I guess the situation is much easier.

It's not hard to show that $X_t$ is $\mathcal{F}_t$ measurable and $L_1$. The major problem is to show $\mathbb{E}(X_t | F_s) = X_s$ precisely.

I tried so: consider different cases

  1. $s < t < \tau$: $\mathbb{E}(W_t|F_s) = W_s$

  2. $s < \tau < t$: $\mathbb{E}(2W_\tau - W_t | F_s) = \mathbb{E}(2W_\tau - 2W_s + W_s - W_t + W_s | F_s) = W_s$

  3. $\tau < s < t$: $\mathbb{E}(2W_\tau - W_t| F_s) = \mathbb{E}(2W_\tau - W_s - (W_t - W_s)|F_s) = 2W_\tau - W_s$

But I guess it's not so fair to write so, since $\tau$ is random variable and for some $\omega \in \Omega$ it might be true and for others not. Any hints?

Equation of a cubic Bezier curve

Posted: 31 Jan 2022 09:08 AM PST

quadratic bezier curve

For a quadratic Bezier Curve defined by points $A, B, C$, with point $M$ on the curve interpolated by $i$,

When points $A, M, C$ and angle $\alpha$ are given, $i$ and $B$ are:

$$i^2 = \frac{(y_A-y_M)\sin\alpha-(x_A-x_M)\cos\alpha}{(y_A-y_C)\sin\alpha-(x_A-x_C)\cos\alpha}$$ $$x_B=\frac{x_A(1-i)^2+x_Ci^2-x_M}{2i(i-1)}$$ $$y_B=\frac{y_A(1-i)^2+y_Ci^2-y_M}{2i(i-1)}$$

for a full working out: $$x_D = x_A+i(x_B-x_A)$$ $$x_E = x_B+i(x_C-x_B)$$ $$x_M = x_D+i(x_E-x_D)$$

$$x_M = x_A(1-i)^2+2ix_B(1-i)+i^2x_C$$ $$x_B=\frac{x_A(1-i)^2+i^2x_C-x_M}{-2i(1-i)} = AB\sin\alpha+x_A$$ $$y_B=\frac{y_A(1-i)^2+i^2y_C-y_M}{-2i(1-i)} = AB\cos\alpha+y_A$$ $$AB = \frac{i^2(x_A-x_C)+x_A-x_M}{2i\sin\alpha(1-i)}= \frac{i^2(y_A-y_C)+y_A-y_M}{2i\cos\alpha(1-i)}$$

hence resulting the above 3 equations.

cubic bezier curve

Now consider a cubic Bezier curve defined by points $A, B, C, D$

$1)$With given points $A, D$, $M$ interpolated by $i$,angles $\alpha, \beta$, Can $B, C$ and $i$ be derived?

$2)$ if not, With given points $A, D$, $M$ (interpolated by $i$), $N$ (interpolated by $j$), angles $\alpha, \beta$, What are the equations for $B, C$, $i$ and $j$?

Why subtracting each data point from the mean and then squaring it and divided it by n-1 is a good measure of spread?

Posted: 31 Jan 2022 08:45 AM PST

So, we are trying to find the distance of all of the data points about the mean. But, isn't it the other way around? When we use things like variance and MAD, aren't we actually finding the average distance of mean to all of the data points and not the distance of all of the data points from the mean? Isn't a more convincing way of finding a good number for a spread would be like this:

Sum of "average distance" of each data point to the other divided by n(sample pop.). Now, think of this thing for a second. Because it has been over a week that I am trying to make sense of why do are they finding just the average distance of one number, i.e. mean, in variance?

Formula is:

Sum of the "average distances" of each point divided by n.

By the sum of average distances I meant is: Let's say you have 4 data points: 2,4,8,12

  • I will ask how far is 2 from all of the data points, in absolute terms;

  • I get these numbers: 2,6,10 (4 is 2 units away, 8 is 6 units away, and 12 is 10 units away);

  • Then, I will ask a statistical question how are the data points from 2. I need one number.

  • Thus, I will take the average of these differences and the number I'll get is the distance of all of the data points from 2 on average.

  • Then, I will repeat the process for all of the data points.

  • And, left with 4 averages, which is the average distance of each point to all of the data points.

  • at last, I will again ask a statistical question, how far are the data points from each other.

  • Thus, I will sum all of these averages and divided them by n, which is 4 in this case.

  • And, the number I'll get is the number representing the spread of the data. Not, only the number is greater than what you could've found otherwise in variance.

I agree that variance and SD are the conventions. But, they give mean a special position. They say let's find the distance of all of the data points from the mean, but the way I see it they actually measure how far is mean to all of the data points. The analysis is incomplete. The way I proposed the formula, I know it's a little bit lengthy, but I take into account each number in the data set, find how far is each of them from each other, and then take an average to finally get to the point. I didn't give any special position to any number.

Note: I understand that it will take time to find the measure for spread relative to what we are used to, i.e., variance and standard deviation. But, I think the important thing to realize is that we will, at last, use all of the data and measure it through programs. And, I can make a code in R that can easily calculate the spread with the formula I just proposed.

Existence elimination in Lean 3

Posted: 31 Jan 2022 08:58 AM PST

Lean 3 is a theorem prover that implements the calculus of inductive constructions. Differently than Coq, Lean 3s kernel works proof irrelevant. This means that in the kernel of Lean all proofs of the same theorem are judgmentally (definitionally) equal and can be substituted for each other.

Does that mean that if I have A : Type, P : A -> Prop, and p : (∃ x : A, P x), then there is no way to extract an actual w : A from p which satisfies P w?

I thought being able to extract witnesses from existence proofs is one of the main arguments for Martin-Löf style type theories.

In how many ways one can arrange the numbers $0,1,2,\dots,n$ using each number exactly once so that no two adjacent numbers sum greater than $n+1$?

Posted: 31 Jan 2022 08:51 AM PST

Given the numbers $0,1,2,\dots,n$. In how many ways one can arrange the numbers using each number exactly once so that no two adjacent numbers sum greater than $n+1$?

I found the answers for small values of $n$. For $n=1$, the answer is $2$. For $n=2$, the answer is $6$. For $n=3$, the answer is $12$. But how to solve this problem for any $n$?

Equivalent condition to boundedness of a linear operator

Posted: 31 Jan 2022 08:44 AM PST

I have to prove the following statement:

Let $X$ and $Y$ be normed spaces over $\mathbb{K}$ and $T:X\to Y$ a linear operator. Prove that $T$ is bounded iff $\sum_{n=1}^\infty T(x_n)$ converges for all sequences $\{x_n\}$ for which $\sum_{n=1}^\infty x_n$ converges absolutely.

I have been stuck on this problem for days, yet I feel I'm really close to solving it. Any hint, idea or advice would be appreciated. I haven't been able to prove any of the implications, but this is what I have right now:

For the $(\implies)$ direction, assume that $T$ is bounded, and let $\{x_n\}$ be a sequence such that $\sum_{n=1}^\infty x_n$ converges absolutely. I'm trying to prove that $\sum_{n=1}^\infty T(x_n)$ converges on two steps. First I prove that the sequence $\{S_k\}_{k=1}^\infty$ where

$$ S_k=\sum_{n=1}^kT(x_n) $$

is Cauchy. This is easy to show using the boundedness and linearity of $T$, and the fact that $\{\sum_{n=1}^k ||x_n||\}_{k=1}^\infty$ is Cauchy, because it converges. Then I would like to prove that the sequence $\{S_k\}$ has a convergent subsequence, as that would imply the result. However, I don't know how to show this. The only idea I had was to prove and use this statement:

If $\{x_n\}$ is a sequence on a normed space $X$ such that $\sum_{n=1}^\infty x_n$ converges absolutely, then there exists a sequence $\{n_k\}$ of positive integers such that the sequence $\{\sum_{n=1}^{n_k} x_n\}_{k=1}^\infty$ converges.

as the continuity and linearity of $T$ would then imply what I want. However, I don't think that statement is true, as it would then imply that every normed space is Banach, which is obviously not true. So I have no idea on how to proceed now. In general I am having trouble to prove the convergence of almost anything, any advice for that would be really helpful.

For the ($\impliedby$) direction, I am trying to use the sequential criterion for continuity to prove that $T$ is continuous, and since $T$ is linear that would prove that $T$ is bounded. Let $a\in X$ and $\{x_n\}$ a sequence in $X$ that converges to $a$. I want to prove that $T(x_n)\to T(a)$. I trying to use the same steps as in the other implication, i.e. I need to show that $\{T(x_n)\}$ is Cauchy and has a subsequence that converges to $T(a)$. Here however, I managed to show the existence of a convergent subsequence, but I don't see how to show that the sequence is Cauchy. To see that it has a subsequence convergent to $T(a)$, notice the following:

As $x_n\to a$, for each $k\in\mathbb{Z}^+$ there exists an $n_k\in\mathbb{Z}^+$ such that

$$ ||x_{n_k}-a||<\dfrac{1}{2^k} $$

And since $\sum_{k=1}^\infty 2^{-k}$ converges, we have that $\sum_{k=1}^\infty||x_{n_k}-a||$ converges. By hypothesis, this implies that $\sum_{k=1}^\infty T(x_{n_k}-a)$ converges, and from here we get that $||T(x_{n_k})-T(a)||=||T(x_{n_k}-a)||\to 0$ as $k\to\infty$, and as such $T(x_{n_k})\to T(a)$.

If now I manage to prove that $\{T(x_n)\}$ is Cauchy, I would get the result. However I have no idea on how to do this.

Thanks in advance for any help you could give me!

Local minima of $f(x) = \begin{cases} 5 x^2 (2 - \sin \tfrac{1}{x}) & \text{ if } x \neq 0 \\ 0 & \text{ if } x = 0 \end{cases}$ dense near $0$

Posted: 31 Jan 2022 08:48 AM PST

Consider $$f(x) = \begin{cases} 5 x^2 (2 - \sin \tfrac{1}{x}) & \text{ if } x \neq 0 \\ 0 & \text{ if } x = 0. \end{cases} $$ For any given $\delta > 0$ it is very clear from the graph of $f$ that there is at least one (in fact infinitely many) point $x_\delta$ in $(-\delta, \delta)$ at which $f'(x_\delta) = 0$. Somehow, I am not getting how to mathematically prove this. Can anyone help me out?

enter image description here

Is this derivation of $\int{\frac{1}{x^2-a^2}}dx$ correct?

Posted: 31 Jan 2022 08:41 AM PST

Let $a>0.$ Using substitution, determine $$\int{\frac{1}{x^2-a^2}}\,\mathbb{d}x.$$

My book's attempt:

$$\int{\frac{1}{x^2-a^2}}\mathbb{d}x\\ [\text{let}\ x=a\sec\theta,\ \therefore dx=a\sec\theta\tan\theta d\theta]\\ =\int{\frac{1}{a^2\sec^2\theta-a^2}}a\sec^2\theta d\theta\\ =\int{\frac{1}{a^2(\sec^2\theta-1)}}a\sec\theta\tan\theta d\theta\\ =\int{\frac{1}{a^2\tan^2\theta}}a\sec\theta\tan\theta d\theta\\ =\frac{1}{a}\int{\frac{\sec\theta}{\tan\theta}}d\theta\\ =\frac{1}{a}\int{\frac{\frac{1}{\cos\theta}}{\frac{\sin\theta}{\cos\theta}}}d\theta\\ =\frac{1}{a}\int{\csc\theta d\theta}\\ =\frac{1}{a}\int{\frac{\csc\theta(\csc\theta+\cot\theta)}{(\csc\theta+\cot\theta)} d\theta}\\ =-\frac{1}{a}\int{-\frac{\csc^2\theta+\csc\theta\cot\theta}{(\csc\theta+\cot\theta)} d\theta}\\ =-\frac{1}{a}\ln|\csc\theta+\cot\theta|+C$$

enter image description here

$$=-\frac{1}{a}\ln\left|\frac{x}{\sqrt{x^2-a^2}}+\frac{a}{\sqrt{x^2-a^2}}\right|+C\\ =-\frac{1}{a}\ln\left|\frac{x+a}{\sqrt{x-a}\sqrt{x+a}}\right|+C\\ =-\frac{1}{a}\ln\left|\frac{\sqrt{x+a}}{\sqrt{x-a}}\right|+C\\ =-\frac{1}{a}{\ln\left|\frac{x+a}{x-a}\right|}^{\frac{1}{2}}+C\\ =-\frac{1}{2}.\frac{1}{a}\ln\left|\frac{x+a}{x-a}\right|+C\\ =\frac{1}{2a}{\ln(\left|\frac{x+a}{x-a}\right|)}^{-1}+C\\ =\frac{1}{2a}\ln\left|\frac{x-a}{x+a}\right|+C.$$

Someone told me that this work contains many errors. The second line clearly has a typo ($\sec^2\theta$ should be replaced with $\sec\theta\tan\theta$ there); what are the other errors?


Related: 1, 2

finding derivatives of variables in multivariable taylor polynomial

Posted: 31 Jan 2022 08:51 AM PST

Given: $$F(x,y) = -6 -4(x-4) +6(y-6) +8(x-4)^2 +9(x-4)(y-6) -4(y-6)^2 + R_2$$ and that $F(4,6)=-6$
find y'(4), y''(4), make sure that the function is applicable for the implicit function theorem.
my attempt: so I've basically made sure that the conditions applied, implicitly derived F and found out y'. It was a lot of hard work and while I got a result my method didn't at all utilize the fact it's taylor -I think there must be an easier way but I just can't put my finger on it. I think it'll utilize the fact that $-4 = F_x(x,y)$ and that $6 = F_y(x,y)$ - and maybe the chain rule? since $$-4 = \frac{\partial F(4,6)}{\partial{x}}=\frac{\partial{y}}{\partial{x}}* \frac{\partial F(4,6)}{\partial{y}} = 6*y'(x) \Rightarrow y'(x) = \frac{-2}3$$ but both my calculation and this calculator https://www.emathhelp.net/en/calculators/calculus-1/implicit-differentiation-calculator/?f=-4%28x-4%29%2B6%28y-6%29%2B8%28x-4%29%5E2+%2B9%28x-4%29%28y-6%29+-4%28y-6%29%5E2%3D0&type=x&px=4&py=6 output $2/3$
To sum up - where is my logic faulty? is there a similar easier way? how do I extend this to y''(4)?

An 8th grade contest-math puzzle

Posted: 31 Jan 2022 08:56 AM PST

In a competitive sort of exam, the following question was aimed at 8th graders and above-

Sophie had written the numbers 1 to 22 in the 22 discs in the figure, but Adelaide, her big annoying sister, erased fourteen.

enter image description here

Find the positions of the numbers erased knowing that

  1. Each number written in the centre of a hexagon represents the sum numbers placed at the vertices of this hexagon
  2. Two discs directly connected by a line never contain consecutive numbers.

On the answer sheet, write the values of the numbers $a, b, c, d$ and $e$.

On top of this, the question may have multiple answers (and the student is expected to report all of them) as well.

I don't have any idea about how to attack this problem. Of course, brute forcing is not a solution since in that case you have to check through $\sim 22^{14}\approx 6.2\times 10^{18}$ cases which is an impossibility even for a computer programme.

After doing some Google search recently, I found out something similar called Hexagonal Tortoise Problem and a paper about it. But, these couldn't take me anywhere.

One random observation is that if we indeed need to brute force the solution with some educated guesses, then maybe the disc connecting $4,7,12$ is the one to start with (since that's the one which is most restricted). But, even in that case, there are too many choices to deal with.

All ideas are welcome.

Prove |Re z| less than or equal to |z| and |Im z| less than or |z|

Posted: 31 Jan 2022 09:07 AM PST

|Re z| less than or equal to |z| ; z = x + yi

|Re z|= |x| --> sqrt(x^2) |z| = sqrt(x^2 + y^2)

sqrt(x^2) less than or equal to sqrt(x^2 + y^2) (therefore y^2 greater than or equal to 0)

then the answer is sqrt(x^2) less than or equal to sqrt(x^2 + y^2) is this correct?

and do the same thing for Im z?

is this correct? Thanks!

Good approximation to $\ln(x)$ for $x$ in $1 < x < e$

Posted: 31 Jan 2022 09:05 AM PST

I'm looking for a simple function that gives a good approximation to $\ln(x) $ within $1 < x < e$.

Do you have anything in mind? I'm not looking for an infinite function, but a short and finite version of it might be good, if it's also a simple solution as well.

RYB and RGB Color Space Conversion

Posted: 31 Jan 2022 09:06 AM PST

I am working on a project where I need to convert colors defined in RGB (Red, Green, Blue) color space to RYB (Red Yellow Blue).

I managed to solve converting a color from RYB to RGB space based on the article - Paint Inspired Color Mixing and Compositing for Visualization.

I convert a color from RYB to RGB with this "algorithm":

So the values of r (red), y (yellow), and b (blue) are known, also these arrays/sets are constants:

white: [1, 1, 1]  red: [1, 0, 0]  yellow: [1, 1, 0]  blue: [0.163, 0.373, 0.6]  violet: [0.5, 0, 0.5]  green: [0, 0.66, 0.2]  orange: [1, 0.5, 0]  black: [0.2, 0.094, 0.0]  

here is how I calculate the value of red for the RGB space based on the parameters above:

i = 1;  rgb_red = white[i] * (1 - r) * (1 - b) * (1 - y) +   red[i] * r * (1 - b) * (1 - y) +   blue[i] * (1 - r) * b * (1 - y) +   violet[i] * r * b * (1 - y) +   yellow[i] * (1 - r) * (1 - b) * y +   orange[i] * r * (1 - b) * y +   green[i] * (1 - r) * b * y +   black[i] * r * b * y);  

for rgb_green exactly the same thing but for i=2, and i=3 for rgb_blue.

My problem is that now I want to convert from RGB to RYB back. In other words, knowing the values of rgb_red, rgb_green and rgb_blue I want to calculate the values of r, y, and b. So I need a kind of inverse function for this, but I don't know how to get it.

Any help is appreciated.

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Creat a list with repeated terms by adding a multiplier index in Pandas Dataframe

Posted: 31 Jan 2022 08:00 AM PST

Given a dataframe like this:

row1 = ['AAA', 'BBB', 'BBB', 'CCC', 'AAA', 'AAA']  row2 = ['CCC', 'CCC', 'BBB', 'AAA', 'AAA', 'AAA']  col = {'Lists': [row1, row2]}  df = pd.DataFrame(col)  

which leads to:

Index List
0 ['AAA', 'BBB', 'BBB', 'CCC', 'AAA', 'AAA']
1 ['CCC', 'CCC', 'BBB', 'AAA', 'AAA', 'AAA']

I would like to generate the following dataframe:

List
0 ['AAA', 'BBB x 2', 'CCC', 'AAA x 2']
1 ['CCC x 2', 'BBB', 'AAA x 3']

where the final column List contain a multiplier index that indicates how many times the term appears consecutively in the list.

Could you suggest a pandas instruction that solves this task?

Integrating DynamoDB Table with Lambda to fetch data for Lex Chatbot - No response

Posted: 31 Jan 2022 07:59 AM PST

I am building a AWS Lex bot integrated with Lambda which can fetch data from table in DynamoDB. I have granted Full Access to DynamoDB for Lambda by adding new role. But every time it is showing- "Invalid Lambda responses". Below I am sharing the Lambda code in python.

import json  import boto3  client = boto3.client('dynamodb')  result = {}  intent=""  Accountnumber=""    def lambda_handler(event, context):      intent=(event['currentIntent']['name'])      #print('the intent is : ',intent)      Accountnumber=(event['currentIntent']['slots']['AccountNumber'])      #print('accountnumber is : ',Accountnumber)      if intent=='AccountBalanceEnquiry':          balanceenquiry(Accountnumber)          return result      # Method to Fetch the account balance from database by giving the Accountnumber as paramater  def balanceenquiry(Accountnumber):          response = client.get_item(              TableName='customerdetails',              Key={                  'accountnumber': {                      'S': Accountnumber,                  }              }              )          #print('responce is: ',response)  # Declaring a key to verify the response          key='Item'  # Storing the boolean value wether key present or not          value = key in response.keys()          if value:              accountnumber=response['Item']['accountnumber']['S']              name=response['Item']['name']['S']              balance=response['Item']['balance']['N']              message='Hello ', name, ' You have $',balance, ' in your account'              msg=''.join(message)              #print(msg)              global result  # Result to lex bot              result = {                  "dialogAction": {                  "type": "Close",                  "fulfillmentState": "Fulfilled",                  "message": {                    "contentType": "PlainText",                    "content": msg                  },                }              }                     return result          else:              #print("didnt find the account")              message="Sorry I can't find your details in our records please contact our support   center on 8083829227"              result = {                  "dialogAction": {                  "type": "Close",                  "fulfillmentState": "Fulfilled",                  "message": {                    "contentType": "PlainText",                    "content": message                  },                }              }              return result  

How to request refresh token from Etsy using OAuth-2.0 from C#

Posted: 31 Jan 2022 07:59 AM PST

Having failed miserably using C# code to get an Etsy OAuth 2 token, I resorted to using Postman for the initial request figuring that it would then be a simple matter of requesting a refresh token as and when needed. So, from Postman, all good, I can sign in and grant access, which then causes Etsy to respond with a shortlived access token (and a refresh token to use to request another access token without having to go through the whole grant process again).

However, I cannot figure out how to get another access token using this refresh token as Etsy keeps on responding with grant_type is required.

OK, the initial response from Postman following the success grant access is:

{      "access_token": "<initial-access-token-from_Etsy>",      "token_type": "Bearer",      "expires_in": 3600,        "refresh_token": "<my-refresh-token>"  }  

And following their docs to request a refresh OAuth token, it implies that all I need to do is to make a POST request to https://openapi.etsy.com/v3/public/oauth/token, adding the following parameters to the JSON body with content type: application/x-www-form-urlencoded:

{     "grant_type": "refresh_token",     "client_id": "<my-client-API-string>",     "refresh_token": "<my-refresh-token>"  }  

Thus, setting all this up in Postman and looking at the generated code for the request gives:

var client = new RestClient("https://openapi.etsy.com/v3/public/oauth/token");  client.Timeout = -1;  var request = new RestRequest(Method.POST);  request.AddHeader("Content-Type", "application/x-www-form-urlencoded");  request.AddHeader("x-api-key", "<my-client-API-string>");*  request.AddParameter("grant_type", "refresh_token");  request.AddParameter("client_id", "<my-client-API-string>");  request.AddParameter("refresh_token", "<my-refresh-token>");  IRestResponse response = client.Execute(request);  Console.WriteLine(response.Content);  

*NOTE - I had to add in the header the parameter x-api-key otherwise it would fail with "error": "Missing x-api-key header or client_id"

Alas, the response from Etsy is always

{      "error": "invalid_request",      "error_description": "grant_type is required"  }  

This post guided me in making the initial request.

Why is it moaning about grant_type when it's in the body as requested!?!?!?

org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 4 times, most recent failure: Lost task UnknownReason

Posted: 31 Jan 2022 07:59 AM PST

With this code I'd got data from oracle, postgres or sql server many times, how ever this time receiving error message in the subject

Comlete log message is below:

py4j.protocol.Py4JJavaError: An error occurred while calling o33.showString. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 4 times, most recent failure: Lost task 0.3 in stage 0.0 (TID 3) (10.42.8.125 executor 1): UnknownReason

Will be appreciated with any help.

Regards,

Mert.

SFTP How to List Large # of Files

Posted: 31 Jan 2022 07:59 AM PST

I am currently working on SFTP load to GCS bucket. However, I am able to do it for a limited number of files in any given SFTP directory. However, if the directory has too many files (or files within another folder), I am not able to do a simple ls & get the list of files to download from SFTP. Following is the working code to get the list of files in any given directory recursively from sftp:

import sys  from stat import S_ISDIR, S_ISREG  import paramiko      sftp_url = '<URL>'  sftp_user = '<USER>'  sftp_pwd = '<PWD>'      def get_sftp_obj(sftp_cred_dict):       server = sftp_cred_dict['server']       username = sftp_cred_dict['username']       password = sftp_cred_dict['password']       timeout_min = sftp_cred_dict['timeout_min']       paramiko.sftp_file.SFTPFile.MAX_REQUEST_SIZE = pow(2, 22) #4MB Chunk Default       transport = paramiko.Transport((server, 22))       transport.connect(username=username, password=password)       sftp = paramiko.SFTPClient.from_transport(transport)       sftp.get_channel().settimeout(timeout_min*60)       return sftp       def sftp_get_recursive_files(path, skip_dir_list, sftp, sftp_files=[]):       item_list = sftp.listdir_attr(path)       for item in item_list:           mode = item.st_mode           item = item.filename           if S_ISDIR(mode):               path_build = path + '/' + item               if not(item in skip_dir_list):                   sftp_get_recursive_files(path_build, skip_dir_list, sftp, sftp_files)               else:                   print('skip directory files: ' + path_build)           elif S_ISREG(mode):               sftp_file_path = path + '/' + item               sftp_files.append(sftp_file_path)       return sftp_files       def main():       sftp_cred_dict = {           "server": sftp_url,           "username": sftp_user,           "password": sftp_pwd,           "timeout_min": 60       }       skip_dir_list = ["archive"]       arguments = sys.argv       ls_dir = arguments[1]       print(ls_dir)       sftp = get_sftp_obj(sftp_cred_dict)       files = sftp_get_recursive_files(ls_dir, skip_dir_list, sftp, [])       print(len(files))      if __name__ == "__main__":       main()  

I get the following exception after some time of execution:

(venv-sftp) user@poc-sftp:~/experiments/sftp-v1$ python ls-sftp.py /BU/SYSTEM/outbound/SYSTEM_Txn_Payment      Traceback (most recent call last):    File "/home/user/experiments/sftp-v1/venv-sftp/lib/python3.7/site-packages/paramiko/sftp_client.py", line 852, in _read_response      t, data = self._read_packet()    File "/home/user/experiments/sftp-v1/venv-sftp/lib/python3.7/site-packages/paramiko/sftp.py", line 201, in _read_packet      x = self._read_all(4)    File "/home/user/experiments/sftp-v1/venv-sftp/lib/python3.7/site-packages/paramiko/sftp.py", line 188, in _read_all      raise EOFError()  EOFError      During handling of the above exception, another exception occurred:    Traceback (most recent call last):    File "ls-sftp.py", line 62, in <module>      main()    File "ls-sftp.py", line 57, in main      files = sftp_get_recursive_files(ls_dir, skip_dir_list, sftp, [])    File "ls-sftp.py", line 27, in sftp_get_recursive_files      item_list = sftp.listdir_attr(path)    File "/home/user/experiments/sftp-v1/venv-sftp/lib/python3.7/site-packages/paramiko/sftp_client.py", line 246, in listdir_attr      t, msg = self._request(CMD_READDIR, handle)    File "/home/user/experiments/sftp-v1/venv-sftp/lib/python3.7/site-packages/paramiko/sftp_client.py", line 822, in _request      return self._read_response(num)    File "/home/user/experiments/sftp-v1/venv-sftp/lib/python3.7/site-packages/paramiko/sftp_client.py", line 854, in _read_response      raise SSHException("Server connection dropped: {}".format(e))  paramiko.ssh_exception.SSHException: Server connection dropped:  

Gstreamer how to get element information from STATE_CHANGED message from the bus

Posted: 31 Jan 2022 07:59 AM PST

I am working with Gstreamer and its Python bindings. Consider the following bus_call function:

import sys  from gi.repository import Gst      def bus_call(bus, message, loop):      t = message.type      if t == Gst.MessageType.EOS:          print("Bus call: End-of-stream\n")          # loop.quit()      elif t == Gst.MessageType.WARNING:          err, debug = message.parse_warning()          sys.stderr.write("Bus call: Warning: %s: %s\n" % (err, debug))      elif t == Gst.MessageType.ERROR:          err, debug = message.parse_error()          sys.stderr.write("Bus call: Error: %s: %s\n" % (err, debug))          # loop.quit()      elif t == Gst.MessageType.BUFFERING:          print("Bus call: Buffering\n")      elif t == Gst.MessageType.STATE_CHANGED:          old_state, new_state, pending_state = message.parse_state_changed()          print((              f"Bus call: Pipeline state changed from {old_state.value_nick} to {new_state.value_nick} "              f"(pending {pending_state.value_nick})"          ))      else:          print(f"Bus call: {message}\n")      return True  

When the message type is Gst.MessageType.STATE_CHANGED, how can I retrieve the element that has changed the state?

app update in google developer console for payment subcribtion

Posted: 31 Jan 2022 07:59 AM PST

I had completed my first app using android studio and firebase and I am now trying to upload to google play store through google play console. I have two sets of users in my app , 1. Buyers and 2. Sellers. Currently my app is free for both buyers and sellers, so in data safety section in developer account, in Financial info section I didn't select any thing like credit card or debit card , but in next update I am planning to make seller subscription charges or 1 year or 2 year like that , so I will be collecting their credit or debit card information... I like to know whether financial information can be changed in every update or I need to plan prior and select payment information in first upload itself.

spark trying to convert .Mf4 to save as .txt files, getting issue

Posted: 31 Jan 2022 07:59 AM PST

I have a spark code which reads .mf4 files and write as a .txt file. Also running this code in databricks.

Could you please suggest? Even after increasing the executor memory in data bricks in cluster, still having the issue.

pip install asammdf    from pyspark import SparkContext  from pyspark.sql import SparkSession  from asammdf import MDF  import io  import os  import sys  from pyspark.sql.functions import col        os.environ['PYSPARK_PYTHON'] = sys.executable  os.environ['PYSPARK_DRIVER_PYTHON'] = sys.executable      spark = SparkSession \      .builder \      .appName("mdf4") \      .getOrCreate()    sc = spark.sparkContext    def decodeBinary(val):      file_stream = io.BytesIO(val)      mdf = MDF(file_stream)      location = mdf.whereis(test_1)      return location  print("1")  input_hdfs_path_to_mdf4 = "dbfs:/FileStore/inputmfd4/"  channel_name = "test_1"  local_or_hdfs_output_path = "dbfs:/FileStore/outputmfd4/opp4.txt"  print("2")  raw_binary = sc.binaryFiles(input_hdfs_path_to_mdf4)  print("3")  decoded_binary = raw_binary.map(lambda r: r[1]).map(decodeBinary)  print("4")  decoded_binary.saveAsTextFile(local_or_hdfs_output_path)  print("5")  print(decoded_binary)  

I am running this code in databricks , I have 5Gb mf4 file as a input. When I try to run small file there is no issue. But when I use this 5GB mf4 file getting

Caused by org.apache.spark.api.python.PythonException: asammdf.blocks.utils.MdfException: <_io.BytesIO object at 0x7efed84482c0> is not a valid ASAM MDF file: magic header is b\xff\xd8\xff\xe1H\xe6Ex from command-2705692180399242 line 24 Full traceback below  Traceback (most recent call last)  

unit testing in springboot - best approach

Posted: 31 Jan 2022 07:59 AM PST

I'm trying to figure out what is the best approch to unittesting in SpringBoot app. Before last friday i thought that best approach is to test:

  • controllers with mockmvc and mocked services
  • services with mocked repositories
  • repositories with mocked db
  • using SpringBootTest mainly for integration tests.

But then i watched this -Ian Cooper - TDD, Where Did It All Go Wrong and I've realized that my testswas implementation tests, and I should only mock db, filesystem, other systems, not my application.

And I'am wondering how should I be doing this? Because when I will be creating all objects myself it will still be "testing implementation", so I can use SpringBootTest with MockBean but this would be extremly slow.

Can someone clever than me could share his experience or thougths on this?

node-polyfill-webpack-plugin not recognizing in webpack.config.js

Posted: 31 Jan 2022 07:59 AM PST

I am trying to use knex for sqlite local storage in an electron application and have gotten the "Breaking Change" message due to knex uses some of the polyfll components that seize to exist on webpack v5. I heard that I can use node-polyfill-webpack-plugin to put the polyfills back in. For this project, I created a "webpack.config.js" at root and put the following contents inside:

const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")    module.exports = {      // Other rules...      plugins: [          new NodePolyfillPlugin()      ]  }  

Here is my package.json:

{    "name": "react_test",    "homepage": "./",    "version": "0.1.0",    "private": true,    "main": "public/electron.js",    "dependencies": {      "@testing-library/jest-dom": "^5.16.1",      "@testing-library/react": "^12.1.2",      "@testing-library/user-event": "^13.5.0",      "assert": "^2.0.0",      "axios": "^0.21.1",      "babel-loader": "^8.2.2",      "buffer": "^6.0.3",      "constants-browserify": "^1.0.0",      "copy-webpack-plugin": "^7.0.0",      "crypto-browserify": "^3.12.0",      "css-loader": "^5.0.1",      "concurrently": "^6.0.0",      "cross-env": "^7.0.3",      "file-loader": "^6.2.0",      "html-loader": "^1.3.2",      "html-webpack-plugin": "^5.0.0",      "https-browserify": "^1.0.0",      "electron": "^12.0.0",      "electron-is-dev": "^2.0.0",      "knex": "^1.0.1",      "node-polyfill-webpack-plugin": "^1.1.4",      "os-browserify": "^0.3.0",      "path-browserify": "^1.0.1",      "prettier": "^2.2.1",      "process": "^0.11.10",      "react": "^17.0.2",      "react-dom": "^17.0.2",      "react-router": "^5.2.1",      "react-router-dom": "^5.2.1",      "react-scripts": "5.0.0",      "regenerator-runtime": "^0.13.7",      "stream-browserify": "^3.0.0",      "stream-http": "^3.2.0",      "style-loader": "^2.0.0",      "svg-url-loader": "^7.1.1",      "webpack": "^5.21.1",      "webpack-cli": "^3.3.12",      "wait-on": "^5.2.1",      "web-vitals": "^2.1.3"    },    "scripts": {      "start": "react-scripts start",      "build": "react-scripts build",      "test": "react-scripts test",      "eject": "react-scripts eject",      "electron": "wait-on tcp:3000 && electron .",      "electron:build": "npm build && electron-builder -c.extraMetadata.main=build/main.js",      "package-mac": "electron-packager . --overwrite --platform=darwin --arch=x64 --icon=assets/icons/mac/icon.icns --prune=true --out=release-builds",      "package-win": "electron-packager . electron-tutorial-app --overwrite --asar=true --platform=win32 --arch=ia32 --icon=assets/icons/win/icon.ico --prune=true --out=release-builds --version-string.CompanyName=CE --version-string.FileDescription=CE --version-string.ProductName=\"Electron Tutorial App\"",      "package-all": "electron-packager . electron-app --all --asar",      "package-linux": "electron-packager . electron-tutorial-app --overwrite --asar=true --platform=linux --arch=x64 --icon=assets/icons/png/1024x1024.png --prune=true --out=release-builds"    },    "eslintConfig": {      "extends": [        "react-app",        "react-app/jest"      ]    },    "browserslist": {      "production": [        ">0.2%",        "not dead",        "not op_mini all"      ],      "development": [        "last 1 chrome version",        "last 1 firefox version",        "last 1 safari version"      ]    }  }  

However, when I run "npm start", I am still getting all of the webpack breaking change messages.

Any help would be much appreciated. I have never seen this problem until I am trying to use any type of local storage (such as sqlite or NEDB) and have done an extensive search on Stack Overflow and tried several of those suggested methods (in fact the node-polyfill-webpack-plugin was from reading this site) but I still cannot get it to work.

Xamarin: Modal from not popping

Posted: 31 Jan 2022 07:59 AM PST

since a couple of weeks I have the problem that a modal form which provides a spinner and a label is not popping anymore. It was running in older versions but not with all NuGet Packages updated. Any idea what this can be? Funnywise it is working on some forms and not on others.

protected async override void OnAppearing()      {                   try          {              await Navigation.PushModalAsync(new BusyPopUpPage("loading products"));                            //ActivityTracker.StartSpinner(true);              base.OnAppearing();              IsFiltered = false;              LblAttributesVisible = false;              AllProducts = await App.AllProductsController.GetAllProducts();                grouped = new ObservableCollection<AssortmentGroups>();                GroupProducts();              AllProductsListView.IsGroupingEnabled = true;              AllProductsListView.ItemsSource = grouped;              await Navigation.PopModalAsync();          }          catch (Exception ex)          {              await CreateNewBug.CreateANewBug(ex.Message,"Error in Module " + ex.Source,"\nMessage---\n{ 0}" + ex.Message + "\nInnerException---\n{ 0}" + ex.InnerException + "\nStackTrace---\n{ 0}" + ex.StackTrace + "\nTargetSite---\n{ 0}" + ex.TargetSite);              ToastOptions toastOptions = Message.ShowMessage("An error was raised and a new bug created in our system.", "error");              await this.DisplayToastAsync(toastOptions);          }                }  

array of string to string

Posted: 31 Jan 2022 07:59 AM PST

Can I use JSONPath expressions to get a string out of an array of string?

Example, here is an array of strings:

{      "objects": [          "a"          "b"          "c"      ]  }  

and the expresion

$.objects[:]  

will result into

[      "a"      "b"      "c"  ]  

however I want to have something like

{      "a b c"  }  

or better

{      "a, b, c"  }  

is this possible?

How to achieve auto scaling with AWS sage maker with single docker image and multiple model artifact?

Posted: 31 Jan 2022 07:58 AM PST

I am exploring AWS sage maker for deploying the machine learning models with single container/docker image and wants to achieve scalability too.

For your info, we have written the training and prediction code in such a way that so, same code is being used for different customers. Only the ENV variables,VERSION_NUMBER are different according to customer.

VERSION_NUMBER : Refers to S3 folder name as current timestamp which contains latest model artifact.

for e.g.

Customer name : XYZ  docker image(training and prediction) : **intent-mapping:latest**  s3 model atrifact path : s3_bucket/XYZ/VERSION_NUMBER/XYZ.tar.gz  ENV variable : CUSTOMER_SUFFIX,IS_INCREMENTAL    Customer name : PQR  docker image(training and prediction) : **intent-mapping:latest**  s3 model atrifact path : s3_bucket/PQR/VERSION_NUMBER/PQR.tar.gz  ENV variable : CUSTOMER_SUFFIX,IS_INCREMENTAL  

If you read it carefully, you will see same docker image is being refereed everywhere

So,my doubts are as follow.

  1. Which approach should i follow to deploy the model with such a scenario?
  2. Let's say, if we use multiple model/multi container option of sage maker then how auto scaling will be managed for each customer independently?

Please let me know your inputs on the same.

Replace strings inside of a file with the same name file for multiple files

Posted: 31 Jan 2022 07:59 AM PST

Im working with coco datasets, so I have jpg files and json files with same name for each image(for example: image1.jpg and image1.json). I needed rename the files, but inside the json files has an "adress" path with the name of the jpg image, this way ("imagePath": "image1.jpg"). But I renamed all my files and the "imagePath" is the former name of jpg file. For example, new names(1.jpg and 1.json), but the ("imagePath": "image1.jpg") and I need ("imagePath": "1.jpg"), but this for around 1500 images and the json files. I tried some codes, but they are unseful and didn't make sense. There is a way to do this with UNIX code?

thank you.

best approche to asynchronous programming

Posted: 31 Jan 2022 07:59 AM PST

I'm building an app with NodeJs that get data from a websocket server and then store or update these data on an array of objects, after that the data on the array is analysed (heavy calculations) none stop.

I need help to choose the best way to execute these two tasks independently from each other.

I tried parallel tasking but it's didn't work, the calculation part takes 250 ms and the websocket takes only 1ms, the app waits untill calculation is done and miss all data from websocket server..

What's the best approach to achieve this?

PS: i'm a self taught please don't down vote :)

How do you POST html form data with javascript

Posted: 31 Jan 2022 08:00 AM PST

Im trying to POST data from a html form using javascript however on submission I believe no data is actually being sent because my alert is showing no data.

when i added an alert box

var jsonStr = JSON.stringify(FD);        alert(jsonStr);  

the output came up as "{}"

here is my full code below if anyone can spot my errora

<form class="emailentry" " method="post" name="myForm" id="myForm">  <label  for ="name">Name: </label><br>  <input type ="text"id="name" name="name: " ><br>  <label for ="emailad">Email: </label><br>  <input type ="email"id="emailad" name="emailad" ><br>  <input type= "submit" id="btn" name="submit" class="submitstyle">  </form>  <script>      window.addEventListener( "load", function () {    function sendData() {      const XHR = new XMLHttpRequest();        // Bind the FormData object and the form element      const FD = new FormData( form );        // Define what happens on successful data submission      XHR.addEventListener( "load", function(event) {          var jsonStr = JSON.stringify(FD);        alert(jsonStr); // should present me the data i entered but it isnt        alert("hi");      } );        // Define what happens in case of error      XHR.addEventListener( "error", function( event ) {        alert( 'Oops! Something went wrong.' );      } );        // Set up our request      XHR.open( "POST", "ExampleUrl.ForStackOveerflow/post" );        // The data sent is what the user provided in the form      XHR.send( FD );            }      // Access the form element...    const form = document.getElementById( "myForm" );      // ...and take over its submit event.    form.addEventListener( "submit", function ( event ) {      event.preventDefault();        sendData();    } );  } );          </script>  

how to return the pointer of a specific value in a tree in C?

Posted: 31 Jan 2022 07:59 AM PST

using this struct :

typedef struct node {    int content;    struct node* right;    struct node* left;  }Node;  

I'm trying to write a code that return the pointer of the the node if node ->content== x I have tried this so far but I don't think its right :

 Node* find (Node* p,int x)  {    Node* L,*R;      if(p==NULL)      retutn NULL;    L=find(p->left,x);      if(L->content == x)      return L;    R=find(p->right,x);      if(R->content == x)    return R;  }  

can u help me correct my code?

Common Lisp Package Definition with Dependencies for Exploloration at the REPL?

Posted: 31 Jan 2022 07:59 AM PST

This is another take at the question of packages and systems especially for usage locally in personal projects (maybe similiar to HOWTO definition and usage of Common Lisp packages (libraries)? from 2014). What are recommendations for how to approach this and can links be provided for sources that describe the recommended approach in 2022? CL's long half-life means lots of old blogs and books are still useful, but unfortunately not all of them, and it is hard for the novice to know which are the still viable guides.

Here is the start of a file that I might write for a simple personal exploration project. My basic working mode would be to start slime, load and compile this in emacs, and then change to the slime repl and use in-package to move into my package and start playing with my functions.

(ql:quickload "alexandria")  (ql:quickload "trivia")    (defpackage computing-with-cognitive-states    (:use cl)    (:nicknames :cwcs)    (:local-nicknames (:alex :alexandria)))    (in-package :cwcs)    (defun sum-denom (dimension dist) ... ; and more defun's  

The leading ql:quickload's strike me as ugly, but without them I can't load and compile. Is it recommended that I do this manually in slime repl first? Or is this considered an acceptable practice for small use cases like this? Or is there another recommended way?

If I am thinking of using my package elsewhere someday is it recommended that I make it a system, perhaps with quickproject? Or is it the more traditional approach to just load a fasl file from one directory on my system when another session (or another package definition) needs it?

In summary, the questions are about the writing of code that is for personal use, might be a small file, or might be a few files that depend on each other and a few external systems. What are some of the reasonable approaches and resources that describe those approaches? And which are the ones that would be easiest to scale up if the project grew into something that one wanted to share?

GravityForms Dynamic Confirmation Redirects

Posted: 31 Jan 2022 08:00 AM PST

I have set up a gravity form with a single line text field. I am using it to check for zip codes and cities. If someone types in the correct zip code it will redirect to a specific page. Also if someone types in a zip code or city and there is no matching value it will also redirect to a certain page. I have tried this code. But I can not seem to get it to work correctly. It works if I have one number but if I add multiple numbers separated by a comma it does not work. Please help if possible.

    <?php  function de_gforms_confirmation_dynamic_redirect( $confirmation, $form, $entry, $ajax ) {      if ( $form['id'] == '38' ) {          if ( $entry['1'] == '89103,80205,91030' ) {          $confirmation = array( 'redirect' => 'https://google.com' );          } else if ( $entry['1'] == '90210,89554,90454' ) {          $confirmation = array( 'redirect' => 'https://yahoo.com' );          } else if ( $entry['1'] == '56678,89004,78896' ) {          $confirmation = array( 'redirect' => 'https://test.com' );          }      }        return $confirmation;  }    add_filter( 'gform_confirmation', 'de_gforms_confirmation_dynamic_redirect', 10, 4 );  ?>  

Firebird reading database issue on iis asp.net core 5

Posted: 31 Jan 2022 07:58 AM PST

I want to develop a demo project in ASP.NET Core MVC with embedded Firebird v2.5. I read Firebird connection string information from a text file. Because I will change database in project presentation thus I must read from a text file. Or what is the your idea?

In this project I create a DbContext file and I fill in the database information using this class:

public class DbContext  {      string startupdirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)+"\\settings.txt";      string dblocation = string.Empty;      string userName = string.Empty;      string pass = string.Empty;      int port = 0;      string dataSource = string.Empty;           public DbContext()      {          if (File.Exists(startupdirectory))          {              string[] allData = File.ReadAllLines(startupdirectory);              dblocation = allData[0].ToString();              userName = allData[1].ToString();              pass = allData[2].ToString();              port = Convert.ToInt32(allData[3].ToString());              dataSource = allData[4].ToString();          }      }        public string GetConnectionString()      {          FbConnectionStringBuilder csb = new();          csb.Database = dblocation;          csb.DataSource = dataSource;          csb.UserID = userName;          csb.Password = pass;          csb.ServerType = FbServerType.Default;          csb.Port = port;          //i added below code for embedded db          csb.Dialect = 3;          csb.Role = "";          csb.ConnectionLifeTime = 15;          csb.Pooling = true;          csb.MinPoolSize = 0;          csb.MaxPoolSize = 50;          csb.PacketSize = 8192;          return csb.ToString();      }        public FbConnection GetConnection()      {          string connectionString = GetConnectionString();          FbConnection connection = new();          connection.ConnectionString = connectionString;          connection.Open();          return connection;      }        public void KillConnection(FbConnection connection)      {          connection.Close();          connection.Dispose();      }  }  

When I work locally, everything is fine. I can do all CRUD operations.

But when I upload my project, I see this screen:

An unhandled exception occurred while processing the request.

IscException: I/O error during "CreateFile (open)" operation for file "C:\Firma\BlinePalmeWEB\Mandanten\11PalmeIT\GDI21.FDB"

Error while trying to open file

FirebirdSql.Data.Client.Managed.GdsConnection.HandleResponseException(IResponse response)

FbException: I/O error during "CreateFile (open)" operation for file "C:\Firma\BlinePalmeWEB\Mandanten\11PalmeIT\GDI21.FDB"

Error while trying to open file
FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect()

Stack Query Cookies Headers Routing

IscException: I/O error during "CreateFile (open)" operation for file "C:\Firma\BlinePalmeWEB\Mandanten\11PalmeIT\GDI21.FDB" Error while trying to open file FirebirdSql.Data.Client.Managed.GdsConnection.HandleResponseException(IResponse response) FirebirdSql.Data.Client.Managed.Version10.GdsDatabase.ReadResponse() FirebirdSql.Data.Client.Managed.Version10.GdsDatabase.Attach(DatabaseParameterBufferBase dpb, string database, byte[] cryptKey) FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect()

Show raw exception details  FbException: I/O error during "CreateFile (open)" operation for file "C:\\Firma\\BlinePalmeWEB\\Mandanten\\11PalmeIT\\GDI21.FDB" Error while trying to open file  FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect()  FirebirdSql.Data.FirebirdClient.FbConnection.Open()  GDIWebApplication.Controllers.DbContext.GetConnection() in DbContext.cs  GDIWebApplication.Models.Deneme.ProductRepository.GetArtikelList() in ProductRepository.cs  GDIWebApplication.Controllers.ProductController.Index(string search) in ProductController.cs  lambda_method1(Closure , object , object[] )  Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)  Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()  Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)  Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()  Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)  Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)  Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()  Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)  Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)  Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)  Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()  Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)  Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)  Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)  Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)    Show raw exception details  FirebirdSql.Data.FirebirdClient.FbException (0x80004005): I/O error during "CreateFile (open)" operation for file "C:\\Firma\\BlinePalmeWEB\\Mandanten\\11PalmeIT\\GDI21.FDB"  Error while trying to open file   ---> FirebirdSql.Data.Common.IscException: I/O error during "CreateFile (open)" operation for file "C:\\Firma\\BlinePalmeWEB\\Mandanten\\11PalmeIT\\GDI21.FDB"  Error while trying to open file     at FirebirdSql.Data.Client.Managed.GdsConnection.HandleResponseException(IResponse response)     at FirebirdSql.Data.Client.Managed.Version10.GdsDatabase.ReadResponse()     at FirebirdSql.Data.Client.Managed.Version10.GdsDatabase.Attach(DatabaseParameterBufferBase dpb, String database, Byte[] cryptKey)     at FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect()     at FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect()     at FirebirdSql.Data.FirebirdClient.FbConnection.Open()     at GDIWebApplication.Controllers.DbContext.GetConnection() in C:\Users\MD\source\repos\GDIWebApplication\Models\Context\DbContext.cs:line 60     at GDIWebApplication.Models.Deneme.ProductRepository.GetArtikelList() in C:\Users\MD\source\repos\GDIWebApplication\Models\Repositories\ProductRepository.cs:line 20     at GDIWebApplication.Controllers.ProductController.Index(String search) in C:\Users\MD\source\repos\GDIWebApplication\Controllers\ProductController.cs:line 16     at lambda_method1(Closure , Object , Object[] )     at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()  --- End of stack trace from previous location ---     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()  --- End of stack trace from previous location ---     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()  --- End of stack trace from previous location ---     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)     at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)     at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)     at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)  

I added all privileges is IIS but I can't make this work - how can I solve this?

Wrong number of item passed 13, placement implies 1 while pivot using pandas

Posted: 31 Jan 2022 07:59 AM PST

I am getting the above error if I add 'column' in the pivot table function of pandas. Without 'Column' it works fine.

df1 = {'Material Code':['A','B','C','D','E','F','G'], 'Material Desc':['ABC','XYZ','QWE','ERT','MNH','LKJ','HGF'], 'Vendor':['Vendor_1','Vendor_2','Vendor_3','Vendor_4','Vendor_5','Vendor_6','Vendor_7'],'Currency':['INR','INR','INR','INR','USD','USD','USD'],'Months':['JAN','FEB','MAR','JAN','FEB','JAN','APR'], 'GRN Quantity':[100, 200, 500, 400, 100, 100, 500], 'Purchase Price':[10, 15, 20, 45, 45, 12, 15]}  index_data = ['Material Code', 'Material Desc', 'Vendor', 'Currency']  column_data = 'Months'  pf = pd.pivot_table(data=df1,index=index_data, columns=column_data,values=values_data,aggfunc={"GRN Quantity":np.sum, "Purchase Price":np.sum}, fill_value=0).reset_index()  

It would be great help, I am struck mid of a project. Thanks You

How This React Hook i.e useEffect is re-rendering even if the second argument being passed is an empty array

Posted: 31 Jan 2022 07:59 AM PST

  function WindowSizeList() {    const [windowWidth, setWindowWidth] = useState(window.innerWidth)      const updateWindowWidth = () => {      setWindowWidth(window.innerWidth)    }      useEffect(() => {      window.addEventListener('resize', updateWindowWidth)    }, [])      return (      <>        <div>Window Width: {windowWidth}</div>      </>    )  }  

This component renders window width when mounted for first time for which useEffect() runs, Ok... then when the browser window is resized the window.addEventListener('resize', updateWindowWidth) runs inside the useEffect()

  useEffect(() => {      window.addEventListener('resize', updateWindowWidth)    }, [])  

and then it triggers

  const updateWindowWidth = () => {      setWindowWidth(window.innerWidth)    }  

for which the component re-renders with the state change of windowWidth and also renders that value in the component, Ok...But when I again resize the browser window, how come the process is repeated i.e useEffect is re-running and then updating the value in DOM even thought it should run once as I have used empty second argument [] in

  useEffect(() => {      window.addEventListener('resize', updateWindowWidth)    }, [])  

how to add and remove specific attribute values

Posted: 31 Jan 2022 08:00 AM PST

In angular it is possible to add and remove class attribute values from an element by specifying a boolean that is bound to a specific variable in the controller:

@HostBinding('class.value-1') value1 = true;  

Is it possible to do the same for other attributes? Similar to below (which does not work)

 @HostBinding('attr.data-custom.value-1') value1 = true;  

nested for loop issue for subfolders and files makefile

Posted: 31 Jan 2022 07:59 AM PST

I have a logical issue, trying to do a nested for loop for a fpöder which holds two subfolders with code files in it.

    for folder in $(twofolders); do \          for file in $$folder; do \              zip -j $$file"_lambda.zip" $(PYTHONPATH)/$$file/*.py; \              aws s3 cp ./$$file"_lambda.zip" s3://$(S3_BUCKET)/$(SOURCE_CODE_VERSION)/lambda/; \          done      done  

But I receive the following error

/bin/bash: -c: line 5: syntax error: unexpected end of file  make: *** [Makefile:62: build] Error 1  

Anyone knows what Iam doing wrong?

How to make Wordpress plugin

Posted: 31 Jan 2022 07:59 AM PST

I want to make my first Wordpress plugin. I made perfect work js, css, html and php widget. Now I want to insert it into plugin. I watched some Udemy.com curses but still do not know exactly how to make. Please give me support.

First, I want to add scripts

function es_scripts()  {      if (!is_admin())      {          wp_register_script('jquery', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js');          wp_enqueue_script('jquery');                     wp_register_script('jquery.cycle.all', 'https://cdn.datatables.net/1.11.3/js/jquery.dataTables.js');          wp_enqueue_script('jquery.cycle.all');            wp_register_script('jquery.cycssle.all', 'https://cdn.jsdelivr.net/npm/apexcharts');          wp_enqueue_script('jquery.cycssle.all');            wp_register_script('jquery.cycssle.all', 'https://cdnjs.cloudflare.com/ajax/libs/mathjs/10.0.0/math.min.js');          wp_enqueue_script('jquery.cycssle.all');            wp_register_script('jquery.all', 'https://code.jquery.com/jquery-migrate-3.3.2.min.js');          wp_enqueue_script('jquery.all');      }  }  

and here style

  function es_styles()  {      if (!is_admin())      {          wp_register_style('font_old_standard_tt', 'https://cdn.datatables.net/1.11.3/css/jquery.dataTables.css');          wp_enqueue_style('font_old_standard_tt');                    wp_register_style('font_lobster', plugins_url('kalk.css', __FILE__));          wp_enqueue_style('font_lobster');                      }  }    add_action('wp_head', 'es_styles');   

and html

function html_section(){      echo: '<div>...</div>'  }  add_shortcode('html_content', 'html_section');  

i have a second script

function wp_super_first_plugin() {    ?>  <script>    }</script><?php   }   add_action('wp_footer', 'wp_super_first_plugin');     ?>  

there is no error, what's making me proud, but first it look ugly because look different then in localhost. Second, javascript do not work at all.

Update:

Finally I know what is require to change the look. My plugin is container into div which have width: 600px, I tried change its possition to another one using script

<script>  $(document).ready(){  $('container').appendTo('wp-container-61f7e07100333 entry-content wp-block-post-content');  }  </script>  

which had 1000px but not work; also change params of the first one.

Another problem is words are callopse one by one like a s d f I tried it remove by <pre>....</pre> but then the <div> does not appear at all.

Update2:

Yuap, it was a jQuery conflict. I change all $ to jQuery and start running.

But still have issue with appearance of plugin. The main <section> should have at least 1000px but have just 600px because of the parent one. What's more the text is writing collapse like

<pre>  a    b    c    d  </pre>  

Emscripten: How to catch JS exception?

Posted: 31 Jan 2022 08:00 AM PST

Emscripten 'val.h' API allows calling methods of JS objects, however, C++ try-catch won't catch JS exception. Consider this example:

#include <emscripten.h>  #include <emscripten/val.h>    void test(){      string t = "some invalid json";      val    v = val::object();        // This C++ try-catch doesn't catch JS exception      try {          v = val::global("JSON").call<val>("parse", t);          cout <<"ok" <<endl;      }      catch(...){          cout <<"failed" <<endl;      }        cout <<"ret" <<endl;  }  

The JS exception makes the 'test' function stop and no ok, no failed, no ret printed out. How to catch that JS exception thrown by JSON.parse?

There's 1 issue here but it's still open: https://github.com/emscripten-core/emscripten/issues/11496

TVCardView rounded corners strange behaviour

Posted: 31 Jan 2022 07:59 AM PST

I'm setting up a new tvOS app with a UISplitViewController and a UICollectionView as a detail view. To achieve some nice out-of-the-box focus behaviour, I'm trying to use TVCardView inside the UICollectionViewCell and adding an image view and a label to the card views content view (in interface builder). That works, but the problem is that the card views always applies rounded corners to the content once they have been selected. Initially all views have sharp corners, but as soon as a cell has been selected, it switches to rounded corners. First of all, I don't even want rounded corners and in Apples examples, I never see those rounded corners anyway: https://developer.apple.com/documentation/tvuikit/tvcardview But even then, it's kind of useless to have rounded corners only partially after selection.

Has anyone experience with TVCardView and knows about this strange behaviour? I cannot find any example code or more detailed documentation. I also tried to use TVLockupView instead, but that doesn't seem to be supported by interface builder.

SQL Cannot get WHERE EXISTS Clause to work properly and only return rows that have a type for a client within a certain date

Posted: 31 Jan 2022 07:58 AM PST

OK, this is driving me crazy and the solution I am sure will be pretty simple and I will probably bang my head into a wall. I have a query where I have client data. On some queries I ONLY want clients between a certain date that have had a client visit at some point within that date range, which correspond to Call_Report_ID's 3, 8 or 12. For these clients, I want it to bring back ALL data within the date range, not just the rows with this client visit code. For the other clients who DON'T have a client visit, I want to exclude them from the data.

Here is what I have been playing around with and cannot get it working at all.

SELECT *   FROM CV.Data AS CV   WHERE EXISTS (SELECT *                 FROM CV.Data AS CVD                 WHERE CVD.Call_Report_ID IN(3,8,12)                     AND CVD.User_ID = 33)       AND CV.User_ID = 33       AND CV.Activity_Date BETWEEN '10/1/2018' AND '3/31/2019'  

So here is an example of What I want:

Cust_ID Call_Report_ID Activity_Date    5         3            10/15/2018    5         7            10/28/2018    6         9            10/21/2018    6         11           10/25/2018   

In the above when I run this query, I want it to return both rows from Customer 5 since they have a call report ID of 3,8, or 12 in ANY row within the date range, and exclude both rows from Customer 6 since they do not have a call_report_Id with those types in a date range

However, every time I run it, it returns all rows for this user, not just the ones specified in the WHERE EXISTS SubQuery.

What am I dong wrong here?

How do I notify VueJS/Vuex of an value change in an array?

Posted: 31 Jan 2022 07:59 AM PST

when I update a value in an array of the store, the interface doesn't reflect the change.

Goal: I'm trying to display a simple minesweeper grid. Once I click on a cell, the object attach to that cell should update isRevealed to true to say is was revealed and Vuejs should add the class dug to that cell.

What's working: isRevealed is switched to true.

What was working: using only props everything was working, but trying to learn VueJS and including Vuex store the UI doesn't update anymore with the array.

Structure:

App shows a grid and grid shows multiple cell.

store.js for Vuex

import Vue from 'vue';  import Vuex from 'vuex';    Vue.use(Vuex);    export const store = new Vuex.Store({      state: {          GameGrid: [],      },  mutations: {      revealCell(state, cell) {          state.GameGrid[cell.y][cell.x].isRevealed = true;          console.log("revealCell ", cell);          },  });  

GameGrid contain the following: 10 arrays of 10 objects:

{      isRevealed: false,      x: 0,      y: 0      ...  }  

grid.vue, nothing special, display every cell

<template>        <div class="grid">          <div v-for="row in $store.state.GameGrid" class="row">              <app-cell v-for="col in row" :cell="col"></app-cell>          </div>      </div>    </template>  

cell.vue:

<template>      <div          @click="dig"          :class="{dug: cell.isRevealed, dd: cell.debug}">          <span class="text" v-html="cell.display"></span>          <span class="small">{‌{ cell.code }}</span>      </div>  </template>  <script>      export default {          props: {              cell: {                  type: Object              },          },          data: function() {             return {                 display: null,             }          },          methods: {              dig() {                  this.$store.commit('revealCell', this.cell);              },      }  </script>  

Edit accoridng to pirs answer:

Grid.vue file

<template>        <div class="grid">          <div v-for="row in gameGridAlias" class="row">              <app-cell v-for="col in row" :cell="col"></app-cell>          </div>      </div>    </template>    <script>      import { mapState } from 'vuex';      import Cell from './Cell.vue';      export default {          components: {              'app-cell': Cell,          },          data: {                  gameGridAlias: []          },          methods: {            },          computed: mapState({              gameGridAlias: state => state.GameGrid          })        }    </script>  

Note that I get The "data" option should be a function that returns a per-instance value in component definitions. error since data doesn't return a function.

My functions to set isRevealed are on the cell.vue though. I'm still seeing no UI updates (except when I'm saving?). Cells with this.cell.isRevealed = true confirmed with console.log but no change in classes.

Here is how I'm populating GameGrid

This function is calling when the user press a button on the hmm, home page? App.vue file.

     generateGrid() {            console.log("generateGrid");            //Generate empty play grid            for(let y = 0; y < this.$store.state.GameGridHeight; y++) {                this.$store.state.GameGrid[y] = new Array();                for(let x = 0; x < this.$store.state.GameGridWidth; x++) {                    this.$store.state.GameGrid[y][x] = {                        content: 'Empty',                        code: 0,                        isRevealed: false,                        x: x,                        y: y,                        debug: false,                    };                }            }        }, //End generateGrid  

Simpler way of sorting three numbers

Posted: 31 Jan 2022 07:58 AM PST

Is there a simpler and better way to solve this problem because

  1. I used too many variables.
  2. I used so many if else statements
  3. I did this using the brute force method

Write a program that receives three integers as input and outputs the numbers in increasing order.
Do not use loop / array.

#include <stdio.h>  main(){     int no1;     int no2;     int no3;     int sto;     int hi;     int lo;       printf("Enter No. 1: ");     scanf("%d", &no1);     printf("Enter No. 2: ");     scanf("%d", &no2);              printf("Enter No. 3: ");     scanf("%d", &no3);       if (no1>no2) {           sto=no1;            lo=no2;        } else {        sto=no2;          lo=no1;       }      if (sto>no3) {         hi=sto;            if(lo>no3){                    sto=lo;                           lo=no3;        }else {           sto=no3;              }              }else hi=no3;        printf("LOWEST %d\n", lo);     printf("MIDDLE %d\n", sto);     printf("HIGHEST %d\n", hi);         getch();   }