How to access local MS SQL database running in docker on MacOS/ Monterey

Question: Working through a programming book ("Learn with" series by Jeffry Houser) I am stuck with accessing the database powering a Java/ Jersey REST service.
The database is a MS SQL Database running in a docker container, the author provided the image, so I know little about the set-up.
I now try to connect from my java program in IntelliJ created with Marven/ Jersey.
Dependency in POM.xml is
<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>9.2.1.jre15</version>
</dependency>

Class and connection string is
public class DatabaseConfig {
    String host = "jdbc:sqlserver://localhost";
    String port = "1433";
    String database = "…";
    String username = "…";
    String password = "…";

    Connection connection = null;

    public Connection openConnection() {
        if (connection != null) {
            return connection;
        }
        String connectionString = host + ":" + port + ";"
                + "database=" + database + ";"
                + "user=" + username + ";"
                + "password=" + password + ";";

        try {
            Class.forName("com.microsoft.sqlserver.jbdc.SQLServerDriver");
            connection = DriverManager.getConnection(connectionString);
        } catch (Exception e) {
            System.out.println("Exception");
            e.printStackTrace();
        }

        return connection;

    }

The error when testing the class is
Exception
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jbdc.SQLServerDriver
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:375)
    at com.dotComIt.learnWith.config.DatabaseConfig.openConnection(DatabaseConfig.java:26)
    at com.dotComIt.learnWith.services.AuthenticationServiceTest.authenticate(AuthenticationServiceTest.java:12)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
java.lang.NullPointerException: Cannot invoke "java.sql.Connection.prepareStatement(String)" because "this.connection" is null
    at com.dotComIt.learnWith.services.AuthenticationService.authenticate(AuthenticationService.java:17)
    at com.dotComIt.learnWith.services.AuthenticationServiceTest.authenticate(AuthenticationServiceTest.java:15)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

Process finished with exit code 0

I installed the database driver from microsoft using homebrew
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release
brew update
HOMEBREW_NO_ENV_FILTERING=1 ACCEPT_EULA=Y brew install msodbcsql17 mssql-tools

But this didn't change the behaviour.
So I tried to connect from Visual Studio Code.
Here the error is
mssql: Failed to connect: Microsoft.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid: Connection string is not valid) at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover, SqlAuthenticationMe...

The Docker container stat show the database is listening at port 1433.
I tried netstat to find the database, it didn't show up.
The local docker container how to is reachable so, I understand the docker container itself is reachable.
My guess for the root cause is "something with the network" or "something with the driver", but I don't know, what to do specifically.
Any ideas will help! Thanks in advance!
Answer: This
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jbdc.SQLServerDriver

means you need to install the JDBC driver in your project dependencies.  You can download the JAR file or use Maven.  Instructions are here.

I installed the database driver ... msodbcsql17

That's the ODBC driver.  Not JDBC which Java programs use.

The Docker container stat show the database is listening at port 1433

