MLE under Gaussian Noise

Question: $$Y_i = \theta + N_i\quad,\, i=1,\ldots,n\,,$$  where  $\theta$  is an unknown parameter and  $N_i$  are i.i.d Gaussian random variables with zero mean.
Would the ML estimator of  $\theta$  change if the  $N_i$ 's are independent Gaussians with possibly different variances  $\sigma^2_1,\ldots,\sigma^2_n$  but same zero mean? $\sigma^2_i$  are known constants.
Comment: Sounds like homework, so please use `[self-study]` tag and tell us how did you try solving it and what kind of help do you need?
Comment: Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for typesetting math.
Answer: The log-likelihood (with possibly different variances) is
     log(1,…,|,21,…,2)=−12∑=1log(22)−∑=1(−)222.
Note that here we cannot take  2  out of the summation. Thus, to solve this, we need to take the derivative of the log-likelihood with respect to    set it equal to zero.
Doing so, we obtain
     ∑2    =∑12,
which yields
     ̂=∑2∑12,
which is not necessarily the same estimator as before. That is, the sample average of   's is no longer the ML estimate of   .
Comment: It will be easier to read this answer if you use math typesetting. More information: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: Consider a simple processing of the outputs $Y_i's$ to obtain $R_i's$ as given by $R_i =Y_i/\sigma_i$. Now, $R_i's$ have the same variance for all $i$ though the mean is now $\frac{\Theta}{\sigma_i}$. If you write the likelihood function based on $R_i's$, the ML estimate for this problem boils down to
$$ arg\min_\limits{\Theta} \sum_{i=1}^{n}\left(R_i -\Theta/\sigma_i\right)^2$$.
Taking derivative w.r.t to $\Theta$, we get $$\Theta_{est}=\frac{\sum_{i}R_i/\sigma_i}{\sum_{i}1/\sigma_i^2}=\frac{\sum_{i}Y_i/\sigma_i^2}{\sum_{i}1/\sigma_i^2}$$.
Answer: $\theta$ won't change. By writing down the log likelihood function $L(\theta)$ and making $\partial L(\theta) / \partial \theta=0$, you'll get:$$\sum_i (\theta_i -y_i)/\sigma_i^2=0 \implies \frac{n}{\sum_i \sigma_i^2} \theta = \frac{\sum_i y_i}{\sum_i \sigma_i^2} \implies \theta = \frac{\sum_i y_i}{n}$$
Comment: The log-likelihood (with possibly different variances) is
   log(1,…,|,21,…,2)=−12∑=1log(22)−∑=1(−)222.
Note that here we cannot take  2  out of the summation. Thus, to solve this, we need to take the derivative of the log-likelihood with respect to    set it equal to zero.

Doing so, we obtain
   ∑2   =∑12,
which yields
   ̂=∑2∑12,
which is not necessarily the same estimator as before. That is, the sample average of   's is no longer the ML estimate of   .

MLE under Gaussian Noise


Frustrating Drupal perfomance

Question: i've started using Drupal few days ago and from the start i've noticed very slow page load, right after installation, i though it's normal and forgot for a while about this problem.
I am running Apache 2.2 and PHP 5.3 on local PC (Core2Duo 2.4, 3GB Ram)
with Drupal 7.14. I have tried using shared hosting (5% of some Xeon CPU, 256Mb Ram for PHP) - same problem, pages took ages to load, not to mention Admin pages loading for 3-5sec, sometimes - minutes. Sometimes UI and Pages are very good, sometimes it hangs for few seconds, minutes even. Always using Ctrl+R for page reload to skip caching on browser side.
Today I've installed Performance module and did the test on shared host with a little content on page and on blank installation of Drupal at local machine mentioned above.
Results on Local: http://s14.postimage.org/ij1isbh33/Drupal_7_Local_default.jpg
Results on Shared: http://s11.postimage.org/asjhasu29/Drupal_7_shared_content.jpg
On local - first time its default installation, second time logging disabled, caching everything, aggregation etc.
Therese a phpBB3 default running on shared and local - very responsive, no hangs, page loads in a few ms.
Also, the amount of Queries, is this normal for Drupal to have 30-200 Queries?
What could be the problem with this issue?
Comment: http://drupal.stackexchange.com/questions/724/why-is-drupal-7-so-slow might help
Comment: I've recently experienced a similar slowdown, as never before, and I could talk my host rep into installing drupal.org/project/memcache. After installing and configuring memcache in Drupal, the improvement was instant.
Comment: I have just tried Memcached with Drupal module, no performance boost on loading index page as seen on screenshot: http://s9.postimage.org/xz0kaxo71/Drupal7_local_memcached.jpg
Comment: Also, local site is fresh install, with default modules and Performance module installed. Issue with missing modules from installation doesn't apply :( Tried with Cron enabled/disabled - same results.
Answer: Things to try:
http://groups.drupal.org/node/242443
http://groups.drupal.org/node/210683
But in reality we don't know until you can profile the code.
http://getmuhammad.blogspot.com/2011/08/installing-xdebug-and-webgrind-on.html
Comment: Thanks, will install xdebug and webgrind today on local and post results. But cant install on shared hosting, don't have rights to do so :( The major problem is random hang up, for example sometimes page takes 3-10sec to load, even after 2-3-5 refreshes and sometime page opens fast (500ms). As for now, 500ms for content-free website is horrible :(
Comment: Theres a link to that site on shared hosting:
http://itship.ws/demo/site1/v1/
Comment: Just looking at your site it firebug I would blame your hosting. It took me 4.9 seconds to get a 304 response back. Doing a forced refresh took 1.5 seconds and that was a cache hit according to the http headers.

My recommendation is to get better hosting... at least from what I've seen here.

More info: http://www.webpagetest.org/result/120720_NR_NW2/
Answer: This is a known problem with MediaTemple's Grid Servers and supposedly doesn't happen with their "1 click installs" of Drupal. The issue is that Drupal's database queries are very very heavy, and their shared MySQL instance is underpowered.
Apparently the fix is to change the table type from INNODB to MyISAM for any tables who's name starts with "cache" or "variable".
Answer: Check your log, if the admin pages are taking awhile to load then it's likely a memory leak in one of the modules that are enabled.

Frustrating Drupal perfomance


webmin memory usage seems wrong

Question: I'll be looking through the list of Running Processes in webmin, and it seems like the memory usage for my applications is wrong.
For instance,
mysql   253956 kB   /usr/sbin/mysqld
Which would equal some 256+megabytes.
The problem with this, is it also reports that the ram on my server isn't used up, and there is only 256megabytes available.
From what I understand a capitol B = Bytes, and a lowercase b=bits.
I even wrote a program that runs on here that says it's using almost 200 MB of space, when there's no way that's possible.
Any idea why the numbers are way off? Or is it possible they mean kilobits, instead of kilobytes?
I'm running Ubuntu 11.04 server 64bit on RackSpace if that helps.
Thanks.
Comment: You sure that numbers are not the cashed memory ? Linux cashes memory and free's it up when needded.
Answer: It depends what reading it is using to pull that memory count from. Memory management in a modern OS is not nearly as simple as you might first expect it to be!
For instance if you take memory readings from top VIRT is almost always noticeably bigger than RES (see articles like this (search for top vert res shr) for more detailed discussion). It is most likely that webmin is reporting the virt value which includes memory shared with other processes (library code that is loaded into real memory only once but mapped into the virtual address spaces of multiple processes) and memory that is allocated but not yet used (it is available in the processes virtual address space, but no real RAM or swap pages have been allocated for it yet).
It may also be that some of the memory allocated to currently swapped out to disk, does the output of free indicate that any swap space in use?
From what I understand a capitol B = Bytes, and a lowercase b=bits.

