Can Bitbucket rerun pull request checks when target branch is modified?

Question: I am currently setting up a CI system that will check for a passing deployment against a test environment as part of a pre-merge pull request check.  This system is using Bamboo and Bitbucket, and will stop devs from merging their feature branches into the main branch if this validation fails. However, I am running into the (possibly common on my project) corner case of multiple pull requests being open at the same time, passing validation, and then being merged. In this scenario the PRs might all separately pass validation while all of them combined would break the build (I.E: PR#1 modifies a method name referenced by PR#2).
Is there a way to configure Bitbucket / Bamboo to rerun builds on pull requests if the target branch has been modified since the check last ran?
Comment: You can use several tools, there are pull request plugin, notification plugin or webhooks. Your CI could be triggered via webhook with PR's changes (target branch changed)
Answer: On git (bitbucket) level you could make sure to synchronize any feature or bugfix branch with an outgoing pull request by merging the latest common target branch (for example develop) immediately after a successful pull request merge to this target. This way you invalidate the 'latest' build result on feature or bugfix branches and they would be re-built because their git commit hash has changed. If any re-build of the feature branch fails, it won't be merged.
Ulrich
// Izymes - our mission is to eliminate boring from work. We build apps that turbo-charge team velocity through contextual automation.


Spring Boot Context Path Ignored With External Tomcat

Question: I have set the context path for tomcat as follows:
<code>@Component
public class CustomContainer implements
        WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        factory.setContextPath("/capripol");
        factory.setPort(8080);
    }
}
</code>
Navigating to localhost:8080/capripol works fine and I am prompted with my login screen, however after logging in my forms and controllers do not append to the context path, so instead of navigating to /capripol/MainMenu etc. they navigate to /MainMenu. How do I set the context path such that my form actions and controllers will be appended do it - why is the tomcat factory context path not setting?
Edit: My Application class
<code>@SpringBootApplication
public class CapripolApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(CapripolApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(CapripolApplication.class);
    }

    @Configuration
    public class WebConfig implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/**")
                    .addResourceLocations("classpath:/static/", "classpath:/images/")
                    .setCachePeriod(0);
        }
    }

}
</code>
Comment: Ofcourse it won't work. That will only work for an embedded container, not for an external one. You cannot control your external container from within an application.If you want to change the context path you need to dive into your application server and configure it there.
Answer: A few ways to do it. You can add it to each controller, usefully if you want to change the context path
<code>@Controller
@RequestMapping(value = "/foo")
public class bar{
    @GetMapping(value = "/bar")
    public void stuff(){
        //doing stuff
    }
}
</code>
Or you can put it in your application.properties / yml
<code>server.servlet.contextPath=/foo/*
</code>
There are technically some other more round about ways to do it, especially if you are using an older version of Spring, but I would think the application properties is what you are looking for.
Comment: this `server.servlet.contextPath=/foo/*` will not work with external tomcat. tomcat always take the war file name as the context path.


pandas profiling import error : not able to import pandas_profiling package

Question: I cannot import name DataError from pandas.core.base
When I import package:
from pandas_profiling import ProfileReport

it shows error:
cannot import name 'DataError' from 'pandas.core.base'

Comment: What versions of pandas and pandas-profiling are you using?
Comment: Typo in ProfileRreport
Comment: pandas   1.5.1
pandas-profiling  3.2.0
Comment: what bugs me is that it installs fine, but just can't be imported
Answer: The new version of Python (3.11) does not work with pandas_profiling. However, the old version works fine.
My version is 3.8.8, and it works in the command line:
import pandas_profiling as pp
data = pd.read_csv( "-----.csv")
pp.ProfileReport(data)


Find a vertex of a tetragon where three vertices are given

Question: Suppose that $V,W,U$ are three 3D points and $L,K$ are given positive values. Let $dist(A,B)$ represents euclidean distance between $A,B$. Morover, assume that $M$ is a plane that passes through $V,W,U$.
What I need is a point $P$ where:
$$dist(V,P)=L \\
dist(U,P)=K \\
P\in M $$
Obviously, we must find the equations of 2 circles, $C_1(V,L), C_2(U,K)$ where $C_1\subset M, C_2\subset M$ and then find their intersections.
These possible intersections would be our points. Of course  $L,K$  are given such a way that the intersections exist.
Answer: Since $P$ lies on the plane of $V, W, U$, then it can expressed using barycentric coordinates as follows
$ P = V + c_1 (W - V) + c_2 (U - V) $
Define the vectors $X_1 = W - V$ and $X_2 = U - V $
then
$ P = V + c_1 X_1 + c_2 X_2 $
Now you want
$ \| P V \| = L $ and $ \| P U \| = K $
Therefore, you want
$ \| c_1 X_1 + c_2 X_2 \| = L $
$ \| c_1 X_1 + (c_2 - 1) X_2 \| = K $
These two equations lead to the following quadratic equations
$ c_1^2 \| X_1\|^2 + c_2^2  \| X_2 \|^2 + 2 c_1 c_2 X_1 \cdot X_2
 = L^2 \tag{1} $
and
$ c_1^2 \| X_1 \|^2 + (c_2 - 1)^2  \| X_2 \|^2 + 2 c_1 (c_2 - 1)  X_1 \cdot X_2 = K^2 \tag{2}$
Subtracting the two equations gives
$ (2 c_2 - 1 ) \| X_2 \|^2 + 2 c_1 X_1 \cdot X_2 = L^2 - K^2 \tag{3} $
Equation $(3)$ is a linear equation in $c_1$ and $c_2$ and can be directly solved for $c_1$ in terms of $c_2$ or vice versa.
Back substituting either variable in $(1)$, two possible values for the other variable are found.
Having determined the possible pairs of $(c_1, c_2)$, two possible solutions for point $P$ are thus determined.
Edit: The code that I wrote to find the solutions for $P$ follows.  It is written in Excel VBA (Visual Basic for Applications).
Public Sub mse_tetragon()

Dim u(3), v(3), w(3) As Double
Dim x1(3), x2(3) As Double
Dim p0(3) As Double
Dim v0(2), v1(2) As Double
Dim a0, a1 As Double
Dim p1(3), p2(3) As Double

Dim l, k As Double

v(1) = 1

u(2) = 1

l = 1
k = 1

For i = 1 To 3
x1(i) = w(i) - v(i)
x2(i) = u(i) - v(i)
Next i

'  Let d1 = X1.X1, d2 = X2.X2 , d3 = X1.X2, then equation (3) is

' (2 c2 - 1) d2 + 2 c1 d3 = L^2 - K^2

' re-arranging,

' 2 d3 c1 + 2 d2 c2 = L^2 - K^2 + d2

'  therefore,

' c2 = 1/(2 d2) [ L^2 - K^2 + d2 - 2 d3 c1 ]

'    = A0 + A1 c1

d1 = dot(x1, x1)
d2 = dot(x2, x2)
d3 = dot(x1, x2)

a0 = (l ^ 2 - k ^ 2 + d2) / (2 * d2)
a1 = -2 * d3 / (2 * d2)

' substitute for c2 into Eqn. (1)

' c1^2 d1 + c2^2 d2 + 2 c1 c2 d3 = L^2

' So,

' c1^2 d1 + (a0 + a1 c1)^2 d2 + 2 c1 (a0 + a1 c1) d3 = L^2

' collect the coefficients of c1^2, c1, 1

s2 = d1 + a1 ^ 2 * d2 + 2 * a1 * d3
s1 = 2 * a0 * a1 * d2 + 2 * d3 * a0
s0 = a0 ^ 2 * d2 - l ^ 2

disc = s1 ^ 2 - 4 * s2 * s0

If Abs(disc) < 0.000001 Then disc = 0

If disc < 0 Then
MsgBox ("No solutions to quadratic equation")
Exit Sub
End If

c11 = (-s1 - Sqr(disc)) / (2 * s2)
c12 = (-s1 + Sqr(disc)) / (2 * s2)

c21 = a0 + a1 * c11
c22 = a0 + a1 * c12

For i = 1 To 3
p1(i) = v(i) + c11 * x1(i) + c21 * x2(i)
p2(i) = v(i) + c12 * x1(i) + c22 * x2(i)

ActiveSheet.Cells(i, 1) = p1(i)
ActiveSheet.Cells(i, 3) = p2(i)

Next i

End Sub

The output of this program is shown below
Comment: Sure, but not at home right now.  When I get back home, I'll post the code.
Comment: @HamidShafieAsl I've just edited my solution to include my code.  Hope you find it easy to follow.  If you still have questions on it, I'll be happy to answer them.
Comment: I set $V = [1, 0, 0], W = [0, 0, 0], U = [0, 1, 0], L = 1, K = 1$ and results are as $P1 =[1.1464191348868271, -1.292838269773654, 0.0]$ and $P2= [-0.20524266429859184, 1.4104853285971835, 0.0]$ which is wrong!!! Obviously, we expect $P1$ or $P2$ equals $[1,1,0]$. Please revise your response!
Comment: @HamidShafieAsl  I've written code to solve the system of equations (1) and (3), and got two solutions for $P$.  The two solutions are $(0,0,0)$ and $(1,1,0)$.
Comment: I tested yours with a python code and I get that result. Maybe my code was wrong! Could you please share your code?
Comment: Dear @of course I check my calculation many times. According to your third equation (3) we have $c_1 = \frac{L^2 - K^2 + (1-2c_2)\|X_2\|^2}{2X_1\cdot X_2}$. Is this rearrange true? Did I make a mistake? I want to rearrange first equation and make quadratic equation $Ac_2^2 + Bc_2 + C = 0$. Rest of my calculation in next comment.
Comment: I reach $A = \frac{\|X_2\|^4\|X_1\|^2}{(X_1\cdot X_2)^2} - \|X_2\|^2$ and $B= (L^2-K^2+\|X_2\|^2)(1 - \frac{\|X_1\|^2\|X_2\|^2}{(X_1\cdot X_2)^2})$ and $C= \frac{(L^2-K^2+\|X_2\|^2)^2\|X_1\|^2}{4(X_1\cdot X_2)^2} - L^2$.

What is my mistake?
Comment: I check my evaluation many times and I couldn't find any mistake. I wrote its code as an answer via python code and I get different result in comparing with yours. Are you sure of yours? See my code in answers
Comment: Yes.  I am pretty sure of my code.  Also, it gives correct answers.
Comment: Thank you very much! I tried to understand my mistake in calculation and I couldn't find any mistake. However, yours works interestingly perfect. I don't know how you did that, but I turned your code into a python code and it worked very well.
Answer: Hint.
Calling $\hat{k}=\frac{(V-W)\times(W-U)}{\|(V-W)\times(W-U)\|}$ we can determine $\hat p,\hat q$ such that
$$
\cases{
\hat p\cdot \hat k = 0\\
\|\hat p\| = 1\\
\hat q = \hat k\times \hat p
}
$$
after that, calling
$$
\cases{
C_1=V+\left(\hat p\cos t_1+\hat q \sin t_1\right)L\\
C_2=U+\left(\hat p\cos t_2+\hat q \sin t_2\right)K\\
}
$$
we will look for solutions to
$$
V+\left(\hat p\cos t_1+\hat q \sin t_1\right)L = U+\left(\hat p\cos t_2+\hat q \sin t_2\right)K
$$
so multiplying successively by $\hat p,\hat q$ we have
$$
\cases{
V\cdot\hat p+\cos t_1 L = U\cdot \hat p + \cos t_2 K\\
V\cdot\hat q+\sin t_1 L = U\cdot \hat q + \sin t_2 K}
$$
Two equations to solve in $t_1, t_2$
NOTE
To solve the system
$$
\cases{
c_1+L\cos t_1 = c_2+K\cos t_2\\
c_3+L\sin t_1 = c_4+K\sin t_2
}
$$
by using $\sin^2t_1+\cos^2t_1 = 1$ we obtain an expression as
$$
b_1 \sin t_2 + b_2\cos t_2 + b_0=0
$$
or equivalently
$$
\frac{b_1}{\sqrt{b_1^2+b_2^2}}\sin t_2+\frac{b_2}{\sqrt{b_1^2+b_2^2}}\cos t_2+\frac{b_0}{\sqrt{b_1^2+b_2^2}}=0
$$
and now we follow making
$$
\cases{
\sin t_0 = \frac{b_1}{\sqrt{b_1^2+b_2^2}}\\
\cos t_0 = \frac{b_2}{\sqrt{b_1^2+b_2^2}}\\
c_0 = \frac{b_0}{\sqrt{b_1^2+b_2^2}}
}
$$
giving thus
$$
\sin t_2\sin t_0 + \cos t_2\cos t_0 + c_0 = 0
$$
or $\cos(t_2-t_0)+c_0 = 0$ and finally
$$
t_2=\arccos(-c_0)+t_0
$$
Here
$$
\cases{
c_1 = V\cdot\hat p\\
c_2 = U\cdot\hat p\\
c_3 = V\cdot\hat q\\
c_4 = U\cdot\hat q\\
b_1 = 2(c_4-c_3)K\\
b_2 = 2(c_2-c_1)K\\
b_0 = (c_1-c_2)^2+(c_3-c_4)^2+K^2-L^2\\
}
$$
so you have a closed answer expression.
Comment: solving these equations, we have $\sin t_1 = \frac{(U-V)\cdot \hat{q} + K\sin (\arccos(\frac{(V-U)\cdot \hat{p} + L\cos(t_1)}{K}))}{L}$. Do you have any idea to get through of this? I mean, how to find $t1$? Numerical solutions? How?
Comment: The determination of $\hat p$ from $\hat k$ can be done by choosing freely the lacking unknowns, respecting the condition $\|\hat p\|=1$ and the last condition involves only two unknowns: $t_1, t_2$.
Comment: Use the property $\cos ^2t_1+\sin^2t_1 = 1$
Comment: I know what is that equation. How to solve it for $t_1$ where it is not simple to separate $t_1$. I know that $\sin(\arccos(M)) = \sqrt{1-M^2}$
Comment: Please. See note included in the answer.
Comment: What is $b_i$ and $t_0$?
Comment: @AidaSAFARY Please. Have a look at the included answer to your request.
Answer: Dear of course this is my code about your response:
import math

def myVector(M,N):
    return [N[i] - M[i] for i in range(3)]
def myNorm(M):
    return math.sqrt(sum(M[i]**2 for i in range(3)))
def myDotProduct(M,N):
    return sum(M[i]*N[i] for i in range(3))

def findVertex2(v, w, u, l, k):
    X1 = myVector(v, w)
    X2 = myVector(v, u)
    d1 = myDotProduct(X1, X1)
    d2 = myDotProduct(X2, X2)
    d3 = myDotProduct(X1, X2)
    a0 = (l**2 - k**2 +d2)/(2 * d2)
    a1 = -2 * d3/ (2 * d2)
    s2 = d1 + (a1 ** 2 )* d2 + 2 * a1 * d3
    s1 = 2 * a0 * a1 * d2 + 2 * d3 * a0
    s0 = (a0 ** 2)* d2 - l ** 2
    disc = s1 ** 2 - 4 * s2 * s0
    if disc < 0:
        return None
    else:
        c11 = (-s1 - math.sqrt(disc)) / (2 * s2)
        c12 = (-s1 + math.sqrt(disc)) / (2 * s2)
        c21 = a0 + a1 * c11
        c22 = a0 + a1 * c12
        P1 = [v[i] + c11*X1[i] + c21*X2[i] for i in range(3)]
        P2 = [v[i] + c12*X1[i] + c22*X2[i] for i in range(3)]
        return P1, P2

v = [1,0,0]
w = [0,0,0]
u = [0,1,0]

print(findVertex2(v, w, u, math.sqrt(2), math.sqrt(2)))

#result
([1.0, 1.0, 0.0], [0.0, 0.0, 0.0])
I edited it and it worked!


Prove that if $n$ is an integer, then $n^2 + n^3$ is an even number

Question: I am trying to work through some of the problems in Stephen Lay's Introduction to Analysis with Proof before my Real Analysis class in the fall term starts, and I was just wondering if I could get some feedback as to whether or not I have completed this proof properly
The question:

Prove that if $n$ is an integer, then $n^2 + n^3$ is an even number
Comment: Note that $n^2(1+n)=2k+1$ does not imply that either $n^2=2k+1$ or  $n+1=2k+1$. Also, $\sqrt{2k+1}$ is sometimes an integer, let $k=4$ for example. And you are not trying to prove that $n$ is even, you are trying to prove that $n^2+n^3$ is even.
Answer: Your approach for the proof is incorrect. You want to prove an implication $P \to Q$. So if you assume that $Q$ is true, then you have nothing left to prove. You should just begin with an integer $n$ then try to see what can be said about $n^3+n^2$. For example, you can say
$$n^3+n^2=n^2(n+1).$$
Now if $n$ is odd then $n+1$ is even and vice versa. So you have a product of odd number and even number and hence even.
Comment: I just realized that I misread the question when I made the answer!!
Comment: Unfortunately no. In the line where you say $n^2(n+1)=2k+1$, you cannot conclude that $n^2=2k+1$.
Comment: If you strictly want to use basic definition, then you need to break it into two cases. Let $n$ be even, then $n=2a$ for some $a \in \mathbb{Z}$. Then you can say $n^3+n^2=8a^3+4a^2=4a^2(2a+1)=2[2a^2(2a+1)]$. Now this is of the form $2k$.
Answer: Hint
$$n^3+n^2=n(n(n+1))$$
$n(n+1)$ is the product of two consecutive integers.
Comment: Nice solution! I didn't think of that.
Comment: Question about that, is there any way you can prove that $n^3 + n^2$ is of the form 2$k$?
Comment: @Toxicz The idea is that $n^{3} + n^{2}$ is equal to $n(n(n + 1))$.  So we have $n*n*(n + 1)$.  One of those is even because we have both a product of both $n$ and $n + 1$.  If you think about it, every other integer is odd, and every other one is even.  For example, in order, we have $1,2,3,4,5,6,\cdots$.  The $1, 3, 5, \cdots$ are odd and the $2, 4, 6, \cdots$ are even.  Every other one is odd.  So when you have $n$ and $n + 1$, since they are consecutive and every other integer is even, one of these integers is even.  So $n*n*(n + 1) = 2k$ for some integer $k$.  Does that help?
Answer: Alternatively, by Fermat's Little Theorem,
$$\begin{align}n^2 + n^3 &= n^2 + n\cdot n^2\\
&\equiv n + n\cdot n \pmod  2\\
&= n + n^2 \pmod 2\\
&\equiv n + n \pmod 2\\
&= 2n \pmod 2\\
&\equiv 0 \pmod 2\end{align}$$
Comment: Or perhaps

$$\begin{align}n^2+n^3&=n^2(n+1)(\mod 2)\\
&=n(n+1)(\mod 2)\\
&=0(mod 2)\end{align}$$
Comment: Or perhaps
$$\begin{align}
n^2+n^3&=n^2(1+n)\mod 2\\
&=n(n+1)\mod 2\\
&=0\mod 2
\end{align}$$

[couldn't edit the previous comment further... this corrects the typesetting]
Answer: Here's a shorter proof:  Select any $n \in \mathbb{Z}$.  There are two cases:  $n \equiv 0, 1 \pmod{2}$.
In either case, use modular arithmetic to compute $n^2 + n^3 \pmod{2}$.  What can we conclude?
Comment: Well, when we say $x \equiv y \pmod{n}$, then that means that $n|(x-y)$.  When we say $n|(x-y)$, that means there is some other integer $z$ such that $nz = x-y$.  Therefore, any even number will be equivalent to $0 \pmod{2}$.  From here, try to prove the facts that $x \equiv y \pmod{n}$ and $a \equiv b \pmod{n} \implies xa \equiv yb \pmod{n}$, and likewise for addition.  The ultimate goal is to show that $n^2 + n^3$ is even, and thus equivalent to $0 \pmod{2}$.
Comment: Thats quite interesting, I will have to read up on this. Thank you :)
Comment: Well, I know what $x$ is congruent to $y$ mod $a$ means, but how would I solve an equation with that sort of "constraint"?
Answer: My attempt via unique prime factorization of integers:
$n = p_1^{a_1} p_2^{a_2} \dots p_n^{a_n}$ for some unique choice of (positive) prime $p_1, \dots, p_n$ and natural $a_1, \dots, a_n$.
Case 1:
Let $n$ be odd. Then each $p_i$, with $1 \leq i \leq n$ is odd (i.e., not 2). Now, $n^2 = (p_1^{a_1} p_2^{a_2} \dots p_n^{a_n})^2 = p_1^{2a_1} p_2^{2a_2} \dots p_n^{2a_n}$, which is still odd. Similar for $n^3$. Thus $n^2 + n^3$ is even, being the sum of two odd numbers.
Case 2:
Let $n$ be even. Then we know that one of the $p_i$'s is $2$. We can write our unique factorization of $n$ as $2^{a_1} p_2^{a_2} \dots p_n^{a_n}$. Now it should be obvious that $n^2 = 2^{2a_1} p_2^{2a_2} \dots p_n^{2a_n}$ is even, since it's a multiple of 2, and likewise for $n^3$. Thus we see that $n^2 + n^3$ is the sum of two even integers and is therefore even.
Answer: This came up as a question that might have the answer to my question. It doesn't, but since I'm here, I might as well:
Suppose $n$ is odd. Then $n^2$ is also odd, as well as $n^3$. But two odd numbers add up to an even number, hence $n^2 + n^3$ is even.
If instead $n$ is even, then $n^2$ and $n^3$ are both even also, and since even numbers add up to even numbers anyway, we're done.
Answer: Integer can be separated into two types one is even number and the other is odd numbers
Case 1: The integer is even:
Even numbers can be represented as: $n = 2k$
$n^2 + n^3 = (2k)^2 + (2k)^3 = 4k^2 + 8k^3 = 2(2k^2 + 4k^3) = 2m$
Therefore if n is even $->$ ${n^2 + n^3}$ is even
Case 2: The integer is odd:
Odd numbers can be represented as $n = 2k + 1$
$n^2 + n^3 = (2k + 1)^2 + (2k + 1)^3 = 8k^3 + 16k^2 + 10k + 2 = 2(4k^3 + 8k^2 + 5k + 1) = 2x$
Therefore if $n$ is odd $->$ $n^2 + n^3$ is even


Installation of Serviio on 14.4

Question: I have little Linux experience and I am completely new to Ubuntu.
I would like to install Serviio media server so that I can stream media from my PC to my TV. Serviio, however, is not available in the Software center.
If I download the package from the official Serviio site, then there is an instruction to create a config file (which I hope I completed correctly), and then to run the program. How can I do that? Ubuntu is opening the .sh file with a text editor..
Comment: Thank you for the link. I have seen this, but I do not understand it, it is a bit too high level for me. Where shall I write all these commands? In Terminal? In which folder? How to create and save scripts?
Comment: @DuminduMahawela The instructions in your link are obsolete for Ubuntu 14.04 and beyond.
Comment: Thank you, @karel! Can I find somewhere guidance what to do in 14.04 environment?
Answer: I have found on the internet a solution that worked for me.
http://www.tylergale.com/?p=77
I am posting it here for future reference if someone else has the same problem

Install Java. The suggestion was to install Java 7, but I couldn't run Serviio later, got some version mismatch error. I installed 8 and this solved the problem.

sudo add-apt-repository ppa:webupd8team/java -y
sudo apt-get update
sudo apt-get install oracle-java8-installer

Install FFMPEG

sudo apt-add-repository ppa:jon-severinsson/ffmpeg -y
sudo apt-get update
sudo apt-get install ffmpeg

Download Serviio from the official site http://www.serviio.org/download and extract it in your desired destination folder. I personally called it 'serviio' and placed it in Home
Give permissions

sudo chown -R YOURUSER:YOURUSER SERVIOFOLDER (e.g. sudo chown -R tyler:tyler /home/tyler/serviio)

Run from terminal

sudo sh SERVIIOFOLDER/bin/serviio.sh

  and
sudo sh SERVIIOFOLDER/bin/serviio-console.sh

I personally had problems to run it from terminal, but I managed to run it from GUI instead.
Comment: Looks like you found a better solution already! ;-)

Installation of Serviio on 14.4


using external php file in html form

Question: I am trying to create simple user registration form. I have an index.html file and a register.php file. When I click the submit button it goes to the register.php page, but nothing happens. There's no error or anything. I have some echo statements in register.php but they also don't work.
This is the code for index.html:
<form action="register.php" method="post">

<? echo '
'.$final_report.'
';?>

Username:

  <input name="username" type="text" id="username" size="30" />

  Password:
  <input name="password" type="password" id="password" value="" size="30" />

  Email:
  <input name="email" type="text" id="email" size="30" />

    <input name="register" type="submit" id="register" value="Register" />

  </form>

This is code for register.php:
<?
include_once"config.php";
if(isset($_POST['register'])){
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$memip = $_SERVER['REMOTE_ADDR'];
$date = date("d-m-Y");
if($username == NULL OR $password == NULL OR $email == NULL){
$final_report.= "Please complete the form below..";
}else{
if(strlen($username) <= 3 || strlen($username) >= 30){
$final_report.="Your username must be between 3 and 30 characters..";
}else{
$check_members = mysql_query("SELECT * FROM `members` WHERE `username` =    '$username'");
if(mysql_num_rows($check_members) != 0){
$final_report.="The username is already in use!";
}else{
if(strlen($password) <= 6 || strlen($password) >= 12){
$final_report.="Your password must be between 6 and 12 digits and characters..";
}else{
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",         $email)){
$final_report.="Your email address was not valid..";
}else{
$create_member = mysql_query("INSERT INTO `members` (`id`,`username`, `password`,`email`, `ip`, `date`)
VALUES('','$username','$password','$email','$memip','$date')");
$final_report.="Thank you for registering, you may login.";
}}}}}}
?>

Can anyone see the error?
Answer: include_once"config.php"

You seem to be missing a space. Either make it include_once "config.php" (notice the space in between) or include_once("config.php").
Also you set $final_report in register.php but I don't see where you are actually printing anything.
Edit: I see you are trying to print $final_report in index.php. This won't work as you expect unless you include the register.php code directly into index.html. Why don't you just have a single register.php file with both the registration script and the HTML code?
Comment: I made my main page as a index.html then I include in it form for registration.If I also include php script in index.html file then I should change it to index.php. I have several pages in a relation with index.html
Comment: You are already using PHP code (``) in index.html. If that is working, then you shouldn't have any problem adding more code there. (Many web servers will parse HTML files as PHP by default.)

using external php file in html form


Type cast optional values

Question: Whenever we need to du something with an optional value in swift we need to unwrap it to operate, not on the optional, but on the value "inside" the optional.
var optionalString:String? = "Hello"
optionalString!.append(" World!")

Note the exclamation mark on the second line.
But when using the optional type cast operator (as?) on an optional value, one does not need to unwrap the optional, we just provide it with the optional itself, and it just magically works.
let sneakyString:Any? = "Hello!"
let notSoSneakyString = sneakyString as? String

Note the absent exclamation mark on the second line.
The magic is a bit more obvious if we spell it out:
let sneakyString:Any? = Optional("Hello")
let notSoSneakyString = sneakyString as? String

Its not a string we're trying to cast but an enum with a string as an associated value.
I would expect that I would have to do this:
let sneakyString:Any? = "Hello!"
let notSoSneakyString = sneakyString! as? String

Note the exclamation mark on the second line.
Does the type cast operators act on optionals and non optionals in the same way?
Comment: Maybe this makes sense after all. To unwrap a nil optional is a runtime error. And we're not casting from Optional(Any) to String, but from Optional(Any) to Optional(String).
Answer: The as? operator makes a cast if it possibly can, and returns either the casted object or nil. It handles nil values too, so that if sneakyString were nil, you wouldn't have been able to cast it to a String and the cast would have failed. Same behaviour as if it were non-nil but not castable to String.
In other words, you don't need the ! because as? handles nil values automatically itself.
Comment: Yea the nil case is a bit more logical. Edited my question to point out that the operator is not operating on a string struct, but on an enum with a string as an associated value. Do you know if this is documented?

Type cast optional values


Tkinter how to size fonts and keep alignment

Question: I'm writing an app that needs to be zoomable. Using the default system fonts, "TkDefaultFont and TkTextFont" I increase their sizes and I get the results I want sort of. The problem is after sizing the alignment is thrown off between the field label and field widget. I have tried applying update_idletasks() but it does nothing. Moving the mouse over the widget fixes the problem as see in the video. If you run the example below go the the size spinbox and change the size to view the issue.
My dev system is Linux, Desktop KDE, I don't know if this is a OS issue.
A link to a short video of the issue.
Video of Alignment Issue.
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.font as tkfont

root = tk.Tk()
root.rowconfigure(0, weight=1)
root.columnconfigure(99, weight=1)

frame = ttk.Frame(root)
frame.rowconfigure(0, weight=1)
frame.columnconfigure(0, weight=1)

cbo = ttk.Combobox(frame)
cbo.config(
    values=('Test 1', 'Test 2', 'Test 3')
)
cbo.set(value='Test 1')

ent_var = tk.StringVar()
ent = ttk.Entry(frame, textvariable=ent_var)
ent_var.set('Test')

lb_size = ttk.Label(frame, text='size')
spn = ttk.Spinbox(frame,  values=tuple(range(1, 101)))

font1 = tkfont.nametofont('TkDefaultFont')
font2 = tkfont.nametofont('TkTextFont')

lbl_field_name = tk.Label(frame, text='Field Name')
lbl_field_name.grid()

def size(e):
    cfg = font1.actual()
    cfg['size'] = e.widget.get()
    font1.configure(**cfg)
    font2.configure(**cfg)

spn.bind('<<Increment>>', size)
spn.bind('<<Decrement>>', size)

cbo.grid(row=0, column=1, sticky=tk.NSEW)
ent.grid(row=0, column=2, sticky=tk.NSEW)
lb_size.grid(row=0, column=3, sticky=tk.NSEW)
spn.grid(row=0, column=4, sticky=tk.NSEW)
frame.grid(sticky=tk.NSEW)

root.mainloop()

Comment: It would help if you included a small [mcve] so that people who are trying to answer this question have a starting point.
Comment: I would but I would need to include to much of the app that that's not possible. I was hoping someone else has had the same problem and could help. All I'm doing is increasing the size of TkDefaultFont and TkTextFont, but the alignment don't happen until you mouse over the widget as see in the video.
Comment: Based on your video, all we need is an app with a couple of comboboxes, a spinbox for the font size, and enough code to make that work. I don't see why you can't provide that in your question.
Comment: Yes that's what I'm doing. I will get back when I have the example.
Comment: Update with working example.
Comment: The problem is in the widget, it's a combo box although I would think it would be the same in an entry widget.
Comment: Yes the same thing happens with an Entry widget.
Comment: I also found out the the mouse over does not affect entry widgets as the code above shows, the alignment stays the same.
Comment: Try updating the `font` property of the widgets in `size(...)` function, e.g. cbo.config(font=font1).
Comment: There is library PyQT5, have you considered using it? I think it is much easier a better, you can design ui without scripting
Comment: btw `ttk.Spinbox()` is throwing error: `AttributeError: module 'tkinter.ttk' has no attribute 'Spinbox'`. I think you mean `tk.Spinbox()`.
Comment: @Grzegorz Krug: No I want to use tkinter I do know about PyQT5, thanks for your suggestion though.
Answer: The only way I have found to avoid this issue is to change the font from each entry's configure() method. I guess the easier way will be to put all the entries in a list, see code below.
I have also noticed that size() uses the previous value of the spinbox not the one after the increment/decrement. To avoid that, I suggest you to use the command option of the spinbox instead of the bindings to <<Increment>> and <<Decrement>> (see code below).
Finally, you do not need to retrieve the whole font settings to update the size, you can simply do font1.configure(size=<newsize>).
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.font as tkfont

root = tk.Tk()
root.rowconfigure(0, weight=1)
root.columnconfigure(99, weight=1)

frame = ttk.Frame(root)
frame.rowconfigure(0, weight=1)
frame.columnconfigure(0, weight=1)

entries = []  # list of all entries

cbo = ttk.Combobox(frame)
cbo.config(
    values=('Test 1', 'Test 2', 'Test 3')
)
cbo.set(value='Test 1')
entries.append(cbo)

ent_var = tk.StringVar()
ent = ttk.Entry(frame, textvariable=ent_var)
ent_var.set('Test')
entries.append(ent)

def size():
    size = spn.get()  # get current spinbox's value
    font1.configure(size=size)
    font2.configure(size=size)
    for e in entries:  # update font in all entries
        e.configure(font=font2)

lb_size = ttk.Label(frame, text='size')
# use the command option to update the font size
spn = ttk.Spinbox(frame, command=size, values=tuple(range(1, 101)))

font1 = tkfont.nametofont('TkDefaultFont')
font2 = tkfont.nametofont('TkTextFont')

lbl_field_name = ttk.Label(frame, text='Field Name')
lbl_field_name.grid()

cbo.grid(row=0, column=1, sticky=tk.NSEW)
ent.grid(row=0, column=2, sticky=tk.NSEW)
lb_size.grid(row=0, column=3, sticky=tk.NSEW)
spn.grid(row=0, column=4, sticky=tk.NSEW)
frame.grid(sticky=tk.NSEW)

root.mainloop()

Comment: You said "use command option of the spinbox instead". I really want to use bind because I attach attributes and or variables to the widget, that are then available in the callback function. I have rewritten the code to use bind and it functions normally. I pasted the code on pastebin if you care to view how I managed to use bind.   https://pastebin.com/3JHjvZ8G
Comment: @DanielHuckson No problem, this was just a suggestion because I noticed that the previous size was used. I understand that you have other constraints coming from your project which where not relevant to this question. Thanks for sharing your solution.
Comment: Yes I found that out as well, but for some reason the call root.after(0, func) seems to fix that issue. Any idea why this is?
Comment: I just finished refactoring the code in my project with your solution and it seems it's not viable for me. I have to many widgets that need to be sized and it kills the zooming effect (getting lag). I guess I will just have to live with it the way it is until they fix the issue. Or someone else comes up with a fix without the lag!
Comment: @DanielHuckson The problem with the binding to `<>` is that it is called before the change of value in the spinbox occurs. By adding the call to`after()`, you execute the function just after the value change. Unfortunately, for your font issue I don't think there is any solution not involving looping over all the entries.
Comment: I would write each of these fields to sit inside of a frame so you can control width. The resizing of everything as the font changes is going to be very annoying.
Comment: Because I want the zooming effect to be as smooth as possible, I need to use the system default names ie. "TkDefaultFont, TkTextFont". The problem with this is just one thing, while zooming live the alignment of the contents does not get centered vertically. I used the solution above but this is not possible to do live I got too much lag. The best solution I have so far is to let it go out of alignment while zooming then fix it when then zooming stops.


Copying partitions from larger HDD to smaller SSD

Question: So I have a laptop with a HDD of 1TB and I'm planning to buy a 500GB SSD, and copy the HDD to the SSD. Many posts already start like this, and I have read many of them, most on this site. Some recommend using Clonezilla, some others to use gparted. It seems, though, that when going from a larger drive to a smaller one, neither Clonezilla or gparted will copy the entire drive (please, correct me if I'm wrong); the way to go about this is to copy partition by partition. I'd like to expose what I'm planning to do to dump the HDD into the SSD just to see if the steps are correct. I would like the people in the community to tell me whether or not I'm doing something wrong and/or if I'm missing something.
First off, this is my hard drive. Nothing outside the norm.

What I'm planning to do is the following:

Create two partitions into my SSD of about roughly the same size, say, 250 GB each, one formatted ntfs and the other ext4. I suppose with the same flags as in the HDD.
Using gparted, shrink the partitions /dev/sda3 and /dev/sda5 in the HDD down to 250 GB each (or even less, just in case).
Using gparted, copy the partitions /dev/sda3 and /dev/sda5 from the HDD to the corresponding partition in the SSD (the ntfs-formatted partition from the HDD to the ntfs-formatted partition in the SSD; do likewise for the other)
Repair the grub by, for example, following the steps in this web.

I've got a few doubts about these steps: Are they complete, i.e., is something missing? What about the other partitions /dev/sda1 (the /boot/efi), /dev/sda2 (Microsoft reserved partition), /dev/sda4 (I don't know what that is), and /dev/sda6 (the swap partition for ubuntu): should they be copied too?
I'm not new to Ubuntu, but I'm new to copying and moving partitions, so any help will be very much appreciated.
Comment: Microsoft requires gpt partitioning for UEFI boot which you have. And it wants these partitions: https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/configure-uefigpt-based-hard-drive-partitions#RecommendedPartitionConfigurations Often easier to just reinstall Ubuntu to avoid issues of duplicate UUIDs.
Comment: I assume you mean install ubuntu in the new SSD, from scratch, and copy the data. What about windows? I can't simply get rid of it (although sometimes I wish...).
Answer: I would do that with clonezilla.
https://clonezilla.org/
Comment: If you are cloning your disk you need to copy all the components. It's generally better to have swap space but not essential. If you don't copy swap without turning swap off you can expect some issues. You can change swap partitions to swap files in Ubuntu but that just moves the space requirement to the Linux partition. You absolutely need the EFI partition, your system will not boot without it and normal boot repair approaches will not work.
Comment: `Clonezilla` is a good tool indeed. I tried it some time ago and seems to do the job. But could you fill in with a few more details? For example, what about the linux swap partition? Do I also have to make a new partition in the SSD flagged as a swap partition? Or will `gparted`/`clonezilla` create it? Is `gparted` replaceable by `clonezilla` in the steps I gave?
Comment: Download the clonezilla iso-file and create a bootable medium. Boot that and you get a menu where you can copy sectorwise partitions or hdd's
Comment: Yes... That I knew, thank you. I suppose you don't have much to say about the smaller partitions (linux swap, ....)? If you know something about that, I would really appreciate it if you mentioned it.
Comment: I would recommend to always turn off all swap partitions. For me it's better to use a swap file.
Comment: @PonJar Thank you for spelling out that I need to copy all the components. I really wasn't sure; now I am, thank you :) Also, thanks for filling in extra details like "It's generally better ...". If you have something else to say, I'll be happy to read it!
Answer: If you just want to get this done and don't mind using Windows based tools Macrium Reflect Free will do the whole job in a single process.
https://knowledgebase.macrium.com/display/KNOW7/Cloning+a+disk
Comment: Thanks for the information, I didn't know this software. Unfortunately, I can't help realising that it is non-free software, the cheapest purchase price being 63€. I don't think throwing money into the problem will help much. I'm only concerned about the Linux swap partitions. Could someone say whether or not those smaller partitions need to be copied? I don't mind copying everything, and creating more than 2 partitions (I've done this before, it's just that OSs weren't involved) but I need to know whether it is necessary or not.
Comment: The free version will do what you have asked unless your comment is about open source vs proprietary. You need all the partitions as indicated by several comments
Comment: My comment was not open source vs proprietary. It's just that I didn't want to pay for a software when there are good open source alternatives, and I believe there are (like gparted and clonezilla). However, since you say there is a free version (which I haven't been able to find yet), I'll read more about the software to learn how to do all this with it and consider using it instead of the open source tools.
Comment: https://www.macrium.com/reflectfree
Comment: Second useful comment from you, thank you
Answer: I finally got my HDD replaced by an SSD. In this answer I would like to describe the setbacks that I run into after the HDD was copied. I also describe the issues during the copy encountered by the IT technician who did the copy.
I must say, though, that the SSD was indeed smaller than the HDD, but rather than being about half the size, the SSD was just 40 GB smaller than the HDD (the size that appears in gparted is 894.25 GB). Therefore, the copy was done by hand (or so the IT technician involved told me). However, it was not done so too comfortably.
Issues during the copy
The partitions were copied one by one in the left-to-right order in which they appear in gparted (see post). After copying /dev/sda3, it was shrunk in the SSD (not in the HDD) so that /dev/sda5 would fit.
Issues after the copy
Booting
Everyone must make sure that the computer boots all OS normally after the copy and always before wiping out the HDD. This goes without saying but a friendly reminder is always welcome: there were some troubles when booting windows. The technician told me he had to run several windows commands. However, I don't remember which, nor how he did it.
Running the OS
Windows: there were two issues with Windows update. To begin with, a little trifle: Windows Update widget wouldn't load the list of new updates. This was resolved by deleting the contents of the folder containing what I believe is the updates cache. The second issue is that Windows wouldn't install certain updates, crashing with the error Windows couldn't finish the update. After hours of trying several possible solutions I gave up since the update that failed was "optional". (fix explained later)
Ubuntu: you know that after certain updates (through apt update ; apt upgrade), apt runs commands that reinstall the grub (or reconfigures grub-related files -- I don't know the exact terminology nor the exact procedure). For example, this happens when updating the Linux kernel. The issue with Ubuntu was that after some time using the SSD, Ubuntu installed some updates which made the computer boot directly into Ubuntu, bypassing the grub (thus Windows was no longer accessible).
Fixing Windows and Ubuntu: I started by trying to fix the grub by running the boot repair tool in Ubuntu. This shed light on the error: the boot repair tool couldn't repair the grub the flags of the partitions weren't copied properly, so it couldn't find the partition were the grub was installed (in my case /dev/sda1 with flags boot,esp). The flags weren't set properly probably due to "miscopying" the partitions: I checked the flags of the partitions in the SSD and, as far as I can remember, the only flag in the partitions was msftdata. So, I set the flags to the appropriate values (following the screenshot in the original post) and I was finally able to repair the grub, and log into Windows and install the updates normally.
Software used
Unfortunately, I don't know what software was used to copy the HDD into the SSD, sorry about that. But I believe that gparted, clonezilla as it was pointed out by Thomas Alchinger, or Macrium Reflect Free as suggested by PonJas would be good enough choices.
Comment: +1, Thanks for sharing your experience :-) I understand that there was a lot of work, that could have been avoided if the target drive was at least as big as the source drive. The price for a big enough SSD today is much lower than the cost for fixing these problems (in a commercial context; it might be different at home, when we talk about the budget for your hobby).
Comment: Happy to help! The copy was done by the IT technician, but yes, it seems there was a lot of work due to the SSD being smaller than the HDD. I don't know much about prices but the SSD cost around 110€ (VAT included).


Is possible call a service inside a @Repository?

Question: I´m new with java spring-mvc current I have a @Controller that call a @Repository and I want to use a @Service inside @Repository is it possible or what is the correct way?
I tried just put the Service inside of Repository
   @RequestMapping(value = "/activa-servicio", params={"cupon"}, method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    public String activaServicio(HttpServletRequest request,@RequestParam(value="cupon") String cupon) throws IOException {

        String json=publicDAO.activaServicio(cupon);

        System.out.println(json);
        return json;
    }

@Repository
public class PublicDAO {

    @Autowired
    JdbcTemplate jdbcTemplate;
    EmailService emailService;

 public String activaServicio(String cupon) {
  emailService.getActivationConfirmation();
}

I expect EmailService is fired, but current the EmailService display null exception
Answer: EmailService is null because you never set it. The @Autowired annotation only applies to JdbcTemplate jdbcTemplate.
Also, field injection is discouraged, so your best bet is to use constructor injection. It's also less verbose.
private JdbcTemplate template;
private EmailService service;

@Autowired
public PublicDao(JdbcTemplate jt, EmailService es) {
  this.template = jt;
  this.service = es;
}


PHP error: Expected different insert

Question: I have some PHP code that inserts data into a database. When I echo the table it has inserted the id instead of the category which is in the dropdown list.
The PHP code for the dropdown is:
<select name='category' id=category class="text">
     <option value='' name='option' selected>Select one</option>
<?Php
   require "config.php";// connection to database
   $sql="select * from category ORDER BY `cat_id` ASC"; // Query to collect data

   foreach ($dbo->query($sql) as $row) {
   echo "<option value=$row[cat_id]>$row[category]</option>";
   }
?>
</select>

The PHP code for inserting values is:
<?Php

    $for= $_GET['category']; //Take the value.
    $request= $_GET['option']; //Take the value.

 myquery="INSERT INTO request (`request for category`, `request`) VALUES ('$for','$request')";
 $query = mysql_query($myquery);

Comment: Also, `$_GET['option']` does not work for `Select one` as only the `` name is sent when a form is submitted, not an `` name.
Comment: If you want to insert the `category` and not the `id`, then you need to put the `category` as the value - `echo "$row[category]";` as `$_GET['category']` gets the selected option value.
Comment: Please avoid using `mysql_*` extensions!
Comment: Thanks for the advice Thamilan.
Comment: Post your error message and connection too!]
Comment: There is no error user Saty.
Comment: It wrote error as I expected another insert value
Comment: Post your connection code too!!
Comment: In case your wondering where the activity on this question is coming from [Is it okay to ask for upvotes in a question?](http://meta.stackoverflow.com/q/323847/692942)...
Answer: Because the name of your <select> field is category, so when it is submitted to your insert query, it will insert the id of that category.
So if you want to display the data from your request table instead of the ID, you can use JOIN.
SELECT a.category FROM request a LEFT JOIN category b ON a.request_for_category = b.cat_id

Advice:

Don't use spaces() for column names
Use at least *_real_escape_string() or better yet, prepared statement
Use mysqli_* instead of deprecated mysql_*
Comment: is this mysql or `mysqli`

PHP error: Expected different insert


Custom class iterator following a list of integer indices?

Question: I've got a templated class myClass that owns an instance of std::vector, and I've overloaded the [] operator to take as argument a std::vector<int> of indices on the member vector and return a secondary class mySubset
template <typename _type>
class myClass {
    // ...
    std::vector<_type> data;
    // ...
    class mySubset {
        myClass<_type>* mc;
        const std::vector<int>::iterator &idx;
    public:
        //constructor
        mySubset(myClass<_type> * _m, const std::vector<int>& _idx);
        // input operator overloads (for data and range input)
        template <typename _input_type> mySubset& operator=(const std::vector<_input_type>& _vals);
        mySubset& operator=(const mySubset& _sbst);
    };

public:

    myClass();
    ~myClass();
    // ...
    //acess operator
    mySubset operator[](const std::vector<int>& _idx) { return mySubset(_idx); };
    // ...
    //iterator
    typename std::vector<_type>::iterator begin() {return data.begin();};
    typename std::vector<_type>::iterator end();  {return data.end();  };
    // ...
}

I'm able to get and set values directly with the [] operator, but I'd like to be able to use range-based loops, e.g.
// ...
myClass<float> foo;
// ...
std::vector<int> indices (3);
indices[0] = 3;
indices[1] = 6;
indices[2] = 10;
// ...
foo[indices] = std::vector<float> (3, 0.47);

for (auto& fval : foo[indices]) { /* do stuff*/}

