A Stranger Error of database in Intellij IDEA

Question: I got a error called java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z when I connected IDEA with mysql database.
I think my configuration is correct as below.In addition, the test is successful.
The configuration pic
And then the something stranger happened. I cannot get the any schemes from my database on the database tool window,but I can get them with Navicat. When I type SELECT * FROM message into console, that error appeared as below.
[2017-03-29 17:51:28] java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z
[2017-03-29 17:51:28]   at com.intellij.database.remote.jdbc.impl.RemoteConnectionImpl.isValid(RemoteConnectionImpl.java:108)
[2017-03-29 17:51:28]   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[2017-03-29 17:51:28]   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[2017-03-29 17:51:28]   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[2017-03-29 17:51:28]   at java.lang.reflect.Method.invoke(Method.java:497)
[2017-03-29 17:51:28]   at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
[2017-03-29 17:51:28]   at sun.rmi.transport.Transport$1.run(Transport.java:200)
[2017-03-29 17:51:28]   at sun.rmi.transport.Transport$1.run(Transport.java:197)
[2017-03-29 17:51:28]   at java.security.AccessController.doPrivileged(Native Method)
[2017-03-29 17:51:28]   at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$256(TCPTransport.java:683)
[2017-03-29 17:51:28]   at java.security.AccessController.doPrivileged(Native Method)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
[2017-03-29 17:51:28]   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[2017-03-29 17:51:28]   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[2017-03-29 17:51:28]   at java.lang.Thread.run(Thread.java:745)

I search Internet for this question via google, then I upgrade mysql driver  to even ver.5.1.40.But it doesn't work as well.
The driver pic
So, How to deal with this error? It stuck me two days.
Thanks in advance.
Answer: java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z
This will help you.
I think you have to remove the previous MySQL driver.
Comment: I upgraded the MySQL driver, But it doesn't work and there is only one driver used by Intellij IDEA which is got from Intellij itself.
Comment: which version of java are you using?
Comment: java version: 1.8.0_71
Comment: try to update your JDK from oracle JDK to open JDK 1.8. this link will help you
    https://intellij-support.jetbrains.com/hc/en-us/community/posts/203366264-MySQL-connection-jdbc-com-mysql-jdbc-Connection-isValid-I-Z-SOLVED-
Comment: I downloaded the  IntelliJ x64 JDK from link given by Eugene Morozov and unzipped it. Then, Set the the unzip directory as IDEA_JDK_64 environment variable.But it still didn't work. Afterwards, I downloaded a latest Version of Intellij IDEA and installed it.It also didn't work.Why?
Comment: can you please attach the screen shot?
Answer: I solved it by changing to the older version of IDEA.
When I used the database of IDEA of Version 2016.1.4, it did work.


The existence of "inverse" in monoidal category

Question: In a monoidal category $\mathcal{C}$, Does any $f\in \operatorname{Hom}_{\mathcal{C}}(X\otimes \mathbf{1},Y\otimes \mathbf{1})$ can be expressed as $f=g\otimes \operatorname{Id}_{\mathbf{1}}$, where $g\in\operatorname{Hom}_{\mathcal{C}}(X,Y)$?
Short remark: I am reading a lecture note about tensor category by P. Etingof, S. Gelaki, D. Nikshych, and V. Ostrik. The link is attached here https://ocw.mit.edu/courses/18-769-topics-in-lie-theory-tensor-categories-spring-2009/pages/lecture-notes/. In their convention, a monoidal category is defined as  a quintuple $(\mathcal{C},\otimes, a, \mathbf{1}, \iota)$ where $\mathcal{C}$ is a category, $\otimes : \mathcal{C}\times \mathcal{C}\to \mathcal{C}$ is a bifunctor.
$a: (\bullet\otimes \bullet)\otimes \bullet \xrightarrow[]{\sim} \bullet\otimes(\bullet\otimes\bullet)$ is natural isomorphism between two tri-functor $\mathcal{C}\times\mathcal{C}\times\mathcal{C}\to \mathcal{C}$.
$$
a_{X,Y,Z}: (X\otimes Y)\otimes Z \xrightarrow[]{\sim} X\otimes (Y\otimes Z),\quad X,Y,Z\in\mathcal{C}
$$
called the associativity constraint (or associativity isomorphism). $\mathbf{1}\in\mathcal{C}$ is an object of $\mathcal{C}$, and $\iota: \mathbf{1}\otimes \mathbf{1}\to \mathbf{1}$ is an isomorphism, subject to the following two axioms.

The pentagon axiom.

The unit axiom. We can easily prove that  $X\to L_1(X):=\mathbf{1}\otimes X$, $X\in \mathcal{C}$, Any $f\in \operatorname{Hom}_{\mathcal{C}}(X,Y)$ is mapped to $L_1(f):= \operatorname{Id}_{\mathbf{1}}\otimes f$, $L_1$ defines a functor $\mathcal{C}\to \mathcal{C}$. The functor $R_1$ is defined similarly. The functors $L_{\mathbf{1}}$ and $R_{\mathbf{1}}$ of left and right multiplication by $\mathbf{1}$ are equivalences $\mathcal{C}\to \mathcal{C}$.

The unit axiom provides the following commutative diagram (natural isomorphism $\eta: (R_1^{-1}\circ R_1)\xrightarrow{\sim} \operatorname{Id}_{\mathcal{C}}$)
$$\require{AMScd}
\begin{CD}
R_1^{-1}(X\otimes \mathbf{1}) @>{\eta_X}>> X\\
@V{R_1^{-1}(g\otimes \operatorname{Id}_{\mathbf{1}})}VV @VV{g}V \\
R_1^{-1}(Y\otimes \mathbf{1}) @>{\eta_Y}>> Y
\end{CD}$$
Therefore, if such $g$ exists, it can be written as $g=\eta_Y\circ R_1^{-1}(f)\circ \eta_X^{-1}$.
Answer: The answer is yes. We can prove that
$$f=(\eta_Y\circ R_1^{-1}(f)\circ\eta_X^{-1})\otimes\operatorname{Id}_{\mathbf{1}}\quad \forall f\in\operatorname{Hom}_{\mathcal{C}}(X,Y)$$
Let $g=\eta_Y\circ R_1^{-1}(f)\circ\eta_X^{-1} $ in the commutative diagram present in the question, we will get $R_1^{-1}(g\otimes \operatorname{Id}_{\mathbf{1}})=R_1^{-1}(f)$. As mentioned in the lecture note attached in the question, there exists a natural isomorphism $r: R_1\xrightarrow{\sim}\operatorname{Id}_{\mathcal{C}}$, combined with the natural isomorphism (category equivalence) $\eta^\prime: (R_1\circ R_1^{-1})\xrightarrow{\sim}\operatorname{Id}_{\mathcal{C}}$, we can establish a natural isomorphism $\lambda: R_1^{-1}\xrightarrow{\sim}\operatorname{Id}_{\mathcal{C}}$. This natural isomorphism tells that if $R_1^{-1}(g\otimes \operatorname{Id}_{\mathbf{1}})=R_1^{-1}(f)$ then $g\otimes\operatorname{Id}_{\mathbf{1}}=f$.


Spring security, anonymous and authenticated for same endpoind

