Q: OpenCL: Blur image with Gaussian filter, Gaussian blur I have gaussian filter mask nxn computed for n = 5. That looks like this:
int gauss5[] = {
    1, 4, 7, 4, 1,
    4, 20, 33, 20, 4,
    7, 33, 55, 33, 7,
    4, 20, 33, 20, 4,
    1, 4, 7, 4, 1
};

int gauss5_summ = 331;

After computation in opencl image become darker. What is the reason?
size_t global_wblur[2];
size_t local_wblur[2];

global_wblur[0] = h;
global_wblur[1] = w;

local_wblur[0] = local_wblur[1] = 32;

err = clEnqueueNDRangeKernel(queue, cl_img_gaussian_blur, 2, NULL, global_wblur, local_wblur, 0, NULL, NULL);

if (err != CL_SUCCESS) {
   fprintf(stderr, "error: clEnqueueNDRangeKernel() blur %d %s\n", err, cl_strerror(err));
   exit(EXIT_FAILURE);
}

kernel source:
 __kernel void cl_img_gaussian_blur(__global const uchar *gray, __global uchar *out, __global const uchar *gbox, uint n, uint sum, uint w, uint h)
{
    int i, j, offset;
    uint x, y, summ;

    y = get_global_id(0);
    x = get_global_id(1);

    offset = n/2;

    /* ignore border pixels
     */
    if (y - offset < 0 || y + offset > h || x - offset < 0 || x + offset > w) {
        out[y*w + x] = gray[y*w + x];
        return;
    }

    summ = 0;

    for (j = -offset; j <= offset; j++) {
        for (i = -offset; i <= offset; i++) {
            summ += gray[(y + j)*w + x + i]*gbox[(j + offset)*n + i + offset];
        }
    }

    out[y*w + x] = summ/sum;
}

Blured images:
dark(opencl) -- https://github.com/apetrunev/imgalg-opencl/blob/master/dark.png
normal -- https://github.com/apetrunev/imgalg-opencl/blob/master/test-blur/out.png

A: You said that the gbox data is initialized like:
clEnqueueWriteBuffer(queue, gauss_buf, CL_FALSE, 0, 5*5, gauss5, 0, NULL, NULL);

That is wrong, since you are copying 1/4th of the real amount of memory. The proper way is:
clEnqueueWriteBuffer(queue, gauss_buf, CL_FALSE, 0, 5*5*sizeof(cl_int), gauss5, 0, NULL, NULL);

Otherwise, the rest is 0s, leading to a low value in the output.


Q: A Basic Question of Continuous Time Macroeconomic Model (Variation of Constant to Solve an ODE) I am going through the continuous time macro slides by Ben Moll (link is: https://benjaminmoll.com/wp-content/uploads/2019/07/Lecture2_ECO521.pdf), when deriving New keynesian model in continuous time, we finally obtained the following ODE (see page 15 of his slides):
$$
\dot{\pi}=\rho \pi - MR(t)
$$
where $\pi$ is the inflation rate, $\rho$ is the subjective discount rate, and $MR(t)$ is some terms on marginal revenue (also function of $t$). The solution to this ODE is
$$
\pi=\int_{t}^\infty e^{-\rho(s-t)}MR(s)ds
$$
When I try to solve this ODE with variation of constant, I assume that $\pi=e^{\rho t}f(t)$, I will obtain:
$$
f'(t)=-e^{-\rho t} MR(t)
$$
I understand that $f(t)=\int_{t}^\infty e^{-\rho s}MR(s)ds$ is a solution to this function, but clearly there should be some initial condition to pin that down which I failed to find. In this case, it is that $\lim_{t\rightarrow\infty}f(t)=0$, but does this condition has a clear macroeconomic implication? Like no Ponzi game, or excluding growth path to explode to infinity?

A: As $
\dot{\pi}=\rho \pi + MR(t)
$
is a linear ODE, the solution ca be stated as
$$
\cases{
\dot{\pi}_h=\rho \pi_h\\
\dot{\pi}_p=\rho \pi_p + MR(t)\\
\pi = \pi_h + \pi_p
}
$$
as $\pi_h = c_0 e^{\rho t}$ now making $\pi_p = c_0(t) e^{\rho t}$ after substitution into the complete ODE we have
$$
\dot c_0(t)e^{\rho t}+\rho c_0(t)e^{\rho t} = \rho c_0(t)e^{\rho t} + MR(t)
$$
so $\dot c_0(t) = e^{-\rho t}MR(t)$ and then $c_0(t) = \int_0^t e^{-\rho\tau}MR(\tau)d\tau$ then
$$
\pi = \pi_h + \pi_p = \left(c_0+\int_0^t e^{-\rho\tau}MR(\tau)d\tau\right)e^{\rho t}
$$
here distinctly $c_0$ is a constant to be assigned according to initial (or final) conditions.

A: The condition which gives you the particular solution you've presented is that $\ e^{-\rho t}\pi(t)\rightarrow0\ $ as $\ t\rightarrow
\infty\ $ (or something which implies this, such as that $\ \pi(t)\ $ remains bounded as $\ t\rightarrow
\infty\ $). The general solution of your differential equation is
$$
\pi(t)=\pi(0)e^{\rho t}-\int_0^te^{-\rho(s-t)}MR(s)ds\ ,
$$
and so $\ \lim_\limits{t\rightarrow\infty}e^{-\rho t}\pi(t)=\pi(0)-\int_0^\infty e^{-\rho s}MR(s)ds\ $.  For this to be zero we must have $\ \pi(0)=\int_0^\infty e^{-\rho s}MR(s)ds\ $, which then gives
\begin{align}
\pi(t)&=\int_0^\infty e^{-\rho(s-t)}MR(s)ds-\int_0^te^{-\rho(s-t)}MR(s)ds\\
&=\int_t^\infty e^{-\rho(s-t)}MR(s)ds\ .
\end{align}


Q: How can i execute a python script using java? I'm trying to integrate a python script in java. I want my java program to be able to execute my python script
I tried to code a class named PythonCaller made to execute a test python script
package pythontest;

import java.io.*;
public class PythonCaller {

    public static void main(String[] args) throws IOException{
        // TODO Auto-generated method stub
            // set up the command and parameter
            String pythonScriptPath = "D:\\Programmes\\test.py";
            String[] cmd = new String[2];
            cmd[0] = "D:\\Programmes\\python.exe"; // check version of installed python: python -V
            cmd[1] = pythonScriptPath;

            // create runtime to execute external command

            Process pr = Runtime.getRuntime().exec("python D:/Documents/Télécom/Programmation/workspace python/test.py");
            System.out.println("adhi");
            // retrieve output from python script
            BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            System.out.println(bfr.readLine());
            String line = "";
            try {
                while((line = bfr.readLine()) != null) {

            // display each output line form python script
            System.out.println(line);
            System.out.println("daiuh");
            }
            }
                catch(IOException e) {
                    System.out.println("Exception in reading output" + e.toString());
                }

    }
    }

When i execute it, it appears that bfr.readLine() returns null
Here is the script in test.py :
print("aiujadh")
print("f")

what i dont understand is that i did tests with the exact same code before, and it worked. I changed it because it failed to read the lines that were not "prints". Then i moved back to the working code, and it doesnt work anymore. I looked at similar topics on the internet, and i do not understand why my code doesn't work.
Can somebody try to explain me pls ?


Q: C++ reliance on argument to const reference not changing Please consider the following code:
void func1(const int &i);
void func2(int i);

void f()
{
  int a=12;
  func1(a);
  func2(a);
}

Compiled with g++ 4.6 with -O3, I can see that the compiled re-reads the value of "a" between the function calls. Changing a's definition to "const int", the compiler doesn't do that, and instead simply loads immediate value "12" into edi. The same is true if a is not const, but I change func1's signature to accept by value.
While not a bug in the code generation, this is still weird behavior. Being as it is that func1 made a commitment not to change a, why should the compiler's code change based on whether a is const or not?
Edit: Some skeptics claim that I might be reading the code wrong. The above code produces the following with -S compilation:
_Z1fv:
.LFB0:
        .cfi_startproc
        subq    $24, %rsp
        .cfi_def_cfa_offset 32
        leaq    12(%rsp), %rdi
        movl    $12, 12(%rsp)
        call    _Z5func1RKi
        movl    12(%rsp), %edi     <-- Rereading a
        call    _Z5func2i
        addq    $24, %rsp
        .cfi_def_cfa_offset 8
        ret
        .cfi_endproc

Changing a to const produces:
_Z1fv:
.LFB0:
        .cfi_startproc
        subq    $24, %rsp
        .cfi_def_cfa_offset 32
        leaq    12(%rsp), %rdi
        movl    $12, 12(%rsp)
        call    _Z5func1RKi
        movl    $12, %edi          <-- Use immediate value
        call    _Z5func2i
        addq    $24, %rsp
        .cfi_def_cfa_offset 8
        ret
        .cfi_endproc

A: In C++, const is really just logical constness and not physical constness. func1 can do a const_cast and modify i. const is like the safety of a gun - you can still shoot yourself in the foot, but not by accident.
As T.C. and juanchopanza have pointed out in the comments, casting away the constness of an object and modifying it is UB. Quoting from "Notes" here :

Even though const_cast may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const or to access an object that was declared volatile invokes undefined behavior.

A: Summing up the answers, I think this explains it best:
It is legal to take a const reference to a non-const variable, and then cast away the constness. Therefore, the compiler in the first case cannot assume that func1 will not change a.
It is undefined what happens if you cast away the constness to a variable declared const. The compiler in the second case may assume that func1 will not cast away the constness. If func1 does cast away the constness, func2 will receive the "wrong" value, but that's just one consequence of undefined behaviour.


Q: Asymptotics for the number of partitions of $n$ into odd prime parts Hello!
I am interested in the asymptotic behavior of the function $p_o(n)$ defined as the number of partitions of $n$ into odd prime parts A099773 - http://oeis.org/A099773 .
I couldn't find any paper or book studying the mentioned quantity but the amount of literature available to me is quite limited and I am wondering if someone could tell me what the asymptotic behavior of $p_o(n)$ is and perhaps point out a relevant reference for me to read.
Thanks!

A: Flajolet and Sedgewick, Analytic Combinatorics (link goes to free, legal downloadable PDF of book), section VIII.6 treats the asymptotics of various types of partitions. They get that the number of partitions of $n$ into prime parts, which they denote $P_n^{(\Pi)}$ (and which is A000607) satisfies $\log P_n^{(\Pi)} \sim (2\pi/\sqrt{3}) \sqrt{n/\log n}$ (Here $f(n) \sim g(n)$ has the usual meaning $\lim_{n \to \infty} f(n)/g(n) = 1$.)
I believe (but have not explicitly checked) that if you disallow any finite number of primes this asymptotic formula still holds; in particular it should hold in the case you're asking about.
Edited to add: The logarithmic growth rate comes from a saddle-point estimate which can in turn be derived from the rate of growth of $\prod_{n \ge 1} 1/(1-z^{p_n})$ (where $p_n$ is the $n$th prime) as $z \to 1^-$ along the real axis. As stated after the equation (73) in F&S, p. 580,
$$ \sum_{n \ge 1} e^{-tp_n} \sim {t \over \log t} $$
and it's from this that the asymptotic result is derived. (Note that $z \to 1^-$ corresponds to $t \to 0^+$.) But if we omit the single term $e^{-2t}$ from that sum it won't change the asymptotic behavior at 0.
This isn't a full proof, though. The result is also a little bit counterintuitive, since one expects that a random partition of $n$ into primes, for large $n$, will contain at least one 2, and therefore leaving the 2s out should reduce the count considerably. But on the logarithmic scale this appears to be negligible.

A: I think I found the answer I was looking for in some old paper by Erdos. http://www.renyi.hu/~p_erdos/1942-02.pdf
On page 448 he says:
Let $a_1 < a_2 < ...$ be an infinite sequence of integers of density $\alpha$ such that the a's have no common factor. Denote by $p'(n)$ the number of partitions of $n$ into the a's. Then $$\log(p'(n)) = c(\alpha n)^{1/2}.$$ where $c = \pi \sqrt{\frac{2}{3}}$
I just have to make sure what precisely he meant with the term density as in the classical sense http://en.wikipedia.org/wiki/Asymptotic_density density of a sequence is defined as a number and in this case the asymptotic identity he derived makes no sense. If someone knows what is the precise definition of density in this case, let me know it as a comment please!


