Endomorphisms and nilpotency

Question: I tried to proof something about nilpotent matrices but I'm not quite sure if my proof is correct, it is at least a bit handwavy so I'd love if someone would explain to me how I should make it more rigorous. The statement is as follows: Let $N$ be a $12 \times 12$ matrix so that $N^4 =0$, proof that $N$ has rank at most 9.
I tried to proof it by contradiction and my argument is as follows:
Consider the situation that $rk (N) >9$, considering $N$ is nillpotent, there exists a basis $B = \{b_{1}, b_{2},\dots,b_{12}\}$ such that for all $i \in \{1,2,\dots,12\}$ $N\cdot b_{i} = b_{i+1}$ or $N \cdot b_{i} = 0_{v}$. Consider this basis $B$ as a multiset, if $rk(N) >9$ then $rk(N)$ is atleast $10$, so for at most $2$ different $i \in \{1,2,\dots,12\}$ we have that $N\cdot b_{i} = b_{i+1}$ or $N \cdot b_{i} = 0_{v}$ Which means that after applying $N$ 4 times at $B$ we find that $B$ consist of at most $4$ distinct elements, hence we find that $rk(N^4) \geq 4$ but we are given that $N^4 = 0$, which lead us to a contradiction.
My biggest problem with this line of reasoning is the line where I state that for at most $2$ different $i \in \{1,2,\dots,12\}$ we have that $N\cdot b_{i} = b_{i+1}$ or $N \cdot b_{i} = 0_{v}$, I know this is true but the fact is that I don't really state anything about the other generators in $B$, this "proof" however is precisely how I tend to think about nillpotent endomorphisms, namely as linear transformations that "make your basis smaller after every application".
Any tips on how to make this argument work better would be greatly appreciated!
Comment: Do you know about Jordan canonical form?
Comment: @Omnomnomnom I'm aware of its "existence" but I haven't studied it yet hahahaha
Comment: If you rely on the proof of its existence, the. You can sidestep the mucking about with bases.
Answer: Consider the sequence of iterated kernels:
$$E_0=0\subset E_1=\ker N\subset E_2=\ker N^2\subset E_3=\ker N^3 \subset E_4=\ker N^4=K^{12}$$
and let $d_i=\dim E_i,\quad i=0,1,2,3,4$. We have
$$d_0=0\le d_1\le d_2\le d_3\le d_4=12.$$
Furthermore, for $1\le i\le 3$, we have an injective homomorphism
\begin{align*}
E_{i+1}/E_i&\longrightarrow E_i/E_{i-1}\\
v&\longmapsto N\cdot v
\end{align*}
which proves  $\;d_{i+1}-d_i\le d_i-d_{i-1}$.
Now suppose $\; \dim E_1\le 2$. Then by the previous observation,$\;\dim E_2\le 4,\enspace \dim E_3\le 6$  and $\;\dim E_4\le 8$, wheras we know it's $12$.
So $\;\dim \ker N\ge 3$ and, by the rank-nullity theorem, $\operatorname{rank}N\ge 12-3=9$.
Answer: The rank of $N$ is the dimension of the image of the endomorphism $f_N$ associated with $N$. The rank plus the dimension of $\ker f_N$ equals 12, so you must show that $\dim \ker f_N \ge 3$.
Take a non-zero vector $v_1$. Put $v_2 = f_N(v_1)$, $v_3 = f_N(v_2)$ and $v_4=f_N(v_3)$. By hypothesis $f_N(v_4)=0$. At some point in the sequence $v_1, ... , v_4$, $v_i \ne 0$ and $f_N(v_i) = 0$.
Then select $w_1$ not in the linear subspace spanned by $v_1, ... , v_4$ and repeat. And finally select $t_1$ not in the linear subspace spanned by the $v$ and the $w$.
You will find three linearly independent vectors in $\ker f_N$. $\square$

Endomorphisms and nilpotency


Deploying Application code in Persisted Volume in Kubernetes

Question: I am new to Kuberentes and am trying to deploying a simple webapp in it, currently I am building an image with all the dependencies and my application bundled in , uploading the image to repo and then deploying it in the pod, but the issue with this approach is that if I just want to edit my application code (let's say to add a print statement) I would need again build the image , upload it to repo and deploy it in K8.
Can I use the PVC to host my application code and refer it in my init container , is this a standard practice ?
Answer: Technically, you can. Practically, as far as I know, it is never a standard practice.

Majority of PVC solutions are ReadWriteOnce. So it would mean that you can't use scaling feature - replicas. You can't duplicate code easily across pods.

PVC is usually used for dynamic data: files or database - you separate code and configuration from data using PVC

Some images detect when there is nothing in PVC so app can be reinitialised from scratch, for example: prometheus, mysql and so on

PVC could be slower than data in Docker image (clustering mechanisms behind PVC)

If you have your code in PVC, you can't use anything app code related in Docker build phase (some testing, libraries resolution, etc.)

Pipeline may move away from standards (apps are usually built and deployed in a pipeline in Kubernetes)

and other consistency issues could occur

In case you need to edit code in development environment, other methods are used:

Locally, you can mount your local app folder to folder on Docker container, for instance it's volumes feature in Docker

Use minikube to recreate all containers locally for convenient development

Use tools to attach to containers such as https://code.visualstudio.com/docs/remote/attach-container

There should be a lot more methods, but you haven't mentioned the reason why building image with code is an issue.
Comment: HI @laimison, Thanks or illustrating why PVC is not a go to practice to have code, the reason I was looking towards PVC is because currently we dont have automated deployment pipeline set up , so after every code change we rebuild the image which can be fast or slow depending on what is cached , but the upload of image to repo is time consuming sometimes takes 3 to 4 hours for 4 GB.
Comment: For the quick win, you can use `ConfigMap` to place specific files on top of image. But it could be also not the best place for professional deployments, if files contain code, not configuration, certificates or similar stuff. An example to replace file `kubectl create configmap myapp --from-file myapp.py -o yaml --dry-run | kubectl replace -f -` it can be mounted with `configMap` in `volumes` and `volumeMounts` in `containers` https://kubernetes.io/docs/concepts/storage/volumes/#configmap . In my opinion solution needs good local and development environments where code is easily amended.


How to preprocess an image in Android (Kotlin)?

Question: I want to show a blurred preview in Android using Camera2 (in Jetpack Compose).
No matter what I try, I can't even pass the image from an ImageReader to a SurfaceView or TextureView. Here's the last thing I tried:
The preview itself is a SurfaceView:
    AndroidView(
        modifier = Modifier.fillMaxSize(),
        factory = {context ->
            SurfaceView(context).apply {
                layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT,
                )
            }.also {
                it.holder.addCallback(object : SurfaceHolder.Callback {
                    override fun surfaceCreated(holder: SurfaceHolder) {
                        scope.launch {
                            val camera = CameraHandler.openCamera(context);

                            camera.startBlurredPreview(
                                it.holder.surface,
                                context,
                                previewSize,
                            );
                        }
                    }

                    override fun surfaceChanged(
                        holder: SurfaceHolder,
                        format: Int,
                        width: Int,
                        height: Int
                    ) {
                    }

                    override fun surfaceDestroyed(holder: SurfaceHolder) {
                    }
                })
            }
        }
    )

while the logic for the camera is here:
class CameraHandler(
    private val manager: CameraManager,
    private val device: CameraDevice,
    private val handler: Handler,
    private val thread: HandlerThread,
    private val lens: Int = CameraCharacteristics.LENS_FACING_BACK,
) {
    private lateinit var imageReader: ImageReader

    val characteristics: CameraCharacteristics
        get() = manager.getCameraCharacteristics(lens.toString())

    @RequiresApi(Build.VERSION_CODES.P)
    private suspend fun createCaptureSession(
        outputs: List<Surface>,
    ): CameraCaptureSession = suspendCancellableCoroutine { cont ->
        // I really don't want to use a deprecated method, but there is
        // absolutely no documentation available for the new method.
        device.createCaptureSession(
            outputs,
            object : CameraCaptureSession.StateCallback() {
                override fun onConfigured(session: CameraCaptureSession) {
                    cont.resume(session)
                }

                override fun onConfigureFailed(session: CameraCaptureSession) {
                    cont.resumeWithException(RuntimeException("Failed to configure session"))
                }
            },
            handler,
        )
    }

    @RequiresApi(Build.VERSION_CODES.P)
    suspend fun startBlurredPreview(
        surface: Surface,
        context: Context,
        size: Size? = null,
    ) {
        val readerSize = size ?: getScreenSize(context).let {
            Size(
                it.width / 10,
                it.height / 10,
            )
        }

        println("Creating image reader with size $readerSize")

        val imageReader = ImageReader.newInstance(
            readerSize.width,
            readerSize.height,
            ImageFormat.YUV_420_888,
            IMAGE_BUFFER_SIZE,
        )

        val rs = RenderScript.create(context)
        val blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs))

        imageReader.setOnImageAvailableListener({ reader ->
            val image = reader.acquireLatestImage() ?: return@setOnImageAvailableListener

            // HERE'S where I struggle. How do I blur the image? How do I send it to the Surface? The code below is the last solution I've tried so far....

            // Show yuv image on screen
            val yBuffer = image.planes[0].buffer
            val uBuffer = image.planes[1].buffer
            val vBuffer = image.planes[2].buffer

            val ySize = yBuffer.remaining()
            val uSize = uBuffer.remaining()
            val vSize = vBuffer.remaining()

            val yData = ByteArray(ySize)
            val uData = ByteArray(uSize)
            val vData = ByteArray(vSize)

            yBuffer.get(yData)
            uBuffer.get(uData)
            vBuffer.get(vData)

            val yuvImage = YuvImage(yData, ImageFormat.YUY2, readerSize.width, readerSize.height, null,)
            val out = ByteArrayOutputStream()
            yuvImage.compressToJpeg(Rect(0, 0, readerSize.width, readerSize.height), 100, out)
            val imageBytes = out.toByteArray()
            val bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)

            if (bitmap == null) {
                return@setOnImageAvailableListener
            }

            println("Bitmap size: ${bitmap.width}x${bitmap.height}")

            val canvas = surface.lockCanvas(null)!!
            canvas.drawBitmap(bitmap, 0f, 0f, null)
            surface.unlockCanvasAndPost(canvas)

            // Release
            image.close()
        }, handler)

        println("Creating capture session")

        val outputs = listOf(imageReader.surface)
        val session = createCaptureSession(outputs)

        println("Creating capture request")

        val captureRequest = device.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
        captureRequest.addTarget(imageReader.surface)

        println("Setting repeating request")

        session.setRepeatingRequest(
            captureRequest.build(),
            null,
            handler,
        )
    }

    companion object {
        const val IMAGE_BUFFER_SIZE = 2

        fun getCameraManager(
            context: Context,
        ): CameraManager = getSystemService(context, CameraManager::class.java)!!

        fun createThread(): HandlerThread = HandlerThread("CameraHandler").apply { start() }
        fun createHandler(thread: HandlerThread): Handler = Handler(thread.looper)

        @SuppressLint("MissingPermission")
        suspend fun openCamera(
            manager: CameraManager,
            cameraId: String,
            thread: HandlerThread,
        ): CameraHandler = suspendCancellableCoroutine { cont ->
            val handler = createHandler(thread)
            manager.openCamera(cameraId, object : CameraDevice.StateCallback() {
                override fun onOpened(device: CameraDevice) {
                    cont.resume(
                        CameraHandler(
                            manager,
                            device,
                            handler,
                            thread,
                        )
                    )
                }

                override fun onDisconnected(device: CameraDevice) {
                }

                override fun onError(device: CameraDevice, error: Int) {
                }
            }, handler)
        }

        suspend fun openCamera(
            context: Context,
        ): CameraHandler {
            val manager = getCameraManager(context)
            val cameraId = manager.cameraIdList.first()
            val thread = createThread()
            return openCamera(manager, cameraId, thread)
        }
    }
}

