How to handle large numbers of redirects for dynamic pages with optional slugs, in Next.js?

Question: My site has a few dynamic routes that result in thousands of hydrated pages. The pages follow a url structure like: /artists/[id]/[slug] or /concerts/[year]/[month]/[day]/[slug]. Currently, my page structure mimics those routes: /pages/artists/[id]/[slug].tsx and /pages/concerts/[year]/[month]/[day]/[slug].tsx.
The route with slug is preferred, but the site should gracefully redirect when the slug is not available. For example, I would like to have any request going to /artist/id be redirected to /artist/id/slug. And likewise, I'd like to do some redirecting for various parts of the concerts urls.
I originally tried specifying the redirects in next.config.js like:
module.exports = {
  ...
  async redirects() {
    const [allArtists, allConcerts] = await Promise.all([...]);
    return [
      ...allArtists.map((artist) => {
        return {
          source: `/artists/${artist.id}`,
          destination: `/artists/${artist.id}/${slugify(artist.name)}`,
          permanent: false,
        };
      }),
      ...allConcerts.map((concert) => {
        return {
          source: `/concerts/${concert.year}`,
          destination: `/tours/${concert.year}`,
          permanent: false,
        };
      }),
      ...allConcerts.map((concert) => {
        return {
          source: `/concerts/${concert.year}/${concert.month}`,
          destination: `/tours/${concert.year}`,
          permanent: false,
        };
      }),
      ...allConcerts.map((concert) => {
        return {
          source: `/concerts/${concert.year}/${concert.month}/${concert.day}`,
          destination: `/concerts/${concert.year}/${concert.month}/${concert.day}/${slugify(concert.name)}`,
          permanent: false,
        };
      }),
    ],
  },
};

However, as of today, vercel/next.js does not support more than 1,000 redirects specified in that file.
I tried to return redirect: pathWithSlug from getStaticProps, but get the following error:
Error: `redirect` can not be returned from getStaticProps during prerendering

Any ideas or approaches for how I can accomplish this behavior?
Answer:
vercel/next.js does not support more than 1,000 redirects specified in that file.

You weren't kidding, this is something important to consider before moving into the platform. Some ideas & compromise:

Use getServerSideProps for pages/artists/[id] and use redirect there