Q: Sonar plugin postjob measure I have a sonar plugin that post a comment in gitlab when there is new sonar issues in a commit. I would like to add difference of code coverage and code duplication in the comment.
This is made by making a sonar plugin based on PostJob.
The issues are recovered by injection of ProjectIssues in the constructor.
Is there a way to recover the Measures in the post job?  I saw that changed in sonar 5.2 but there is no real explanation on how to proceed to read measures.
Thank you for any help.

A: if the ProjectIssues or PostJobContext have no data you are looking for,  you can use the web API rest:
WsRequest wsRequest = new GetRequest("api/...");
but beware the last measures will not be computed at the moment of @BatshSide, you have to wait for the Compute Engine to finish his work.  So as you cannot wait in 'BatchSide',  look for moving your plugin under @ComputeEngineSide


Q: brain-teaser R problem - programming problem solving in R I am trying to write a function to solve a novel problem:
Given the following data:
S = c(19, 10, 12, 10, 24, 25, 22)
k = 4

I am trying to calculate a function. I want to print the maximal subset of S in which any sum of 2 numbers in S' is not evenly divisibly by k
So one answer might be S' = [10, 12, 25] and the other could be S' = [10, 22, 24].
Another example:
if S = {1, 7, 2, 4} and K = 3
Then
1 + 7 = 8
1 + 2 = 3
1 + 4 = 5
7 + 2 = 9
7 + 4 = 11
2 + 4 = 6

That is S' = {1, 7, 4} and will never sum to a multiple of  k = 3

A: There is a linear time algorithm for this. This algorithm is well explained by orezvani in this post on Computer Science section of stackexchange.
I translated the orezvani pseudo code in R:
max_subset<-function(S,K){
  R <- S %% K
  Res <- c()
  for(k in 1:(ceiling(K/2)-1)){
    index_k = which(R==k)
    index_K_k = which(R==(K-k))
    if(length(index_k) >= length(index_K_k)){
      Res <- c(Res, S[index_k])
    }else{
      Res <- c(Res, S[index_K_k])
    }
  }
  print(R)
  Res <- c(Res, S[which(R==0)][1])
  if(K %% 2 == 0){
    Res <- c(Res, S[which(R==(K/2))][1])
  }
  return(Res)
}

I tried with different example:

*

*with S <- c(1, 7, 2, 4) and K = 3 give 1 7 4;

*with S <- c(3, 17, 12, 9, 11, 15) and K = 5 give 11 17 12 15

*with S <- c(3, 7, 2, 9, 1) and K = 3 give  7 1 3

*with S <- c(19, 10, 12, 10, 24, 25, 22) and K = 4 give 25 12 10
In order to be more understandable I tried to be as similar as possible to the pseudocode, probably my solution could be optimized using R language specific features.


Q: The GHZ-State in conflict with local realism Consider three, with respect to their polarisation, entangled particles in the following state:
$|\psi\rangle = \frac{1}{\sqrt2}(|H\rangle_1|H\rangle_2|H\rangle_3 + |V\rangle_1|V\rangle_2|V\rangle_3)$
In the book I read (The Physics of Quantum Information: Quantum Cryptography, Quantum Teleportation, Quantum Computation - Anton Zeilinger) it is stated that from the point of local realism, if particle 1 is measured to have horizontal polarisation, the other two particles must have opposite circular polarisation and if particle one is measured to have vertical polarisation the other two particles are ident in circular polarisation.
I can only obtain this statement, if I change basis of two particles to the circular polarisation state basis. This basically means, I use the superposition principle and therefore a quantum mechanical description. Is this really legitimate? Is there any way of seeing this in a classical image?

A: Since  $|H\rangle=  \frac{1}{\sqrt2}(|R\rangle + |L\rangle)$
and $|V\rangle=  \frac{1}{i\sqrt2}(|R\rangle - |L\rangle)$ the state
$|\psi\rangle = \frac{1}{\sqrt2}(|H\rangle_1|H\rangle_2|H\rangle_3 + |V\rangle_1|V\rangle_2|V\rangle_3)$
and the state $\frac{1}{\sqrt2}(|H\rangle_1
\frac{1}{\sqrt2}(|R\rangle_2 + |L\rangle_2) \frac{1}{\sqrt2}(|R\rangle_3 + |L\rangle_3)$
 + $|V\rangle_1
\frac{1}{i\sqrt2}(|R\rangle_2 - |L\rangle_2)
\frac{1}{i\sqrt2}(|R\rangle_3 - |L\rangle_3))$
are exactly the same state, just like writing a vector in two different coordinate systems is the same vector.
Some people use the word superposition to make it sound like something deep is going on. The reality is much much simpler, systems are vectors in a vector space (a particular kind of a vector space called a Hilbert space that has an inner product that gives it nice properties). And you are free to use any basis you want for a vector space.
So we can expand out $\frac{1}{\sqrt2}(|H\rangle_1
\frac{1}{\sqrt2}(|R\rangle_2 + |L\rangle_2) \frac{1}{\sqrt2}(|R\rangle_3 + |L\rangle_3)$
 +$ |V\rangle_1
\frac{1}{i\sqrt2}(|R\rangle_2 - |L\rangle_2)
\frac{1}{i\sqrt2}(|R\rangle_3 - |L\rangle_3))$ to get $\frac{1}{2\sqrt2}(|H\rangle_1
(|R\rangle_2 + |L\rangle_2)(|R\rangle_3 + |L\rangle_3)$
 -$ |V\rangle_1
(|R\rangle_2 - |L\rangle_2)
(|R\rangle_3 - |L\rangle_3)),$ which equals
$\frac{1}{2\sqrt2}(|HRR\rangle+ |HRL\rangle+ |HLR\rangle+ |HLL\rangle$ $-|VRR\rangle+ |VRL\rangle+ |VLR\rangle- |VLL\rangle)$
Which does not match what you said, each possibility (RR, RL, LR, LL) is equally possible if you project onto the first particle being $|H\rangle$ or onto the first particle being $|V\rangle.$
And your whole statement seemed a little weird in that it makes a giant distinction between horizontal and vertical, as if the universe cares whether you tilt your head 90 degrees.
Let's investigate what happens if you are in the state $|\psi\rangle = \frac{1}{\sqrt2}(|H\rangle_1|H\rangle_2|H\rangle_3 + |V\rangle_1|V\rangle_2|V\rangle_3)$
  and you project onto the first particle being $|R\rangle$ or $|L\rangle.$
Like all situations with vectors, computing a projection can be easier if you choose the basis aligned with the projection. So let's write that same vector $|\psi\rangle = \frac{1}{\sqrt2}(|H\rangle_1|H\rangle_2|H\rangle_3 + |V\rangle_1|V\rangle_2|V\rangle_3)$
 In a basis with all $R$ and $L$ so we can jump straight to $\frac{1}{2\sqrt2}(|HRR\rangle+ |HRL\rangle+ |HLR\rangle+ |HLL\rangle$ $-|VRR\rangle+ |VRL\rangle+ |VLR\rangle- |VLL\rangle)$ since that does two out of three of them. Then we just need to replace the $H$ for particle one with some $R$ and $L.$
