How can I store types in go maps for initialisation at a later stage

Question: I'm trying to implement a factory function that will return an instance of one of many structs that fulfil the contract of an interface X.
m := make(map[string] ?)
func init () {
    m["a"] = ?
    m["b"] = ?
}

type X interface {
    y()
}

type A struct {}
func (a * A) y () {}

type B struct {}
func (b * B) y () {}

function factory(name string) X {
    return &m[name]{}
}

The code above is just a simplified demonstration of what I'm trying to achieve - looking for pointers for whether this is possible, or if there is a different go idiom to solve this kind of requirement that I'm missing.
Answer: You can use map[string]X, with X the interface (which can reference a value or a pointer of any object respecting X contract)

or if there is a different go idiom to solve this kind of requirement that I'm missing?

You can also use reflection (as in "Instance new Type") to implement your factory.
reflect.New(yourtype).Elem().Interface()

You can see a factory example in "is there a way to create an instance of a struct from a string?".

The quicker approach for a factory method (returning a new instance each time) is using a switch (like in this example):
// Create a new Widget interface based on WidgetType and set WidgetInfo
func New(wt WidgetType, wi WidgetInfo) Widget_iface {
    switch wt {
    case Widget_A:
        return newWidgetA(wi)
    case Widget_B:
        return newWidgetB(wi)
    }
    return nil
}

Comment: Thanks @VonC. Looks like theres a minor additional overhead of registering the type using an instance but I guess that instance will be garbage collected reasonably quickly?
Comment: @Ali-AkberSaifee yes, it will. But in general reflection is slower so if you intend to call your factory hundreds of time per second, a map is quicker.
Comment: @Ali-AkberSaifee do you want your factory to return a *new* instance of A or B? If yes, I have edited the answer.
Comment: for my current usecase I'm ok with just getting a new instance - but in terms of trying to understand the language I'm curious if I can return just the type
Answer: If you have a simple value type then as @VonC said, you can just use map[string]X and return a copy of the exemplar value.
For anything else, instead of using reflection, I'd just use a map of creation functions. Like what the image package does with
image.RegisterFormat.
E.g. (playground):
package main

import "fmt"

type X interface {
        y()
}

type newXFunc func() X

// Here just a map variable and two functions, but
// this could be a type with two methods instead.

var m = map[string]newXFunc{}

func register(name string, fn newXFunc) {
        m[name] = fn
}

func factory(name string) X {
        return m[name]()
}

func init() {
        // If register is exported than these
        // calls can be in other packages that
        // implement A and B.
        register("a", NewA)
        // For simple things that don't have/need
        // their own stand-alone "new" function.
        register("b", func() X { return B{} })
}

type A struct{}

func (a *A) y() {}
func NewA() X   { return &A{} }

type B struct{}

func (b B) y() {}

func main() {
        a1 := factory("a")
        b1 := factory("b")
        fmt.Printf("%T\n", a1)
        fmt.Printf("%T\n", b1)
}

Comment: A map of functions is more efficient than my answer. +1


JSON.API Failed to fetch