From what I've gathered, I'd need the advance( InputIt& it, Distance n ); to achieve what I want, and add begin() and end() members to mySubset that return an iterator-like type object with the ++ operator incrementing the iterator by looking at the index vector:
class myIterator {
    mySubset * sb;
    std::vector<_type> it; // myClass::data iterator
public:
    myIterator(mySubset * _sb, int pos): sb(_sb) { it = sb->mc->data.begin() + sb->idx[0]; }   ;
    myIterator& operator++() { };
    myIterator& operator!=(myIterator& _other) { };
};

//.. mySubset
myIterator begin();
myIterator end();

But at the moment I'm having trouble understanding what is the actual syntax required to achieve this?
Answer: I'll be lazy.
Go and implement _type& operator[](size_t) and .size() on mySubset.
template<class C>
struct range_for_helper{
  using self=range_for_helper;
  C* c=0;
  std::size_t i = 0;
  self(C* cin, std::size_t idx):c(cin),i(idx){}
  friend bool operator==(self lhs, self rhs){return lhs.i==rhs.i;}
  friend bool operator!=(self lhs, self rhs){return lhs.i!=rhs.i;}
  void operator++(){++i;}
  decltype(auto) operator*(){ return (*c)[i]; }
};

Then add
to mySubset and done.
It isn't a real iterator, but sufficient for for(:) loops.  It could be extended to a real iterator, bit like I said, lazy.
Also :
range_for_helper<mySubset> begin() const { return {this,0}; }
range_for_helper<mySubset> end() const { return {this,size()}; }