So $\frac{1}{2\sqrt2}(|HRR\rangle+ |HRL\rangle+ |HLR\rangle+ |HLL\rangle)$ becomes
$\frac{1}{4}(|RRR\rangle+ |RRL\rangle+ |RLR\rangle+ |RLL\rangle$+$
|LRR\rangle+ |LRL\rangle+ |LLR\rangle+ |LLL\rangle).$
And similarly $\frac{1}{2\sqrt2}(-|VRR\rangle+ |VRL\rangle+ |VLR\rangle- |VLL\rangle)$ becomes $\frac{1}{4i}(-|RRR\rangle+ |RRL\rangle+ |RLR\rangle- |RLL\rangle$+$
|LRR\rangle- |LRL\rangle- |LLR\rangle+ |LLL\rangle).$
And once again every possibility happens with equal frequency.
So I can't get your results. Maybe I made a mistake. Or, since you mentioned something about realism it is possible that by realism your text meant "doing things wrong."
It is unfortunate that this happens often enough that I have to entertain the possibility.  There are perfectly fine realist ways to do quantum mechanics correctly. All you need to be a realist and do things correctly is to have a thing that determines what happens and does so in a proper way that agrees with experiments.
Sometimes people think this can't be done because they imagine ways to be a realist that they want to pretend is general enough and then show that those don't work. Instead of actually looking at what people that make correctly functioning realist pictures do.  For instance, if you have a spin degree of freedom it is entirely possible to get correct answers by having a spatial wavefunction that has values that aren't just complex numbers but are spin valued and then have it evolve according to the evolution equations.
People that make realist models that also want to do it correctly actually do this.
People that want to pretend you can't be a realist pretend people don't do that. They pretend like a realist's goal must be to assign an up/down left/right clockwise/counterclockwise etcetera choice for each possible direction and type of spin measurement. But the evolution equations are quite clear about describing an evolving wave that has a larger spin degree of freedom, so a realist that wants to do it correctly models that (or models something equivalent if they'd rather).
Why would I want to assign a $\pm 1$ to a bunch of different directions and types of measurements when that technique doesn't model what we actually observe? Why would anyone assume that people do except to show they shouldn't? It's good to tell people not to do that. But instead of being a realistic about assigning $\pm 1$ to a bunch of different directions and types of measurements you can be a realist about a wave in configuration space that has spin values that evolves according to evolution equations that give experimentally confirmed results.
For instance you can realistically model a polarization measurement by looking at a differential beam deflection that alters the spin as the beams separate and does it in a wave where the amount of beam going into each separation is proportional to the amount of that type of spin that was in the incoming spin. Why? Because that's what we actually do and observe. But then which part of the beam ends up in which of the separated beams will depend on exactly what equipment you set up and how you ran the experiment. But that is what really happens, it isn't failing to be a realist to be realistic.
But someone that doesn't want to be a realist and is just trying to scare you into not being one either might (incorrectly) claim that the result shouldn't depend on the details of how you set up your measurement. But it does matter. And someone telling us we shouldn't do things we have to do in order to do it correctly is someone that is setting people up for failure.
There is a whole research area where you make restrictions on what you are allowed to do, then show that it doesn't work. You can learn things that way, but the more time you spend working with wrong systems the more your intuition is bent towards thinking about things in incorrect ways. And everyone will keep making up their own new ways to do things wrong because wrong things don't build on older wrong things.
If you learn to do things correctly, your intuition can start to help you. And you can build on it in the sense that at the worst you get multiple ways to do things to be able to check your work. And it might get used again since people like to do things correctly. So it is empowering.
I would not suggest learning about alleged realism from someone that doesn't use realist models to do correct physics.  If the realistic model is nonlocal, so be it. If the realist model has the results depend on exactly how you did your measurement, so be it. But if it gives wrong results, don't even call it realist, call it wrong. And you don't have to use realist models explicitly, but of course if someone watches you do the math they could always make a model that has that math be a realistic model of how it behaves.
Don't get mad at them if they do so (and aren't making you do it too). Don't freak out if it is nonlocal or depends on the context the subsystem is placed in on the context of how it interacts.  After all, if they aren't forcing you, why care what they do, and why should they listen to you about what to do if the things you tell them would make them get wrong answers and their methods get right answers.
And the real problem with all the acrimony is that two methods that make the same predictions aren't really very different. It simply isn't worth fighting over. One might be easier to remember, another easy to visualize, one easier to learn first, another easier to compute with, and another might be faster to compute with or easier to take limiting cases or more stable computationally. There are so many reasons why one method might be better in a particular situation, so different things that give the same answers never have to be enemies.
Just don't read too much into the fact that different things can make he same predictions. If they make the same predictions they are potentially equally good. The only reason to favor one in a particular situation would be if it helps in that particular more than the cost of switching and learning.
If you asked the soft question about how to decide what to learn or teach, then clearly you want to weigh the efficiency of teaching, access to prior literature, ability to communicate results, ease of use, whether it creates barriers or misunderstandings, etc.
And that's why it can be good to look at a correct way of doing Physics as merely telling you how to make your predictions, but if it starts to go meta and claim that its way is the only way to make correct predictions then that has veered away from telling you what predictions to make and is telling you how you must make them.  Must make is different than can make.
So when you study quantum mechanics, pay attention to theories that tell you how you can make predictions. Focus on how to make them correctly and how to use theories that make correct predictions. If your theory has a limited domain of validity, know the limits.  But if you veer off into someone telling you that their way is the only way then watch out. Sure, they might be warning you about the danger of careless mix and match, like taking part of one system and part of another, for instance you wouldn't want to use two coordinate systems and just throw coefficients from both systems around without regard for when they are coming from which.
But if they instead are really trying to tell you about other methods, stop. Ask yourself if it matters. Does it affect how you use this system, are they warning you about a domain of validity? Or are you starting to learn a new method, in which case separate the two methods and learn the new method properly and from a good source. Not every source is a good source for every method.
And learning about realism should be done from a source that knows how to be realist and still agree with experimentally confirmed results. Otherwise what is the point? You probably aren't trying to learn how to do things wrong.


Q: Pinescript issue between local and global scope if (barstate.islast)
    myLine = line.new(x1=bar_index[SHI], y1=rsi[SHI],
         x2=bar_index[FHI], y2=rsi[FHI], color=color.lime)

    line.set_extend(id=myLine, extend=extend.right)

alertcondition(condition=crossover(rsi, myLine), title="RSI breakout", message="RSI crossed The Line")

I'm drawing a line between certain points on RSI I named the line myLine and now I want to add an alert that fires when RSI passes thru that line.
The issue is I can't declare alertcondition inside if statement local scope and also I can't access myLine since it is in the local scope of the if statement, what shall I do in this case?

A: This will solve the myLine access problem.
However, it doesn't solve your crossover() problem, because that function expects 2 series as arguments.
You're providing a series (rsi) and a line object (myLine), which will result in an error.
I've commented out that line.
//@version=4
study("Test", shorttitle="TST")

var line    myLine      = line.new(na, na, na, na, color=color.lime, extend=extend.right)
var int     SHI         = 30
var int     FHI         = 20

rsi = rsi(close, 14)

if (barstate.islast)
    line.set_xy1(myLine, bar_index[SHI], rsi[SHI])
    line.set_xy2(myLine, bar_index[FHI], rsi[FHI])

plot(rsi)
// alertcondition(condition=crossover(rsi, myLine), title="RSI breakout", message="RSI crossed The Line")


Q: Windows Firewall how to allow only Remote Desktop from ip range like 118.102.*? I would like to limit remote desktop to my Windows Server 2008 by only allowing ip from a range starting with 118.102.*
If I set 118.102.0.0 - 118.102.0.255 then it seems like I need to add 118.102.0.0 - 118.102.1.255, 118.102.0.0 - 118.102.2.255 and so on...
118.102.0.0 - 118.102.255.255 doesn't seem right too.
What is the correct way?

A: Try with 118.102.0.0/16 or 118.102.0.1 - 118.102.255.254


Q: Google chrome browser is misbehaving I don't know what's going wrong with my chrome browser. Everything was working fine but all of a sudden the width from my css styling for divs, input elements and all other widths are disorganised. I don't know if its the width that increased or the padding or margin but what I know is that everything is disorganised. But I checked firefox and other browsers everything is okay. I cleared my cache and cookie but no solution. Please does anyone knows how I can fix this?

A: I found the silly solution. The browser was zoomed to 120% unknown to me so I adjusted it back to 100%


Q: Prove/Disprove: When $A,B,C$ are symmetric matrices, the transpose of $ABC$ is $CBA$
Prove/Disprove the following: When $A,B,C$ are symmetric matrices, the transpose of $ABC$ is $CBA$

This was what I did:
$$\text{Symmetric}   \ A,B,C \implies (A^T = A) \land (B^T = B) \land (C^T = C) \ \ \ \ \ \ \ (1)$$
$$(ABC)^T = C^TB^TA^T = CBA \ \ \ \  \ \ \text{(By (1))} $$
But according to the solutions manual $$(ABC)^T = C^TB^TA^T \neq CBA$$
Why would that be so?


Q: Azure Cloud Service stops saving to table storage when storage is accessed in visual studio server explorer I am working on an azure cloud service that has two different worker roles saving entities to an azure table storage. When I run the solution locally (both in debug and release mode) it works perfectly, however when I deploy the solution (either in debug or release) to the Azure Cloud Production Environment it writes the correct data and works well; but after I open the storage account in the server explorer in visual studio to review what was saved, then the cloud service worker roles stop saving new data to the tables.
Does accessing the azure storage account from the server explorer window in visual studio freeze the storage account when an azure cloud service is running against it?

A: No, that's not possible. Could you please provide more description about how the worker role "stop saving new data to table"? Did it encountered failures? If so, what's the detailed error message? Or did it make no progress while writing table entities?


Q: Reading XML File Through Dataframe I have XML file like below format.
<nt:vars>
<nt:var id="1.3.0" type="TimeStamp"> 89:19:00.01</nt:var>
<nt:var id="1.3.1" type="OBJECT ">1.9.5.67.2</nt:var>
<nt:var id="1.3.9" type="STRING">AB-CD-EF</nt:var>
</nt:vars>

I built a dataframe on it using below code. Though the code is displaying 3 rows and retrieving id and type fields it'snot displaying actual value which is 89:19:00.01, 1.9.5.67.2, AB-CD-EF
spark.read.format("xml").option("rootTag","nt:vars").option("rowTag","nt:var").load("/FileStore/tables/POC_DB.xml").show()

Could you please help me if I have to add any other options to above line to bring the values as well please.

A: You can instead specify rowTag as nt:vars:
df = spark.read.format("xml").option("rowTag","nt:vars").load("file.xml")

df.printSchema()
root
 |-- nt:var: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- _VALUE: string (nullable = true)
 |    |    |-- _id: string (nullable = true)
 |    |    |-- _type: string (nullable = true)

df.show(truncate=False)
+-------------------------------------------------------------------------------------------+
|nt:var                                                                                |
+-------------------------------------------------------------------------------------------+
|[[ 89:19:00.01, 1.3.0, TimeStamp], [1.9.5.67.2, 1.3.1, OBJECT ], [AB-CD-EF, 1.3.9, STRING]]|
+-------------------------------------------------------------------------------------------+

And to get the values as separate rows, you can explode the array of structs:
df.select(F.explode('nt:var')).show(truncate=False)
+--------------------------------+
|col                             |
+--------------------------------+
|[ 89:19:00.01, 1.3.0, TimeStamp]|
|[1.9.5.67.2, 1.3.1, OBJECT ]    |
|[AB-CD-EF, 1.3.9, STRING]       |
+--------------------------------+

Or if you just want the values:
df.select(F.explode('nt:var._VALUE')).show()
+------------+
|         col|
+------------+
| 89:19:00.01|
|  1.9.5.67.2|
|    AB-CD-EF|
+------------+


Q: Two interpretations of implication in categorical logic? I am a bit confused about the interpretation of "implication" in the standard treatment of categorical logic, for example in [Bart Jacobs 1999] "Categorical Logic and Type Theory".
(A). On the one hand, the book says that "terms give rise to morphisms between contexts, this is the canonical way to produce a category from types" (p.5)  Under this interpretation, type contexts are the objects in the category, also called indices, such that fibers can be built over indices.  Under the Curry-Howard isomorphism, this arrow would correspond to an implication $\Rightarrow$ in logic.
(B). On the other hand, "each fiber category $P(I)$ is a Boolean algebra... with propositional connectives such as $\wedge, \vee, \top, \bot, \neg$ in (Boolean) logic" (p.12, ibid). This seems to be the approach used by Lawvere when he formulated the notion of topos, with the sub-object classifier $\Omega$.  Under this interpretation, one can also create the (Boolean) logic implication operator $A \Rightarrow B$ defined as $\neg A \vee B$ (in Boolean algebra, but one can also do similarly in Heyting algebra).  Would this $\Rightarrow$ be in conflict with the $\Rightarrow$ in (A)?
Edit: More specifically, if there is an arrow $A \Rightarrow B$ in the fiber, as in (B), how does it correspond (via Curry-Howard) to some type or term in the base category?

A: The answers of varkor and Dmitri explain that in a given category, entailment corresponds to external homsets while implication corresponds to internal-homs.  However, there's another thing going on here too that may be relevant to your question.  When interpreting a logic over a type theory, the corresponding categorical structure is a fibration, in which there is both a base category (corresponding to types and terms) and a fiber category (corresponding to propositions and entailment).  The Curry-Howard interpretation of "logic" happens only in the fiber category.  Thus, the internal-hom in the base category corresponds to a function-type, while it is the internal-hom in the fiber category that corresponds to implication.