Question: I am trying to set up a React component that will fetch the JSON from my Drupal 9 site using JSON:API and JSON:API Views module.
I can see the JSON when I visit the URL, but get 'failed to fetch' from the React component.
What is the problem?
<code>const endpoint = "http://my_site.com/jsonapi/views/job_listings/page_2";
const Job_Board = () => { const [users, setUsers] = useState([]);

useEffect(() => {
  (async () => {
    const data = await fetch(endpoint).then((res) => res.json());
    setUsers(data);
  })();
}, []);
</code>
Comment: If Drupal's output is correct, but React is failing, then this question belongs on Stack Overflow, not here.  Generally speaking, try using Postman to make the request; if Postman works but fetch() doesn't, you're definitely using fetch() wrong.  Also, consider using a library that has built-in error handling like `axios` instead of fetch.
Comment: Postman GET works fine
Answer: I needed to set CORS headers for the Drupal site. I did this with https://www.drupal.org/project/cors_ui
I just set allowed headers, methods, and origins to *

JSON.API Failed to fetch


WildFly App Dev: how to reflect the runtime classpath at development time?

Question: I am working on a Project that is deployed as .war WebApp on a single WildFly 16 instance.
Using IntelliJ Idea UE with Maven as development environment, I ask myself how to reflect the classpath that the deployed app will see at runtime in the development classpath at development time.
I have read about implicit dependencies in the Developer Guide.
So I conclude that the classpath of my deployment will contain the elements from the "Dependencies that are always added" column plus those that are added on trigger conditions (in my case these are Weld, Web, Hibernate, Resteasy, EJB3).
How can I figure out what Maven artifacts I have to import so that my development classpath equals the runtime classpath of my WebApp?
I would like to solve dependency conflicts at development time, not at runtime.
Answer: You can use the WildFly 16 Bill of Materials (BOM) for that. I'm sure you are well aware of Maven's import feature for artifacts of type POM. Just in case you are not, add these lines to your Maven pom.xml:
<dependencyManagement>
  <dependencies>
      <dependency>
        <groupId>org.wildfly.bom</groupId>
        <artifactId>wildfly-javaee8</artifactId>
        <version>16.0.0.Final</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

It enables you to reference most of WildFly's artifacts (or at least the relevant ones) as well as the Java EE 8 specification artifacts. Here's an example:
<dependencies>
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>org.jboss.spec.javax.servlet</groupId>
    <artifactId>jboss-servlet-api_4.0_spec</artifactId>
    <scope>provided</scope>
  </dependency>
</dependencies>

You still need to list all the dependencies you require though. If you have additional dependencies (not provided by WildFly), you should package them in your WAR or EAR. This way you shouldn't get any conflicts.
Oh, and one more thing, because you mentioned several dependencies, which are WildFly specific (e.g. Weld and Hibernate): Try sticking to Java EE APIs, where possible. It enables you to port your application to other application servers faster, if needed.
Comment: Thank you for answer. If I look into the BOM, there is no mention of jboss-servlet-api_4.0_spec, for example. How would I know that this exact artifact is provided?
Comment: Oh I see, I would find it to be listed here https://mvnrepository.com/artifact/org.wildfly.bom/wildfly-javaee8/16.0.0.Final
Comment: @Thomas, yes, that's right and I totally forgot to mention it. Sorry about that. So to sum up: BOMs too can import BOMs. You will need to dig into those BOM `pom.xml` files to find all the _Maven_ coordinates you need.
Comment: OK, but if I update the WildFly version, I will have to do all of this again, right? There is no simple solution to resolve classpath conflicts, as I can see.
Comment: @Thomas, no, you won't have to do all of it again. Some of the coordinates stay the same, such es Hibernate, Weld, and so on - unless they get dropped of course. The Java EE specification artifact coordinates will change, because the specification version is reflected in the _artifactId_.


$ 1 - \cos 2 \Theta$ can be rewritten as $1 - \left( 1 - 2 \sin^2 \Theta\right)$ - I don't understand why though

Question: Going through a video I saw this and wasn't sure how to sort it -
given the following :
$$  r = 4 \left( 1 - \cos 2 \Theta \right) $$
the part in parenthesis $ 1 - \cos 2 \Theta$ can be rewritten as $1 - \left( 1 -
2 \sin^2 \Theta\right)$.
I'm not sure where this comes from though? I have a sheet of identities, but this
isn't on there. If anyone could point me in the right direction as to why this
can be rewritten as such that'd be ace.
Looking through a sheet such as this
one I can't really intuit
them, I just use them when needed (I couldn't write a proof).
Cheers.
Comment: $\cos2\theta$ is the middle of the double-angle formulas in the bottom left of your formula sheet.
Comment: are you familiar with $\cos2\theta=1-2\sin^2\theta$ (or maybe another formula where $\cos2\theta$ is the LHS)?
Comment: @drhab no this is pretty new to me, and I'm self teaching (if that makes any difference). The thing I'm finding at the moment is that if I am given a formula such as these I can apply it, but I don't have an intuitive understanding of why they work or what they're doing. $y=x^2$ is quite understandable, but these don't really mean anything even though I can see that they work when the answer matches the books or whatnot... Sos if that's a bit off topic !
Answer: There are three forms of the $\cos{2x}$ "double-angle" formula, which you can shift between by using $\cos^2{x}+\sin^2{x}=1$:
$$ \cos{2x} = \cos^2{x}-\sin^2{x} = \cos^2{x}-(1-\cos^2{x}) = 2\cos^2{x}-1 \\
= (1-\sin^2{x})-\sin^2{x}, $$
so
$$ \begin{align}
\cos{2x} &= \cos^2{x}-\sin^2{x} \\
 &= 2\cos^2{x}-1 \\
&= 1-2\sin^2{x}.
\end{align} $$
Answer: Use this identity $\sin^2(x)=\frac{1}{2}(1-\cos(2x))$:

$$ 1 - \cos(2x)=1 - \left( 1 - 2 \sin^2(x)\right) \Longleftrightarrow$$
$$ 1 - \cos(2x)=1 - \left( 1 - 2 \left(\frac{1}{2}(1-\cos(2x))\right)\right) \Longleftrightarrow$$
$$ 1 - \cos(2x)=1 - \left( 1 - \left(1-\cos(2x)\right)\right) \Longleftrightarrow$$
$$ 1 - \cos(2x)=1 - \left( 1 -1+\cos(2x)\right) \Longleftrightarrow$$
$$ 1 - \cos(2x)=1 - \left( 0+\cos(2x)\right) \Longleftrightarrow$$
$$ 1 - \cos(2x)=1 - \cos(2x) $$


Evaluate the Integral $\int\frac{(1+e^x)^2}{e^x}dx$

Question: $\int\frac{(1+e^x)^2}{e^x}\ dx$
$u=e^x$
$du=e^x\ dx$
$\frac{du}{e^x}=dx$
$e^{-x}\ du$
$\int\frac{(1+u)^2}{u}\frac{du}{e^x}$
I am on the right track?
Comment: $1/e^x = e^{-x}$.  So $(1/e^x) * e^{-x} = e^{-x} * e^{-x} = e^{-2x}$.
Comment: No, you can't, you don't simplify $e^x$ with $e^{-x}$.
Comment: Can you explain why this is the case?
Comment: @ Michael Seifert can you take a look at the problem and solve it in the way I am attempting to do so (top to bottom)?
Answer: $$\begin{align*} \frac{(1+e^x)^2}{e^x} &= \frac{(1+e^x)(1+e^x)}{e^x} \\ &= \frac{1+e^x+e^x+(e^x)^2}{e^x} \\ &= \frac{1+2e^x+(e^x)^2}{e^x} \\ &= \frac{1}{e^x} + \frac{2e^x}{e^x} + \frac{(e^x)^2}{e^x} \\ &= e^{-x} + 2 + e^x. \end{align*}$$  Now integrate each term (leaving the constant of integration for the last step when you put everything back together):
$$\int e^{-x} \, dx = -e^{-x},$$ which you can check by differentiating.
$$\int 2 \, dx = 2x$$ since the derivative of $2x$ is $2$.
$$\int e^x \, dx = e^x.$$  So the result is $$\int \frac{(1+e^x)^2}{e^x} \, dx = -e^{-x} + 2x + e^x + C.$$
Comment: Great job! Nonetheless, can you give me the power and integration rule for  $\int e^{-x} \, dx = -e^{-x}$ ? I ma aware of$\frac{d}{dx}x^n=nx^{n-1}$ and $\int x^ndx=\frac{x^n+1}{n+1}+C$ but I can not figure out how you calculated your answer
Comment: @Cetshwayo We know that $$\frac{d}{dx} [ e^x ] = e^x.$$  So using the Chain rule, we know that $$\frac{d}{dx} \left[ e^{f(x)} \right] = e^{f(x)} \frac{df}{dx}.$$  Therefore, the derivative of $e^{-x}$ is $-e^{-x}$ (with the choice $f(x) = -x$), and consequently, an antiderivative of $-e^{-x}$ is $e^{-x}$.  It follows that an antiderivative of $e^{-x}$ is $-e^{-x}$.
Answer: If you differentiate your answer, you will see that it isn't correct.
Instead, notice that: $$(1+e^x)^2e^{-x}=(1+2e^x+e^{2x})e^{-x}=e^{-x}+2+e^{x},$$ so the primitive is: $$-e^{-x}+2x+e^{x}+c.$$
Comment: You should be more careful before claiming mistakes: $e^{2x}\,e^{-x}=e^x$.
Comment: I do't follow what you did. Can you follow my layout (top to bottom) and express your steps?
Comment: @JuliánAguirre I never claimed I didn't make one :P
Comment: @Sonner Your answer is wrong. The second term of the last line must be $2x$.
Comment: Ok fine I should have just said "and the result easily follows"...
Answer: Take $e^{x}=u$, $du=e^{x}dx$ to get $$\int\frac{\left(1+e^{x}\right)^{2}}{e^{x}}dx=\int\frac{\left(1+u\right)^{2}}{u^{2}}du=\int\frac{u^{2}+2u+1}{u^{2}}du
 $$ so we have $$=\int\frac{u^{2}+2u+1}{u^{2}}du=\int\frac{u^{2}}{u^{2}}du+\int\frac{2u}{u^{2}}du+\int\frac{1}{u^{2}}du=$$ $$=u+2\log(u)-\frac{1}{u}+C$$ now substitute back.
Comment: You skipped to many steps. I can't follow what you did. If I knew how to solve the problem I wouldn't be asking.
Comment: Ok I will add some steps.
Comment: Where did the $u^2$ come from. I understand you replaced the $e^x$ terms with $u$ but I am confused as to why u is squared. And what happened to $\frac{du}{e^x}$ = dx?
Comment: @Cetshwayo Note that $u=e^{x}$ so from that you have $dx=du/u$.
Comment: @avid19 You're right ;)
Comment: @MarcoCantarini Actually since $u=e^x$ and $e^x>0$, it's okay to not have $|u|$ there but it is just something that might have been addressed. Either way +1
Comment: Look at my edit and tell me where I am going wrong. Thanks.
Comment: @Cetshwayo Using the substitution you have $e^{x}=u$ so from your actual form you get the $u^{2}$ at the denominator, like me. If you want, use the equivalent substitution $x=\log(u)$.


Motivation behind locally convex spaces, seminorms, and Frechet spaces

Question: I am looking for some motivation behind the definition of locally convex spaces, seminorms, and Frechet spaces. Since all three concepts are related I have grouped them as one question. I am familiar with the technical definitions but I don't see what would lead one to defining them.
What is so special about locally convex spaces that we wish to focus are analysis only on them?
I am aware that seminorms are generalizations of norms but with the condition $\|x \| = 0 \implies x = 0$ dropped. But why do we care about such objects?
The idea of angles and inner products would naturally lead one to define a Hilbert space and similarly length would lead one to define Banach spaces. Is there any similar idea that a Frechet space captures?
Comment: You should probably read all that from the lion's paws. See Dieudonne, J. History of Functional Analysis Chapter VIII. Section 2.
Comment: Finite dimensional Hilbert and Banach spaces can be viewed as geometric space, but I have never viewed the infinite dimensional versions as geometric spaces. In applications, these spaces are usually spaces of functions, where the linear and topological structures are quite useful. I don't have any geometric intuition for these spaces. I don't think of these spaces as geometric spaces. A Frechet space is nontrivial only if it is infinite dimensional. Again, for me it is useful only as a space of functions.
Comment: (not posting as an answer because not comprehensive) I would point out that for open $\Omega \subseteq \mathbb R^d$ and $k \in \mathbb Z_{\ge 1} \cup \{\infty\}$, $C^k(\Omega)$ is a Frechet space that is not normable. Distributions can be understood as the continuous linear functionals on $C_0^\infty(\Omega) \subseteq C^\infty(\Omega)$, understood as a locally convex space, and so on. The choice of seminorms for $C^k$ is $p_{\alpha, K}(u) = \sup_K |\partial^\alpha u|$ for each compact $K \subseteq \Omega$ and multi-index $|\alpha| \le k$.
Comment: oh, and to give some sense to this, the topology on $C^k$ then becomes that of uniform convergence on compacts. So $u_n \to u$ in this topology iff $\sup_K |\partial^\alpha u_n - \partial^\alpha u| \to 0$ for each compact $K$ and suitable $\alpha$
Comment: Spaces of $C^\infty$ functions are never Banach spaces but are Frechet spaces. So if for example you want to prove the existence of a smooth solution to a nonlinear PDE, it is sometimes best to use Frechet spaces. This is the case if you want to use the Nash implicit function theorem.
Comment: @MarianoSuárez-Álvarez I think the existence of motivating examples answers my question, but I was wondering if there was, say, a geometric motivation as we have in Hilbert or Banach spaces
Comment: @Deane I see, so the definition is as it is because it captures a lot of frequently occurring examples? Is there any geometric idea that Frechet captures like Banach or Hilbert spaces do?
Comment: @MarianoSuárez-Álvarez But is there any overarching theme that Frechet spaces or seminorms capture? For example Hilbert spaces and inner products are defined the way they are, as you mention, based on examples that all involve angles. But all the examples have the same theme of angles. I was wondering if seminorms or Frechet spaces have any similar overarching theme.
Comment: @Deane Thank you for your comment.
Comment: @MarianoSuárez-Álvarez Thank you, that explanation of seminorms capturing only part of a thing is very helpful.
Answer: Why Locally Convex Topological Vector Spaces?
Some reasons why the attention is focused on locally convex (Hausdorff) spaces:

The topological vector space topology generated by a family of semi norms is locally convex (meaning that such a topology arises quiet naturally, because semi norms arise naturally in the study of function spaces and operator spaces)
Many interesting topological vector space topologies generated by a family of semi norms are neither normable nor metrizable.
The theorem of Hahn-Banach remains true for locally convex spaces (Hahn Banach gets brutally violated even by metrizable topological vector spaces, this is one of the reasons why we dont focus our attention on those)

Some of the motivation for the study of locally convex spaces:

The weak topology on a Hilbert space is not metrizable (and therefore also not normable).
The first to show this was von Neumann, who shortly after was the first to define a locally convex topological vector space.
Schwartz, Dieudonne, Grothendieck and others were motivated to develop the theory of locally convex spaces as we know it today by the study of function spaces and distributions

Example: Locally Convex Topology Of Pointwise Convergence
In the context of function spaces seminorms and locally convex topological vector spaces arise naturally, as the following example shows:
Let $S$ be any set and let $F$ be the set of all functions $S \to \mathbb{C}$ with the obvious (pointwise) vector space operations.
Then for each $s \in S$ we can define a semi-norm $p_s: F\to [0,\infty)$ by
$$p_s(f) = | f(s) | \quad \forall f \in F.$$
The semi norm $p_s$ does not give us the "size" (or length) of the function, but it gives us "partial information" about the size of $f$ (namely the size of $f$ at $s$). This is how semi-norms are usually defined in this context: They give us the "size" of some aspect of the function.
Together all the semi norms $(p_s)_{s \in S}$ give us a complete "picture" of the function. Namely if $f\neq 0$, then there exist a $s \in S$ with $p_s(f) \neq0$. This property will translate to the fact that the topological vector space topology generated by this family of semi-norms is point separating.
Now endow $F$ with the topological vector space topology $\tau$ generated by the family of semi-norms $(p_s)_{s \in S}$. Then (by a general result) a sequence $(f_n)_{n \in \mathbb{N}}$ in $F$ (or more generally a net) converges to $f\in F$ with respect to $\tau$ if and only if
$$
\lim_{n \to \infty} p_s(f-f_n)= 0 \quad \forall s \in S.
$$
In other words $f_n \overset{\tau}{\to} f$, if and only if $f_n(s) \overset{| \cdot| }{\to} f(s)$ for all $s \in S$.
Therefore the elementary idea of pointwise convergence (that can be found in even the most basic analysis book) is captured with this topology, which is clearly a very usefull thing.

Why Frechet Spaces?
The (or at least part of the) reason why Frechet spaces are interesting is that

a few major theorems in Banach space functional analysis hold for Frechet spaces as well (some are listed here)
Some interesting locally convex spaces (that are not normable) are Frechet spaces (for example the Schwartz space or the space described in the comment by George C)

I dont think that there is any deeper motivation than the above (although i might be wrong of course). I think they are used, because someone realised that being a Frechet space is enough to prove some of the major Banach space theory results and that some interesting spaces are Frechet spaces.
Comment: @MarianoSuárez-Álvarez But that does not explain why we should care about locally convex topological vector spaces instead of say topological vector spaces or any other way to generalize banach spaces.
Comment: Thank you, this was extremely insightful!
Answer: In Dieudonne's "History of Functional Analysis", Chapter VIII is on locally convex spaces and distributions, and Section 2 discusses the development of locally convex spaces. In the 1st paragraph he writes

the various notions belonging to what we now call the general theory of topological vector spaces made their appearance in a rather random way and were not the subject of a systematic treatment until 1950.

In 1906 Mazur and Orlicz defined Frechet spaces (called by them "spaces of type $B_0$") and in 1935, von Neumann defined locally convex spaces (called by him "convex spaces").
Dieudonne particularly emphasizes the work of Grothedieck on the tensor product of locally convex spaces, calling it

the greatest progress in functional analysis after the work of Banach.

In the 1950s, Grothendieck introduced nuclear spaces in his work on topological tensor products. Nuclear spaces are locally convex and generalize Euclidean spaces in a quite different way than Banach spaces: a nuclear space is a Banach space if and only if it is finite-dimensional. So perhaps it was the introduction of nuclear spaces that brought attention to the need for a systematic development of locally convex spaces and more generally topological vector spaces.
Comment: @CBBAM   See https://mathoverflow.net/questions/442204/nuclear-spaces-and-intuition-behind-their-topology both the answers and comments.
Comment: Thank you. Much of the reason I am interested in this area of functional analysis is to build up to nuclear spaces. How do these generalize Euclidean space? And do you have any references you can recommend to learn about nuclear spaces?
Comment: re: nuclear spaces behaving like finite-dimensional ones, this is particularly relevant in the case of multilinear algebra, e.g., the Schawrtz Kernel Theorem see https://math.stackexchange.com/questions/2623515/schwartz-kernel-theorem-and-dual-topologies/2647815#2647815 and in the case of probability theory where Bochner's Theorem and the Levy Continuity Theorem have formulations which are as clean and simple as in the finite-dimensional situation, see https://mathoverflow.net/questions/384124/bochner-minlos-for-moment-generating-functions/384168#384168 ...
Comment: ...this is especially useful in quantum field theory which deals with probability measures on spaces of distributions like $\mathscr{S}'$.
Comment: @AbdelmalekAbdesselam Thank you for your comment. Quantum field theory is actually the reason I am interested in nuclear spaces. I tried reading some of the literature on rigorous QFT but I noticed I need to learn more about nuclear spaces/operators and probability theory on distribution spaces before continuing. For this I've been reading through the fourth volume of Gelfand and Vilenkin's series on generalized functions. Is there any other resource you recommend or is their treatment of these subjects enough to read, for example, Glimm & Jaffe's book?
Comment: Unfortunately, that's a lot of wasted effort, since you have taken the very long way around when there is much more direct route: learn the isomorphism with spaces of sequences, prove the Bochner-Minlos theorem for sequence spaces, and then transfer it to $S'$. This is what I have been explaining in my previous answers. For learning about probability theory on spaces of distributions in 2024, the books by GJ and GV are not the best source.
Comment: If you email me I can send you lecture notes on distributions where the sequence space isomorphism is done in detail. For Bochner-Minlos and Levy Continuity see https://arxiv.org/abs/1706.09326
Comment: @AbdelmalekAbdesselam Thank you very much! I will send you an email.
Comment: @AbdelmalekAbdesselam I am having some issues with my email. May we discuss this further in a stackexchange chat?
Comment: @CBBAM: I don't correspond by email with pseudonyms. In any case, I just resurrected my webpage and the notes I talked about are posted here https://mabdesselam.github.io/MATH7320Fall2017.html The sequence space stuff is in Chapter 4.
Comment: @AbdelmalekAbdesselam Thank you!


Missing data from socket

Question: I am trying to write Java code to receive data from a streaming HTTP connection (I would like to debug a problem I have with running Sockjs XHR-streaming against a spring-websocket server).
I use some really simple code to connect:
    URI uri = // The server
    Socket socket = new Socket();
    socket.connect(new InetSocketAddress(uri.getHost(), uri.getPort()));
    OutputStream os = socket.getOutputStream();
    PrintWriter pw = new PrintWriter(os);
    int id = new Random().nextInt() % 100000;
    pw.println("POST /socket/" + id + "/xxx/xhr_streaming HTTP/1.1");
    pw.println("Content-Type: application/stomp");
    pw.println("Content-Length: 0");
    pw.println("Connection: keep-alive");
    pw.println();
    pw.flush();
    InputStream is = socket.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[8192];
    int bytes;
    do {
        bytes = is.read(buffer);
        if (bytes > 0) {
            System.out.println("read: "+ bytes);
            System.out.print(new String(buffer, 0, bytes));
            System.out.println("----");
        }
    } while (bytes >= 0);

but when I run it I only get the HTTP headers.
That would not be too surprising in itself. I would suspect that the server did not send the contents properly.
But when I monitor the traffic using Wireshark, I can see that I receive three TCP segments in response to my POST. One containing 1460 bytes (+54 bytes TCP/IP headers), one of 1178 bytes (+54 bytes header) and one of 7 bytes (+44 bytes header).
The first one contains the HTTP headers as well as 878 bytes of the contents (Sockjs XHR streaming starts with sending a preamble of 2048 h's). The next one contains the rest of the preamble and the final one contains the 'open frame'. Exactly as I would expect from the server.
Why do my Java code not receive the remaining data? When I use a raw Socket it should be completely unaware of the HTTP protocol, so I do not understand why I receive only the HTTP headers. The server probably flushes the data after writing the headers, but I can see in the network-dump that both the headers and the first part of the data is contained in the first TCP segment.
Here is a dump of the first received TCP segment:
0000   e8 39 35 45 20 df 00 0c 29 09 62 3b 08 00 45 00  .95E ...).b;..E.
0010   05 dc 0c 5e 40 00 80 06 5b 27 c0 a8 06 26 c0 a8  ...^@...['...&..
0020   06 20 1f 90 df d9 92 50 c3 f6 ac 89 8a c3 50 10  . .....P......P.
0030   01 00 fc 88 00 00 48 54 54 50 2f 31 2e 31 20 32  ......HTTP/1.1 2
0040   30 30 20 4f 4b 0d 0a 53 65 72 76 65 72 3a 20 41  00 OK..Server: A
0050   70 61 63 68 65 2d 43 6f 79 6f 74 65 2f 31 2e 31  pache-Coyote/1.1
0060   0d 0a 58 2d 55 41 2d 43 6f 6d 70 61 74 69 62 6c  ..X-UA-Compatibl
0070   65 3a 20 49 45 3d 65 64 67 65 2c 63 68 72 6f 6d  e: IE=edge,chrom
0080   65 3d 31 0d 0a 58 2d 43 6f 6e 74 65 6e 74 2d 54  e=1..X-Content-T
0090   79 70 65 2d 4f 70 74 69 6f 6e 73 3a 20 6e 6f 73  ype-Options: nos
00a0   6e 69 66 66 0d 0a 58 2d 58 53 53 2d 50 72 6f 74  niff..X-XSS-Prot
00b0   65 63 74 69 6f 6e 3a 20 31 3b 20 6d 6f 64 65 3d  ection: 1; mode=
00c0   62 6c 6f 63 6b 0d 0a 43 61 63 68 65 2d 43 6f 6e  block..Cache-Con
00d0   74 72 6f 6c 3a 20 6e 6f 2d 63 61 63 68 65 2c 20  trol: no-cache,
00e0   6e 6f 2d 73 74 6f 72 65 2c 20 6d 61 78 2d 61 67  no-store, max-ag
00f0   65 3d 30 2c 20 6d 75 73 74 2d 72 65 76 61 6c 69  e=0, must-revali
0100   64 61 74 65 0d 0a 50 72 61 67 6d 61 3a 20 6e 6f  date..Pragma: no
0110   2d 63 61 63 68 65 0d 0a 45 78 70 69 72 65 73 3a  -cache..Expires:
0120   20 30 0d 0a 58 2d 46 72 61 6d 65 2d 4f 70 74 69   0..X-Frame-Opti
0130   6f 6e 73 3a 20 44 45 4e 59 0d 0a 58 2d 46 72 61  ons: DENY..X-Fra
0140   6d 65 2d 4f 70 74 69 6f 6e 73 3a 20 41 4c 4c 4f  me-Options: ALLO
0150   57 2d 46 52 4f 4d 20 2a 0d 0a 58 2d 41 70 70 6c  W-FROM *..X-Appl
0160   69 63 61 74 69 6f 6e 2d 43 6f 6e 74 65 78 74 3a  ication-Context:
0170   20 61 70 70 6c 69 63 61 74 69 6f 6e 0d 0a 43 61   application..Ca
0180   63 68 65 2d 43 6f 6e 74 72 6f 6c 3a 20 6e 6f 2d  che-Control: no-
0190   73 74 6f 72 65 2c 20 6e 6f 2d 63 61 63 68 65 2c  store, no-cache,
01a0   20 6d 75 73 74 2d 72 65 76 61 6c 69 64 61 74 65   must-revalidate
01b0   2c 20 6d 61 78 2d 61 67 65 3d 30 0d 0a 41 63 63  , max-age=0..Acc
01c0   65 73 73 2d 43 6f 6e 74 72 6f 6c 2d 41 6c 6c 6f  ess-Control-Allo
01d0   77 2d 4f 72 69 67 69 6e 3a 20 2a 0d 0a 41 63 63  w-Origin: *..Acc
01e0   65 73 73 2d 43 6f 6e 74 72 6f 6c 2d 41 6c 6c 6f  ess-Control-Allo
01f0   77 2d 43 72 65 64 65 6e 74 69 61 6c 73 3a 20 74  w-Credentials: t
0200   72 75 65 0d 0a 43 6f 6e 74 65 6e 74 2d 54 79 70  rue..Content-Typ
0210   65 3a 20 61 70 70 6c 69 63 61 74 69 6f 6e 2f 6a  e: application/j
0220   61 76 61 73 63 72 69 70 74 3b 63 68 61 72 73 65  avascript;charse
0230   74 3d 55 54 46 2d 38 0d 0a 54 72 61 6e 73 66 65  t=UTF-8..Transfe
0240   72 2d 45 6e 63 6f 64 69 6e 67 3a 20 63 68 75 6e  r-Encoding: chun
0250   6b 65 64 0d 0a 44 61 74 65 3a 20 46 72 69 2c 20  ked..Date: Fri,
0260   32 36 20 53 65 70 20 32 30 31 34 20 30 39 3a 32  26 Sep 2014 09:2
0270   36 3a 31 37 20 47 4d 54 0d 0a 0d 0a 38 30 31 0d  6:17 GMT....801.
0280   0a 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  .hhhhhhhhhhhhhhh
0290   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
02a0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
02b0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
02c0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
02d0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
02e0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
02f0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0300   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0310   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0320   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0330   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0340   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0350   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0360   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0370   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0380   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0390   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
03a0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
03b0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
03c0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
03d0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
03e0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
03f0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0400   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0410   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0420   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0430   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0440   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0450   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0460   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0470   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0480   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0490   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
04a0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
04b0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
04c0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
04d0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
04e0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
04f0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0500   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0510   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0520   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0530   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0540   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0550   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0560   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0570   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0580   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
0590   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
05a0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
05b0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
05c0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
05d0   68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68  hhhhhhhhhhhhhhhh
05e0   68 68 68 68 68 68 68 68 68 68                    hhhhhhhhhh

and here is the output from the code:
read: 582
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
X-UA-Compatible: IE=edge,chrome=1
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
X-Frame-Options: ALLOW-FROM *
X-Application-Context: application
Cache-Control: no-store, no-cache, must-revalidate, max-age=0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Content-Type: application/javascript;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 26 Sep 2014 09:26:17 GMT

----

How do I get the remaining data?
Edit: If I decrease the receive buffer size and write a single byte to the outputstream after reading, I seem to receive the missing data. Why is that?
Comment: Decreasing the receive buffer size somehow makes it work. Why?!
Comment: Scratch that. Decreasing the receive buffer size in combination with writing data to the OutputStream works, however.
Comment: "*The first one contains the HTTP headers as well as 878 bytes of the contents ...*" and in the logs you show it says: `read: 582` and then the header follows. This does not fit. Or am I missing something?
Comment: @alk : When I inspect the network traffic using Wireshark, I see three TCP segments, the first of which contains the HTTP headers and 878 bytes of content. But my application only receives the HTTP headers after which read() just blocks without providing the remaining data. I agree: this does not fit, but I too am probably missing something.
Comment: Ahok, out of the 1st packet's 878 bytes your 1st call to `read()` returns 582 bytes. And then? `read()` blocks, or it returns `-1` and the loop exits? Does it ever return `0`? Or what else?
Comment: @Ahok: It just blocks until the server closes the connection (which it does after 5 minutes). At that point it receives the missing data in two blocks and finally returns -1.
Comment: @alk : Sorry, that should have been alk instead of ahok.
Comment: Don't use println() for HTTP. The line terminator is defined strictly as \r\n, not whatever rprintln() may happen to do on your system.
Answer: Turns out that it was caused by my virusscanner's "online shield". As soon as I turned off AVG AntiVirus Business Editions' online shield, my missing data started coming through. Looks like it does not like streaming data.

Missing data from socket


How to "fix" Toccata and fugue?

Question: Disclaimer: I know Toccata and Fugue in D Minor (BWV 565) is a classic, and a very good piece for many musicians. It's just that it's not right for me, for the reasons below.
So I really like a lot of Toccata and Fugue, but there's a few problems for me if I want to play it. For one thing, I have a piano instead of an organ, so it'll obviously not be the original. But theres a few other things I'd like to change about it. I'm also fairly new, so this piece is about twice as long as I can learn. And I know this bit is subjective but I'd like to have the theme at the beginning show up again in the song like a chorus.
So how can I change a classical piece like this to be easier to play for me? I thought of just cutting and pasting bits of it, but I doubt it would turn out well.
Is there a procedure for changing lengthy pieces?
Answer: There is no "one fits all" procedure. What you want to do is arranging: cutting out parts, changing where notes are to fit the instrument or your hand. Arranging was and is very commonly done by many composers and interprets, especially with orchestra scores. Busoni arranged many Bach pieces from organ or orchestra to piano, and added many things that where not written, though gracefully. You have a full range of piece modification from arranging, transcript, to write a fantasia. What you are looking for is the simplest of them: arranging.
Bach and his peers were arranging and improvising, rearranging a lot, so "he" would encourage you to do so.
A good start is to analyse the piece and spot themes (melodic, harmony, rythmic, etc), variations, harmony progression, and remove parts that are dispensable in your opinion, while avoiding cutting in the middle of a sentence, and make sure that the new harmonic progression is acceptable. Analysis is also very good and can help you understand better the piece and remember it formally.
If you're refering to BWV565, the piece is a lot simpler than other Bach pieces such as BWV1080 or BWV1079, so it's rather a good one to start arranging.
You may start arranging without too much analysis: just jump from the end of one part to another, and evaluate if you like the result, and if it makes sense.
As for the "organ to piano" arranging, just play what you can and skip or change the octava of what you can't play easily; if it's already doubled, just drop the note. Busoni published many organ to piano arrangings, you may be inspired by those texts.
At last, if you want to add new elements and improvise from the piece, just do it, you may want to try to do something like Bach would do, but it's not an obligation. Understanding and analyzing how an author is writing can take some time, but it's useful to know that in order to write à la manière de.
A trick: you mentionned the desire to repeat the theme like a chorus; you might want to consider also harmonic marchs, which J.S.Bach used a lot: you take a small sentence and you just play it again transposed say one tone below or above, as many times you may find it fitting both what you want or like and the mindset or aesthetics of the piece.
Answer: Given the popularity of that piece, there should already exist numerous simplifications as score. I recommend to search for one of those, e. g. this at SheetMusicPlus.
Note, that the fugue is far less well-known, so you may restrict to the toccata in the first step.
Simplifying and condensing an existing piece is an advanced topic, where I see only small chances of a satisfying result for a non-experienced amateur.
Answer:
And I know this bit is subjective but I'd like to have the theme at the beginning show up again in the song like a chorus.

Well, one thing to keep in mind is that is not classical music but baroque, and a toccata and particularly a fugue are musical forms with a certain structure that progressively addresses a theme and works towards a conclusion.  "I'd like to have the theme at the beginning show up again in the song like a chorus" is something that happens in a rondo, and it implies a musical progression both from the repeated theme as well as the previous continuation.
So "rearranging" this comparatively well-known work is not likely to lead to convincing results.  Instead think more in terms of parodying it.  I actually remember hearing this at one time used for a Samba (I had to leave the dance floor because that made it impossible for me to focus on dancing).  That would have been the kind of "structurally simplified parody with thematic repetition" general approach that would work for amusing an audience.
However, losing the original thematic progression and continuum would mean that you should add structure and elements of your own tying this together into a coherent whole.
That's fairly non-trivial.  Here is one example that does some simplistic arrangement (including theme repeats) on diatonic accordion, stealing fragments of both toccata and fugue to make up a coherent whole.  It does not have the baroque tenacity of thematic work but has, well, something.

How to "fix" Toccata and fugue?


Templatization for different countries

Question: Which is the best module to do a multilingual site for different countries. This is the exact word from client requirement.
"Site created for ABC country can be quickly adapted for country XYZ"
They are mainly looking for reuse of code.  Like they create a website for one country and they reuse the same code and same DB fro different county but language will be different.
Answer: You can maybe try something like this:
<code>function phptemplate_preprocess_node(&$vars, $hook) {
    $language = $vars['language']->language;
    $vars['template_file'] = 'page-'. $language;
}
</code>
Answer: Drupal has user interface localisation out of the box.  For user generated content,  I18N module will be your friend.  This module offers an interface for translation and contains submodules to translate your menus, paths, variables, including your node content.  You can even hook-up to IcanLocalize and have your content translated by professional translators.
Be aware, with all this power comes a small cost: there is some tweaking and configuring to do before everything plays nice, first time can be painful. I very highly recommend you read the documentation before diving in, to have an idea of how the pieces work together.
Good-luck, happy coding!

Templatization for different countries


Rootless Podman UID mapping and volume mount issues

Question: I am trying to start kafka inside a container via podman-compose.  I am using /opt/kafka/kafka_2.12-2.4.1/bin/kafka-server-start.sh which is fine.  However, I am mounting a directory that contains the properties file /home/vagrant/repos/kafkazookeeper/config:/home/kafka/config. Right now, this properties file has owner/group permissions of nobody/nobody. On the host, the kafka user is kafka:x:1001:1001::/home/kafka:/bin/bash but in the container, the kafka user is kafka:x:1000:0::/opt/kafka/:/bin/bash
I've tried using --uidmap 1001:kafka in the docker-compose.yaml but that didn't work. Any thoughts are greatly appreciated.
Answer: I would highly recommend reading this article: https://www.redhat.com/sysadmin/rootless-podman-makes-sense
Users and their UIDs in a container get mapped onto a different set of users and UIDs on the host.  This is controlled by /etc/subuid and /etc/subgid and you can see the actual mappings when you run podman unshare cat /proc/self/uid_map.
If you run the container under the kafka user on the host, the kafka user is going to be mapped to root inside the container. You cannot map the kafka user inside the container to the kafka user outside the container because root is already mapped to it and you can't map two different UIDs in the container to a single one on the host.
I think you can either set the permissions on the config files to be readable by everybody.  Or you can create another user on the host, map it to the kafka user inside the container using --uidmap and then use the newly created user to control the configuration.


Dirac delta function and dirac measure

Question: I want to know the relationship between these two things. e.g. What's the results of following integrals? (Let $\mu$ Lebesgue measure, $\nu$ Dirac measure)
$$(1)\int\delta_c(x)\mu(dx)$$
$$(2)\int\delta_c(x)\nu(dx)$$
$$(3)\int f(x)\delta_c(x)\mu(dx)$$
$$(4)\int f(x)\delta_c(x)\nu(dx)$$
Comment: Why do you use the same notation for the Dirac delta distribution $\delta(x)$ defined by $\int_\mathbb{R} \varphi(x) \delta(x)dx = \varphi(0)$ (whenever $\varphi$ is continuous at $0$) and the Dirac measure $\nu((a,b)) = \int_{(a,b)} d\nu(x) =\int_\mathbb{R}1_{x \in (a,b)} d\nu(x)= \int_{(a,b)} \delta(x)dx = 1_{0 \in (a,b)}$ ie. $\int_\mathbb{R} \varphi(x) \delta(x)dx = \int_\mathbb{R} \varphi(x) d\nu(x)=\int_\mathbb{R} \varphi(x) \nu(dx)$ ?
Comment: What does $\delta_c$ mean as a function?
Comment: @reuns, sorry about that but that is what I mean.
Comment: @copper.hat, $\delta_c$ is the dirac delta function. I've corrected the notation in the question.
Comment: @reuns, I've corrected the notation and my question remains the same. What's thes result of these four integrals?
Comment: What did you try given what I wrote ?
Comment: @reuns So is $\int\varphi(x)\delta(x)\nu(dx)$ meaningless or it equals to something?
Comment: What is your guess ?
Comment: @reuns I guess it is meaningless or equals infinity? I'm not sure since I don't know how to use $\delta(x)$ to define a general probability function of a mixed random variable with a measure that is not Lebesgue.
Comment: A useful definition of $\delta(x)$ is $$\int_{-\infty}^\infty \varphi(x) \delta(x) dx = \lim_{\epsilon \to 0}\int_{-\infty}^\infty \varphi(x) \frac{1_{|x| < \epsilon}}{2 \epsilon} dx$$ Note you can replace $1_{|x| < \epsilon}$ by $1_{x \in  (\epsilon,3 \epsilon)}$ the result will be the same whenever $\varphi$ is continuous.
Comment: They are not meaningful as functions, but they can be made sense as distributions over $\mathcal{D}(\mathbb{R})$ via the notion of **convolution**. Indeed, if $\mu$ is a $\sigma$-finite measure on $\mathbb{R}$ (which covers OP's all the four cases), then as a distribution, $$ \forall\varphi\in\mathcal{D}(\mathbb{R}) \ : \quad \int \varphi(c) \int \delta_c(x)\,\mu(\mathrm{d}x) \, \mathrm{d}c = (\delta_0 \star \mu)[\varphi] = \mu[\varphi].$$
Answer: So first the Dirac delta is not and can not be a function but it is a distribution of order $0$, which can be seen as a measure. This is why it is better to use the notation
$$
\int f(x)\,\delta_c(\mathrm{d}x) = f(c)
$$
or $\langle \delta_c,f\rangle = f(c)$. In particular, there is no general way to multiply two measures.  However, one can multiply a measure by a continuous function. Moreover, one can associate to every measure $\lambda$ that is absolutely continuous with respect to the Lebesgue measure a function $f_\lambda$ and so one can identify these measures with functions by writing $\lambda(\mathrm{d}x) = f_\lambda(x)\,\mu(\mathrm{d}x)$ (and one usually denotes just by $\mathrm{d}x$ the Lebesgue measure so that the associated function is $1$). So one could define the product of $\delta_c$ with $\lambda$ by $(\lambda\delta_c)(\mathrm{d}x) = f_{\lambda}(x)\,\delta_c(\mathrm{d}x)$. In any case, one cannot multiply the Dirac delta with itself.
Knowing all that, lets try to give a meaning to your very formal expressions:
$$\begin{align*}
(1)&& \int 1\, \delta_c(\mathrm{d}x) &= 1
\\
(2)&& \int \delta_c(\mathrm{d}x)^2 &\ \textbf{ has no meaning!}
\\
(3)&& \int f(x)\,1\, \delta_c(\mathrm{d}x) &= f(c)
\\
(4)&& \int f(x)\,\delta_c(\mathrm{d}x)^2 &\ \textbf{ has no meaning!}
\end{align*}$$
As usual, this comes from the misconception that $\delta_c$ is a function ...
Edit: I see in the comments you are asking about probability distributions. In general, probability distributions can be measures that are not absolutely with respect to the Lebesgue measure. As an example, $\mathbf{1}_{[0,1]}$ is the distribution of the uniform law in $[0,1]$, $\delta_0$ is the distribution of the constant law $\mathbb{P}(X=0)=1$. You can for example then get $f = \frac{1}{2} \mathbf{1}_{[0,1]} + \frac{1}{2} \delta_0$ to get half a chance to get $0$ and half the chance to be in $[0,1]$. But there is no meaning to multiply probability distributions. The product of random variables will imply the convolution product of their probability distributions, and the law of a couple $(X,Y)$ will be the tensor product of their probability distributions (which always make sense for distributions).
Answer: In analysis and probability, Dirac's delta $\delta_c$ is commonly seen as a function defined on a space of functions. Here are two examples:

In the Theory of distributions for example $\delta_c$ is defined as  $\delta_c:\mathcal{C}^\infty_c(\mathbb{R}^d)\rightarrow\mathbb{R}$ defined as $\delta_c\phi = \phi(c)$.  Clearly $\delta_c$ defines a linear function.

In measure theory or the thoery of integration, the $\delta_c$ is defined as a measure on a measurable space $(X,\mathscr{B})$ such that $\delta_c(A)=1$ if $c\in A$, $0$ otherwise. It is easily seen that $\delta_c$ induces a linear function on the space of measurable functions on $(X,\mathscr{B})$ be setting $\delta_cf=f(c)$.

your expressions (1)-(4) are not properly defined unless there is some additional context. For instance, if $\delta_c$ and $\mu$ are measures,  it make sense to talk about the product measure $\delta_c\otimes\mu$:
$$
\int f(x,y)\delta_c(dx)\mu(dy)=\int f(c,y)\mu(dy)$$
If  $\delta_c$ is though of as a  distributions, and may talk about $\delta_c*\phi$, for any $\phi\in C^\infty_c(\mathbb{R}^d)$
Comment: I would say a functional or a mapping on a space of functions, in order to reserve the word function to functions defined on finite dimensional spaces and avoid the confusions of all these people struggling with the Dirac delta.
Comment: And also write $\delta_c(f)$, $\delta_c[f]$ or $\langle \delta_c, f\rangle$ to emphasise that you are talking about a functional acting on $f$ there, and not a generalisation of the product of functions. The product of the delta with a continuous function is $\delta_c f = f(c)\, \delta_c$

Dirac delta function and dirac measure


Create a timer in asp.net Server side

Question: I have a asp.net web application , in that application I will call a function once that function s called , it has to wait for some time interval then execution should take place how to do that.......
Comment: Why do want this? What are you trying to achieve?
Comment: Timer is related to threads and in server side programming you are not supposed to use threads. You have to make it to work alternatively for whatever you want to do. First you see whether what you need to achieve is possible thru different event trigger or can do same using Javascript ajax call or some other means.
Answer: Sleeping or delaying the thread in asp.net is not recommended.  If you need to to retrieve some data after a specific period of time, make an ajax call  through javascript after a period of time.
If you want to perform some action (such as sending an email) after some time, create a service or a console application that you can run on a timer, create some sort of persistent queue, and have said service process the items in the queue.
This will allow your app to remain quick and responsive while still performing the actions you require.
Answer: you can do it like this System.Threading.Thread.Sleep(5000); 5000 = 5 seconds
since you only need it once
Answer: The simplest is:
Thread.Sleep(<mlsec>)

The coolest is using some scheduler, e.g. Quartz.net.

Create a timer in asp.net Server side


Why does Frisch-Waugh produce inconsistent estimates with Weighted Least Squares?

Question: Frisch-Waugh's theorem states that in the setup $Y = X^T \beta $, where $\beta = [\beta_1,\beta_2]^T$, $X = [X_1, X_2]$,
 $\hat{\beta}_2$ obtained from the multiple regression is the same as that obtained from  a two-stage specification, i.e.  $\hat{\beta}_2 = (X_2^T X_2)^{-1} X_2^T(Y-X_1\hat{\beta}_1)$
This procedure should also hold for WLS:
$\hat{\beta}_2 = (X_2^T \Omega^{-1}X_2)^{-1}X_2^T \Omega^{-1}(Y-X_1\hat{\beta}_1)$
However, I find different coefficient estimates for a single multiple regression than for two separate regression.
From the equation I derived, weights should be used in both parts of the two-part regressions, but just in case, I tried adding weights to only the first or second regression as well.
A simple reproducible example in R:
<code># load dataset from MASS package
data(cabbages)
# Here we see exactly what the coef on Cult should be:
target <- lm(VitC ~ Date + Cult, weight=HeadWt, data=cabbages)
# We see that the coef of Cultc52 is 12.69

# Weights on both equations:
one_f <- lm(VitC ~ Date,weight = HeadWt,data=cabbages)
(one_s <- lm(resid(one_f) ~ Cult,weight=HeadWt,data=cabbages))
# 12.42

# Weights on the first equation only
two_f <- lm(VitC ~ Date, weight=HeadWt,data=cabbages)
(two_s <- lm(resid(two_f) ~ Cult, data=cabbages))
# 12.90... hmmm...

# Weights on second equation only
three_f <- lm(VitC ~ Date,data=cabbages)
(three_s <- lm(resid(three_f) ~ Cult,weight=HeadWt,data=cabbages))
# 12.79
</code>
Answer: Your statement of Frisch-Waugh is actually incorrect; essentially you can partial $X_1$ out of $Y$, but you have to partial it out of $X_2$. you want the following:
$$
\hat{\beta}_2=(X_2M_{x1}X_2)^{-1}X_2M_{x1}Y
$$
Where
$$
M_{x2}=(I-X_2(X_2X_2)^{-1}X_2X_1)
$$
That does work with weights in the first and second stage.


How to unzip or uncompress a file .epub on Drupal?

Question: I've created a content type that upload files .epub on database. Now for some reason (to use epub on a mobile app) I need to get the file .epub uncompressed.
It's like in my content type I upload a .zip file but when drupal store it it's stored unzipped.
Did someone knows a Drupal API function or a method that uncompress or unzip a .epub files?
Note that when I upload an .epub file or .jpg image or any other type of extensions, in the table file_managed I always get filemime : "application/octet-stream"? is it normal ?
Comment: Is this functionality to be exposed exposed to a moderated and manged group of users, or to anonymous users as well?
Comment: Hi, the upload of an .epub is done by the admin
Answer: PHP already has a built in class to process zip files. You can combine that with a hook_node_presave invocation in a custom module to process the field containing your ePub file and extract it to a directory in your file system.
/**
 * Implements hook_node_presave().
 */
function MYMODULE_node_presave($node) {
  if(isset($node->field_MYFIELD[LANGUAGE_NONE][0]['fid'])) {
    $file = file_load($node->field_sss[LANGUAGE_NONE][0]['fid']);
    $file_path = drupal_realpath($file->uri);
    $file_name = pathinfo($file_path, PATHINFO_FILENAME);
    $zip = new ZipArchive;
    if ($zip->open($file_path)) {
      $zip->extractTo(drupal_realpath("public://MYMODULE_customdir/$file_name"));
      $zip->close();
    }
  }
}

Comment: Just tested it, it's all that that i wanted Shawn, thank you again !


Why are the cookies not setting when not on localhost?

Question: I am building an Angular application and I am using ngx-cookie-service to manipulate the cookies.
When I run on my local machine, the cookies are set just fine.
When I run on my test server and access it via localhost, it also works just fine.
eg: http://localhost:<port_number>
But if I try to access it on the test server from another machine using the ip address (http://<server_ip>:<port_number>), the application works but the cookie is not there and there is no message, error or warning, about what is happening.
I searched other answers but couldn't find a clue. I also fiddled with the setting for Same-Site = 'Lax' or 'None' and Domain but it didn't change things.
Here is a sample of what I am doing
  constructor(private cookieService: CookieService) { }

    this.cookieService.set("cookieName", "value", null, "/", null, true);

What am I doing wrong?
Edit:
I discovered that if I set the cookie with secure=false and sameSite="Lax", it does set:

If I set secure=true and SameSite="Lax", it does not set:

I need the secure to be true as a security requirement, so I cannot leave it like that.
This cookie is not being sent from the back-end, the front-end is creating it to store some info.
Does anyone know why it sets in without secure?
Comment: Browsers won't return cookies set by IP.. security risk.
Comment: @MikeOne, sorry I didn't understand. This cookie is being created on the front-end, it is not being set by the server that I am accessing. Is that what you meant?
I've added more information to the question
Comment: It doesn't really matter if you only set/get it front-end. A cookie is always set in the context of the domain name the code currently runs on. So for the browser to decide which cookies to 'expose' to your code, it checks if the domain name matches with the domain at the time it was set. Does that make sense?
Comment: @MikeOne, okay so if I got it right, the browser will always try to match the cookie domain with the domain the user curretly is, is that correct?
Comment: Basically yes..
Answer: I managed to find a way for the cookie to appear.
Installing a certificate on the server, when the website is called with the https protocol, the cookie appears.
I couldn't find anywhere were it said that cookies with Secure set were not created over plain http but it does make sense, when you think about it.


Compiling Visual Studio project as a pre-commit git hook

Question: Is there a way to create a git pre-commit hook that will try to compile the Visual Studio project I'm committing in several configurations and then allowing for the commit only if all compilations succeed?
I get the general idea of how to write a pre-commit hook, but that's all bash, so I'm not sure if I can make it to run what I'm guessing is a MSBuild.exe with the configuration of my project.
Answer: This ended being much simpler than I anticipated. I my case I wanted to run both debug and release configurations on x64 platform.
#!/bin/bash

MSBuild="path\to\MSBuild.exe"

if ! exec "$MSBuild" VulkanRT.sln -t:build -p:Configuration=Debug -p:Platform=x64 | grep -q "Build succeeded."
then
    echo "Debug build failed!"
    exit 1
elif ! exec "$MSBuild" VulkanRT.sln -t:build -p:Configuration=Debug -p:Platform=x64 | grep -q "Build succeeded."
then
    echo "Release build failed!"
    exit 1
fi

echo "Release and debug build succeeded!"
exit 0

Note that this is only viable for smaller projects where build times are low, unless you're fine waiting on the long build times.


Java Default NumberFormat Currency symbol

Question: I'm using NumberFormat's format() method to format currency in my application. When obtaining the currency instance, I'm not passing any locale to the method.
I've deployed this code to my app cluster which contains two nodes/servers. Interestingly, on one of the app server, the formattedAmmt is $xxxx.xx but on the other one it is ¤xxxx.xx. As far as I understand, this character is a universal currency symbol and JDK uses this when no particular locale is available. Is my understanding correct? If yes, how come it is working on one of the app server but not on the other? We are not seeing any default locale or such properties in app server/JVM properties.
double amount = xxxx.xx;
String formattedAmt = NumberFormat.getCurrencyInstance().format(amount);

PS: I'm deploying this app to WebSphere app server cluster which is using JDK 1.6.
Answer: Based on the java doc : https://docs.oracle.com/javase/6/docs/api/java/text/NumberFormat.html#getCurrencyInstance()
public static final NumberFormat getCurrencyInstance()
Returns a currency format for the current default locale.
It will base on the current locale of the server. That's why you may have two differents behavior.
If you want to specify the local, you have to use the following method:
public static NumberFormat getCurrencyInstance(Locale inLocale)
Returns a currency format for the specified locale


RSA - Under What Circumstances does Encryption Key Also Decrypt Cyphertext?

Question: I used primes $p = 7$, $q = 13$, to get $n = 91$ and $\phi(n) = 72$.
I chose $E=19<\phi(n)$, but found that $D=19$, which meant $x^E=x$ $(mod$ $n)$, i.e. the encryption is just the identity transformation!
I encountered the same issue with $E=17$.
My first question then is when you find $E$ and $D$ in practice, is it a case of trial and error until you find $E$ and $D$ that do encrypt the text?  Is there some better way than trial and error?
Then I tried $E=11$ and got $D=59$.  However, here I discovered that $x^{11}$ $(mod$ $91)$ and $x^{59}$ $(mod$ $91)$ are actually the same function, as well as being inverses of each other.  I don't recall reading anywhere that the encryption key can also sometimes be the decryption key.
Further investigation showed that $x^{59}$ $(mod$ $91)$ may be split into $(x^{7})^7x^{10}$ $(mod$ $7)=x^{11}$ $(mod$ $7)$ and $(x^{13})^4x^7$ $(mod$ $13)=x^{11}$ $(mod$ $13)$, by the CRT and FLT, which $x^{11}$ $(mod$ $91)$ can also be split up into.  Therefore they are the same function.
So my second question is under what conditions does the encryption key also act as the decryption key?  Again in practice, is it just trial and error until you find keys without this drawback?
A third question also could be, is there something about $n=91$ that makes it impossible to use for RSA?
Thank you for your time.  This is my first time using Stack Exchange so I hope to have posed an original and clear question.
Comment: In the first example, you do *not* get $x^E\equiv x\bmod n$.
Comment: You get $D=E$ when $D^2\equiv1\bmod{\phi(n)}$.
Comment: The original version of your question was better.
Comment: Thank you Randall for taking the time to explore this for me.  You have covered all the points I made.  I think the final result you state is quite useful.
Comment: In practice, people don't choose a random $e$, but $e=2^{16}+1$ (an industry standard), as this ensures fast exponentiation and as this $e$ is prime, it will almost surely be relatively prime with $\phi(n)$; $d$ is then computed and typically (we're talking 100's of digits numbers here, eg. around 616 for 2048 bit moduli) is a lot larger than $e$. $e=d$ never occurs in practical cases, just in small toy examples.
Answer: If you know some basic group/ring theory (or maybe just quadratic residues) this is all easily explainable.  Recall that once $E$ is selected, $D$ is dictated as $E^{-1} \bmod \varphi(n)$.  In other words, $E$ is selected from the group of units $\mathbb{Z}_{\varphi(n)}^*$ and $D$ is then its inverse in this group. (As pointed out, your edit with $E=D=19$ is wrong regarding $x \mapsto x^E$ being the identity map.)
Now, how large is the group of units $\mathbb{Z}_{\varphi(n)}^*$?  By some basic ring theory, this group has size $\varphi(\varphi(n))$.  [In general, the ring $\mathbb{Z}_k$ has $\varphi(k)$ units.]  For example, with $n=91$, $\varphi(n) = 72$ and sure enough, working mod $72$ there are $\varphi(\varphi(91)) = \varphi(72)=24$ units.  In short, you only have $24$ valid choices for $E$ when you work RSA mod $91$.
Your (original) first question was, paraphrased:  is $D=E$ always a possibility?  And why does this happen?  Here is the relevant fact for your question on why $D=E$ is possible.  (In fact, it is inescapable:  no RSA moduli avoid this phenomenon completely.)
Theorem: When $m \geq 3$, the value of $\varphi(m)$ is even.
The only RSA modulus for which this is false is $n=6$, which gives $\varphi(\varphi(6))=1$, odd.  For all other RSA moduli $n$, we have that $\varphi(\varphi(n))$ must always be even.
Hence the group of units $\mathbb{Z}_{\varphi(n)}^*$, from which you selected $E$, has even order.  Now any group of even order has at least one (probably more) element of order $2$ (meaning $x^2=1$), and such elements are there own inverses (meaning $x=x^{-1}$).  This is what happened in your example.  If you get out your modular calculator, set the modulus to $72$ and ask for the multiplicative inverse of $19$, you will see that the answer is itself.  This must always happen for at least one key-choice of $E$ because this group has even order.
If this bothers you, then don't use it.  Check that $D$ is not $E$, and if it was, then choose again.  By probability, it won't happen again.
In your second example, you chose $E=11$ and $D=E^{-1} \bmod 72$ is in fact $D=59$.  Nice observation that exponentiation by each results in the same function; this is insightful on your part.  I'm not sure of a completely general set of conditions that explain or predict this based on $n$, $p$, $q$, etc.  I will point out that, in your example, $n=91=7 \cdot 13$, and $p-1=6$ divides $q-1=12$.
Proposition:  Suppose we have an RSA setup $n=pq$ with $E$ and $D$ correctly chosen.  Then the encryption function $f: x \mapsto x^E \bmod n$ is the same as the decryption function $g: x \mapsto x^D \bmod n$ if $D$ is simultaneously congruent to $E$ modulo $p-1$ and $q-1$.
The proof of this is basically the same as the proof that RSA works.  You can write $D=E + k(p-1)$ for some $k$, and $D  = E + j(q-1)$ for some $j$.  Show that $x^D \equiv x^E \bmod n$ by arguing mod $p$ and mod $q$ in cases.  You'll need to consider when $x$ is divisible by $p$ and not $q$, the vice versa, then neither.  It will all work because of Euler's theorem.
It gets worse in some cases.  If we additionally knew that $p-1$ divides $q-1$, then we don't have to check both congruences above.  This is your "problem," since $91 = 7 \cdot 13$ and $7-1$ divides $13-1$.
Corollary:  Suppose we have an RSA setup $n=pq$ where $p < q$ and with $E$ and $D$ correctly chosen.  Suppose also that $p-1$ divides $q-1$.  Then the encryption function $f: x \mapsto x^E \bmod n$ is the same as the decryption function $g: x \mapsto x^D \bmod n$ if $D$ is congruent to $E$ modulo $q-1$.
Proof.  If $q-1$ divides $D-E$ then $p-1$ also divides $D-E$, so the previous result applies.  $\Box$
Note:  This is exactly your situation.  You have $E=11$ and $D=59$, and $D-E=48$ is divisible by $q-1=12$.
Finally, this business of $p-1$ dividing $q-1$ is not sufficient to create this behavior.  So, whatever is going on with $n=91$, this isn't the whole explanation.
Example: With $p=11$ and $q=71$ we have $n=781$, $\varphi(n)=700$, and $p-1$ dividing $q-1$.  However, plenty of key choices do NOT result in $x \mapsto x^E$ agreeing with $x \mapsto x^D \bmod n$.  One example is $(E,D) = (3, 467)$.
There is one general thing you can say about the encryption function agreeing with the decryption function.  Let $f : x \mapsto x^E$ be the encryption, and $g: x \mapsto x^D$ be the decryption, all mod $n$. We have $f \circ g =1=g \circ f$ by design.  Certainly if $D=E$ then we'll have $f=g$, but as you've pointed out this need not be necessary.  If $f=g$ this will say $f \circ f=1$.  The converse is also true by uniqueness of inverses for bijective functions:  $f \circ f =1$ implies that encryption is decryption.  However, $f \circ f =1$ means that $f(f(x))=(x^E)^E = x^{E^2} \equiv x \bmod n$.  However, we are now multiplying up in the exponent, so we should work mod $\varphi(\varphi(n))$, not just $\varphi(n)$.  Hence we would have $f=g$ if $E^2 \equiv 1 \bmod \varphi(\varphi(n))$.
Sure enough, this is your example!  With $n=91$, $\varphi(\varphi(n))=24$, and with $E=11$ we get $E^2 = 121 \equiv 1 \bmod 24$.


Survival analysis mostly censored data

Question: I have (another) question regarding survival analysis: If I had two groups of participants (rather small, less than 100, well-matched apart for one or two covariates) exposed to treatments A and B respectively (say, a cancer drug) in a time period of about 5 years, with similar distribution (i.e. similar number of participants recruited each month). A year or two later, in both groups some, but few, have died (say, 2 in group A, but 15 in group B), but most are still alive. In both groups, the majority of individuals have only been followed for 2-3 years.
Given the fact that most of the data is censored, is there a way to estimate the survival function and its CI, as well as compare survival in both groups? Essentially, how would I estimate how likely it is, given current, data that treatment A is or is not more effective than treatment B? Thank you!
Answer: Everything you want to do is theoretically possible, following the same procedures as usual for survival analysis. In practice, however, you have very little information, so the conclusion is likely to be that you can't tell which treatment is more effective (e.g. wide confidence intervals on (e.g.) the coefficient giving you the log-hazard difference between the groups).
On the other hand, this quick summary suggests that you might actually have enough information if your numbers of deaths are really approx 2 vs 10.
<code>dd <- data.frame(trt = rep(c("A", "B"), each=100))
set.seed(101)
dd$time <- rexp(200, rate = ifelse(dd$trt == "A", 0.02, 0.1))
dd$death <- dd$time < 1
dd$time[!dd$death] <- 1.0
library(survival)
cc <- coxph(Surv(time, event = death) ~ trt, dd)
> summary(cc)
Call:
coxph(formula = Surv(time, event = death) ~ trt, data = dd)

  n= 200, number of events= 13

       coef exp(coef) se(coef)    z Pr(>|z|)
trtB 1.7451    5.7267   0.7687 2.27   0.0232 *
</code>
Comment: i see, thank you so much! This really helps me!

Survival analysis mostly censored data


CSS - 100% width on hover, despite setting the element to a different width

Question: I have a problem with CSS.
I centered all and it works properly but there is a problem with the hover css.
When I set active class or hover li element the background color is set to 100%.
Also the parapraph starts from the left side and is not exacly under the element.
I try inspect code but I don't see anything there.
What's the reason and how to avoid somethig like that in the future??

I want to get something like that:

I tried to preview the code and change widths and other classes

function myFunction() {
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName("li");
  for (i = 0; i
 -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
}
:root {
  --main-color: #009add;
}

* {
  box-sizing: border-box;
  font-family: 'Century Gothic';
}

h2 {
  text-align: center;
  text-transform: uppercase;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}

#myInput {
  background-image: url('https://cdn.iconscout.com/icon/free/png-512/free-search-1779499-1513194.png');
  background-size: contain;
  background-position: 0;
  background-repeat: no-repeat;
  width: 50%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  outline: none;
  border-style: none;
  margin-bottom: 12px;
  border-radius: 20px;
  box-shadow: 0 0 5px var(--main-color);
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
  border-radius: 20px;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px;
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  border-radius: 20px;
  display: block;
  width: 90%;
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}

.accordion {
  /* background-color: #eee; */
  color: #444;
  cursor: pointer;
  padding: 5px;
  margin: 5px;
  /* width: 100%; */
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
  transition: 0.4s;
  border-radius: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.active,
.accordion:hover {
  background-color: var(--main-color);
}

.panel {
  padding: 0 18px;
  display: none;
  background-color: white;
  color: var(--main-color);
  overflow: hidden;
}
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">

Najczęściej zadawanie pytania:

    <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Wyszukaj.." title="Wyszukaj">

TYTUŁ

    </id>

Rozwiązanie

TYTUŁ2

Rozwiązanie

Comment: I think you mean to set the `` element to a width of 90%, but instead you've reduced the width of the `` element inside it to 90%.
Comment: I want there to be a slight border around that I can define myself, and a paragraph to be directly under the 'Title' and not starting from the beginning of the page.
Comment: If i remove width from  then element is shorter but the blue hover still exists.
Adding width into  element does nothing.
Answer: I managed to fix some of your code. The thing was that the active hue was from the background and not the border which is the common thing to do in CSS.
Not the cleanest code in the planet, there's a lot to simplify, but hey, I think you might like it!

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">

Najczęściej zadawanie pytania:

        <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Wyszukaj.." title="Wyszukaj">

TYTUŁ

        </id>

Rozwiązanie

TYTUŁ2

Rozwiązanie

Comment: Checkout the last edit. No need to add width to `#myUL li`
Comment: Looks great, The UI will be changed so don't worry how it looks right now
But now this is also one problem.
This elements are not centered and if I add Display Flex then again destroys everything.
Comment: This solved my problems. I modified a bit but now it's working properly.
Thank you!
Comment: Great to hear! Feel free to edit my answer.
Answer: you can change you .panel class like this
.panel {
   padding: 0 18px;
   margin: 0 auto;
   width: 90%;
   display: none;
   background-color: white;
   color: var(--main-color);
   overflow: hidden;
}

function myFunction() {
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName("li");
  for (i = 0; i
 -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
}
:root {
  --main-color: #009add;
}

* {
  box-sizing: border-box;
  font-family: 'Century Gothic';
}

h2 {
  text-align: center;
  text-transform: uppercase;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}

#myInput {
  background-image: url('https://cdn.iconscout.com/icon/free/png-512/free-search-1779499-1513194.png');
  background-size: contain;
  background-position: 0;
  background-repeat: no-repeat;
  width: 50%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  outline: none;
  border-style: none;
  margin-bottom: 12px;
  border-radius: 20px;
  box-shadow: 0 0 5px var(--main-color);
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
  border-radius: 20px;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px;
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  border-radius: 20px;
  display: block;
  width: 90%;
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}

.accordion {
  /* background-color: #eee; */
  color: #444;
  cursor: pointer;
  padding: 5px;
  margin: 5px;
  /* width: 100%; */
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
  transition: 0.4s;
  border-radius: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.active,
.accordion:hover {
  background-color: var(--main-color);
}

.panel {
  padding: 0 18px;
  margin: 0 auto;
  width: 90%;
  display: none;
  background-color: white;
  color: var(--main-color);
  overflow: hidden;
}

  <meta name="viewport" content="width=device-width, initial-scale=1">

Najczęściej zadawanie pytania:

    <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Wyszukaj.." title="Wyszukaj">

TYTUŁ

Rozwiązanie

TYTUŁ2

Rozwiązanie

Comment: This solved paragraph alignment but there is still problem with hover one.
I saw that if I uncomment background-color then this size is seen but I can't resize that.


C++ how to detect eof using getline()

Question: There are some variations of this question but none exactly matches what I'm looking for.
Giving the following code:
string command="";

while (command.compare("quit")!=0)
{
    os << prompt;
    getline(is,command);
}

How may I detect if getline reached eof (end of file)
Comment: You should avoid the attempt to use eof()  in the loop because of this: [https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons)
Comment: looking as *is* flags
Comment: better yet, just check if `is == false`
Comment: @drescherjm what do you mean? I want to exit the loop when I reach the end of file
Answer: getline returns a reference to the stream you pass to it, and that stream will evaluate to false if it hits a failure state.  Knowing that, you can leverage that to move getline into the condition for the while loop so that if it fails, then the condition will be false and the loop stops.  You can combine that will your check for quit as well like
while (getline(is,command) && command != "quit")
{
    // stuff
}

You can also add the prompt to the loop like
while (os << prompt && getline(is,command) && command != "quit")

Comment: to be compatible to the OP code : `while (os << prompt, getline(is,command) && command != "quit") {}` ;-)
Comment: @bruno Good idea.  I used `&&` instead of `,` just to keep it consistent.
Answer: while (command.compare("quit")!=0)
{
    os << prompt;
    getline(is,command);
    if (is.eof())
         do something at end of file
}

But note that is reaching end of file does not mean that there isn't something in command. You can read data and reach the end of file at the same time.
What you might be looking for instead is this
os << prompt;
while (getline(is,command) && command != "quit")
{
    do something with command
    os << prompt;
}

That code will quit the loop if you reach end of file and nothing has been input, or if 'quit' is input.
Comment: How may I save what getline returns in a variable so I can pass it to another function?
Comment: @daniel *getline* returns *is* so you already have it
Comment: @daniel getline always returns a reference to the stream that was passed to it (`is` in this case).
Comment: `os << prompt`must be made each turn, so `while (os << prompt, getline(is,command) && command != "quit") ...`
Comment: I mean what is the variable type int string etc?
Comment: The type is `std::istream&`.

C++ how to detect eof using getline()


Is Graeme Souness the one who played and managed in 5 countries, winning European Cup as a player and Scottish Premier DIvision as a manager?

Question: I ran into the following quiz question the other day, but I wasn't sure about the answer:

Name the footballer who has played in 5 countries, winning the European cup, and has also managed in 5 countries, only winning a league title in Scotland.

The name that came to mind was Graeme Souness, but I'm not sure if this is correct.  Does he fit this description?  Is there anyone else who would fit it better?
Comment: Well, if you look at Wikipedia article about [Graeme Souness](https://en.wikipedia.org/wiki/Graeme_Souness), you will find there: 1) teams where he played; 2) teams where he worked as a coach/manager; 3) [titles](https://en.wikipedia.org/wiki/Graeme_Souness#Honours) he won as a player/as a manager.
Answer: As you can see from Graeme Souness's Wikipedia profile, he:

Played in 5 countries:

England (Tottenham Hotspur, Middlesbrough, Liverpool)
Canada (Montreal Olympique)
Australia (West Adelaide)
Italy (Sampdoria)
Scotland (Rangers)

Won 3 European Cups with Liverpool (1977–78, 1980–81, 1983–84) as a player
Managed in 5 countries:

Scotland (Rangers)
England (Liverpool, Southampton, Blackburn Rovers, Newcastle United)
Turkey (Galatasaray)
Italy (Torino)
Portugal (Benfica)

As a manager, only won a league title in Scotland; 3 times (1986–87, 1988–89, 1989–90)

So Graeme Souness is indeed the answer to your quiz.


Logging out a user with Custom Authenticator using Ember Simple Auth

Question: I have a Custom Authenticator that I am using with the Ember Simple Auth (1.0.1) add-on.  To log a user out, I call invalidate() on the session object. As documented, I also resolve the promise in the custom authenticator's invalidate method like so:
invalidate() {
    return RSVP.resolve();
 }

Reading the documentation on the invalidate method for the Base Authenticator that my custom authenticator extends, I expect the session to remove any data that was in local storage (which is the default storage for the session data).  However, upon resolving the promise as told I still see the localstorage data persist after invalidating the session which causes the session to not be invalidated.
"This method returns a promise. A resolving promise will result in the session becoming unauthenticated." See http://ember-simple-auth.com/api/classes/BaseAuthenticator.html
Do I need to pragmatically clear the local storage, or do I need to import the localStorageStore and use its clear() method?
Thanks!
Answer: Ember Simple Auth will clear all data in the authenticated section of the session store. This is all data acquired by the authenticator when authenticating the session. All other session data will remain in the session and would have to be manually cleared.
Comment: I see. Thanks for the quick answer!
Comment: I'm having the same problem currently. Any chance you could include an example of how you would clear the session store?
Comment: You simply unset all the data that you previously set. You'll have to do that manually though. Ember Simple Auth doesn't provide any functionality to clear out the complete session.


Raspberry PI 3, SerialPort and strange response

Question: I'm trying to control my old Samsung DLP SP-A600B with the Serial Port (jack). To do so, I have resused my Raspberry Pi 3, and I have plugged a USB to Jack cable (UART) that I found on the net.
I made a small Python file but I don't understand the output I'm receiving. Here's my code:
import time
import serial

ser = serial.Serial(
    port='/dev/ttyUSB0',
    baudrate=9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.SEVENBITS
)

ON = b"\x08,\x22,\x00,\x00,\x00,\x00,\xD6"
# other hard-coded commands

ser.write(ON)
time.sleep(1)
out = ser.read(3)

# 0x03 0x0C 0x7F doesn't match the spec!

print out
ser.close()

According to the manual:

5-2 RS-232C Command Table
Communication Format (Complies with the RS232C Standard)

Baud rate : 9,600 bps
parity : None
Data bits : 8, stop bit : 1
Flow Control : None

Serial Communication Protocol

Command Packet Structure [7bytes]

A command packet consists of 7 bytes in total.
The two bytes 0x08 and 0x22 signify that the packet is for serial communication.
The following 4 bytes represent a pre-defined command that can be defined by the user.
The last byte is the checksum which checks the validity of the current packet.
Header [2 Byte]: Pre-defined values fixed to 0x08 and 0x22.
Cmd1 [1 Byte]: The first value of the code defined in the command list (Hexadecimal)
Cmd2 [1 Byte]: The second value of the code defined in the command list (Hexadecimal)
Cmd3 [1 Byte]: The third value of the code defined in the command list (Hexadecimal)
Value [1 Byte]: Input parameter for the command (Default: 0) (Hexadecimal)
CS [1 Byte]: Checksum (the 2's complement of the sum of all the values except for the CS value.)

Response Packet Structure [3 Bytes]

Success

0x03 0x0C 0xF1

Fail

0x03 0x0C 0xFF

I used this website to calculate the 2's complement (I'm more NodeJS / Android guy) for the 7th byte (D6). Unfortunately, I only receive
0x03 0x0C 0x7F

for this command. If I try to set strange values like serial.PARITY_ODD or serial.EIGHTBITS I receive the fail packet
0x03 0x0C 0xFF

And I did not succeed to receive one success packet. Any help would be greatly appreciated!
Comment: I think you are getting `0x7f` as your last byte because you have set `serial.SEVENBITS` and that is the 7-bit representation of `0xff`. I think you need to set `serial.EIGHTBITS`
Comment: You're right: `0xFF` is `11111111` and `0x7F` is `01111111`. So in the end, I just receive Fail Packets :(
Comment: Maybe it's the cable, I bought a "TipRX RingTX SlvGND" cable and I had another choice "TipTX RingRX SlvGND", I don't know how I can be sure...
Comment: I don't speak Python, but I wonder about the commas in your string. Can you try `ON = b"\x08\x22\x00\x00\x00\x00\xD6"` and EIGHTBIT.
Comment: Yes it's working! Perfect
Answer: As we eventually worked out in the comments, the problem is that there are superfluous commas in the command string and the data need to be 8-bit.
So, in concrete terms, use:
bytesize=serial.EIGHTBITS
...
...
ON = b"\x08\x22\x00\x00\x00\x00\xD6"


Simple REST request to create nodes

Question: I'm having the following issue trying to create nodes from Drupal 7 to a Drupal 6 install. The target Drupal site is running Services 3.x.
Here's my code:
$base_url = $params['path'];
$data = array(
  'username' => $params['username'],
  'password' => $params['password'],
);
$data = http_build_query($data, '', '&');
$headers = array();
$options = array(
  'headers' => array('Accept' => 'application/json'),
  'method' => 'POST',
  'data' => $data
);

$response = drupal_http_request($params['path'] . '/user/login', $options);
$data = json_decode($response->data);

// Check if login was successful
if ($response->code == 200) {
  // Now recycle the login cookie we recieved in the first request
  $options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;

  // Create a new node
  $data = array(
    'node' => array (
      'type' => 'cloudnode',
      'title' => 'node1',
      'field_ip_address' => array ('value' => '18.104.22.168'),
    )
  );
  $options['data'] = http_build_query( $data, '', '&');
  $options['method'] = 'POST';
  $response = drupal_http_request($base_url . '/node', $options);
}
else {
  die ('Failed to login');
}

I get a 200 response; the node is being created, but somehow it doesn't take care of my 'field_ip_address' CCK field at all.
I've tried any kind of variations but they don't work. There is not much documentation around as well.
If anyone has succeeded in creating nodes using REST, I would be very interested for any help.
Comment: Not sure if that is your problem, but cck fields are always stored as an array of values. So in your case, it would be something like `'field_ip_address' => array(array('value' => '18.104.22.168')),`. If that's I'll write up an answer, but I'm just guessing right now.
Comment: @kiamlaluno: I think the correct tag here is actually drupal-6 (or maybe both?), because he is creating nodes on the D6 site, so the API must match d6, even if the code runs on a d7 site.
Comment: Exactly !!! That was it ! Thank you very much, you saved my hairs :)
Comment: Would you mind posting your full method for creating a node with CCK fields to this page at drupal.org: http://drupal.org/node/1070066 Or make a new documentation page, but put it in the new Services 3.0 handbook, which is where that that other page is located.
Answer: CCK fields are always stored as an array of fields, even if the actual field is limited to only a single value.
So you it should be something like:
'field_ip_address' => array(array('value' => '22.214.171.124'))
Note that in Drupal 7, field values are additionally grouped by the language, which is 'und' (LANGUAGE_NONE) if the field is language-agnostic. So it would be something like this:
'field_ip_address' => array('und' => array(array('value' => '126.96.36.199')))
Copied from my comment, so that the question can be marked as fixed :)
Comment: Will keep that in mind; also do you have any example for rest file upload ?
Comment: No idea :) I suggest you create a new question, someone else might.

Simple REST request to create nodes


MD5 hash for zip files

Question: Is it possible to generate MD5 hash for .zip files in java? All the examples I found were for .txt files.
I want to know when we unzip the data, edit a file, again zip it and find the hash, will it be different from the original one?
Answer: You can create MD5 hashes for any arbitrary file, independently of the file type. The hash just takes any byte stream and doesn't interpret its meaning at all. So you can use the examples you have found for .txt files and apply them to .zip files.
And yes, editing a file inside the .zip will most likely change the MD5 of the .zip file - even though that's not guaranteed, due to hash collisions. But that's just a general property of hashes and has nothing to do with the zipping.
Note, however, that rezipping files may change the MD5 hash, even if the content has not changed. That's because even though the unzipped files are the same as before, the zipped file may vary depending on the used compression algorithm and its parameters.
EDIT (based on your comment):
If you want to avoid those changing MD5 hashes on rezipping, you have to run the MD5 on the unzipped files. You can do that on-the-fly without actually writing the files to disk, just by using streams. ZipInputStream helps you. A simple code example:
    InputStream theFile = new FileInputStream("example.zip");
    ZipInputStream stream = new ZipInputStream(theFile);
    try
    {
        ZipEntry entry;
        while((entry = stream.getNextEntry()) != null)
        {
            MessageDigest md = MessageDigest.getInstance("MD5");
            DigestInputStream dis = new DigestInputStream(stream, md);
            byte[] buffer = new byte[1024];
            int read = dis.read(buffer);
            while (read > -1) {
                read = dis.read(buffer);
            }
            System.out.println(entry.getName() + ": "
                    + Arrays.toString(dis.getMessageDigest().digest()));
        }
    } finally { stream.close(); }

Comment: @Priya: I see. Yes, that's unavoidable. Not only because of a time stamp, but only because of different compression algorithms, different options or a different file order.
Comment: Thanks for the reply. But do we have any other way to find the contents inside .zip files are changed?
Comment: @Priya: If you mind the false positive for changes that I mentioned (changed MD5 on rezipping), you have to extract the files and apply the MD5 to the extracted files. Then you will get the same hash for the same content, guaranteed. But you won't ever get rid of the (extremely unlikely) false negatives for changes (same hash code for different files). They are just a property of hashes you have to accept. If you cannot live with that, don't use hashes.
Comment: @Priya: Btw. by "extracting" I don't mean you have to write the files physically to disk. You can do that on-the-fly by using Java's zip streams. Here's an example on how to use them, just instead of writing them to disk you can pass them on directly to a MD5 algorithm: http://www.thecoderscorner.com/team-blog/java-and-jvm/12-reading-a-zip-file-from-java-using-zipinputstream
Comment: @Priya: I've just updated my answer to reflect what we've been discussing here in the comments.
Comment: Thanks for the input.. I'm trying your solution.
Comment: I was able to hash zip files with md5, but the hash differs when we zip it again because of the time stamp.
Comment: @Priya: Time stamp? The code in my answer hashes the *content* of the files within the .zip - no time stamp involved.
Comment: Its not about the code you shared. You initially gave me an explanation right, for the same zipped file, the hash may differ. It's because of the time it is zipped.
Comment: @mastov This does not give the md5 hash of the files inside the zip, instead it gives `[-105, 9, -28, -58, -32, 71, 119, -115, -91, -127, -105, 101, 91, 79, 5, 10]` what are those? and is there any way we can get the `md5hash` of files without extracting the zip. thanks

MD5 hash for zip files


Insert Block Inbetween Paragraphs of the Content Body Field

Question: I have a block I am trying to insert into the body field, catch is I want it to appear after the first two paragraphs. I tried using something similar to this in my node.tpl.php:
<?php
$array = explode ("
", $content['body']);
$array[2] = $myBlock . $array[2];
$content['body'] = implode("
", $array);
?>

//Important: This code snippet needs to be inserted before

<?php
print $content['body'];
?>

This code does insert my block in the body field, but also overwrites all the content in the field.
I'm using Drupal 7.10, any help is appreciated.
Answer: I think you want to be doing this on $body[0]['value']; And then in your output put echo render($content['body']); see the answer to this post on rendering fields.
Comment: Thank you! Your tip helped me figure it out. Here is how I got it working:

`$array = explode("", $body[0]['value']);
$array[2] = $myBlock . $array[2];
$content['body'] = implode("", $array);`


Getting value on XML string

Question: Hi I've been working on this asp.net webform written on c# and i'm currently
stock getting value on XML result encapsulated in a string.
I know little about XML and here is my attemps.
i have this XML string
0
<responseData>
    <LotDetails>
        <DEVICE>OH503/E-ICAM</DEVICE>
        <DEVICE12NC>340000064194</DEVICE12NC>
        <CONTAINERNAME>MBP001012700</CONTAINERNAME>
        <PACKAGE>SOT1207</PACKAGE>
    </LotDetails>
</responseData>

and i need to get the value of  <CONTAINERNAME>
in c# i have this code
string result = tmpVal.GetQueryResult(System.Configuration.ConfigurationManager.AppSettings["queryname_CMSS"].ToString(), System.Configuration.ConfigurationManager.AppSettings["paramnames_CMSS"].ToString(), LotID).InnerXml.ToString();
     XmlDocument doc = new XmlDocument();
            doc.LoadXml(result);
            XmlNode idNode = doc.SelectSingleNode("//responseData/LotDetails/CONTAINERNAME");

My code above returns me an error of dditional information: There are multiple root elements. Line 1, position 16.
It looks like i'm not getting the root element on my XML result.
Would someone help me out with this?
Thank you in advance.
Hope you understand what i mean.
Comment: I ran your code and it returns the idNode like how its supposed to. Are you sure this xml is what you are dealing with? idNode.InnerText gives you the value. [Tested here as well. dotnetfiddle](https://dotnetfiddle.net/b7dXMe)
Comment: on doc.LoadXml(result); the error pop
Comment: how are you getting result populated ? Can you share the code that sets up result with your xml data ?
Comment: ow your right this is not the xml im getting i updated my question
Comment: it still return's error There are multiple root elements. Line 1, position 16.  on loadXml part i'll update again my question
Comment: You can't have two root elements in your XML - and now you have  and .
Comment: what do you mean i did't get it
Comment: You do not have an XML string; [that's not XML](https://stackoverflow.com/questions/35310590/).
Answer: You can deserialize the xml that does not have a parent node like this,
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<parent>" + result + "</parent>");
    //doc.LoadXml($"<parent>{result}</parent>");

    XmlNode idNode = doc.SelectSingleNode("//responseData/LotDetails/CONTAINERNAME");

Or you can use a method to Parse XML without a parent node.
Comment: Use the + sign instead of $ sign to concatenate the string.
Comment: Be aware that this won't work if the supplied XML includes an XML declaration or DOCTYPE declaration.
Comment: Proper XML should have a parent node defined and in such case, this wouldnt be required. Since its a specific use-case, adding parent with two rootElements is being suggested. I totally agree with you @MichaelKay, If you are trying to work XML like this, you are most likely better off trying to get the source of XML corrected
Comment: why im not getting the parent it suppose to be like this
0

OH503/E-ICAM
340000064194
MBP001012700
SOT1207
Comment: The root cause problem is with the very first line: **string result = tmpVal.GetQueryResult(System.Configuration.ConfigurationManager.AppSettings["queryname_CMSS"].ToString(), System.Configuration.ConfigurationManager.AppSettings["paramnames_CMSS"].ToString(), LotID).InnerXml.ToString();** You need to get from the configuration file XML as XML data type, not the string.

Getting value on XML string