Use the same content for pages/artists/[id] as pages/artists/[id]/[slug], but set canonical url to avoid SEO penalty
Answer: First, you could significantly reduce the number of entries for the /concerts/* to /tours/* redirects by using path matching.
async redirects() {
    return [
        // ...
        {
            source: '/concerts/:year/:month',
            destination: '/tours/:year',
            permanent: false
        },
        {
            source: '/concerts/:year',
            destination: '/tours/:year',
            permanent: false
        },
        // ...
    ]
}

Unfortunately, the same cannot be done for the other paths. This alone could potentially reduce the number of entries below 1000 - depending on the amount of artists/concerts you have - but sooner or later it would become a problem again.
Second, to address the remaining paths, I would convert your /artists/[id]/[slug] and /concerts/[year]/[month]/[day]/[slug] routes into dynamic catch-all routes:

/artists/[...slug]
/concerts/[...slug]

This would allow the /concerts/[...slug].tsx page to match both /concerts/2020/08/20 and /concerts/2020/08/20/concert-name URLs, meaning you wouldn't need a redirect for these pages at all. The same would apply for the artists/* routes.
As @DerekNguyen mentioned in his answer, having a canonical URL that would be used in both for SEO purposes would be ideal.
Comment: Thanks - I was hoping for an approach other than a catch-all route. The catch-all page kind of defeats the purpose of the routing infrastructure and I'm not sure it offers much over having `pages/artists/[id]/index.tsx` return content with only meta refresh and canonical link tags.


Proof of correctness of normal equation

Question: I was taking an online course and saw linear regression being by gradient descent The intuition behind why the method would work seemed plausible.
I tried understanding normal equation as to why setting individual partial derivates to 0 and solving the equations give the optimal values of theta, but that didn't ring a bell.

Why setting partial derivatives to zero, and solving the equations gives optimal value of theta. I also went through the following link. The part about The minimum is determined by calculating the partial derivatives of S(β1,β2) with respect to β1 and β2 and setting them to zero
is still dicey to me. Why would it work. Why would it give the values of β1 and β2 for minimized cost function.
If we have multiple local optima, would the normal equation method give the global optima? If so, why?
Answer: This is really just a matter of using standard results in multivariate calculus.  In the ordinary least-squares (OLS) problem, the objective function being minimised is:
$$F(\boldsymbol{\beta}) = ||\mathbf{y} - \mathbf{x} \boldsymbol{\beta} ||^2.$$
The first and second derivatives (gradiant and Hessian) are:
$$\begin{equation} \begin{aligned}
\nabla F(\boldsymbol{\beta}) &= 2 [ (\mathbf{x}^\text{T} \mathbf{x}) \boldsymbol{\beta} - (\mathbf{x}^\text{T} \mathbf{y}) ], \\[6pt]
\nabla^2 F(\boldsymbol{\beta}) &= 2 (\mathbf{x}^\text{T} \mathbf{x}). \\[6pt]
\end{aligned} \end{equation}$$
The Gramian matrix $\mathbf{x}^\text{T} \mathbf{x}$ is non-negative definite.  So long as the columns of the design matrix $\mathbb{x}$ are linearly independent (which is generally the case in regression problems) it is positive definite.  In the latter case the objective function $F$ is strictly convex, which means that it has a global minimising value at its unique critical point, which is found by solving:
$$\nabla F(\hat{\boldsymbol{\beta}}) = \mathbf{0}
\quad \quad \implies \quad \quad
\hat{\boldsymbol{\beta}} = (\mathbf{x}^\text{T} \mathbf{x})^{-1} (\mathbf{x}^\text{T} \mathbf{y}).$$
In the least-squares problem, linear independence of the columns of the design matrix $\mathbb{x}$ ensures that we do not have multiple optima.  In the case where we have linearly dependence in the design matrix, this means that there are excess variables that give "ridges" of minimising values, and the parameters are not identified.  This is usually dealt with by removing columns of the design matrix until linear independence is obtained.
Answer:
Why setting partial derivatives to zero, and solving the equations
      gives optimal value of theta.  I also went through the following
      link. The part about The minimum is determined by calculating the
      partial derivatives of S(β1,β2) with respect to β1 and β2 and
      setting them to zero  is still dicey to me. Why would it work. Why
      would it give the values of β1 and β2 for minimized cost function.

From calculus, if we set the gradient to zero we arrive at an extremum (see, e.g, here). Hence, setting the partial derivatives to zero w.r.t. the $\beta_i$'s is generally a good approach to optimise over some objective function.

If we have multiple local optima, would the normal equation method
      give the global optima? If so, why?

We do not have multiple local optima. The loss function for the linear regression problem is quadratic and (strictly) convex, so there exists only one, unique, global optimum. Hence, by the properties of the objective function the normal equations will yield that global optimum.
Comment: Why are you so surprised? The cost function is a quadratic polynomial with a positive sign on the highest term, so it is strictly convex and admits only one global extremum (by convexity, that will be a minimum). This holds both in the multivariate and scalar case, and, assuming the matrix $X$ is of full column rank, for all data.
Comment: Multivariate linear regression would **"always"** have a convex plot?(i.e. only one global minima)
Not only for 2 variables, and no matter what the data set is. For any variables, for any data points, if we use linear regression, then the cost function will have only global minima?
Answer: I just want to complement and integrate the very good answers provided above, just to provide a different point of view and provide a different intuitive understanding of the mathematical nature of the solution.
Given an OLS problem like the typical $y=X \beta + \epsilon$ where y is a $Tx1$ vector, $X$ is a $TxN$ matrix where the number of samples is T and the number of regressors is N, $\beta$ and $\epsilon$ are $Nx1$ vectors, you want to minimize the sum of squared errors. The problem can be seen as the resolution of an overdetermined set of T equations (each corresponding to a row of the precious representation): each equation is $y_{t}=x_{t} \beta$ for each row t (notice that $x_{t} $ is now a vector representing the t-th row of the matrix $X$, $y_{t}$ is a scalar). Since the system is overdetermined for most real-world applications where $y$ is not a linear combination of the columns of $X$, then there exists no exact solutions to this set of equations. However the best proxy for a solution for an overdetermined system is to choose the minimum norm solution, which is obtained by setting $\beta$ equal to the product of the pseudoinverse of the matrix $X$ and the vector of dependent variable $y$, where the pseudoinverse of $X$ is indeed $(X^{T}X)^{-1}X^{T}$. This is indeed the solution to the system that minimizes the squared norm of the vector $\epsilon = y-X\beta$. This is why you have that formula for the OLS estimator.
This is a just different way of interpreting the OLS estimator compared to the usual minimization of squared error or maximization of the corresponding likelihood. Just a different way of looking at the same mathematical problem.
I also add this concise source
Comment: This is a very confusing post because it switches between using "underdetermined" and "overdetermined" inexplicably.  Taken literally, the set of  $T$ equations "$y_t=X_t\beta+\epsilon_t$" (notice there should be no subscripts on the $\beta$) involves $T+N$ variables $\beta_i$ and $\epsilon_t$ and therefore is *underdetermined,* not overdetermined.  The set of equations $y_t=X_t\beta_t$ involves just $N$ variables and therefore, *provided $T\gt N,$* indeed is overdetermined: but the relevance of this point of view to the original problem is unclear.
Comment: @whuber oh my god just a typo, sorry for this, it was 4 am European time.. I think it may be an explanation for the typo. It was evident it was a typo..
Comment: OK, but now it seems you are consistently using "overdetermined" to mean *underdetermined.*  If not, then some explanation of your meaning is required.  Indeed, there *always* exists at least one exact solution to your system of equations: set $\beta$ to be *any* $N$-vector and for each $t$ between $1$ and $T,$ define $\epsilon_t = y_t - x_t\beta.$
Comment: I apologize for the edited typo and thank @whuber for noticing it. I also provided more clarity on the system of equations, that however to me is very trivial to see. I remember everyone that you are free to edit my answers, if you see evident typos.
Comment: I would have no idea how to fix your post because it doesn't seem to be a matter of typos, but of some kind of miscommunication about what you really mean by "$y_t=x_t\beta+\epsilon_t.$"  I have explained my interpretation, but your edits don't address that.
Comment: The miscommunication is in the following dichotomy equation/rows: the equation is $y_t=\beta x_t$ FOR EACH ROW $y_t=\beta x_t + \epsilon_{t} $. To me it was clear, maybe the sentence was not built appropriately, so I fixed for better clarity to the general public
Comment: It now looks correct, thank you.  However, your post essentially asserts (albeit in disguise), without proof or explanation, that the Normal equations minimize the sum of squares of residuals--and that's exactly what is being asked.
Comment: @whuber I posted it here because an equivalent question that was more in line with my answer was closed as a duplicate. However I do not see inconsistencies with the question, as the guy initially said "I do not understand why this solution works and how the maximization leads there etc..". My answer for future readers just aimed to provide an additional point of view on the topic without being forced to pass through optimization. Because the guy had issues in understanding it. Personally, I find it clearer to think of the system. So I just decided to share my view as it helped in my past.
Comment: @whuber and notice the disclaimer at the beginning "it is an answer to complement and provide a different point of view".
Comment: @whuber a user like you should understand even without sources (that however I posted) that the minimum norm solution is the one that minimizes the sum of squared residuals. What proof do we need?? It is in the source. Do not have time for a full proof, and think that everything is clear enough for everybody literate in statistic. But if you want to keep me hours talking about this post written in 5 minutes yesterday, I apologize but I do not have time for this kind of "gentle conflicts" leading nowhere.

Proof of correctness of normal equation


Has Belwin Mills improved their bookbinding?

Question: I'm sitting here looking at three separate books of sheet music for piano published as Kalmus Piano Series by Belwin-Mills. You know the ones; they have a cover in a solid color (often red or orange) with a handwritten score of Bach's Sinfonia #15 superimposed in white ink, and the actual title of the score in black on top of all that.

All of them have disintegrated into little pamphlets of music. Most of my equally old scores by different publishers are still intact.
I'm wondering whether I should replace them with new copies or seek alternative editions. Will newer ones fall apart too?
Comment: (Also, sometimes I've taken a big unwieldy volume, sliced off its binding, and taken it to Kinkos to be spiral-bound so now it lies flat. I started the habit when a big glue-bound paperback volume disintegrated, but now sometimes do it preventatively.)
Comment: @Lazy so all the covers look the same.
Comment: I have a hard time imagining anyone here knowing, but have you tried asking them directly?
Comment: I do not know the ones, but I'm seriously confused why they would put Bach on the cover for a Beethoven score ...
Comment: "You know the ones"? Are you sure they're a thing the world over? Many of us have never been to your continent (regardless which one it is).
Comment: @Divizna true enough, but by reading this description you can infer that these editions are well known by at least some people in at least some part of the world.
Answer: Belwin-Mills no longer exists as such. Their catalog is now owned by Alfred Music, which

continues to publish music with the Kalmus name under the Kalmus Classic Series imprint, the vast majority consisting of inexpensive reprints of old editions now in the public domain. (Wikipedia)

Even with better binding, these are cheap and potentially unreliable (i.e., error prone). If possible, the investment in higher quality scores would be worthwhile. Bärenreiter and Henle being top choices.
However, the latter are expensive. I have had good experiences with Alfred scores generally, but can't speak specifically to their Kalmus publications. These scores are also available from publishers like Peters, which similarly produces reprints of other editions, and Dover.
The same source editions can also be printed for free from websites like IMSLP and put in a three ring-binder (I recommend using plastic sheet protectors) or a dedicated music folder like the one produced by Cranbury.
Comment: "potentially unreliable (i.e., error prone)": for the most part this arises because the business model is to publish reproductions of older editions whose copyright protection has expired.  These older editions are more likely to have errors because they are less likely to benefit from the latest musicological research.  A problem with plastic sheet protectors is that they make it difficult to use a pencil.  If one is printing music for use in rehearsal it may be better to invest in heavier paper.
Comment: @phoog Follow the link to the Cranbury folder. It's designed specifically for music, and the plastic area comprises two strips covering the top and bottom of the page, allowing for note taking.
Comment: Nice.  I _had_ followed the link, but hadn't noticed that detail.


Android Kotlin: Translate animation on view is not working

Question: I am working on an Android Kotlin project. I am applying animation on views. Starting from the basics, I am trying to animate an image view from the bottom of the screen to the center of the screen.
I have an XML layout with the following code.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"
    tools:context=".MainActivity">

    <LinearLayout
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <ImageView
            android:id="@+id/main_image_logo"
            android:src="@drawable/memento_text_logo"
            android:layout_width="@dimen/main_logo_image_width"
            android:layout_height="wrap_content" />
        <TextView
            android:textColor="@android:color/white"
            android:id="@+id/main_tv_slogan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/main_slogan"
            />
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

I am animating the logo image translating from the bottom to the center (where it is originally) in the activity with the following code.
private fun animateMainLogo() {
        val valueAnimator = ValueAnimator.ofFloat(0f, main_image_logo.y)

        valueAnimator.addUpdateListener {
            val value = it.animatedValue as Float
            main_image_logo.translationY = value
        }

        valueAnimator.interpolator = LinearInterpolator()
        valueAnimator.duration = 1000
        valueAnimator.start()
    }

When I run the code, it is not animating the view. It is just there where it is and static. What is wrong with my code and how can I fix it?
Answer: translationY of view in layout is 0. If you want to animate it from bottom to current position - you should change translationY values from some positive value to 0.
private fun animateLogo() {
    val translationYFrom = 400f
    val translationYTo = 0f
    val valueAnimator = ValueAnimator.ofFloat(translationYFrom, translationYTo).apply {
        interpolator = LinearInterpolator()
        duration = 1000
    }
    valueAnimator.addUpdateListener {
        val value = it.animatedValue as Float
        main_image_logo?.translationY = value
    }
    valueAnimator.start()
}

Same thing can be done this way:
private fun animateLogo() {
        main_image_logo.translationY = 400f
        main_image_logo.animate()
            .translationY(0f)
            .setInterpolator(LinearInterpolator())
            .setStartDelay(1000)
            .start()
    }

Add this lines to LinearLayout and ConstraintLayout because without them LinearLayout will cut of parts of animated view when it is outside of LinearLayout bounds.
android:clipChildren="false"
android:clipToPadding="false"

Or make main_image_logo direct child of root ConstraintLayout. Here is result:


How to solve $\sec^4(x)=\tan^4(x)+3\tan(x)$

Question: Background
I was trying to solve this purely trigonometric equation:
$$\sec(x)^4=\tan(x)^4+3\tan(x)$$
I performed my usual tactic,which is to rewrite everything in terms of sin and cos, and solve the resultant equation. (Works 100% of the time,70% of the time) and got:
$$1=\sin(x)^4+3\sin(x)\cos(x)^3$$
Which I could not solve, although if anybody CAN solve it I would love to hear how. So I input the original equation into a computer algebra system and it told me that it is an equivalent problem to the solution of this equation:
$$2\sec(x)^2=3\tan(x)+1$$
Now this was solvable with the same approach that failed on the original equation. I just converted it into a quartic polynomial problem at the end, after rewriting it in terms of sin and cos.
But a number of questions arose, the answers to which would greatly help my ability to solve trig equations, but for the purpose of this site I think i'll split them up into multiple posts each with a very precise focus, so that they will be more useful to other users.
Question: How do I know if a given trigonometric equation can be simplified?
(of course im primarily concerned about non obvious cases)
and by

simplified

I think the example I gave is a good one for what I mean by simplified. Two things happened:
(1) The number of terms in the equation that contained trigonometric functions was reduced. it went from 3 in the original to only 2 in the computer algebra system's output
(2) The order (natural power) of any trig terms in the equations was reduced.
How do I know if it is possible to accomplish one or both of these goals, given a purely trigonometric equation?
(note: im not asking for a general procedure to do so, just a method of determining if this can be done given a purely trigonometric equation. I will ask other questions that arose from this problem later. )
Comment: Why do you stick to sin and cos rather than using the identity $\sec^2 x = \tan^2 x + 1$ from the outset? You immediately get a *quadratic* in $\tan x$.
Comment: Generally speaking, you don't know until you try.
Comment: Agreeing with what @AdamRubinson says, I think this is why math is "difficult". You just need to put in the practice.
Comment: It's impossible in the general case as that's equivalent to solving the halting problem.
Answer:
$$1=\sin(x)^4+3\sin(x)\cos(x)^3$$

Start from here,
$$\begin{align}
1&=\sin^4(x)+3\sin(x)\cos^3(x)\\
\\
1-\sin^4(x)&=3\sin(x)\cos^3(x)\\
\\
(1+\sin^2(x))\cos^2(x)&=3\sin(x)\cos^3(x)\\
\\
&\Rightarrow \cos(x)=0\tag{1}\\
\\
&\text{or}\\
\\
1+\sin^2(x)&=3\sin(x)\cos(x)\\
\\
\cos^2(x)+2\sin^2(x)&=3\sin(x)\cos(x)\\
\\
1+2\tan^2(x)&=3\tan(x)\\
\\
(\tan(x)-1)(2\tan(x)-1)&=0\\
\\
&\Rightarrow \tan(x)=1 ~~\text{or} ~~\tan(x)=\frac{1}2\tag{2}
\end{align}$$
From (1), (2) we get:
$$x=\frac{\pi}2+n\pi, ~\frac{\pi}4+n\pi,~ \arctan\left(\frac{1}2\right)+n\pi, n\in\mathbb{Z}$$


Writing a plugin file in ClojureScript for use in CKEditor

Question: I currently have a project that is using ClojureScript, shadow-cljs, re-frame, and CKEditor.
I am trying to figure out how to write a custom plugin for CKEditor usoing CLJS instead of JS.
CKEditor uses the following to load external custom plugins
// Loads a plugin from '/myplugins/sample/my_plugin.js'.
CKEDITOR.plugins.addExternal( 'sample', '/myplugins/sample/', 'my_plugin.js' );

Is there a way to write my_plugin.js in CLJS in my current project?
Comment: I think your going to have to be more specific. Have you tried? What issue did you run into?
Answer: I think your question is: I have a CLJS project that uses shadow-cljs and happens to use CKEditor as a library. I also want to create a plugin for CKEditor within the same project.
If that's the case, I think what you need is just create a new build for the plugin code in the :builds section of your shadow-cljs.edn file and configure it properly (eg. source files, etc.). See the Build Configuration section of the shadow-cljs User's Guide for details.
Once you build your plugin, it will put the output JS file in some location. Probably you need to copy this plugin JS file to a location in the "parent" project before building the main project.
Comment: I do believe your answer is going in the right direction, but my unfamiliarity with CLJS and shadow-cljs is getting in my way. I am going to have to come back to this a little while latter and hopefully I can get it working. Thanks for your answer.
Comment: I don't know much about your project and how you want to extend CKEditor, but depending on the features of plugin, you may want to consider writing it in plain JavaScript. ClojureScript is great but for a trivial extension it may be overkill.
Comment: I hear you, it is probably easier to write in plain JavaScript, but since I am already in a CLJS environment I thought it would make sense to also use ClojureScript to develop the plugin as well. It seems that thought might be a bit naive though. Seems to me like that would be a big hole for CLJS if you have to fire-up another environment to produce JS code for a project already being developed with CLJS; I am sure as with most things, there is probably a good reason for this, but it sure crushed my dreams of "one language to rule them all" :)   Thanks for your help anyway.
Comment: There might be some hope: maybe you can declare your CKEditor plugin as a module that depends on the code the main app, so that you don't have two copies of the CLJS runtime but just one. See the [Code Splitting](https://shadow-cljs.github.io/docs/UsersGuide.html#CodeSplitting) section of the CLJS User Guide.
Comment: That looked promising at first unfortunately, this app is an SPA so separate pages is not an option.


interior and adherence

Question: i have a difficulties for this question. Can you help me please to resolve it.
For all $r \in \mathbb{R}_+,$ we let $$\Omega_r = \{(x,y) \in \mathbb{R}^2, x= r \cos t , y = r \sin t , t \in [0,2 \pi]\}$$ and we consider the family $\sigma = \{\Omega_r , r \in \mathbb{R}_+\}$
We endow $\mathbb{R}^2$ with the topology $\tau$ such as its base is $\sigma.$ Let $$A = \{(x,y) \in \mathbb{R}^2: |x+y| > 2\}$$
My question is: can you give me please an simple methode to find $\overline{A}$ and the interior of $A$?
Answer: The basis elements of this topology are the circles centered at $(0, 0)$. Here is what the region $A$ looks like:

The interior of $A$ consists of all open sets contained in $A$. Which basis elements are in $A$? The answer is none, and therefore the interior is empty.
$\overline{A}$ consists of $A$ and its limit points. $x$ is a limit point of $A$ if every neighborhood of $x$ intersects with $A$ at a point other than $x$ itself. Can you identify all such points? Which basis elements intersect with $A$?
Comment: Let $x \in A.$ Any voisinage of $x$ must contain an circle $\Omega_r$ but i don't know how we find all the point $x$ such that $\forall V \in \mathcal{V}(x), V \cap A \neq {x}$ Can you help me please on this difficuties.
Comment: @luluuuu Which circles $\Omega_r$ from $\sigma$ intersect with $A$?

interior and adherence


Geometry with parallelogram

Question: My question is...
I want to know your another solution.
or I want to know if my solution is appropriate.
and I'd appreciate some feedback on my work.

Mentioned the word)
Parallelogram ABCD, $\angle BAE = \angle CAE$  , $\overline{BE}+\overline{BC}=\overline{BD}$  , Find the $\overline{BC} : \overline{BD}$
Answer: Your solution is correct. And I think this is the only geometry way to do it. (You can try using complex plane, but I tried and it's messy). Well done :)
Answer: I finished the final conclusion in a different way.(I used circle)
Additionally, Let's solve the problem without the auxiliary line.

Geometry with parallelogram


Utilizando @Table Hibernate

Question: Como que faço para utilizar a anotação @Table do hibernate utilizando uma variável que traga o nome da tabela por exemplo @Table(name = "dep4"+Dados.getCodEmp)? Pois estou utilizando dessa forma mas me apresentada o seguinte erro:
The value for annotation attribute Table.name must be a constant expression

Preciso disso porque no banco de dados do sistema em questão as tabelas são geradas com a seguinte nomenclatura prefixo + o código atribuído a empresa, por exemplo dep4+(CodEmp). Esse código eu pego de um arquivo de texto que fica dentro do diretório da aplicação.
Comment: Até dá pra fazer uma coisa, mas não entendi esse `"dep4"+Dados.getCodEmp`. Isso é o nome da tabela ou seria um "prefixo"? Tipo: `("dep4"+Dados.getCodEmp) +  "_nome_da_tabela"`
Comment: O **"dep4"+Dados.getCodEmp** seria o nome da minha tabela, onde o **dep4** é prefixo padrão do nome da tabela o **Dados.getCodEmp** é de onde eu pego o código da empresa para compor o nome da tabela. Por exemplo estou logado no banco com a empresa de código **01** então o nome da minha tabela seria **dep401**
Comment: Ah sim, a solução que eu tinha como sugestão era para outro propósito. Dá para gerar os nomes dinamicamente, mas não pela anotação `@Table`: https://stackoverflow.com/a/1507980/4056678
Answer: Creio que infelizmente não possa fazer isto.
@Table é um anotação do Java, e anotações Java não podem receber valores em tempo de Runtime. As anotações do Java só podem receber constantes, conforme a mensagem de erro lhe informou.
Answer: Você deve criar um  Generating Database Schemas
 ou  Interceptors para os schemado seu banco de dados.
public class Main {

   public static void main(String[] args) {
     Persistence.generateSchema("samplePU", null);
   }
}

De uma olhada no links.
Comment: Embora este link possa responder à pergunta, é melhor incluir as partes essenciais da resposta aqui e fornecer o link para referência.  As respostas apenas por link podem ser invalidadas se a página com o link for alterada. - [Da Revisão](/review/low-quality-posts/151427)
Comment: O link não é uma resposta para o casso dele. Só coloquei  para ele da uma olhada ..
Comment: Não são regras minhas, são regras do StackOverflow, recomendo que leia https://pt.stackoverflow.com/tour

Utilizando @Table Hibernate


Suppose G is a connected planar simple graph with $e$ edges and $v$ vertices with no cycles of length 4 or less...

Question: Suppose G is a connected planar simple graph with $e$ edges and $v$ vertices with
no cycles of length 4 or less.
Prove  that (For $ v ≥ 4$):
$$e ≤ {\frac{5}{3}}v - {\frac{10}{3}}$$
-I have a basic understanding of planar graphs based off of our lecture in class. I understand that planar means it can be drawn on a single plane without any edges crossing and I know that since it's a connected graph it has one component, and I know that since it is a simple graph it does not contain loops or multi-edges. Although I don't understand how to tie this in with a proof such as this, any help is appreciated.
Comment: Use Euler's formula and double-count the number of pairs $(e,f)$ such that $e$ is an edge of the face $f$.
Answer: The following theorem is well known in graph theory (see theorem 6.10 in http://compalg.inf.elte.hu/~tony/Oktatas/TDK/FINAL/Chap%206.PDF):
For a connected simple planar graph with $v$ vertices and $e$ edges, and girth $g$, we have
$$e\leq \frac{g}{g-2}(v-2)$$
Note the girth $g$ is the length  of the smallest cycle.
In our case $g=5$, thus $$e\leq \frac{5}{3}(v-2)$$
Comment: This looks good,although in our question is states that this must be less than or equal to the number of edges, where do we get this number from and how do we know that the edges will always be less than it when v is greater than or equal to 4?
Comment: @D.Peterson I have not completely understand the problem that you are talking about. Could you please be more specific about it?
Comment: I understand the theorem that you presented. But I don't see how to apply this specifically to the $v\ge4$ case as the question states. Furthermore, do you apply a real number in as $e$ or just leave it as a variable to represent any # of edges w/ the 4 vertices.
Comment: @D.Peterson The result apply to all graphs with girth of least 5. Then it's true for all graphs with $v\geq 5$ (Or if they do not have cycles, then they will be trees and it will be also true " in tree $e\leq v-1$ "). Note that the since the smallest cycle is of length 5, then the result is obvious for $v=4$. Thus the above result  is true for $v\geq 4$. On the other hand, $e$ is the number of edges of any planar graph with girth at least 5.
Answer: The sum of the degree of the regions in the graph will be $2e$ as each edge contributes to 2 regions. But again, we have no circuits of length $4$ or less. So each region has degree $\geq 5$. So, $2e \geq 5f \implies \frac{2}{5}e \geq f$.
Now, apply the Euler's formula which states $v-e+f=2\implies e-v+2=f \implies e-v+2 \leq \frac{2}{5}e \implies e \leq \frac{5}{3}v - \frac{10}{3}$.
Answer: Maybe you are stuck at why $5$ and $g$ in the other 2 answers by tomriddle99 and M.Badaoui. Here I show the reasons behind that.

For any edge, it contributes 1 (in one cycle) or 2 (not in one cycle) to the degree of the region it is inside.
Then when $v=4$, it may be $C_4$ (cycle-4) which has degree 4, $C_3$ with one edge with degree 5, $C_2$ with 2 edges (but $C_2$ is excluded by not allowing the multi-edge), $C_1$ with 3 edges (excluded by not allowing the loop) or $C_0$ with 4 edges with degree 8.
For $v=1\sim 3$, the above process can also be applied although you stated $v\ge 4$.
Since "no cycles of length 4 or less", so we can only $v=5$ which has the least degree 5 when $C_5$. This is what the reference chapter by M.Badaoui says:

As g is the length of the smallest cycle in G,
therefore g is the smallest degree of a region.


custom module: drupal_add_js and drupal_add_css do not work after form validation?

Question: I have created a custom module that changes the layout & adds extra functionality to one of my content type creation and edit forms.
It works beautifully and as expected apart from when I submit the form with, for example, a blank node title or any other required fields.
The page is reloaded as expected with the error message, the form modifications are loaded from the module (field #prefix, #suffix etc..) but the css and the js are not loaded.
Here is the code I have:
/**
* Implementation of HOOK_form_alter()
*/
function mymodule_entry_form_modify_form_alter(&$form, $form_state, $form_id) {

  // 1.ENTRY FORM
  if ($form_id == 'entry_node_form') {

  // here were some form field modifications i removed

/* 1.3 LAYOUT - ADD JAVASCRIPT FILES
 * Add .js files
 */
// add jquery script before calling it
drupal_add_js(drupal_get_path('module', 'mymodule') . '/includes/js/jquery.fixheight.js');
// call the script
drupal_add_js(drupal_get_path('module', 'mymodule') . '/includes/js/mymodule_entry_form_modify.js');

/* 1.4 LAYOUT - ADD CSS FILES
 * Add .css files
 */
drupal_add_css(drupal_get_path('module', 'mymodule') . '/includes/css/mymodule_entry_form_modify.css');

 }
}