A: Morphisms A→B form a set (typically denoted by C(A,B) or hom(A,B)), whereas the internal hom Hom(A,B) is an object in the same category C.
A morphism A→B corresponds to the entailment A⊢B,
whereas the internal hom Hom(A,B) corresponds to the implication A⇒B.
Given a morphism A→B, by the product-hom adjunction we get a morphism 1→Hom(A,B).
That is, A⊢B can be replaced by ⊢(A⇒B).
More generally, D,A⊢B can be replaced by D⊢(A⇒B),
which correspons to replacing D⨯A→B with D→Hom(A,B).
This is how you pass between these two notions.

if there is an arrow A⇒B in the fiber, as in (B), how does it correspond (via Curry-Howard) to some type or term in the base category?

Given some topos T and an object X of T,
we can interpret the above
in the category Sub(X) of subobjects of X,
whose objects are monomorphisms A→X
and morphisms are inclusions of subobjects.
Then if A and B are two subobjects of X,
their internal implication A⇒B is another subobject of X,
i.e., we have a monomorphism (A⇒B)→X in the topos T.
On the other hand, having an entailment
A⊢B means that the subobject A of X (given by a monomorphism A→X)
is contained in the subobject B of X (given by a monomorphism B→X),
i.e., in the topos T there is a monomorphism A→B
such that the composition A→B→X equals A→X.
The terminal object 1 of Sub(X) is the identity map X→X,
and there is a morphism (i.e., entailment) from 1 to A⇒B
in Sub(X) if and only if (by adjunction) A entails B in Sub(X),
i.e., there is a morphism A→B in Sub(X).
That is, externally, (A⇒B)→X coincides with the identity map on X
if and only if A is contained in B (as a subobject of X).

A: It's not always true that implication $A \Rightarrow B$ can be expressed as $\neg A \lor B$ [1]. This is in particular case in most systems in type theory at type level. Usually when the axiom of excluded middle is not assumed in the corresponding logic of types, implications cannot be expressed in terms of negation and disjunction.
[1] Crolard: Subtractive Logic

A: There are two concepts here, which are tightly connected. Logically, this corresponds to the distinction between $\vdash$ and $\Rightarrow$.
(A) Morphisms $t : \Gamma \to A$ represent (well-formed, typed) terms $\Gamma \vdash t : A$ in a context. If there is a single type (such as in universal algebra), we may write this simply as $\Gamma \vdash t$. This represents entailment, or derivability, of $t$ in the context $\Gamma$.
(B) Objects $A \Rightarrow B$ (which is the exponential $B^A$) represent implication. This may be thought of as an internalisation of the notion of entailment: in fact, terms $\vdash f : A \Rightarrow B$ are in bijection with terms $x : A \vdash t : B$. By modus ponens (the counit of the adjunction $A \times (-) \vdash A \Rightarrow (-)$), if we have a term of type $A$ and a term of type $A \Rightarrow B$, we can form a term of type $B$. This corresponds to the process of substituting one term for a free variable in another (at the level of entailment).
You can think of (A) as a meta-logical construction, which is necessary to even talk about terms or derivations in the first place. Then (B) is a way to reason about entailment within the logic itself (it is not present in every logic, but can be constructed in Boolean logic as you point out).


Q: When I do a delete:TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing table http://1.z9ls.com/t6/701/1555244797x1822611239.png
one table is article,the other is category:
article:article_id,article_title,article_category_id...and article_category_id
is the foreign key and references category_id of table category.
When I delete an article：object references an unsaved transient instance - save the transient instance before flushing: com.wjh.blog.domain.Category
Attention:when I DELETE a article，but not insert or update.
//I have already use the @Transactional
//this is the code of ArticleDaoImpl.java
 @Override
    public void delete(Long article_id) {
        Article article = new Article();
        article.setArticle_id(article_id);
        this.getHibernateTemplate().delete(article);
    }

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.wjh.blog.domain.Category" table="category">
        <id name="category_id" column="category_id">
            <generator class="native"/>
        </id>
        <property name="category_name" column="category_name"/>
        <property name="category_parent_id" column="category_parent_id"/>
        <set name="category_articles" inverse="true">
            <key column="article_category_id"></key>
            <one-to-many class="com.wjh.blog.domain.Article"/>
        </set>
    </class>
</hibernate-mapping>

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.wjh.blog.domain.Article" table="article" >
        <id name="article_id" column="article_id">
            <generator class="native"/>
        </id>
        <property name="article_title" column="article_title"/>
        <property name="article_content" column="article_content"/>
        <property name="article_time" column="article_time"/>
        <property name="article_pic" column="article_pic"/>
        <property name="article_desc" column="article_desc"/>
        <!--category-->
        <many-to-one name="article_category" class="com.wjh.blog.domain.Category"
                     column="article_category_id" cascade="save-update,persist" ></many-to-one>

    </class>
</hibernate-mapping>


Q: Python - cannot set wallpaper with tempfile Code:
import urllib.request
import tempfile
import shutil
import ctypes

SPI_SETDESKWALLPAPER = 20
with urllib.request.urlopen('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png') as response, tempfile.NamedTemporaryFile() as f:
    shutil.copyfileobj(response, f)
    ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, f.name, 0)

However, if you use tempfile.NamedTemporaryFile(delete=False) it works.
The docs state:

If delete is true (the default), the file is deleted as soon as it is
  closed.

In my original code the file isn't deleted until after having exited the body of the with statement when it is automatically closed. So why isn't SPI_SETDESKWALLPAPER working?

A: You need to read the next couple sentences in the documentation, which read something like this:

Under Unix, the directory entry for the file is either not created at all or
  is removed immediately after the file is created. Other platforms do not
  support this; your code should not rely on a temporary file created using
  this function having or not having a visible name in the file system.

A: I figured out the problem:
To begin with, the value  of the fWinIni parameter needs to be changed:
SPIF_UPDATEINIFILE = 0x01
SPIF_SENDCHANGE = 0x02
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, f.name, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE)

This preserves the wallpaper after logging off.
Second, the temp file needs to be closed in order for SystemParametersInfoW to work. Therefore, delete=False is necessary.
Finally, delete the temp file manually using os.remove(f.name).


Q: How to tell nuget to add package resource files as links, and not copy them into project directory Intro (how to pack resources into a nuget package)
To pack some resource files into a nuget package, what one would normally do, is the following.
Put all the resource files into the content\ directory of a nuget package. This would be specified by the following line in a .nuspec file:
<files>
  <file src="Project\bin\Release\script.js" target="content\js\script.js" />
<files>

Now, when this nuget package gets installed into AnotherProject, the following file structure emerges:
Solution.sln
packages\Project.1.0.0\content\js\script.js  // the original resource file
AnotherProject\js\script.js                  // a physical copy
AnotherProject\AnotherProject.csproj         // <Content /> tag (see below)

During package installation, AnotherProject.csproj was injected with tag:
<Content Include="js\script.js" />

and this is for the physical copy of the original resource (which is under packages\ directory).
The actual problem (how to pack resources into a nuget package as link)
My aim is not to have the physical copy of a resource file in the AnotherProject directory but rather a "link" to the original resource under packages\ directory. In the csproj, this should look like this:
<Content Include="packages\Project.1.0.0\content\js\script.js">
  <Link>js\script.js</Link>
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>

Brute force solution that I would rather avoid
Now, one "do it the hard way" workaround I can think of is:

*

*not putting resource files under content\ so they do not get added automatically,

*writing Install.ps1 script that would hack the csproj file structure and add the necessary XML piece manually,

This, however, has the following drawbacks:

*

*all my nuget packages need the same script piece in their Install.ps1,

*when installing my packages, there would be a nasty "project reload prompt" in Visual Studio.

A: Since NuGet currently does not support this out of the box your options are either to use PowerShell or to use a custom MSBuild target.
PowerShell

*

*Leave your resources outside of the Content directory in your NuGet package (as you already suggested).

*Add the file link using PowerShell in the install.ps1.

You should be able to avoid the project reload prompt if you use the Visual Studio object model (EnvDTE). I would take a look at Project.ProjectItems.AddFromFile(...) to see if that works for you.
MSBuild target

*

*NuGet supports adding an import statement into a project that points to an MSBuild .props and/or .targets file. So you could put your resources into the tools directory of your NuGet package and reference them from a custom MSBuild .props/.targets file.

Typically the custom .props and .targets are used to customise the build process. However they are just MSBuild project files so you could add items for your resources into these project files.
Note that .props are imported at the start of the project file when a NuGet package is installed, whilst .targets are imported at the end of the project.
Customising NuGet
Another option, which would take more work, would be to modify NuGet to support what you want to do.


Q: How to write unit test case IHttpClientFactory I have a method in service layer to  connect to a service and i am using IHttpClientFactory. My method is working fine. Now i am trying to write unit test cases for the same.
public async Task<MyObject> MyMethodAsync(string arg1, string arg2)
{
    var client = _httpClientFactory.CreateClient("XYZ");

    var Authkey = "abc";
    var AuthToken = "def";

    var headers = new Dictionary<string, string>
        {
            { Authkey,AuthToken }
        };

    client.AddTokenToHeader(headers); //This method set  the DefaultRequestheader from the dictionary object

    var reqData = new
    {
        prop1 = "X",
        prop2 = "Y"
    };//req object

    var content = new StringContent(JsonConvert.SerializeObject(reqData), Encoding.UTF8, "application/json");

    //This is httpClient Post call for posting data
    HttpResponseMessage response = await client.PostAsync("postData", content);
    if (!response.IsSuccessStatusCode || response.Content == null)
    {
        return null;
    }

    MyObject myObject = JsonConvert.DeserializeObject<MyObject>(response.Content.ReadAsStringAsync().Result);//read the result to an object
    return myObject;
}

For the above method i am writing test cases. Here i am trying to set the Post methods out put a status code OK and expecting the
MyMethodAsync method to be true as the PostAsync is true. Here i am getting an exception

System.InvalidOperationException : An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.

[Test]
public async Task MyMethodAsync_Gets_True()
{
    var response = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent("It worked!")
    };

    //Mock the httpclientfactory
    var _httpMessageHandler = new Mock<HttpMessageHandler>();
    var mockFactory = new Mock<IHttpClientFactory>();

    //Specify here the http method as post
    _httpMessageHandler.Protected()
      .Setup<Task<HttpResponseMessage>>("SendAsync",
       ItExpr.Is<HttpRequestMessage>(req => req.Method == HttpMethod.Post),
       ItExpr.IsAny<CancellationToken>())
       .ReturnsAsync(new HttpResponseMessage
       {
           StatusCode = HttpStatusCode.OK
       });

    var httpClient = new HttpClient(_httpMessageHandler.Object);
    mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(httpClient);

    var arg1 = "X";
    var arg2 = "D101";

    var service = new MyService(_mockAppSettings.Object, mockFactory.Object);
    var result = await service.MyMethodAsync(arg1, arg2);
    // Assert
    Assert.IsNotNull(result);
}

Can someone show what mistake i am doing here?

A: As the exception says you have to

*

*either call the PostAsync with an absolute url

*or set the BaseAddress of the HttpClient