Port 1433 inside the container.  But what port is that mapped to on the host?
Comment: Thanks @david for the quick response and the hints.
My understanding was, Intellij/ Maven should load the JDBC driver after I put the dependancy in the pom? Does this mean something is wrong with my IntelliJ/ Maven setup or did I get that wrong? thanks again!
Comment: Also, the jar file for the driver is in the lib folder. I also checked the version numbering. What am I missing? :-(


Derivation of $\mathbb{E}\lbrack MSLF \rbrack$ in lack of fit test

Question: I'm currently studying the lack of fit test in a linear regression course. I'll define a few things here, then state precisely what it is I'm trying to derive.
$$SSE = \sum_{i = 1}^c \sum_{j = 1}^{n_i} (y_{ij}-\hat{y}_{ij})^2 $$
$$ SSLF = \sum_{i = 1}^c \sum_{j = 1}^{n_i}(\overline{y}_i - \hat{y}_{ij})^2 $$
$$ SSPE = \sum_{i = 1}^c \sum_{j = 1}^{n_i}(y_{ij} - \overline{y}_{i})^2 $$
$$ MSLF = \frac{SSLF}{c-2} $$
$$ MSPE = \frac{SSPE}{n-c} $$
I wish to derive the following:
$$ \mathbb{E} \left\lbrack MSLF \right\rbrack = \sigma^2 + \frac{1}{c-2} \sum_{i=1}^{c} n_i (\mathbb{E}\lbrack y_{ij} \rbrack -(\beta_0 + \beta_1 x_i))^2 \tag{$\star$}$$
We have
$$ \mathbb{E} \left\lbrack MSLF \right\rbrack = \frac{1}{c-2} \mathbb{E} \left\lbrack SSLF \right\rbrack$$
and since $SSE = SSLF + SSPE,$
$$ \mathbb{E} \left\lbrack SSLF \right\rbrack = \mathbb{E} \left\lbrack SSE \right\rbrack - \mathbb{E} \left\lbrack SSPE \right\rbrack.$$
I was able to derive $\mathbb{E}(SSPE) = (n-c)\sigma^2.$ But I cannot finish the derivation for $\mathbb{E}(SSE).$ I figure if this can be done, I will have completed a derivation of $\mathbb{E}\lbrack SSLF \rbrack$. I want to show that $1/(c-2) \mathbb{E}\lbrack SSLF \rbrack$ is equivalent to the expression in $(\star)$.
How is this one done?
Comment: Please add the self-study tag and I'll add a hint in the answer.
Comment: It appears on page 126, in the Comments section. Thanks for your help, it's bugging me that I can derive the top equality but not the bottom. The post I linked above mentions using E(SSE) to do this after computing E(MSPE), but I didn't get anywhere with that.
Comment: Edited, hopefully it is more clear now.
Comment: So are you trying to derive $E[MSLF]$ or $E[SSE]$ or both?
Comment: Specifically, I'm trying to derive $\mathbb{E}\lbrack MSLF \rbrack.$ The post here https://stats.stackexchange.com/questions/122328/deduction-of-the-expectation-for-lack-of-fit-test near the bottom mentions a computation for $\mathbb{E}\lbrack SSE \rbrack$ being useful for this.
Comment: Is there a specific results you are trying to obtain? $E[MSLF]$ can be expressed in several different ways.
Comment: Yes, the version I'm trying to derive is the one in the question. This specific form is mentioned in Applied Linear Statistical Models (5ed.) in a comment without proof, so I'm trying to do it.
Comment: Page number?  I have that book.
Comment: BTW, this wasn't clear from your question.  In the question you said you "know that" so I assumed you could already show this.
Comment: Yes.  I see it now.  Give me minute.  There's a method to prove this using the trick I mentioned below.  I'll derive this and post back.
Comment: So, can you pleased it the question by adding at the very end exactly what you are trying to prove?  The way it's worded now, it's not clear to me and may not be to other users. Just a single sentence that says something like, "I need help showing $LHS=RHS$."
Comment: Thanks, @dove!  Will post back late tonight if someone doesn't beat me to it -- off to dinner. ;-)
Answer: Here's a hint for your self-study question:
To prove $E[SSLF]=E[SSE]−E[SSPE]$, try adding and subtracting $\bar{y}_i$ from the terms in parenthesis of SSE and use algebra to group like terms, noting that the cross product terms vanish to zero.


Trazer registro de cada ID com a data de alteração mais recente

Question: Estou trabalhando com banco Oracle e PHP, preciso retornar apenas um produto de cada com a data de alteração mais recente, as tabelas são as seguintes.
produto

preco

Já tentei vários tipos de consulta, mas sempre obtenho resultados duplicados.
E tentando agrupar com a seguinte consulta
SELECT a.CODPROD, a.DESCRICAO, b.PVENDA, b.CODPROD FROM PCPRODUT a, PCPRECO b
GROUP BY b.CODPROD

Obtenho o seguinte erro:

"ORA-00979: não é uma expressão GROUP BY"
Comment: Tentou agrupar a consulta? como você tentou a consulta?
Comment: Realizei a seguinte consulta agora, porém a pagina fica só carregando e não me retorna nada.
"a.CODPROD, a.DESCRICAO, b.PVENDA, b.CODPROD, max(b.DATAALTER) FROM PCPRODUT a, PCPRECO b GROUP BY a.CODPROD, a.DESCRICAO, b.PVENDA, b.CODPROD"
Comment: Quando tento agrupar obtenho o seguinte erro: "ORA-00979: não é uma expressão GROUP BY"
Comment: A consulta é "SELECT
  CODPROD,
  DESCRICAO,
  PVENDA

FROM
  PCPRODUT, PCPRECO WHERE PCPRODUT.CODPROD = PCPRECO.CODPROD"
Comment: [Edite](http://pt.stackoverflow.com/posts/173009/edit) a pergunta e coloque a consulta que vc tentou com o group by
Comment: Todas as colunas que estão no `select` deve estar no `group by`
Comment: QUando vc testa no banco obtem o resultado desejado?
Comment: Não, acontece a mesma coisa
Answer: Cara faz um tempo que não uso o Oracle, tenta algo desse tipo:
SELECT a.CODPROD, a.DESCRICAO, b.PVENDA, b.CODPROD, MAX(b.DATAALTER)
FROM PCPRODUT a,
INNER JOIN PCPRECO b ON a.CODPROD = b.CODPROD
GROUP BY a.CODPROD, a.DESCRICAO, b.PVENDA, b.CODPROD
Comment: Agora puxou, porém ainda com alguns resultados duplicados.

Ex:

40 REFRESCO PO QUALIMAX ABACAXI 1 KG 4.51 40 2013-04-05 20:40:55
40 REFRESCO PO QUALIMAX ABACAXI 1 KG 5.34 40 2015-03-20 07:08:03
40 REFRESCO PO QUALIMAX ABACAXI 1 KG (null) 40 2015-06-08 00:00:00
74 REFRESCO PO QUALIMAX LARANJA 1 KG 7.74 74 2016-08-05 19:15:59
Comment: veja se ajuda http://forum.imasters.com.br/topic/512214-selecionando-item-max/#entry2030107
Comment: Ajudou, obrigado!


Is there a way in firebase functions to delete storage files that match a regular expression?

Question: I can't find a way to delete all the files inside firebase storage that match a regular expression. I would like to use something like:
        const bucket = storage.bucket(functions.config().firebase.storageBucket);
        const filePath = 'images/*.png';
        const file = bucket.file(filePath);
        file.delete();

Or similar to be able to delete all files inside "images" with png extension.
I tried searching in Stackoverflow and in the samples repository without luck https://github.com/firebase/functions-samples
Any help would be much appreciated. Thanks!
Answer: No.  In order to delete a file from Cloud Storage, you need to be able to construct a full path to that file.  There are no wildcards or regular expressions.
It's common to store the paths to files in a database in order to easily discover the names of files to delete by using some query.
Answer: If you want to do this in Cloud Functions, you'll be using the Firebase Admin SDK. And the Cloud Storage functionality in there (admin.storage()) is a thin wrapper around the Cloud Storage SDK for Node.js. So if you search for cloud storage node.js path regular expression you'll get some relevant results.

How to get files from Google Cloud Storage bucket based on a regular expression?, which indicates that prefix matching is quite possible with bucket.getFiles({ prefix: 'path/to/file' }....
Answer: What about this solution
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference mStorageRef =
    storage.getReference().child("fotos_usuarios/"+id);
mStorageRef.listAll().addOnSuccessListener(listResult -> {
    for (StorageReference item : listResult.getItems()) {
        if (item.getName().contains("SOME_WORD")){
            item.delete();
        }
    }
})

Comment: Thanks for sharing your code! Would be great if you could add a few words of explanation how it works?


How to handle Unable to decode stream: java.io.FileNotFoundException: on using FileProvider (No such file or directory)

Question: Am trying to support Nougat by getting rid of FileUriExposedException.When I use Uri.fromFile(gettheImageFilehere()) method I successfully get the image path file:///storage/emulated/0/DCIM/Camera/IMG_20170308_171951.jpg
When I use
FileProvider.getUriForFile(HomeView.this, getApplicationContext().getPackageName() + ".provider",
                gettheImageFilehere());

I get the image path as : /external_files/DCIM/Camera/IMG_20170308_171951.jpg
I have tried to use the implemetation provided on android.os.FileUriExposedException
Here is my code in my androidmanifest.xml  inside  I added the provider:
<provider
       android:name="android.support.v4.content.FileProvider"
       android:authorities="${applicationId}.provider"
       android:exported="false"
       android:grantUriPermissions="true">
        <meta-data
           android:name="android.support.FILE_PROVIDER_PATHS"
           android:resource="@xml/provider_paths"/>
    </provider>

I then created the provider_paths.xml in res/xml folder as below:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

My doubts about the above:

In some example I found that they use the full path. i.e Android/data/com.example.com/files.I don't know if its the same as just having the path as a. Hopefully someone can clear that up for me.

The full error am getting is Unable to decode stream: java.io.FileNotFoundException: /external_files/DCIM/Camera/IMG_20170308_175833.jpg (No such file or directory)
The code snippet .java file is here to view my implementation.
Answer: Try using
           Intent iGallery = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);


Left Cyclic Modules and Canonical Homomorphism

Question: I am trying to show that if $_{R}M$ is a left R-module and cyclic, then $M\cong R/I$ for some left ideal $I$ in $R$.
If $l-ann(x)$ is the left annihilator of $x\in M$, then I showed that $l-ann(x)$ is a left ideal of $R$ and then I defined $\phi:R/l-ann(x)\to M$ by $\phi(r+l-ann(x))=(r+M)x=rx\in _{R}M\subset M$. But is this the correct mapping?
Comment: Yes, that's the correct mapping, but please don't abuse the minus sign like that.
Answer: You know that $M$ has a generator $x$, which means $M=Rx$. Try defining a map $R\rightarrow M$ by $r\mapsto rx$. The kernel is exactly this annihilator you mention.
Comment: Nice, a first isomorphism theorem problem!


Is it possible to calculate LUB on type level?

Question: I need to get least upper bound of two types given as parameters. Something like that:
class Holder[T] {
  type Shrink[S] = ???
}

where ??? generates some type expression that produces least upper bound for the T and S types. Something that looks like LUB_Magic[T,S].
I tried many things but couldn't find any way to express it.
For example, if types A and B predefined then
final case class Solve() {
  val query = (x : Any) => x match {
    case a : A => a
    case b : B => b
  }
  type Q = query.type
}

would produce type based on the least upper bound.
But if I try to parametrize it like class Solve[A,B]() then the type would be Any instead of the least upper bound. Same goes with the gist solution
Is it ever possible to get least upper bound on type level?
Answer: If your main goal is to have the right result type in query, then you can simply add implicit evidence for A <:< C and B <:< C to the invocation of query. I've grouped the both types of evidence into a class called Lub here:
class Lub[A, B, C](val ev1: A <:< C, val ev2: B <:< C)

object Lub {
  implicit def lub[C, A <: C, B <: C]: Lub[A, B, C] =
    new Lub[A, B, C](implicitly, implicitly)
}

Now you can use it to ensure that query returns the right type of function:
import scala.reflect.ClassTag

case class Solve[A: ClassTag, B: ClassTag]() {
  def query[C](implicit lub: Lub[A, B, C]): Any => C = {
    (x: Any) => x match {
      case a : A => lub.ev1(a)
      case b : B => lub.ev2(b)
    }
  }
}

val s1 = Solve[Int, Float]
val q1: Any => AnyVal = s1.query // typechecks

If you insist on having q as val and the least upper bound as a type member of Solve instead of inferring it at the call site, you could do something like this:
abstract class Solve2[A: ClassTag, B: ClassTag] {
  type C
  def query: Any => C
}

object Solve2 {
  final class Solve2Builder[A: ClassTag, B: ClassTag] {
    def build[X](implicit lub: Lub[A, B, X])
    : Solve2[A, B] { type C = X } = new Solve2[A, B] {
      type C = X
      val query: Any => C = _ match {
        case a: A => lub.ev1(a)
        case b: B => lub.ev2(b)
      }
    }
  }
  def apply[A: ClassTag, B: ClassTag]: Solve2Builder[A, B] = new Solve2Builder[A, B]
}

Now the Solve2[A, B]{ type C = ... } is built using the builder created by the companion object, the implicit evidence for A <:< C and B <:< C has to be supplied only once:
val s2 = Solve2[Int, Float].build
val q2: Any => AnyVal = s2.query

Note that all these maneuvers with ClassTags only take you so far: you will be able to distinguish between Int and Float, but you won't be able to distinguish between List[Int] and List[Float]. Before you investigate any further, you might take a closer look at what shapeless has to offer.
Comment: Implicit evidence is unstable. I could not calculate it on the type level, i.e. without creating objects. `query` typing is not the goal but the solution I tried, but failed. If creating objects are allowed then the gist I mentioned offers fine solution
Comment: To distinguish `List[Int]` from `List[Float]` you could use `TypeTag`s
Comment: @ayvango Then I've misinterpreted your question, sorry. I'll delete my answer, so your question hopefully gets a bit more attention again.


What is the best module for student registration form

Question: What is the best module to use if i want to create a
student registration form for my website.
Some of the fields in this form is referred to taxonomy and content types as entities.
Im a novice user of drupal 7
and cant find any mdoule that does this, I keep getting FORM API tutorial in my seaches but I when I checked it involves a lot of programming.. :(
Thanks
Answer: Webform module is pretty popular among Drupalers for registration forms. It is quite well supported and documented. It also has many cool in-built features and a few other 3rd party modules that bring in even more sizzle to the mix.
Good-luck to you friend & welcome to drupal.stackexchange.
Comment: Thank you for a warm welcome.
I have tried it but my concern is it doesnt support using fields from taxonomy or content types.. Is there a work around for it?
Comment: @ARGO I think it could be helpful to better define your use scenario.  Why does a registration form need to refer to directly refer taxonomy terms?  You can recreate the list in the webform if you have a list of terms you want.  Typically, nodes are used if you want to display the registration information to the outside world.  Again a better description of your use scenario could be worthwhile here.
Comment: Hi Rider, sorry to get have given you limited info. Here is my case:
We are selling courses. I have created a node (Content Type) that contains course titles and other info. They are more than 50 courses.
Come of the fields in the courses content type are linked in taxonomy such as course levels and duration.

now I want to create a form that contain a list field displaying the available course titles and durations. I dont want to redo the titles by adding another list to webform's list configuration.
Comment: I want to keep it centralised so whenever I did changes in the title from the course content type Its reflected in the form list as well. What do you think?
Comment: @ARGO: You may be stuck with a custom content type which anonymous users can create but not view/edit/delete. Or perhaps require signup so they can edit their own registration/s. One of my biggest problems with Webform is that it doesn't support the Fields API (and CCK before it), meaning that you're stuck with the very few fields that it provides itself. Fieldable webform submissions would have been a hugely awesome feature, but I fear that ship sailed long ago.
Comment: I agree Matthew, it could have been more awesome if it supports fields just like Entityforms module. I guess im really going for content type for now.


Quadrado Misterioso

Question:

Os números inteiros posicionados em um quadrado NxN tal que todas as linhas e diagonal principal têm a mesma soma.
Por exemplo, o quadrado abaixo
2 7 11
9 5 6
4 3 13

é um quadrado misterioso de soma 20, pois todas as linhas (2+7+11 = 20, 9+5+6 = 20 e 4+3+13 = 20) e diagonal principal (2 + 5 + 13 = 20) têm a mesma soma (20).
Escreva um programa que, dado um quadrado, determine se ele é misterioso ou não e qual a soma dele (caso seja mágico).
Entrada
A primeira linha contém um inteiro N. As N linhas seguintes contêm N inteiros cada, separados por exatamente um espaço em branco.
Saída
Seu programa deve imprimir, na saída padrão, uma única linha com um inteiro representando a soma do quadrado mágico ou -1 caso o quadrado não seja mágico.

PS: não posso usar vetor, só posso usar estruturas de repetição.

EXEMPLO 1
ENTRADA:
3
2 7 11
9 5 6
4 3 13

SAÍDA:
20

PS: A minha saída foi:

-1

Segue o meu código:
int main()
{
    int n, i, j, elem;
    int , soma_linhas = 0, soma_dp = 0;

    scanf("%d", &n);

    //leitura dos elementos
    for(i = 0; i < n; i++){
        for(j = 0; j < n; j++){
            scanf("%d", &elem);
            //somatorio de cada linha
            aux += i;
            soma_linhas = aux;
        }
    }

    //somatorio da diagonal principal
    for(i = 0; i < n; i++){
        for(j = 0; j < n; j++){
            if(i == j){
                aux += i + j;
                soma_dp = aux;
            }
        }
    }

    if(soma_linhas == soma_dp)
        printf("%d", soma_linhas);//se for quadrado misterioso tanto faz mostra a linhas ou da diagonal
    else
        printf("-1");
    return 0;
}

Onde estou errando?
Comment: Seu exemplo de entrada não se trata de um quadrado mágico. O somatório de nenhuma das colunas é `20`. A saída esperada seria `-1`.
Comment: Esse que é a questão. É um quadrado misterioso não um mágico. Por isso que deve ser só a soma das linhas e da diagonal principal.
Answer: Vejamos esses laços:
//leitura dos elementos
for(i = 0; i < n; i++){
    for(j = 0; j < n; j++){
        scanf("%d", &elem);
        //somatorio de cada linha
        aux += i;
        soma_linhas = aux;
    }
}

Independente do que aconteça, ao final soma_linhas e aux terão o mesmo valor. Qual será o valor de aux. Para um quadrado de 3x3, será 0 na primeira iteração, 1 na segunda (+1) e 3 na terceira (+2). No entanto, não era isso que ele deveria fazer! Não há sentido somar os valores de i e desconsiderar os valores de elem. Você deveria é verificar os valores de elem.
No entanto, mesmo se você usar aux += elem;, ainda vai estar errado, pois isso vai acabar somando todos os valores, e não os valores de cada linha separadamente.
O que você tem que fazer é mudar esse laço para que ele vá somando os valores de cada linha e a partir da segunda linha, compare com o valor da linha anterior.
Note que você não está armazendando os valores lidos em lugar nenhum, a variável elem só irá guardar o último valor. Por causa disso, o seu laço para verificar a diagonal principal também não vai funcionar, pois você só está somando valores fixos 0, 1 e 2 e ignorando completamente o conteúdo da matriz.
Sem armazenar a matriz inteira, fica bem difícil verificar se todas as linhas e a diagonal principal têm os mesmos valores. Mas como você não pode armazenar os valores em vetores, você faz o seguinte:

Use uma variável (vamos chamar de ok) para indicar se as somas das linhas e da diagonal principal coincidem. Inicialize ela com 1.
Leia a primeira linha, somando todos os itens (vamos chamar isso de a). Armazene o primeiro elemento em uma variável auxiliar (b).
Use um for para ler as demais linhas, somando os elementos de cada linha em uma outra variável c. O elemento da coluna principal você soma também à variável b. Ao final de cada linha, confira se a == c e mude ok para 0 se não for. Não se esqueça de voltar c para 0 antes de começar a linha seguinte.
Ao terminar a última linha, confira se a == b e mude ok para 0 se não for.
No fim, basta verificar a variável ok.

Algo mais ou menos assim:
#include <stdio.h>

int main() {

    int n;
    scanf("%d", &n);

    int elem, a = 0, b = 0, ok = 1;
    for (int i = 0; i < n; i++) {
        int c = 0;
        for (int j = 0; j < n; j++) {
            scanf("%d", &elem);
            if (i == j) b += elem;
            if (i == 0) a += elem;
            c += elem;
        }
        if (a != c) ok = 0;
    }
    if (a != b) ok = 0;

    if (ok) {
        printf("Quadrado misterioso com soma %d.", a);
    } else {
        printf("Não é um quadrado misterioso.");
    }
    return 0;
}

Veja funcionando no ideone:

Para um quadrado misterioso.
Para um quadrado não misterioso.
Comment: Fiquei curioso sobre uma implementação prática da solução **sem usar vetores**.
Comment: @Lacobus Resposta editada.
Comment: @VitorStafusa: As colunas do quadrado não estão sendo verificadas! `2 + 9 + 4 == 15`, `7 + 5 + 3 == 15` e `11 + 16 + 13 = 40`. (O quadrado da pergunta não se trata de um quadrado mágico!)
Comment: @Lacobus Isso é o esperado. Leia o enunciado, ele não fala nada sobre as colunas. O quadrado misterioso diz respeito apenas às linhas e à diagonal principal. Talvez você esteja pensando no [quadrado mágico](https://pt.wikipedia.org/wiki/Quadrado_m%C3%A1gico) que esse sim tem que ter a soma das linhas, colunas e ambas as diagonais iguais. Todo quadrado misterioso é mágico, mas o contrário não necessariamente é verdadeiro.
Comment: @Lacobus Até dá para verificar a diagonal secundária sem usar vetor, mas para as colunas, acredito que o uso de um vetor de acumuladores seja inevitável. No entanto, como isso é para verificar se o quadrado é misterioso ao invés de mágico, não preciso desse vetor pois não preciso das colunas.
Comment: @VictorStafusa sobre as colunas, precisa de `o(N)` de memória extra. Independente se tiver de validar as linhas. Inclusive isso me deu uma ideia de questão estilo code-golf aqui xD
Answer: Você não menciona na pergunta nada sobre o somatório das colunas, segundo a Wikipedia a definição de um Quadrado Mágico é:

Quadrado Mágico é uma tabela quadrada igual a intersecção de números
  em que a soma de cada coluna, de cada linha e das duas diagonais são
  iguais.

Segue uma solução testada e comentada para verificar se um dado quadrado misterioso é mágico ou não, veja só:
#include <stdlib.h>
#include <stdio.h>

int eh_magico( int ** quad, int n )
{
    int i = 0, j = 0;
    int x = 0, y = 0;
    int d1 = 0, d2 = 0;

    /* Somatorio das diagonais */
    for( i = 0; i < n; i++ )
    {
        d1 += quad[i][i];
        d2 += quad[n - i - 1][i];
    }

    /* Verifica se diagonais sao iguais */
    if( d1 != d2  )
        return -1;

    for( i = 0; i < n; i++ )
    {
        x = 0;
        y = 0;

        /* Somatorio linha e coluna */
        for( j = 0; j < n; j++ )
        {
            x += quad[i][j];
            y += quad[j][i];
        }

        /* Verifica linha e coluna */
        if( x != d1 || y != d1 )
            return -1;
    }

    /* Eh magico! */
    return d1;
}

int main( void )
{
    int lin, col, dim;
    int ** quadrado_misterioso;

    /* Le dimensoes */
    scanf( "%d", &dim );

    /* Aloca memoria para n linhas */
    quadrado_misterioso = malloc( dim * sizeof(int*) );

    /* Para cada linha */
    for( lin = 0; lin < dim; lin++ )
    {
        /* Aloca memoria para n colunas da linha atual */
        quadrado_misterioso[lin] = malloc( dim * sizeof(int) );

        /* Para cada coluna da linha */
        for( col = 0; col < dim; col++ )
            scanf( "%d", &quadrado_misterioso[lin][col] );
    }

    /* Verifica se eh um quadrado magico */
    printf("%d\n", eh_magico( quadrado_misterioso, dim ) );

    /* Libera memoria ocupada pelo quadrado */
    for( lin = 0; lin < dim; lin++ )
        free(quadrado_misterioso[lin]);
    free(quadrado_misterioso);

    return 0;
}

Teste (n = 3):
3
4   9   2
3   5   7
8   1   6
15

Teste (n = 4):
4
2   16  13  3
11  5   8   10
7   9   12  6
14  4   1   15
34

Teste (n = 5):
5
1   23  16  4   21
15  14  7   18  11
24  17  13  9   2
20  8   19  12  6
5   3   10  22  25
65

Teste (n = 3):
3
1   2   3
4   5   6
7   8   9
-1

Teste (n = 3):
3
2   7   11
9   5   6
4   3   13
-1

Veja funcionando no Ideone.com
Comment: É porque essa questão não está se importando com os valores das colunas. Nem da diagonal secundária. Há na verdade um erro de redação na questão, ela deveria ser resolvida com memória constante, independente de N

Quadrado Misterioso


c# is it possible to create extension method for string keyword

Question: I created an extension method for generating string from System.Guid like this.
public static class Fnk
{

    public static string Guid(bool dash = true)
    {
        return dash ? System.Guid.NewGuid().ToString() : System.Guid.NewGuid().ToString("N");
    }
}

I am using it like Fnk.Guid(). I wonder that, is it possible to call it like string.Guid()? If yes, how?
Comment: Also, Guid already has an option for generating a dash-less string. `Guid.NewGuid().ToString("N")`
Comment: An extension-method has a `this`-kewyord for the param. Your code is no extension-method.
Comment: `this sting variableName` must be the first argument. In your code you just return a guid value based on condition
Comment: Do you want to parse string to guid? what will the string.Guid() method do?
Comment: I'm sorry, but I don't understand what's the point of this. [`Guid` has an overload of `ToString` that takes in a string as a format specifier](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tostring?view=netframework-4.8#System_Guid_ToString_System_String_) - use `"N"` to remove the dashes.
Comment: Thanks to everyone who warned me. I fixed the dash.
Answer:
Is it possible to call it like string.Guid()

No. Extension methods allow static methods to be called as if they're instance methods. You're trying to write a static method and allow it to be called as if it's a static method on an unrelated type.
That isn't supported - at least not as of C# 8.
Writing genuine extension methods targeting string is entirely feasible. For example:
public static class PointlessExtensions
{
    public static HasEvenLength(this string text) => (text.Length & 1) == 0;
}

Called as:
bool result1 = "odd".HasEvenLength(); // False
bool result2 = "even".HasEvenLength(); // True

Comment: "PointlessExtensions". I think I'm going to use that name.
Comment: Small addition: if a class derives another having  static member, you´ll be able to call that static member via the derived class as well.
Comment: I understood. Thank you very much for your interest and support.


Can software render music as well as a skilled human with a physical instrument and a microphone?

Question: From a comment on Hacker News:

[...] physical playing has been replaced by software quite a while ago. [...] almost nobody can distinguish a computer rendering from the real thing on a recording.

Can software really convert sheet music into an audio recording as well as a skilled human with a physical instrument and a microphone (as judged by the audience)?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/129136/discussion-on-question-by-bobcat-can-software-render-music-as-well-as-a-skilled).
Answer:
Can software really convert sheet music into an audio recording as well as a skilled human with a physical instrument and a microphone (as judged by the audience)?

"Converting sheet music into an audio recording" consists of two steps: recreating instrument sound and recreating artist expression.
Recreating instrument sound
Virtual instruments do exist and are widely in use. You tagged your question as synthesizer but while modeling sounds of real instruments was explored in the past, presently most instruments emulating sounds of real acoustic instruments base on sampling. Recording technique is developed since over 100 years, and today it works just perfect – you record a note played on an instrument, and then you play it back. It can't go wrong.
Typically an instrument consists of several or even several tens of GB of audio samples. The challenge, besides the obvious one of getting a consistent and high quality recording of all notes of the instrument, is to collect samples representing various dynamic levels and articulations. Another difficulty is to represent various nuances, like moving from one note to another, repeating the same note, ending a note, additional mechanical sounds made by the instrument...
Imitation is the most successful in music styles that don't rely too heavily on subtle instrument articulation changes, though the instrument producers keep pushing these boundaries farther.
Recreating artist expression
This is more difficult, as it's not well defined in technical terms. Sheet music represents certain idea, but the composer must rely on the musician's ability to interpret it. A musician will play each note differently. They will emphasize metric accents and phrases using capabilities of their instrument. A crescendo mark represents idea of increasing the volume, but in practice a simple gradual change may not create appropriate artistic effect.  And "appropriate artistic effect" is a highly subjective term.
Various instrument offer various expressive capabilities. The most universal ones are timing and changes of tempo. Most instruments also can be played with various dynamics and may also provide various articulations. These nuances typically are not, or even cannot be precisely notated in a sheet music meant for humans. A music score fed directly into a virtual instrument, and thus devoid of these nuances will sound rather mechanical and not interesting.
Much better results can be obtained by converting sheet music to a MIDI sequence with manual adjustment of dynamics, timing and articulation of each note. It is a tedious process, and most importantly: manual. While some software tools can aid in it, human involvement is necessary. And recreating the expression of a skilled musician this way is still very challenging.
In practice MIDI sequences which are played by virtual instruments are often recorded by human musicians on MIDI controllers that capture their expression. This can yield very good results, but as a musician is involved, this doesn't fulfill the requirement of "converting sheet music into an audio recording by software".
Use of programmed music sequences emulating the real instruments is therefore the most successful in styles and situations that don't rely heavily on artist expression and interpretation, that have fixed tempo, or where said instrument is in the background. But as soon as we focus on artistic interpretation, a machine cannot replace a skilled musician. At least not yet.
Comment: @ojs that's exactly the point of my answer. A good MIDI sequence doesn't have a simple correspondence to sheet music notation, and conversion between the two is not trivial. I made an edit to make it more clear.
Comment: The "fun" part: MIDIs recorded by human musicians on MIDI controllers often come with horrific tuplets, off-beat 64th notes, and readability issues. (At least that's my experience seeing others' MIDIs on Musescore and Finale Notepad.)
Comment: MIDI file is not a notation format, but sequence of events (note on, note off, control change). If the musician doesn't play precisely on the beat, naively converting event timestamps to notation will produce horrible results.
Answer: No, software that could take any given piece of sheet music and render it with the inflections and expressive devices that would be expected of a human performer (or group) is not yet generally available. A musical score isn't generally intended to be rendered precisely, but in a stylistically-appropriate way (see What does it mean to "play what is not written"? ; What does play with feeling mean?) and you need your performer to add that stylistic 'flavour'.
There's no reason that it would be impossible to create such software, and a google search for "render sheet music expressively" brings up links to a number of research projects - but we're certainly not at the point where "physical playing has been replaced by software quite a while ago" is a sensible statement.
Even if you involve a human in playing or programming in a digital performance for a synthesizer to render, it's arguable that synthesizer technology itself isn't quite at the point where it can reproduce all physical instruments in a way that would satisfy critical ears - so the statement "physical playing has been replaced by software quite a while ago" seems to me to fail on that count as well.
It seems rather similar to making a statement like "physical acting has been replaced by software quite a while ago". Clearly computers are able to help humans generate some very realistic artificial imagery, but you can't yet feed a script into a computer and render a photo-realistic movie.
Answer: The question was "Can software render music as well as a skilled human with a physical instrument and a microphone?" and before you answer no, (which seems to be most people's answers here) you should check out NotePerformer which performs music scores (Sibelius, Dorico, Finale) using AI. I'm only mentioning it because no-one else has.
Sure you can tell it's not live musicians, but it's far better than the sample or GM playback that music typesetting programs generally provide out of the box.
It sounds like an actual performance because of the way it renders legato and dynamics changes using AI. Check out some of the sample audio snippets on the site.
Comment: Being aware of NotePerformer, I only didn't mention it because it still doesn't replace humans
Comment: Wow! although samples can be misleading, if the same pieces were part of their training dataset (then the trained neural network would essentially copy the training data)
Answer: The word "well" is subjective.  If by "well," you mean "precisely," then 100%, computers can do infinitely better than any person can.  Scales at 1000 BPM, all notes played at exactly the same volume?  Check!
If by "well," you mean "played with dynamics that give human beings deep and complex emotional reactions," then YES. . . but not yet.
As long as you can hook up an AI system to something real (like a brain), and you can correlate that to something abstract (like subjective reports of feelings), computers can absolutely learn to do that, infinitely better than even the best people.
Give it about 10-20 years before computers start playing "feedback music" that is dynamically interact to YOUR brain at a given MOMENT, to maximize mood.
Comment: Any sources to back up the claim would be nice.
Comment: Sorry if this sounds arrogant, but do you have any actual neuroscience background?
Comment: All of them, of course. But let's start with the 10-20 years. It sounds suspiciously close to the time when fusion power will be available.
Comment: I'm also interested what "hooking up an AI system to a brain" means
Comment: The people featured on thedailywtf are professional programmers too. Anyway, do you have any sources?
Comment: Yup, the question is in present sense though. In my opinion we're not so close though, keyboard instrument models are pretty good but a human player is needed and synthesizer orchestras are passable if you don't listen too closely. Of course it's subjective so the more deaf your subject is, the better the computer becomes.
Comment: Which one?  I made several claims in that answer.
Comment: Well, we can't measure experiences objectively, so we need to establish some physical correlate that CAN be-- brain waves, blood flow, and so on, often taken in conjunction with verbal reports: "What happens if I do THIS?" (pokes brain with a pin).  "I smell smoke!"
Comment: 10-20 years is a guesstimate.  However, we already have most of the tools right now-- the ability to measure brain function, and the ability to process massive amounts of data.  The problem is that we can't get 6 billion people to sit down while we collect information directly from their brains-- so we probably have to use things like subjective ratings on websites-- at least until I'm president of the world.
Comment: Yes, I have a degree in psychology, with an emphasis in special state psychology ("the zone", OBE, etc.).  I'm also a professional programmer (I came here from Stack Overflow).  I've even modeled basic ANNs on my own (though mine were very poor compared to modern models).  If you want to say "prove it," then I'm out.  If you'd like to learn something about the fields of the study of neurology and how it might be modeled in AI systems, then I'm happy to give some pointers on where to look.  Be warned-- the material gets dense pretty fast.
Comment: Also. . . asking questions for credentials isn't arrogant.  However, it's a poor man's response to an assertion-- the equivalent to a kid arguing, "Well, MY Dad works for NASA, and HE says. . . "  A better approach would either be a philosophical position of your own, or a request for sources-- credible information that might help you understand my position.
Comment: I no longer have access to academic periodicals and so on, but let me see what I can find.  Why don't you narrow down your point of skepticism?  Is it with the ability to measure aspects of mind (either philosophical or practical), the ability to collect enough data for AI, or a general skepticism about AI's ability to ever "get" the subtleties of performance as they relate to feeling?
Comment: (Wait, did you just delete a post, or am I hallucinating?)  You don't map "subjective reports of feelings to music," at least not very effectively-- that's basically taking a survey, which is FAR too imprecise (and slow) to train an AI system well.  You map subjective reports of feelings to brain function (waves, blood flow, etc.), and then treat those neural correlates as targets for an AI system.  Until we all have the Musk-o-matic Brain Sensing Headset at home, it's going to be hard to do this well.
Comment: I think it would be enough information to generate maximally irritating noise, but playing generated music to test subjects at machine learning scale and controlling for other variables would take impractically long time. The magic of GANs is eliminating the test subject, and I don't really see how it would happen here.
Comment: Sorry about deleting the comment. I was just rewriting it to more polite form when your answer appeared.
Comment: Anyway, reacting to listener's mood is just one track here. The actual question was about computer-generated sound that is indistinguishable from good human musician. We already have lots of studio-made music that clearly has only processed samples of human-played music or not even that, and various top ten lists suggest listeners like it :)
Comment: In my opinion, we're actually closer to that than to completely computer-composed and -performed music.  Modeled sounds are pretty impressive already, and I suspect we'll get something akin to orchestral and vocal "deep fakes" soon enough.  "Make me sound like Pavarotti" will be a thing sooner rather than later, I guess.  (only guess, though)


References for calculating cohomology rings

Question: I am struggling to calculate homology rings.
Even for a simple space such as the sphere, it is easy to calculate the cohomology, but I find it much harder to find the ring structure. (This link gives the answer for the 2-sphere, and the generalisation to the $n$-sphere is clear)
I have tried having a look at Hatcher's notes on this (specifically examples 3.7-3.9 on pp. 207-209). Specifically in Hatcher's book, he  claims that $\varphi_1 \cup \psi_1 = 0$ on all 2-simplcies, except the one with outer edge, $b_1$ which is where I got lost.
I tried having a look at the sphere, which has a very simple cohomology, so I figured the cup product should be easy to calculate. I know that the only two non-zero homology groups are $H^0(S^1,\mathbb{Z}) \simeq \mathbb{Z}$ and $H^n(S^n,\mathbb{Z}) \simeq \mathbb{Z}$. So let 1 be the generator of $H^0$ and $x$ the generator of $H^n$ (do we say 1 in the $H^0$ case, as this is the unit of the ring?). Then we have the cup products $1 \smile 1$, $1 \smile x$, $x \smile 1$,$x \smile x$. I can guess that $1 \smile 1 = 1$, but what about the others? How does one calculate this in general? Obviously there is some something simple I am missing?
Is there another nice book that has some nice examples on calculating cohmology rings?
Comment: The sphere really is a simple case...maybe too simple to get a feel for what's going on. Two observations: (i) the cohomology ring does have a multiplicative identity. You should convince yourself that what you've labelled $1$ is indeed this identity. That gives you everything but $x \cup x$: for this, (ii) remember that the cup product takes $H^k \times H^l \rightarrow H^{k+l}$. And then move on to something like complex projective space: that's one of the relatively small number of cases people will expect you to know!
Comment: @Qwirk: (It's not.)
Comment: This way it's correct. Observe that as Abelian groups $\mathbb Z[x]/(x^2)$ is the same as $\mathbb Z\cdot 1\oplus \mathbb Z\cdot x$, and that the multiplication is precisely the one you described.
Comment: @Pete - so $1 \smile x = x$ and $x \smile 1 = x$? And in this case $x \smile x \in H^{2n}=0$, so I guess the ring is determined by $x \smile 1 = x = 1 \smile x$ (I still don't see how that is $\mathbb{Z}[x]/(x^n)$!
Comment: @Rasmus - sorry $\mathbb{Z}[x]/(x^2)$ where $x$ is the generator of $H^n(S^n,\mathbb{Z})$
Comment: @Rasmus - that makes sense - I will try some less trivial examples!
Answer: Maybe I will at least show how the cohomology ring for the sphere works, based on the above. I will leave as community wiki, so it can be tidied up if something is not quite right. If I work out any other spaces, I will try explain them here as well.
Firstly, note that we know that there are only two non-zero cohomology groups $H^0(S^n,\mathbb{Z})\simeq \mathbb{Z}$ and $H^n(S^n,\mathbb{Z})\simeq \mathbb{Z}$. The element of degree 0 must be the unit of the ring (noting that cup product with $H^0$ is a map $H^k(X;\mathbb{Z}) \otimes H^0(X;\mathbb{Z}) \to H^k(X;\mathbb{Z})$). We therefore label the generator of $H^0$ as 1 and $H^n$ as $x$. The relations satisfied are therefore $1 \smile 1 = 1, 1 \smile x = x, x \smile 1 = x, x \smile x = 0$ (as we end in degree $H^{2n}=0$). We know that $$H^*(X;\mathbb{Z}) = \bigoplus_{p \ge 0} H^p(X;\mathbb{Z})$$ and so we have that $$H^*(X;\mathbb{Z}) \simeq \alpha_1 \cdot 1 \oplus \alpha_2 \cdot x, \quad \alpha_1,\alpha_2 \in \mathbb{Z}$$ with the relations as above. This is abstractly isomorphic to the polynomial ring $\mathbb{Z}[x]/(x^2)$, where $x$ is the generator of $H^n(S^n,\mathbb{Z})$
A similar calculation shows that the cohomology ring for $H^*(\mathbb{R} P^2, \mathbb{Z})$ is $\mathbb{Z}[x]/(2x,x^2)$ where $x$ is a generator of $H^2(\mathbb{R} P^2,\mathbb{Z})$
Comment: How about $H^{\ast}(S^2\times S^2)$? By Kunneth's theorem there is an isomorphism $H^{\ast}(S^2\times S^2,\mathbb{Z})\simeq H^{\ast}(S^2)\otimes H^{\ast}(S^2)=\mathbb{Z}[\alpha]/(\alpha^2) \otimes \mathbb{Z}[\beta]/(\beta^2)$ Is there anything else to say in this case?
Comment: Next interesting examples: $H^*(\mathbb R P^2,\mathbb Z/2)$.
Comment: @Rasmus - yes - I am trying to understand this (it seems like this is a very common example, of which the (similar) proof is given in a lot of places)
Comment: That's true.\\\
Comment: Should the last line be "$x$ is a generator of $H^1(\mathbb{R} P^2,\mathbb{Z})$" ?


React Material UI + React Router >>>> I cannot use Redirect inside a onClick function in a button

Question: I am trying to trigger the Redirect React Dom
that is my button component in the handleMenuItemClick() function. But nothing happens.
I have tried a bunch of stuff but but still no success.
How can I make the both work together? My best try was to make a function that return the Redirect component as I saw in one post around, but still no success.
My Code:
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { Grid, Button, ButtonGroup, ArrowDropDownIcon, ClickAwayListener, Grow, Paper, Popper, MenuItem, MenuList, Link }  from '@material-ui/core/Grid';

const SplitButton = (props) => {
    const [open, setOpen] = React.useState(false);
    const anchorRef = React.useRef(null);
    const [selectedIndex, setSelectedIndex] = React.useState(1);

    const myGroups = props.myGroups

    const handleMenuItemClick = (event, index) => {
        setSelectedIndex(index);
        setOpen(false);
        return <Redirect to={`/groups/${index}`} />
    };

    const handleToggle = () => {
        setOpen((prevOpen) => !prevOpen);
    };

    const handleClose = (event) => {
        if (anchorRef.current && anchorRef.current.contains(event.target)) {
            return;
        }

        setOpen(false);
    };

    return (
        <>
            <ButtonGroup variant="contained" color="primary" ref={anchorRef} aria-label="split button">
                <Button onClick={null}>My Groups</Button>
                <Button
                    color="primary"
                    size="small"
                    aria-controls={open ? 'split-button-menu' : undefined}
                    aria-expanded={open ? 'true' : undefined}
                    aria-label="select merge strategy"
                    aria-haspopup="menu"
                    onClick={handleToggle}
                >
                    <ArrowDropDownIcon />
                </Button>
            </ButtonGroup>
            <Popper open={open} anchorEl={anchorRef.current} role={undefined} transition disablePortal>
                {({ TransitionProps, placement }) => (
                    <Grow
                        {...TransitionProps}
                        style={{
                            transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom',
                        }}
                    >
                        <Paper>
                            <ClickAwayListener onClickAway={handleClose}>
                                <MenuList id="split-button-menu">
                                    { myGroups.map((group) => (
                                        <MenuItem
                                            key={group.id}
                                            onClick={(event) => handleMenuItemClick(event, group.id)}
                                        >
                                            {group.title}
                                        </MenuItem>
                                    ))}
                                </MenuList>
                            </ClickAwayListener>
                        </Paper>
                    </Grow>
                )}
            </Popper>
        </>
    );
}

export default SplitButton

Answer: You can redirect user via 2 methods: useHistory or <Redirect />
useHistory hook
If you want to redirect the user directly on click, you can treat the code imperatively and tell React what to do:
const history = useHistory();

const handleMenuItemClick = (event, index) => {
    setSelectedIndex(index);
    setOpen(false);
    history.push(`/groups/${index}`)
};

More info https://reactrouter.com/web/api/Hooks/usehistory
Redirect component
Or if you feel more comfortable using React's default declarative model, you can say what's changed and allow your code to react to this change:
const [redirectUrl, setRedirectUrl] = useState('')

const handleMenuItemClick = (event, index) => {
    setSelectedIndex(index);
    setOpen(false);
    setRedirectUrl(`/groups/${index}`)
};

if (redirectUrl) {
    return <Redirect to={redirectUrl} />
}

return (
    <>
        <ButtonGroup variant="contained" color="primary" ref={anchorRef} aria-label="split button">
            <Button onClick={null}>My Groups</Button>
            <Button

...

More info https://reactrouter.com/web/api/Redirect


Testar função de soma

Question: Olá pessoal tudo bem? primeiramente quero dizer que é um prazer fazer parte desta comunidade.
Estou estudando python por conta própria, achei um curso por aplicativo, já estou na parte de funções mas não compreendi corretamente a sintaxe do comando.
Eu gostaria de fazer algo simples, implementar uma função de soma e uma função para testar a soma, apenas para fins didáticos.
Mas meu código não exibe nada na tela, segue:
def soma (x, y):
    return (x + y)

def testa_soma():
    if (soma(10, 20) == 30):
        print ('correto')

Answer: Você definiu duas funções uma testa_soma e a soma, mas não fez a chamada de nenhuma delas, deveria ser assim:
def soma (x, y):
    return (x + y)

def testa_soma():
    if (soma(10, 20) == 30):
        print ('correto')

testa_soma()

Veja que na última linha eu coloquei a chamada.
Answer: Pra que uma função seja executada, você tem que chamar ela:
def soma (x, y):
    return (x + y)

def testa_soma():
    if (soma(10, 20) == 30):
        print ('correto')

testa_soma()

Comment: Muito obrigado pessoal!!
Answer: Você pode também utilizar o modulo doctest. Com ele você pode criar os testes direto na docstring da função, o que centraliza os testes junto com a função e auxilia da documentação da mesma.
def soma(x, y):
    """ Retorna a soma de dois números.

    Parâmetros:
        x, y: números a serem somados.

    Retorno:
        Resultado da soma dos números de entrada.

    Exemplos:

    >>> soma(10, 20)
    30
    >>> soma(0, 5)
    5
    >>> soma(-1, -3)
    -4
    >>> soma(-2, 3)
    1
    """
    return x + y

Assim, no arquivo, basta incluir:
if __name__ == "__main__":
    import doctest
    doctest.testmod()

E quando executar o arquivo, os testes serão verificados. Se não produzir nenhuma saída, é porque todos os testes foram bem sucedidos.
Comment: e se eu quiser chamar a função testa_soma dentro da função soma? é possível? tipo pra ela já puxar o teste sozinha
Comment: @LeandroSargi isso não é bom fazer, porque quando chamar a função soma você espera que seja apenas somados os números e não testar a função; gera efeitos colaterais.
Comment: a tá ok, obrigado amigo.
Comment: Eu perguntei isso porque no meu curso, tem um exercício pra fazer um jogo. O nome é jogo do NIM, vai ser usado 6 funções, e conforme termina uma, ela passa pra outra função e executa. Não sei se perdi alguma parte da teoria, mas não tenho ideia de como fazer essa passagem

Testar função de soma


Existe algum comando no sql server que retorna o numero de registros de uma tabela?

Question: Possuo uma tabela chamada cliente com vários clientes já cadastrados e quero filtrar todos os clientes que tenham a mesma idade e obter um numero inteiro desses registros, no caso a quantidade de clientes com a mesma idade.
Comment: Eu nao sei como esta a sua tabela, mas acredito que você possa usar o COUNT na sua consulta.
https://docs.microsoft.com/en-us/sql/t-sql/functions/count-transact-sql?view=sql-server-2017
Comment: Precisa definir melhor o problema, a descrição está ambígua. Oque é ter a mesma idade? Comparado a que? Dependendo da descrição todos clientes tem a mesma idade de outro cliente a não ser que ele seja o único com aquela idade, o que é raro acontecer em bases com um tamanho até pequeno, e mesmo que dê uma pequena diferença deve ser irrelevante.
Comment: E você tem o que cadastrado em sua tabela a idade ou a data de nascimento? Caso seja a data de nascimento você quer comparar com a data corrente e qual a precisão que gostaria de utilizar para comparar a igualdade de idade, anos? anos/meses? anos/meses/dias? Se você deseja contar os clientes com a mesma idade então o resultado desta contagem certamente será um número inteiro.
Comment: @RaquelAndrade Obrigado, seu comentário me ajudou bastante. :)
Answer: Estou considerando que você tem uma tabela chamada Cliente, e nessa tabela tem um campo chamado DataNasc.
O código abaixo retorna uma lista de todas as idades e a quantidade de registros com aquela idade:
declare @hoje as datetime = getdate()

select idade, count(*) as qtd_idade
from (
    select CASE WHEN datepart(mm,DataNasc) > datepart(mm,@hoje) OR
                      (datepart(mm,DataNasc) = datepart(mm,@hoje)
                   AND datepart(dd,DataNasc) >= datepart(dd,@hoje))
                THEN DATEDIFF(year, DataNasc, @hoje) - 1
                ELSE DATEDIFF(year, DataNasc, @hoje)
            end as idade
    from Cliente
) as t
group by idade

Me avise se eu tiver entendido errado.


Strumming all string but just one note. Something like Jimi Hendrix did

Question: Sometime ago I found a video on Youtube showing that strumming all strings but playing just one makes the improvisation/the rhythm a lot more 'richer'.
Now I see how amazing it's and I want to train, but I don't find much videos speaking of this... Is there a name to refer this?
I want exercices/tutorials of something like said on this video, by Paul Davids:
Answer: It's called left hand muting or fretting hand muting. You can mute with either hand, but when you're strumming with your picking hand it is not available to mute.
I'm not a fan of the presentation the guy makes in the video you linked, but at least he shows what he's doing. If you watch his hand, he always has one to three fingers spanned across all the strings. Those fingers are muting. If you mute behind the finger that's fretting, the fretted note will sound even though you have muting behind. You can also mute above and below the fretted string to isolate the note you want to hear.
I would practice muting all of the strings and strumming until you can get a clean chick sound and you can do the muting easily. Then try using just your third finger to fret notes while muting all the strings with your first and second fingers. Expand your muting and fretting practice and start to play actual riffs and songs with this technique.
I highly recommend when learning this technique that you learn thumb muting as he says in the video. To do it, you have to get your hand right up against the back of the guitar neck. There should be no gap at all, the web between your thumb and first finger should be totally touching the neck. You might find with this hand position that you can't easily play the low E string because it's too far away from your knuckles. You can either shift your hand just for those notes, or you can fret with your thumb! I prefer the latter.


How to position rectangles such that they are as close as possible to a reference point but do not overlap?

Question: Given a set of rectangles contained within a larger rectangle such that none overlap, what is the most efficient way to determine the position of a new rectangle such that it is as close as possible to a given reference point while still not overlapping any existing rectangle?
For example, in the following diagram:

the two red rectangles are positioned within the larger, black rectangle, and a third, green rectangle is to be added. The proper position of that green rectangle is shown given three example reference points, denoted by small, blue squares. You'll see that the proper position of the green rectangle always corresponds to the shortest possible distance to its reference point, illustrated by blue lines.
Edit: I should add that the reference point will always lie on the edge of the bounding rectangle.
Comment: How are you defining the closeness of the newly-placed box? The nearest point on that box to the reference point? For example, on the bottom-right of your picture your ray would actually be shorter if it were measuring distance, and would go to the bottom-right corner of the green box.
Comment: Though I suppose you would want to alter that notion when the box could partially or fully overlap the reference point.
Comment: the closeness is defined by the distance between the reference point and any constant point on the box. so in the example i've used the top left corner, but you could use the center, as long as you're consistent
Comment: So, the nearest point on the (filled) box.
Comment: on second thought, it would probably be best to use the center of the box-to-be-placed to calculate distance to the reference.
Answer: I've decided this is way too complicated to ask someone to do for you. Here are my thoughts:
Let $T$ be the rectangle to place.

Consider the outer dilation of each rectangle already placed by $2*T$ (double both dimensions - see Wikipedia picture), and the inner dilation of the bounding rectangle. If the point of reference is not in the union of these dilations, there must be no box near enough to it to stop you placing the box directly on it.
Consider that the whitespace of a rectangle - the dilation minus the rectangle - has the same width or the same height as $T$ in any region. This implies that if one box enters the whitespace of another, both boxes are in eachother's whitespace.
Notice this can be associated with a specific Region of Anger. If Box A is above Box B, projecting each box's vertical sides onto the other's horizontal sides will yield two or four of the corners of this Region of Anger. See: collision detection using Separating Axis Theorem.
Notice the whitespace of the Region of Anger is within the union of Box A and Box B's whitespace. So, the collision regions for rectangles is stable. However, the Total Region of Anger is not - consider placing a box a little to the bottom-right of the two red boxes, and removing the two Regions of Anger it would create for $T$. It would not remove the corner region. Thus, if one removes Regions of Anger pairwise, one does not need to add it as a new box and redo the whole calculation, but rather to, upon detecting whitespace infringement, add all infringers (one one side of the same box) to a list, and then add each Region of Anger obtained pairwise to the list of infringers until no new boxes are added
If there are no infringers on some box's whitespace, of course that box can simply be removed from the union of the dilations. The analogous thing when there are some whitespace infringers is to take the union over all the boxes in infringement lists on all sides as well as all boxes with no infringers, and remove THAT from the union of dilations. This I reckon will leave only whitespace some $T$ can sit in at all, reducing the problem to calculating the nearest point in this region to the reference point.
Comment: this definitely gets me going in the right direction, thanks!
Comment: Sure thing! Have to say though, this is purely heuristic, and when I do heuristic things like collision detection algorithms I often get it wrong.
Comment: I have an addendum I've been meaning to make: You can also skeletonize the whitespace put out by this process. By reducing every region of whitespace to the inner region at least half the width of $T$ from the horizontal edges and the same vertically, you obtain the set of points where the *center* of $T$ can be placed without overlap. It will avoid branching when defining the nearest point, the other pts on $T$ are detemined by it, it might only be made of lines, and if the target isn't in a solid region's interior, only the boundary of the region will be extremely close.


Probability with percentage

Question: I'm new at probability. Could anyone explain me how to calculate the problem below?
A recent survey revealed that 54% of 18 to 34 years olds, 33% of 35-54 years olds, and 15 % of 55+ years old own smartphone. If 9 people ages 18 to 34 are randomly selected, find the probability that no less than 7 own a
smartphone
My problem is that th examples doesn't make sense. From the image below, how (0.3) power 2 * (1 - 0.3) power 4 = 0.324135 ???
(0.3) power 2 = 0.09
(1 - 0.3) power 4 = 0.2401
Now:
0.09 * 0.2401 = 0.021609 NOT 0.324135 ????

Thanks
Comment: Look up the binomial distribution.
Comment: An example of how to look it up? https://lmgtfy.com/?q=binomial+distribution
Comment: Could you please give an example?
Comment: I always find simple examples with coins. Nothing like my question. Thank you anyway
Comment: Hint: this is a binomial experiment.
Comment: You are flipping a coin that lands heads $54\%$ of the time.  You need $7, 8$ or $9$ heads in $9$ tries.  That should match the description of the binomial distribution you find.
Comment: I just updated the post with an example of what does make sense to me
Answer: The "biased coin" is just a metaphor for any kind of procedure you can do where you can identify two possible outcomes, and each time you do the procedure there is the same probability $p$ that you will get the "good" outcome.
"Tossing the coin" can mean you randomly select someone between the ages of 18 and 34 and ask if they have a smartphone.
"Comes up heads" can mean that they say "yes."
To interpret the examples, it's important to account for all parts of the formula.
The general formula you found (at the top of the article) is
$$
\mathrm{Pr}(X = k) = \binom nk p^k (1 - p)^k
$$
where $\displaystyle\binom nk = \dfrac{n!}{k!(n-k)!}.$
The notation $\displaystyle\binom nk$ is called a binomial coefficient.
(That is why the probability distribution is called the binomial distribution.)
The notation $n!$ is a factorial; it says to take the product of the first $n$ positive integers.
Sometimes the binomial coefficient is written
$$\displaystyle\binom nk = \dfrac{n(n-1)(n-2)\cdots(n-k+1)}{k(k-1)(k-2)\cdots 1},$$
that is, there are $k$ factors in the numerator, the largest factor being $n,$
and $k$ factors in the denominator, the largest being $k.$
So in the example where $p = 0.3$, $n = 6,$ and $k = 2,$ you are correctly calculating that
$p^k = 0.3^2 = 0.09,$ that $(1 - p)^{n - k} = (1 - 0.3)^4 = 0.2401,$
and that $p^k = (1 - p)^{n - k}= 0.3^2 (1 - 0.3)^4 = 0.021609.$
But there are three factors in the formula:
$p^k,$ $(1 - p)^{n - k},$ and (first of all!) $\displaystyle\binom nk.$
So we also need to compute
$\displaystyle\binom nk = \displaystyle\binom 62$
and multiply $0.021609$ by that number.

Conceptually, the product $(1 - p)^{n - k}$ tells us the probability of a certain sequence of outcomes,
for example with $n = 6$ and $k = 2$ (two heads out of six)
one of the sequences is (tails, tails, heads, tails, heads, tails).
But if we are just interested in whether there were exactly two heads,
not whether they happened to occur on the third and fifth attempt,
we also want to count sequences like (heads, heads, tails, tails, tails, tails)
and (heads, tails, heads, tails, tails, tails).
Every such sequence has the same probability to occur, but each sequence is an exclusive event that prevents any other sequence from occurring,
and there are $\displaystyle\binom nk$ possible sequences of $k$
"heads" outcomes in $n$ attempts.
Hopefully if you are in a position to be asked a question like this you are taking a course in probability. You should then have a textbook or course notes containing explanations of these things, hopefully better than mine.
That is actually where to look for definitions of things such as "binomial distribution", not on the internet (even if someone snarkily tells you to "Google it").

Probability with percentage


OpenEdge ODBC for Access

Question: I cannot update the links in my access to a new ODBC driver.
I believe it to be that OpenEDge 10.1C is not doing a handshake with Access.
The dns will import external data into excel. The error is "error(-7748) the is no message for this error"
Answer: Most "weird" errors involving SQL and Progress are a result of the fact that Progress stores all data as variable length.  Furthermore most of the data in most Progress databases is created, updated and manipulated by 4GL programs and those programs have no awareness of nor any sensitivity to SQL's ideas regarding column width.
Your first line of defense when you get a strange error trying to query a Progress database with SQL should be to run dbtool (on the db server) to fix any possible SQL width issues.  Simply run dbtool (found in the Progress "bin" directory, $DLC/bin/dbtool if the OS is UNIX, use "proenv" to get a command prompt and then %DLC%\bin\dbtool if you are running Windows) and select option 2.  You may want to script this and run it automatically if you frequently have issues.
Comment: I don't quite understand the relevance of variable-length storage here, given that Access's default database engine, Jet/ACE, has always used variable-length storage. That's a db engine detail that your interface layer should completely abstract away from you and shouldn't have any relevance at all with an ODBC driver.
Comment: Even if Access uses variable width fields if it is assuming that it can trust the width information that it gets from the Progress schema then it is going to be disappointed.

I'm just saying that an awful lot of weird issues that people have using ODBC with Progress databases are fixed by running dbtool and fixing the SQL width.  It's worth a try.
Answer: Progress ODBC error -7748 can be solved by adding a registry entry. This discussion explains the workaround and what it does.
Essentially, the registry key:
<code>HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\[Your data source name]
</code>
should be a string value entry named 'Workarounds2', and its value should be set to 8192.
See:
http://media.datadirect.com/download/docs/odbc/allodbc/index.html#page/odbc/workaround-options.html

OpenEdge ODBC for Access


What does the actual difference in sound between different brands of electric guitars come from?

Question: I own 2 different electric guitars (a Fender stratocaster and a Gibson SG) and this question came to mind.
How do the actual differences in sound differ between the two?
And by which components this diversity is influenced?
For example: from the harder and more metallic sound of the Gibson, to a higher and more "jazz" sound of the Fender.
Comment: See [Is EQ the only reason pickups sound different?](https://music.stackexchange.com/questions/120810/is-eq-the-only-reason-pickups-sound-different)
Answer: The main factor will be the pickups. Standard Strats have single coil, while SGs have humbuckers. There's also the placement of pups - 3 on the Strat, two on the SG.
The strings will probably be different gauges, as the scale lengths are different, so that will add to different sounds.
The SG has a through-neck, compared wth a bolt-on for Strats, and some say that the wood - or more importantly its density - for both body and neck - are contributing factors. As are the differences between vibrato on Strat compared to none on SG - where the strings go straight over the bridge and into the part holding the bullets - although I'm sceptical those factors make much difference, as the strings don't vibrate on that side of the bridge, in either case.
All that, and subtle differences in the circuitry used, add up to a marked difference in sound.
Comment: @CarlWitthoft - OP asks about the *difference in sound*, and the strings and their material will have a marked difference to that effect. Notwithstanding the gauge may well be different due to the scale lengths. Don't think the decay curve influences the *sound*, though.
Comment: thank you @Tim very much for the comprehensive answer. I didn't think so many factors could actually change the sound so much! Have a great day!
Comment: I tend to agree with Tim here.  Notice that all the important factors relate to the electronics, and second-most important (my view) to string type & thickness, which will affect the decay curve of the string's vibration.
Answer: If we ignore things like EQ the major influence on the tone comes from the pickup position, pickup height/action. You get some influence from the pickup design and things like the scale length, and then a minor influence from the strings, and the materials the instrument is made of (unless it is a very bad instrument, in which cases this might have a big negative effect).
Also the probably biggest influence is how the player plays the instrument. Different designs will lead to different comfortable playing positions.
Comment: I daresay OP will play both guitars similarly.
Comment: @Tim Wouldn't think so. The shape of the instrument has an effect on how you hold it, and this may lead to differences in playing position


How to find position in outer coordinates of a point inside a rotated rectangle?

Question: I have a feeling this has a simple solution however it eludes me. It's a simplified version of a real problem. Any tips or pointers are appreciated.

Given a point inside a rectangle where you know the position of the point relative to the rectangle boundary (b, a in the image). When the rectangle is rotated $\pi/4$ so it touches the axis, what is the coordinates of the point in the outer coordinates.
The width and height of the internal rectangle are also known.
Comment: For both segments $a$ and $b$, it is easy to find the lengths of their projections onto the horizontal and vertical axes.
Comment: Ooh, so you can do C + project(b) - project(a) = x, and C + project(a) - project(b) = y, thanks.
Comment: For $y$, the length $c$ is not related. $y = a\cos\frac\pi4 + b\sin\frac\pi4$. @Annan
Answer: In general, the black rectangle was transformed by a translation after rotation.
First, the red dot has a coordinate $\begin{bmatrix}b\\a\end{bmatrix}$.
The black rectangle is rotated anticlockwise by $\theta = \frac\pi4$:
$$\begin{bmatrix}x'\\y'\end{bmatrix}
= \begin{bmatrix}\cos\theta&-\sin\theta\\\sin\theta&\cos\theta\end{bmatrix}\begin{bmatrix}b\\a\end{bmatrix}
= \begin{bmatrix}b\cos\theta-a\sin\theta\\b\sin\theta+a\cos\theta\end{bmatrix}$$
Then the rotated black rectangle is translated right by $\begin{bmatrix}c\\0\end{bmatrix}$:
$$\begin{bmatrix}x\\y\end{bmatrix}
= \begin{bmatrix}x'\\y'\end{bmatrix}+\begin{bmatrix}c\\0\end{bmatrix}
= \begin{bmatrix}c+b\cos\theta-a\sin\theta\\b\sin\theta+a\cos\theta\end{bmatrix}$$


How do I inherit from the base theme?

Question: I want to inherit from the businessplus_lite theme I use as base theme, but I can't see any CSS applicable. There is just a board template blank with articles. Can anyone tell me how I can inherit the CSS styles from businessplus_lite?
name: some name
type: theme
description: 'description for my theme'
core: 8.x
base theme: businessplus_lite

Answer: It looks like you've created the *.info.yml file, but not yet created a *.libraries.yml file.
The libraries file is where you'll define which CSS is used in your theme.
See for more details on how to set this up: https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme#s-example-sub-theme-fluffiness
Comment: There should be no need for a libraries.yml just to inherit them, you only need this if you want to define your own libraries.
Comment: the css of the templates located in the base theme i think , how can i call them in labraries.yml of sub-theme??
Comment: Usually you'll want some custom CSS. I'll leave that part of the answer for you or anyone else who views this problem. Plus, I'll add some info for linking it all together.
Comment: yes please bro ;)

How do I inherit from the base theme?


Why is my Pantheon git clone not loading correctly?

Question: My website is on Pantheon. I am using linux ubuntu 17.10 and LAMP for local development. I use the git clone command and it works. My drupal 8 files are there. Then I export and import the database sql file and the files folder. When I load my website on the local host I get this:

How do I fix this? What am I doing wrong? Am I missing a step?
Comment: If the CSS is messed up, re-save the theme settings in the UI.  This will re-create the relevant files
Comment: Also, consider using Lando for Pantheon development instead of a LAMP stack.  You can pull your Pantheon site with a single command and you get terminus, drush, and all the relevant tools installed for you.  In addition, Lando uses nginx, not apache, so your local dev server will basically be the same as the Pantheon one.  https://github.com/lando/lando
Answer: The issue you're exhibiting is most likely a result of the database reflecting a temp directory (on the Pantheon server) that does not exist or is not writable on your local LAMP environment.
To reset the temp directory for your local development instance, you can:

use drush to set the temp directory (typically /tmp)
navigate to admin/config/media/file-system

If after setting the temp directory and clearing caches, you still exhibit similar behavior, you may want to double check the file owner/group permissions for the public files directory.
See https://www.drupal.org/node/244924 for a how to identify and set permissions, and refer to http://www.drupalden.co.uk/file-folder-permission-settings-drupal-7 which provides a good summary (note- permissions recommended for D7 also apply to D8)
Answer: If you have "Aggregate CSS files" and "Aggregate JavaScript files" checked in /admin/config/development/performance then the site will be trying to aggregate css and js files below the sites/default/files directory. However that site is not included in the codebase cloned from Pantheon, and you might not have thought to create it, especially if you haven't added files to your site.
Quick Fix:
As a quick fix you can uncheck "Aggregate CSS files" and "Aggregate JavaScript files" checked in /admin/config/development/performance, then refresh the page. If that doesn't work then click "Clear all caches" on the same page. However your site will perform better with those 2 aggregation boxes checked. So...
Better Fix:
A better solution is to visit your site's Pantheon dashboard, switch to the Git mode, open "Backups", create a new backup, then download the "Files" backup. Extract that downloaded tar.gz file which will give you a directory called something like files_dev. Move that directory into sites/default/ and rename it to files. Check that it has drwxr-xr-x permissions. If not then cd to its parent default directory and issue the command chmod 755 files.
You should also check that your sites/default directory has drwxr-xr-x permissions. If not then open a terminal, cd to your sites directory and issue the command chmod 755 default.
Refresh the site and if necessary clear all caches and the css/js should work again.
For me this fixed a similar issue after importing a site from Pantheon to Lando.


Programmatically showing the summary of a post

Question: What's the PHP code to call summary of a post (teaser) in a custom page?
I use Drupal 6 and I want to show a small part of a specific post in a custom page.
Comment: node_teaser() for Drupal 7, text_summary() for 7.
Answer: You can use teasers from node. In node.tpl.php you can use $teaser variable to print it.
In other templates, you need to use node_load().
$node = node_load(211); // 211 is the Node ID
print $node->teaser;

Comment: Keep in mind that $teaser is not same as node_teaser() always because user can enter a different teaser instead of allowing Drupal to trim the content at a length.
Comment: Thanks, It works great. how can I find out other properties related to $node? like "title"?
Comment: Just print `$node` (`print_r($node)`). You will get other related data for that node including title.
Answer: Apart from the $teaser variable, you can also use the node_teaser() function (http://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_teaser/6). This allows you to create a custom teaser, in case $teaser is not present.
Answer: The function that creates the teaser of a node is node_teaser(), which is called from node_submit(), the function called from the form submission handler for the node edit form, and from node_preview(), the function used to create a preview of the node being saved.
It can happen a node doesn't have a teaser, for example when a module saves the node using node_save(). in such cases, you can use code similar to the following one.
$node = node_load($nid);
if (!isset($node->teaser)) {
  if (isset($node->body)) {
    $node->teaser = node_teaser($node->body, isset($node->format) ? $node->format : NULL);
  }
  else {
    $node->teaser = '';
    $node->format = 0;
  }
}

To notice that Drupal 7 doesn't have the node_teaser() function anymore, as the body of a node is a field.
Comment: Thanks kiamlaluno, It helped me out to fix my other problem.


is there a problem in the answer? finiding an angle

Question: Can you tell me if there's an error in the answer ?
Given isosceles $\triangle ABC$ ($AB=AC$) and $AB=b$.
$BD$ is perpendicular to $AC$ and $DE$ is perpendicular to $BC$.
$\angle BAC=2x$.
The question is what should be $\angle BAC$ so $DE$ will be maximum ?
The answer is $109.47^\circ$ but isn't it an angle in a right triangle?
Thanks!
Answer: I assume $D\in AC$ and $E\in BC$.
Note that $BD=b\sin2x$ and $DE=BD\sin\angle BCD$. Since $\angle BCD=\frac \pi2-\angle ACB = \frac\pi2-\frac{\pi-2x}2=x$, we find
$$ DE = b\sin2x\sin x$$
which you can maximize with calculus methods.
This task may be simplified if you let $y=\cos x$ and observe that
$$ \sin 2x\sin x=2\sin^2x\cos x=2(1-\cos^2x)\cos x=2(y-y^3).$$
Comment: i know how "to solve" it, my problem is that triangle $ABD$ as a right angle so how can angle $BAC$ be $109.47^0$?
Comment: because then the sum of angles in triangle $BAD$ is more than $180^0$
Comment: @daveo How is the sum of angles in $BAD$ more than $180^\circ$? Make a sketch. You will find that $\angle BAC=109.47^\circ$ and $\angle DAB=70.53^\circ$.
Comment: but $\angle BDA=90^\circ$
Answer: I am assuming that you already know how to solve the problem and have got the following relation:
$$ DE = b\sin2x\sin x$$
Since $x$ can only take values in $(0, \pi/4]$ in order to not violate any triangle properties, we need to maximize DE in this interval to get the correct answer. You'll find that $DE$ increases monotonically in the said interval. So, at $x = \pi/4$, $A$ and $D$ are the same point (your problem doesn't prohibit that) and $DE_{max} = b/\sqrt2$.