Note:
Changing the format to ImageType.JPEG does work, but since I need a realtime preview, this isn't applicable unfortunately.
Sometimes the error Failed to create image decoder with message 'unimplemented' popped up when trying different solutions, but I couldn't fix it.
Here all the solutions I've tried:

How to convert android.media.Image to bitmap object?
How to convert YUV_420_888 image to bitmap
Displaying YUV Image in Android
https://blog.minhazav.dev/how-to-convert-yuv-420-sp-android.media.Image-to-Bitmap-or-jpeg/
https://blog.neteril.org/blog/2013/08/12/blurring-images-on-android/
D/skia: --- Failed to create image decoder with message 'unimplemented'
Answer: It seems you're trying to use Android's Camera2 API to capture a preview from the camera, then blur it using RenderScript, and finally show it on a SurfaceView. The core of your problem seems to be the transition between capturing the YUV image, converting it to a bitmap, blurring it, and drawing it on the Surface.
I'll provide a simplified solution for the image blurring process within your setOnImageAvailableListener:

You've already converted the YuvImage to a Bitmap. Instead of drawing this bitmap directly onto the canvas, you can first blur it using RenderScript.

Blur the Bitmap:

fun blurBitmap(context: Context, bitmap: Bitmap, blurRadius: Float = 10f): Bitmap {
    val rs = RenderScript.create(context)
    val input = Allocation.createFromBitmap(rs, bitmap)
    val output = Allocation.createTyped(rs, input.type)
    val script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)).apply {
        setRadius(blurRadius)
        setInput(input)
        forEach(output)
    }
    output.copyTo(bitmap)
    rs.destroy()
    return bitmap
}

Use the above function in your setOnImageAvailableListener:

val blurredBitmap = blurBitmap(context, bitmap)

Finally, draw the blurred bitmap onto the canvas:

val canvas = surface.lockCanvas(null)!!
canvas.drawBitmap(blurredBitmap, 0f, 0f, null)
surface.unlockCanvasAndPost(canvas)

Remember, the process might be computationally intensive. If the updates from the camera come in too quickly, the system might get bogged down blurring and rendering. Consider adding optimizations, such as:

Reducing the resolution of the preview stream.
Skipping some frames if the processing of a previous frame is not yet finished.
Running the blurring process in the background using Kotlin coroutines or another concurrency mechanism for smoother UI updates.
Comment: Thanks for the answer. Unfortunately, the current bitmap itself is the problem. I can't figure out how to properly convert the image to a bitmap. The current bitmap is just completely green. Another bitmaps were empty, completely black or just like random noise :/


Use Attributes To Check Whether to Access a Method

Question: I have a method that is only accessible if a certain criteria is fulfilled, if it's not, then the method won't be executed. Currently, this is how I code the thing:
public void CanAccessDatabase()
{
   if(StaticClass.IsEligible())
   {
      return;
   }
   // do the logic
}

Now, this code is ugly because out of no where there is this  if(StaticClass.IsEligible()) condition that is not relevant to the concern of the method.
So I am thinking about putting the IsEligible method in the attribute, so that my code will look like this. If the condition is not fulfilled, then this method will just return without executing the logic below.
[IsEligibleCheck]
public void CanAccessDatabase()
{
   // do the logic
}

Eligibility is a runtime decision, of course.
Any idea on how to code up the logic for IsEligibleCheck ? Thanks
Edit: I know PostSharp can do this, but I am looking at something that works out of box, not depending on any third party library.
Comment: Unrelated to your question, I consider having a method called `CanAccessDatabase` that doesn't return anything to be a huge failure of naming standards.
Comment: So the idea is that by adding an attribute to a method, you can get the compiler to automatically emit a bit of code either at the top of the function or whenever it's called?  I had no idea that this was even possible...
Comment: Is eligibility a compile time or runtime decision?
Comment: What should happen if something attempts to call the method when it's not accessible? Exception thrown? Silent failure? Garbage result?
Comment: If this is a compile time decision, then you can use the attribute '[Conditional("CONDITION1")]'
Comment: @PK: No, it's not a compile time decision.
Comment: @Anon: Well, that `CanAccessDatabase` was a name that I conjured up while I was typing the question. The name was not even remotely connected with my *real* application.
Answer:
Any idea on how to code up the logic for IsEligibleCheck?

This is a perfect spot for AOP.

Edit: I know PostSharp can do this, but I am looking at something that works out of box, not depending on any third-party library.

Is Microsoft considered third-party? If not, you could look at Unity from their Patterns & Practices team. Look at the Interceptor mechanism in Unity.
Otherwise, you effectively have to roll your own implementation using reflection. Effectively what you have to do is wrap your objects in a proxy wherein the proxy uses reflection to check the attributes and interpret them appropriately. If IsEligibleCheck succeeds then the proxy invokes the method on the wrapped object. Really, it's easier to just reuse an already existing implementation.
My advice is just use Unity (or another AOP solution).
Comment: I hate to break the news, but Patterns and Practices stuff is not considered MS products. They may be built on top of MS products, by MS people, but they are not officially supported. WCSF was also put out by the P&P guys, and it is pretty much an abandoned framework at this point. PostSharp and Castle may very well have more community support than anything from the Patterns and Practices guys.
Comment: ++ for suggesting unity. I suspect the OP doesn't want 3rd party stuff due to corporate requirements. The company may be more comfortable with using an MS product.
Answer: This looks like a perfect candidate for AOP. In a nutshell, this means that the CanAccessDatabase logic will live in an "aspect" or "interceptor", that is, separate from the business logic, thus achieving separation of concerns (the aspect is only responsible for security, business code is only responsible for business things).
In C#, two popular options for doing AOP are Castle.DynamicProxy and PostSharp. Each has its pros and cons. This question sums up their differences.
Here are other options for doing AOP in .Net, some of them can be done without 3rd-party libraries. I still recommend using either DynamicProxy, PostSharp, LinFu, Spring.AOP or Unity, other solutions are not nearly as flexible.
Comment: Thanks, as I can use PostSharp or Castle, I would prefer something .Net framework built-in, i.e., not depending on third party libraries.
Comment: @Ngu ALL of the Microsoft.Practices libraries are "third party" Just as previously stated in my other comment, they are not officially supported.
Answer: Custom attributes go hand in hand with Reflection.
You will need to create another class that is responsible for calling the methods in your CanAccessDatabase() class.
Using reflection, this new class will determine the attributes on each method.  If the IsEligibleCheck attribute is found, it will perform the StatiClass.IsEligible() check and only call CanAccessDatabase() if the check passes.
Heres an introduction to doing this at MSDN.  It revolves around using the MemberInfo.GetCustomAttributes() method.
Heres the pseudocode:
Get the Type of the CanAccessDatabase() class
Using this type, get all methods in this class (optionally filtering public, private etc).
Loop through the list of methods
    Call GetCustomAttributes() on the current method.
    Loop through the list of custom attributes
        If the IsEligibleCheck attribute is found
            If StaticClass.IsEligible is true
                Call the current method (using MethodInfo.Invoke())
            End If
        End If
    End Loop
End Loop

Comment: Thanks, you have any examples? so far all the examples I got,none of them deal with precondition check.
Comment: I read your example; all it says is how to check the existence of the attribute of any method at runtime and work upon it. But that means that I would have to specifically write the mechanism for to check for the attribute and call the `Eligible` class before any method is executed. And that's the piece of code I hope is written already by Microsoft. All I have to do ( and all I ask here) is to find it out.
Comment: @Ngu Soon Hui, yes, if you choose to do this yourself, you need to use reflection to first check for the attibute and then execute the method based on your custom logic.  If you don't want to do this you should use an AOP frmaework.  Microsoft don't currently provide AOP as part of the Framework C Library.
Answer: Unfortunately, attributes doesn't get executed at runtime. A handful of built-in attributes modify the code that gets compiled, like the MethodImpl attributes and similar, but all custom attributes are just metadata. If no code goes looking for the metadata, it will sit there and not impact the execution of your program at all.
In other words, you need that if-statement somewhere.
Unless you can use a tool like PostSharp, then you cannot get this done in out-of-the box .NET, without explicit checks for the attributes.
Answer: I know this is an old thread...
You can use the Conditional Attribute: http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx
"Indicates to compilers that a method call or attribute should be ignored unless a specified conditional compilation symbol is defined."
#define IsEligibleCheck // or define elsewhere

[Conditional("IsEligibleCheck")]
public void CanAccessDatabase()
{
   // do the logic
}

Answer: check AOP that will help you a lot in this, one of the powerful components in the market is PostSharp


How to minimise the upper boundary of this weird function?

Question:
Let $\{x\}$ denote the fractional part of $x$, which is $\{x\}=x-[x]$. Let $f_{a,b}(x)=\{x+a\}+2\{x+b\}$ and let its range be $\{m_{a,b},M_{a,b})$. Find the minimum value of $M_{a,b}$ as $a$ and $b$ range along all real numbers.

I tried two methods, one is to sketch a graph which proves to be useless because there is too many things to consider if $a,b$ could be changed.
I also tried by writing $\{x\}=x-[x]$, which also seems to me to be intractable.
How should questions of this type be solved and how shall I solve this problem?
Comment: Sketching a graph sounds like the way to go. From the definition, the function is clearly seen to be periodic with period $1$, and it is linear between $\{-a\}$ and $\{-b\}$, and again between $\{-b\}$ and $\{-a\}+1$. Figuring out its behavior at these two jump discontinuities should be enough to get a hold of the function. Also, it seems clear that the range of $f_{a,b}$ depends only on $\{b-a\}$, so there's only a small variation of representative $a,b$ choices you need to consider.
Comment: @HenningMakholm The problem is it is hard to determine the equation of the line. I also find it difficult to locate where the two graphs meet.
Answer: We can assume without loss of generality that $b=0$ -- adding the same constant to both $a$ and $b$ will just translate the function horizontally. Since only the fractional part of $a$ matters, we can also assume that $a\in[0,1)$.
Then we have
$$f(0)=a$$
from which point it grows with a slope of $+3$ until $x=1-a$. There we have
$$f(1-a-\varepsilon) = a+3(1-a-\varepsilon) = 3-2a-3\varepsilon \\
f(1-a) = 2(1-a) = 2-2a $$
and it then keeps growing with a slope of $+3$ until
$$f(1-\varepsilon) = a+2-3\varepsilon$$
The highest of these two peaks is our $M_{a,0}$:
$$ M_{a,0} = \max(3-2a,a+2) $$
and we can graph this as a function of $a$ to find that the minimal $M_{a,0}$ occurs when $3-2a=a+2$. This is easy to solve and gives $a=1/3$ and $M_{a,0}=2\frac13$.