Unfortunately while many people make that distinction when writing it isn't a "real" standard so can not be relied upon. Unless bits/bytes is explicitly stated you unfortunately need to use context to try conclude which is being intended. When reporting memory from the OS's point of view and formatted drive space B or b almost always refer to bytes not bits.
Comment: well it also shows me the swap space used/available...I'm thinking I agree with you about shared memory space being combind, as i'm not sure what command they are calling for there data...even if that's true though my MySql is using more ram than I have available, so even if it is shared, my ram should be maxed out.
After typing that I'm leaning more tword it being a typo in the gui.

webmin memory usage seems wrong


Como realizar a migração do spring security 3.0.5 para o 4.2.3

Question: Gostaria de saber como faço para passar do Spring Secuirty 3.0.5 para o 4.2.3
Meu xml:
    <?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Production</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>client</param-value>
    </context-param>
    <filter>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/root-context.xml
            /WEB-INF/spring/security.xml
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>

    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.faces</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>login.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

Meu root-context.xml:
 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                            http://www.springframework.org/schema/tx
                            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                        http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="de.slackspace.tutorials.customloginpage" />

</beans>

Meu xml do security:
<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
                                 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                                 http://www.springframework.org/schema/security
                                 http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <http auto-config="true" use-expressions="true" disable-url-rewriting="false">

        <intercept-url pattern="/View/UnSecured/**" access="permitAll" />
        <intercept-url pattern="/login" access="permitAll"/>
        <intercept-url pattern="/View/Secured/user/**" access="hasAnyRole('ROLE_ADMIN', 'ROLE_COMMON')"/>
        <intercept-url pattern="/View/Secured/adm/**" access="hasRole('ROLE_ADMIN')"/>
        <intercept-url pattern="/javax.faces.resource/**" access="permitAll"/>
        <intercept-url pattern="/img/**" access="permitAll" />
        <intercept-url pattern="/theme/**" access="permitAll" />
        <intercept-url pattern="Pacotes de Código-fonte/**" access="permitAll"/>

        <form-login always-use-default-target="true"
                    default-target-url="/View/Secured/user/index.jsf"
                    authentication-failure-url="/login.xhtml?error=true"
                    login-page="/login.jsf"/>

        <logout logout-success-url="/login.jsf" logout-url="/logout" />
    </http>

    <authentication-manager>
        <authentication-provider>

            <jdbc-user-service data-source-ref="dataSource"
                               users-by-username-query="xxxxxxxxx"
                               authorities-by-username-query="xxxxxxxx"
            />
        </authentication-provider>
    </authentication-manager>
    <beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
        <beans:property name="url" value="xxxxxxxxxxxxxxx" />
        <beans:property name="driverClassName" value="xxxxxxxxxx" />
        <beans:property name="xxxxxx" value="xxxxx" />
        <beans:property name="xxxxxx" value="xxxxx" />
    </beans:bean>

</beans:beans>

Meu servlet context:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"

    xsi:schemaLocation="
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <resources mapping="/resources/**" location="/resources/" />

    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

</beans:beans>

Minha classe de aplicação do spring:
package de.slackspace.tutorials.customloginpage;

import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.WebAttributes;

@ManagedBean(name="loginController")
@RequestScoped
public class LoginController implements PhaseListener {

     protected final Log logger = LogFactory.getLog(getClass());

    /**
     *
     * Redirects the login request directly to spring security check.
     * Leave this method as it is to properly support spring security.
     *
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String doLogin() throws ServletException, IOException {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();

        RequestDispatcher dispatcher = ((ServletRequest) context.getRequest())
                .getRequestDispatcher("/j_spring_security_check");

        dispatcher.forward((ServletRequest) context.getRequest(),
                (ServletResponse) context.getResponse());

        FacesContext.getCurrentInstance().responseComplete();

        return null;
    }

    public void afterPhase(PhaseEvent event) {
    }

    /* (non-Javadoc)
     * @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent)
     *
     * Do something before rendering phase.
     */
    public void beforePhase(PhaseEvent event) {
        Exception e = (Exception) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(
                WebAttributes.AUTHENTICATION_EXCEPTION);

        if (e instanceof BadCredentialsException) {
            logger.debug("Found exception in session map: "+e);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(
                    WebAttributes.AUTHENTICATION_EXCEPTION, null);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Username or password not valid.", "Username or password not valid"));
        }
    }

    /* (non-Javadoc)
     * @see javax.faces.event.PhaseListener#getPhaseId()
     *
     * In which phase you want to interfere?
     */
    public PhaseId getPhaseId() {
        return PhaseId.RENDER_RESPONSE;
    }
}

Answer: Primeiramente , eu não utilizaria mais o XML para configurar e sim anotações.
Segundo ao invés de utilizar o 4 já passe para o 5.
Crie um arquivo de configurações extendendo a classe WebSecurityConfigurerAdapter habilitando o springsecurety com a anotação @EnableWebSecurity.
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter  {

}

Com o método @Override public void configure(WebSecurity web) throws Exception você configura as exceções.
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter  {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
        .antMatchers("/layout/**")
        .antMatchers("/stylesheets/**")
        .antMatchers("/fonts/**")
        .antMatchers("/javascriptsgeral/**")
        .antMatchers("/images/**");
    }

}

Com o metodo @Override protected void configure(HttpSecurity http) throws Exception você faz as demais configurações.
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter  {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
        .antMatchers("/layout/**")
        .antMatchers("/stylesheets/**")
        .antMatchers("/fonts/**")
        .antMatchers("/javascriptsgeral/**")
        .antMatchers("/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("cadastro/novo").permitAll()
                .antMatchers("cadastroestoque/**").hasRole("USUARIO")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .and()
            .sessionManagement()
                .maximumSessions(10)
                .expiredUrl("/login")
                .and()
                .invalidSessionUrl("/login");
    }

}

Existem outras configurações dependendo com qual arquitetura estais utilizando. Se JSF, Spring MVC, Spring Boot....
Contudo espero ter lhe dado um inicio.
Comment: Vou tentar a migração, utilizando o anotações. Ja deu pra dar um norte mesmo.
Comment: Qualquer coisa posta ai


How do I replace [number] to {number - 1} using Regex in C#?

Question: I have string values like A, something happened [1], something else [2], whatever [3] and want to replace it to A, something happened {0}, something else {1}, whatever {2}.
So, basically replace [ with { and ] with } if there is a number between and then decrement the number between by one. Is this possible with Regex somehow?
So far I got this:
var text = "A, something happened [1], something else [2], whatever [3]";
var result = Regex.Replace(text, @"\[(\d+)\]", @"{$1}");
Console.Write(result);