Can anyone explain why this happens?
Comment: I'm still using drupal 7.9
Comment: If I understand your code correctly the js and css are just loaded only inside the form.
Comment: well yes, what the codes says is if the $form_id == 'entry_node_form' (my custom content type is called 'entry') it does the following ... which includes heaps of $form modifications, for example: $form['field_entry_cust_id']['#disabled'] = TRUE; and it also adds javascripts and css files. I only want them to be applied and loaded to that specific content form of course.
Comment: @tecjam is it a typo where in you've used **mymodule** at one place and **mymodul** in another?
Comment: Hi, yes it is. My custom module has a different name with regards to the project i'm working on which I didn't feel like enclosing. I've edited it to avoid any further confusion. ;-)
Answer: I don't use D7, but I believe you should be using #attached and it should fix your issue.
Comment: @tecjam It's by design not a bug. The form is cached, and so the code to build it (including your form_alter) is never called whenever the cache is used. That's why it's important that the data's actually stored in the FAPI array itself.
Comment: Thanks for your answer, Andy. Again I've learnt something new with regards to FAPI. =)
Comment: You are right, now it works. Is there any specific reason why drupal_add_ doesn't work in this case, or is it a bug?
Answer: You have to add to your hook_form_alter a new validation callbacks:
/**
* Implementation of HOOK_form_alter()
*/
function mymodule_entry_form_modify_form_alter(&$form, $form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'mymodule_entry_form_modify_form_alter-submit_callback';
}