just works if your [] is overloaded for const, so that is nice.
Comment: Fair enough, seems like a simple enough solution. However, how exactly is `_type& operator[](size_t)` supposed to return a data value from the index vector size?
Comment: @joaocandre First, `const std::vector::iterator & idx` get rid of `const&` there.  There is no way that is defined behavior in any practical use; you pass a vector into the ctor, probably call begin, that begin iterator expires when the ctor is done.  Second, you can obviously get the nth item, that is what your `operator=` has to do.  Third, `(mc-> data)[idx[i]]`.
Comment: "that begin iterator expires when the ctor is done" well, it makes sense and I was unaware of that. Also, I was looking at `i` as the fixed size of the index vector instead of the *current* index.


C - function returns a pointer to a string from char matrix ONLY use pointers

Question: I need to write a function called MakeString. The function returns a pointer to a string, which contains one word composed of each row of the small matrix in order, so that each line break will be expressed
as a single space between the words In the string. (After the last word there will be no space.)
Inference: In the function there is no use of [], but executes by working with pointers.
Function. In addition, trips should be carried out with the voters, meaning that they will actually move to vote for each other
Whatever it takes, and will not stay in the same location all the time.
 The 'answer' that the function returns, which is a pointer, will be input into a pointer in MAIN.
I tried to do the function, but It NOT like instruction and not good...
#define SIZE 4
static char allocbuf[SIZE][];
static char *allocp = allocbuf;