Question: I have /home endpoind:
@RequestMapping(value = "/home", method = RequestMethod.GET)
    public ModelAndView getLoginPage(
            HttpServletResponse response,
            @RequestParam(value = "msg", required = false)  String message{

            modelView.setViewName("landingpage/home");

        return modelView;
    }

it returns html that contains also login and also dashboard for logged users. So, for authenticated users, it is open:
http
        .authorizeRequests()
        .antMatchers("/", "/home", "/book/**").authenticated()

but also after failed login, it must be open because it throws message to /home endpoint:
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
....
     String exceptionMessage = exception.getMessage();
        String msgParam = "?msg=" + EncryptionUtil.encode(exceptionMessage);
        response.sendRedirect(/home + msgParam);

So what i want is, for
localhost:8080/home -> should be open to onlyauthenticated
localhost:8080/home?msg=asdsada -> should be open to all users

I tried to add this
  .antMatchers("/reset-password", "/login", "/home/**").anonymous()

So all class became like this:
        .antMatchers("/", "/home", "/deposit/**").authenticated()
         .antMatchers("/reset-password", "/login", "/home/**").anonymous()

but when i go to
http://localhost:8080/home?msg=BAcQreS-4_K54e3jWSksds
it cant go because  not allowed for nonauthenticated.
What can i do?
Answer: You should use regexMatchers instead of antMatchers, antMatchers ignores the query string.
.regexMatchers("/home").authenticated()
.regexMatchers("/home?msg=.*").permitAll()

Comment: `           .regexMatchers("/home?msg=.*").anonymous()
                .regexMatchers("/home").permitAll()` i did like this. It works only when logged in. When logged it, home works. For anonyömous, `/home?msg` this does not work


Standardized residuals vs. regular residuals

Question: I've got an easy question concerning residual analysis. So when I compute a QQ-Plot with standardized residuals $\widehat{d}$ on the y-axis and I observe normal distributed standardized residuals, why can I assume that the error term $u$ is normal distributed? I'd think that if $\widehat{d}$ looks normal distributed I just could assume that the standardized error term $d$ should be normal distributed.
So why can we assume that $u\sim N$ when we just observe that $\widehat{d}\approx N$. By the way can we assume it?
Comment: could you please mention how you calculate $u$ and $\hat d$
Comment: Hi. you can't calculate $u$ (except you're observing the whole population). So I'd say I calculate $\widehat{u}=y-\widehat{y}$ and $\widehat{d}=\widehat{u}/\widehat{\sigma^2}$. I guess I've got an idea of the answer, but I can not show it. What I know is, that we often assume that $u\sim N(0,\sigma^2)$, so when we divide $u$ by $\sigma^2$ I assume that we divide the first 2 moments of the distribution as well $u/\sigma^2 \sim N(0/\sigma^2,\sigma^2/\sigma^2)$ where $u/\sigma^2=d$ ist the std.error term which is (from above) $d\sim N(0,1)$. But I'm not sure if this makes sense (That's why I ask)
Comment: ... Thus when $u\sim N(0,\sigma^2)$ we assume automatically that $d\sim N(0,1)$. Is this correct? And where can I find a proof that this is correct?
Comment: In practical situations we estimate $\sigma^2$, then $\hat d$ is no longer gaussian. Instead, it is a $t$. But a $t$ with higher than 10 is not very different from a gaussian distribution.
Comment: @suncoolsu: I absolutely don't understand what you mean :) Please clarify and give a reference. Thank you!
Answer: The $u$s are unobserved and the $\hat{d}$s are just estimates of them.
Answer: This inference is no different from any other inference we make.  We assume a default (you could call it a 'null').  In this case, it's that the underlying distribution is Gaussian.  We examine the data to see if they are inconsistent with our default hypothesis.  If the qq-plot of our residuals looks sufficiently Gaussian for your satisfaction, then we stick with that assumption.  In truth, no matter how non-normal our residuals appear, they could still have come from an underlying Gaussian distribution, but at some point, we just don't believe it anymore.  Another way to phrase this is that we don't assume they're Gaussian because the qq-plot looks Gaussian, rather we don't stop assuming they're Gaussian because the qq-plot doen't look sufficiently non-Gaussian.
Some people have trouble with this line of reasoning; which is perfectly fine.  You might be interested in checking out the Bayesian approach to statistics.
Answer: In a linear model $ y = X\beta + u $   with $u \sim N(0, \sigma^2I)$, the vector of raw residuals is $ \hat u = y - \hat y = (I - H)y $ where the hat matrix $H = X(X'X)^{-1}X' $.   The response $y$ is normally distributed given the assumed normality of the error terms.
Consequently, if the model assumes normality correctly, $\hat u$ is also normally distributed since each residual is a linear combination of $y$.  Therefore, if a QQ-plot does not support the normality of $\hat u$, it warrants a question about the normality of $y$, which in turn raises a doubt about the normality assumption of $u$.  On the other hand, if there is a lack of evidence to reject the normality of $\hat u$, the logic is to accept the normality of $u$.
On the specific question about checking normality of $\hat d = \hat u/\hat \sigma $ and its relationship to the normality of $u$ ...
As just mentioned, $\hat u$ is normally distributed under the model, so is $\hat u/c$ for any non-zero constant $c$, such as $\sigma$.  If $\sigma$ were known, the scaled residual $\hat u/\sigma$ would be better than $\hat u$ for identifying potential outliers.   As $\sigma$ is usually unknown, $\hat d$ = $\hat u/\hat \sigma$ is used instead. However, the approach of checking the normality of $\hat d$ to validate the normality of $u$ is approximate and less preferred given that its divisor $\hat \sigma$ is a statistic, not a constant.
Is then using $\hat u$ to assess the normality of $u$ a perfect approach?  Not necessarily...
Note that $Var(\hat u)$ = $\sigma^2(I - H)$, indicating that raw residuals are correlated and variances are not constant.  More specifically, such residuals are not sample points randomly (independently) drawn from a common underlined distribution.  Is it then appropriate to subject the residuals to a univariate QQ-plot to assess normality?
In brief, any conclusion about normality from a QQ-plot is visual based, thus subjective, regardless of which type of residuals (raw or otherwise) is evaluated.  Besides, normality assessment is only one aspect of model adequacy assessment.  While raw residuals may be more appropriate with QQ-plot, other types of residuals may be better suited with other diagnostic tools.


Continuous at some and at all points

Question: Can I have someone to show me an insight on how to prove these? I had referred to a number of books but most authors merely state them as definitions or theorems without proof.
Let $T:X \to Y$ be a linear operator. Then the following are equivalent:

$T$ is continuous at some point $v_{0} \in V$
$T$ is continuous at all points of $V$
$T$ is bounded
$T$ is uniformly continuous.
Comment: Usefull intuition is that the linearity allows us to transport properties at origo to other points and vice versa (injectivity, continuity etc.).
Answer: Those results are standard and appear in (almost) any functional analysis textbooks. The equivalence between (1), (2) and (3) appears in the text "Analysis Now" by Petersen (full proof with all the details).
$\bf Edit:$ $(1)\rightarrow (2)$ Suppose $T$ is continuous at $v_0$ and let $x\in X$ be given. Let $\epsilon>0$ be given. Find $\delta>0$ so that $\| T(v_0)-T(v)\|<\epsilon$  whenever $\| v_0-v\|<\delta$. Note that if $\|x-y\|<\delta$ then $\|x-y\|=\| v_0-(x-y+v_0)\|<\delta$. It follows  from linearity that $T(x)-T(y)=T(v_0)-T(x-y+v_0)$, hence $\|T(x)-T(y)\|<\epsilon$. Thus $T$ is continuous at $x$.
$(2)\rightarrow (3)$: If $T$ is continuous at zero then there exists $\delta>0$ so that $\|T(x)\|\leq 1$ for all $\|x\|\leq \delta$. This implies that, for all $x\ne 0$, $\|T(\frac{\delta\cdot x}{\| x\|})\|\leq 1$, hence $\| T(x)\|\leq \frac{\| x\|}{\delta}$. Therefore $T$ is bounded.
$(3)\rightarrow (4)$: Follows easily from Beni's observation and $(4)\rightarrow (1)$ is obvious.
Comment: Thanks Azarel. Guess you can't find (4) because I added in myself. Do you know how to prove (4)? I am thinking of the relation (1) \rightarrow (4) \rightarrow (2) \rightarrow (3) \rightarrow (1) but still thinking on how to get them.
Comment: @sandra (4) comes from $\|Tx-Ty\|\leq \|T\| \|x-y\|$
Comment: Dear Beni. Ok Thanks. Sadly Peterson's book is not in our library. Have to look for others book now.
Comment: @sandra I'll add a full proof then.

Continuous at some and at all points


Independance of three random variables

Question: I have a problem in understanding the independence concept. I have this problem.
let us assume that a video frame of size L bytes has to be carried over N packets. The frame size Land the number of packets are both random. now, let the size of the packet be S, which is also a random variable since (i guess). I want to compute the expected size of the packet S
What is the relationship between the three RVs in term of dependency?
are N and L independent?
if yes then
S=L/N  ---> E[S]=E[L/N] ---> is this true E[S]=E[L]*E[1/n]

N is Uniform random variable. RVs are discrete

Answer: Two things:

I find it highly unlikely that $L$ and $N$ would be independent of one another. This is likely an erroneous assumption and you should take caution.
No, $E[S] \neq E[L] \times E[1/N]$. You would have to find the distribution of $S$ directly from the distribution of $L$ and $N$ unless $L$ is a certain random variable such that $L/N = S$ follows a well-known distribution.
Comment: Regarding  (1), i know that from system operation that N , is chosen randomly and independently within  a range ( for security security purpose ). Does that justify  the independency assumption ?
Comment: You're saying that $N$ is chosen randomly from a set of numbers?  The number of packets $N$ is not affected whatsoever by the video frame size?  I would imagine that if the video frame size $L$ gets larger, $N$ must also get larger. If this is the case, this implies that the two are *not independent.*  However, I know very little about graphics and sending information so my intuition could certainly be off the mark here.

Independance of three random variables


Imputation with R and MICE

Question: A short mice-related question as follows: when running simple mice imputation the function goes through well. But complete() function does not substitute my NA's at all. I guess it must be something wrong with my dataset but I can't see what. It is just a matrix as any other although with roughly equal number of rows and columns. Maybe this is the source of the problem. What should I look into?
Comment: As Nick said, posting some sample data and code for what you're doing is necessary. As a wild guess, you're sure you didn't end up with "NA" as a string value instead of an actual NA?
Answer: My guess is that this arises from including the original dataset. You can specify that by either choosing the 0 dataset or complete(..., action="long", include=TRUE), see below example:
# Generate data
dat=data.frame(x1=c(21, 20, 31, 50),
               x2=c(0, NA, 18, 3),
               x3=c(0, 0, 54, 10))

library(mice)
# Do imputation
imp <- mice(dat, m=2)

Now this gives:
> # Look at the original dataset
> complete(imp, 0)
  x1 x2 x3
1 21  0  0
2 20 NA  0
3 31 18 54
4 50  3 10
>
> # Get all the datasets
> complete(imp, action = "long", include = TRUE)
   .imp .id x1 x2 x3
1     0   1 21  0  0
2     0   2 20 NA  0
3     0   3 31 18 54
4     0   4 50  3 10
5     1   1 21  0  0
6     1   2 20  0  0
7     1   3 31 18 54
8     1   4 50  3 10
9     2   1 21  0  0
10    2   2 20 18  0
11    2   3 31 18 54
12    2   4 50  3 10

Imputation with R and MICE


Justification of an isomorphism between $\mathbb{Z}[t]/(t,3)$ and $\mathbb{Z}/3$

Question: I am wondering if the following is true:
$$\mathbb{Z}[t]/(t,3)\cong\mathbb{Z}/3.$$
I can tell that the ideal $(t,3)$ is maximal. In contrast, the ideal $(t^2,2t)$ is not even irreducible. So it's less likely that we can simplify $\mathbb{Z}[t]/(t^2,2t)$ further.
If the aforementioned isomorphism is true, that means $\mathbb{Z}[t]/(t,3)\cong(\mathbb{Z}[t]/t)/(3)\cong\mathbb{Z}/3$, where the $(3)$ is an ideal in $\mathbb{Z}[t]/t$. My questions are:
1) Is this argument legitimate?
2) If it is true, is there any theorem justifying the aforementioned isomorphism?
Answer: Yes your intuition is correct and I try to explain necessary steps:

Claim. $\Bbb{Z}[x]/\langle x,3\rangle\cong\Bbb{Z}/\langle3\rangle$

Well, I'll prove the following steps:
$$\Bbb{Z}[x]/\langle x,3\rangle\cong \frac{\Bbb{Z}[x]/\langle x\rangle}{\langle x,3\rangle/\langle x\rangle} \cong\Bbb{Z}/\langle 3\rangle$$