Custom CSS for title fields of Articles specified in content creation

Question: Custom CSS for title fields of Articles specified in content creation
As an example, I have a view that displays my latest 10 articles but want the titles to be different colours. I want these colours to be determined based on what I input at the content creation form, whether it be in a separate field or by defining/attaching a specific class to each new Article.
Is there a way to do this or a better solution to my problem available? Thanks in advance :)
Answer: For the simplest and quickest implementation I'd suggest you create a array in your THEME_preprocess_node(&$vars) in  template.php:
<?php
$vars['color_cls'] = array(
    'red',
    'blue',
    'yellow'
);
?>

Then you could simply randomly address those in your node.tpl.php and print them as a class in your node, something like this:
<div class="node <?= $color_cls[array_rand($color_cls)]; ?>">

You could also make the color_cls array associative and give them, for example, priorities:
<?php
$vars['color_cls'] = array(
    'critical' => 'red',
    'important' => 'blue',
    'normal' => 'yellow'
);
?>

And ofcourse, then you just style them with your CSS. I'm assuming you do know how to style the classes, so I'll leave out the CSS  bit.
Comment: Well... The somewhat limited information you gave in the initial question, made it look like you are trying to randomly assign colors to your nodes. So this would make it a theme-level issue, so I would do this all at theme level. If you are actually trying to assign severities to nodes or something of that nature, I'd suggest you make a field with a Priority dropdown for that with a few options that you would select on creation/edit of the node. Then print the values of that field in the `class` attribute of the node's div.
Comment: Thanks mate, I'll give this a try. Is there no module that handles this sort of thing?
Comment: No, I have a view listing all articles in lots of 10, I want to change the colour of their title field at will. I was thinking if I could add a class to each particular article content then I could alter it like that.
Answer: I had to do this as a hack solution for the interim until I find a better solution to implement. The following will apply a blue background to all articles in the front page feed view that have the title 'First Article'.
HTML:

            First Article

jQuery:
function ($) {
    Drupal.behaviors.ApplySpecificTitle = {
        attach: function(context, settings) {
            $('span.views-field-title a:contains("First Article")').parent().addClass('article-title-first');
        }
    };
})(jQuery);

CSS:
.views-field-title {
    background: #CCC; /* Default background */
}
.article-title-first {
    background: blue;
}

Note: This is probably far from the most graceful solution but it works for my instance as I won't be adding new articles very often.


Pairs Trading: What statistics to use for analysis of Cointegration using ADF Test?

Question: I have just begun to study Pairs Trading strategy as a part of my assignment for an internship. My purpose is to analyse any two stocks/commodities for possible co-integration. I made a VBA code where I take the OLS of the data and test the residual of the data for stationarity using the ADF test but I am confused as to what statistics to use for testing the null hypothesis? Till now I am considering the distribution for no drift and no trend since the average of the residual should ideally be zero. The other two options are constant but no trend and constant  plus trend.
I am using the MacKinnon (1996) one-sided p-values.
Please guide me through.
Another thing that I would like to know is, how much better is GLS-ADF test against the ADF test, and where can I find the details about the former test, as I couldn't find any resource on this test.
Comment: I don't see what the argument of @user46740 is. I think cointegration is the way to go, and pairs trading is a textbook example (e.g. in Tsay ["Analysis of Financial Time Series"](http://www.amazon.com/Analysis-Financial-Time-Ruey-Tsay/dp/0470414359/ref=sr_1_1?s=books&ie=UTF8&qid=1422793261&sr=1-1&keywords=tsay+analysis+of+financial+time+series) section 8.8).
Comment: Are you planning on using cointegration for pairs trading? You don't need cointegration to test for pairs trading.
Comment: @user46740 if not co-integration then what do I need to identify pairs for this kind of trading? Anyways I would appreciate if you could still help me in figuring out this doubt specific to the ADF test.
Answer:
Choosing the ADF test specification

There are three ADF test specifications:
(1) {no constant, no trend};
(2) {constant, no trend};
(3) {constant, trend}
Which one to choose depends on what you believe the relationship between the two prices should be. For example, if you have the same stock traded on two exchanges using the same currency, you may expect that the two prices should be approximately equal at all times. You would not expect the prices to diverge linearly with time $\rightarrow$ no constant. You would not expect the prices to diverge at a quadratic rate of time $\rightarrow$ no trend. Thus you would choose (1) {no constant, no trend}. There may perhaps be other examples where (2) would be more appropriate, but I cannot think of one right now. I doubt (3) would ever be relevant for pairs trading.
If you do not want to believe in any specification in advance (although (3) really does not seem to fit the pairs trading picture), you could try (3) and see whether the trend component is statistically significant. If it is, stay with (3). If not, try (2). If in (2) the constant is significant, stay with (2). If not, try (1). This and this are related posts with more detailed explanations.

ADF versus GLS-ADF

GLS-ADF a.k.a. DF-GLS test is said to be more powerful than the ADF test. For a technical treatment, there is the original paper by Elliott, Rothenberg and Stock. For a relatively easy read, Eric Zivot has nice lecture notes (especially pages 132-138) where you can learn more about it (there used to be a couple of typos in the formulas but the explanation is great anyway). Given these sources, it should be easier to look for more material if you need.
Comment: @CagdasOzgenc, I don't know and I hesitate to guess. The estimators would have to be worked out and then checked whether they converge to the same quantities in the direct versus the double-step approach. You could try that out, the algebra part should not be too difficult; the convergence part could. Or you could post a new question with the algebraic results worked out and just focusing on what distributions the estimators will have.
Answer: I would start with throwing out VBA. You can't do a serious analysis of things like cointegration in VBA unless you want to spend all your time coding stuff that has already been coded and has very little to do with trading. Focus on the subject, i.e. trading, and let the appropriate tools do what they do best.
For instance, take a look at Johansen test. It's one of the popular cointegration tests. There are two variants of it. Get the returns of your stocks, and run the test on them. That would have been the first thing that I'd do. Obviously, I'm assuming you did the exploratory analysis already, i.e. scatter plots, histograms and such.


Proving exponentiation in $\mathbb{Z}^{*}_{pq}$ is one to one