char matrix[SIZE][SIZE]
{
    {U,N,T,E},
    {C,P,G,X},
    {D,L,A,B},
    {J,T,N,N}
};
char MakeString(int n)  /*return pointer to n charachters*/
{
    if (allocbuf + SIZE - allocp >=n)
    {
        allocp += n;
        return  allocp - n;
    }
    else
        return 0;
}

For example:
Small matrix:
U N T E

C P G X

D L A B

J T N N

pStr = UNTE CPGX DLAB JTNN

Thanks (:
Comment: The only times you can use `[]` in an array declaration is in a function parameter or when declaring an array with an initialization list (the size comes from the number of items in the list).
Comment: What is `allocbuf` supposed to be? An array of strings? Will the strings have a fixed static (at compile-time) size? Or will they need to be dynamically allocated?
Comment: Also, your `MakeString` function doesn't "make" a string. And it doesn't return anything that can be used as a string either. And I really don't see the need for all that pointer arithmetic either, what's wrong with a simple index that's compared to `SIZE`?
Comment: Our lecture force us use pointers. I know it unnecessary.... My function Not good also \: The strings not static BUT dynamically allocated. Must not use [][] ONLY USE POINTERS. @Some programmer dude
Comment: So then `allocbuf` should be an array of *pointers* really? And your `MakeString` function needs to allocate the correct size (not forgetting the string null-terminator) and then return the pointer?
Comment: You right only in the declaration of function of function parameter you can use [][] to initialization list @Barmar
Comment: What is the part talking about voters all about? What does that have to do with this?
Comment: What does this mean: **Whatever it takes, and will not stay in the same location all the time.**
Comment: You need to use `malloc()` in the function to allocate space for the string. It should be `SIZE * (SIZE+1)` bytes long. This allows space for the space character between the words and a null byte at the end.
Comment: Also (and something you should have done from the start), please try to create a [mcve] that replicates the problem you have. Also please read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please [learn how to debug your programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/).
Answer: If I understand your question, you want write a function to read the characters from matrix (a 2D array of char) into an allocated string placing a space between each rows worth of characters and returning the nul-terminated string back to the calling function. You need to do this using pointers and without array [index] notation.
To begin, your declaration of matrix is wrong. E isn't a character, it is a variable. 'E' is a character literal. (note the single-quotes) So a proper declaration of matrix would be:
    char matrix[SIZE][SIZE] = { {'U','N','T','E'},  /* don't use globals   */
                                {'C','P','G','X'},  /* declare in main and */
                                {'D','L','A','B'},  /* pass as a parameter */
                                {'J','T','N','N'} };

(note: simply char matrix[][SIZE] = {{...}}; is sufficient, where the number of rows will be sized based on your initialization)
As noted in the comment, avoid the use of global variables unless absolutely necessary. (very limited cases -- not here). Instead, declare matrix in the scope where it is required and pass matrix as a parameter to any function that needs to process the data. By contrast, defining is constant with #define is perfectly correct, and you should define constants as needed to avoid using magic-numbers in your code.
Since matrix is a 2D array, to pass it as a parameter, you must include the number of columns as part of the parameter passed. You can either declare the parameter as char matrix[SIZE][SIZE] or equivalently as char (*matrix)[SIZE] reflecting the fact that the first level of indirection is converted to a pointer to the first element on access. See: C11 Standard - 126.96.36.199 Other Operands - Lvalues, arrays, and function designators(p3) (paying attention to the 4-exceptions)
Within your makestring() function you must allocate storage of at least SIZE * SIZE + SIZE (space for each character + 3 spaces + the nul-terminating character). Assigning the starting address of your new block of memory to a pointer, and then creating a second pointer to the block will allow you to iterate over it, copying characters to it -- while preserving a pointer to the beginning.
Putting those pieces together, you could do something similar to:
char *makestring (char (*a)[SIZE])
{
    char *str = malloc (SIZE * SIZE + SIZE), *p = str;  /* allocate */
    if (!str) {                         /* validate EVERY allocation */
        perror ("malloc-str");
        return NULL;
    }
    for (int i = 0; i < SIZE; i++) {    /* for each row   */
        if (i)                          /* if row not 1st */
            *p++ = ' ';                 /*    add space   */
        for (int j = 0; j < SIZE; j++)  /* for each char  */
            *p++ = *(*(a + i) + j);     /*    copy to str */
    }
    *p = 0;         /* nul-terminate string */

    return str;     /* return pointer to allocated string */
}

(note: while not an error, C generally avoids the use of camelCase or MixedCase variable names in favor of all lower-case while reserving upper-case names for use with macros and constants.)
Putting it altogether in a short example, you could do:
#include <stdio.h>
#include <stdlib.h>

#define SIZE 4

char *makestring (char (*a)[SIZE])
{
    char *str = malloc (SIZE * SIZE + SIZE), *p = str;  /* allocate */
    if (!str) {                         /* validate EVERY allocation */
        perror ("malloc-str");
        return NULL;
    }
    for (int i = 0; i < SIZE; i++) {    /* for each row   */
        if (i)                          /* if row not 1st */
            *p++ = ' ';                 /*    add space   */
        for (int j = 0; j < SIZE; j++)  /* for each char  */
            *p++ = *(*(a + i) + j);     /*    copy to str */
    }
    *p = 0;         /* nul-terminate string */

    return str;     /* return pointer to allocated string */
}

int main (void) {

    char matrix[SIZE][SIZE] = { {'U','N','T','E'},  /* don't use globals   */
                                {'C','P','G','X'},  /* declare in main and */
                                {'D','L','A','B'},  /* pass as a parameter */
                                {'J','T','N','N'} },
        *str;

    if ((str = makestring (matrix))) {  /* validate call to makestring */
        printf ("str: '%s'\n", str);    /* output string */
        free (str);                     /* free allocated memory */
    }
}

(note: don't forget to free the memory you allocate. While it will be freed on program exit, get in the habit of tracking your allocations and ensuring all blocks you allocate are freed)
Example Use/Output
$ ./bin/makestring
str: 'UNTE CPGX DLAB JTNN'

Memory Use/Error Check
In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.
It is imperative that you use a memory error checking program to insure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.
For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.
$ valgrind ./bin/makestring
==6576== Memcheck, a memory error detector
==6576== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==6576== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==6576== Command: ./bin/makestring
==6576==
str: 'UNTE CPGX DLAB JTNN'
==6576==
==6576== HEAP SUMMARY:
==6576==     in use at exit: 0 bytes in 0 blocks
==6576==   total heap usage: 1 allocs, 1 frees, 20 bytes allocated
==6576==
==6576== All heap blocks were freed -- no leaks are possible
==6576==
==6576== For counts of detected and suppressed errors, rerun with: -v
==6576== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Always confirm that you have freed all memory you have allocated and that there are no memory errors.
Look things over and let me know if you have further questions.
Comment: Thanks (: I tried in my linux eclipse... Not work /: Any idea? @David C. Rankin
Comment: You have an eclipse problem. What compiler is eclipse using? MinGW? VS (`cl.exe`)? Do you have a *Developer Command Prompt* or *MinGW Msys* shell? Let me know and I'll show you how to compile it from the command line (which you should be doing anyway -- that way you would know what to tell eclipse to do....)
Answer: You need to specify the size of allocbuf so it can hold the entire result:
char allocbuf[SIZE * (SIZE + 1)];

There's no need for allocp, because the array name will decay to a pointer when used in calculations. In MakeString, you need to loop over the rows and characters of matrix, copying them to allocbuf.
char *MakeString()
    for (int i = 0; i < SIZE; i++) {
        memcpy(allocbuf + i * SIZE, matrix + i, SIZE);
        if (i < SIZE - 1) {
            // write space between rows
            *(allocbuf + i * SIZE + SIZE) = ' ';
        } else {
            // write null at end
            *(allocbuf + i * SIZE + SIZE) = 0;
        }
    }
    return allocbuf;
}

The instructions don't mention the n argument to MakeString(), so I removed it.
Comment: Thanks (: How can i change it get from user matrix? Does declaration of char allocbuf is on main Or in method MakeString() @Barmar?
Comment: It's a global variable, just like you wrote in the question.
Comment: I put the char allocbuf above the method in the file.c but it not print anything via main.. and I changed it get values char **smallMat \:  I will update all up. Thanks @Barmar
Comment: Don't remove your original code when you update the question, add this new code as an addition at the bottom.


Making low voltage prettier/weatherproof?

Question: I've got a big hole in my exterior wall where several coax and (old) phone cables punch through. It's just... there in the stucco. All of my low voltage wires are just hanging out on the outside wall too and I'd like to clean it up/weatherproof everything a bit.
I will eventually be running ethernet through the wall there as well (the hole's already there so why not) so I didn't just want to seal it up with caulk and walk away. So I have a couple of questions:

Would putting a LB connector or exterior box over the hole in my wall and then running some PVC conduit back to the cable company box be against any kind of national code?
If I use an LB can I mount it sideways as long as I'm caulking behind it and using watertight conduit?
Do conduit straps/surface-mount box screws have to penetrate the wall to a stud or can they just go into the stucco?
I've got one coax run (exiting the cable company box midway on left side) running up to the second floor, pretty close to the electrical weatherhead. Is there a keep out zone I should be aware of if I wanted to put that cable in conduit as well?
Answer: I'd slap up a 6" box, maybe PVC with threaded entries, and then use weathertight screw-in cable clamps to bring each data cable into the box.
And I'd either glue and caulk the back of the box to the wall... or have conduit go through the wall from that box, and fill the rest of the hole.  My concern is animals or insects using the hole as a superhighway.
Comment: @RoscoePyell Yeah, that'd be fine if it's big enough.  My experience buying those styles of weatherproof boxes and clamps is that you're really better off going to the electrical supply on both price and availability.  Home Depot won't have it, or won't be able to find it if the computer says they have it.  They suck at obscura.   OTOH if you're mail-ordering, HD is the top choice.
Comment: So something like [this 2 gang box](https://www.homedepot.com/p/Commercial-Electric-3-4-in-2-Gang-5-Holes-Weatherproof-Box-Gray-WDB575G/300846319?MERCH=REC-_-pipinstock-_-300846371-_-300846319-_-N) and a couple of [these clamps](https://www.homedepot.com/p/Halex-3-4-in-Service-Entrance-SE-Water-Tight-Uf-Connector-90662/100131217) on the bottom?

I assume these [tapcon screws](https://www.homedepot.com/p/Tapcon-3-16-in-x-1-3-4-in-Hex-Washer-Head-Concrete-Anchors-75-Pack-24305/100201596) could be used to secure the box to the wall with some caulk behind/around it to waterproof.


How to update the "last update" date in text files automatically according their modification date in OS?

Question: There are sevaral source files in VHDL. All files have a header which gives the file name, creation date and description among other things. One of these things is the last update date. All files are version controlled in Git.
What happens is that often the files are modified, commited and pushed up. However, the last update date is not updated often. This happens by mistake since so many different files are worked on at different times and one might forget to always change the "last update" part of the file header to the latest date when it has actually been changed.
I want to automate this process and believe there are many different ways to do this.
A script of some sort, must check the last update date in the text file header. Then, if it is different from the actual last modified date that can be accessed through properties of the file in the file-system, the last update date in the text must be updated to the last modified date value. What would be the most optimal way to do this? A Python script, Bash script or something else?
Basically I want to do this when the files are being commited into Git. It should ideally happen automatically but running one line in terminal to execute script is not a big deal perhaps. The check is required on the files that are being commited and pushed up.
Comment: Of course this is possible. I can give you a little start-helping script wirtten in Autoit, if you want.
Comment: Could you provide a testfile with the header datetime information, please.Are you on a Windows machine? I would use Python or on Windows Autoit.
Comment: Line 9 usually says this "-- Last update: 2020-09-28"
Comment: An Autoit script (runs only on Windows) would be ok or does it need to be Python?
Comment: Should the script look for all .vhdl files in a folder and do the check/update?
Comment: I just want to know how this would usually be done, it is possible to write python script, bash script, powershell script and I don't know what else. I am not from software engineering background so will have to figure out how to write the actual script in whatever tool is recommended here. Actually I have found that the solution must be linux specific which means that maybe autoit is not possible. We use Cygwin here.
Answer: I'm not a Python programmer, but I made a little script to hopefully help you out. Maybe this fits your needs.
What the script should do:

Get all files form the path (here c:\Python) which have the extension .vdhl

Loop over the files and extract the date from line 9 via regex

Get the last modified date from the file

If last modified > then the date in the file, then update the file
<code>import os
import re
import glob
import datetime

path = r"c:\Python"
mylist = [f for f in glob.glob("*.vhdl")]
print(mylist)

for i in mylist:
    filepath = os.path.join(path, i)
    with open(filepath, 'r+') as f:
        content = f.read()
        last_update = re.findall("Last\supdate\:\s+(\d{4}-\d{2}-\d{2})", content)
        modified = os.path.getmtime(filepath)
        modified_readable = str(datetime.datetime.fromtimestamp(modified))[:10]
        #print(content)
        #print(last_update)
        #print(modified_readable)
        #print("Date modified:", datetime.datetime.fromtimestamp(modified))
        if (modified_readable > last_update[0]):
            print(filepath, 'UPDATE')
            text = re.sub(last_update[0], modified_readable, content)
            f.seek(0)
            f.write(text)
            f.truncate()
        else:
            print(filepath, 'NO CHANGE')
</code>


When should I use cursor:default?

Question: On a website, text will by default have the cursor:text type which looks like this:

However I've noticed some websites use the cursor:default type on text.

When should cursor:default be used on text?
Stack exchange uses cursor:default on some parts of text, but I cannot work out why cursor:default has not been applied to all non-clickable text.
Answer: Good question. The general rule of thumb is to show the text cursor when a section of the page is expected to be copied. The text cursor provides visual feedback that the user can highlight text or input text. So it should be displayed when the design calls for the user to interact with text.
In your example of the tags text, the user really isn't supposed to interact with that text. It's really a label, and while some labels are helpful to be able to copy, here, it just kind of gets in the way of the same cursor being used to type in the tags directly below. It's one of those nit-picky kind of things, but when used properly, can add nice subtleties to the page.
It harkens back to the age of desktop applications. If you see a regular application with an input box and a label above it describing what the input is for, your user is expecting to interact with the input field, not the label, and so the label doesn't have the text cursor, the input does.

If you're looking for a general rule of thumb, I would say use the text cursor whenever the label (or what have you) might be useful for the user to copy or interact with in some way. Otherwise, if the user is not expected to interact with the text in any way except just reading it, I would stick to the default cursor. The user can still copy the text if they need to, so no need to worry about that.
Comment: I agree, it can be difficult to determine what the user might want to copy. In general, I'd say it's safe to use the text cursor. Things like price, and especially a product title, would probably be copied at one time or another. While things (or labels) like "Tags", or "Email Address," are less likely to be copied. That's why it's a good idea to have a test user base to get ideas back on. A person individually is very unlikely to think of every scenario, and a test base helps see problems that you might not have considered (such as wanting to copy a product title).
Comment: Thanks dude. It's hard to tell what some users might want to copy, for example a product title or a price. Nevertheless this is helpful!

When should I use cursor:default?


Is there an equivalent to Bedrock Edition's /ride command in Java Edition?

Question: For the most part, Minecraft Bedrock Edition has a very limited command supply, and no NBT access from commands. However, Bedrock Edition has gained a unique trick as of the 1.16.100 update: the /ride command. What is it used for? Let the Minecraft Wiki explain:

Used to make entities ride other entities, stop entities from riding, make rides evict their riders, or summon rides or riders.

In Java Edition, the /ride command doesn't exist, which makes it one of the only Bedrock Edition-exclusive commands. While it may be easy to summon stacked entities through commands like these, nothing has been documented yet to make two existing entities ride each other.
Let's show you a few /ride command samples, and the ones that you must find Java Edition workarounds for:

ride <riders: target> start_riding <ride: target> [teleportRules: TeleportRules] [howToFill: FillType]

This command is used to select two existing entities and make them ride on top of each other. rider rides on top of ride, and teleportRules shows whether to make the passenger move to the ride to begin riding, or vice versa. fillRules comes into effect if multiple riders are specified, but we won't need that much detail.
Java Edition equivalent: Unknown. This question's task is for you to find or create a command contraption that will emulate the behaviour above!

ride <riders: target> stop_riding
ride <rides: target> evict_riders

These commands are very similar, so I've grouped them as part of one example. They are used to end rides and make riders dismount from their rides. You either target some passengers or some rides, and use evict riders if you're targeting the rides, or use stop_riding if you're targeting the passengers. The selected entities will dismount from their rides, or evict the rider immediately on top of them.
Java Edition equivalent: Unknown. This question's task is for you to find or create a command contraption that will emulate the behaviour above!

ride <rides: target> summon_rider <entityType: EntityType> [spawnEvent: string] [nameTag: string]
ride <riders: target> summon_ride <entityType: EntityType> [rideRules: RideRules] [spawnEvent: string] [nameTag: string]

These two syntaxes are used if you have either the passenger or the ride, but not both, and want to summon the other and begin a ride.
Java Edition equivalent: If you are working from scratch (no entities at all), you can summon a ride with a passenger on it with one command, like so:
summon cow ~ ~ ~ {Passengers:[{id:"minecraft:pig"}]}

How can one achieve the effects of BE's /ride command using only Java Edition commands?

When creating your JE alternative for syntax #1 above, don't cheat by killing the entity and summoning it as a rider or ride. I need a legitimate move, not a clone and delete.
The official /ride command is restricted to ride combinations available in survival Minecraft. Please do not implement such restrictions on your workaround, because we are already able to summon entities with arbitrary passengers!
If you've found a solution for one of the above, but not all three, please still post the answer to the one you've found! That way, we can all know sooner.
From a post on Reddit on player NBT, modifying player data could potentially kick the player out of the game and force them to log back on. If possible, try to avoid this.
Comment: /data merge entity might help... but also you would summon a new mob tho... so idk.
Answer: 1.19.3 and below
As other commenters have pointed out, something like this is unfortunately close to impossible to make a good solution for. Because passengers is one of those NBT attributes that cannot be modified with commands once the entity has been summoned, the only option is to re-summon the involved entities, for which you'd need to know all the data of said entities that can only be set at summon time (like Passengers or IsBaby) and then copy over the existing entity data to the newly summoned entities (for everything that can be modified like Attributes or Silent). This is likely unreasonable and unfeasible unless you're in a very controlled environment like a mob arena in a map with only very specific entities.
The only option you have for unmounting entities is to put them into water, as that forces an unmount.
1.19.4
As of 23w03a, a snapshot for 1.19.4, the /ride command exists on Java.
Though at the time of writing it is not as powerful as the bedrock command and can only make a target mount a vehicle (partially covers your usecase (1)) as well as makeing an entity unmounts its vehicle (partically covering your usecase (2)).
Answer: You cannot ride a player or a mob without using any mods / plugins. But it's possible for normal mobs using a command.
I am not sure where did i see it or how can you do it.
I only remember where someone made a video about salmon riding on salmon ridinmg on salmon riding on salmon and more.
Answer: Currently in vanilla Java 1.19.2, the only way to do this through commands would be to summon a new entity or modify the data of an existing entity. There is an NBT tag called Passengers which can contain a list of entities riding on the original first entity, however they can be nested together to make large towers of entities if you wish. See https://minecraft.wiki/w/Entity_format#Entity_Format


Will siding with The BOS mess up my supply lines?

Question: During one of the Brotherhood side quests I am supposed to get supplies from a settlement that belongs to the Minutemen and has supply lines to another settlement but when I do that, there is a message saying that this settlement now belongs to the Brotherhood of Steel.
Will I have to setup those supply lines again?
Comment: It sounds like you've already done it. Can you just check if the supply lines are still intact?
Comment: I quick saved, reloaded and walked away from the quest. I guess I can do it again but I was hoping someone had some input.
Comment: I would be surprised if you had to reestablish the supply lines, but I haven't actually tried this scenario. If you try it, please answer and let us know what you found.
Answer: I went and did the quest again but I forgot to grab screenshots. I could still build structures(defense turrets and walls) and I didn't have to re-establish my supply lines.
Comment: +1, Thanks for figuring that out. I can stop ignoring that mission now.
Answer: I came to post that it does not affect your supply lines or the settlements at all (except maybe for its happiness) but then I stumbled upon this reddit post and apparently some people say doing the quest DOES make you completely lose control over it.(i.e. You can't use the workshop or build, hence no more supply lines either I assume)
I don't know if it's a bug that settlements sometimes remain yours or not, but since the only time I did this quest I did NOT lose control of the settlement I can't say for sure.
Comment: I'm not sure if this is really an answer. The link is interesting, but it sounds like they can't decide what causes you to keep or lose control.


help, can't empty my trash folder on external hdd

Question: I've been searching for this problem on the webs but none of the solutions i've found worked for me.
The problem is that I have an external hard drive and the trash folder won't delete.
the complete path of the problem folder:
/media/Elements/.. .Trash-1000/expunged/2969272896
For some reason if i just press delete when that folder is selected it delete's as a normal folder, but it will always reappear.
Deleting the folder in windows won't work either.
There are no files in the folder.
Comment: please add (from terminal) the result of the command `ls -ld` applied to every component of the path... like `ls -ld /media/Elements/.Trash-1000/expunged/2969272896`, `ls -ld /media/Elements/.Trash-1000/expunged/` etc.
Answer: If the trash has nothing else important in it:
rm -rf /media/Elements/.Trash-1000/

You may want to try as root as well:
sudo rm -rf /media/Elements/.Trash-1000/

Another method would be to use srm - it would wipe over the data and remove it. It also shows if it is a hardlink etc.
If you need to install it:
 sudo apt-get install secure-delete

and then
srm -rf /media/Elements/.Trash-1000/

Comment: What if I want to delete only specific files from the trash? Is there any utility to do it correctly or do I have to manually delete the file from both trash subdirectories `files` and `info` (anything else apart that?)?
Comment: Never mind, I have found it. There's a package `trash-cli` that contains several commands for the proper trash management that handles common operations (delete to trash, restore, empty, list, remove from trash).


Issue connecting a spring boot application with elasticsearch 8.6 using spring data

Question: I am new on ElasticSearch, and I would like to have a Spring Boot Application that connects to a database ElasticSearch 8.6, in order to do CRUD operations over an index.
I was trying to do a CRUD application using Spring Boot with ElasticSearch database.
Entity:
@Document(createIndex = true, indexName = "client")
public class ClientEntity {

  public ClientEntity() {
    super();
  }

  @Id
  private String id;

  @Field(type = FieldType.Text, name = "name")
  private String name;

  @Field(type = FieldType.Long, name = "phoneNumber")
  private Long phone;

The repository interface from spring data is:
    import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
    import org.springframework.stereotype.Repository;

    @Repository
    public interface ClientRepository extends ElasticsearchRepository<ClientEntity, String> {

    }

Elastic search config:
    import org.apache.http.HttpHost;
    import org.apache.http.auth.AuthScope;
    import org.apache.http.auth.UsernamePasswordCredentials;
    import org.apache.http.client.CredentialsProvider;
    import org.apache.http.impl.client.BasicCredentialsProvider;
    import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
    import org.elasticsearch.client.RestClient;
    import org.elasticsearch.client.RestClientBuilder.HttpClientConfigCallback;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.elasticsearch.client.ClientConfiguration;
    import org.springframework.data.elasticsearch.client.elc.ElasticsearchConfiguration;
    import     org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

    import co.elastic.clients.elasticsearch.ElasticsearchClient;
    import co.elastic.clients.json.jackson.JacksonJsonpMapper;
    import co.elastic.clients.transport.ElasticsearchTransport;
    import co.elastic.clients.transport.rest_client.RestClientTransport;

    @Configuration
    public class ConfigElasticSearch extends ElasticsearchConfiguration {
      @Bean
      public ElasticsearchTransport getElasticsearchTransport() {
        return new RestClientTransport(getRestClient(), new JacksonJsonpMapper());
      }

      @Bean
      public ElasticsearchClient getElasticsearchClient() {
        ElasticsearchClient client = new ElasticsearchClient(getElasticsearchTransport());
        return client;
      }

      @Override
      public ClientConfiguration clientConfiguration() {
        return ClientConfiguration.builder().connectedTo("localhost:9200")
         .withBasicAuth("user", "my-password").build();
      }

pom.xml:
    <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.7.12</version>
    </parent>

    <properties>
      <java.version>17</java.version>
      <spring-cloud.version>2021.0.5</spring-cloud.version>
      <json-web-token.version>0.9.1</json-web-token.version>
      <org-modelmapper.version>3.1.1</org-modelmapper.version>
    </properties>
    <dependencies>
          <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>${org-modelmapper.version}</version>
          </dependency>
          <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
           </dependency>

           <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
          </dependency>
         <dependency>
            <groupId>jakarta.json</groupId>
            <artifactId>jakarta.json-api</artifactId>
         </dependency>
        <dependency>
           <groupId>com.fasterxml.jackson.core</groupId>
           <artifactId>jackson-databind</artifactId>
        </dependency>

The service that uses the Spring Data repository is the following:

    @Service("clientPersistence")
    public class ClientPersistenceElasticSearchDb {

      @Autowired
      private ClientRepository clientRepository;

      public Stream\<ClientEntity\> findAll() {
       return StreamSupport.stream(this.clientRepository.findAll().spliterator(), false);
      }

      public Optional\<ClientEntity\> findById(String id) {
        return clientRepository.findById(id);
      }
    }

The main configuration for my microservice is:

    @SpringBootApplication
    public class ClientMicroserviceApplication {

      public static void main(String[] args) {
        SpringApplication.run(EmpleadosMicroservicioApplication.class, args);
      }

    }

If I start my microservice, I get the following when starting (and then, the microservice hangs):

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clientPersistencia': Unsatisfied dependency expressed through field 'clientRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientRepository' defined in es.clientmicroservice.dao.clientRepository defined in @EnableElasticsearchRepositories declared on ConfigElasticSearch : Cannot resolve reference to bean 'elasticsearchTemplate' while setting bean property 'elasticsearchOperations'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'elasticsearchOperations' defined in class path resource [es/clientmicroservice/config/ConfigElasticSearch .class]: Unsatisfied dependency expressed through method 'elasticsearchOperations' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'elasticsearchClient' defined in class path resource [es/clientmicroservice/config/ConfigElasticSearch .class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [co.elastic.clients.elasticsearch.ElasticsearchClient]: Factory method 'elasticsearchClient' threw exception; nested exception is java.lang.NoClassDefFoundError: jakarta/json/spi/JsonProvider
I don't know why my class clientPersistence is not build because missing JsonProvider dependency.
Any one could help me?
Thank you in advance!!

Answer: Looking at the Spring Boot version, you are using Spring Data Elasticsearch 4.4.x (which now is out of maintenance). You are using the configuration for the new Elasticsearch Client (org.springframework.data.elasticsearch.client.elc.ElasticsearchConfiguration). The use of the then new client was introduced in 4.4 as a still new and potentially unstable feature.
I am not seeing that you set the jakarta-json.version (see the documentation about configuration of the new client.
Do you special reasons why you override and provide getElasticsearchTransport() and getElasticsearchClient()? These beans are alrea provided by the base class, the only method you need to provide is the one providing the configuration.
Remember that when using that version and connecting to Elasticsearch 8 you need to set the compatibility headers on each request, see the documentation about that.
I'd recommend you use an up to date version of Spring Data Elasticsearch.
Answer: You are using spring-boot-starter-parent:2.7.12, which means you are using spring-boot-starter-data-elasticsearch:2.7.12. If you look at the dependencies, the last one has a dependency on spring-data-elasticsearch:4.4.12. The migration guide for 4.4.x says that you need to manually add some dependencies. I'm not seeing any of those dependencies in the pom.xml you showed in the question.


Find distribution function of a PDF

Question: I'm learning probability and trying to solve the following problem:
Find distribution function of:
$p(x)=\left\{\begin{matrix}
0 & x<2 \\
 \frac{A}{(1-x)^2}&x\geq 2
\end{matrix}\right.$
Could you please tell me how would I do so? What do I need to calculate? Thanks
Comment: Do you know the definition of a [distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) and [how it relates to the density function](https://en.wikipedia.org/wiki/Cumulative_distribution_function#Definition)?
Comment: @angryavian I'm not sure I understand it correctly, it's my first problem regarding distribution function.
Comment: $$\int_{-\infty}^x p(y)dy$$
Comment: @Andrei Could you please show me how would the distribution function look in this case? So that I know how to correctly apply the definition
Answer: From the definition of the distribution,
$$D(x)=\int_{-\infty}^xp(y)dy$$
Since $p$ is $0$ for $x\lt 2$, $D(x)=0$ for $x<2$. For $x>2$ $$D(x)=\int_2^x\frac A{(1-y)^2}dy=\int_2^x\frac A{(y-1)^2}dy$$
Change the variable $z=y-1$, with $dz=dy$. The new integration limits will be $1$ and $x-1$.
$$D(x)=A\int_1^{x-1}\frac{dz}{z^2}=-A\frac 1z\bigg|_1^{x-1}=A\left(1-\frac1{x-1}\right)=A\frac{x-2}{x-1}$$
Notice that $D(\infty)$ must be $1$, so $A=1$
Answer: First calculate $A$ setting
$$\int_2^{\infty}f(x)dx=1$$
Finding $A=1$
Then apply the definition where
$$F_X(x)=\int_2^x\frac{1}{(1-t)^2}dt=\Bigg(1+\frac{1}{1-x}\Bigg)\mathbb{1}_{[2;\infty)}(x)$$
Answer: For a valid pdf the following condition must hold: $\int\limits_{-\infty}^{\infty} p(x) \,dx =1$. That means in your case
$$\int\limits_{2}^{\infty} \frac{A}{(1-x)^2} \,dx =1$$
Simplifiying the equation
$$A\int\limits_{2}^{\infty} (1-x)^{-2} \,dx =1$$
$$A\cdot \left[(1-x)^{-1}\right]_2^{\infty} =1$$
$$A\cdot \left(0-(1-2)^{-1}\right)=1$$
$$A\cdot \left(0+1\right)=1\Rightarrow A=1$$

Find distribution function of a PDF


Objective-C autoreleasepool directive effect variables outside scope.

Question: Let's say I've got c++ function combined with objective-c members.
The function gets std::string and convert it to NSstring*, and work with this variable before leaving...
Should i expect the NSstring* to be released at the end of autoreleasepool scope ?
void myclass::myfunc(context& ctx)
{
    @autoreleasepool
    {
        std::string path = ctx.getData().path;
        NSString *nsPath = [NSString stringWithUTF8String:path.c_str()];
        ... (do something with nsString, Should it be released after leaving the scope ?)
    }
}

Answer: No you don't need to. According to the rule you only need release the variable if you are increasing its retain count in one of the following ways:

Initializing via new or alloc/init.
Copying via copy.
Increasing the retain count via retain.

If you are getting a variable by any means but the above-mentioned ways, you don't own it, and hence you don't need to release it.
The string returned via [NSString stringWithUTF8String:path.c_str()] is autoreleased string. It will be released once the current runloop finishes. So you don't need to release it.
Comment: "It will automatically be released once your current function exits" - unfortunately this is *incorrect*. Under ARC the object will be released *either* when the current auto release pool is emptied, and the systems default pool is emptied at the end of each iteration of the run loop; *or* sooner if ARC determines this is possible, while this may be at the end of the current function it most definitely may not be.
Comment: But `nsPath` is set according to `path.c_str()` using method  `NSString stringWithUTF8String` and i'm not sure if it's perform copy behind scene or not...
Comment: It returns autoreleased object of NSString. So again as per the rule, you don't need to release it.
Comment: ok thanks... perhaps do you know what's happen if the return value of the expression `[NSString stringWithUTF8String:path.c_str()]` is NULL.. does the ARC handle this situation as well ?
Comment: If its nil for some reason then there is no object. No object means no memory.
Comment: @CRD Here I mean that exact thing that you mentioned. I just hide the details. According to ARC, anything that you don't create / copy / retain, you don't own. And when you don't own anything, you shouldn't worry about its retain count. They are supposed to be autoreleased and good only for your current use (i.e in the current function). If you are interesting in using it even after the current scope you can retain/copy it and you becomes the owner. Now its your responsibility to release it.
Comment: @HAK - There might be a language misunderstanding here. "(i.e in the current function)" - no, it can be used beyond the "current function", for example it can be passed to other functions or returned from the current one. The lifetime of the object is not tied directly to the "current function" but to the "current auto release pool". ARC is capable of optimising the lifetime but that is essentially invisible.
Comment: @CRD You are correct. I mentioned function to keep the things simple. But I think its misleading. I will update my answer. Thanks for pointing it out.
Comment: "The string returned via [NSString stringWithUTF8String:path.c_str()] is autoreleased string." There is no guarantee that it is autoreleased (i.e. that it ever goes into the autorelease pool) in ARC.
Comment: "If you are getting a variable by any means but the above-mentioned ways, you don't own it, and hence you don't need to release it." Just because you don't see a retain doesn't mean that ARC isn't retaining what you get from that call when you assign it to the local variable. But the programmer shouldn't be worried about retains and releases in ARC anyway.


Twilio SMS Webhooks and Group Text Messages

Question: Is it possible to maintain both group text messages and single text messages with users and keep them separate? I understand there is no concept of a group message per se, but wanted to see if any recent advances in tech has made this possible with Twilio or other providers.
In short, I am creating a POC where a user inside an iOS App can send invoke an API call to my backend application. This application receives a phone number from someone's contact list, and then connects to Twilio to send the SMS message to that target user.
When the user replies, I was researching Twilio Web hooks to receive the message, and then save it in the database. The originating user, then, would be able to see the message on a screen.
I would guess that when a user responds to the twilio message, the only metadata that comes in is their message and phone number, so the "foreign key" is the phone number.. Thus when I save it in my database, I have their phone number and message.
This works up until someone decides to target two or more people in an SMS message using my API, and then target one of those people individually. For example they select me as a sole recipient, and then select me and someone else as a group text message.
In this case, how could my system/Twilio differentiate between if I was responding to the group message, or to the single message?
Any ideas or work arounds? Maybe another technology? Thanks!
Answer: I wanted to provide an answer to this in case anyone else was looking into this.
Essentially you pay 3 cents (0.03) per month per active user in each group. Basically you buy phone numbers for each group chat you need.
https://www.twilio.com/conversations/pricing
So if you're doing a million group chats obviously it can get costly, but for simple POCs this isn't the end of the world.
Enjoy!
Answer: Group texts (at least those started by Android's Messages app & Google Voice) are actually Group MMS.  In my Twilio messages webhook receiver, I get extra headers OtherRecipients0 - OtherRecipientsN which can be used to disambiguate one group text from another or another 1:1 SMS message.


How to use Firebird transaction isolation levels with UIB?

Question: According to documents there are four transaction isolation levels in Firebird. However, as far as I know, there's no explicit isolation level selection in uib library (TUIBTransaction), but bunch of options for transactions. How I should use those? Is there documentation somewhere?
Comment: Quoting UIB: `const
  TRDefault                 : TTransParams = [tpConcurrency,tpWait,tpWrite];
  TRSnapShot                : TTransParams = [tpConcurrency, tpNowait];
  TRReadCommitted           : TTransParams = [tpReadCommitted, tpRecVersion, tpNowait];
  TRReadOnlyTableStability  : TTransParams = [tpRead, tpConsistency];
  TRReadWriteTableStability : TTransParams = [tpWrite, tpConsistency];`
Comment: The document you link to does not actually say that Firebird has four isolation levels, it says that the SQL standard defines four, there is no direct mapping to the way Firebird handles this.
Comment: You're right. So to re-phrase: I'm looking for documentation for all those options in UIB and how they are related to isolation levels.
Answer: These bunch of options are what will change the isolation level. As @Arioch said in his compact comment, you can change the isolation level changing the property Options that is of type TTransParams. This is a set of TTransParam as below.
 // Transaction parameters
TTransParam = (
{ prevents a transaction from accessing tables if they are written to by
other transactions.}
tpConsistency,
{ allows concurrent transactions to read and write shared data. }
tpConcurrency,
{ Concurrent, shared access of a specified table among all transactions. }
{$IFNDEF FB_21UP}
tpShared,
{ Concurrent, restricted access of a specified table. }
tpProtected,
tpExclusive,
{$ENDIF}
{ Specifies that the transaction is to wait until the conflicting resource
is released before retrying an operation [Default]. }
tpWait,
{ Specifies that the transaction is not to wait for the resource to be
released, but instead, should return an update conflict error immediately. }
tpNowait,
{ Read-only access mode that allows a transaction only to select data from tables. }
tpRead,
{ Read-write access mode of that allows a transaction to select, insert,
update, and delete table data [Default]. }
tpWrite,
{ Read-only access of a specified table. Use in conjunction with tpShared,
tpProtected, and tpExclusive to establish the lock option. }
tpLockRead,
{ Read-write access of a specified table. Use in conjunction with tpShared,
tpProtected, and tpExclusive to establish the lock option [Default]. }
tpLockWrite,
tpVerbTime,
tpCommitTime,
tpIgnoreLimbo,
{ Unlike a concurrency transaction, a read committed transaction sees changes
made and committed by transactions that were active after this transaction started. }
tpReadCommitted,
tpAutoCommit,
{ Enables an tpReadCommitted transaction to read only the latest committed
version of a record. }
tpRecVersion,
tpNoRecVersion,
tpRestartRequests,
tpNoAutoUndo
{$IFDEF FB20_UP}
,tpLockTimeout
{$ENDIF}
);

Since Interbase 6.0 code "opensourced", the documentation for the API hasn't changed much. So if you want an explanation about any of them the docs you are looking are in Interbase manuals.
You can get them here https://www.firebirdsql.org/en/reference-manuals/
Below I'm quoting Ann Harrison in this link to an quick explanation on the usual options used:

isc_tpb_consistency can cause performance problems due the fact that it's locking tables and possibly excluding concurrent access.
isc_tpb_concurrency is the design center for Firebird. Readers don't
block writers, writers don't block readers, and both get a consistent
view of the database.
isc_tpb_read_committed + isc_tpb_rec_version + isc_tbp_read_only give
inconsistent results and occasionally produces an error on a blob
read*, but unlike other modes, it does not block garbage collection so
it's a good mode for long running read transactions that don't have to
get the "right" answer.
isc_tpb_read_committeed + isc_tpb_rec_version has the same performance
as isc_tpb_concurrency, but gets inconsistent results - the same query
run twice in the same transaction may return different rows.
isc_tpb_read_committed + isc_tpb_no_rec_version + isc_tpb_wait is
slower than other modes because it will wait for a change to be
commited rather than reading the newest committed version. Like all
variants of isc_tpb_read_committed, it does not produce consistent
results.
isc_tpb_read_committed + isc_tpb_no_rec_version + isc_tpb_no_wait
gives lots and lots of deadlock errors because every time a reader
encounters a record that's being changed, it returns an error.

NOTE: I hope that you can see that, beside the parameters are not named equally, it's not that hard to understand if you remove the "isc_tpb_" part.