However, this gives me A, something happened {1}, something else {2}, whatever {3}.
Is there an option to decrement the numbers by one?
Comment: [@Peter B](https://stackoverflow.com/users/1220550/peter-b): Thanks for the edit, I did some wrong typing there...
Answer: You may decrement the number in a match evaluator:
var text = "A, something happened [1], something else [2], whatever [3]";
var result = Regex.Replace(text, @"\[(\d+)\]", m => $"{{{int.Parse(m.Groups[1].Value)-1}}}");
Console.Write(result); // => A, something happened {0}, something else {1}, whatever {2}

See the C# demo
In case the number cannot be cast to int use int.TryParse:
var result = Regex.Replace(text, @"\[(\d+)\]", m =>
    int.TryParse(m.Groups[1].Value, out var number) ? $"{{{number - 1}}}" : m.Value);

For C# prior to C#7:
var result = Regex.Replace(text, @"\[(\d+)\]", m => {
         int number;
         if (int.TryParse(m.Groups[1].Value, out number))
         {
            return $"{{{number-1}}}";
         }
         else
         {
            return m.Value;
         }
    });

Comment: @FranzHuber23 If you want you may replace `int` with `long`, just make sure you use what works for your scenario best.
Comment: @FranzHuber23 Yeah, it will work starting with C#7, since the [`out` argument "can pass without its declaration and initialization"](https://social.technet.microsoft.com/wiki/contents/articles/37675.c-7-0-out-parameter.aspx).
Comment: I will try this. I guess, that's what I was looking for :)
Comment: [@Wiktor Stribiżew](https://stackoverflow.com/users/3832970/wiktor-stribi%C5%BCew) I put your code into one line like that: `var result = Regex.Replace(text, @"\[(\d+)\]", m => int.TryParse(m.Groups[1].Value, out var number) ? $"{{{number - 1}}}" : m.Value);`. Of course, if the value is a `long`, I can simply use the same with `long.TryParse`. Thank you for the fast reply.
Comment: [@Wiktor Stribiżew](https://stackoverflow.com/users/3832970/wiktor-stribi%C5%BCew) Thank you for the additional information, I did not really look for the C# version as I'm always using the latest features but it's good to notice this to  others.


Does the jquery autosuggest plugin allow you to enter your own values (not from the dropdown)?

Question: i really like this plugin but it seems to be a flaw in it that its missing the feature to be able to create you own tags on the fly (its restrict to choosing from the dropdown list).
is there any other plugin that supports this additional feature or does the autosuggest plugin have anyway of supporting entering my own tags.  I would rather not have 2 textboxes (1 for checking for existing items and one for entering new ones).
Comment: ooo - i'm not stalking you, honest. :). just want to add, that adding your own tag is easy (as per example below - tab key). however, you have to then figure a way to save that new tag. this unfortunately is where your skill as a developer has to kick in. there isn't a save method for the simple reason that the implementation detail is open and down to you to create. fwiw - in the space of an hour, i had all the basics running in both directions enough to convince me that this was a usable bit of kit. other than pasting my code, i'm not sure what else to suggest in support of this plugin...
Comment: jim - thanks for the feedback. i am not trying to get out of writing code but ultimately for something like tags, i would have thought this was a "101" feature as the vanilla use case is people having to create their own tags.. Tab key seems to work but this plugin doesn't work in IE6 so thats a showstopper for me.  Ultimatley i think i am going to write one that mimics SOF's tags functionality
Answer: It (the demo sample) let me enter a tag that wasn't part of the demo set of tags.

I've never used this plug-in, so I may be missing something with the underlying implementation.
I do know the jQuery UI AutoComplete widget supports this.  Here's the document link, and there's a good example on having multiple tags ("multiple values sample") that aren't part of a custom data set.  That was the sample that I learned from to build my page.
The downside with the jQuery UI widget is that a lot of the fancy styling is up to you.
Hope this helps!
Comment: what browser are you using.  I am not able to enter my own tag in the same example you are referring to. are you just typing something and hitting ENTER ??
Comment: Interesting.  I used Chrome for the screenshot I attached.  I typed my tag and hit the  key.  I just tried the site on IE8 and I get a javascript error when the page loads.  Maybe that's the problem.
Comment: In looking at the JS error I'm getting in IE8, looks like the site may just have jQuery referenced incorrectly.  (The jQuery.js library is throwing a 'blah is undefined' error.)  I doubt there's a problem with jQuery.  :)


RDWeb and RemoteApp: How to launch RemoteApp after RDWeb login?

Question: I have Windows Server 2012 R2 and RDWeb configured. If I login using RDWeb I can see my RemoteApp and I can launch it. What if I want to launch this RemoteApp automatically after login. How can I do it?
Answer: First, you have to configure SSO on your server.
I recommend to follow this tutorial : https://nedimmehic.org/2017/11/20/remote-desktop-services-2016-standard-deployment-part-4-rd-web-access-part4-sso-high-availability/
After this, you have to modify some GPO for activate autologon. This link can help you : https://www.sevenforums.com/tutorials/141937-remote-desktop-connection-automatic-log-allow-prevent.html
Enjoy !
Comment: Hi and welcome on serverfault. Can you please edit your answer and sum up important points of the tuturials? links can become obsolete, not the content of your answer.


Creating a database link from AWS EC2

Question: Our staging database is stored on Amazon Web Services EC2.  I'm trying to create a database link from the server to an external database because, unfortunately, there's data in another system that we have to join our tables with, and it has to stay there.
On my local I can create a linked database easily in SSMS.  But I can't do that for staging because AWS doesn't allow any users to have the sysadmin role.  Supposedly AWS lets you do some things through it that the sysadmin role can do, but I can't find a definitive list anywhere for that.
Is there anyway to created linked servers in AWS?
Comment: Are you using RDS, or SQL Server installed on your own EC2 instance?
Comment: I'm using SQL Server Management Studio on my computer and accessing the EC2 server/databases from there.
Comment: AWS didn't limit the permission and provide system role for your own ec2 instance. It is your responsible to make it work. In your case, mostly it is the firewall setting. Review and Work on `security group` and assign proper security group to that ec2 instance will fix your problem.
Answer: As per comment to your question, your issue is probably linked to network access.
See this question for a checklist of items to verify in terms of network connectivity :
Can not remote connect to RDS DB instance of AWS

Creating a database link from AWS EC2


Scripts in footer in Wordpress custom theme

Question: Hi i created a wordpress site, starting from one html template.
I installed a naked theme, and modified header.php, footer.php ect adding the specific part of the html theme.
Now i have installed one plugin but it seem no to work.
I discovered that the plugin script was missing in the footer, there were only the html theme scripts.
Is there a specific method for add the plugins scripts into the custom footer.php?
Thanks
Answer: wp_head(); to header.php and wp_footer(); to footer.php and plugins can load js or css when they need.


Can you do anything about the div soup?

Question: All the sites I have seen that build on drupal looks like it's hit by div soup. There are so many unused divs produced by the content and some templates I have looked on contribute more by adding even more terrible markup.
I know most people with some knowledge about drupal know about this issue. For instance, here is a dump from drupal.org:

So why does Drupal need all these divs? Is there any rational behind them or is it just a flawed design?
Is there anything that could be done with this issue or are there some plans to improve on all these divs? Maybe a module that remove the divs that are not required and append the class statements so that markup will look better?
Are there some modules or solution that tries to address this annoying issue?
Comment: It may not look pretty, but it allows for great flexibility. Personally I've found that most of the divs and classes generated have been useful at some stage
Comment: Usually, a table-less theme needs to use some container tags, to build content.
Comment: Making/using a custom theme or override themable output would be the only way. Personally, I made an HTML5 theme from scratch for a customer and am quite happy of the result because it drastically reduced the tags soup and even dynamic pages have a proper yet lightweight semantic, so it's possible to reduce the soup if you're willing to take the time to make a theme (or find one that you like).
Answer: This is the result of a flexible content management that tries to be everything to everyone. Adding more divs upon request would be difficult, so it provides everything anyone will ever need.
Every template can be overridden as you see fit. For an example of a theme that really clears out a lot of cruft, see Mothership.
Answer: If you want to output a particular page element without burying it in DIVs, you can always put the relevant tag or print render() statement inside a strip_tags() function. Admittedly, this is a bit of a kludge, but it works for many common cases.

Can you do anything about the div soup?


How to send hidden field value to db on webform submit

Question: I am using Drupal 7 webform api, have a created a field in my <code>_form_alter</code> hook in a custom module, but while on page load the hidden field contains the correct value, when I submit the form it does not save to the mysql table, and gives me an empty cell
<code>$form['State'] = array(
  '#type' => 'hidden',
  '#value' => 'Unread',
  '#attributes' => array('id' => array('stateform')),
);
</code>
How can I make it save to the mysql table on submit?
UPDATE:
<code>$form['State'] = array(
'#type' => 'hidden',
'#title' => t('Hidden'),
'#attributes' => array('id' => array('state')),
);
drupal_add_js(drupal_get_path('module','mymodule') . '/js/custom.js');
</code>
Comment: What code is in your submit function?
Comment: I do not have one, since am using webform's default submit function.
Answer: You also will need to write a hook_form_submit for your form. In the _form_submit() you will take the hidden value and store it where you like.
That is the simple answer for your question. If you provide more details there could be other ways of handling the data. What is your form action?
Comment: The hidden value should be configured to be "less secure" while creating the webform component.
Answer: You do not need any hooks to do this. You can simply create an element via the webform UI of type "hidden." and it will save when the webform is submitted.
Comment: From my updated post above, am now using a JS instead of `#value` to fill in the value in my hidden field. Again it is found in the _alter hook, but the above mentioned methods did not work for me. Unless am doing it all wrong here.

I am using webform's default submit actions here, which send the data to the `webform_submitted_data` table.
Comment: Did you try my suggestion? Allows you to get rid of all php code except for the 1 line that adds js. Which type of hidden field did you add? Don't use the "secure value" type as that is not alterable via js.
Answer: This value should be stored in
$form_state['values']
You can access that in your hook_form_submit.   It wouldn't hurt to do a drupal_set_message on $form_state['values'], so that you can see exactly what values are stored there.


How is it possible to filter either high or low frequencies of a single sine wave?

Question: I started learning music production. I created (or generated) a sine wave with the oscillator in FL Studio, but did not add any more sine waves into it (by turning the volume off for the two other oscillators;  the built-in synth in FL Studio has 3 oscillators in total). Then, I hold the key (it was the middle A) of my midi keyboard then adjusted EQ to see whether there would be any changes with the sound. Yes, the timbre (or the color -not sure about the terminology) changed.
The interesting thing is and the thing I don't understand is: the process with the electric guitar is logical because it is a 'real' instrument and it creates overtones; when someone adjust the treble-middle-bass knobs on the amp then the amp cut offs some frequencies. But in the aforementioned experiment, there was just a one, single sine wave and there was none overtones if I'm not mistaken. So, which frequencies were cut off by the EQ in the FL Studio? How did this happen?
To show the oscillator and EQ I use in FL I recorded my screen with the audio: https://streamable.com/9b3ifz
Comment: Are you sure the oscillator was only generating a sine wave? If it's truly a sine wave, EQ should only affect volume, not timbre.  (I don't know FL studio, but maybe add a screenshot to the question for those who do.)
Comment: There was most likely something either in the oscillator, EQ plug-in, or other processing that is done to all audio in DAWs that created overtones
Comment: That there are overtones present is clearly audible in the video. Whether they were added by the video encoding or were actually present in the DAW, I can't say. I think you're assuming that the "sine wave" waveform in the virtual synth oscillator is a perfect sine wave. There's no reason to believe that. More likely is that it's designed to imitate a "sine wave" produced by a real-world analog synth, and real-world systems are never perfect, therefore the sine wave would have to have "unintended" overtones to sound just like a real analog synth sine wave.
Comment: Thank you so much for the great -all of them-answers.
Answer: It is important to note that software synthesizers are not scientific software, instead they try to replicate the sound of "real" synthesizers, and often vintage analogue synthesizers at that. The waves they produce may be labelled "sine" or "square" or "triangle", but that doesn't mean that these waveforms will be mathematically perfect. It is the imperfections in the sound and slight variations in pitch that make a synthesizer sound like a musical instrument and not like a test device in a laboratory. I assume that the sine wave produced by FL Studio is trying hard not to sound like a straightforward sine wave, and that's what you're hearing when you filter it. Besides, the same thing is true for the filter; it may be adding things to the sound instead of only taking things away, in a way that is modelling the behaviour of filters in "real" synthesizers.
Answer: Looking at the posted video, your "sine wave" isn't a sine wave, see the image below. Those small deviations from the perfect sine represent higher frequency components which are audible.
I don't know why it happens. I hope it's not video compression artifact. Maybe it's some kind of jitter simulated by the virtual instrument, or aliasing, or some artifact added somewhere in FL – in any case this shouldn't happen in a well written system, unless it's intended.
The best for you would be to repeat this experiment by yourself – record the sound and look at the waveform. Perhaps display its frequency spectrum too. Try disabling or manipulating various dials you have available in FL and see if it changes. Try disabling the EQ... look for documentation, though I can't find anything obvious in https://www.image-line.com/fl-studio-learning/fl-studio-online-manual/html/plugins/3x%20Osc.htm except for mention of aliasing (which somehow seems unlike to me for such a big effect).
Answer: It's not possible, something went wrong with your experiment.
The audio from your video sounds extremely aliased, and it doesn't match your eq moves, so I will assume that this is entirely a video artifact and not actually what you are hearing.  If it is what you're hearing, something's gone terrible wrong between FL studio and your speakers.
The plugin 3xOsc runs in draft mode until you export your project*, and in draft mode, the sine waves generated are a bit less perfect than you might expect.  I recreated your experiment, and I have to treble boost about 20dB for the aliasing to be even a little audible on middle A, but if you have brighter speakers and younger ears you might hear the aliasing sooner.  Try the experiment again with the Sytrus "default" preset, which generates a much cleaner (although still not perfect) sine wave and compare your results.
In recreating your experiment, I also heard a significant amount of noise generated while moving the eq bands.  This is totally an artifact of how the software takes inputs, and you should ignore this.

*Even in render mode, 3x osc is quite aliased, and the sine waves are still not quite sines, though the newest version has an "HQ" mode which is fully anti-aliased.
Comment: @ToddWilcox double precision, which is a standard in computing gives at least 10⁻¹⁵ precision. For comparison 16 bit audio CD precision is worse than 10⁻⁵. And that's just about rounding precision, not aliasing. I understand aliasing might be an issue with square or sawtooth waves, which have many high frequency components, but a sine wave has none. There is nothing to alias. _Unless_ there is something else going on.
Comment: I assume you mean during my recreation of the experiment and not in the video.  I think it's aliasing because 1) It sounds *just like* aliasing. 2) The [3xosc software manual](https://www.image-line.com/fl-studio-learning/fl-studio-online-manual/html/plugins/3x%20Osc.htm) makes 3 mentions of aliasing
Comment: @user1079505: Quantization noise would occur without aliasing if instantaneous amplitudes were rounded to some value, *via process that was independent of sampling rate*.  Aliasing can occur if rounding errors occur in ways that "almost" repeat at some regular frequency.  Even simple amplitude quantization noise can introduce aliasing in sampled audio.  As a simple example, suppose one is using a sampling rate of 15,750Hz and is trying to produce a 1000Hz tone, but all voltages are quantized to be either +0.,5 or -0.5 volts [only two possible levels].  Then for the most part...
Comment: ...the wave should be +0.5 for eight cycles, then -0.5 for eight, etc. except that 250 times per second it would be necessary to replace what would be a run of eight with a run of seven instead.  One would thus end up with a sequence of 63 samples of which 32 were +0.5, then a sequence of 63 in which only 31 were +0.5, then a sequence of 63 samples where 32 are were +0.5, etc., thus yielding some an unwanted 250Hz component.
Comment: What makes you confident the artifacts are aliasing? One could think there's nothing simpler than generating a pure sine wave, what would cause aliasing?
Comment: @user1079505 Why would one think there could be nothing simpler than creating a perfect sine wave? Creating anything perfect sounds impossible to me, not simple.
Comment: @ToddWilcox not perfect, but precise enough. A simple task for a computer. Perhaps in this particular virtual instrument they cut every corner in order to gain processing efficiency? I don't know.
Comment: @user1079505 How precise is "precise enough"? In my experience, the human ear is often so sensitive and discerning that it's extremely difficult to fool. Can you make a sine wave "precise enough" that no human ears can detect any difference in sound if any overtone artifacts are filtered out? I wouldn't be at all surprised if the answer is "no".
Comment: @user1079505: Calculating a sine at every point is going to take a lot more CPU time than using a table that contains the sines of 256 discrete angles.  While a typical PC would have no trouble generating a single sine wave in real time, it's hardly uncommon to use dozens or even hundreds of audio plug-ins simultaneously.  For some tasks, 2% CPU utilization for a sine wave generator would be no problem, but for other tasks that could be way too much.
Comment: @supercat So you're suggesting that first an approximate sine is generated e.g. with the algorithm you describe, and then it is smoothed, and this is what "anti-aliasing" refers to in this context?
Comment: @user1079505: Suppose one is trying to generate A440 using a 256-step approximation, and a 44,100Hz sample rate.  Each waveform should be about 100.227 samples long, meaning that each sample should advance the waveform by about 2.5542 steps.  If the sound generator always outputs whichever of the 256 values is closest, then it will mostly alternate between advancing two steps and advancing three, but about once every nine samples there will be two triple advances in a row.
Comment: @supercat Right, but the distortion introduced this way is quantization noise, not aliasing.
Comment: @supercat Thanks, this example helps to understand it.
Answer: I like the screen recording of your session. What I hear is a pure sine. It sounds sharp and awful, due to lack of other spectral components ("overtones").
You can fiddle whatever you want with the filters, but the only effect is the loudness ("amplitude") of the single frequency sine signal. For example, turning the knob for high pass filter will not change the sound in terms of more or less high tones, because these are not present. Because such a filter also has some effect on other parts of the spectrum, the sine will be somewhat louder or weaker.
Regarding precision, other answers correctly emphasize that your "sine" is not an absolutely pure sine. There is a minute deviation from the pure sine leading to some harmonics. However, I would say that the deviation is very small.
Even if your sine is high quality, there is for example still a quantization effect, because your sine is build from a number of discrete steps, because you are using digital equipment. But this effect is also very minor because of high sample rate and lots of bits in the quantization.
My guess is that you will not be able to perceive the harmonic distortion, and that fiddling with filters will not change the sound perceivably.
Comment: I rewatched the video on another device to rule out playback issues on my end, and the sine still sounds very not-pure.  The deviation (in the video) is not small at all.  You should rewatch it on better speakers and compare the sound of the video to a better recording of a sine A.
Comment: @Edward Can FL Studio do a spectrum analysis of the output signal? Before I go through the trouble of hooking up the pc headphone output to my oscilloscope, which has an fft button
Comment: Yes.  If you click the oscilloscope at the top of FL studio, it switches to spectrum analysis.  You can't adjust anything about this display besides its size though, so I'd recommend a VST such as SPAN in the last effect slot of the master channel.
Comment: @Edward And? How big are the harmonics, in percent of the base frequency sine?
Comment: There are 2 frequency peaks at about -40dB from the sine, roughly, and more which are lower.  It might not sound like a lot, but when you have this degree of separation in frequency, it can be very easy to hear.
Comment: https://imgur.com/7b0JzbL
Answer: Disclaimer: I have never written a software synth app - so this answer is based on theory, not personal and practical experience.
FL, like any digital software, is incapable of producing a pure sine wave which is truly analog - having no discrete intermediate states. That is, a software synth will create a close approximation of a sine wave by creating first an ascending stair-step with very small steps very close together, and a variation of the duration of each step to simulate the rounded shape of a sine. No matter how close in appearance this is to an actual sine wave, it is actually a series of compounded square waves - each state building on or subtracting from the previous state. As such, it will have harmonic content, although much lower level than a square or sawtooth.
It might be possible to get an even closer approximation by using a bandpass filter set to sweep with the tonic - which would reduce the more distant frequencies, but would still allow some through. I wouldn't be surprised if this method is used by at least some software synths.
Comment: Digital audio usually consists of a series of samples at a constant rate. So if I asked some software to generate a sine wave, and that software used a 44,100 Hz sample rate, I'd expect to get a kind of stair-step where all the steps have the same duration (1/44000 s), but the _height_ of the steps varies. And I'd expect it to generate the best possible approximation of a sine wave right off the bat, so applying a bandpass filter wouldn't improve it.


Which is the optimum number of threads in a 2 core system to read and encrypt a file from HDD?

Question: Which is the optimum number of threads in a 2 core system, supposing that it has to:
1) read a file from HDD
2) encrypt the file by xor-ing its bytes with a secret key
3) transfer the encrypted file on a network
I think that 2) can be done in parallel, 3) can be done in parallel but as I understand 1) cannot be done in parallel, so the system has to use only 1 core to read the file into RAM, then 2) and 3) can be done using 2 cores. Am I correct?
Comment: As a rule of thumb number of cpu cores == number of threads.
Answer: See file reading is not a CPU bound process its IO bound process. So its handled directly by the DMA controllers only. Anyway all those file operations should be handled in single threaded only.
You can parallize the xoring operation after read the contents from the file by separate thread. Even you can place place your file junks in one queue and the multi-threaded x-oring thread will read the content from queue and do its operation and send the result back to the network. If you are using async socket channel then it wont block you so each x-oring thread could place its contents in that channel.
Thats it.