Question: We saw in our crypto class that in the group $\mathbb{Z}^{*}_{pq}$ where $p$ and $q$ are primes, that if for some $a$, $gcd(a, \phi(pq) = (p-1)(q-1))$ = 1 (where $\phi$ is Euler's totient function) then the function $f(x) = x^a$ is one to one, and he lecturer proved this by calculating the inverse of $a$ (the RSA trapdoor). What I have trouble understanding is why this proves the function is one to one. We computed an inverse function, that is showed that there is an inverse, but how does this show that there is no other inverse for an element?
Comment: If you can compute an inverse function, then by definition your function is both one-to-one and onto.
Answer: If $f$ is an function and $g$ and $h$ are inverse functions for $f,$ then $g=h$ since $$g=g(fh)=(gf)h=h.$$
Answer: In general: if $G$ is a finite group and $k$ a positive integer. Then the map $f: G \rightarrow G$ defined by $f(g)=g^k$ is a bijection if and only if $gcd(k,|G|)=1$. (The proof of the "if" uses Bézout's Lemma, the "only if" leverages Cauchy's Theorem)


Author can't see drafts when "sent back" from publisher in workbench

Question: I have a problem after installing workbench access, workbench moderation.
When an author creates a blog entry and sets it to needs review, the publisher will receive it in his work bench.  When the publisher sets the blog entry back to draft, the author DOES NOT see it in his work bench.  If the author were given the link directly to the the blog entry, he can still end it.
How can the author access the draft content that's been sent back to him by using the workbench interface?
Comment: why the down vote?  I was also able to resolve the situation with a custom module as per answer below
Answer: The creators of workbench didn't accommodate the behaviour that I mentioned in my question.  Hence, we have to build a simple module to do this .  Here's the code I used from the
<code>/**
 * Implements hook_node_update().
 */
function mymodule_node_update($node) {
  db_update('node_revision')
    ->fields(array('uid' => $node->uid))
    ->condition('nid', $node->nid)
    ->condition('vid', $node->vid)
    ->execute();
}

/**
 * Implements hook_workbench_moderation_transition().
 */
function mymodule_workbench_moderation_transition($node, $previous_state, $new_state) {
  if (isset($node->nid) && isset($node->vid) && isset($node->uid)) {
    mymodule_node_update($node);
  }
}
</code>
I got the solution from an answer in this question here:
Assigning revision owner when moderating backwards with Workbench


How can I get data in ascending using DynamoDB

Question: I'm Using the DynamoDB Database has around 2,40,000 data how to get the latest added data first in scanCommand
Answer: That you cannot do. DynamoDB stores data in sorted order based on the sort key as it relates to the partition key, but there is no order for partition keys.
If you need a global sorted order, like it seems then you need to use an index. Have a read of this blog post that describes how:
Effective data sorting with Amazon DynamoDB | AWS Database Blog


A product of a $H^1_0(\Omega)$ function with a function defined on $S^{N-1}$ is also in $H^1_0(\Omega)$.

Question: Let $\Omega = B_1(0)$ the ball centered at $0$ with radius equal 1 and $u \in H^1_0(\Omega).$ Also consider $f \in C^\infty(S^{N-1})$. I'm trying to prove the function $g(x) := u(x) f(x/|x|)$ is in $H^1_0(\Omega)$. The difficulties for me are in the fact that $x/|x|$ has no weak derivative. I took a sequence $u_n \in C^1_0(\Omega)$ such that
$$||u_n - u||_{H^1(\Omega)} \rightarrow 0.$$
My first attempt was to prove that $g_n(x) := u_n(x) f(x/|x|)$ is in $C^1_0(\Omega)$. I don't think this is true.
Any help is welcome.
Comment: For $n\geq2$, you can use that $f\in L^\infty(\mathbb{R}^n)$ and $f'\in L_{loc}^{\frac{n}{2}-\varepsilon}(\mathbb{R}^n)$ for all $\varepsilon>0$ to get that the usual product rule applies.
Comment: Thank you Jose.
Comment: When $n=1$, it is false, just take $f(x) = x$ (that is $f(1) = 1$ and $f(-1) = -1$) and $u(0)\neq 0$. Then $u(x) \,f(x/|x|) = u(x) \,\mathrm{sgn}(x)$ is discontinuous and so not in $H^1_0$.
Answer: I don't think that this is true for $n = 2$. Let us identify $f$ with a function on $[0,2\pi]$. Suppose that $u \equiv 1$ on a small ball with radius $R$ around the origin. Then, we get
$$
|\nabla g(x)| = \frac1{r(x)} |f'(\theta(x))|
$$
for $0 < |x| < R$
with the usual polar coordinates $(r(x), \theta(x))$.
That is, $g$ is differentiable on $B_R \setminus \{0\}$. However,
$$
\int_{B_R} |\nabla g(x)|^2 \mathrm{d}x
=
\int_0^{2\pi}\int_0^R \frac1{r^2} |f'(\theta)|^2 r \mathrm{d}r \mathrm{d}\theta
=
\int_0^{2\pi}|f'(\theta)|^2 \mathrm{d}\theta
\int_0^R \frac1{r}\mathrm{d}r
$$
and this is $+\infty$ (unless $f$ is constant).
Comment: Thank you gerw for your reply. That makes sense.


In Banach space over $\mathbb{C}$ maximal chain in the collection of all-invariant-subspaces for-compact-operator

Question: I saw the page
Maximal chain in the collection of all invariant subspaces for compact operator $K$
And I cannot understand Ali's answer. I'm wondering that where the $X$ is Banach space over "$\mathbb{C}$".
I'm trying to make that if $\mathcal{L}$ is not maximal, then we can make $\mathcal{L} \subset \mathcal{L_2} $ that $\mathcal{L_2}$ is chain of $\mathtt{Lat}K$.
The problem is in below.

Let $X$ be a Banach space over ${\Bbb C}$, and $K\in K(X)$ ($K(X) = $ compact operators space). Show that if ${\cal L}$ is a maximal chain in the $Lat K$ ($Lat K = $ the collection of all invariant subspaces for $K$), then ${\cal L}$ is a maximal chain in the lattice of all subspaces of $X$.

Thank you.
Comment: Ali's proof is definitely not correct.
Answer: Lemma 1.  Every compact operator on a space of dimension 2 or more has a nontrivial invariant subspace.
Lemma 2.  If $M\subseteq L$ are closed invariant spaces for a compact operator, such that $\text{dim}(L/M)\geq 2$, then there exists a closed invariant space $N$ with $M\subsetneq N\subsetneq L$.
Proof. Apply Lemma (1) to the induced operator on $L/M$.  QED.
Now assume that $\mathcal L$ is a maximal chain in $\text{Lat}(K)$, which is not maximal in the lattice of all subspaces of $X$.
We may then assume that there exists a chain of the form  $\mathcal L\cup\{L\}$, such that $L$ is not invariant under $K$.  Setting
$$L'=[K;L]:= \overline{\text{span}}\{K^nx: n\geq0, x\in L\},$$
we have that $\mathcal L\cup\{L'\}$ is a chain in $\text{Lat}(K)$, so $L'$ must be in $\mathcal L$ by maximality.
Also let $L''$ denote the closed linear span of the union of the members of $\mathcal L$ which are contained in $L$.  It follows that
$$L''\subsetneq L\subsetneq L'.$$
Therefore the codimension of $L''$ in $L'$ is at least 2, and I claim that there can be  no member of $\mathcal L$ in
between $L''$ and $L'$.  This is because every $M$ in $\mathcal L$ obviouly belongs to $\mathcal L\cup\{L\}$, so either
$M\subseteq L$ or $L\subseteq M$.  In the first case $M⊆L''$, and in the second case
$$
  L'=[K;L]⊆[K;M]=M.
  $$
We then get a contradiction by Lemma (2).
Comment: thank you. Then it is not important that $X$ is banach space over $\mathbb{C}$.
Comment: True!  In fact there are only a few results for Banach spaces that rely on properties of the field of complex numbers, most of which are facts on spectra of operators.


Copying Avatars over to new JIRA instance

Question: I've created a new JIRA instance, copied over the avatars folder and re-indexed the instance several times. I have cleared my browser cache several times, restarted JIRA and also rebooted the server several times. I still don't see the avatars appear on the new instance. I've made sure all permissions are recursively the same as the original JIRA instance. No change.
I have asked this on Atlassian Answers as well, I thought I'd ask here to in case anyone happens to be able to help.
Answer: You can only copy over avatars if you are importing the old database, as the database contains data that links the avatars to the users. So if you are creating a fresh instance of JIRA for a separate purpose, the users will have to manually re-add their avatars.


Problem with topological proof about borel measures

Question: It is given a finite Borel measure $\mu$ on a polish space $E$. The claim is that $\mu$ is then a regular measure. In the proof, it is shown that for any closed set $A$  it holds$$(1) \quad \mu(A) = \sup \{ \mu(K):K\subseteq A,\, K \text{ compact}\}.$$
Then, it is shown that a set $B$ fulfills
$$ \mu(B) = \sup \{ \mu(C): C\subseteq B,\, C \text{ closed}\}.$$ The author claims that it is clear that then $C$ also fulfills $(1)$. Could someone explain to me why this is the case?
Answer: To show that for a set $B\subseteq E$ we have
$$\mu(B) = \sup \left\{ \mu(K) : K \subseteq B,\, K\text{ compact}\right\},\tag{$\ast$}$$
we need to find, for an arbitrary $c < \mu(B)$, a compact $K\subseteq B$ with $\mu(K) > c$.
We know that $(\ast)$ holds for all closed $B$, and it was shown that the analogue of $(\ast)$ with "compact" replaced by "closed" holds [for all Borel sets $B$, presumably, or at least for the class of Borel sets under consideration at that point in the proof].
So, we fix a $c < \mu(B)$. Then it is known that there is a closed $F\subseteq B$ with $\mu(F) > c$. But since $(\ast)$ holds for all closed sets, and $c < \mu(F)$, there is a compact $K\subseteq F$ with $\mu(K) > c$. But of course $K\subseteq B$ by transitivity.
So, for all $c < \mu(B)$ we have
$$c < \sup \left\{ \mu(K) : K \subseteq B,\, K\text{ compact}\right\} \leqslant \mu(B),$$
which yields $(\ast)$ by taking the supremum over all $c < \mu(B)$.


Webform Start Date and End Date

Question: I'm having a heck of a time setting the start date and end date for a Webform.
We've got a node with a webform entity reference field that generates a new Webform. On that node form, we want to give people the option to set the new form's status. Here's a trimmed-down look at our code (I've omitted most of the superfluous stuff)...
// Get the status from the node creation form
$reg_form_status = $form_state->getValue('field_registration_form')[0]['settings']['status'];
// Get the scheduled dates
$reg_form_scheduled_open = $form_state->getValue('field_registration_form')[0]['settings']['scheduled']['open'];
$reg_form_scheduled_close = $form_state->getValue('field_registration_form')[0]['settings']['scheduled']['close'];
// create a new instance of our pre-generated webform
$webform = \Drupal::entityTypeManager()->getStorage('webform')->load('student_registration');
if (!empty($webform)) {
  $duplicate = $webform->createDuplicate();
  $duplicate->set('status',$reg_form_status);
  $duplicate->set('open',$reg_form_scheduled_open);
  $duplicate->set('close',$reg_form_scheduled_close);
  $duplicate->save();
}

Without setting the open/close dates, the form is created just fine. If it's set as "Open", then it sets correctly as open. If it's set as "Closed", then it is created as closed. However, if I try to set it as Scheduled, it defaults to open. If I try to set it as scheduled with the dates, then it throws Invalid data type for config element when saving the node.
I tried re-casting as a date object, but that doesn't seem to be working either.
$event_date_start = new DrupalDateTime($reg_form_scheduled_open, 'EST');
$event_date_close = new DrupalDateTime($reg_form_scheduled_close, 'EST');

with
$duplicate->set('open',$event_date_start);
$duplicate->set('close',$event_date_close);

Which hasn't resolved this issue. Here's the full stack trace...
An error has occurred: Drupal\Core\Config\UnsupportedDataTypeConfigException: Invalid data type for config element webform.webform.student_registration2006:open in /var/www/docroot/core/lib/Drupal/Core/Config/StorableConfigBase.php:207 Stack trace: #0 /var/www/docroot/core/lib/Drupal/Core/Config/Config.php(212): Drupal\Core\Config\StorableConfigBase->castValue('open', Object(Drupal\Core\Datetime\DrupalDateTime)) #1 /var/www/docroot/core/lib/Drupal/Core/Config/Entity/ConfigEntityStorage.php(284): Drupal\Core\Config\Config->save(false) #2 /var/www/docroot/core/lib/Drupal/Core/Entity/EntityStorageBase.php(457): Drupal\Core\Config\Entity\ConfigEntityStorage->doSave('student_registr...', Object(Drupal\webform\Entity\Webform)) #3 /var/www/docroot/core/lib/Drupal/Core/Config/Entity/ConfigEntityStorage.php(263): Drupal\Core\Entity\EntityStorageBase->save(Object(Drupal\webform\Entity\Webform)) #4 /var/www/docroot/modules/contrib/webform/src/WebformEntityStorage.php(133): Drupal\Core\Config\Entity\ConfigEntityStorage->save(Object(Drupal\webform\Entity\Webform)) #5 /var/www/docroot/core/lib/Drupal/Core/Entity/EntityBase.php(395): Drupal\webform\WebformEntityStorage->save(Object(Drupal\webform\Entity\Webform)) #6 /var/www/docroot/core/lib/Drupal/Core/Config/Entity/ConfigEntityBase.php(616): Drupal\Core\Entity\EntityBase->save() #7 /var/www/docroot/modules/custom/shgt_theme_helper/shgt_theme_helper.module(288): Drupal\Core\Config\Entity\ConfigEntityBase->save() #8 [internal function]: shgt_theme_helper_event_by_county(Array, Object(Drupal\Core\Form\FormState)) #9 /var/www/docroot/core/lib/Drupal/Core/Form/FormSubmitter.php(114): call_user_func_array('shgt_theme_help...', Array) #10 /var/www/docroot/core/lib/Drupal/Core/Form/FormSubmitter.php(52): Drupal\Core\Form\FormSubmitter->executeSubmitHandlers(Array, Object(Drupal\Core\Form\FormState)) #11 /var/www/docroot/core/lib/Drupal/Core/Form/FormBuilder.php(593): Drupal\Core\Form\FormSubmitter->doSubmitForm(Array, Object(Drupal\Core\Form\FormState)) #12 /var/www/docroot/modules/contrib/autosave_form/src/Form/AutosaveFormBuilder.php(144): Drupal\Core\Form\FormBuilder->processForm('node_event_by_c...', Array, Object(Drupal\Core\Form\FormState)) #13 /var/www/docroot/core/lib/Drupal/Core/Form/FormBuilder.php(321): Drupal\autosave_form\Form\AutosaveFormBuilder->processForm('node_event_by_c...', Array, Object(Drupal\Core\Form\FormState)) #14 /var/www/docroot/modules/contrib/autosave_form/src/Form/AutosaveFormBuilder.php(97): Drupal\Core\Form\FormBuilder->buildForm(Object(Drupal\node\NodeForm), Object(Drupal\Core\Form\FormState)) #15 /var/www/docroot/core/lib/Drupal/Core/Controller/FormController.php(91): Drupal\autosave_form\Form\AutosaveFormBuilder->buildForm(Object(Drupal\node\NodeForm), Object(Drupal\Core\Form\FormState)) #16 /var/www/docroot/core/modules/layout_builder/src/Controller/LayoutBuilderHtmlEntityFormController.php(39): Drupal\Core\Controller\FormController->getContentResult(Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\RouteMatch)) #17 [internal function]: Drupal\layout_builder\Controller\LayoutBuilderHtmlEntityFormController->getContentResult(Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\RouteMatch)) #18 /var/www/docroot/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(123): call_user_func_array(Array, Array) #19 /var/www/docroot/core/lib/Drupal/Core/Render/Renderer.php(573): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() #20 /var/www/docroot/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(124): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure)) #21 /var/www/docroot/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(97): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) #22 /var/www/vendor/symfony/http-kernel/HttpKernel.php(151): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() #23 /var/www/vendor/symfony/http-kernel/HttpKernel.php(68): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1) #24 /var/www/docroot/modules/contrib/simple_oauth/src/HttpMiddleware/BasicAuthSwap.php(67): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #25 /var/www/docroot/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Drupal\simple_oauth\HttpMiddleware\BasicAuthSwap->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #26 /var/www/docroot/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #27 /var/www/docroot/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #28 /var/www/docroot/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(52): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #29 /var/www/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #30 /var/www/docroot/core/lib/Drupal/Core/DrupalKernel.php(708): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #31 /var/www/docroot/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request)) #32 {main}

Does anyone have a working example or link to documentation on setting the open/close date on a webform programmatically?
Answer: I believe I may have found the answer in WebformEntityTest.php in the Webform module. There, a test creates a webform with the following settings for the scheduled dates...
$webform->setStatus(WebformInterface::STATUS_SCHEDULED);
// Check set open date to yesterday.
$webform->set('open', date('Y-m-d\TH:i:s', strtotime('today -1 days')));
$webform->set('close', NULL);
$this->assertTrue($webform->isOpen());

So I've done some testing, and for my use case, the following seems to be working so far.
$duplicate->set('open',date('Y-m-d\TH:i:s', strtotime($reg_form_scheduled_open)));
$duplicate->set('close',date('Y-m-d\TH:i:s', strtotime($reg_form_scheduled_close)));

If anyone has any remaining input on this, I'd appreciate that. Thanks!

Webform Start Date and End Date


Question about Multivariate normal distribution

Question: If $X_1$, … , $X_n$ are iid standard normals, does it follow that $(Xbar, X_1 - Xbar, … , X_n - Xbar)$ are MVN, where Xbar is the mean of the $X_i$? I don't think so, since taking a linear combination of 0 times the first component and 1 times the other components gives 0. However, I read the following in Blitzstein and Hwang:
Comment: A constant can be seen as a degenerate normal with variance 0.
Answer: Write a vector $X=[X_1,...,X_n]'$ and a second vector $\bar{X}=[Xbar,X_1-Xbar,...,X_n-Xbar]'$
Then note that there is a matrix
$M=\begin{pmatrix}
1/n & 1/n & \cdots & 1/n \\
1-1/n & -1/n & \cdots & -1/n \\
-1/n & 1-1/n & \cdots & -1/n \\
\vdots  & \vdots  & \ddots & \vdots  \\
-1/n & -1/n & \cdots & 1-1/n
\end{pmatrix}$
such that $\bar{X}=MX$. Then if $X \sim N(\mu,\Sigma)$, $\bar{X} \sim N(M\mu,M'\Sigma M)$
This is a standard result that linear combinations of normals remain normal.
It is true that $M'\Sigma M$ is not of full rank -- that's because $\bar{X}$ has more elements than $X$. If you dropped the last element of $\bar{X}$, then it would be of full rank again. But none of this changes the multivariate normality.


Existe função strpos() do php equivalente em JavaScript?

Question: Gostaria de saber se existe função equilavante a strpos() do php em javascript na principalmente para o ambiente Node.js e gostaria de saber como usa-la.
Answer: Trelhac, a função mais próxima da strpos do PHP no javascript é a indexOf, sendo que ela retorna um inteiro em relação a posição da string pesquisada:

let valor = "Teste";

//Vai encontrar o valor
console.log(valor.indexOf("Tes"));

//Não vai encontrar o valor
console.log(valor.indexOf("tes"));

https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

Caso você queira verificar apenas o contido, vale a pena dar uma lida também sobre a includes:
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/includes
Comment: tem como eu usar isso no if?
Comment: Aqui um exemplo: https://repl.it/repls/ProudDescriptiveDiscussions


Express route not being recognized. Responds with 'Cannot GET'

Question: app.js
var express = require("express");
var app = express();
var path = require('path');
var db = require('./db');
var bodyParser = require('body-parser');

app.listen(80);

app.set('view engine', 'jade');
app.set('views', "./views");

// app.get('/', _GetMainPage);
// app.get('/sites', _GetSites);

app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true })); // Support encoded bodies
app.use(bodyParser.json()); // Support json encoded bodies
app.use(require('./controllers'));