If you choose the second one all you need to do is this:
var httpClient = new HttpClient(_httpMessageHandler.Object);

httpClient.BaseAddress = new Uri("http://nonexisting.domain"); //New code

mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(httpClient);

With this modification the exception will be gone.
But your test will fail because the response.Content will be null and that's why MyMethodAsync will return with null.
To fix this let's change the Setup to this:
public static async Task MyMethodAsync_Gets_True()
{
    //Arrange
    MyObject resultObject = new MyObject();
    var response = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent(JsonConvert.SerializeObject(resultObject))
    };

    var _httpMessageHandler = new Mock<HttpMessageHandler>();
    _httpMessageHandler.Protected()
        .Setup<Task<HttpResponseMessage>>("SendAsync",
          ItExpr.Is<HttpRequestMessage>(req => req.Method == HttpMethod.Post),
          ItExpr.IsAny<CancellationToken>())
        .ReturnsAsync(response);
    ...

    //Act
    var result = await service.MyMethodAsync(arg1, arg2);

    //Assert
    Assert.NotNull(result);
}


Q: How to restore bootloader or bootsector for Windows Vista? I've restored NTFS containing Windows Vista. But the bootloader or bootsector got corrupted.
How can i detect what of them got corrupted?
How can i restore bootloader if it's corrupted?
How can i repair bootsector if it's corrupted?
All of these things should be done from linux or from bootable CD.

A: Boot from Windows installation DVD, choose to repair your PC, choose recovery console and then type in "bootrec /fixmbr", next type "bootrec /fixboot" just for being shure that's everything was taken into consideration. That's Vista way. Win 7 way is to type in "bootsect /nt60 SYS".


Q: Is there a way to create a .net project in eclipse using no template I have eclipse 2021 installed on my laptop which is running Ubuntu 20.04 and I have .net 6 installed with snap when I go to create a .net project it says no template selected it in preferences the .net folder is in the snap folder. I just want to create a blank project , how can I do this. photo


Q: bsmultiselect Select one option at a time on div I was trying to use "setSelected" option on my multiselect, but I nnoticed that this does not work with divs (at least I couldn't reach it myself). I am trying to make two synced multiselects, using this example: https://dashboardcode.github.io/BsMultiSelect/snippetJs.html but with the last two inputs only.

var options = [

       { text: 'item1', value: 'item1'},
       { text: 'item2', value: 'item2'},

   ];

    var teste1 = null;
    var teste2 = null;
    let isTeste2 = true;
    var $testes = $('#teste1-id')
    if (isTeste2)
        $testes = $testes.add('#teste2-id')

    var install = function () {
        $testes.bsMultiSelect({
            options: options
        });
        if (isTeste2) {
            $('#teste1-id').on('dashboardcode.multiselect:change', function () {
                $('#teste2-id').bsMultiSelect("UpdateOptionsSelected");
            })
        }

    }
    install();

    $("#btn").click(
       function(){
          options[0].selected = true;
          var api1 = $testes.BsMultiSelect();
          api1.updateOptionSelected(0);
       }
    )

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

Teste1

    Teste2:

<button id="btn">Click Me</button>

Could you help me find a solution, please?

A: For only "one select":

var options = [
       { text: 'item1', value: 'item1', selected: true},
       { text: 'item2', value: 'item2', selected: false},
];

function isValidSelection(v){
    var l = options.filter(function(item){
         return item.selected==true;
    }).length;
    var r = ( !v ) || (v && l==0);
    return r;
}

var teste1 = null;
var $teste1 = $('#teste1-id')

var install = function () {
   $teste1.bsMultiSelect({
       options: options,
       setSelected: function(o,v){
           if (isValidSelection(v)){
              o.selected = v;
              return true;
           }
           else{
              return false;
           }
       }
   });
}
install();

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

Test it (only one select allowed)


Q: How to set headers in SQLPLUS? I have set following SQLPLUS commands:
SET ECHO OFF
SET FEEDBACK OFF
SET HEADING ON
SET LINESIZE 100
SET PAGESIZE 1000
SET SPACE 0
SET TERMOUT OFF
SET TRIMOUT OFF
SET TRIMSPOOL ON
SET VERIFY OFF

But i am getting the result as:
ERROR_CODE
----------
ERROR_DESC
----------------------------------------------------------------------------------------------------
ERROR_COUNT
-----------
EXCP098

EXCEPTION: Processing not allowed

          2

EXCP014

EXCEPTION: UNKNOWN STATUS

         11

i.e. all the column headings and column values are in a new line instead of all column header should be in the same row and then record 1 should be in the first row and then record 2 should be in the second row.
I want it should be displayed as:
ERROR_CODE             ERROR_DESC                          ERROR_COUNT
-----------------------------------------------------------------------
EXCP098             EXCEPTION: Processing not allowed         2

EXCP014             EXCEPTION: UNKNOWN STATUS                11

A: If "ERROR_DESC" is too long to fit on a line (together with "ERROR_CODE" and "ERROR_COUNT"), you have a few options to try:

*

*return just a substring,

*TRIM the value, or

*change the data type for "ERROR_DESC".

What's working and appropriate, depends on your overall context. After all, the display in SQLPlus is usually not the most important aspect.


Q: wireless temperature sensor Are there any low-cost (<50$USD) wireless ambient temperature sensors available?
I would like a simple to interface to the sensor i.e. IP over Wifi if at all possible.

A: One solution would be to use a a JeeNode and a JeeLink (plugged into a PC or router). Cheap, open-source and programmable from the Arduino IDE.

A: Another vote for a JeeNode radio and receiver. I suggest you review this weather station wireless implementation:
JeeNode Weather Station

A: The book 'Practical Arduino', available from little bird electronics (and elsewhere) contains information on how to decode the data from wireless temperature probes as sold with consumer weather stations.

A: Not wifi but a standalone XBee + temperature sensor will do this for around $30-$40 or so.
The XBee has a uC + A/D converter and could read an analog sensor. At a 0.1% duty cycle (transmitting for 1 second every 1000 seconds) you can get around two years on two
AA's with a fairly simple design.
I have a short ZigBee writeup at
http://wiblocks.luciani.org/white-papers/intro-to-zigbee.html

A: You might want to consider building such a device yourself. If you need the communication to be over TCP/IP networks then the mbed has in-built ethernet capabilities and could communicate temperature data (and a lot more!), but you would need to buy a wifi adaptor for wireless comms. As davr points out, thats going to be a power drain at the least!
Alternatively you could use an arduino and a zigbee module to send the data over potentially large distances back to a controller device with the lower power 802.15.4 protocol.
Either way I think you're going to have to get your hands dirty and build the thing yourself. The bonus of that approach is that depending on how far to need to communicate wirelessly over, you could keep the cost down.

A: Why not use a standard remote sensor for a consumer-grade weather station? Most of the ones you find in stores are made by Oregon Scientific. I'm not sure of the wireless band and the protocol, but it ought to be fairly simple and probably documented somewhere out there on the internet.

A: DISCLAIMER I do work for that Yoctopuce company which designed  the product described here, so that answer might not feel as altruist as you would like it to be.
You might want to have a look at Yocto-Temperature and YoctoHub-Wireless from Yoctopuce.  The Yocto-temperature is a just regular USB temperature sensor as you can find many on the internet, but it can be plugged on a YoctoHub-Wireless from the same company. That hub is a  WiFi transmitter which can control any Yoctopuce device.  You will then have  direct WiFi access to your sensor. You
can also ask  the hub to automatically report sensors data on a server of your choice (much easier to go through NAT filters that way).
Ease of use
Plug, configure, program your application and play. But you  will have to work on the enclosures, especially if you want to  put it outdoors as I suspect.
Electrical consumption
WiFi is a power greedy technology. Actually a YoctoHub-wireless + one sensor consumption is about 140mA. But the hub features a deep sleep mode. In that mode the hub wakes up from time to time, post sensors data, and goes back to sleep. Consumption in deep sleep more is less than 15 uA. Then, depending on how you configure it, the installation can hold on batteries for weeks... or months.
Price
More than $50, I'm afraid. But I seriously doubt you can find a reliable WiFi temperature sensor for less than $50. Note that if you use a cheaper technology, you will have to buy a bridge between that technology and your network. Moreover, if you really think that more than $50 is a deal
breaker, you should ask yourself how much you would like to be paid to provide what you're asking for. And don't forget: that money is supposed to pay for raw components and to feed you as well :-)
Application
Here is a application example involving a YoctoHub-Wireless and
an Yocto-Meteo which is just an improved Yocto-Temperature. Basically it's an outdoor solar-powered, wifi, temperature/humidity/atmospheric pressure sensors array. It is powered by one of these USB solar chargers.
http://www.yoctopuce.com/EN/article/an-autonomous-solar-weather-station
Alternatives
Here are some other WiFi alternatives, which I believe are as good as the Yoctopuce one, minus the power issue handling.

*

*DIY Hardcore: Arduino + wifi shield +  temperature sensor such as http://www.sparkfun.com/categories/82

*DIY casual: Raspberry PI + USB wifi dongle + usb temperature sensor . Note that USB temperature sensors are very common:
http://www.phidgets.com/products.php?category=35
http://www.raphnet.net/electronique/usbtenki/index_en.php

*Ready to use: Temper@tureAlert have a whole range  of ready to use
temperature sensors, including wifi version
http://www.temperaturealert.com/Temperature-Alarm.aspx
As a conclusion
The hardware is just the visible part of the  iceberg. Whatever solution you choose, make sure you choose one with a decent API, or it will be useless.


Q: Parallel Solution search I have written some code in python using multiprocessing package. It sort of searches for a solution for an equation in 6 different ways.So I have 6 different processes running the same function with different parameters. I would like to stop all the sub-processes once the solution has been found by one of the sub-process.Right now after using the join function, the result is that even if the solution is found , the other processes continue , till they find one . I'm using join()  .
for i in range(N):
                    p=multiprocessing.Process(target=mysolver,args=(g,h,q,B[i],i,dic,))
                    jobs.append(p)
                    p.start()

            for p in jobs:
                    p.join()

This how I call the function for solving. Usually N is 6 -10 .

A: You need to have a list containing a reference to all threads and accessible by all threads. This list of threads should be ready before you start the threads. The thread that finds a solution first can kill the others using the list, taking care of not commiting suicide.
You might face a racing condition in case one of the threads dies before you call join. As such you might be calling join on a already dead thread. A quick and dirty workaround is to let each thread wait few milliseconds fot the main thread to call join for all threads.
An other cleaner solution is to use a flag that is checked by all threads while they look for a solution. If they find it to be true, they should immediately terminate by returning. The thread that finds a solution can set the flag to true and return. Now all threads will nicely join the main thread.


Q: Diffing between two entire directories/projects in hg or git? I inherited a project originally stored in CVS with all the revisions. I made quite a few edits, and I'm trying to compare all the changes I made in the original directory, in regards to new files added versus the old ones.
Is there some sort of utility for hg/git where I can do a tree diff, or something of that nature? So that say, there's a mark between newly added files, deleted files, am I asking for too much?

A: I don't really understand what you want, but isn't diff -ur enough for you? It will work even on directories without any kind of version control.