The first isomorphism is due to the 2nd Isomorphism Theorem of Ring theory.
I think $\Bbb{Z}[x]/\langle x\rangle \cong \Bbb{Z}$ is clear. (Hint: consider the homomorphism $f(x) \mapsto f(0)$ form $\Bbb{Z}[x]$ to $\Bbb{Z}$ and use 1st Isomorphism Theorem on Rings.
Now for the equality $\langle x,3\rangle/\langle x\rangle\cong \langle 3\rangle$ Try to define the homomorphism as follows:

$\phi :\langle x,3\rangle \to \langle 3\rangle$ by mapping any element $xf(x)+3g(x)\in \langle x,3 \rangle$ to $3g(0) \in \langle 3\rangle$ (N.B. Here, $f,g \in \Bbb{Z}[x]$), i.e. $$\phi: xf(x)+3g(x) \mapsto 3g(0)$$
See that this is an epimorphism. Also $\ker \phi=\langle x\rangle$. Then by 1st Isomorphism theorem $\langle x,3\rangle/\ker \phi \cong \langle 3\rangle$. Which justifies all your steps...!!
N.B. To find out the $\ker \phi$, remember for any $g(x)\in \Bbb{Z}[x]$ if we have $g(0)=0$ that means $x$ is a factor of $g$ and so $g\in \langle x\rangle$.
Comment: $>$ is an operator; &\rangle$ is a grouping symbol. They have different formatting rules, and are the reason for all the weird spaces in your answer.
Comment: @BobKrueger...Thanks for mentioning that....I'll take care of it next time....:)
Comment: What's wrong with using the [edit] function to fix it *this time* as well? Is your time somehow more important than that of someone who might have edited this?
Comment: I'll note that I didn't edit it so that the poster would recognize the mistake. @IndrajitGhosh happy to help even if it's not expressly math.
Answer: It's legitimate and a consequence of the isomorphism theorems.


IIS 10 PHP rewrite rule not running

Question: I'm attempting to rewrite all PHP requests to 410 Gone on IIS 10/Windows Server 2016. With this rule in place, PHP requests are returning 404 errors. If I change the pattern to "^.*.ph1", a request to /test.ph1 returns 410.
What could be catching the PHP request to return a 404 prior to URL Rewrite rules? PHP is not installed on this server.
<code> <rewrite>
  <rules>
    <rule name="RequestBlockingRule1" stopProcessing="true">
      <match url=".*" />
      <conditions>
        <add input="{URL}" pattern="^.*\.php" />
      </conditions>
      <action type="CustomResponse" statusCode="410" statusReason="Gone" statusDescription="Gone" />
    </rule>
  </rules>
</rewrite>
</code>
Answer: IIS Request Filtering will catch requests before URL Rewrite rules, and sets a 404.7 response (that gets sent back to the browser as 404).

IIS 10 PHP rewrite rule not running


how to use map in react typescript

Question: Currently using a react in typescript.
make a separate file and manage it.
I want to do map work on the `card component
parameter on the map wrong?
definition wrong?
Can I get some advice...
Card.tsx
import { LIST_DATA, ListData } from './data';

const Card = () => {
return(
  {LIST_DATA.map(({ id, title }: ListData[]) => {
    return <S.InfoTitle key={id}>{title}</S.InfoTitle>;
  })}
)
}

data.tsx
export interface ListData {
  id: number;
  title: string;
}

export const LIST_DATA: ListData[] = [
  {
    id: 0,
    title: 'drawing',
  },
  {
    id: 1,
    title: 'total',
  },
  {
    id: 2,
    title: 'method',
  },
  {
    id: 3,
    title: 'material',
  },
];

Comment: since map function parameter is a single item remove array brackets from type

{LIST_DATA.map(({ id, title }: ListData) => {
    return {title};
  })}
Answer: When you map, each item inside the map as argument is only one item from the original array. In your case you have an array of ListData but when you map each argument is only one of this ListData item type, therefore you have to change ListData[] to ListData as such:
import { LIST_DATA, ListData } from './data';

const Card = () => {
   return(
     {LIST_DATA.map(({ id, title }: ListData) => {
       return <S.InfoTitle key={id}>{title}</S.InfoTitle>;
     })}
   )
}

Otherwise to answer the main question: map in typescript is the same as map in javascript, you just have to ensure you input the right type in order to "secure" your app.

how to use map in react typescript


what is the default file template in drupal when you set your own theme?

Question: What is the default template in drupal when you set your own template and you don't have page.tpl.php
??
where does the html beeing rendered from?
Answer: If the active theme doesn't have a page.tpl.php, the default page.tpl.php from core is used.
See Default theme implementations for more information.
Comment: and the default regions?
Comment: Regions are defined in the theme's .info file, they all have them. There aren't 'default regions' as such
Comment: yes but i haven' defined my regions and even such so, it displays
header
footer
content
etc..
in Admin ->Blocks
Comment: @Clive the default region in .info D7 can be found https://www.drupal.org/node/171206#default-regions. and for more information about the defualt template check modules/system (core Drupal module) for the templates structure


UITableView com UITableViewCell customizada e redimensionável

Question: Estou criando um chat para IOs em Objective C, e utilizo UItableViewCell customizada. Minha dificuldade é em redimensionar a Cell conforme o texto nas conversar, como a imagem:

E essa segunda tela, é de como esta, com uma conversa, sobrepondo a outra, sem ter um limite de quando passara de uma cell para a outra.

Ja tentei utilizar a partir de Auto Layout, e não funcionou também. Poderiam me ajudar?
Comment: Não entendi o problema. tem como mandar um print como devia ser?
Comment: @PauloHDSousa a imagem a cima é como deveria estar, que seria o background e a cell sendo redimensionavel através da quantidade de texto, porém não consigo redimensionar a cell, e assim o texto não aparece inteiro.
Comment: @PauloHDSousa inseri um print de como esta no momento.
Comment: Em todas as versões do IOS acontece isso?
Comment: Esse cara aqui teve um problema igual o seu. http://stackoverflow.com/questions/18527227/uitableviewcell-with-dynamic-height-ios
Comment: @PauloHDSousa estou utilizando na versão 9.0, porém creio que sim, pois não mexi em nada que redimensiona a cell, pois não sei, apenas esta separando pelo tamanho da cell fixa na hora em que criei a view separada
Comment: @PauloHDSousa vou dar uma olhada no problema dele.
Answer: Pesquisei sobre tutoriais sobre o mesmo assunto, acho que o site do raywenderlich se encaixa bem no que você quer.
Tutorial
A titulo de curiosidade não sei se isso poderia ajudar, mas procurei por bibliotecas de terceiros que teriam até coisas a mais do que acho que você precisa. Vai ai alguns links:
SPHChatCollectionView
SlackTextViewController
whatsapp-ios
SOMessaging
Espero ter ajudado.
Comment: Vou dar uma olhada em todo material que você me passou, desde já, obrigado pela ajuda.


Why is reduce working this way?

Question: I wrote a function to fulfil the following criteria:
"Write a function that, given a string, produces a map of the indexes of all characters. For example,
indexes("Mississippi") should return a map associating 'M' with the set {0}, 'i' with the set {1, 4, 7, 10}, and
so on."
But why is the first value of i 1 in my implementation, thus chopping off the M?

var s = 'Mississippi';

function indexes(s) {
  var acc = {};

  return s.split('').reduce(function(p, c, i) {
    if (!acc[c]) {
      acc[c] = [i];
    } else {
      acc[c].push(i);
    }

    return acc
  });
}
console.log(indexes(s)); // Object {i: Array[4], s: Array[4], p: Array[2]}
Comment: `i = 1` because of: "The first time the callback is called, previousValue and currentValue can be one of two values. If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. **If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second**."
Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce the `M` is stuck in the `previousValue` parameter
Answer: Because you haven't specified an initial value for the accumulator, and so the first call to your callback has the first two entries in your array (e.g., p will be "M" and c will be "i"), but you're not using p, so you end up missing the "M".
Not providing an initial value is useful when you're doing a straight sum (for instance), but for this sort of thing, I find the easiest way to use reduce to provide that initial value, like so:

var s = 'Mississippi';

function indexes(s) {
  // Note: No `acc` here
  return s.split('').reduce(function(p, c, i) {
    // Note: Using `p` here
    if (!p[c]) {
      p[c] = [i];
    } else {
      p[c].push(i);
    }

    return p;
  }, {});
  // ^^-- Initializing the accumulator here
}
snippet.log(JSON.stringify(indexes(s))); // {"M":[0],"i":[1,4,7,10],"s":[2,3,5,6],"p":[8,9]}

If you preferred to keep using the external acc instead, I'd probably use forEach rather than reduce.

Why is reduce working this way?


For what sequences of consecutive perfect squares would the sum be a perfect square?

Question: For example, the sum of the sequence of perfect squares from 1^2 to 24^2 = 70^2.
What other sequences (of let's say length >= 5) of some starting n^2 and ending m^2 would sum to a perfect square?
Comment: http://math.hashcode.ru/questions/71079/%D0%B4%D0%B8%D0%BE%D1%84%D0%B0%D0%BD%D1%82%D0%BE%D0%B2%D1%8B-%D1%83%D1%80%D0%B0%D0%B2%D0%BD%D0%B5%D0%BD%D0%B8%D1%8F-%D1%81%D1%83%D0%BC%D0%BC%D1%8B-%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%D0%B4%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D1%8B%D1%85-%D0%BA%D0%B2%D0%B0%D0%B4%D1%80%D0%B0%D1%82%D0%BE%D0%B2?%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D0%B0=1&focusedAnswerId=71097#71097
Answer: This is a famous problem and the answer is none. The challenge is to prove it which isn't so hard once you know the answer ahead of time. Try it.


Add hook after registration form submit

Question: I'm trying to club Drupal & Magento together. So I want to make the registration seamless. If any user register in Drupal they want to register in Magento automatically using a custom module in Drupal. I have scripts to register in Magento by sending data to Magento script file.
I want to know how to make a AJAX call to that script file, using a custom Drupal module. I'm using Drupal 7 version.
Comment: I also want to pass registration form data in the ajax call.
Comment: You can try http://php.net/manual/en/book.curl.php
Comment: This is php curl by default to get response from the page. My Question is how to add a hook after registration form submit in drupal framework.
Answer: You can use hook_user_insert, in which you can easily execute CURL, in hook_user_insert you will have all your data regarding the user.
Answer: For achieving this goal you have to Implement drupal hook_user_insert
and Use php cURL

Add hook after registration form submit


Generic parameter 'Success' could not be inferred; Key path value type '_' cannot be converted to contextual type '_'; Cannot find 'Response' in scope

Question: I think this might be the last push for my project of mobile GitHub query repository search, but I get 3 errors I cannot find out how to cope with.
The code:
import SwiftUI
import Combine

struct Root: Codable {
    let items: [Item]

    enum CodingKeys: String, CodingKey {
        case items
    }
}

struct Item: Identifiable, Codable {
    let id: Int
    let urlCode: String
    let fullName: String

    enum CodingKeys: String, CodingKey {
        case id
        case urlCode = "url"
        case fullName = "full_name"
    }
}

private final class ContentViewState: ObservableObject {

    @Published var isLoading = false
    @Published var query = ""
    @Published var stuff = [String]()

    private var subscription: AnyCancellable?

    func fetchRepos(query: String) {
        isLoading = true
        subscription = Just("test")
            .delay(for: 2, scheduler: RunLoop.main)
            .sink(receiveValue: {[weak self] (title: String) in
                self?.isLoading = false
                self?.stuff.append(title)
            })
    }
}

struct ContentView: View {
    @StateObject private var state = ContentViewState()
    @State private var items = [Item]()

    var body: some View {
        VStack {
            if state.isLoading {
                ProgressView()
            } else {
                HStack {
                    TextField("Enter search", text: $state.query)
                    Button("Search") {
                        state.fetchRepos(query: state.query)
                    }
                }
                List(items, id: \.id) { item in
                    VStack(alignment: .leading) {
                        Text(item.fullName).font(.headline)
                        Text(item.urlCode)
                    }
                }.task {
                    await loadData()
                }
            }
        }
    }

    func loadData() async {
        guard let url = URL(string: "https://api.github.com/search/repositories?q=" + state.query + "&per_page=20") else
        {
            print("Invalid URL")
            return
        }

        do {

            let (data, _) = try await URLSession.shared.data(from: url)

            if let decodedResponse = try? JSONDecoder().decode(Root.self, from: data) {
                items = decodedResponse.items
            }
        } catch {
            print("Invalid data ")
        }
    }
}

The errors:
"Generic parameter 'Success' could not be inferred" on line:
TextField("Enter search", text: $state.query)

"Key path value type '' cannot be converted to contextual type ''" on line:
           await loadData()
        }
    }

"Cannot find 'Response' in scope" on line:
      } catch {
            print("Invalid data ")
        }
    }
}

Please help :)
Comment: Your code seems to run just fine for me. Have you tried the following: closing and reopening xcode, cleaning your project, deleting derived data?
Comment: It is built fine here. Xcode 13.2 / iOS 15.2. I suppose you might have conflict of types (redeclaration, etc.) somewhere.
Comment: Thanks, @Anwuna :) I have copied the code to another project and it works perfectly now!
Answer: The answer was to move the code to another file, change its structure a bit and everything works fine now!


How do I turn a "broken" plot into a smooth curve

Question: I developed and solved a differential equation that predicts fluid temperature along the length of a long pipe with time.
Analytical solution is such that it is causing a "discontinuity" in the temperature profile along the depth at fixed time. (This discontinuity travels down the pipe as time progresses. So the picture shown here is just a snapshot frozen at a fixed time at the start of flow.
In actual physical world, this break/discontinuity does not exist.
I want to make it smooth as shown in red in bottom right plot (like red line).
Would you please suggest any method that can fix this problem.
**

Suggested method should be reproducible, repeatable and programmable.
  (I am using VBA)

**
Comment: Doesn't this suggest that the PDE fails to capture the physical flow, and a different PDE is needed? Sure you can patch things up with splines, but choosing the shape of connecting curve will be an arbitrary decision on your part. Might as well forget the PDE and fit a smooth curve to experimental data.
Comment: Well you need to show your DE so that people can fix it.
Comment: I am interested in a "curve fitting" solution. The solution of DE is correct as I have searched in literature and other papers also have such discontinuities. So a possible way could be "approximating" this result using a graphical technique.
Comment: Also, there is a reason that heat transfer is usually modeled not by an ordinary DE but partial DE.
Comment: I am using PDE.
Comment: cubic splines ?
Comment: @GregMartin Would it be reproducible/repeatable?
Comment: In the physical world, there are things that called shock wave. If the ODE is non-linear, the physical solution can be discontinuous...
Comment: The flow here is slow. There is no shockwave here. Also, I have talked to some experienced people who have worked in industry that they have never seen such anomaly. So this anomaly is only because of the nature of PDE. I want to find out a method to remove this discontinuity and that method has to be reproducible/repeatable.
Comment: @wordsthatendinGRY Yes it does but then I want to salvage whatever results it is giving me. This is just one of several cases for which my model predicts temperature. This is the only case that is giving me a discontinuous profile.
Answer: A standard technique is indeed to use a piece of a cubic polynomial for connecting broken curve parts. The cubic polynomial is uniquely determined by the function values and derivatives at the end points. This function is well behaved, as proved in lemma 1.1 of the following German text, which I wrote a long time ago.
To turn this technique into a "reproducible, repeatable and programmable" method applicable for scenarios like the one in the plot, one can vary the connecting point on the smooth curve, such that $\max(|m_a-m|,|m_b-m|)$ is minimized. Here $m_a$ is the derivative at end point of the discontinuous curve, $m_b$ is the derivative at the connecting point on the smooth curve, and $m$ is the slope of the straight line connecting the two points.

A drawback of cubic curves is that they are not well suited for nearly vertical slopes. The plots suggest that this might be the case here. In this case, it is better to work with exponential functions.
In the plot, it looks like only one curve is broken, and the other curve is smooth. In this case, we can add $a \exp(bx)$ to the smooth curve, where $a$ and $b$ are uniquely determined by the conditions that the new smooth curve meets the broken curve at the end point, and that the derivative is continuous at that point. This automatically satisfies the requirement to be a "reproducible, repeatable and programmable" method.
Comment: If I use the cubic polynomial, would it be reproducible/repeatable and automatic considering I am using VBA to write the program?
Comment: @Lee It will not. The result of interpolation will depend on the mesh of the interpolation grid. The red curve you drew makes the transition over the interval of size about 15. That 15 was your choice, it wasn't automatic. The spline will make the transition over the interval comparable to the mesh size: it could be 15 or 0.15, as you choose it. By the way, if you go with cubic spline, I recommend [B-spline](http://en.wikipedia.org/wiki/B-spline) approximation which is  more suitable for rough data than interpolating cubic splines.
Comment: @wordsthatendinGRY what if I write a code that works as follows: 1) Pick the highest temperature point from the top curve. 2)From the bottom curve, discard all the points lesser than the highest temperature point of top curve. 3) Now apply cubic spline (or B-spline approximation). Even if I take this approach do you think it would be an acceptable approach in the eyes of scientific community?
Comment: @Lee How will your code choose the nodes of interpolation? They could be spaced at 10 degrees, 1 degree, 0.1 degree... This is what I keep harping about.
Comment: @Lee There are some options for making such methods "reproducible, repeatable and programmable". The method with the exponential function already satisfies this property without any further modification. For the method with the cubic polynomial, I added a suggestion how to make it reproducible. I'm not sure why you stress VBA.


Update start urls at scrapinghub hosted Scrapy project via API call

Question: My Scrapy spider is hosted at scrapinghub. It is managed via run spider API call.
The only thing that changes in spider from call to call is a list of start urls. The list may vary from 100 urls to couple thousand. What is the best way to update start urls in this scenario?
From what I see there is no direct option in SH API for this.
I am thinking of updating MySql with list of urls and once updated send simple Run job API call. (Start urls will be generated from MySql table).
Any comments on such solution or other options?
My current setup is as follows.
def __init__(self, startUrls, *args, **kwargs):

    self.keywords = ['sales','advertise','contact','about','policy','terms','feedback','support','faq']

    self.startUrls = startUrls

    self.startUrls = json.loads(self.startUrls)

    super(MySpider, self).__init__(*args, **kwargs)

def start_requests(self):

    for url in self.startUrls:

        yield Request(url=url)

Answer: You can pass parameters to scrapy spider and read them inside your spider.
Send list of URLs encoded as JSON and then decode them, and now fire requests.
class MySpider(scrapy.Spider):

    def __init__(self, startUrls, *args, **kwargs):

        self.startUrls = startUrls

        self.startUrls = json.loads(self.startUrls)

        super(MySpider, self).__init__(*args, **kwargs)

    def start_requests(self):

        for url in self.startUrls:

            yield Request(url=url ... )

And here is how you run send this parameter to your spider.
curl -u APIKEY: https://app.scrapinghub.com/api/run.json -d project=PROJECT -d spider=SPIDER -d startUrls="JSON_ARRAY_OF_LINKS_HERE"

Your scrapinghub.yml file should be like this
projects:
  default: 160868

Comment: Thank you. This whould work perfectly for a list of 10 urls. But how do I deal with 1000 urls?
Comment: what whould the keys in urls array be ?
Comment: @BillyJhon just create a list/array of URLs in whatever programming language you are using, and then encode it as JSON .. the encoded JSON will look like this ... http://www.jsoneditoronline.org/?id=256353f25851ab72ef689ece443dd071 ... in PHP, create an array of URLs, and then do `json_encode($array)` ...
Comment: Got it. Thanks. Marked your answer as accepted one.
Comment: Hey. I am getting this error when shub deploy. Error: Deploy failed (400):
project: non_field_errors. Have added the code into original post.
Comment: @BillyJhon Show me your `scrapinghub.yml` and `requirements.txt` file
Comment: project: 252665. And there is no requirements txt for this one.
Comment: @BillyJhon See my edited answer, that is how your scrapinghub.yml file should look like
Comment: Hmm not sure whats going on ... please try to remove `project.egg-info/` & `build/` folders
Comment: Did it twice before every change.
Comment: I dont have further knowledge .. try `shub logout` and then again `shub login` ... and then deploy ... if that doesnt work too, try to update your `shub` by `pip install shub --upgrade`
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/158252/discussion-between-billy-jhon-and-umair).
Comment: Just for reference: `yield Request(url=url ... )` returned `SyntaxError: invalid syntax`. I just removed the 3 dots and got it working.
Comment: @Linkmichiel dots were just for explanation of more code follows, they were not part of Python code


Get Height/Width of imageView from Android.Support.V4.Fragment(always return zero)

Question: I'm using V4.Fragments. So from activity i'm creating new instance of my fragment and after that i begin transaction.
The main problem,that my imageview control is defined(in axml) as Layout_width="match_parent"
 and  weightSum=1 (for height).
For some reason i need to know height/width of my imageView.
What i tried :
was created class that implements IOnGlobalLayoutListener
     class GlobalLayoutListener : Java.Lang.Object, ViewTreeObserver.IOnGlobalLayoutListener
        {
            System.Action _OnGlobalLayout;

            public GlobalLayoutListener (System.Action onGlobalLayout)
            {
                this._OnGlobalLayout = onGlobalLayout;
            }

            public void OnGlobalLayout ()
            {
                _OnGlobalLayout ();
            }
        }

After that,in my V4.Fragment class,i'm doing this:
           public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
                {
                    Arguments = new Bundle();
                    View _View = inflater.Inflate(Resource.Layout.MyFragmentLayout, container, false);
                    imgView = _View.FindViewById<ImageView>(Resource.Id.imgView);

                Action CallBack = () =>
                {
                    ImgHeight = imgView.Height;
                    ImgWidth = imgView.Width;
                };
           //new instance of class,that implements IOnGlobalLayoutListener
            GlobalLayoutListener Global = new GlobalLayoutListener(CallBack);
            imgView.ViewTreeObserver.AddOnGlobalLayoutListener(Global);
retun _View;
}

Trick doesnt worked. Always return zero(height/width).
Second variant,i implemented interface of IOnGlobalLayoutListener directly in MyFragment
 public class MyCustomFragment : Android.Support.V4.App.Fragment,View.IOnTouchListener,ViewTreeObserver.IOnGlobalLayoutListener
    {
        int ImgHeight;
        int ImgWidth;
        ImageView imgView;
        Bundle Arguments;

  public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
            {
                Arguments = new Bundle();
                View _View = inflater.Inflate(Resource.Layout.MyFragmentLayout, container, false);
                imgView = _View.FindViewById<ImageView>(Resource.Id.imgView);

        ViewTreeObserver Vto = imgView.ViewTreeObserver; //also tried with _View.ViewTreeObserver; result same
        Vto.AddOnGlobalLayoutListener(this);

    retun _View;
}

Same problem,doesnt worked.
And my last variant is like :
        public class MyCustomFragment : Android.Support.V4.App.Fragment
            {
                int ImgHeight;
                int ImgWidth;
                ImageView imgView;
                Bundle Arguments;

  public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
            {
                Arguments = new Bundle();
                View _View = inflater.Inflate(Resource.Layout.MyFragmentLayout, container, false);
                imgView = _View.FindViewById<ImageView>(Resource.Id.imgView);

        imgView.ViewTreeObserver.GlobalLayout += (sender, e) =>  //also tried with _View
                {
                    ImgHeight = imgView.Height;
                    ImgWidth = imgView.Width;
                };

    retun _View;
}

Again no luck,what i'm doing wrong? Thanks.
PS Sorry for my eng.
Answer: All works fine,i was doing something wrong.
So this code works great :
imgView.ViewTreeObserver.GlobalLayout += (sender, e) =>
                {
                     ImgHeight = imgView.Height;
                     ImgWidth = imgView.Width;
                };

Enjoy!


Item displays get key added but dont show in the inventory

Question: When adding the key it displays key added but then when I type inventory it says backpack empty, also when I go to use the item it wont let me, as its not usable.
public class Get extends AbstractCommand {

public Get (String name, String description){
    super (name, description);
}
@Override

public void execute (Game game, String string) {

    Item temp = game.getCurrentRoom().getItem(string);

    UserInterface ui = game.getUI();

    if(temp == null) ui.println("Item added\n");

    else if (!(temp instanceof Moveable)) ui.println("item can not be moved");

    else if (!game.getBackpack().add(temp)) ui.println("item can not be moved");

    else game.getCurrentRoom().removeItem(temp);

}

}

    @Override
   public void execute(Game game, String string){
      Item itemInBag = game.getBackpack().getItem(string);
      Item itemInRoom = game.getCurrentRoom().getItem(string);

      if(itemInBag!= null) {

            if(itemInBag instanceof Useable){
               game.setGameState(((Useable)itemInBag).use(game));
                        }else game.getUI().println("you can not use item");

      }else if(itemInRoom!= null){
                if(itemInRoom instanceof Useable){
                    game.setGameState(((Useable)itemInRoom).use(game));
                         }else game.getUI().println("this item can not be used");
               }else {

                    game.getUI().println("take the item and use when you need to");

      }
      }
   }

public class Inventory extends AbstractCommand {

public Inventory (String name, String description){
    super (name, description);
}
@Override

public void execute (Game game, String string) {

    if(((BackpackImpl)game.getBackpack()).getCount()==0) {
            game.getUI().println("Backpack is empty");

    }else {
        for(Item i: game.getBackpack().getItems()) {
            game.getUI().println(i.getName());

             }

            }
        }

}

    List<Item> items;
    int maxCapacity;

    public BackpackImpl (int maxCapacity){

    this.maxCapacity = maxCapacity;
    items = new ArrayList<Item>(5);

    }

    public BackpackImpl () {
    this.maxCapacity = 5;

    }

    @Override
    public boolean add(Item item){
    if(items.size()>maxCapacity)

    {System.out.println("your backpack canot fit no more\n");
    return false;
    }
    items.add(item);
    return true;
    }

    @Override
    public Item remove(String string){
        for(Item i: items){
        if(((i.getName()).toLowerCase()).equals(string.toLowerCase())) {
            items.remove(i);
            return i;

            }

        }
    return null;
    }

    @Override
    public Item getItem(String string){
    for(Item i: items){
        if(((i.getName()).toLowerCase()).equals(string.toLowerCase())) {

            return i;
        }
    }
    return null;
    }

    @Override
    public int getCapacity(){
        return maxCapacity;

    }

    @Override
    public List<Item> getItems(){

        return items;
    }

    public int getCount (){
    return items.size();

    }
    public void clear(){
    items.clear();
    }
}

Answer: Due to the "if/else (if)" construction in your Get.execute method, a new item is never added via the BackpackImpl.add() method.
Revise your Get.execute method and only print "Item added" when your code has actually called the BackpackImpl.add() method. Also, to keep your code readable, always use {} when using "if/else (if)" constructions. E.g.:
if (temp == null) {
    ui.println("Item added\n");
} else if (!(temp instanceof Moveable || game.getBackpack().add(temp))) {
    ui.println("item can not be moved");
} else {
    game.getCurrentRoom().removeItem(temp);
}

Comment: this is fantastic it adds and removes thank you so much, but now my use item does not work, sorry to be a pain its my project for college and it has to be in on Tuesday. Any suggestions :-)
Comment: i have been up all night trying to figure it out :-( u are a life saver
Comment: To confirm your code does what you think it does, add a print statement like `System.out.println("Here")` at each step (this is also why you should use `{}` often: you can add the print-statement without changing anything else). Add variables to the print-statement to see if they match your expectations. This is basically manual debugging: your IDE should be able to give you the same kind of information when you run your program in debug-mode.
Comment: @user3211616 Can you please accept my answer if it works for you? Else your question will keep showing up as unanswered.


Are $l^p$ spaces compact?

Question: Given the sequence space $l^p$ where it represents the set of sequences $d=(d_n)_{n\in\mathbb{N}}$ s.t
$$\sum_{n=1}^{\infty} |d_n|^p<\infty$$
Is the metric space $(l^p,q)$ compact? Where $q$ is a metric I apologise if this a a dumb question but because the terms a bounded I assume intuitivly it's true but I'm not sure how one would prove it. this is the first I'm taking a math course in years.
Answer: No.  The only compact normed linear space is $\{0\}$.  Moreover, $l^p$ is infinite-dimensional so it is not even locally compact.
Comment: is it separable? That was my follow up question but I wasn't sure how to prove it either
Answer: Firstly, normed vector spaces are metric spaces, and compactness in metric spaces is equivalent to sequential compactness. So you only need to look at converging subsequences to check compactness.
Note that if $e_{1}\in \ell^{p}$ is the vector $e_{1}=(1,0,0,...)$, then defining $x_{n}=n e_{1}$ for all $n\in\mathbb{N}$ we get a sequence $(x_{n})_{n=1}^{\infty}\subseteq \ell^{p}$ with $\|x_{n}-x_{m}\|=|n-m|\geq 1$ for all $n\neq m$, so it can not have a convergent subsequence. Hence $\ell^{p}$ is not compact. This same argument can be used for any norm space with a non zero vector.
Regarding the follow up question: $\ell^{p}$ is separable. The subset of $\ell^{p}$ consisting of all sequences with finitely many non-zero rational elements is countable and dense. Note however that $\ell^{\infty}$ is not separable. You can for example consider the set of all the characteristic functions on $2^{\mathbb{N}}$. On each element of this subset you can draw an open ball so that all these balls are disjoint, and note that $2^{\mathbb{N}}$ is uncountable.

Are $l^p$ spaces compact?


Is it a good idea to create fomulas for chords and secondary dominants?

Question: For example say I'm analyzing the piece and I'm using C major as a reference
and I realize that the composer plays a dominant chord 3rd inversion
Can I think of the dominant is 5-7-2-4 as well as keeping in mind that 5 is the root note of the dominant chord and 3 is the 7th of the dominant chord? if I want to figure out the 3rd inversion I see that the 7 and the 1 always appear in the same order and it is at the bottom  so the shape of dominant chord 3rd inversion is (7(leading )tone-1(root)-3(major third)-5(fifth))*and also keep track of leading, root, maj 3 and fifth for all inversions
I can do this with secondary dominants as well like the V/IV is 1-3-5-b7. This way if I know the scale degree by heart, I can easily find my way through the key
I can also do it like this, were going to take the same chord.
I can think of the dominant of as a change in key, so instead of thinking in C major, I think of G major 7th 1-3-5-b7 instead of 5-7-2-b4 but that means I have to have already memorize the scale degree of D major as well as all the other scales.
for now since I want to know the patterns after i memorize the scale degrees of the scales I can immediately apply the patterns in that scale
let me know if you guys need more clarification
Answer: You seem to be overthinking all of it!
The way I look at this is that each chord has its own dominant 7th, which is the dominant of that chord - the V of the chord I. So, looking at, say, Amaj. The dominant is going to be E7 (having only notes that belong to A).
The big difference with V7 chords is that they contain a note which is not in their own key. It's the b7, which needs to be flattened from its own key in order to make it a dominant 7th.
Example - in C. Dominant of C > G7. G B D F all notes belonging to key C. When Cdom7 arrives, it has the notes belonging to F: C E G Bb. I only ever think 1,3,5,b7 of the chord itself, because the rest is irrelevant. If I start thinking 5,7,2,4, I just mess up. Stick with the root of the chord in question as being called 1. Otherwise, you'll likely get number-bound.
Comment: " Stick with the root of the chord in question as being called 1." - the other historical option was to call the bass note of the chord 1. That gave 7-5-3 for root position, 6-5-3  for first inversion, 6-4-3 for second, and 6-4-2 for third. Figured bass notation conventionally abbreviated those to 7, 6-5, 4-3, and 4-2. if the OP wants "a system based on intervals," he/she might as well learn something that some musicians still actually use, and is included in some advanced music theory exams - e.g. ABRSM.
Comment: @alephzero - yes, that works for some, though I have never found use for it. I think the OP is already confused, so I tried to simplify the situation. Using figured bass at the OP's level may cause explosion of the brain! Perhaps save figured bass till it's needed in an advanced theory exam?
Comment: In my Royal Conservatory of Music Harmony lessons, inversions like V 4/3 were introduced in Grade 3 Harmony (above Grade 2 Theory, but Grade 2 Theory still taught pretty basic stuff). At least according to RCM, figured bass is not an "advanced theory" concept--maybe intermediate at most.


Why does the Node reference module search only for node titles?

Question: I have two content types: Type A and Type B. Type A has 3 fields: title, location, and zip code.
I want to get references to Type A in a field for Type B. I have tried using the Node reference and the Entity reference modules, but they allow only to get options in autocomplete when I write the title of a Type A node. I want to get a list of all the Type A nodes with the zip code entered in the field.
Comment: if anybody can help me then please help me friends as it is very important for me
Answer: You should  use tokens and autonodetitle modules.
After enabling tokens and automatic node title , go to Stucture->content types -> edit (type A) content type. If you scroll below you will see an option Automatic title generation . Click on 'automatic title generation' you will see an Pattern for the title and list of options containing token list
like curent user, current date, current page, node , random etc.
Click on node and find the token related to node Type A.Like for the field location and field zip there will be token similar to this [node:field-zip],[node:field-location]
add this into pattern for title field. Now you can check the Type B autocomplete entity reference field for type A . you will find that as title is changed the entity reference field has location and zip in the title.
Comment: Hi friend Thanks for your help, i tried each step mention in your answer but the main problem is that it changes the title of the node. i don't want to change the title. i just want that when i take refernce of this content type then it populate titles of referenced node based on another field. like zipcode is a filed in the another content type. if i enter zipcode 92980 then there is a field for autopopulate where i need titles which have the zipcode 92980. there are many nodes with same zipcode , i want these nodes to be populate. thanks in advance for help. please help me
Answer: Text or Nodereference this module may solve your issue

It simply adds a new widget and a new formatter for the text fields
  provided by the great text.module from the CCK project.
The widget has autocompleting on both the existing field data and any existing node
  titles (you may want to filter this on specific content type(s),
  though, which is possible.) The formatter checks if a node exists with
  the title that is stored to the textfield, then it is displayed as a
  link to that node (if that textfield's widget is limited for any
  content type(s), then the target node must be one of the specified
  content type's, though).
Comment: source http://drupal.stackexchange.com/questions/49186/autopopulate-a-different-field-if-node-reference-autocomplete-doesnt-have-a-mat
Comment: thanks Bala for your answer but it is not solving my problem
Answer: The main issue here is that the node reference widget has no idea of the zip code field because it hasn't been submitted into the database yet.  Yes, you have typed information into it, but until the form is submitted, it's still just out there with the client.
What you will probably have to do is code up some custom AJAX/AHAH for your form to look when your user has entered information into the zip code field, then pass that to drupal and then have drupal return your node information based upon that filter (See Views) and either repopulate or initially populate a drop down list of nodes.
Lots of information on this can be found in the Drupal Form API Reference and most probably some code examples in the aptly titled Examples Module.
Side note:  If these were all node references, you could also investigate the Hierarchical Select Module.


Proof of orthogonality using tensor notation

Question: Suppose $\textbf{A}$ is radial. Prove that $\operatorname{rot}\textbf{A}$ is a vector orthogonal to $\textbf{A}$. First show that $\varepsilon_{ijk}k_jk_k=0$.
I have no problem showing the second part but I don't know how to use it in the proof.
I want to prove the orthogonality with scalar product so I should obtain 0 from the equation. So far I have:
$$\boldsymbol{\nabla}\times\textbf{A}\ \cdot \ \textbf{A} = \hat{e_i}a_i(\varepsilon_{jkl}\hat{e_j}\frac{\partial}{\partial x_k}a_l)=\delta_{ij}\varepsilon_{jkl}\frac{\partial}{\partial x_k}a_la_i$$
I don't know what to do after this so that I use the shown property.
Comment: This is false in general, e.g. take $A=x_2\hat{e}_1+x_3\hat{e}_2+x_1\hat{e}_3$. Perhaps you're meant to add another assumption, e.g. that $A_i$ is a function of $x_i$ alone... although that would prove something even stronger, $\boldsymbol{\nabla}\times\mathbf{A}=\mathbf{0}$. How about $\mathbf{A}$ being radial?
Comment: The only assumption in the exercise is that $\textbf{A}(\textbf{r})$ is in constant direction. I don't know if this is crucial to the problem.
Comment: Always mention every assumption! I've edited your question to include it.
Comment: Ah, thank you! I'll remember that. I didn't even know what radial means... We have yet to cover that druing the lectures but it's already on the list of problems. Classic, I guess. Once again, thank you very much!
Comment: Radial means parallel to $\sum_ix_i\hat{e}_i$.
Answer: Write $A_i=fx_i$ so$$A_j\varepsilon_{jkl}\partial_kA_l=fx_j\varepsilon_{jkl}\partial_k(fx_l)=f\underbrace{x_jx_l\varepsilon_{jkl}}_{0}\partial_kf+f^2x_j\underbrace{\varepsilon_{jkl}\partial_kx_l}_{\varepsilon_{jkl}\delta_{kl}=0}.$$


Kernel and image of composition of maps.

Question: Let $V$ be a vector space. Let $f:V \to V, g:V\to V$ be linear and bijective maps such that $f \circ g = \operatorname{id}_V$ (identity mapping). Show that:
a) $\ker(f) = \ker(f\circ g)$.
b) $\operatorname{Im}(g) = \operatorname{Im}(g \circ f)$
I'm not sure where to start and what strategy to use. Please help to guide me.
Thanks.
Answer: Both $f$ and $f \circ g$ are linear bijective maps (composition of linear maps is linear) so they have trivial kernel. This shows a).
For b), the right inverse of a linear bijective map (isomorphism in the category of vector spaces) is also its left inverse. So $g \circ f = \operatorname{id}_V$. So $g$ and $g \circ f$ are both linear bijective maps, which shows that both their images is whole $V$.
Answer: Usually when you want to show that two things are equal one way to do it is show that they are contained in on another, for example in your case show that $\ker(f)\subseteq \ker(f\circ g)$ and $\ker(f\circ g)\subseteq \ker(f)$.  Also in you case it is really easy to see what are the kernel of these maps since you know $f\circ g =\operatorname{id}_V$, so the kernel must be trivial.
Comment: No problem, By definition of bijection you have that the function is injective and since you are working with a linear map that is equivalent to a trivial kernel.
Comment: Thank you! Sorry if that seems dumb, but how do you go from bijection to the fact that the kernel is trivial?


Run QEMU command with cron

Question: I have a machine that, aside of other services, needs to run a server VM. I'm running the VM with:
qemu-system-x86_64 -nographic \
    -enable-kvm \
    -m 8G \
    -smp 2 \
    -hda gw_disk.qcow2

This is on a script start.sh and then I have on the root crontab (sudo crontab -e):
@reboot cd /disk/folder && setsid ./start.sh
After reboot I look at /var/log/syslog and I get this:
(CRON) INFO (Running @reboot jobs)
(root) CMD (cd /disk/folder && setsid ./start.sh)
(CRON) info (No MTA installed, discarding output)

I can't find the process with ps -o pid,sess,cmd afx | grep qemu
Any idea what I'am missing?
Thanks
Answer: Several things jump out at me here

Consider installing libvirt with its virsh, or something similar, so that you have a management layer around your VM

Capture the output of your crontab entry. It's telling you there's output but that it can't email it to you ("info (No MTA installed, discarding output)"). You can either write it to the system logger or directly to a file:
# Direct to a logfile (remember to rotate/truncate it periodically)
@reboot ( echo "Starting: $(date)"; cd /disk/folder && setsid ./start.sh ) >>/var/log/startvm.log 2>&1

# To the logger subsystem (usually ends up in /var/log/user.log)
@reboot ( cd /disk/folder && setsid ./start.sh ) 2>&1 | logger -t startvm

Consider using a systemd unit to start the process rather than a boot-time crontab entry. Initially more complicated, certainly, but easier to maintain once you have it and with better logging and failure reporting
References:

Use systemd to Start a Linux Service at Boot on Akamai/Linode
How do I run a single command at startup using systemd? on Ask Ubuntu

Run QEMU command with cron


Bias of MLE scales with $1/N$?

Question: I was reading this paper (link) and it gave me some confusion.
$P(r|\theta)$ is a distribution that generates sample $r$ based on some Poisson distribution, whose mean and variance are defined as some function $f(\theta)$, e.g. $\cos(\theta)$. Given some samples of $r$, we want to find MLE of $\theta$.
In "ML Estimation" section (page 2) of the paper, it says

... This is in contrast to the bias of the ML estimate,
which is of the order of 1/N.

I am not sure why this is the case. The mean estimate using MLE is unbiased, and I know the variance has a bias and it scales with $1/N$. But I am not sure why in this context, the bias of $\theta$ scales with $1/N$.
Answer: First, statements like this about order are typically one-sided. So they're saying the bias of the MLE is no more than a multiple of $1/N$. It's sometimes zero.
The statement is also a bit imprecise in other ways.  It's quite possible for the MLE not to have a mean and so not to have a finite bias. On example is the MLE of the odds ratio in a 2x2 table, which is infinite if one of the diagonal cells is zero. There's a non-zero probability of having a zero on the diagonal (very small, usually, but non-zero) so the MLE is infinite with non-zero probability and so has no finite mean.  It would be more precise to define an asymptotic bias and say that was of order $1/N$

Bias of MLE scales with $1/N$?


Prove: the radius of convergence of the series $\sum_{k=1}^{\infty}a_kx^{n_k}$ is $R^L$.

Question:
Let $\sum_{n=1}^{\infty}a_nx^n$ be a power series with a radius of
convergence $0<R<\infty$ and let $\left \{ n_k \right \}_{k=1}^\infty$
be a strictly monotonically increasing sequence of natural numbers,
such that the limit $L=\lim_{k\to\infty}\frac{k}{n_k}$ exists.
Prove: the radius of convergence of the series $\sum_{k=1}^{\infty}a_kx^{n_k}$ is $R^L$.

My attempt:
$$  a_k \;=\;
\begin{cases}
a_{n_k},  & \text{$k = n_k$} \\
0, & \text{else}
\end{cases}$$
$$  \sqrt[k]{|a_k|} \;=\;
\begin{cases}
|a_{n_k}|^\frac{1}{k},  & \text{$k = n_k$} \\
0, & \text{else}
\end{cases}$$
$$\lim_{k \to \infty}{|a_{n_k}|^{\frac{1}{k}}} \;=\; \lim_{k \to \infty}{|a_{n_k}|^{\frac{1}{Ln_k}}} \;=\;\; ?$$
Answer: We are given that
$$ \limsup_{n\to\infty}\sqrt[n]{|a_n|}=\frac1R$$
Letting $$b_n=\begin{cases}a_{k},&n=n_k\text{ for some }k\\0,&\text{otherwise}\end{cases} $$
(I'm avoiding confusion between the coefficients here)
we want to show that
$$ \limsup_{n\to\infty}\sqrt[n]{|b_n|}=\frac1{R^L}.$$
We do so by showing two things:

If $c>\frac1{R^L}$, then there are at most finitely many $n$ with $\sqrt[n]{|b_n|}>c$.
And if $c<\frac1{R^L}$, then there are infinitely many $n$ with $\sqrt[n]{|b_n|}>c$

Note that $\sqrt[n]{|b_n|}>c>0$ means $|b_n|>c^n$. This can happen only if $n=n_k$ for some $k$, and then is equivalent to $|a_k|>c^n$.
Now if $c=\frac q{R^L}$ with $q>1$, then
$$c^n=\frac {q^n}{R^{Ln}} $$
Given $\epsilon>0$, we know that $|L-\frac kn|<\epsilon$ for almost all $n$ and matching $k$, thus $|Ln-k|<k\epsilon$ and
$$\sqrt[k]{|a_k|}>\sqrt[k]{c^n}=\sqrt[k]{\frac{(q^{1/L})^{nL}}{R^{nL}}}>\sqrt[k]{\frac{(q^{1/L})^k(q^{1/L})^{-k\epsilon}}{R^kR^{k\epsilon}}} =\frac1R\cdot \frac{q^{1/L}}{R^\epsilon q^{\epsilon/L}}$$
If we pick $\epsilon$ small enough, the last factor will be $>1$, hence this inequality can hold at most for finitely many $k$, and so $\sqrt[n]{|b_n|}>c$ only for finitely many $n$.
On the other hand, if $c=\frac q{R^L}$ with $0<q<1$, we find by a similar argumentation that, given $\epsilon>0$,
$$\sqrt[k]{c^n}<\frac 1R\cdot q^{1/L}R^\epsilon q^{\epsilon/L} $$
for almost all $k$ and $n=n_k$.
If $\epsilon$ is small enough, the right hand side is $<\frac 1R$, hence
 $\sqrt[k]{|a_k|}>\frac 1R\cdot q^{1/L}R^\epsilon q^{\epsilon/L}$ for infinitely many $k$, hence $\sqrt[n]{|b_n|}>c$ for infinitely many $n$.


How to change field setting using on some condition based?

Question: I want to change image property like resolution based on other field.Like I have a field that tells how the image will be shown. If I select a large image then minimum image resolution have to change higher.
There is no option to do it with conditional field. So Is there any other way?
Comment: I'm afraid there is not, but if you have like 4 available display settings, why don't you just add 4 fields, each wit one? And then just use dropdown field to select which one is supposed to be shown?
Comment: Ya that is a good idea but I have to change most of the things that I already done. So I want to change only  setting. If there is any module or anything?
Answer: It looks like you are looking for Formatter Field:

The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.

Emphasis mine.
Comment: Does this module will checks validation for minimum resolution of images.
Comment: @SumitMadan if you will require minimum resolution and prevent upscaling in your formats, it should.
Comment: Prevent upscaling only controls the image cache I think not the validation of resolution.
Comment: @SumitMadan well, right. See if it would allow you to save node if Allow Upscaling is false and image is to small. I'm sure it will not or there is a module that will prevent it - either way I've seen it work even if I can't recall all the pieces now.
Comment: ok I am testing it.
Comment: naah, It doesn't meet my requiments. It is not validating the image resultion.
Comment: @SumitMadan Sorry to hear that. You may need to write your own module for that, in this case. Unless I can find the one I was using, but I don't work for that site any longer so it might not be easy.
Comment: ok sure. thanks. Could you mail me the attachment if you found that?
Comment: If I'll find it, I'll either post a link or code here.
Answer: Checked my condition pragmatically in hook_node_validate function.


Is there such thing as a secondary dominant (or 2-5) of the 7th degree?

Question: Specially in jazz, it is common to approach a chord that is not the root by its diatonic 2-5, or simply its 5 (secondary dominant). When approaching a minor, it will be a ii7b5 - V7, and, in major, a ii7 V7. My question is, is there such thing as a secondary dominant of the 7th degree, specially a 2-5 of 7?
If so, what quality of 2 and 5 will it be since the chord being approached is not a major nor a minor, but a half diminished?
Answer: In this video:

Jens Larsen says "I actually don't know of any songs that have a cadence to the seventh degree, but if I was to add a cadence to that one I would say [the half diminished chord] is a minor chord, and then I would make a minor cadence. So that [would be] C# half diminished to F#7 to B half-diminished."
I think he's got a good idea. It makes sense to me because if we think about a half-diminished chord as sounding like a chord built on the seventh degree of the major scale, then the "ii" of that chord would seem to be a major 7th chord one half-step above, the Imaj7 chord. But a half-step up isn't really a ii because it's not a 5th above the V/vii. If we raise the root only of the Imaj7 chord and keep the other notes diatonic, then we get a half-diminished 7th chord as our "ii" chord.
It's a hack, but if you really wanted to add a ii-V in front of a half diminished chord, this is probably the best way to do it. You could also try a fully diminished 7th chord for the "ii" chord.
All that said, I think what the other answers are getting at is no matter what you play in front of a half-diminished chord, it's never going to sound like a ii - V - i progression, because the quality of the final chord is going to change the sound enough that it will end up in its own sonic territory.
Answer: In your first sentence I think you meant to say "tonic", not "root".
Taking the ii chord out of the equation for now, a secondary dominant chord is typically a dominant chord resolving down a 5th to a chord other than I or i. If using 7th chords secondary dominants are all non-diatonic to the original key and can use any chord as their target, including the chord built on the 7th degree in either major or minor. However the chord built on the 7th degree in major does not work well as a target chord because of its dissonance. It is better not to think of secondary dominants as diatonic to the scale degree they are approaching, but rather simply a 7th chord resolving to a non-tonic chord such as V7/ii, V7/iii, etc. the reason for this is because it is usually a fleeting moment in a progression and not actually a modulation.
The iim7 or iim7b5 is not a part of a secondary dominant. However it can be added before a secondary dominant in a chord progression if desired. It is more common to use iim7b5 going to a minor chord and ii7 when going to major but there are many instances of the opposite being done. It is up to the composer or arranger to use the one of their preference when creating a chord progression.
Comment: I understand what you mean, and don't want to quibble, but `V` resolving to `vi` is not  resolving to `I` or `i`, but it is not a secondary dominant. Even if a dominant doesn't resolve to a tonic, we still need to theoretically relate it to a tonic. If that tonic isn't the prevailing tonic, then the dominant is secondary.
Comment: @MichaelCurtis If what I wrote is unclear please point it out but I did not refer to V resolving to vi, or to the diatonic V at all.  In the context of my answer that would be V7/vi-vi, i.e. E7-Am in the key of C.
Comment: "a secondary dominant chord is simply a dominant chord resolving to a chord other than I or i"
Comment: `V vi` is a dominant resolving to a chord other that `I` or `i`, but it is not a secondary dominant.
Comment: "...any chord as their target, including the chord built on the 7th degree in either major or minor." So what chord specifically would be the dominant to `viio` in major?
Comment: @MichaelCurtis Yes. I pointed out that even though it is possible viio is not a good choice for a target chord because of its dissonant quality.
Comment: _a secondary dominant chord is simply a dominant chord resolving down a 5th_ – Now you're suggesting that a secondary dominant cannot resolve deceptively.
Comment: I think it's very important that _fifth_ be specified as a _perfect fifth_ both in the root relationships and the internal structure or the tonic/dominant chords. It gets to the crux of what is tonal and what is not.
Comment: @MichaelCurtis A 5th is commonly understood to be a P5 unless labeled dim or aug.
Comment: I suppose, but in this discussion the quality of the fifth is unclear because the of the diatonic descending diminished fifth to vii and the perfect fifth of the dominant relationship.
Answer: When you bring up II V I and secondary dominant, it muddies the waters...

ii7 V7 I in major
ii7b5 V7 I in minor

...neither of those progression involves a secondary dominant, both are diatonic for their respective modes.
Both of those progression can be called "roots by descending fifths"
Diatonically, roots by descending fifths to the seventh scale degree would be...

I IV viio in major
i iv ♭VII in minor

I see another problem in the wording of the question, because this, "secondary dominant", does not change in meaning, because of this "specially in jazz".
A dominant is a dominant, and it is a concept from the major/minor harmony system, where tonics are major or minor triads, and their dominants are major chords rooted a perfect fifth above the tonic root. Secondary dominant are dominants to any major/minor triads that are not the prevailing tonic. In the major/minor system a diminished triad can't be a tonic so there is no dominant to relate to that non-tonic chord.
Essentially, secondary dominants follow the function of diatonic harmony, the only difference is a temporary change of the tonic.
The two main thing jazz introduces to the tonic/dominant concept are:

extending the tonic chord with sevenths, sixths, etc.
tritone substitution of the dominant

...otherwise the basic tonic triad in jazz is still a major or minor triad.
You can look into people working with locrian harmony in jazz, where the "tonic" would be the diminished triad, but IMO it makes more sense to think of that as a kind of modal harmony and not a flavor of the major/minor system.
Ah, I overlooked the obvious: in minor ♭VII can have secondary dominant IV7 or V7/♭VII so the II V I to the seventh scale degree, in minor, would be i IV7 ♭VII. Of course that doesn't end on a diminished chord, so I think this isn't really what you are asking about.
Comment: I'm not sure but I think current teaching in jazz theory is a bit different from this. I'll have to check my notes.
Comment: You can (ii) V7 (almost) any chord in jazz, and when you do, the V7 you use is often dominant even when that dominant chord is not diatonic, so the concept of secondary dominants, AKA "applied chords" is relevant to jazz. Even if the V7 in a progression is diatonic to the key of the song or the key of the moment, it can sometimes be lumped in with all the applied V7 chords or applied ii V7 chord pairs. See https://viva.pressbooks.pub/openmusictheory/chapter/ii-v-i/
Comment: Sure, you can modulate to/tonicize something like `♭II` a chord not diatonic to the current key, but that new tonic is still a major/minor triad base. But the point is those tonics will not be a diminished chord. I tweaked my sentence to clarify that.
Comment: What is it you want me to see in that linked site? Is there an example of a purported dominant to a diminished chord?
Comment: I don't totally agree with your first sentence. I also feel like I've seen a specific ii - V - i° progression that would answer this question but I can't find it right now.
Comment: That example, in a real song, where that RNA is aurally justified, meaning the key really had been established, would be interesting to see. Speaking categorically that would be some kind of deceptive progression.
Comment: Ok, I found what I was thinking of. In [this video](https://youtu.be/0dpXtr_LdPg?t=300), Jens Larsen says "I actually don't know of any songs that have a cadence to the seventh degree, but if I was to add a cadence to that one I would say [the half diminished chord] is a minor chord, and then I would make a minor cadence. So that [would be] C# half diminished to F7 to B half-diminished." So you're right that it kind of doesn't make sense to talk about a "ii - V" tonicizing a half-diminished chord, but I feel like what Larsen suggests should be part of an answer to this question.
Answer: II - V - I a regular cadence with the subdominant being replaced by a functionally equivalent chord.
So then let us ask if there can be secondary tonality on the VII. First we see that clearly in minor this is significantly easier than in major, as VII in minor is a major chord, but in major it is a diminished chord. That one is considered as characteristic and will imply a dominant or a subdominant function, will thus be hard to be considered as a secondary tonality.
But in minor we have a slight similar problem: The natural 7th chord on the VII would be a dominant 7 and thus again imply a resolution. One can of course go by the mysterious ways of jazz and claim that dominant 7 chords do not imply a resolution, or one could alterate the 7th, so you'd sharpen the 6th of the original tonic.
The other question is how we can get a sort of dominant for the VII. This requires a leading tone, so a half step above and below. In minor this could only be that sharpened VI, in major this can only be I.
But obtaining that sharpened VI in minor is not much of a problem, as the minor mode allows for the raised VI as preparation for the raised VII. So we can then use I as a sort of secondary II or III as a secondary IV and thus do i - IV7 - VII. In fact this has the character of a common sequence used in baroque music, where you use repeated cadences, such as I - IV - VII - III - VI - II - V - I.
So what can be done in major? That diminished chord is somewhat of a problem, but we can have the major mode steal the #IV from the lydian mode to obtain an augmented 4th. This way we can spell the VII as a minor chord instead. Then the dominant here would be a sort of phrygian dominant, so bII - I (in terms of the tonic I - VII5#), so you can do something like iii - I - vii5#. Alternatively we can turn I into a I6 and interpret this as a neapolitan for VII, allowing us to do I6 - #IV - VII, although that one needs to borrow a few more notes.
Answer: You can certainly include viio   in a 'cycle of 5ths' type progression.   Whether you'd refer to the preceding chord as a 'secondary dominant' depends on how far you're prepared to stretch that definition!  I doubt viio is likely to be heard as a tonic, even the most temporary kind of one.   So my practical answer to "Is there such thing as a secondary dominant (or 2-5) of the 7th degree?" would have to be 'no'.
I would be delighted, however, to see a musical demonstration proving me wrong!  But let's see some actual music, the theoretical nit-picking has run its course I think!


homeomorphism from interval $[a,b]$ to $[0,1]\subset \mathbb{R}$

Question: I need to show that every interval $[a,b]$ is homeomorph to $[0,1]\subset \mathbb{R}$. I've found this answer but it only deals with open sets, and I need an answer that deals with closed sets.
Comment: @TokenToucan I think that the first sentence is clear ("homeomorph" should be homeomorphic, as far as I know).
Comment: The question you ask is about $[0,1]$ to $[a,b]$. The answer you link to goes from $(0,1)$ to $\mathbb R$, and your phrasing sounds like you want something from $[0,1]$ to $\mathbb R$ (which is not possible).
Answer: Why don't you linearly do it: interval length should be expaded/shrunk, and $a$ must map to $0$, so
$$f:[a,b] \longrightarrow [0,1]$$
$$\ \ \ \ \ \ \ \ \ x\longrightarrow \frac{x-a}{b-a}$$
?
It has a continuous inverse.
Answer: Consider $A=\{(x,0) \mid 0 \leq x \leq 1\}$ and $B = \{ (x,1) \mid a \leq x \leq b\}$. Then draw the line thru $(1,0)$ and $(b,1)$. This line intersects the vertical axis somewhere. Use straight lines from this intersection point to construct a homeomorphism of $[0,1]$ onto $[a,b]$.


Função de Ackerman - Python

Question: Bom, ainda estou aprendendo a programar em python e me deparei com exercício que não sei resolver.
Preciso escrever uma função que resolver a famosa função de Ackermann. Creio que não terei problemas com a sintaxe e a logica por traz da função em si, o problema e o calculo. Símbolos como "," e o próprio "A" me confundem. Se alguem souber como resolver ficaria grato.

PS: estou interessado em como se resolve a função , o código em python ficaria por minha conta.
Comment: Oi, Otávio, se precisar de ajuda no uso do site, tem a área de suporte [meta]. O site tem algumas regras bem específicas que a **[help]** esclarece muito bem, é só gastar um tempinho ali e depois partir pro abraço.
Comment: `A` é o nome da função. Se tem `A` na sua definição (corpo), isso significa que ela será chamada recursivamente em algumas situações. E a vírgula simplesmente separa os argumentos - essa função `A` recebe dois números como argumento (aqui denominados `m` e `n`) e retorna um único número, dado a definição. Está mais claro? Você entende o que é uma função recursiva? (seja na matemática, seja na programação)
Comment: Sim, uma função recursiva é aquela que chama a si mesmo no "corpo" da função , certo ? Sim esclareceu algumas dúvidas , então, se hipoteticamente eu tivesse um grupo (1,3) o A seria substituído pelos mesmos e multiplicariam a sentença entre "( )" seguinte ?
Comment: Não entendi o que você quis dizer. Se você tem um par `(1,3)` e quer aplicar a função `A`, i.e. `A(1,3)`, você estaria associando ao parâmetro `m` o valor `1` e ao parâmetro `n` o valor `3`. Pela definição, `m = 0` é falso e `m > 0 and n = 0` é falso, de modo que o valor da função nesses pontos seria `A(m - 1, A(m, n - 1))`. Substituindo os parâmetros pelos seus valores, temos `A(1 - 1, A(1, 3 - 1))` que é igual a `A(0, A(1, 2))`. Então você teria que calcular `A(1, 2)` - pelo mesmo processo - e usar seu valor para calcular `A(0, ...)` - também pelo mesmo processo.
Comment: P.S. Por favor, não use o espaço de respostas para fazer comentários a respeito da pergunta. Você sempre pode comentar nas suas próprias publicações (link "comentar" embaixo da pergunta/respostas) ou - se tiver informações adicionais para melhorar a pergunta - você também pode **editar** a pergunta (link "editar") com essas informações. Pedi a um moderador que convertesse sua resposta em comentário, ok?
Comment: Ah sim agora entendi :) muito obrigado pela ajuda e desculpa pela resposta, esse e meu primeiro post e não sei muito bem como funciona. Muito obrigado mesmo
Answer: Isso é uma função recursiva.
Você deve criar uma função ackerman que recebe dois parâmetros: m e n. Dentro dela, vai colocar uma sequência do tipo if... else if... else testando todos os três casos. Nos casos recursivos, deve returnar o valor de ackerman com os devidos parâmetros. No último else (que indica que algum dos parâmetros é negativo), lance uma exceção de parâmetros inválidos.
Answer: Aqui está a sua função! Esta função é a origem da função recursiva. Nela você tem que ter dois parametros que seguem aquelas regras que você passou na fórmula matemática, após isso, você pega os parametros e os roda afim de chegar nesta função:
#Função de Ackerman
calls = 0

def ackerman(m, n):
    global calls
    calls += 1
    if m == 0:
        return n + 1
    elif n == 0:
        return ackerman(m - 1, 1)
    else:
        return ackerman(m - 1, ackerman(m, n - 1))

print(ackerman(m,n))

Função de Ackerman - Python