In your new validation callback, add your drupal_add_css().
function mymodule_entry_form_modify_form_alter-submit_callback($form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/includes/js/jquery.fixheight.js');
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/includes/js/mymodule_entry_form_modify.js');
  drupal_add_css(drupal_get_path('module', 'mymodule') . '/includes/css/mymodule_entry_form_modify.css');
}

And this is a general rule: add your drupal_add_css in the validation callback of all your forms if they need a dedicated style even if a drupal_set_form have been triggered.


How do I unhook an action? My current method does not seem to be working

Question: I am working on a WordPress website, with WooCommerce functionality.
I am currently trying to remove the social sharing feature, which is displayed on the Product Pages.  I am trying to achieve this through the removal of the Action from its Hook, by placing the following code in the functions.php file:
<?php
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_sharing', 50 );
?>

Said functions.php is placed within the Child Theme I have created.
Unfortunately, this is not removing the social sharing feature.  Does anyone know why?  To see if there was an issue with the Hooks, I added an Action to the same Hook, to which this worked.
Could it be possible that the Social Sharing feature has been placed in some parent folder which overrides/has higher priority over the functions.php file in the Child theme?  If this is the case, what would be my options in getting said feature removed.  I can only think of placing the affected file in the Child theme and then manually removing the relevant coding.  This is a last resort as it may cause problems, at a later date, when parent files are updated etc.
Answer: woocommerce_template_single_sharing() calls the Woocommerce template located at woocommerce/templates/single-product/share.php where there's a do_action call for other plugins & themes to add social sharing. If you want to "block" plugins from using that, your best bet (if you're building a theme) would be to use the built-in Woocommerce template override feature and simply prevent this do_action from firing. This would not cause any problems unless Woocommerce did a massive, structural rework. But otherwise, updating Woocommerce and any other plugins or a parent theme wouldn't affect your child theme.
In your child theme, create a directory called woocommerce, add a sub-directory called single-product, and then copy the share.php file from the above location in the plugin to that location in your theme.
Comment out the do_action and voila! No more social sharing and anything that hooks into that do_action won't run.
As an alternative...if you know exactly what's hooking into that do_action, you would run a remove_action on that bad boy, but then you need to hunt these things down and manually update your call any time a plugin tries to hook into it.
Comment: Thank you for this answer.  After playing around myself, the suggestion was pretty much what I did. :-)
Answer: You could use https://codex.wordpress.org/Function_Reference/remove_all_actions
add_action('plugins_loaded', function(){
   remove_all_actions('woocommerce_share_hook');
});

Comment: Thank you for your answer.  Whilst not my chosen approach this time,  this is something that may be useful in the future. :-)


How can you lower the speed of voice vibrato?

Question: Over time with practise and good technique, I have finally developed a soft vibrato on the deeper notes. However, it is quite a fast-paced vibrato with a short period between oscillations.
What kinds of drills can I practise to increase the period between oscillations, or in other words slow down the vibrato? I am looking for a slow and rich vibrato like in this video @ 2:30.
Comment: Hard to say for sure without hearing your voice specifically, but often too-fast vibrato is caused by air pressure beneath, instead of only through, the vocal chords. This can be an indication of poor, "tense" technique (again, not saying this is your case necessarily). If this is the case, you need to relax your entire throat and, even more importantly, your diaphragm. Start with a full breath, and keep your diaphragm relaxed, flexible, and as low as  possible. Don't "push" to create vibrato; it should naturally happen on its own.
Answer: Well, in the video it sounds like the singer is slowing down the vibrato by singing the two notes separately and "melding" them together through glissandos. For me, the easiest way to sing with a slow vibrato is to do the same. I would consider the two notes as separate, and alternate between them in a smooth fashion.
For the strong and rich vibrato, you could sing the vibrato as you've practiced normally and then, with that same tone, slow it down using the method above.
Hope this helps!


Ajax Data is not properly assigning to jQuery Input with the same classes

Question: I'm working on Invoicing System in which Rate(Amount) value automatically changes on changing the Product(Item).
The issue I am facing is on Changing the first Product all rest of the Product Rate changes to Rate of the first Item.
Code to change the Rate on selecting Product. (jQuery)

//Values and Inputs
$(document).on('change', '.Item', function() {
    var Item = $('.Item').closest('.Item').val();
    $.ajax({
        type: 'GET',
        url: 'AjaxPrice.php',
        data: { Item: Item },
        success: function(response) {
            $('.Rate').val(response);
        }
    });
});

Code of Predefined Table

      <input type="text" class="form-control Item" name="Item" id="Item" placeholder="Nombre del producto" required autocomplete="off">

      <input type="number" name="QTV" min="1" name="QTV" id="QTV" class="form-control text-right" placeholder="00" required>

      <input step="2" type="number" class="form-control text-right Rate" min="1" id="Rate" placeholder="0.00" readonly>

      <input step="any" id="Disc" name="Disc" type="number" min="0" name="" class="form-control text-right" placeholder="00">

      <input type="text" name="SubTotal" class="form-control text-right" id="Total" placeholder="Total" readonly>

      <button type="button" class="btn btn-danger DelRow">Delete</button>

Code to Add new Item

$('#AddNewItem').click(function() { $('.TableBody').append(`

    <input type="text" class="form-control Item" name="Item" id="Item" placeholder="Nombre del producto" required autocomplete="off">

    <input type="number" name="QTV" min="1" name="QTV" id="QTV" class="form-control text-right" placeholder="00" required>

    <input step="2" type="number" class="form-control text-right Rate" min="1" id="Rate" placeholder="0.00" readonly>

    <input step="any" id="Disc" name="Disc" type="number" min="0" name="" class="form-control text-right" placeholder="00">

    <input type="text" name="SubTotal" class="form-control text-right" id="Total" placeholder="Total" readonly>

    <button type="button" class="btn btn-danger DelRow">Delete</button>

`); });

Any help would be highly appreciated.
Comment: Yea, so, there's no element with the className `Rate`. Maybe you meant to select by ID instead? Maybe the target element needs to be given said class?
Comment: Because you need to select the rate input in the row..... (and ids need to be unique)
Comment: @epascarello Yeah now i'm using unique Classes for each new Item(row)
Answer: Select the input that is in the row. You are selecting the first input
$(document).on('change', '.Item', function() {
    var item = this.value // get the item that was changed
    var row = $(this).closest("tr")  // get the table row the item is in
    var rate = row.find(".rate") // find the rate input in the row
    $.ajax({
        type: 'GET',
        url: 'AjaxPrice.php',
        data: { Item: Item },
        success: function(response) {
          rate.val(response);
        }
    });
});

Comment: Thank you @epascarello Your answer is correct but that's not what I was asking for. I just wanted to alter the Price of the specific row on Product change
Answer: Your predefined table and the dynamic table-row are using the same classes and id's.
So, if you call $('.Rate').val(response);, it will change all elements owning the class ".Rate".
One possible solution could be adding a increment number, like so:
$('#AddNewItem').click(function() {

var i = parseInt($('.TableBody').length)+1;

$('.TableBody').append('
.
.

    <input step="2" type="number" class="form-control text-right Rate_'+i+'" min="1" id="Rate" placeholder="0.00" readonly>

.
.
');

});
Of course you're free to use that on an other classname.
To grab that number to use it after your ajax-call is finisyou could add that number as data-attribute to the ".Item" element:
$('#AddNewItem').click(function() {

var i = parseInt($('.TableBody').length)+1;

$('.TableBody').append('
.
.

    <input type="text" data-loop="'+i+'" class="form-control Item" name="Item" id="Item" placeholder="Nombre del producto" required autocomplete="off">

.
.

    <input step="2" type="number" class="form-control text-right Rate_'+i+'" min="1" id="Rate" placeholder="0.00" readonly>

.
.
');

});
And your ajax function could be:
$(document).on('change', '.Item', function() {
var Item = $('.Item').closest('.Item').val();
var loop_id = $(this).data('loop');
$.ajax({
    type: 'GET',
    url: 'AjaxPrice.php',
    data: { Item: Item },
    success: function(response) {
        $('.Rate_'+loop_id).val(response);
    }
});

});
-> Not sure if loop_id is available in success-scope, maybe you have to pass it with the ajax call and recieve it with response. By thisd way, i would recommend you to use JSON as dataType. Like so:
$(document).on('change', '.Item', function() {
var Item = $('.Item').closest('.Item').val();
var loop_id = $(this).data('loop');
$.ajax({
    type: 'GET',
    url: 'AjaxPrice.php',
    dataType: 'JSON',
    data: { Item: Item, loop_id:loop_id },
    success: function(response) {
        $('.Rate_'+response.loop_id).val(response.html);
    }
});

});
Hope it helps you a little out.
Comment: Not tested, by the way. If you find a typo, you may keep it :-)
Comment: Thank you, The concept was nearly same and that helped me. Thanks a lot for your time
Comment: `var Item = $('.Item').closest('.Item').val();` is wrong.... not sure how it works unless there is only one Item


How to render Views anchors with `title` attribute?

Question: By default the Views module doesn't put title attributes on anchors as it only puts them on anything that has an alt attribute.
Seeing as you're not likely to have an alt attribute on a standard anchor. Could someone please advise what you need to do in order to render Views anchors with title attribute?
Answer: You can do this:
In your Content: Title expand Rewrite Results and check Rewrite the output of this field
In the Text field enter: [title]
This will create your anchor jump point.
Next you can add a block and repeat the same process replacing Text field with [title]
Answer: You can supply your own 'alt' attribute (and thus 'title' when rendered) by outputting your field as a link. Choose "Output this field as a link", and enter the path, and alt text from the available tokens. Sometimes you might have to define a separate 'path' field for use in the 'link path' value. You might also have to experiment with the "Use absolute path" setting to get the href right.


How can I prevent a custom block from rewriting HTML?

Question: I have a self-contained widget written by a third party that consists of HTML, JS, and CSS. I've dumped it into a custom block with Full HTML (and verified the Full HTML settings are loose enough that they shouldn't conflict with the markup). Also, I'm using CKEditor. When I save the custom block, it turns
 into

 so that the widget doesn't even get an opportunity to render.