How to show a Hilbert matrix is invertible?

Question: I got the matrix for the standard inner product space on polynomial space $\mathbb{P}_n$  as
$$H_n=\begin{bmatrix}1&1/2&1/3&\cdots&1/(n+1)\\1/2&1/3&1/4&\cdots&1/(n+2)\\\cdots&\cdots&\cdots&\cdots&\cdots\\1/(n+1)&1/(n+2)&1/(n+3)&\cdots&1/(2n+1)\end{bmatrix}.$$
We know matrix representation of inner product is invertible. But I want to show explicitly that the obtained matrix is invertible. How to show that?
Comment: What exactly do you mean by "show explicitly"? Would it be enough to show that (in general) the matrix associated with an inner product is necessarily invertible?
Comment: without using the fact that the matrix representation of IP is invertible.
Comment: [Cauchy determinant](https://proofwiki.org/wiki/Value_of_Cauchy_Determinant) ?
Answer: Define $\langle.,,\rangle$ on $\mathbb{P}_n$ as
$$
\langle p(x), q(x)\rangle = \int_0^1 p(x)q(x)dx.
$$
It is easy to check that $\langle.,,\rangle$ is an inner product.
Notice that
$$
H_n=\begin{bmatrix}
\langle 1,1\rangle&\langle 1,x\rangle&\langle 1,x^2\rangle&\cdots&\langle 1,x^n\rangle\\
\langle x,1\rangle&\langle x,x\rangle&\langle x,x^2\rangle&\cdots&\langle x,x^n\rangle\\
\cdots&\cdots&\cdots&\cdots&\cdots\\
\langle x^n,1\rangle&\langle x^n,x\rangle&\langle x^n,x^2\rangle&\cdots&\langle x^n,x^n\rangle\\
\end{bmatrix}$$
is the Gram matrix of $1,x,x^2,\dots,x^n$ with $\langle.,,\rangle$. Now, determinant of a Gram matrix is non-zero if and only if the vectors whose inner products are used in its construction are linearly independent. However, $1,x,x^2,\dots,x^n$ is a basis of $\mathbb{P}_n$ and hence linearly independent. Therefore, $\det H_n\ne 0$ and so we conclude that $H_n$ is invertible.
Comment: This particular Gram matrix has a name: it is the [Hilbert matrix](https://en.wikipedia.org/wiki/Hilbert_matrix) ; it is well known in numerical analysis because its determinant is very close to $0$ even for moderate values of $n$, then is a good test for analysing stability of some algorithms.
Comment: Moreover, we know explicitly its determinant.
Comment: @JeanMarie Numerical analyst here -- good point, although what matters is not its determinant, but rather its condition number.
Answer: It suffices to show that the equation $H_nx = 0$ has the unique solution $x = 0$ (i.e. that its columns are linearly independent). So, suppose that $x = (x_1,\dots,x_{n}, x_{n+1})$ is such a solution. It follows that $x^T(H_n x) = 0$, which is to say that
\begin{align}
0 & = x^TH_n x = \sum_{i,j = 1}^{n+1} H_n[i,j] x_i x_j
\\ & = \sum_{i,j = 1}^{n+1}  x_i x_j \int_0^1 t^{i-1} t^{j-1}\, dt
\\ & = \int_0^1 \sum_{i,j = 1}^{n+1} x_ix_j \,t^{i-1}t^{j-1}\,dt
= \int_0^1 (x_1 + x_2 t + \cdots + x_{n+1} t^{n})^2\,dt.
\end{align}
This integral can only be zero if $x_1 + x_2 t + \cdots + x_n t^{n-1}$ is the zero-function over $[0,1]$ (in general, the integral of a continuous non-negative function over an interval is zero iff that function is identically zero). However, this only occurs if $x_1 = \cdots = x_n = 0$, which is to say that $x = 0$, which is what we wanted to show.
Comment: +1 It's worth noting that this is essentially the proof that Grammian matrices are positive semi-definite (see Adam Zalcman's answer) applied to this particular matrix.


VimL: capture output of `exec` command, inside a variable is possible?

Question: I have some bash scripts and I need to retrieve them output from a Vim script. Is it possible? If yes, how?
Answer: To execute an external command and capture its output in a Vim variable, use system():
:let hostname = system('hostname')

The command is invoked through the configured 'shell'; as long as your Bash script has a proper shebang line (#!/bin/bash), everything should be fine.
If you eventually want to insert the output into the current buffer, you can alternatively use :read !{cmd} directly:
:read !hostname

Answer: As an alternative approach, note that the default signature of the let statement is:
let {var} = {expr}

where the right hand side must be an expression. This means that  let cannot capture the output of an execute command. In other words, trying:
let {var} = {cmd}

will produce an error. A workaround is to use the redir command, which has the following syntax:
redir => {var}
{cmd}
redir end

Let's see how it works in practice. First trying:
let somevar = echo "The current locale settings are: " . v:lang

returns the error E15: Invalid expression. Now with:
redir => somevar
echo "The current locale settings are: " . v:lang
redir end

the error is gone and the variable was successfully allocated, which  is verified by printing its value:
echo somevar

with output:
The current locale settings are: en_US.UTF-8


What is the minimum amount of chord categories?

Question: This question is not about some kind of mathematical permutation of notes, but a perceptual categorization, mostly related to jazz and improvisation.
There's a video of Jacob Collier answering what was his favorite chord at the moment and it was the chord with the following voicing: F,D♭,A,B,E,G♯. It would be an F with ♯11, M7, ♯5, ♯9, but he says "it's basically an F major". Likewise, Rick Beato also categorizes augmented chords in the same group as major chords in some of his videos.
For these people, sometimes an augmented chord is not an important entity that deserves a new category. In some sense, it shares many features with the category "major chord", so it's inside the same group. I can think of some "fundamental" categories: major, minor, dominant, diminished. (could a half-diminished always be seen as an inversion of a minor?)
How do you approach this type of categorization? In what sense an augmented chord IS a major chord? What is it being taken into account?

EDIT
Just some thoughts:
It's possible to see the existence of accessory/embellishment notes in some chords. CM7, CM13, C6add9 or even CM♯11 can be seen as C triads with cherries on top. They are treated in similar ways when improvising. Also, Cm7, Cm9, Cm(M7) are treated in a similar fashion (sometimes musicians even play the 7M over a Cm7 and vice-versa and it can sound good). On the other hand, the addition of a minor 7th on a C makes it fundamentally different from a CM7. You don't land on a 7M over a dominant chord. The C7 behaves and carries different expectations than the CM7.
Some categories might also be hidden inside others in another way. All possible triads can be mathematically defined, but the chord with the notes C-F♯-G for example, (which could be called a "lydian triad") is heard as something major in the lydian world. The ear gravitates towards the perfect fifth (it's not a diminished thing with an added perfect 5th, but a triad with a perfect 5th and an added ♯4), and it fills a major third. It's not exactly a new entity.
In this sense, I would have the categories: minor, major, dominant, diminished. And I'd have some doubts about half-diminished and augmented. A better systematization of my thoughts is needed and it might have limited application, but I'm interested in hearing other definitions and opinions.
Comment: I'm personally a little skeptical of saying that augmented chords are "in the same group" as major chords. It's like saying a square is "basically a triangle," no?
Comment: It's like a trapezium is "basically a rectangle"
Comment: @AllanFelipe you may want to try sending a message to Jacob Collier and/or Rick Beato asking what they mean by this. They might respond or make a video about this topic. Clearly, they think of these chords differently than the members of this forum.
Comment: Yes, that's right, but the "in some sense" fix this. With this expression, the mentioned geometric analogies can be made correct, for example: In some sense, a trapezium is a rectangle (they both have 4 sides). Yes, you lose the fine-grained categorization, but if you are only looking for "things with 4 sides" this coarse grouping can be useful.
Comment: to make the analogy - chord inversions might be like the types of quadrilaterals. @Richards point is to say that _musically_ comparing a augmented chord to a major chord as the same category is like calling a triangle and square with one side missing!.That might be true is some sense, but it overlooks an obvious fundamental!
Comment: that fundamental being there are four permutations of stacking two third and those are the four chords making up the category called "Triads." Anything else is failing to understand the category.
Comment: @Peter not a bad idea :) I'll add a little brainstorming in the post later.
Comment: this is just a normal E major chord above (or over?) an  F+5 (augmented 5th). but we can make it  a little more complicated notating C# as an Db.
to me it doesn't make sense as long I don't know in what context it is used  and how to solutions of the tones will be..
Answer: I'm not sure exactly what point these Youtubers are trying to make, but sometimes chords can be categorized by their function. This generally breaks down into three functions: Tonic, dominant, and pre-dominant
When categorizing them this way, we have to consider the music around the chord to decide how it works with the other chords that come before and after it.
Tonic chords are ones that offer a sense of resolution and don't want to pull somewhere else, while dominant chords contain tension that leads back to the tonic. Pre-dominant chords have some harmonic tension, but do not pull clearly back to the tonic.
So, I think the idea that Collier and Beato are trying to get across is that augmented chords can act in a tonic function.
Comment: And augmented chords often function as dominants, as well!
Comment: Both minor and major chords can be tonic chords and they are definitely in different categories, so I believe the idea of function might not be the main feature to look for in this situation.
Comment: @MichaelCurtis I'm not disagreeing, but the functions I listed are also categories mentioned in harmony textbooks. The OP clearly understands the normal triad chord classifications, but he wants to understand what these particular Youtubers are saying. I'm explaining how someone could put augmented chords in a category with major chords.
Comment: Those aren't really *chord* types. They are *function* types. `ii` and `IV` are both pre-dominant, `V` and `viio` are dominants, etc.
Comment: @MichaelCurtis The OP asked about "categories," which aren't a standard way of organizing chords, so I gave an alternative to the traditional chords types.
Comment: @Richard Absolutely augmented chords can be dominant (they usually are). My point with this post was to show that chords can be categorized differently depending on how they are actually use in a specific instance. The whole tone scale has a very stable character due to being symmetrical, which means it can function as a tonic in certain situations.
Comment: @Peter, 'triads' and 'seventh chords' are standard categories and harmony textbooks often divide chapters accordingly.
Answer: The list of triads is easy:

major
minor
diminished
augmented (some theories believe this isn't a bona fide chords as it isn't from the diatonic triads.)

Seventh chords are a little more complex. To start with just the diatonic seventh chords:

major seventh
minor seventh
dominant seventh
half diminished

Add to that the fully diminished seventh chord which comes from the minor mode with a raised ^7 leading tone:

diminished seventh

...(could a half-diminished always be seeing as an inversion of a
  minor?)...

I don't see any way it could be seen that way. You cannot invert a minor seventh in any way to get a chord other than a minor seventh. Actually, it works that way for any chord. The quality of the chord does not change when it is inverted.
If you meant half-diminished = inverted minor 6 like Cm6, then "yes." But it needs to be stated clearly. The same kind of thing can be said about Am7b5. It is a half-diminished chord. But they b5 must be stated to make clear the chord quality. Somewhat similar confusion can result when chord symbols are handled indiscriminately. G9 and Gadd9 aren't the same thing. The actual chord qualities help make things clear. G9 is a dominant ninth chord. Gadd9 is a G major triad with an A added.
Without getting into a jazz theory versus classical theory battle, the point here is that the multitude of jazz symbols tends to obscure the shorter list of classical chord qualities. m7b5 and madd6 aren't two different types they are both half-diminished sevenths in two inversion forms. Same goes with chords like C6 and Am7. Classical would call them both minor seventh chords. The add6 type is a bit of a special case. There is some classical history about treating it as a triad with an added note, but let's skip that for the moment. From a classical point of view Fadd6 - F A C D - in the key of C major would very commonly be labelled ii6/5 which is a minor seventh chord.
So, the list of 9 chord types above is a pretty good minimal list of types.

... In what sense an augmented chord IS a major chord...

I suppose if you take a major chord - G major in the key of C major V - and then altered it with a #5 G B D#, it could be categorized as a kind of major chord. But I disagree. If that's the view, then clearly major chords are just altered minor chords. If we go that way, the whole system of chord qualities collapses.
In classical style you could have a G major in the key C minor and then move the 5th of the G chord D up to the escape tone Eb before resolving to the i chord. The sonority that results with the escape tone is G B Eb which would be the same notes as a augmented chord built on the mediant. Basically you could relabel that "chord" as III+6/3. The problem with that labeling is that it treats a non-chord tone embellishment of a clearly functional V chord as equivalent to an ambiguous, non-diatonic, non-functional augmented "chord". That seems wrong. Go with the functional description. The point is to not confuse simultaneous notes with chord. Chords need to be identifiable as significant tonal things.

There is one other special case involving so-called augmented sixth chords. These chords exist in classical style and jazz although the function differs a little and the labeling is of course different.
The short version is a German augmented sixth chord (in Cm:Ab C Eb F#) is like a re-spelling of a dominant seventh chord and is like the jazz tritone substitution bII7. In the sense that the chord is just a respelled dominant seventh chord we can say this is not a new category. In classical theory you could call it an altered iv7 as #iv6/5 but it's common label is Gr+6.
The Italian augmented sixth chord (in Cm:Ab C D F#) is like the jazz tritone substitution bII7b5. The flat 5th makes this a unique chord not on the list of nine above. In classical theory you could call it an altered half-diminished chord iiØ7 as iiØ+6/4 but it's common label is It+6.
In jazz these chords resolve by the bass note moving a half step down to the root of the tonic chord. In classical the resolve with the bass moving down by half step to the root of the dominant (and the note of the augmented sixth goes up by half step to the tonic.)
All that detail is just to give the background. The point is add one more category:

Italian augmented sixth chord a.k.a. bII7b5 or It+6
Comment: Regarding the half-diminished as an inverted minor: maybe OP meant an inversion of, e.g., Cmadd6?
Comment: I pointed out in a recent thread that jazz musicians in the 40s conceived of the half-diminished chord as an inversion of minor 6 chord.
Comment: @Richard, I thought maybe that was the intention - half diminished as an inverted Cmadd6, but the OP was kind of vague mixing seventh and unspecified minor something.
Comment: I made a little edit to my answer re. my chord label nitpickiness. :-)
Comment: Yes, I meant add6 chords :) And I made an edit to correct the "seeing" to "seen", ouch ...


Initializing a class in another function

Question: I have a code that if simplified would look like this:
void foo(MyObject& y){
    int 2;
    MyObject y(2);
}

int main (int argc, char** argv) {
    MyObject x;
    foo(x);
    x.run();
}

However, I get the error message "error: declaration of 'MyObject y' shadows a parameter. Note that foo() is originally a much more complicated function, i.e., I would rather not copy and paste foo's code to main (although it looks very possible in the above example). What I would like to do here is that to pass MyObject x to foo in main(), initialize x in foo(), and call x.run() in main.
Any ideas?
Answer: You can't initialize an object twice. What you can do is assign it a different value:
void foo(MyObject& y){
    int n = 2;
    y = MyObject(n);
}

Alternatively, write a function that initialized an object and returns it:
MyObject foo(){
    int n = 2;
    return MyObject(n);
}

MyObject m(foo());

Answer: Your definition of foo() does not do what you think, it has a parameter called y and a local variable also called y; they do not refer to the same object.
void foo(MyObject& y){
    int 2;
    MyObject y(2);  // This is a new instance of MyObject independent of the parameter y
}

Solutions include:

Adding a "modifier" method to MyObject to change its state y.set(2),
Constructing a temporary MyObject and assigning it to y: y = MyObject(2),
Returning a copy of a temporary object: return MyObject(2) (making the reference parameter unnecessary).

These last two require that your class has suitable copy semantics, which may require a copy constructor or assignment operator to be defined if the object is not trivial.


Anti Derivatives of Product Rule

Question: Find the anti-derivatives of the following, given that F(x) and G(x) are the anti-derivatives of f(x) and g(x), respectively.

$f(x) + g(x) \rightarrow$ would this just be $F(x) + G(x) +c$?
$f(x)G(x) + F(x)g(x) \rightarrow$? I recognize this as the product rule, but how do I find the antiderivative of this? I know the antiderviative of $f(x)$ is $F(x)$, but what is the anti-derivative of $F(x)$?

Sorry if this is very easy, it's late in the semester and my brain is fried. Thank you for the help!
Comment: For 2, what is the derivative of $FG$?
Answer: Since differentiation is linear, we know that $(F+G)'=F'+G'=f+g$. Hence, $F+G$ is an antiderivative of $f+g$ (this is what we mean by antiderivative). We often write this as
$$
\int f(x)+g(x) \, dx = F(x)+G(x) + C \, ,
$$
to emphasise that any function of the form $\phi(x)=F(x)+G(x)+C$ for some number $C$ satisfies $\phi'(x)=f(x)+g(x)$. We also have that $$(F\cdot G)'=\left(F'\cdot G\right)+\left(F \cdot G'\right)=\left(f \cdot G\right)+\left(F\cdot g\right) \, ,$$
and we can adopt the same notation as before.
Answer: A couple notes:
$$\int[f(x)+g(x)]\,dx=\int f(x)\,dx+\int g(x)\,dx$$

$$\frac{d}{dx}[F(x)G(x)]=F(x)G'(x)+F'(x)G(x)=F(x)g(x)+f(x)G(x)$$

Anti Derivatives of Product Rule


how to detect malicious activity from my server

Question: I'm using a linode virtual server.
My machine is Ubuntu 10.04.
I got a ticket from Linode that they detected malicous activity coming from my server.

"We have detected your system with an IP of, , scanning
  a client we monitor. This was not a short attack but a prolonged scan
  and/or probe that was designed to find and intrude into the target
  network."

Now I'm hosting on linode to test an application, I have no idea how to manage and secure a server.
Please can someone give me some lead on how i should investigate the issue and how to solve it.
Thank you
Answer: If your server has been compromised then you should rebuild it from scratch, rather than waste too much time investigating how it was cracked. This may be easier on a virtual server.
Install both chkrootkit and rkhunter, and run them regularly as cron jobs.
Then google harden ubuntu
Also consider restricting access to your own ip address or subnet.
Comment: thank you. any more advice on how to prevent this in the future ?
Comment: No, there is a lot of material out there written by experts. But before concluding the worst, you might just ask your colleagues if they have run a port scan or used nmap. That might trigger the warning you have received.


Usando $this quando não está no contexto do objeto

Question: Estou tentando criar uma classe em PHP que conecta no banco MySQL e estou obtendo o seguinte erro:

Fatal error:  Using $this when not in object context

ConnectDB.class.php
class ConnectDB
{
    public $pdo;
    private $driver, $host, $port, $base, $user, $pass;

    public function __construct() {
        $this->setDriver('mysql');
        $this->setHost('localhost');
        $this->setPort('3306');
        $this->setBase('bsn');
        $this->setUser('root');
        $this->setPass('');
        $this->connect();
    }

    public function connect() {
        try {
            $this->pdo = new PDO("{$this->getDriver()}:host={$this->getHost()};port={$this->getPort()};dbname={$this->getBase()}", $this->getUser(), $this->getPass());
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->pdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
        } catch (PDOException $e) {
            die('Ocorreu um erro na conexão com o banco de dados.');
        }
    }

    public function setDriver($str) {
        $this->driver = $str;
    }

    public function setHost($str) {
        $this->host = $str;
    }

    public function setPort($str)   {
        $this->port = $str;
    }

    public function setBase($str)   {
        $this->base = $str;
    }

    public function setUser($str)   {
        $this->user = $str;
    }

    public function setPass($str)   {
        $this->pass = $str;
    }

    public function getPDO()    {
        return $this->pdo;
    }

    public function getDriver() {
        return $this->driver;
    }

    public function getHost() {
        return $this->host;
    }

    public function getPort() {
        return $this->port;
    }

    public function getBase() {
        return $this->base;
    }

    public function getUser() {
        return $this->user;
    }

    public function getPass() {
        return $this->pass;
    }
}

ManipulateData.class.php
require_once('ConnectDB.class.php');
require_once('ITemplate.php');

class ManipulateData extends ConnectDB implements ITemplate
{
    public function __construct() {
        parent::__construct();
    }

    public static function select($query) {
        $stmt = parent::getPDO()->prepare($query);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public static function insert($query) {}

    public static function update($query) {}

    public static function delete($query) {}

    public static function doubleData($dados) {}
}

Eu estou tentando executar as minhas queries dessa forma:
print '
';
print_r(ManipulateData::select('SELECT * FROM vagas'));

O que eu estou fazendo de errado?
Comment: E quais as outras informações da mensagem, tal como a linha que gerou o erro?
Comment: Porque não deixa tudo estático na classe `ConnectDB`? Já que fez assim no resto do código
Comment: @AndersonCarlosWoss o erro esta apontando para o método `Connect::getPDO()'
Comment: Mas o método `getPDO` não é estático e você está chamando a partir de um estático. Se você não instanciou a classe, quem deveria ser `$this`?
Answer: Há de cara um erro conceitual. Quase todos os códigos PHP que eu vejo postados aqui cometem esse erro. As pessoas não entendem o que é herança e usam mesmo assim. Esta classe não deveria herdar da outra, não tem relação entre elas. Isto é gambiarra. Entendo que aprendeu assim porque quase todos os códigos PHP usando OOP estão errados. Por isso é melhor não usar OOP. Não use algo que não domina. Ferramentas só são boas quando você sabe usá-las. No seu caso, faça de forma mais simples que sairá um código melhor. E em PHP raramente OOP é uma vantagem, afinal ela é uma linguagem de scripts, não tem a mesma dificuldade de outras linguagens. E esse ITemplate parece inútil. Existem outros problemas conceituais na classe, inclusive o nome em inglês está errado, mas nem vou me atentar a isso porque a existência dela já é um erro. E não vi muito motivo para capturar uma exceção só para dizer que não conseguiu conectar e acabar com a aplicação. Captura de exceção deve ocorrer para fazer algo útil.
O erro é justamente o que foi dito, está usando o $this fora de um objeto. O $this é a variável do objeto, todos os métodos que acessam dados do objeto possuem esta variável, são os métodos de instância. Em métodos de classe esta variável não está disponível, portanto ela não existe, não pode ser usada. Seus métodos são todos estáticos, ou seja, todos de classe, e ainda não criou uma instância, portanto o $this não está disponível. Então não vai funcionar. Assim funciona:
class ManipulateData extends ConnectDB {
    public function select($query) {
        $stmt = $this->getPDO()->prepare($query);
        $stmt->execute();
        return $stmt->fetchAll();
    }
}
$obj = new ManipulateData();
print_r($obj->select('SELECT * FROM vagas'));

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Mas ainda é um conceito muito errado. Você poderia só plugar na tomada, mas está fazendo isto:


Is the conditional likelihood of a sample of $(X,Y)$ a conditional joint distribution of all $Y$ on all $X$'s?

Question: Given random variables from a random sample  $(X_1,Y_1),\dots,(X_n,Y_n)$, the conditional likelihood of observing $y_i |x_i$ (for all $i$) given parameters $\theta_1,\dots,\theta_n$ is usually written as something along the lines of $L(y|x;\theta_1,\dots,\theta_n)$. Is it correct to view the conditional likelihood of the entire sample as $f(y_1,\dots,y_n|x_1,\dots,x_n,\theta_1,\dots,\theta_n)$, where $f$ is a conditional probability density function? If $Y_i$ and $Y_j$ ($i \neq j$) is conditionally independent given $X_1,\dots,X_n$, then I assume the joint distribution can be broken down to equal $\Pi f(y_i|x_1,\dots,x_n,\theta_1,\dots,\theta_n)$? Most notations I see don't explicitly denote conditioning of $Y_i$ on all $X$'s, only on $X_i$.
Answer: As you point out, $f(y_1, ..., y_n | x_1, ..., x_n; \theta_1, ..., \theta_n)$ is valid for the most general case.
When $y_j$ are independent,
$$
f(y_1, ..., y_n |
    x_1, ..., x_n; \theta_1, ..., \theta_n)
= \Pi f(y_i| x_1, ..., x_n; \theta_1, ..., \theta_n).
$$
You say you "assume it". You can easily prove it by iteratively applying the following:
$$
f(y_1, ..., y_n |
    x_1, ..., x_n; \theta_1, ..., \theta_n)
\\= f(y_1| x_1, ..., x_n; \theta_1, ..., \theta_n)
f(y_2, ..., y_n | y_1, x_1, ..., x_n; \theta_1, ..., \theta_n)
\\= f(y_1| x_1, ..., x_n; \theta_1, ..., \theta_n)
f(y_2, ..., y_n | x_1, ..., x_n; \theta_1, ..., \theta_n).
$$
The first step is the law of conditional probability. The last step follows from the independence of $y_j$ on $y_i$, $i \neq j$.
In many problems of the literature, I guess that $y_i$ only depends on $x_i$. Hence the notation that you mention.
Comment: independence of $y_i$ and $y_j$ doesn't mean they're independent conditioned on some other variable, say $x_i,x_j$.