./controllers/index.js
var express = require('express');
var router = express.Router();

router.use('/', require('./sites'));
router.use('/site', require('./site'));

module.exports = router;

./controllers/sites.js
var express = require('express');
var router = express.Router();
var site = require('../models/site');

router.get('/', function(req, res) {
    site.getAll(function(err, rows){
        if(err) {
           res.send(err);
           return;
        }

        res.render('sites', { sites : rows });
    });
});

./controllers/site.js
var express = require('express');
var router =  express.Router();
var site = require('../models/site');

router.get('/site', function(req, res) {
    // console.log("get /site received. req.body: " + req.body);
    res.render('site', {
            site: {
                name : req.params.name
            }
        });
});

module.exports = router;

When I request localhost/site I get a response saying:

Cannot GET /site

localhost/ works perfectly
I have been looking at this for a while and can't find the problem yet. If there is anything I can add, let me know. Thanks.
Comment: What happens if you navigate to /site/site? Your site.js route is relative to the route you provided in use. So it should be `router.get('/' ...` not `router.get('/site' ...`
Comment: That's exactly what the problem is, thanks!
Answer: Thank you to the person that  commented with the answer:

What happens if you navigate to /site/site? Your site.js route is relative to the route you provided in use. So it should be router.get('/' ... not router.get('/site' ...

The ./controllers/site route is already being routed to /site. On top of this I was calling router.get('/site', ...). This means it was actually routing to /site/site.
The solution is to just use router.get('/', ...) in the site.js file instead.
Answer: This really helped me, thank you.
Basically, the root path in the sub-app is defined in your core app where you mount it via the app.use() method.
the best example I can find from app.mountpath docs is here:
https://expressjs.com/en/4x/api.html#express.router

The app.mountpath property contains one or more path patterns on which a sub-app was mounted.

var express = require('express');

var app = express(); // the main app
var admin = express(); // the sub app

admin.get('/', function (req, res) {
  console.log(admin.mountpath); // /admin
  res.send('Admin Homepage');
});

app.use('/admin', admin); // mount the sub app

It is similar to the baseUrl property of the req object, except
  req.baseUrl returns the matched URL path, instead of the matched
  patterns.
If a sub-app is mounted on multiple path patterns, app.mountpath
  returns the list of patterns it is mounted on, as shown in the
  following example.

var admin = express();

admin.get('/', function (req, res) {
  console.log(admin.mountpath); // [ '/adm*n', '/manager' ]
  res.send('Admin Homepage');
});

var secret = express();
secret.get('/', function (req, res) {
  console.log(secret.mountpath); // /secr*t
  res.send('Admin Secret');
});

admin.use('/secr*t', secret); // load the 'secret' router on '/secr*t', on the 'admin' sub app
app.use(['/adm*n', '/manager'], admin); // load the 'admin' router on '/adm*n' and '/manager', on the parent app


Explain the SQL expression

Question: I'm going through the spring-security samples on GitHub and found a class, which is a repository itself, where we use a @Query annotation.
Database used: HSQL
I don't clearly understand the contents of the query, particularly what does m mean and this part m.to_id = ?#{principal?.id } as well. This symbol is being underlined with red line and the following message is shown: Cannot resolve symbol 'm'
Code:
/**
 * A repository that integrates with Spring Security for accessing {@link Message}s.
 */
@Repository
public interface SecurityMessageRepository extends MessageRepository {
    @Query("SELECT m FROM Message WHERE m.to_id = ?#{principal?.id }")
    List<Message> findAll();
}

Here's my data.sql file used to populate the initial data (taken from the example):
insert into user(id,email,password,firstName,lastName) values (0,'firstname.lastname@example.com','password','Rob','Winch');
insert into user(id,email,password,firstName,lastName) values (1,'firstname.lastname@example.com','password','Luke','Taylor');

insert into message(id,created,to_id,summary,text) values (100,'2023-01-05 10:00:00',0,'Hello Rob','This message is for Rob');
insert into message(id,created,to_id,summary,text) values (101,'2023-01-05 11:00:00',0,'How are you Rob?','This message is for Rob');
insert into message(id,created,to_id,summary,text) values (102,'2023-01-05 12:00:00',0,'Is this secure?','This message is for Rob');

insert into message(id,created,to_id,summary,text) values (110,'2023-01-05 10:00:00',1,'Hello Luke','This message is for Luke');
insert into message(id,created,to_id,summary,text) values (111,'2023-01-05 10:00:00',1,'Greetings Luke','This message is for Luke');
insert into message(id,created,to_id,summary,text) values (112,'2023-01-05 10:00:00',1,'Is this secure?','This message is for Luke');

Could you explain what does mean that SQL expression or provide a link to some article explaining this? (because I can't even figure out how to google it correctly to find the answer quickly).
Answer: this SQL will work, m is not a column in your table so you can't select it.
* will get all columns. And m is used as an alias for Message, so it will be resolved with the m.to_id column.

SELECT * FROM Message m WHERE m.to_id = ?#{principal?.id }
Comment: This SQL doesn't work. I wrote the query as you suggested, but the `*` is being underlined with the description " or DISTINCT expected, got '*'". If I replace the * symbol with `ALL` keyword, `Cannot resolve symbol 'ALL'` and `Cannot resolve symbol 'to_id' ` messages are shown.
Comment: Try this then,same result different syntax: SELECT m.id, m.created, m.to_id, m.summary, m.text FROM Message m WHERE m.to_id = ?#{principal?.id }
Comment: everything ok, except of `to_id` – `Cannot resolve symbol 'to_id' `
Comment: Can you run this test? SELECT m.id, m.created, m.to_id, m.summary, m.text FROM Message m WHERE m.to_id=0
Comment: there's another thread with more info on this: https://stackoverflow.com/questions/45704036/spring-4-rest-query-annotation-not-working-with-security-principal

Explain the SQL expression


como resolvo esse exercico em c/c++

Question: no final eu ainda preciso printar quais lojas estão apresentando um preço dentro da media, alguem me ajuda;
#include<bits/stdc++.h>
struct difsites{
    double preco;
    char loja[50];
    char site[50];
};
int main(){
    int i,j;
    double soma, media;
    struct difsites MP;
    for(i=0;i<6;i++){
        printf("Insira o nome da loja: ");
        scanf(" %50[^\n]s", &MP.loja);
        printf("Insira a URL: ");
        scanf(" %50[^\n]s", &MP.site);
        printf("Insira o valor do computador: ");
        scanf(" %lf", &MP.preco);
        soma+=MP.preco;
        media=soma/6.0;
    }
    printf("Preco medio: R$%.2lf\n",media);
}

Comment: Se você selecionar o código e apertar `ctrl+k`, ele ficará formatado bonitinho como está agora. Isso facilita a leitura
Comment: Para resolver esse problema, melhor começar armazenando diversas "`difsites`" para poder acessá-las depois. Você só vai ler elas uma vez, só pode tirar a média depois de ler todas elas e, no final, você precisa comparar cada "`difsites`" com a média. Isso é um bom indicativo de que necessita armazená-las para acessar posteriormente
Comment: Porquê a tag c++ ? Você não está a usar nada no programa que seja de c++.
Answer: Primeiro erro no seu código está na variavel "soma", devemos inicializar ela como 0 se vamos incrementar a partir dela, por causa do lixo de memoria.
double soma = 0, media;

Para você armazenar as lojas, recomendo criar um vetor de estruturas. Ficando assim
struct difsites MP[6];

O segundo erro está na hora de calcular a media, você só irá calcular a media quando o ciclo for estiver acabado.
 for(i=0;i<6;i++){  //Le cada loja do vetor, começando da posicao 0 até 5
        printf("Insira o nome da loja: ");
        scanf(" %50[^\n]s", &MP[i].loja);
        printf("Insira a URL: ");
        scanf(" %50[^\n]s", &MP[i].site);
        printf("Insira o valor do computador: ");
        scanf(" %lf", &MP[i].preco);

        soma = soma + MP[i].preco; //Soma todos os preços das lojas
    }

    media = soma/6.0;

Depois para verificar se a loja está dentro da média é só fazer um ciclo for novamente com uma condição se menor que media, exibir o preço.
printf("Media do preco = %lf\n",media);
    for(i=0; i <6; i++){
        if(MP[i].preco <= media){
            printf("Loja %s | Preco =  R$%.2lf\n",MP[i].loja,MP[i].preco);
        }
    }

Comment: Acho que de tudo que o código original me incomodava, você só não tirou o número mágico. Então parabéns, eu sou muito chato e você atendeu a todas as minhas chatices =D
Comment: Kkkkkkk valeu cara, acabei não tirando o número mágico para tentar deixar o código mais parecido com o original.

como resolvo esse exercico em c/c++


Seg Fault resulting from push_back call on vector (threads linux)

Question: So what I'm trying to do is write a program that creates a series of child threads that take the arguments using the pthread_create method and uses the parameter passed in to do more manipulation and so on. The parameter I'm trying to pass in is a vector argument called reduce_args_. this is the header information for the struct ReduceVector.
typedef vector<string> StringVector;

// a data structure to maintain info for the reduce task
struct ReduceArg
{
  ReduceArg (void);  // constructor
  ~ReduceArg (void); // destructor

  pthread_t tid;  // thread id of the reduce thread
  StringVector files_to_reduce; // set of files for reduce task
};

// more typedefs
typedef vector<ReduceArg *> ReduceVector;

now the issues comes when I call push_back here:
for(int i = 0; i < num_reduce_threads_ ; i++){
            reduce_args_.push_back(phold);
        int count = 0;
        for(ShuffleSet::iterator it = shuffle_set_.begin(); it!=shuffle_set_.end(); ++it){
            string line = *it;
            string space = " ";
            string file = line.substr(0, line.find(space)) + ".txt";

            if (count < num_reduce_threads_){
                cout << reduce_args_[i+1];
                (reduce_args_[i+1] -> files_to_reduce)[count] = file;
                            //(reduce_args_[i+1] -> files_to_reduce).push_back(file);
             }
             count++;
            //cout << ((reduce_args_.back())->files_to_reduce).back()<< endl;
    }
}

both of those push_back methods cause a seg fault. the shuffle set is just a set and is outputting strings. and as noted in the .h file, the files_to_reduce is a string vector. So what I'm trying to do is access the files_to_reduce and push_back a string onto it, but each time I get a seg fault. The reduce_args_ obj is declared as below:
ReduceArg* plhold;
    reduce_args_.push_back(plhold);
    ((reduce_args_.back()) -> files_to_reduce).push_back("hello");
    for (int i = 0; i < this->num_reduce_threads_; ++i) {
      // create a placeholder reduce argument and store it in our vector
      (reduce_args_.push_back(plhold));
    }

thanks for the help!!
Comment: Not a direct solution but could save you a lot of trouble: If you're using C++11, please prefer `std::thread`.
Comment: Looks like you're pushing an uninitialized pointer into the vector `reduce_args_` then trying to access it.
Comment: if the application crashes in push_back it means that the actual problem has nothing to do with the vector, but with a heap corruption that you cause earlier by writing over another arrays' bounds, in that case we'd need more code to be able to point you in the right direction. It might also be what Mgetz is saying
Comment: Lots of spurious parentheses by the way: Just write `reduce_args_.back()->files_to_reduce.push_back("hello");`
Comment: basically you guys were right, I forgot to initialize it and as a result was accessing undefined memory outside of the bounds. Then I needed to move that initializing statement inside the loop. Thanks!
Answer: This:
ReduceArg* plhold;
reduce_args_.push_back(plhold);

Unless you've hidden some important code, you're pushing an uninitialised pointer, so the next line will cause chaos.
Possibly you meant this?
ReduceArg* plhold(new ReduceArg);

..but I suspect you haven't properly thought about the object lifetimes and ownership of the object whose address you are storing in the vector.
In general, avoid pointers unless you know exactly what you're doing, and why. The code as posted doesn't need them, and I would recommend you just use something like this:
typedef vector<ReduceArg> ReduceVector;

....
reduce_args_.push_back(ReduceArg());
reduce_args_.back().files_to_reduce.push_back("hello");
for (int i = 0; i < num_reduce_threads_; ++i) {
  // create a placeholder reduce argument and store it in our vector
  (reduce_args_.push_back(ReduceArg());
}

Comment: @MGetz Yes, but: It's difficult to know where to start given the posted code. My guess is that he shouldn't be storing pointers in the first place.
Comment: I would suggest using [unique_ptr](http://en.cppreference.com/w/cpp/memory/unique_ptr), by declaring `typedef vector> ReduceVector;` if pointers are required.
Comment: That was it! I didn't realize I needed to initialize the plhold with new ReduceArg! Thank you so much!


React - Setting state inside use Effect problem

Question: i ve got simple problem, just solving for 2 hours and cannot find solution(i am new to React)
I want to set State to true when all conditions inside use Effect are true. Use effect runs every time i click on button
const [allBtnOff, setAllBtnOff] = React.useState(false)

React.useEffect(() => {

        if (btnOff.ER1 === true &&
            btnOff.ER2 === true &&
            btnOff.ER3 === true &&
            btnOff.ER4 === true &&
            btnOff.ER5 === true &&
            btnOff.ER6 === true &&
            btnOff.Dreier === true &&
            btnOff.Vierer === true &&
            btnOff.Full === true &&
            btnOff.Kleine === true &&
            btnOff.Grobe === true &&
            btnOff.Kniffel === true &&
            btnOff.Chance === true
            )
            {
                setAllBtnOff(prevState => !prevState)
                console.log(allBtnOff)

            }
    },[btnOff])

Problem is, that its always one step back so i have to click two times on button to set it true.
For more details:
I click a button and then it will set it true and will disable button. Same time use effect will run, so i need extra click button to check if conditions are true. Any solutions?
EDIT: (maybe understanding code more will help)
// BTN OFF/ON after passing score
    const [btnOff, setBtnOff] = React.useState({
        ER1: false,
        ER2: false,
        ER3: false,
        ER4: false,
        ER5: false,
        ER6: false,
        Dreier: false,
        Vierer: false,
        Full: false,
        Kleine: false,
        Grobe: false,
        Kniffel: false,
        Chance: false
      })

// Passing score and disabling button
      function handleClick(event) {

        setTotalValues(prevState => {
            return {
                ...prevState,
                [event.target.name]: Score
            }
        })

        setBtnOff(prevState => {
            return {
                ...prevState,
                [event.target.name]: true
            }
        })
}

return (

1ER:

{totalValues.ER1}

                <button disabled={btnOff.ER1 && true} name="ER1" onClick={handleClick}>Add score</button>

// ...MULTIPLE SCORE--INSIDE BOXES

)

Comment: Consider having a look at `useReducer`. Also have a look at `Object.values` and `Array.prototype.every`
Comment: Yea i will definitely make objects more efficient. Thanks for tip
Answer: Create another useEffect and follow this:

React.useEffect(() => {

        if (allBtnOff) console.log(allBtnOff)

    },[allBtnOff])
Comment: I dont understand, this doesnt solve the problem.


Compute the cumulative hazard of a time interval

Question: I'm a little confused in calculating the cumulative hazard within a time interval.
We know that $H(t)=\int^{t}_{0}h(u)du$, if I have $\Delta t=t_1-t_0$
(1) $H(\Delta t)=\int^{\Delta t}_{0}h(u)du$
(2) $H(\Delta t)=\int^{t_1}_{0}h(u)du-\int^{t_0}_{0}h(u)du$.
Which is the correct one? (1) or (2)?
I felt the (1) may be the correct.
Comment: In which time interval are you interested?  From $0$ to $\Delta t$ or from $t_1$ to $t_0$?
Comment: it is $0<t_0<t_1<T$ and $\Delta t=t_1-t_0$
Comment: You have just named *three* distinct intervals $(0, t_0)$, $(t_0,t_1)$, $(t_1,T)$, and one *duration* ($\Delta t$). Your question has an answer once you can decide which of those you want to accumulate the hazard within.
Comment: Which is the correct one for $H(\Delta t)$? This is my question.
Answer: If $h(u)$ doesn't depend on $u$ then (1) has the same value as (2). Otherwise, $H$ is a function of both time interval boundaries rather than just the difference between them.
Comment: Assuming that $h(u) = C$ take all integrals and see.
Comment: Thanks, James. I'm wondering why (1) has the same value as (2) if $h(u)$ doesn't depend on $u$.


Devo checar datas com DateTime ou regex?

Question: Tenho visto duas maneiras diferentes de verificar se uma data é válida.
De uma forma "moderna", com DateTime:
$date="2014-02-04";
$dt = DateTime::createFromFormat("Y-m-d", $date);

return $dt !== false && !array_sum($dt->getLastErrors());

E usando uma expressão regular:
$date="2014-02-04";

// regex bem simples, apenas para demonstrar a situação.
return (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date));

Não encontrei muito informação comparativa sobre esses métodos. Sei que o DateTime é mais moderno, mas isso basta para considerá-lo mais recomendável? Quais são as vantagens e desvantagens de cada método?
Comment: Eu recomendo a utilização da Classe http://www.php.net/manual/en/class.datetime.php, pois além de ser especializada em datas Expressões regulares devem ser utilizados em último caso, pois é bastante custoso tanto para trabalhar com as mesmas quanto para o servidor. Podendo em alguns casos causar lentidão.
Answer: Datas são no fundo números. Mesmo que você declare na forma de string, é mais eficiente representá-las como inteiros.
A classe DateTime é especializada, logo, possui todas as otimizações possíveis para se trabalhar com datas.
Expressões regulares são de uso geral e processam strings. Normalmente, têm um custo computacional elevado (normalmente são O(n²)).
Some-se isso ao fato de que é muito mais fácil para um computador interpretar inteiros que strings e você tem a sua resposta.
Via de regra: sempre que houver uma alternativa às expressões regulares, use-a. Expressões regulares são como um canivete suíço: sempre úteis, mas se você tiver um alicate de verdade, por que usar aquele alicate mais ou menos que vem no canivete?
Comment: +1 Excelente comparação com o canivete :)
Answer: Não precisa complicar. Use a função nativa checkdate do PHP:
https://www.php.net/manual/pt_BR/function.checkdate.php
bool checkdate ( int $month , int $day , int $year )
Exemplo:
if (checkdate(2, 29, 2014)) {
    echo 'Data válida';
}
else {
    echo 'Data inválida';
}

Isso vai imprimir na tela: Data inválida. Porque 2014 não é ano bissexto.
Answer: É melhor utilizar o DateTime::createFromFormat() mesmo. Foi feito para isso e trata condições que sua expressão regular não trata.
Não sei te dizer qual é a mais rápida (voto no DateTime) pois isso dependerá da implementação e da versão do PHP.

Para versões do PHP menores que 5.3 a documentação apresenta esse código alternativo para o DateTime::createFromFormat():
static function createFromFormat ($format, $time){
assert ($format!="");
if($time==""){
    return new DateClass();
}

    $regexpArray['Y'] = "(?P<Y>19|20\d\d)";
    $regexpArray['m'] = "(?P<m>0[1-9]|1[012])";
    $regexpArray['d'] = "(?P<d>0[1-9]|[12][0-9]|3[01])";
    $regexpArray['-'] = "[-]";
    $regexpArray['.'] = "[\. /.]";
    $regexpArray[':'] = "[:]";
    $regexpArray['space'] = "[\s]";
    $regexpArray['H'] = "(?P<H>0[0-9]|1[0-9]|2[0-3])";
    $regexpArray['i'] = "(?P[0-5][0-9])";
    $regexpArray['s'] = "(?P<s>[0-5][0-9])";

    $formatArray = str_split ($format);
    $regex = "";

    // create the regular expression
    foreach($formatArray as $character){
        if ($character==" ") $regex = $regex.$regexpArray['space'];
        elseif (array_key_exists($character, $regexpArray)) $regex = $regex.$regexpArray[$character];
    }
    $regex = "/".$regex."/";

    // get results for regualar expression
    preg_match ($regex, $time, $result);

    // create the init string for the new DateTime
    $initString = $result['Y']."-".$result['m']."-".$result['d'];

// if no value for hours, minutes and seconds was found add 00:00:00
    if (isset($result['H'])) $initString = $initString." ".$result['H'].":".$result['i'].":".$result['s'];
    else {$initString = $initString." 00:00:00";}

    $newDate = new DateClass ($initString);
    return $newDate;
    }
}

E como dá para ver eles também utilizam regex (não se nas versões 5.3+). Mas, regex por regex, use o DateTime::createFromFormat() mesmo.
Answer: A expressão regular não é muito boa para fazer validação de datas, visto que você não quer somente validar se existe números ou traços você também quer validar a data.
A expressão que você colocou
^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$

Seria responsável por validar a data "2014-02-31", e essa data não existe.
Uma opção seria usar uma expressão regular mais complexa (valida entre 1800-2099 com anos bissextos)
^((?:18|19|20)[0-9]{2})-(?:0[13578]|1[02])-31|(?:18|19|20)[0-9]{2}-(?:01|0[3-9]|1[1-2])-(?:29|30)|(?:18|19|20)[0-9]{2}-(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:(?:(?:(?:18|19|20)(?:04|08|[2468][048]|[13579][26]))|2000)-02-29)$

Mas quanto maior a expressão regular maior o processamento, por isso, recomenda-se  transformar texto no tipo Data como melhor opção, dessa maneira a conversão impede que seja feita com datas inválidas.
Comment: Está explicado na minha resposta logo acima.
Comment: Não... Tipo, nãaaaaaaaaooooo faça dessa forma.
Comment: @HenriqueBarcelos Que tal expandir seu comentário pra explicar melhor o que tem de errado com essa forma? É melhor pra todo mundo
Comment: A resposta esclarece bem que a melhor opção é a outra e não esta. Acho bem valida esta resposta por mostrar a outra forma de o fazer e o porque de não usar essa forma @HenriqueBarcelos.


Turn off Drupal caching without Access to admin panel

Question: I'm using Drupal 7 on WAMPP , Windows 7
Background: Drupal on my local box is copy of working project, but this local version I can not login like admin , because it doesn't store session. It doesn't give out any PHP Error.
So I guess I have to turn off cache to find out , is there any PHP Error appearing.
Read that there is such thing as drush , but is it possible to use from Windows ?
But the main question , is how to stop caching on Windows 7 without Admin access !?
Answer: Yes, you can run Drush under Microsoft Windows if you use the Drush Windows Installer. Drush will allow you to turn of caching with the command:
drush en cache_disable --yes

It is not easy to set up the Drush Windows Installer.  As an alternative, you may consider explicitly set variables in your settings.php to turn of various caches.  Note that when set, these values will be locked to whatever is set in the file, and cannot be changed through the admin interface (so remove them when you're done debugging).
To disable page, JS, and CSS caching, set cache, preprocess_js, and preprocess_css all to '0' in the $conf array:
$conf = array(
  'cache' => '0',
  'preprocess_css' => '0',
  'preprocess_js' => '0',
);

If you set other values by means of the $conf array, add these fields, do that, rather than replacing the entire array.
Answer: If you look at this link you can see disable cache by puting below line in settings.php files
  $conf['display_cache_disable'] = TRUE;

Comment: "Also" to what, exactly? Is this a full answer? If so, please make that clear. If not, add an excerpt and link to part you are referring, so your answer would continue to be an answer even if the other one gets deleted.


Deconvolution of the sum of three gaussian distributions

Question: Consider the sum of three normal random variables:
$
R_{i,j}=A_{i}+B_{j}+C_{i,j}\,
$
where
$
A_{i}∼N(μ_{A},σ_{A})
$
,
$
B_{j}∼N(μ_{B},σ_{B})
$
and
$
C_{i,j}∼N(μ_{C},σ_{C})
$
. Assuming $A$, $B$ and $C$ are iid (independent), the density of $R$ is still normal, with mean $μ_{A}+μ_{B}+μ_{C}$ and variance $σ_{A}+σ_{B}+σ_{C}$.
Suppose I observe a list of realizations of $R$ (about 500 observations) as well as the $i$ and $j$ of each realization (so I know if two realizations of $R$ share the same $j$ for example).
How can I recover the distribution (mean and variance) of $A$, $B$ and $C$?
Comment: Could you explain the subscripting?  The double subscripting of $C$ is especially mysterious.  It looks like you are able to observe various sums $A+C$ and $B+C$ as well as an indicator of whether $A$ or $B$ is the first component, but that's only a guess.
Comment: Your title says you're summing *distriutions* while your body text says you're summing *random variables*. $X+Y$ is an *entirely* different kind of thing to $t(z) = F_X(z)+G_Y(z)$ (i.e. the 'distribution of sum' is not the same as 'sum of distributions'). Please make your title and question-body consistent. (Note also that you're using the symbol $\sigma$ in a non-conventional fashion, one likely to lead people into confusion or errors)
Comment: Whuber, say R is the outcome, i a given person and j a given place.
Answer: You can estimate the three variances by fitting a mixed model with $R_{i,j}$ as the response and the factors $i$ and $j$ included as random effects.  All three variances would be identifiable but not only the sum of the $\mu$'s.
The following R code simulating data and fitting the mixed model
i <- factor(rep(1:20,each=25))
j <- factor(rep(1:20,25))
set.seed(1)
A <- rnorm(nlevels(i), mean=1, sd=1)
B <- rnorm(nlevels(j), mean=2, sd=2)
C <- rnorm(length(i), mean=3, sd=.5)
R <- A[i] + B[j] + C
library(lme4)
summary(lmer(R ~ (1|i) + (1|j)))

gives the estimates
Linear mixed model fit by REML ['lmerMod']
Formula: R ~ (1 | i) + (1 | j)

REML criterion at convergence: 944

Scaled residuals:
    Min      1Q  Median      3Q     Max
-2.9493 -0.6611 -0.0223  0.6345  3.5898

Random effects:
 Groups   Name        Variance Std.Dev.
 i        (Intercept) 0.8373   0.9150
 j        (Intercept) 3.0804   1.7551
 Residual             0.2612   0.5111
Number of obs: 500, groups:  i, 20; j, 20

Fixed effects:
            Estimate Std. Error t value
(Intercept)   6.1824     0.4432   13.95

that are pretty close to the true values.
Comment: Thanks Jarle. I guess in Stata this would be a standard linear regression with random effects. There is no way to obtain the means? The mean of C is what I'm interested in...
Comment: I don't know Stata but I guess it can do this too.  Yes, there is no way of getting the separate means because the multivariate normal distribution of $\mathbf{R}$ depends on the $\mu$'s only through $\mu_A + \mu_B + \mu_C$.
Answer: Since $$\overbrace{\mathbf R}^{\text{vector of}\atop\text{$R_{ij}$'s}}=\overbrace{\mathbf X}^{\text{matrix of}\atop\text{$1$'s and $0$'s}}\underbrace{(\mathbf A^\top \mathbf B^\top)^\top}_{\text{vector of}\atop\text{$A_i$'s and $B_j$'s}} + \overbrace{\mathbf C}^{\text{vector of}\atop\text{$C_{ij}$'s}}$$the problem can be rewritten as a standard Normal regression problem with Normal priors on $\mathbf A$ and $\mathbf B$
Comment: Can you elaborate a bit more? Thanks


How to print out two columns per line, formatted

Question: I have two files with 2 columns each, I need to use 1 column from one and one from another and create a new file with 2 columns.
while i<500020:
    columns=datas.readline()
    columns2 = datas2.readline()
    columns = columns.split("  ")
    columns2 = columns2.split("    ")
    colum.write(" {1}   {0}".format((columns2[1]), (columns[1]) ))
    i=i+1

My output is like this:
 181.053131
  0.0005301
 168.785828
  0.3596852

I want to show them on same line, EX:
 181.053131     0.0005301
 168.785828     0.3596852

Answer: You need to remove the newline from columns2[1]:
columns2 = datas.readline().rstrip('\n')

otherwise you'll always insert those newlines into your output.
I'd also remove the newline from columns and use an explicit newline when writing:
columns = datas.readline().rstrip('\n')

and
colum.write(" {1}   {0}\n".format(columns2[1], columns[1]))

Comment: Thanks! Worked perfectly


A quotient module of a Lie algebra

Question: Let $L$ be a Lie algebra. If $A$ and $B$ are $L$-submodules of an $L$-module $V$, such that $A\subset B$ and $I\cdot B\subset A$ for some ideal $A$ in $L$.
I want to understand why this implies that  $B/A$ is an $L/I$-module?
Comment: Do you understand why it is an L-module?
Comment: Then you should start with that...
Comment: Sorry, maybe I didn't understand your question, do you mean that $B/A$ is an $L$-module?
Comment: Indeed. ${}{}{}$
Comment: Yes it is by setting $x + \overline v=\overline{ x + v}$, where $\overline v $ denotes the coset v + W. and the space $V/W$ is called the quotient module of $ V$ and $W$.
Comment: I think you mixed up the sum with the action, but ok. Now: under that action, in the situation of your question, how do elements of the ideal I act on that quotient?
Comment: well, since $x\cdot B\subset A$ then $x\cdot (b+A)=(x\cdot b)+A=A$
Comment: Sorry, but I still don't understand why $I\cdot B/A=A$ implies B/A is an  L/I - module.. Any hints ? Thanks
Answer: There are two things going on here:

If $A$ and $B$ are $L$-modules then so is $B/A$. Do you know how $L$ acts on $B/A$?
If $Q$ is an $L$-module, $I\trianglelefteq L$ an ideal and every element of $I$ acts as the zero map on $Q$, then $Q$ naturally becomes an $L/I$-module. Do you know how $L/I$ acts on $Q$?

After understanding both of these things, apply with $Q=B/A$.
Comment: The first action is $x.(b+A):=(x.b)+A$ ,, but the second action can we set it like $(x+I).q:=x.q$ which is well-defined since $(i+I).q=i.q=0$ for $i\in I$?
Comment: @Ronald Yes. ${}$

A quotient module of a Lie algebra


Custom plugin method won't be triggered when submitting ajax request

Question: I have created a custom plugin in Craft CMS 4 that has to decode data and store it in it's corresponding entries. However, while developing I fired the method in my init function so on every pageload, it would be triggered which is not necessary. So I want to fire the method when a button in my twig template is clicked. I managed to puzzle my way through the fundamentals but for some reason won't it fire the actual function. Does anybody knows what I'doing wrong..?
My code:
Edited Plugin.php
public function init(): void
{
    parent::init();

    // Render the template for my plugin.
    Event::on(
        View::class,
        View::EVENT_REGISTER_SITE_TEMPLATE_ROOTS,
        function(RegisterTemplateRootsEvent $event) {
            $event->roots['_jsonify'] = __DIR__ . '/src/templates';
        }
    );

    // Register the event that should be triggered on this url.
    Event::on(
        UrlManager::class,
        UrlManager::EVENT_REGISTER_CP_URL_RULES,
        function(RegisterUrlRulesEvent $event) {
            $event->rules['_jsonify/import/test'] = '_jsonify/import/test';
        }
    );

    Craft::$app->onInit(function() {
        $this->getJsonFile();
        $this->decodeJsonFile();
    });
}

PluginController.php
<?php
namespace plugins\jsonify\controllers;

use Craft;
use craft\web\Controller;
use craft\elements\Entry;
use yii\web\Response;

class JsonifySettingsController extends Controller
{

// Test function for test purposes
public function test(): Response
{
    dd('test');
    return $this->asJson(['message' => true]);
}

private function actionHandleJsonRead(): Response
{

    $jsonFile = $this->decodeJsonFile();

    $section = Craft::$app->sections->getSectionByHandle('test');

        foreach ($jsonFile as $key => $data) {
            $existingEntry = Entry::find()
            ->sectionId($section->id)
            ->andWhere(['title' => $data['Trial_name']])
            ->one();

            if ($existingEntry) {
                Craft::$app->getSession()->setNotice('Entry already exists with the same unique identifier. Skipping.');
                continue;
            }

            $entry = new Entry();
            $entry->sectionId = $section->id;
            $entry->title = $data['Trial_name'];
            $entry->testId = $data['testID'];
            $entry->entryName = $data['Name'];
            $entry->contractorSampleAnalysis = $data['Contractor_sample_analysis'];
            $entry->country = $data['Country'];
            $entry->crops = $data['Crops'];
            $entry->deltaYield = $data['Delta_yield'];
            $entry->lat = $data['lat'];
            $entry->location = $data['Location'];
            $entry->locationXy = $data['location_XY'];
            $entry->lon = $data['lon'];
            $entry->mapExport = $data['Map_export'];
            $entry->primaryCompany = $data['Primary_company'];
            $entry->primaryContact = $data['Primary_contact'];
            $entry->sizeHa = $data['Size_ha'];
            $entry->specsTrial = $data['Specs_trial'];
            $entry->entryStatus = $data['Status'];
            $entry->summaryResults = $data['Summary_results'];
            $entry->testType = $data['Test_type'];
            $entry->variety = $data['Variety'];
            $entry->year = $data['Year'];
            $entry->entryId = $data['ID'];
            $entry->internalSpecsTrial = $data['Internal_specs_trial'];
            $entry->prio = $data['Prio'];
            $entry->trialName = $data['Trial_name'];
            $entry->xy = $data['XY'];
            $entry->internalStatusTodo = $data['Internal_status_todo'];
            $entry->samplingAnalysis = $data['Sampling_Analysis'];
            $entry->statusObservations = $data['Status_Observations'];
            $entry->subsidyProject = $data['Subsidy_project'];
            $entry->xyRandomiser = $data['XY_randomiser'];

            if (Craft::$app->elements->saveElement($entry)) {
                Craft::$app->getSession()->setNotice('Entry saved.');
            } else {
                Craft::$app->getSession()->setError('Couldn't save the entry: ' . implode(', ', $entry->getErrorSummary(true)));
                continue;
            }

    }
    $data = ['message' => 'JSON data read successfully'];
    return $this->asJson($data);
}

}
Edited Twig template
{% extends "_layouts/cp.twig" %}
{% set title = "jsonify"|t('_jsonify') %}

{% set fullPageForm = true %}

{% block content %}

{% set folderId = 1 %}
    {% set assets = craft.assets.folderId(folderId).kind('json').all() %}

    {% if assets|length %}

            {% for asset in assets %}

                    {% if asset.extension == 'json' %}
                        {{ asset.filename }}
                        <form method="post">
                            {{ csrfInput() }}
                            {{ actionInput('jsonify/import/test') }}
                                <button
                                    style="margin-left: 30px; background: #d3d3d3; padding: 3px 12px; border-radius: 4px"
                                    class="json-button"
                                    width="120px"
                                    >
                                    Read JSON
                                </button>
                        </form>
                    {% endif %}

            {% endfor %}

    {% else %}

No assets found.

    {% endif %}
   {% endblock %}

Inside the button is the action to trigger the method.
At this moment the template is loaded inside the settings. I rather have my plugin in a screen which is accessible from crafts dashboard sidebar, but I have no clue how to make that happen..
Answer: Before we dive in… you might try the first-party Feed Me plugin, which can import and synchronize data from JSON files, without any coding required.

I think you've got all the pieces you need—and then some!

You don't need to configure a route to your controller—plugins automatically have their controllers exposed via action routes.
Solution: Remove UrlManager::EVENT_REGISTER_SITE_URL_RULES event listener.

As you noted, Craft::$app->onInit() is triggered on every request.
Solution: Remove this block, and allow the plugin methods to be called from your dedicated controller!

Your controller is not autoloadable. PHP classes must be named the same as their file.
Solution: Rename the class from JsonifySettingsController to ImportController, and rename the file to ImportController.php. This file must be in the your-plugin-directory/controllers/ directory—or, in a controllers/ directory next to your primary plugin class.

Only public controller methods can be routed automatically. Currently, your action method is private!
Solution: Use public function actionHandleJsonRead() for the method signature.

Your settings template includes markup that conflicts with the built-in form element. Craft wraps the output from getSettingsHtml() in a <form> that automatically POSTs values to its plugins/save-plugin-settings action.
Solution: Use a different template. Add templates/import.twig to your plugin's folder, and it will be automatically accessible at /admin/jsonify/import!
Don't worry about Javascript and Ajax right now. Use the actionInput() function inside a basic HTML form, like this:
<form method="post">
    {{ csrfInput() }}
    {{ actionInput('jsonify/import/handle-json-read') }}

    <button>Import JSON Data</button>
</form>

This will submit a normal HTTP request to Craft, which will route it to your controller.
Note: You are already loading the asset in the back-end during import (with Asset::find()). There is no need to send its URL as part of the request, nor download the asset file from its URL. Instead, the browser will make a request to the back-end, which reads the file and performs the import.

Setting a flash message has no effect for JSON requests—and repeatedly setting the same flash level multiple times ("notice," in this case) will only display the last message (the others are overwritten).
Solution: Track failures by setting a flag, and use the asSuccess() method to send a response. The body of your action method might look like this:
$failures = 0;

foreach ($jsonFile as $key => $data) {
   // ... look up existing entry

   if ($existingEntry) {
       $failures++;

       continue;
   }

   // ... do import
}

// ...

return $this->asSuccess(Craft::t('jsonify', 'Import complete, skipping {num} duplicate record(s).', ['num' => $failures]));

Note the different return statement. This method automatically sets flash messages, or formats them appropriately for Ajax requests (if you want to switch back). Our message includes the number of entries that didn't import due to duplication.

ImportController::actionIndex() is not currently used.
Solution: Remove it!

This is not guaranteed to be a complete solution, but hopefully it helps clean up what you have so it's easier to tell what's going on!
Comment: I thank you so much for tyour help!
All your solutions are very good explained so I've seen where I did it wrong.

However, at this moment when I submit the form, I get a message that my settings are saved but not the actual function is being fired. Any idea how I can fix that?
Comment: Ah, I believe this is a result of the form ending up nested inside another form, which  is preconfigured to hit Craft's internal plugin settings controller. I would recommend adding a separate template dedicated to this form, according to [these instructions](https://craftcms.com/docs/4.x/extend/cp-templates.html).
Comment: I'm heading right into it!!
Comment: So after an hour of puzzling and going back and forth, I think I'm on the verge of getting things done how I want them to be done.

So now my plugin has it's on template page accessible from the dashboard, so I copied my code from the settings to the index.twig. But now when I click the button: I get the error: Page not found -> Caused by invalid route: Unable to resolve the request '_jsonify/import/handle-json-read'. Any ideas how this can come?
Comment: There shouldn't be an underscore in the first segment of that path… an action path is always in the format `{plugin-handle}/{controller-name}/{action-name}`!
Comment: This was also not working. Meanwhile, there are a lot of edited files so let me give an update on how the code looks now. I'll edit my code on the top


Quotient groups of a finite symmetric group

Question: What are the quotient groups of a finite symmetric group $S_n$? Can we classify them?
Answer: For $n \neq 4$, the subgroup $A_n$ is simple. Thus its image in any quotient of $S_n$ is either trivial or all of $A_n$. In the former case the only quotient groups are the trivial group and $S_n/A_n \cong C_2$. In the latter case the only quotient group is $S_n$ (except for $n = 1, 2$ but nothing new happens here).
The only remaining case is $S_4$, and here one can just write down all normal subgroups by hand (e.g. by inspecting the character table, or just casework on cycle types). In this case the Klein four group $V_4$ is also a normal subgroup of $S_4$ so there is an exceptional quotient $S_4/V_4 \cong S_3$, but I think this is it. Algebraically this exceptional quotient is responsible for the existence of the resolvent cubic.
Comment: "In the latter case the only quotient group is $S_n$"

Could you explain this?
Comment: @Makoto: if $A_n$ injects into a quotient group of $S_n$, then the corresponding kernel has order at most $2$, and you can easily verify that $S_n$ has no normal subgroups of order at most $2$ except for very small $n$.
Comment: Thanks. Let $K$ be the kernel. By the assumption $K \cap A_n = 1$, Hence $|KA_n| = |K||A_n|$.
Hence $|K| = 2$ if $K \neq 1$.
As for the fact that there is no normal subgroups of order 2, I found the following proof.
http://planetmath.org/NormalSubgroupsOfTheSymmetricGroups.html