Is there a workaround for this? Is my only alternative to create a custom module?
Answer: Try going to Admin menu > Configuration > Content authoring > Text formats and editors then edit yours (E.g. "basic html")
Down towards the bottom you should see an option: Correct faulty and chopped off HTML - uncheck that option and save.
Not sure why a widget would expect an un-closed
 tag though.
Comment: That option is unchecked. There is a close div,  it's just after all the HTML/JS/CSS. But when the editor rewrites it, it removes the  at the end and sticks it at the top.
Answer: If you want to avoid creating a custom plugin, then I would try creating a new Text Format and remove all processing options and offer no WYSIWYG.
However, this block of code sounds problematic, and the WYSIWYG is not really intended to host full applications. I think you would end up with a more reliable, more secure, higher quality product if you created a custom block and integrated the JS and CSS as libraries. This is more in line with the way that Drupal is intended to operate and allows the markup and JS/CSS assets to properly participate in sanitization, caching, aggregation, etc...
Comment: I did try creating a custom text format which had no editor and didn't do anything to the HTML. The result wouldn't render the HTML. I'll look into creating a custom block. I just thought this could be so easy.


Terminal command line - Dungas-iPhone

Question: Recently the following has appeared on my MacOS Terminal. I'm relatively new to using Terminal and have installed various bits of software lately, but cannot find any reference to this anywhere. My name is not Dungas, my iPhone isn't called Dungas and i'm pretty confused by this. Any ideas anyone?

Last login: Thu Apr 30 13:59:40 on ttys000
  brettmoreton@Dungas-iPhone ~ %
Answer: Maybe you executed some script or tried to run some command from any tutorial that caused this.
You can revert it back. Change newname to whatever value you want and you are good to go.
sudo scutil --set ComputerName "newname"
sudo scutil --set LocalHostName "newname"
sudo scutil --set HostName "newname"

Comment: Hi, thanks for the suggestion but it hasn't worked :-(

Terminal command line - Dungas-iPhone


PHP $_GET not get value of RewriteRule in case of "index"

Question: I'm having a problem. I'm trying to get this url:
mySite.com/index.php?url=category/value1/value2/value3

From this:
MySite.com/category/value1/value2/value3

I have this .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]
</IfModule>

everything is working fine if category is everything but "index", so if I put the URL:
MySite.com/content/tv/color

The array $_GET is equal to:
Array
(
    [url] => content/tv/color/
)

but when i put:
MySite.com/index/option1/option2

the array is empty
Array()

I checked my apache.conf file and I can't see the problem.
<VirtualHost *:80>
        ServerAdmin email@example.com

        DocumentRoot /home/htdocs
        <Directory />
                AllowOverride all
        </Directory>
        <Directory /home/htdocs>
                #>>>>>HERE I HAVE MY TEST APP <<<<<<<<
                DirectoryIndex index.html index.php
                Options FollowSymLinks MultiViews
                RewriteEngine ON
                AllowOverride all
                Order allow,deny
                allow from all
        </Directory>
        Alias /simplesaml /var/simplesamlphp/www
        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog ${APACHE_LOG_DIR}/access.log combined

    Alias /doc/ "/usr/share/doc/"
    <Directory "/usr/share/doc/">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.0/255.0.0.0 ::1/128
    </Directory>

</VirtualHost>

Comment: You're certain `index` doesn't exist as a folder? Also you don't need the `$` in your regexp
Comment: Yes, it does't exist as a folder, thanks for the $ advice.
Comment: @Mikeroguez: so what about my answer?
Comment: @zerkms I have not tried it, but it sounds very logical, that was the default settings, just moved the AllowOverride, I'll try in a moment and vote your answer.
Answer: You need to turn off MultiViews option by prepending minus sign - before it like -MultiViews.
Actually I'm not sure why you turned it on explicitly. Was it just a config copy-paste?
Also if you don't need FollowSymLinks (I'm sure you don't need it) - turn it off as well.


Statistical analysis of amino acid profiles, quantitative vs qualitative methods?

Question: I work on a study comparing the amino acid profile of 5 sample groups with 3 replicates in each group. This is how the data looks like except that there are 17 columns (one for each amino acid) in total. The values represent the measured level (in micromole per gram sample, not percentage of total) of individual amino acid in each sample.
Group Asp   Asn   Glu   Gln   His  ...
  A    13    8     9    15    12
  A    5     7     6    11     1
  A    10   15     1    14    13
  B    13   10    11     5     7
  B    12    5    10     9     4
  B    6     2    13     1     5
  C    9     4     3    15     1
  C    2     4    10     1     5
  C    5     9     8     7    14
  D    5    13     2    10     6
  D    7    13     9     1     5
  D    13   12     5     8    15
  E    15    7     4     2     1
  E    1     2    15    14     8
  E    1     3     2    13     5