A: git diff does exactly that. but it only works for git projects.
hg diff, svn diff pretty every version control system can diff directory trees

A: From git diff manpage:

git diff [--options] [--] [<path>...]

[...]
    If  exactly two paths are given, and at least one is untracked, compare the two files / directories. This behavior  can  be  forced  by --no-index.

If you want to compare two versions (e.g. two tagged releases, or two branches) in two different repositories, you can use trick described in GitTips page on Git Wiki, under "How to compare two local repositories".
Assuming that you are inside one repository, and second repository is in /path/to/repo, so its GIT_DIR is /path/to/repo/.git if it is non-bare repository, you can something like the following:
$ GIT_ALTERNATE_OBJECT_DIRECTORIES=/path/to/repo/.git/objects \
   git diff $(git --git-dir=/path/to/repo/.git rev-parse --verify A) B

where A and B are revisions you want to compare.  Of course you can also specify path limiter in above expression.
Explanation: GIT_ALTERNATE_OBJECT_REPOSITORIES variable can be used to make git commands concatenate object database of the two repositories.  git --git-dir=... rev-parse ... is used to turn name (extended SHA-1 expression) in repository given as parameter to git-dir option into unique SHA-1 identifier.  The $( ... ) construct puts result of calling given command in command line.  git diff is used to compare two revisions (where one is from alternate object repository).
Alternate solution would be to simply import other repository into given repository, using git remote add (and git fetch).  Then you would have everything locally, and would be able to do comparision inside single repository.

A:
Is there some sort of utility for hg/git where I can do a tree diff... [s]o that say, there's a mark between newly added files, deleted files... [emphasis added]

Yes. We can git diff the current directory against another directory and...
...mark the added, deleted, and modified files:
git diff --name-status --no-index ./ path/to/other/dir

...show only added files:
git diff --diff-filter=A --name-status --no-index ./ path/to/other/dir

... show only deleted files:
git diff --diff-filter=D --name-status --no-index ./ path/to/other/dir

...show only modified files:
git diff --diff-filter=M --name-status --no-index ./ path/to/other/dir

See also: https://git-scm.com/docs/git-diff

A: To simply create a diff patch in git's diff format from two arbitrary files or directories, without any fancy repository stuff or version control:
git diff --no-index some/path other/path > some_filename

Jakub Narębski's comment on knittl's answer hinted at the answer... For simplicity's sake, that's the full command.
The > part creates a file and redirects the output to it. If you don't want a file and just want the output printed in your console so you can copy it, just remove the > some_filename part.

For convenient copying and pasting, if you've already cded to a directory containing the original directory/file named a and the modified directory b, it'll be:
git diff --no-index a b > patch

A: It's not git-specific, but as a general diff utility for Windows, I really like WinMerge.

A: There Are Following Another Ways For Diffing between two entire directories/projects.

*

*In Git There is Syntax:
Syntax: git-diff [] [--] […]
This form is to view the changes you made relative to the index (staging area for the next commit). In other words, the differences are what you could tell Git to further add to the index but you still haven’t.
Here is the.
URL: https://git-scm.com/docs/git-diff
git diff --no-index directory 1 project /path directory 2 project/path >>  File name

*Using Linux Command diff --brief --recursive dir1path/ dir2Path/

*If you are using windows there is an application WinMerge.

A: Creating the patch from dir1 to dir2 (--binary only needed for binaries):
git diff --no-prefix --no-index --binary dir1 dir2 > dir.diff

Applying the patch to contents of working directory, which has the same contents as dir1:
cd dir1_copy
git apply ../dir.diff

git apply has default -p1 which strips the leading directories in diff commands.


Q: Subir y guardar imagen PHP Tengo un problema al subir imágenes al servidor, solo se deben actualizar las imágenes de la tabla si se marca un checkbox, sino guarda el valor anterior
la base de datos solo guarda el nombre de la imagen asociada
Form.html
<form name ="dormUpdate" class="form" method="post" action="update.php" align="center">

        <fieldset>

 Producto

             <input id="id"   value="<?php echo $id; ?>"      type="hidden"   name="id" />
             Imagen Chica:    <input id="imagen_chica"   value="<?php echo 'No Change'; ?>"   type="file"     name="imagen_chica"  />

             Cambiar:    <input id="changed1"     type="checkbox"     name="changed1"  />

             Imagen Grande:  <input id="imagen_grande"  value="<?php echo 'No Change'; ?>"   type="file"     name="imagen_grande" />

             Cambiar:    <input id="changed2"     type="checkbox"     name="changed2"  />

        </fieldset></form>

update.php
<?php
ini_set('display_errors',1);
require "funciones.php";
$ch1      = 0;
$ch2      = 0;
$img_ch   = 'NOT SET';
$img_gr   = 'NOT SET';

$con      = conecta();
$id       = $_REQUEST['id'];
$ch1      = $_REQUEST['changed1'];
$ch2      = $_REQUEST['changed2'];

$target_path = './fotos';
$img1path = $target_path .  $_FILES['imagen_chica']['name'];
if(move_uploaded_file($_FILES['imagen_chica']['tmp_name'], $img1path))
{
    $img_ch = $_FILES['imagen_chica']['name'];
 }

$img2path = $target_path . $_FILES['imagen_grande']['name'];
if(move_uploaded_file($_FILES['imagen_grande']['tmp_name'], "$img2path"))
{
    $img_gr = $_FILES['imagen_grande']['name'];
}

$res = mysqli_query($con,"SELECT * FROM productos WHERE id = $id;");
$row = mysqli_fetch_assoc($res) ;
$img_1orig    = $row['imagen_chica'];
$img_2orig    = $row['imagen_grande'];

if($ch1 != "on"){
    $img_gr = $img_1orig;
}
if($ch2 != "on"){
    $img_ch = $img_2orig;
}

$res = mysqli_query($con,
                    "UPDATE productos SET
                            imagen_chica  = '$img_ch',
                            imagen_grande = '$img_gr'
                            WHERE id      =  $id;"
);

/////////////////////////////

A: El problema está que se te ha olvidado el atributo enctype="multipart/form-data". Este valor es necesario cuando se utilizan formularios que tienen un control de carga de archivos

Nota: El atributo enctype sólo se puede utilizarse si usamos method = "post".

Ejemplo:
<form method="POST" enctype="multipart/form-data">

El segundo error esta en tu ruta, debes añadir al final /.
Ejemplo:
$target_path = './fotos/';


Q: MetPy Wet Bulb Temperature function returns error when output of Most Unstable Parcel function is used as input When attempting to use the find the wet-bulb temperature for a parcel returned by MetPy's most_unstable_parcel function, I am getting an error that seems to be related to the Pint attributes of the most unstable parcel pressure.  It is necessary to strip away those attributes by coercing the pressure to be of type int or float.
See discussion, below.
I would greatly appreciate some help in understanding how to use the most unstable parcel pressure without resorting to the artifice of coercing it to a type that requires re-assigning units.  Thank you!
Example Calculation (data from OUN 20220328 00Z sounding):
from metpy.units import units
import metpy.calc as mpcalc

#  Construct a sample sounding:
p = [972.0, 942.8, 925.0, 910.1, 878.2, 850.0, 847.3, 826.0, 817.0, 787.5]*units('hPa')
T = [25.4, 22.4, 20.6, 19.3, 16.4, 13.8, 13.6, 11.6, 11.1, 9.4]*units('degC')
Td = [6.4, 5.3, 4.6, 4.1, 2.9, 1.8, 1.7, 0.6, -0.2, -2.9]*units('degC')
h = [345,  610,  776,  914, 1219, 1497, 1524, 1737, 1829, 2134]*units('m')

#  Find the Most Unstable Parcel
MUp = mpcalc.most_unstable_parcel(p,T,Td,h)

# MUp
# (972.0 <Unit('hectopascal')>,
#  25.4 <Unit('degree_Celsius')>,
#  6.4 <Unit('degree_Celsius')>,
#  0)

#  Next compute the wet-bulb-temperature for this parcel:

Twb = mpcalc.wet_bulb_temperature(MUp[0],MUp[1],MUp[2])

When this is executed, we get the following error traceback:
IndexError                                Traceback (most recent call last)
Input In [4], in <module>
----> 1 Twb = mpcalc.wet_bulb_temperature(MUp[0],MUp[1],MUp[2])

File ~/miniconda3/envs/MetPy/lib/python3.8/site-packages/metpy/xarray.py:1230, in preprocess_and_wrap.<locals>.decorator.<locals>.wrapper(*args, **kwargs)
   1227     _mutate_arguments(bound_args, units.Quantity, lambda arg, _: arg.m)
   1229 # Evaluate inner calculation
-> 1230 result = func(*bound_args.args, **bound_args.kwargs)
   1232 # Wrap output based on match and match_unit
   1233 if match is None:

File ~/miniconda3/envs/MetPy/lib/python3.8/site-packages/metpy/units.py:288, in check_units.<locals>.dec.<locals>.wrapper(*args, **kwargs)
    285 @functools.wraps(func)
    286 def wrapper(*args, **kwargs):
    287     _check_units_inner_helper(func, sig, defaults, dims, *args, **kwargs)
--> 288     return func(*args, **kwargs)

File ~/miniconda3/envs/MetPy/lib/python3.8/site-packages/metpy/calc/thermo.py:3073, in wet_bulb_temperature(pressure, temperature, dewpoint)
   3071 ret = it.operands[3]
   3072 if ret.size == 1:
-> 3073     ret = ret[0]
   3074 return units.Quantity(ret, temperature.units)

IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed

After running a few permutations of inputs, I discovered that it is possible to use the output pressure value if one first coerces it to, say, type float or int.
#  Reformat the pressure value as input to
#  wet_bulb_temperature()

d = float(MUp[0].magnitude)*units('hPa')
Twb1 = mpcalc.wet_bulb_temperature(d,MUp[1],MUp[2])
print(Twb1)

#  output is 14.209821596989343 degree_Celsius

# As far as Python is concerned, the two instances of pressure are
# identical:

print(MUp[0]==d)

#  Output:  True

It's just not clear to me why the pressure output from most_unstable_parcel (e.g. MUp[0]) cannot be used directly as an input to the wet-bulb temperature calculation.

A: This is a bug with MetPy's wet_bulb_temperature function in handling NumPy scalars, so thank you for identifying the issue! A pull request fixing this has been submitted, which should make it into the upcoming MetPy v1.3.0 release.
For now, you will need to somehow override the array shape recognition that exists in wet_bulb_temperature. Converting from a NumPy scalar to a Python scalar as you discovered is one such way to do so. Another is converting to 1D NumPy arrays, like the following:
Twb = mpcalc.wet_bulb_temperature(
    *(np.atleast_1d(arg) for arg in (MUp[0], MUp[1], MUp[2]))
)