I used an ANOVA to compare the mean sum of total amino acids between groups, then I ran a PCA to visualize differences in profile.
I was asked by a reviewer to also analyze for significant differences in individual amino acids.
I generally find PCAs sufficient for this type of analysis. Besides, the number of samples per group is small (n = 3) and there may be correlation between the response variables (i.e. individual amino acid content) meaning the results of multiple univariate ANOVAs (for each amino acid) may be misleading (inflating type I error).
Correlation seems to be an issue for multivariate ANOVA (MANOVA) as well. In this specific case a MANOVA would be rank defficient anyway.
But there are examples of comparable data published in the scientific literature where multiple univariate ANOVAs are used to detect difference in individual amino acids between groups.
Does anyone has good arguments for or against using multiple univariate ANOVAs or other quantitative methods in such cases?
Comment: Are the values in the table in units like micromoles per sample, or are they percentages of each individual amino acid with respect to the total of all amino acids? Also, out of curiosity, why are there only 17 columns? Particularly interesting as you have separate values for Asp and Asn and for Glu and Gln, the pairs that some analytical methods can't distinguish.
Comment: Yes the values are given as individual content (like I micromole per gram sample) and not in percentage of the total. I edited the question to clarify. Each column correspond to an amino acid detected in at least one of the samples. There are some HPLC methods to distinguish Asp/Glu from Asn/Gln.
Answer: Your approach, starting with ANOVA to compare total amino acid content among groups and then using PCA to illustrate underlying differences in composition, seems sound. Your reluctance to just go forward with 17 univariate ANOVAs is well founded. Besides not accounting for the possibility of correlations among the response variables, the simple fact of performing 17 univariate ANOVAs will require substantial correction for multiple comparisons.
The simplest way forward might be to just do the requested 17 univariate ANOVAs anyway (after all, if the reviewer wants to know the results then other readers probably would, too). You do this, however, while highlighting the difficulties involved in interpreting the results. That would get you quickly beyond the issue raised by the reviewer, and could even give you the opportunity to demonstrate the superiority of your PCA-based approach.
For MANOVA, it's not immediately clear to me why you think that it would be rank deficient, unless the analyses were done on percentages rather than raw values. (Maybe I just haven't thought that through enough.) The literature on handling necessarily rank-deficient compositional data and associated threads on CrossValidated could provide guidance.
You could consider multivariate partial least squares (or "projection to latent structures"), a technique frequently used in chemometrics, which I think in your case would be closely related to your PCA approach.
Note that the problem of having multiple correlated response variables is even more dramatic in gene-expression studies, which can have on the order of 20,000 response variables with only a handful of different conditions and replicates. Although it might be overkill for your application, you might consider exploring how information is pooled among observations and how the multiple comparisons problem is dealt with by packages like  limma for differential expression analysis.
Comment: @Drosof your Bonferroni p value is OK, but that correction is extremely conservative. The Holm method would be better for controlling family-wise error rate. You could consider controlling false-discovery rate instead (Benjamini-Hochberg), as used in large-scale gene-expression studies. For dealing with your reviewer, I would recommend placing the results of the 17 individual ANOVAs and discussion of the difficulties in interpreting the results in the paper itself or in a supplement; that way you address the reviewer's concern without a back-and-forth argument.
Comment: I guess running `manova()` on 17 response variables with only 3 values per group is the reason why the model is rank deficient. I also ran a PLSR on this data.
Comment: In the case I would perform the multiple univariate ANOVAs, I assume the threshold _p_-value from the Bonferroni correction would be 0.05/17 = 0,00294. Is it the treshold one would look at when running the multiple comparisons using multiple `pairwise.t.test(aa, Group, p.adjust.method="bonferroni")`? As you mention it still doesn't account for possible correlations so perhaps I should just argue for not using this method.
Comment: Thanks for your thourough answer and comments. What about the [Benjamini-Yekutieli](https://projecteuclid.org/download/pdf_1/euclid.aos/1013699998) correction ? It accounts for correlations among response variables. Following [that post](https://stats.stackexchange.com/questions/63441/what-are-the-practical-differences-between-the-benjamini-hochberg-1995-and-t), I'm not sure `"BY"` method is appropriate in this case though.
Comment: @Drosof I don't have any experience with the B-Y correction. My understanding is that gene-expression analysis uses B-H despite the inherent correlations among expression of 10,000 to 20,000 genes. The R `p.adjust()` function allows for either.


GC Lagging app when scrolling my custom component

Question: I had to create a custom component (I could not use gridview or dataTable), which is a table with 6 columns and X rows (no images). The image below shows it working:

The problem occurs when I scroll up or down on that table. Sometimes it scrolls correctly, in others it takes a lag. In the logcat, I realized that the lag occurs when the GC kicks in.

I was looking for a way to optimize my component, however I am new to Java. I read about optimizing Views, and reuse of objects width getView. Below is my current getView code:
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {

                if (null == this.parent)
                    this.parent = (ListViewOT) parent;

                if (this.parent.isInEditMode()) {
                    super.getView(position, convertView, parent);
                }

                mActivity = (MainActivity) parent.getContext();
                this.c = this.getCursor();
                c.moveToPosition(position);

                if (null == convertView) {

                    view = (LinearLayout) LinearLayout.inflate(
                            this.context, R.layout.item_lvacoes, null);

                    row = (LinearLayout) view.getChildAt(1);
                    headerRow = (TableRow) this.parent.getHeader().getChildAt(0);
                    for (int j = 0; j < this.c.getColumnCount(); j++) {
                        columnName = c.getColumnName(j);

                        if (columnName.startsWith("Status")) {
                            continue;
                        }

                        headerCell = (CelulasLV) headerRow.getChildAt(j);
                        current_width = headerCell.getWidth();
                        headerCell.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);

                        cell_width = AdapterLVAcoes.CalculateTextSize(headerCell.getPaint(), c.getColumnName(j));
                        column_width = this.parent.getColumnWidthAt(j);

                        if (column_width == 0)
                            headerCell.setWidth(0);
                        else if (cell_width <= column_width)
                        {
                            if (current_width != column_width)
                                headerCell.setWidth(column_width);
                        } else
                        {
                            this.changedWidth = true;
                            this.parent.setColumnWidthAt(j, cell_width);
                        }

                        column = new CelulasLV(this.context,(ListViewOT) parent);
                        if (columnName.equals("No"))
                            column.setText("" + (position + 1));
                        else
                            column.setText(c.getString(j));

                        column.setIndexColumn(j);
                        column.setIndexRow(position);
                        column.setEPC(c.getString(c.getColumnIndex("_id")));

                        int status = c.getInt(c.getColumnIndex("Status"));
                        if (status == 0)
                            column.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.cell));
                        else if (status == 1)
                            column.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.cellachado));
                        else if (status == 2)
                            column.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.cellextraviado));
                        else if (status == 3)
                            column.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.cellinexistente));
                        else if (status == 4)
                            column.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.cellpreachado));

                        activity.registerForContextMenu(column);
                        cell_width = AdapterLVAcoes.CalculateTextSize(column.getPaint(), column.getText().toString());
                        column_width = this.parent.getColumnWidthAt(j);

                        if (column_width == 0)
                            column.setWidth(0);
                        else if (cell_width <= column_width)
                            column.setWidth(column_width);
                        else
                        {
                            this.changedWidth = true;
                            this.parent.setColumnWidthAt(j, cell_width);
                        }
                        row.addView(column);
                    }
                    return view;
                }
                else
                {
                    view = (LinearLayout) convertView;
                    row = (LinearLayout) view.getChildAt(1);
                    int i = 0;
                    headerRow = (TableRow) this.parent.getHeader().getChildAt(0);
                    {
                        for (int j = 0; j < this.c.getColumnCount(); j++)
                        {
                            columnName = c.getColumnName(j);

                            if (columnName.startsWith("Status")) {
                                continue;
                            }

                            headerCell = (CelulasLV) headerRow.getChildAt(j);
                            current_width = headerCell.getWidth();
                            headerCell.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
                            cell_width = AdapterLVAcoes.CalculateTextSize(headerCell.getPaint(), c.getColumnName(j));
                            column_width = this.parent.getColumnWidthAt(j);

                            if (column_width == 0)
                                headerCell.setWidth(0);
                            else if (cell_width <= column_width)
                                if (current_width != column_width)
                                    headerCell.setWidth(column_width);
                            else
                            {
                                this.changedWidth = true;
                                this.parent.setColumnWidthAt(j, cell_width);
                            }
                            column = (CelulasLV) row.getChildAt(i);

                            if (columnName.equals("No"))
                                column.setText("" + (position + 1));
                            else
                                column.setText(c.getString(j));

                            column.setIndexColumn(j);
                            column.setIndexRow(position);
                            column.setRealIndex(c.getLong(c.getColumnIndex("No")));
                            column.setEPC(c.getString(c.getColumnIndex("_id")));

                            status = c.getInt(c.getColumnIndex("Status"));
                            if (status == 0)
                                column.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.cell));
                            else if (status == 1)
                                column.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.cellachado));
                            else if (status == 2)
                                column.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.cellextraviado));
                            else if (status == 3)
                                column.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.cellinexistente));
                            else if (status == 4)
                                column.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.cellpreachado));

                            activity.registerForContextMenu(column);
                            column.setOnClickListener(this.cellClick);
                            cell_width = AdapterLVAcoes.CalculateTextSize(column.getPaint(), column.getText().toString());
                            column_width = this.parent.getColumnWidthAt(j);

                            if (column_width == 0)
                                column.setWidth(0);
                            else if (cell_width <= column_width)
                                column.setWidth(column_width);
                            else
                            {
                                this.changedWidth = true;
                                this.parent.setColumnWidthAt(j, cell_width);
                            }
                            i++;
                        }
                    }
                    return convertView;
                }
            }

It basically redraws the columns according to the widest column found.
How to optimize my component, so these lags do not occur when the GC into action?
Thanks in advance and sorry for bad english.
Comment: (1) Why can't you use a `ListView` for this? (2) I don't think the GC is slowing you down I think the use of a scrolling table view is. If you can use a `ListView` or some other optimized structure that recycles views it will likely be much smoother.
Answer: Dude, I'm cringing just looking at this and your other post.  Lets try to work with what you have. You have some pretty complicated algorithms in determining width but before we address that, we can definitely speed things up.  I will paint a higher overview of what you should do. You'll have to translate that into the code as this is a complex problem.
You'll need to create a cache which given a position and a column # will store the measured width. Always check your cache first and only measure if there's nothing found.  The getView() method can be invoked 3-4 times per position.  So this should yield a huge improvement.
An alternative to this, if you have a lot of dynamic text or repetitive text...you can create a cache based on text instead.  So for a given String, you cache what the measured width is.
Assuming you are only ever showing text in the columns, there's an alternative measuring solution which may be quicker. Just use the TextView's getPaint().measureText(String) method.  It'll return the width of the text in pixels.  You'll probably need to throw on some fluff like an additional 4-8 dp but that may be quicker then what you are doing.
Cache Example:
In the constructor of the adapter, do something like:
Map<String, Float> mWidthCache = new HashMap<String, Float>();

Then within the for loop within getView() do something like:
String key = String.valueOf(position) + c.getColumnName(j);
Float measuredWidth = mWidthCache.get(key);
if (width == null) {
    //Calculate measuredWidth
    mWidthCache.put(key, measuredWidth); //Then place back in cache
}

//Adjust width of layout based on measureWidth

Comment: Hello Jay. I have no idea how to cache the position. Can you help me a little bit more?
Comment: Updated with simple cache example
Comment: OK. This solution seems to be correct. But I am not able to implement it. As I said before, I'm new to Android, and the function shown is much more complex than your example. But thank you anyway...
Answer: I believe GC kicks in a lot because you're churning through too much memory.
Instead of recreating your bitmaps every time you call getView (...) you need to cache them - create them once and store them in memory, then just reuse them instead of reloading them.
Create new function:
private Drawable getMyBackgroundDrawable (int status)
{
    if (status == 0)
        return a;
    else if (status == 1)
        return b;
    else if (status == 2)
        return c;
    else if (status == 3)
        return d;
    else if (status == 4)
        return e;
    return null;
}

You'll need to define the cached drawables in your class body:
Drawable a;
Drawable b;
Drawable c;
Drawable d;
Drawable e;

And somewhere in this class load the drawables (in the constructor or in onFinishInflate is usually my choice):
a = context.getResources().getDrawable(R.drawable.cell);
b = context.getResources().getDrawable(R.drawable.cellachado);
c = context.getResources().getDrawable(R.drawable.cellextraviado);
d = context.getResources().getDrawable(R.drawable.cellinexistente);
e = context.getResources().getDrawable(R.drawable.cellpreachado);

Remove these (you have them twice):
if (status == 0)
    column.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.cell));
else if (status == 1)
    column.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.cellachado));
else if (status == 2)
    column.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.cellextraviado));
else if (status == 3)
    column.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.cellinexistente));
else if (status == 4)
   column.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.cellpreachado));

Replace them with:
column.setBackgroundDrawable(getMyBackgroundDrawable (status));

Please note that I haven't compiled or tested any of this code, so you may need to fix some syntax errors I missed.
Comment: Hello Kibler88. Thank you for the help. I did what you recommended, but the result still the same. Is there anything else I can do?


How to change order of custom module theme output?

Question: I need to add some top links and sub top links . I altered hook_theme function and created two templates for these
code is like this-
function acts_theme() {
    return array(
            'acts_top_links' => array(
                    'variables' => array(
                            'links' => NULL,
                            'activelink' => NULL,
                        ),
                    'template' => 'acts-topmenu',
            ),
            'acts_submenu_links' => array(
                    'variables' => array(
                            'links' => NULL,
                            'activelink' => NULL,
                        ),
                    'template' => 'acts-submenu',
            ),
    );
}
function template_preprocess_acts_top_links(&$variables){
    $toplinks=$variables['links'];
    $activelink=$variables['activelink'];
    $variables['toplinks']=$toplinks;
    $variables['activelink']=$activelink;

}
function template_preprocess_acts_submenu_links(&$variables){
    $toplinks=$variables['links'];
    $activelink=$variables['activelink'];
    $variables['sublinks']=$toplinks;
    $variables['activelink']=$activelink;
}