Q: Boost.flyweight and Boost.MPL I have a question regarding flyweight options, given the definition below, based on http://www.boost.org/doc/libs/1_40_0/libs/flyweight/test/test_basic.cpp
typedef boost::flyweights::flyweight<
    std::string,
    boost::flyweights::tag<int>,
    boost::flyweights::static_holder_class<boost::mpl::_1>,
    boost::flyweights::hashed_factory_class<
        boost::mpl::_1,
        boost::mpl::_2,
        boost::hash<boost::mpl::_2>,
        std::equal_to<boost::mpl::_2>,
        std::allocator<boost::mpl::_1>
    >,
    boost::flyweights::simple_locking,
    boost::flyweights::refcounted
> StringFlyweight;

StringFlyweight    test1("Hello World");

what value has boost::mpl::_1 and boost::mpl::_2 ? When are asigned ?
boost::mpl::_1 is most probably std::string. boost::mpl::_2 should be size_t ? If true, how is deducted ?
I don't understand how is key_type chosen.
I have read http://www.boost.org/doc/libs/1_41_0/libs/flyweight/doc/tutorial/lambda_expressions.html but I it is my first contact with Boost.MPL and is not enough :)

A: boost::mpl::_1 and boost::mpl::_2 are placeholders; they can be used as template parameters to differ the binding to an actual argument to a later time. With this, you can do partial application (transforming a metafunction having an n-arity to a function having a (n-m)-arity), lambda expressions (creating a metafunction on-the-fly where it is needed), etc.
An expression containing at least a placeholder is a placeholder expression, which can be invoked like any other metafunction, with some arguments that will replace the placeholders.
In your example, assuming the following typedef
typedef boost::flyweights::hashed_factory_class<
    boost::mpl::_1,
    boost::mpl::_2,
    boost::hash<boost::mpl::_2>,
    std::equal_to<boost::mpl::_2>,
    std::allocator<boost::mpl::_1>
> hashed_factory;

we can assume that at some other point in the code, the hashed_factory will be invoked with some parameter:
typedef typename
    boost::mpl::apply<
       hashed_factory,
       X,
       Y
    >::type result; // invoke hashed_factory with X and Y
                    // _1 is "replaced" by X, _2 by Y

I did not look in Flyweight code, but we can suppose that _1 will be bound to the value type of the flyweight, and _2 to the key type (since it is used for hashing and testing equality). In this case, I think both will be std::string since no key type is specified.
I'm not sure my explanation about MPL's placeholders is quite clear, feel free to read the excellent MPL tutorial that explains very well metafunctions, lambda expressions and other template metaprogramming features.


Q: How do I create an array of ascending and then descending numbers? For example:
I have min and max values and a number of increments which may be odd or even;
if I have min = 3 and max = 10 and increments = 15 then I want:
3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3

However, if increments = 16 I want (notice the two 10's in the middle):
3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3

I have to create these arrays add-hoc using just min, max, and number of increments.
UPDATE:
To make this clearer the number of increments is equal to the number of items that must be in the array and the items are decimals.
so if min = 5.0 and max = 15.0 and increments = 6 then the array would contain:
5.0, 10.0, 15.0, 15.0, 10.0, 5.0

A: Linq way:
int min = 3;
int max = 10;
int increments = 15;

Enumerable
    .Range(min, max - min + 1)
    .Concat(Enumerable
        .Range(min, max - min + 1)
        .Reverse()
        .Skip(increments % 2))
    .ToArray();

A: This should work:
public static IEnumerable<decimal> NewMethod(decimal min, decimal max, int count)
{
    var increment = (max - min) / (int)((count - 1) / 2);

    for (var i = min; i < max; i += increment)
        yield return i;

    if (count % 2 == 0)
        yield return max;

    for (var i = max; i >= min ; i -= increment)
        yield return i;
}

Sample test:
var min = 3.0m;
var max = 10.0m;
var count = 16;

MessageBox.Show(string.Join(", ", NewMethod(min, max, count)));

Edit: You have to cope with floating point types losing precision, otherwise you will be missing an element in the final result set. Tinker a bit with Math.Round over the i += and i -= part, that's up to you. I have updated code to replace double with more reliable decimal type. But there is no guarantee this should not fail every time. Easier is to avoid cases where you will need decimal types in the result like { 1, 2.2, 3.4 } etc.

A: Here's a one-way ramp that handles floating point values correctly.  You should be able to modify it to make a triangle waveform.  When implementing a ramp, care must be taken to make sure not to accumulate either round-off errors, or off-by-one errors for various inputs.
void Packet::SetRamp( const SampleType start /*= Signal::One*/,
                      const SampleType finish /*= -Signal::One */ )
{
    SampleType slope, current;
    SampleOffsetType len;
    len = GetLength();
    if ( len < 2 )
        throw std::range_error( "packet is not large enough to set ramp into" );
    slope = ( finish - start ) / ( len - 1 );
    for ( SampleOffsetType row = 0; row < len; row++ )
    {
        current = slope * row + start;
        SetSample( row, current );
    }
}


Q: Do we have a way to include full source into APK? I'm developing samples for different Android technologies and want to include the full source code (Eclipse project) archived into the APK. That should allow anyone with Google Market access to easily reuse the code.
Is there a proper way to automatically pack the code/resources and put it into assets?
I'm using Eclipse under Win//Linux.
Currently I have to manually 7z-compress the src&res and put it into assets before signing.

A: Sure, just compress it and include it in a directory under your APK (e.g. raw). But be aware that your APK will at least x2 its size.


Q: Fourier tranform of $\int_{R^n}\frac{u(x)-u(y)}{|y-x|^{n+2s}}dy$ How to compute the Fourier transform of
$$F: x \mapsto\int_{R^n}\frac{u(x)-u(y)}{|y-x|^{n+2s}}dy$$
where $0<s<1$.
It is shown to be $\hat{F}(\xi)=|\xi|^{2s}\hat u(\xi)$.

A: I'm not sure your result is true. However, a result that is true and seems very close to your result is the following one :
$$\int_{\mathbb{R}^n} \int_{\mathbb{R}^n} \frac{|u(x)-u(y)|^2}{|x-y|^{n+2s}} \ dx dy = C \int_{\mathbb{R}^n} |\xi|^{2s} |\hat{u}(\xi)|^2 \ d\xi$$
You can find a proof in https://arxiv.org/abs/1104.4345v3 at the prop 3.4.


Q: Display calendar to pick a date in java In other languages like VB, C#, in occasions where you want the user to enter a date, say in a text box,we can make a calendar to appear once you click on it. So the user can click on the corresponding date and that date will be put to the text box.
By that way we can get rid of problems that can be caused due to dates in an incorrect format. I need to know how we can achieve this in java?
Actually, I need to combine this with a JTable. there is a column where the date need to be entered. But users may enter dates in various formats. So I thought of going to something like this. Hope there is a way to do this, easily.
Will anyone please show me how to do this. Any help is greatly appreciated..
Thank you.

A: Another easy method in Netbeans is also avaiable here,
There are libraries inside Netbeans itself,where the solutions for this type of situations are available.Select the relevant one as well.It is much easier.After doing the prescribed steps in the link,please restart Netbeans.
Step1:- Select Tools->Palette->Swing/AWT Components
Step2:- Click 'Add from JAR'in Palette Manager
Step3:- Browse to [NETBEANS HOME]\ide\modules\ext and select swingx-0.9.5.jar
Step4:- This will bring up a list of all the components available for the palette.  Lots of goodies here!  Select JXDatePicker.
Step5:- Select Swing Controls & click finish
Step6:- Restart NetBeans IDE and see the magic :)

A: I found JXDatePicker as a better solution to this. It gives what you need and very easy to use.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jdesktop.swingx.JXDatePicker;

public class DatePickerExample extends JPanel {

    public static void main(String[] args) {
        JFrame frame = new JFrame("JXPicker Example");
        JPanel panel = new JPanel();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(400, 400, 250, 100);

        JXDatePicker picker = new JXDatePicker();
        picker.setDate(Calendar.getInstance().getTime());
        picker.setFormats(new SimpleDateFormat("dd.MM.yyyy"));

        panel.add(picker);
        frame.getContentPane().add(panel);

        frame.setVisible(true);
    }
}

A: I wrote a DateTextField component.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class DateTextField extends JTextField {

    private static String DEFAULT_DATE_FORMAT = "MM/dd/yyyy";
    private static final int DIALOG_WIDTH = 200;
    private static final int DIALOG_HEIGHT = 200;

    private SimpleDateFormat dateFormat;
    private DatePanel datePanel = null;
    private JDialog dateDialog = null;

    public DateTextField() {
        this(new Date());
    }

    public DateTextField(String dateFormatPattern, Date date) {
        this(date);
        DEFAULT_DATE_FORMAT = dateFormatPattern;
    }

    public DateTextField(Date date) {
        setDate(date);
        setEditable(false);
        setCursor(new Cursor(Cursor.HAND_CURSOR));
        addListeners();
    }

    private void addListeners() {
        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent paramMouseEvent) {
                if (datePanel == null) {
                    datePanel = new DatePanel();
                }
                Point point = getLocationOnScreen();
                point.y = point.y + 30;
                showDateDialog(datePanel, point);
            }
        });
    }

    private void showDateDialog(DatePanel dateChooser, Point position) {
        Frame owner = (Frame) SwingUtilities
                .getWindowAncestor(DateTextField.this);
        if (dateDialog == null || dateDialog.getOwner() != owner) {
            dateDialog = createDateDialog(owner, dateChooser);
        }
        dateDialog.setLocation(getAppropriateLocation(owner, position));
        dateDialog.setVisible(true);
    }

    private JDialog createDateDialog(Frame owner, JPanel contentPanel) {
        JDialog dialog = new JDialog(owner, "Date Selected", true);
        dialog.setUndecorated(true);
        dialog.getContentPane().add(contentPanel, BorderLayout.CENTER);
        dialog.pack();
        dialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
        return dialog;
    }

    private Point getAppropriateLocation(Frame owner, Point position) {
        Point result = new Point(position);
        Point p = owner.getLocation();
        int offsetX = (position.x + DIALOG_WIDTH) - (p.x + owner.getWidth());
        int offsetY = (position.y + DIALOG_HEIGHT) - (p.y + owner.getHeight());

        if (offsetX > 0) {
            result.x -= offsetX;
        }

        if (offsetY > 0) {
            result.y -= offsetY;
        }

        return result;
    }

    private SimpleDateFormat getDefaultDateFormat() {
        if (dateFormat == null) {
            dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
        }
        return dateFormat;
    }

    public void setText(Date date) {
        setDate(date);
    }

    public void setDate(Date date) {
        super.setText(getDefaultDateFormat().format(date));
    }

    public Date getDate() {
        try {
            return getDefaultDateFormat().parse(getText());
        } catch (ParseException e) {
            return new Date();
        }
    }

    private class DatePanel extends JPanel implements ChangeListener {
        int startYear = 1980;
        int lastYear = 2050;

        Color backGroundColor = Color.gray;
        Color palletTableColor = Color.white;
        Color todayBackColor = Color.orange;
        Color weekFontColor = Color.blue;
        Color dateFontColor = Color.black;
        Color weekendFontColor = Color.red;

        Color controlLineColor = Color.pink;
        Color controlTextColor = Color.white;

        JSpinner yearSpin;
        JSpinner monthSpin;
        JButton[][] daysButton = new JButton[6][7];

        DatePanel() {
            setLayout(new BorderLayout());
            setBorder(new LineBorder(backGroundColor, 2));
            setBackground(backGroundColor);

            JPanel topYearAndMonth = createYearAndMonthPanal();
            add(topYearAndMonth, BorderLayout.NORTH);
            JPanel centerWeekAndDay = createWeekAndDayPanal();
            add(centerWeekAndDay, BorderLayout.CENTER);

            reflushWeekAndDay();
        }

        private JPanel createYearAndMonthPanal() {
            Calendar cal = getCalendar();
            int currentYear = cal.get(Calendar.YEAR);
            int currentMonth = cal.get(Calendar.MONTH) + 1;

            JPanel panel = new JPanel();
            panel.setLayout(new FlowLayout());
            panel.setBackground(controlLineColor);

            yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
                    startYear, lastYear, 1));
            yearSpin.setPreferredSize(new Dimension(56, 20));
            yearSpin.setName("Year");
            yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));
            yearSpin.addChangeListener(this);
            panel.add(yearSpin);

            JLabel yearLabel = new JLabel("Year");
            yearLabel.setForeground(controlTextColor);
            panel.add(yearLabel);

            monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,
                    12, 1));
            monthSpin.setPreferredSize(new Dimension(35, 20));
            monthSpin.setName("Month");
            monthSpin.addChangeListener(this);
            panel.add(monthSpin);

            JLabel monthLabel = new JLabel("Month");
            monthLabel.setForeground(controlTextColor);
            panel.add(monthLabel);

            return panel;
        }

        private JPanel createWeekAndDayPanal() {
            String colname[] = { "S", "M", "T", "W", "T", "F", "S" };
            JPanel panel = new JPanel();
            panel.setFont(new Font("Arial", Font.PLAIN, 10));
            panel.setLayout(new GridLayout(7, 7));
            panel.setBackground(Color.white);

            for (int i = 0; i < 7; i++) {
                JLabel cell = new JLabel(colname[i]);
                cell.setHorizontalAlignment(JLabel.RIGHT);
                if (i == 0 || i == 6) {
                    cell.setForeground(weekendFontColor);
                } else {
                    cell.setForeground(weekFontColor);
                }
                panel.add(cell);
            }

            int actionCommandId = 0;
            for (int i = 0; i < 6; i++)
                for (int j = 0; j < 7; j++) {
                    JButton numBtn = new JButton();
                    numBtn.setBorder(null);
                    numBtn.setHorizontalAlignment(SwingConstants.RIGHT);
                    numBtn.setActionCommand(String
                            .valueOf(actionCommandId));
                    numBtn.setBackground(palletTableColor);
                    numBtn.setForeground(dateFontColor);
                    numBtn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
                            JButton source = (JButton) event.getSource();
                            if (source.getText().length() == 0) {
                                return;
                            }
                            dayColorUpdate(true);
                            source.setForeground(todayBackColor);
                            int newDay = Integer.parseInt(source.getText());
                            Calendar cal = getCalendar();
                            cal.set(Calendar.DAY_OF_MONTH, newDay);
                            setDate(cal.getTime());

                            dateDialog.setVisible(false);
                        }
                    });

                    if (j == 0 || j == 6)
                        numBtn.setForeground(weekendFontColor);
                    else
                        numBtn.setForeground(dateFontColor);
                    daysButton[i][j] = numBtn;
                    panel.add(numBtn);
                    actionCommandId++;
                }

            return panel;
        }

        private Calendar getCalendar() {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(getDate());
            return calendar;
        }

        private int getSelectedYear() {
            return ((Integer) yearSpin.getValue()).intValue();
        }

        private int getSelectedMonth() {
            return ((Integer) monthSpin.getValue()).intValue();
        }

        private void dayColorUpdate(boolean isOldDay) {
            Calendar cal = getCalendar();
            int day = cal.get(Calendar.DAY_OF_MONTH);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            int actionCommandId = day - 2 + cal.get(Calendar.DAY_OF_WEEK);
            int i = actionCommandId / 7;
            int j = actionCommandId % 7;
            if (isOldDay) {
                daysButton[i][j].setForeground(dateFontColor);
            } else {
                daysButton[i][j].setForeground(todayBackColor);
            }
        }

        private void reflushWeekAndDay() {
            Calendar cal = getCalendar();
            cal.set(Calendar.DAY_OF_MONTH, 1);
            int maxDayNo = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
            int dayNo = 2 - cal.get(Calendar.DAY_OF_WEEK);
            for (int i = 0; i < 6; i++) {
                for (int j = 0; j < 7; j++) {
                    String s = "";
                    if (dayNo >= 1 && dayNo <= maxDayNo) {
                        s = String.valueOf(dayNo);
                    }
                    daysButton[i][j].setText(s);
                    dayNo++;
                }
            }
            dayColorUpdate(false);
        }

        public void stateChanged(ChangeEvent e) {
            dayColorUpdate(true);

            JSpinner source = (JSpinner) e.getSource();
            Calendar cal = getCalendar();
            if (source.getName().equals("Year")) {
                cal.set(Calendar.YEAR, getSelectedYear());
            } else {
                cal.set(Calendar.MONTH, getSelectedMonth() - 1);
            }
            setDate(cal.getTime());
            reflushWeekAndDay();
        }
    }
}

A: The LGoodDatePicker library includes a (swing) DatePicker component, which allows the user to choose dates from a calendar. (By default, the users can also type dates from the keyboard, but keyboard entry can be disabled if desired). The DatePicker has automatic data validation, which means (among other things) that any date that the user enters will always be converted to your desired date format.
Fair disclosure: I'm the primary developer.
Since the DatePicker is a swing component, you can add it to any other swing container including (in your scenario) the cells of a JTable.
The most commonly used date formats are automatically supported, and additional date formats can be added if desired.
To enforce your desired date format, you would most likely want to set your chosen format to be the default "display format" for the DatePicker. Formats can be specified by using the Java 8 DateTimeFormatter Patterns. No matter what the user types (or clicks), the date will always be converted to the specified format as soon as the user is done.
Besides the DatePicker, the library also has the TimePicker and DateTimePicker components.
I pasted screenshots of all the components (and the demo program) below.
The library can be installed into your Java project from the project release page.
The project home page is on Github at:
https://github.com/LGoodDatePicker/LGoodDatePicker .

A: *

*Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.

*Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:
TableModel datePicker = new DatePickerTable("01011999","12302000");

*Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:
datePicker.interval = 15;

*Attach your table model into your JTable:
JTable newtable = new JTable (datePicker);

Your Java application now has a drop-down date selection dialog.


Q: C# UI automated testing - Does anyone succeeded to capture the command prompt window object? I have an UI automated test developed with White. One of the cases needs to open cmd and write some commands. The problem is when I input the first command. I tried something like:
Process.Start("CMD.EXE");

///Thread.Sleep(2000);

SendKeys.SendWait(command);

The problem is that sendkeys starts to input before the windows is opened, and trims the command, skipping first characters (depending on window appearance moment). It works with a sleep, but I'm trying to avoid such practices.
In order to avoid this I would insert a timer to wait for the window to be visible. So my questions:

*

*Can this window be captured, so I can wait for it?

OR

*

*Any other way to send the command?

A: for this special case ,you could execute the cmd  to run your commands as args, i mean, avoid sendKeys and execute the cmd like this : Process.Start("CMD.EXE", "/c echo hello world");
note that /c will execute the cmd and exit while /k execute the cmd and return to the CMD prompt.


Q: Pasarela de pago Stripe con Angular Tengo una aplicación con Angular, estoy intentando implementarle un sistema de pagos, ya me crea el token, se supone que ahora debo de crear un servicio y mandar ese token a stripe para que registre el pago, pero claro nose por donde van los tiros estoy un poco perdido, os dejo mi código actual de stripe donde obtengo el token y el enlace a la web de donde seguí los pasos.
  // Realización de renovaciones de licencias con stripe
  loadStripe() {
    if(!window.document.getElementById('stripe-script')) {
      var s = window.document.createElement("script");
      s.id = "stripe-script";
      s.type = "text/javascript";
      s.src = "https://checkout.stripe.com/checkout.js";
      s.onload = () => {
        this.handler = (<any>window).StripeCheckout.configure({
          key: 'MIKEYTEST',
          locale: 'auto',
          token: function (token: any) {
            // You can access the token ID with `token.id`.
            // Get the token ID to your server-side code for use.
            console.log(token)
            alert('Payment Success!!');
          }
        });
      }
      window.document.body.appendChild(s);
    }
  }

  pay(amount) {
    var handler = (<any>window).StripeCheckout.configure({
      key: 'MIKEYTEST',
      locale: 'es',
      country: 'ES',
      currency: 'eur',
      token: function (token: any) {
        // You can access the token ID with `token.id`.
        // Get the token ID to your server-side code for use.
        console.log(token)
        alert('Token Created!!');
      }
    });
    handler.open({
      name: 'XXXXXX',
      description: 'XXXXXX',
      amount: amount * 100
    });
  }

A: Para crear un enlace de Checkout debes seguir los siguientes pasos:

*

*[Backend] Crear una sesión de Checkout desde tu servidor.

*[Frontend] Redirigir al usuario a Checkout para que puedan ingresar sus datos.

*[Backend] Procesar el resultado del pago.

*[Frontend] Mostrar al usuario la página de success/failure.

Puedes ver códigos de ejemplo actualizados en https://stripe.com/docs/payments/checkout/one-time
De todas formas te comento sobre algunos plugins de Angular que parecen simplificar la integración de Checkout utilizando este framework:


Q: Data.Aeson encoding optional keys I have the following problem, I have a JSON format with optional keys that I need to generate from my haskell code.
Lets make an example
{-# LANGUAGE DeriveGeneric #-}

import GHC.Generics
import Data.Aeson

data Person = {
    name :: String,
    shoeSize :: Maybe Int,
    favoriteColor :: Maybe String,
    favoriteFood :: Maybe StringC
} deriving (show, eq, generic)

instance ToJSON Person -- Generic instance

now, if I try encoding a Person without a shoesize I still get a key "shoeSize" set to null, what is the Aeson way of making keys optional in encoding
edit, example of an encode
encode $ Person "windwarrior" Nothing "green" Nothing

should result in
{"name":"windwarrior", "favoriteColor":"green"}

A: Use TemplateHaskell to derive the ToJSON instance instead of Generic. The TH functions optionally take an Options which has the omitNothingFields option.

A: There is the Options datatype with an omitNothingFields field for Generics as well so you don't have to use TemplateHaskell, however there's currently (v0.11.2.0) a bug that makes it generate invalid JSON under certain circumstances, e.g. several record fields. It has been fixed but is in master.
You can also handwrite instances if you prefer, for your example:
instance ToJSON Person where
    toJSON (Person name shoeSize favoriteColor favoriteFood) = object fields
      where
        consMay attr = maybe id ((:) . (attr .=))
        conss = consMay "shoeSize" shoeSize
              . consMay "favoriteColor" favoriteColor
              . consMay "favoriteFood" favoriteFood
        fields = conss ["name" .= name]