Now I am using these theme output as-
function acts_display(){
    $build['acts_toplinks'] = array(
            '#theme' => 'acts_top_links',
            '#links' => $toplinks,
            '#activelink'=>'Company Law',
    );
    $build['acts_sublinks'] = array(
            '#theme' => 'acts_submenu_links',
            '#links' => $submenulinks,
            '#activelink'=>'/companylaw/acts',
    );

    $build['acts_table_rows'] = array(
            '#theme' => 'table',
            '#rows' => $rows,
            '#empty' => t('Currently there are no active content'),
    );
return $build;
}

I expect output as -
first to show- top links, then sub menu links and then table but output exactly reverse-
first I get table,then sub menu links and then top links
How can I achieve this?
Comment: Did you try just adding `#weight` to the arrays in `$build()`?
Comment: Yes, this worked with #weight, Post it as answer, will mark as an correct answer
Answer: If you add the #weight property to the arrays in $build() then that will allow you to order them e.g.:
$build['acts_table_rows'] = array(
        '#theme' => 'table',
        '#rows' => $rows,
        '#empty' => t('Currently there are no active content'),
        '#weight' => 99,
);


Is the ball out of bounds when hitting the referee?

Question: In basketball, if the ball goes through the hands of a player and hits the referee (who is out of bounds) and comes back in the court, is it a live ball, or out on last player to touch the ball?
Comment: @Rt88 I've edited this question to explicitly specify the sport of basketball.  If you were referring to a different sport, please edit the question.
Answer: If the referee is standing out of bounds, then the ball is out of bounds and dead as soon as it hits the referee.  It is out on the last player to touch the ball.
From NCAA Men's Basketball 2013-14 and 2014-15 Rules, Rule 7 (Out of Bounds and the Throw-in), Section 1 (Out of Bounds - Player, Ball):

Art. 2. The ball shall be out of bounds when it touches a player who is out of
  bounds, any other person, the floor or any object on or outside a boundary, the
  supports or back of the backboard, or the ceiling or overhead equipment.

Section 2 (Ball Caused To Go Out of Bounds):

Art. 1. The last player to touch the ball before the ball goes out of bounds caused
  the ball to go out of bounds, provided that the ball is out of bounds because it
  touched something other than a player who is out of bounds.
Comment: This is correct for NFHS, NCAA, and NBA. A ref inbounds is part of the (inbounds) court. A ref out of bounds is out of bounds. There are a few examples of advantages/disadvantages gained/lost from refs getting in the way of balls.


Does the image format (png, jpg, gif) affect how an image recognition neural net is trained?

Question: I'm aware that there's been lots of advances with regards to image recognition, image classification, etc with deep, convolutional neural nets.
But if I train a net on, say, PNG images, will it only work for images so encoded? What other image properties affect this? (alpha channel, interlacing, resolution, etc?)
Comment: I don't have enough experience with the statistics of images to give a confident answer, but I would expect that different models use completely different schemes to code images into features, some of which will be affected by lossy JPEG compression, alpha channels, etc., and some of which won't, with the details being model-specific. I know that there exist both models that treat each pixel as a feature and models that carve images into regions and use region properties as features.
Comment: what happens when you trained a model using PNG images and tested it for jpeg images. PNG has 4 color channels right? while jpeg only has 3. will it have a big effect with regards to its accuracy in classification.
Answer: Short answer is NO.
The format in which the image is encoded has to do with its quality. Neural networks are essentially mathematical models that perform lots and lots of operations (matrix multiplications, element-wise additions and mapping functions). A neural network sees a Tensor as its input  (i.e. a multi-dimensional array). It's shape usually is 4-D (number of images per batch, image height, image width, number of channels).
Different image formats (especially lossy ones) may produce different input arrays but strictly speaking neural nets see arrays in their input, and NOT images.
Answer: While Djib2011 answer is correct, I understand your question as more focused on how the image quality/properties affect neural network learning in general.
There is only little research in this topic (afaik), but there might be more research on it in the future. I only found this article on it.
The problem at the moment is, that this is more a problem appearing in practical applications and less in an academic research field. I remember one current podcast where researchers observed that even the camera that was used to take a picture could have a big effect.
Comment: Could you point me to the podcast please?
Comment: It's a one hour episode of "talking machines", where they have a discussion with a researcher practicing machine learning in Africa (ca. middle to end) iTunes link: https://itunes.apple.com/de/podcast/talking-machines/id955198749?mt=2&i=1000392591423
Answer: This is a riff on the first answer from Djib2011.  The short answer has to be no.  Longer - Firstly photos are always encoded as a tensor as follows.  An image is a number of pixels.  If the photo is considered to have m rows and n columns, each pixel is specified by it's row and column location, that is by the pair (m,n).  In particular there are m*n pixels which is very large even for 'small' photos.   Each pixel of the photo is encoded by a number between zero and one (blackness intensity)  if the photo is black and white.  It is encoded by three numbers (RGB intensities) if the photo is color.  So one winds up with a tensor that is either a 1xmxn or a 3xmxn. Image recognition is done through CNN's which, taking advantage of the fact that photos don't change that much from pixel to pixel, compress the data via filters and pooling.  So the point is that CNN's work by compressing the incredibly large numbers of data points (or features) of a photo into a smaller number of values. So whatever format you start with, CNN's start off by further compressing the data of the photo.  Hence the per se  independence from the size of the  representation of the photo.
However,  a CNN will demand that all images being run through it are all of the same size.  So there is that dependency that will change depending on how the image is saved.  In addition, to the extent that different file formats of the same  size produce different values for their tensors, one cannot use the same CNN model to identify photos stored by different methods.
Answer: While changes in camera or image compression after training can be severe, if it is the same, the problem is much less. Of course with more noisy images the performance is less, but I never heard that standard JPEG compression would make a big difference. But it will depend on the application.
If you change things after training, it very much depends. E.g. for some networks changing the resolution doesn't work at all. For others its possible. Its very network specific. In general any change (even lens, lighting, background, etc) needs to be evaluated and needs to be included in the training from a theoretical perspective.
In general its not a good idea to have training data that is qualitatively different. If you want to classify PNG and JPG, then it would be best to also train on both. The same for other image properties.
A CNN cannot extrapolate, it usually just works within the training set space. Other models can do that, like rule based models.


Algorithm for grouping users by their quiz answers

Question: Let's say I have a cluster of users that I want to group to N groups by the similarities of their quiz answers.
Questions have predefined answers with value of a letter (a, b, c, etc.).
My criteria is to split users into groups based on how similar their answers values are.
Is there an algorithm for that?
Comment: Could you be more specific? What type of questions are these, what criteria are you looking for separating them into groups, etc.
Comment: Updated my post.
Answer: You might be able to get better answers if you post in stats.stackexchange or datascience.stackexchange.
Anyway, here's a very simple method to get you started:
Assume you have $m$-questions and $n$ users which you want to cluster into $N$ groups.
For user $i$, let $x_i = (x_{i1},\dotsc,x_{i2}) \in \{a,b,c,d\}^m$ be the vector corresponding to the answers he gave, i.e. $x_{ik}$ is the answer he gave to the $k$-th question.
You now essentially want to assign a distance between two users. One way to do so is the Hamming distance:
$$d(i,j) = \sum_{k=1}^m \mathbf{1}_{\{x_{ik} \neq x_{jk}\}} $$
Once you have a distance matrix $(d(i,j))_{1\leq i,j\leq n}$ there are many methods you can use to cluster the users, for example you could use
   Hierarchical clustering.


Usar querySelectorAll em um option quando existe mais de um Select

Question: Bom dia galera, já de antemão tenham todos um ótimo feriado.
Estou com uma função em javascript que faz a contagem de uma lista assim:
let counting = document.querySelectorAll("option:checked");

No começo achei que tinha funcionado, mas via que quando limpava a lista, ainda na contagem sobravam 2 itens, que descobri ser de outros elementos <select> que existem na mesma página.
Tem como filtrar o querySelectorAll, por exemplo apenas contar as options, o select tenha uma id específica por exemplo?
Answer: No final descobri que posso passar 2 parâmetros no querySelectorAll então agora minha variável ficou assim:
let counting = document.querySelectorAll("#selection option:checked");

Fica aí a resposta se alguém procurar pela mesma situação =]


Convert datetime in MySQL

Question: How can we convert the time in AM/PM to 24-hrs format in MySQL? Example 2:50 PM should be converted to 14:50. Please help me to convert this.
Answer: use %p with STR_TO_DATE()
SELECT STR_TO_DATE(  '2:50 pm',  '%h:%i %p' ) // will return 14:50:00

Convert datetime in MySQL


How many ways are to arrange the letters in MISSISSIPPI so that AT LEAST ONE of the following properties holds:

Question: continuing the question from:
so that AT LEAST ONE of the following properties holds: the $4$ I's are all consecutive or the $4$ S's are all consecutive or the $2$ P's are consecutive?
The answer is supposed to be $$2 \cdot \frac{8!}{4!2!} + \frac{10!}{4!4!} - \left[2 \cdot \frac{7!}{4!}+ \frac{5!}{2!}\right]+ 4!$$
Can someone explain where is each part from?
$2 \cdot \frac{8!}{4!2!} \to 4$ I's and it's multiplied by $2$ because counting in pairs?
$\frac{10!}{4!4!} \to$ counting the M, but I'm not sure why it is $10$ factorial
$2 \cdot \frac{7!}{4!} + \frac{5!}{2!} \to$ don't understand where is the $\frac{7!}{4!}$ coming from?
$4! \to$ the $2$ P's
Comment: Please read this [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference), which explains how to typeset mathematics on this site.
Answer: Let $I$ denote the set of arrangements such that the four I's are consecutive.
Let $S$ denote the set of arrangements such that the four S's are consecutive.
Let $P$ denote the set of arrangements such that the two P's are consecutive.
With the principle of inclusion/exclusion and symmetry we find:$$|I\cup S\cup P|=2|I|+|P|-|I\cap S|-2|I\cap P|+|I\cap S\cap P|$$
$|I|$ equals the number of arrangements of the letters MISSSSPP.
$|P|$ equals the number of arrangements of the letters MIIIISSSSP.
$|I\cap S|$ equals the number of arrangements of the letters MISPP.
$|I\cap P|$ equals the number of arrangements of the letters MISSSSP.
$|I\cap S\cap P|$ equals the number of arrangements of the letters MISP.
So we end up with:$$|I\cup S\cup P|=2\times\frac{8!}{1!1!4!2!}+\frac{10!}{1!4!4!1!}-\frac{5!}{1!1!1!2!}-2\times\frac{7!}{1!1!4!1!}+\frac{4!}{1!1!1!1!}$$
Answer: The idea here is to treat a block of consecutive identical letters as a single object.
Let's adopt the notation used by drhab.
Let $I$ denote the set of permutations in which the four I's are consecutive.
Let $S$ denote the set of permutations in which the four S's are consecutive.
Let $P$ denote the set of permutations in which the two P's are consecutive.
The set of arrangements of the word MISSISSIPPI in which at least one of the properties the four I's are consecutive, the four S's are consecutive, or the two P's are consecutive is $I \cup S \cup P$.  By the Inclusion-Exclusion Principle, the number of such arrangements is given by the formula
$$|I \cup S \cup P| = |I| + |S| + |P| - |I \cap S| - |I \cap P| - |S \cap P| + |I \cap S \cap P|$$
$|I|$:  We treat the block of four consecutive I's as a single object.  Therefore, we have eight objects to arrange: IIII, M, S, S, S, S, P, P.  We can fill four of the eight positions with S's in $\binom{8}{4}$ ways and two of the remaining four positions with P's in $\binom{4}{2}$ ways.  There are $2!$ ways to fill the remaining two positions with the distinct objects IIII and M.  Hence,
$$|I| = \binom{8}{4}\binom{4}{2}2! = \frac{8!}{4!4!} \cdot \frac{4!}{2!2!} \cdot 2! = \frac{8!}{4!2!}$$
The factor of $4!$ in the denominator represents the number of ways the S's can be permuted among themselves without producing an arrangement distinguishable from the given arrangement.  The factor of $2!$ in the denominator represents the number of ways the P's can be permuted among themselves without producing an arrangement distinguishable from the given arrangement.
$|S|$:  We treat the block of four consecutive S's as a single object.  Again, we have eight objects to arrange:  SSSS, M, I, I, I, I, P, P.  By symmetry, there are
$$\binom{8}{4}\binom{4}{2}2! = \frac{8!}{4!2!}$$
such arrangements.
$|P|$:  We treat the block of two consecutive P's as a single object.  This time we have ten objects to arrange: PP, M, I, I, I, I, S, S, S, S.  We can fill four of the ten positions with I's in $\binom{10}{4}$ ways and four of the remaining six positions with S's in $\binom{6}{4}$ ways.  The remaining two positions can be filled with the distinct objects M and PP in $2!$ ways.  Hence, there are
$$\binom{10}{4}\binom{6}{4}2! = \frac{10!}{4!4!}$$
such arrangements.
$|I \cap S|$:  We treat the block of four consecutive I's as a single object and the block of four consecutive S's as a single object.  Therefore, we have five objects to arrange:  IIII, SSSS, M, P, P.  We can choose two of the five positions for the P's in $\binom{5}{2}$ ways.  The remaining three distinct objects can be arranged in the remaining three positions in $3!$ ways.  Hence, there are
$$\binom{5}{2}3! = \frac{5!}{2!3!} \cdot 3! = \frac{5!}{2!}$$
such arrangements.
$|I \cap P|$:  We treat the block of four consecutive I's as a single object and the block of two consecutive P's as a single object.  Therefore, we have seven objects to arrange:  IIII, PP, M, S, S, S, S.  We can choose four of the seven positions for the S's in $\binom{7}{4}$ ways.  The remaining three distinct objects can be arranged in the remaining three positions in $3!$ ways.  Hence, there are
$$\binom{7}{4}3! = \frac{7!}{3!4!} \cdot 3! = \frac{7!}{4!}$$
such arrangements.
$|S \cap P|$:  We treat the block of four consecutive S's as a single object and the block of two consecutive P's as a single object.  Therefore, we have seven objects to arrange:  SSSS, PP, M, I, I, I, I.  By symmetry, there are
$$\binom{7}{4}3! = \frac{7!}{4!}$$
such arrangements.
$|I \cap S \cap P|$:  We treat the block of four consecutive I's as a single object, the block of four consecutive S's as a single object, and the block of two consecutive P's as a single object.  Therefore, we have four objects to arrange:  IIII, SSSS, PP, M.  Since the four objects are distinct, they can be arranged in $4!$ ways.
Hence, by the Inclusion-Exclusion Principle,
\begin{align*}
|I \cup S \cup P| & = |I| + |S| + |P| - |I \cap S| - |I \cap P| - |S \cap P| + |I \cap S \cap P|\\
 & = \frac{8!}{4!2!} + \frac{8!}{4!2!} + \frac{10!}{4!4!} - \frac{5!}{2!} - \frac{7!}{4!} - \frac{7!}{4!} + 4!\\
 & = 2 \cdot \frac{8!}{4!2!} + \frac{10!}{4!4!} - \frac{5!}{2!} - 2 \cdot \frac{7!}{4!} + 4!
\end{align*}
Note that the factors of $2$ are due to symmetry:  the word MISSISSIPPI has four S's and four I's, so $|I| = |S|$ and $|I \cap P| = |S \cap P|$.
Answer: Well, MISSISSIPPI is word of type $1^12^43^44^2$ (M occurs 1-time, I 4-times, S 4-times, P 2-times) so that the number of words that can be formed by these letters is the multinomial coefficient (length 11)
$${11 \choose 1,4,4,2}.$$
Four consecutive I's are reached if you consider the number of words that can be formed by MSSSSPP, which has type $1^12^43^2$, i.e.,
$${7\choose 1,4,2}.$$
Then the four I's can be placed at any position (i.e., multiply by 7(length)+1). Hope it helps!
Comment: I get the first part of your explanation, but don't understand the second part. Are you explaining where the (8!/4!2!) is coming from or (7!/4!)?


Karlin-Rubin theorem: relationship between test statistic having the MLR property vs being sufficient

Question: Let's suppose we are trying to compare two hypotheses for a single parameter $\theta$. The null hypothesis $H_0$ is that $\theta = \theta_0$, and the alternative is that $\theta ≥ \theta_0$.
The Karlin-Rubin theorem, as I learned it, tells us that if there is such a statistic $T(X)$ which has the monotone likelihood ratio (MLR) property, meaning that the function
$$
\frac{P\left(T(X)|\theta_1\right)}{P\left(T(X)|\theta_0\right)}
$$
is monotonically non-decreasing in $T$, that we can obtain a UMP test by thresholding samples based on the value of $T(X)$.
Question: what is the relationship between $T(X)$ being MLR and $T(X)$ being a sufficient statistic?

Is it required for the Karlin-Rubin theorem that $T(X)$ also be sufficient, or just MLR?
Are there any implications regarding being MLR and being sufficient?

Do we have MLR $\to$ sufficient and/or sufficient $\to$ MLR?

What about regarding being MLR and being minimal sufficient?

Do we have minimal sufficient $\to$ MLR and/or MLR $\to$ minimal sufficient?

Are these things related in any way at all?

In short, I see lots of posts on here talking about sufficient statistics in the setting of the Karlin-Rubin theorem, but as I'm reading about it, it seems like the MLR property is the criterion that really matters.
Comment: If $T$ were not sufficient for $\theta$ could you base the most powerful level-$\alpha$ test of any particular $\theta_0$ vs $\theta_1$ on $T$?
Answer: The Neyman–Pearson lemma states that the most powerful tests of $H_0: \theta=\theta_0$ vs $H_1: \theta=\theta_1$ are based on the likelihood ratio statistic for the full sample
$$
\frac{P\left(X|\theta_1\right)}{P\left(X|\theta_0\right)}>k
$$
Only when $T$ is sufficient for $\theta$ can you equate $P(T(X)|\theta)$ to $P(X|\theta)$; & only when the likelihood ratio is a monotonic function of a scalar $T$ can you equate the test to $T(X)> k'$.
Sufficiency & monotone likelihood ratio are distinct distributional properties, which $T$  may enjoy neither or either or both of.

$T$'s being sufficient doesn't imply a monotone likelihood ratio in $T$. Consider a single observation $x$ from a Cauchy distribution with unknown location $\mu$: $x$ is sufficient for $\mu$, but the likelihood ratio for $\mu_1$ > $\mu_0$ increases from $x-\mu_0$ to a maximum & thereafter declines.  See https://stats.stackexchange.com/a/635195/17230 for details.

A monotone likelihood ratio in $T$ doesn't imply $T$ is sufficient. Let $X_1, \ldots, X_n$ be i.i.d., with $S(X_1, \ldots, X_n)$ sufficient for the parameter $\theta$, & a monotone likelihood ratio in $S$. Now let $T=S(X_1)$: $T$ is clearly not sufficient, yet the likelihood ratio in $T$ is still monotone.

$T$ needn't be minimal sufficient. When the minimal sufficient statistic $M$ has a discrete distribution, a uniformly most powerful test may need to be based on $T(X) = M(X) + U$, where $U$ is a uniform random variable, to achieve a given significance level exactly (see e.g. How to design a randomized test?). But when $M$ has a continuous distribution, with no restrictions on its range, the requirement for $T$'s being a scalar entails minimal sufficiency. I'm not sure what can be said in general about in-between cases.

The point of the Karlin–Rubin theorem is just to state the conditions under which likelihood ratio statistics (for the full sample) order the sample space in the same way regardless of the particular parameter values stipulated in the alternative hypothesis (provided $\theta_1$ > $\theta_0$ of course), thus rendering all most powerful tests of the null equivalent.
Comment: It's that the two unrelated properties, sufficiency of $T$ & a monotone likelihood ratio in $T$, together allow you to infer that the test based on $T$ is uniformly most powerful.  I'll edit my answer to elaborate.
Comment: I am rewriting my earlier comment to correct something. I get what you are saying for the Neyman-Pearson lemma. With two simple hypotheses looking at $\theta_0$ and $\theta_1$, the likelihood ratio itself *is* minimal sufficient wrt this restricted parameter space of two points. But I don't quite get how this relates to the Karlin-Rubin theorem. With the Karlin-Rubin theorem I thought we're looking for a statistic with this "MLR property." I don't get the relationship between this property and being sufficient. Is it that any MLR statistic is always sufficient? Minimal sufficient?
Comment: OK, thanks, that makes sense. And I think it would be *minimal* sufficient, not just sufficient, right? A non-minimal sufficient statistic would partition things less coarsely than the likelihood ratio would.
Comment: Thinking about it, do we perhaps have sufficient + MLR -> minimal sufficient?