CSS Responsive Layout help: Div not staying on the same line

Question: I'm in the beginnings of teaching myself how to code and working on an assignment to create a responsive site but can't use frameworks like Twitter bootstrap or any of the new grid properties. The problem is I'm trying to get 3 divs to align for devices with a min-width of 992px and for devices with a min-width of 768px and a max-width of 991px, I'm trying to get two across the two and one at the bottom. With my current code, I can get 3 across the top but when I go to tablet devices I'm getting all 3 laid vertically and taking 50% of the screen.
I've tried adjusting the width property, removing padding and margins, adding an overarching div with the class of "container", border box, removing and adding the float property.
Here's my current CSS code and image of what's expected.
*{
    box-sizing: border-box;
  }

body {
    background-color: white;
    margin: 0px;
}
h1 {
    color: black;
    text-align: center;
}

.container {
    width: 100%;
}

section {
    background-color: gray;
    border: 1px solid black;
    margin: 5px;
}
p#description {
    /*text-align: left;*/
    /*font-weight:100;*/
    padding-top: 20px;
    padding-left: 20px;
    padding-right: 20px;
    /*padding-bottom: 0px;*/
    height: 250px;
}
p#suboptions {
    float: right;
    border-left: 1px solid black;
    border-bottom: 1px solid black;
}
p.chick {
    background-color: lightpink;
    color:black;
    text-align: center;
    font-size: large;
    font-weight: bold;
    font-family: 'Times New Roman', Times, serif;
    width: 25%;
    margin-top: 0px;
    padding: 5px;
}
p.beef {
    background-color:maroon;
    color: white;
    text-align: center;
    font-size: large;
    font-weight: bold;
    font-family: 'Times New Roman', Times, serif;
    width: 25%;
    margin-top: 0px;
    padding: 5px;
}
p.sushi {
    background-color: blanchedalmond;
    color:black;
    text-align: center;
    font-size: large;
    font-weight: bold;
    font-family: 'Times New Roman', Times, serif;
    width: 25%;
    margin-top: 0px;
    padding: 5px;
}

@media (min-width: 768px) and (max-width: 991px) {
/*tablets*/
.col-s-1 {width: 8.33%;}
.col-s-2 {width: 16.66%;}
.col-s-3 {width: 25%;}
.col-s-4 {width: 33.33%;}
.col-s-5 {width: 41.66%;}
.col-s-6 {width: 50%;}
.col-s-7 {width: 58.33%;}
.col-s-8 {width: 66.66%;}
.col-s-9 {width: 75%;}
.col-s-10 {width: 83.33%;}
.col-s-11 {width: 91.66%;}
.col-s-12 {width: 100%;}
section {
    float: left;
    margin: 5px;
}
p#description {
    height: 170px;
}
}

@media (min-width: 992px) {
    .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 {
      float: left;}
.col-lg-1 {width: 8.33%;}
.col-lg-2 {width: 16.66%;}
.col-lg-3 {width: 25%;}
.col-lg-4 {width: 33.33%;}
.col-lg-5 {width: 41.66%;}
.col-lg-6 {width: 50%;}
.col-lg-7 {width: 58.33%;}
.col-lg-8 {width: 66.66%;}
.col-lg-9 {width: 75%;}
.col-lg-10 {width: 83.33%;}
.col-lg-11 {width: 91.66%;}
.col-lg-12 {width: 100%;}
}

Comment: CSS is meaningless without some HTML. Please provide some. Put it all in a working demo using the editor, and scrap the images.
Answer: So after 992px you can use FlexBox to align all items horizontally in a row.
Between 768px and 992 you can use CSS Grid to create 2x2 grid and third box will span in 2nd row.

.container {
  height: 100vh;
  max-width: 1100px;
  margin: 0 auto;
}

.box-1 {
  background-color: red;
}

.box-2 {
  background-color: green;
}

.box-3 {
  background-color: blue;
}

@media screen and (min-width: 992px) {
  .container {
    display: flex;
    flex-direction: row;
    padding: 5rem;
  }

  .container > * {
    flex: 1;
    height: 300px;
  }
}

@media screen and (min-width: 768px) and (max-width: 992px) {
  .container {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);
    padding: 5rem;
  }

  .box-3 {
    grid-column: 1 / span 2;
  }


Calculate the MLE of $\lambda$ when $\lambda \in \{4,5,2 \}$

Question:
$s = \{4, 4, 1, 5, 4 \}$ is an observed sample from a Poisson$(\lambda)$ distribution where $\lambda \in \{4,5,2 \}$ is unknown. Calculate the MLE of $\lambda$.

Attempt:
$L(\lambda \mid s) = e^{-n\lambda} \lambda^{n \bar{x}}$
$L(\lambda = 4\mid s) = e^{-5 \cdot 4} 4^{5 \cdot 3.6} \approx 141.641$
$L(\lambda = 5\mid s) = e^{-5 \cdot 5} 5^{5 \cdot 3.6} \approx 52.9783$
$L(\lambda = 2\mid s) = e^{-5 \cdot 2} 2^{5 \cdot 3.6} \approx 11.9013$
Therefore the MLE is $$\hat{\lambda} = 4$$
I can do this right? Just see which has the highest value and in this case it was $\lambda = 4?$
Comment: What you did is correct.
Answer: The likelihood is the probability you get all the data you find given a particular Poisson distribution having (unknown) $\lambda$.
This likelihood is the product of the individual probabilities you get the measured data:
$$P(4|\lambda)^3 P(1|\lambda) P(5|\lambda) = \frac{e^{-5 \lambda } \lambda ^{18}}{1658880} \propto e^{-5 \lambda } \lambda ^{18}.$$
You take the derivative of this with respect to $\lambda$, set it to zero (to find the maximum), which happens to be $3.6$... which makes eminent sense.
Here's the resulting distribution:

If you must select from the three $\lambda$s given, then compute the value of the expression above for each of the three candidate $\lambda$ values and choose the one that leads to the highest likelihood.
(Incidentally, perhaps you can see from this problem why we frequently work with the log likelihood...)
Comment: Did I not apply that above formula for the given $\lambda$ and chose the highest likelihood ? Oh, did you mean $\hat\lambda = 141.61?$
Comment: You are incorrect to write $\hat{\lambda} = 141.61$.  $\hat{\lambda}$ denotes the estimate of the *Poisson parameter*, while the $141.61$ is proportional to the *likelihood*.  Be sure you're clear on the difference!!
Comment: Gosh... not even an upvote!
Comment: Please remove the bit about differentiation with respect to $\lambda$ which is not valid here. Obviously we must select from the three given values of $\lambda$.


React navigation não redireciona na primeira vez

Question: Boa noite, tenho um preload que redireciona o usuário para determinadas telas de acordo com alguns parâmetros, ele somente redireciona quando eu atualizo a tela do emulador.
import { StackActions, CommonActions } from '@react-navigation/native';
import React, { useState, useEffect } from "react";
import { connect } from 'react-redux';

const mapStateToProps = (state) => {
    return {
        name: state.userReducer.name
    }
}

const Preload = (props) => {
    function onRedirect() {
        if (!props.name) {
            //mandar para starter stack
            props.navigation.dispatch(CommonActions.reset({
                index: 0,
                name: "teste",
                routes: [
                    { name: 'StarterStack' }
                ],
                actions: [
                    CommonActions.navigate({
                        name: 'StarterStack'
                    })
                ]
            }))
        } else {
            //app tab
            props.navigation.dispatch(CommonActions.reset({
                name: "AppTab",
                routes: [
                    { name: 'AppTab' }
                ],
                actions: [
                    CommonActions.navigate({
                        name: 'AppTab'
                    })
                ]
            }))
        }
    }
    useEffect(() => {
        onRedirect();
    }, []);

    return null;
}

export default connect(mapStateToProps)(Preload);

Answer: Sempre coloque as referências utilizadas como dependência do useEffect, com isso você garante que ele possui a versão mais atualizada da referência que ele está usando.
useEffect(() => {
    onRedirect();
}, [onRedirect]);

Outra possibilidade é colocar toda a função dentro do useEffect.
Comment: Ainda não funcionou amigo, já tentei colocar console log dentro do if para ver se estava entrando mesmo e ele entra porem não redireciona.


Value of the Eigenfunction at a point

Question: I'm reading "Laplace-Beltrami Eigenfunctions for Deformation Invariant Shape Representation" http://www.cs.jhu.edu/~misha/Fall07/Papers/Rustamov07.pdf
At a certain point the author states
"where φi(p) is the value of the eigenfunction φi at the point p."
What does that mean? Cuz if you just multiply the eigenvector φi times the point p = (x, y, z) the only possible result is a Nx3 matrix, where N is the dimension of the eigenvector. However, this doesnt make any sense (I think...it's more likely I just didnt understand it).
Answer: Note that it's an eigenfunction not eigenvector. For example an eigenfunction with eigenvalue $\lambda$ of the operator $$\frac{d}{dx}$$ is a solution to $$\frac{d}{dx}f=\lambda f$$ which is $f= e^{\lambda x}$

Value of the Eigenfunction at a point


SonarQube Force Authentication with Anonymous scan upload

Question: tl:dr; We would like to enable Force Authentication while still allowing anonymous scans/uploads to sonarqube.
Sonarqube v.6.7.5
We have a requirement of enforcing authentication into the sonarqube UI. To enable this, we have configured LDAP and the "Force Authentication" option.
This has worked as desired from the UI's perspective as we wish to limit who can view the projects/scans on sonarqube. However, we would still like anyone (anonymous users) to submit their projects for scanning analysis (they will just have to login to actually see the results).
Upon enabling Force Authentication, our previously working maven command fails with the following error (below). I am aware of using the sonar.login and sonar.password arguments, but we would like to avoid that, and allow anonymous users. Mainly we would like to avoid people having to send in their credentials or tokens and just use a simpler command.
Is it possible to have both Forced Authentication while still allowing anonymous uploads to sonarqube? Any help would be greatly appear, thank you
Regards,
Erik
mvn command:
<code>mvn -X -Dsonar.clover.reportPath=target/site/clover/clover.xml -Dsonar.host.url=${sonarqube_url} org.sonarsource.scanner.maven:sonar-maven-plugin:3.2:sonar
</code>
maven output*:
<code>[DEBUG] 14:20:22.416 GET 401 ${sonarqube_url}/sonar/api/settings/values.protobuf | time=215ms
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.404 s
[INFO] Finished at: 2019-06-27T14:20:22-07:00
[INFO] Final Memory: 12M/194M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.2:sonar (default-cli) on project cyberark-poc: Unable to load component class org.sonar.scanner.bootstrap.ScannerPluginInstaller: Unable to load component class org.sonar.home.cache.FileCache: Unable to load component class org.sonar.scanner.bootstrap.GlobalConfiguration: Not authorized. Analyzing this project requires to be authenticated. Please provide the values of the properties sonar.login and sonar.password. -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.2:sonar (default-cli) on project cyberark-poc: Unable to load component class org.sonar.scanner.bootstrap.ScannerPluginInstaller
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:309)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:194)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:107)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:993)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:345)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:191)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Unable to load component class org.sonar.scanner.bootstrap.ScannerPluginInstaller
at org.sonarsource.scanner.maven.bootstrap.ExceptionHandling.handle(ExceptionHandling.java:36)
at org.sonarsource.scanner.maven.bootstrap.ScannerBootstrapper.execute(ScannerBootstrapper.java:81)
at org.sonarsource.scanner.maven.SonarQubeMojo.execute(SonarQubeMojo.java:122)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
… 20 more
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.bootstrap.ScannerPluginInstaller
at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
at org.picocontainer.DefaultPicoContainer.instantiateComponentAsIsStartable(DefaultPicoContainer.java:1034)
at org.picocontainer.DefaultPicoContainer.addAdapterIfStartable(DefaultPicoContainer.java:1026)
at org.picocontainer.DefaultPicoContainer.startAdapters(DefaultPicoContainer.java:1003)
at org.picocontainer.DefaultPicoContainer.start(DefaultPicoContainer.java:767)
at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:134)
at org.sonar.batch.bootstrapper.Batch.doStart(Batch.java:94)
at org.sonar.batch.bootstrapper.Batch.start(Batch.java:88)
at org.sonarsource.scanner.api.internal.batch.BatchIsolatedLauncher.start(BatchIsolatedLauncher.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.sonarsource.scanner.api.internal.IsolatedLauncherProxy.invoke(IsolatedLauncherProxy.java:60)
at com.sun.proxy.$Proxy23.start(Unknown Source)
at org.sonarsource.scanner.api.EmbeddedScanner.doStart(EmbeddedScanner.java:220)
at org.sonarsource.scanner.api.EmbeddedScanner.start(EmbeddedScanner.java:156)
at org.sonarsource.scanner.maven.bootstrap.ScannerBootstrapper.execute(ScannerBootstrapper.java:60)
… 23 more
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.home.cache.FileCache
at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:62)
… 51 more
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.bootstrap.GlobalConfiguration
at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
at org.picocontainer.injectors.SingleMemberInjector.getMemberArguments(SingleMemberInjector.java:61)
at org.picocontainer.injectors.MethodInjector.getMemberArguments(MethodInjector.java:100)
at org.picocontainer.injectors.MethodInjector$2.run(MethodInjector.java:112)
at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
at org.picocontainer.injectors.MethodInjector.decorateComponentInstance(MethodInjector.java:120)
at org.picocontainer.injectors.CompositeInjector.decorateComponentInstance(CompositeInjector.java:58)
at org.picocontainer.injectors.Reinjector.reinject(Reinjector.java:142)
at org.picocontainer.injectors.ProviderAdapter.getComponentInstance(ProviderAdapter.java:96)
at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:62)
… 65 more
Caused by: Not authorized. Analyzing this project requires to be authenticated. Please provide the values of the properties sonar.login and sonar.password.
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>
Answer: Accepting @agabrys' response as it answers the question, however posting our workaround for others who may be interested.
We will be disabling Force Authentication, and will be using Permission Templates, along with making projects private. This will prevent anonymous access to the analysis results and source code from the UI, however still allow anyone (anonymous) to submit code for analyzation.
Answer:
Is it possible to have both Forced Authentication while still allowing anonymous uploads to sonarqube?

No. You cannot force people to login and at the same time allow using the server without login (SonarScanner pushes results to the server by Web API services which are served by the same server which serves Web UI).
Comment: Hey @agabrys, thanks for responding. As a follow up, do you know if it's possible (or a way) to configure a type of _default_ token that we can somehow apply to all scan commands? Essentially, if people provide their own tokens, use that, however, if they don't provide anything, use a default token? Possibly via group configuration?
Comment: Two ideas (both ugly). 1) create your own scanner, which proxies the original scanner and add the default token if users didn't specify it. 2) configure a proxy server which will add the default token to request when it is missing.
Comment: Thanks again @agabrys. I think we will look at using permission templates. Possibly leave force authentication off, but make every project private. Then use groups to manage who can see what. A bit more administrative work, but a must to meet our requirements.


How do I filter items by name and timestamp range in django?

Question: I want to filter transactions by external id that fit in start and end date range. When I add dates within the range they don't show up. Here is my current code
filtered_transactions = Transaction.objects.filter(
        organisation_id_from_partner=organisation_id,
        timestamp__range=[latest_transaction.timestamp, start_date]
    )

Comment: It's not clear to me why you use `start_date` as the "end date" of the range?
Comment: Thanks @WillemVanOnsem that was my mistake. I should have started with start date(smaller date)
Comment: so your question is resolved?
Answer: Change the order of dates in range to start with the start_date
filtered_transactions = Transaction.objects.filter(
        organisation_id_from_partner=organisation_id,
        timestamp__range=[start_date, latest_transaction.timestamp]
    )


How to render mongodb data to ejs file?

Question: I am learning how to display mongodb data in html, but the code cannot work when I learn from network. I want to create the button to change the page to view data, and I don't know how to render data to ejs.
I try to find some method to solve the problem in network, but most of them are  not the problem which I get.
code of find data
app.post('/viewdata', function (req, res) {
res.render('staffDisplay');
try{
    MongoClient.connect(uri, function(err, client) {
        if(err) {
             console.log('Error occurred while connecting to MongoDB Atlas...\n',err);
        }else{
           var game=[];
           var collection = client.db("GameDB").collection("Game");
           var result = collection.find();

           result.forEach(function(error,result){
               if(error){
                   console.log(error);
               }else{
                   if(result != null){
                       game.push(result);
                   }else{
                       console.log(game);
                       res.render('views/staffDisplay.ejs',{game:result})
                   }
               }
           })

           console.log('show');
            client.close();
        }
     });
}catch(ex){
    throw new Error(ex.toString());
}
});

display.ejs
//skip the html code

      <% for(var i=0;i<=game.length;i++) {%>

<%=game[i].gName%>

<%=game[i].gDesc%>

<%=game[i].gDate%>

      <%}%>

the result is display 'game is not define', how can I do?
Answer: Can you try to remove this res.render('staffDisplay'); on the first part then replace res.render('views/staffDisplay.ejs',{game:result}) with this res.render('staffDisplay.ejs',{game:result})
Comment: it does not work, the result still is 'game is not defined'

How to render mongodb data to ejs file?


CouchDB setup issues. RHEL6

Question: I recently started an EC2 instance to test some couchdb projects, but for some reason I cannot seem to access the database.
Port 5984 is open on both RHEL and in the security group, but I get cannot connect issues both remotely and locally
Netstat also shows nothing listening on port 5984, even though couchdb is running and configured to listen on port 5984. The service is running, but it is like it isn't doing anything.
Any thoughts?
Comment: Can you please confirm that 5984 is allowed in the EC2 security policy?
Comment: Sorry! Obviously you already answered this question. I read it wrong. Check my answer below about the listen address.
Answer: Check your local.ini file, for the bind address. Perhaps the port is correct but the address is wrong. (By default, CouchDB only listens for local connections.)
[httpd]
    # ... snip other stuff ...
    bind_address = 127.0.0.1

Change to:
[httpd]
    bind_address = 0.0.0.0

And restart couch. Did that help?
Comment: If this answer is incorrect (I am nervous because you say local connections are also down), then would you mind updating your question indicating whether or not the logs show any information at all. The logs may have errors or not, but either way, that is a clue.
Comment: I have tried changing the bind_address in the local.ini, I will check the logs in the morning
Comment: So I just booted up a new instance and the first thing I did was install couch and change the local.ini file, no idea what the issue was on the other instance, but it works now. Thank you so much! (So much for going to bed an hour ago)
Answer: I had the same problem: service "running" but not logging anything and no port opened.
The cause is the following: I tried running couchdb as root directly after installing and before running it as a service. It created the log and db files with owner set to root, so when it was run as the proper service it couldn't access the files and couldn't even log about the problem. I deleted the /var/log/couchdb/couch.log and cleared /var/lib/couchdb and it seems to work now.
Maybe it was not the cause in your case, but the symptoms look pretty similar.

CouchDB setup issues. RHEL6


Users can't log in sometimes

Question: Drupal 7.5, PHP 5.6.27 Debian 8, remote host.
We are running into a problem where some people can't log in some of the time and sometimes it works if they try multiple times. Users have reported the issue with different browsers and only a small percentage of people seem to be affected. Please note that I can only reproduce the error on occasion, and very inconsistently.
Watchdog simply shows that a session is opened for the user, even if the front page shows that they are not logged in.
Edit: Users can usually log in if they enter the wrong password first!
Things I've tried:

changed cookie_domain from www. to .
made sure rewrite condition allows https
cleared Drupal cache
we have no external caching
added redirect from port 80 only to default-ssl.conf
Users can't always log in with a one-time log in link generated with drush uli "[username] (the site will ask them to log in)
creating a custom login module to set a new custom session suggested here
added some cookie configurations to the sites/default/settings.php file as suggested in this post
installed the website on a different environment with PHP 5.5 and different settings.php .htaccess and php and mysql configurations.

Known Workarounds:
May or may not provide clues.

Sometimes if we change a user's password, they can get in that way
If a user enters the wrong password first on purpose then logs in, they are able to log in
Sometimes we can provide a one-time log in link for users to get in, but that doesn't always work

Edit: I've managed to recreate the issue on a local development environment with different settings files. I removed all the settings files information from my original post since I know now that they are not relevant.
Comment: Note: "Make sure to always start the $cookie_domain with a leading dot, as per RFC 2109." So it should be `.example.com`.
Comment: Another thing to try would be to turn of any external cache. If you use something like Varnish this may cause users to see the "logged out" version even if they are logged in.
Comment: It does feel a lot like HTTP > HTTPS bouncing as enzipher already described. The user first fills his credentials in the HTTP version of the site, the form submission then redirects to HTTPS (because of the base url) and a new session is started. To debug, see if the login page is accessible via HTTP as well. See [Enabling HTTP Secure (HTTPS)](https://www.drupal.org/https-information) for what to do. I recommend the last option to redirect all HTTP traffic to HTTPS. The required `.htaccess` lines are at the bottom.
Comment: The site always comes up as https. If you attempt to go to http, it directs. When login fails for me, I make sure it's https.
Comment: Can you provide a link to the site and a dummy username/pw ?
Comment: http://www.fosterclub.com demouser123 / demo123. We're a non-profit organization and are currently working on either rebuilding or refreshing our website, but in the meantime, I need to make sure users are able to get in without being told to enter the wrong password first (which works most of the time) or without sending them a one-time log in, which also only works some of the time.
Comment: Does anyone think this could be related to some kind of log getting full or session tables?
Comment: Hi @Christia, please don't add meta commentary to the question. If you want to put a bounty on it you have enough rep to do so and it doesn't need to be added to the title as it will naturally appear on the featured questions tab when you start the process. Q+A doesn't suit eh kind of back and forth/polling for general ideas you seem to be hoping for, that's why comment threads are moved into chat where it's fine to have such discussions. If you need some input into how it could be changed to be easier to answer, please head over to meta and ask there (don't add it as a commentary to the...
Comment: ...original question). It's also worth bearing in mind that you might (only might, i don't know) not have enough information presented in the question yet for someone to be able to help. If you find yourself having several running conversations about different avenues to follow with different people, it's a good sign that there isn't enough detail yet for it to be a good question for the knowledge repository here. Best of luck
Answer: That can happen if the site is redirecting to a different domain or to a secure/non-secure protocol upon login. I.e. with/without www or to http/https. If so, you could set a base domain and cookie domain in settings.php, and/or enable www/non-www redirect in .htaccess.
It also seems there may be a problem with PHP 5.6.1.
https://www.drupal.org/node/2723927
https://www.drupal.org/node/2379019
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/50166/discussion-on-answer-by-enzipher-users-cant-log-in-sometimes-session-opens).
Answer: I believe there is some kind of caching in play here. I've found that I can successfully log in with the demo user provided by generating unique login URLs.  Each unique login URL I create has worked for me exactly one time and then no longer works after that.  This strongly suggests that something is caching pages based on their URL and dynamic backend functionality (PHP) is no longer taking effect on subsequent attempts to log in via that URL.
For example.. I could not log in via /user/login, but when I manually switched that to /user, I was able to log in once, but after logging out, I couldn't log in via that URL anymore.  I tried appending a series of ?itok=asdf query parameters to the login URLs and each would work once.  Adding numbers at the end of the query string did not appear to work, so ?itok=asdf1 worked, but then trying ?itok=asdf2 did not, but ?itok=asd did.
I've already burned /user/login/a and /usr/login/b with further testing.  To test this yourself, I suggest coming up with a unique alphabetical prefix and then alphabetically appending to that, e.g.
/user/login/prefix
/user/login/prefixa
/user/login/prefixb

... etc
Note again that in my testing each URL is working exactly once and "never" works again.. you must keep coming up with new ones to repeat the test.
As stated above, this strongly suggests something is caching pages based on the URL.
Comment: Nice sleuthing!
Comment: I don't have good suggestions on where to "look". In these kinds of situations I look for ways to "split the problem in half" such that I can determine it is either "somewhere over here" or "somewhere over there". If it were me, the first thing I would try would be to test whether it's part of the system the site is on or if it's in the site code itself.  I would do this by setting up another system to run the site, like a local development system (a Mac or a VirtualBox VM).  Export DB, copy files, see if the problem repeats itself in the new environment.
Comment: If the behavior persists in a new environment, it's somewhere in the Drupal site code most likely. If the problem disappears, it's something in the system or network where the site is running. With complex systems like these, the most effective way to isolate a problem is with various tests to see if it's generally on this side of the test or that side. Wandering around through code hoping to stumble on the core problem can take months.
Comment: @Christia I personally would test as mentioned above, but to to answer your question more directly -- I don't expect it to be in `php.ini` or `settings.php`. My guess would be a Drupal module or an outside "reverse proxy". Consider asking your network people how requests get routed to your site.  But hey, I could be wrong.  Complex systems and all that.
Comment: Wonderful insight!! Any suggestions on where to go to look at caching functions? Would it be in php.ini, settings.php, an installed module in Drupal or on the server or any/all of those things? I'll try to index all of possible caching systems we have. (I have no documentation from the previous developer).
Comment: It's worth noting that the problem could be entirely outside the server running the site.  Who manages the network?  Are they running some kind of "reverse proxy"?  At my previous job we used an outside service called Yottaa that sped up site requests by being a sort of _outside_ front-door. When someone hit `site.com/asdf`, they were actually hitting Yottaa and it would hit our server and fetch the page.  The next request to `site.com/asdf` never touched our server at all.  It caused _all kinds_ of problems like these!  Fun stuff!  xD
Comment: I've managed to reproduce the issue on a local dev environment with the same codebase and database. Now I know it's in my Drupal.
Comment: Now that you have a separate and low-risk environment, you're free to modify it aggressively -- i.e. disable modules until login works and/or stand up vanilla drupal and add modules until it breaks. (I don't think I can access chat for non-comments discussion..)
Comment: Did you ever resolve this? I'm having a similar issue.
Answer: If I can make a guess correctly, the users might have forgotten or entered a wrong password for 5 times which in turn will block access for over 6 hours. Post down the cool down period they'll be able to access. For immediate access, drupal developers need to clear there IP from the flood table in database.
Comment: Hi, sorry. It's not that. This happens a lot on first-time logins, but also, if they get blocked out, they get an error message that tells them so. In case anyone finds this useful, if users get blocked out, you can clear the flood tables with drush: `drush php-eval 'db_query("DELETE FROM 'flood' ");'`

Users can't log in sometimes


Add two value into array's cell

Question: How can i push two values to a vector and reach both seperatly ?
I am try to do 1 A | 2 A |3 B | 4 C   each one is in the one cell.
Is that possible to do that ?
Comment: `A` is not a number(in the conventional decimal base). It is also not clear what do you mean by `1 A` is one cell. What is the type of your vector?
Answer: I believe you're looking for std::vector<std::pair<int, char>> (substitute the types of 1 and A for int and char, respectively).
This is how you could fill the vector:
std::vector<std::pair<int, char>> vec;

vec.push_back(std::make_pair(1, 'A'));

And this is how you access its contents:
int theOne = vec[0].first;
char theA = vec[0].second;

Answer: Use a std::pair in your vector.
http://www.cplusplus.com/reference/utility/pair/
Answer: You can use the std class pair, which simply regroup two elements :
std::pair< T1 , T2 > p ;

you can access T1 and T2 by using
p.first ;
p.second ;

then here it would do
vector< pair< int , char > >

Add two value into array's cell


What measures to take to prevent electrostatic if we dont skip a rack unit between servers?

Question: After going through the post Do you skip a rack unit between servers? . We thought to consolidate our rack to save space and to improve cooling in lab. If we put servers without skipping a single gap between server what are the chances of electrostatic and What measures need to take to prevent electrostatic if we don't skip a rack unit between servers?
Comment: Why would there be any static generated between servers if the systems are properly grounded.  Can you point me to a resource that talks about this?
Answer: Grounded servers and grounded racks. If your servers are plugged in with proper three-prong plugs into a properly-grounded power source, then they're good. In datacenters, you will often see racks grounded to the cages around them with thick green wire.
The point is, as long as everything is grounded, you won't have a problem with static.
They make little 5$ testers at Home Depot that you can plug into a three-prong outlet and it will tell you if it is not properly grounded.
Comment: Any electrostatic issues are likely to be worse with space between the servers.  Without space there is likely to be contact between the servers which will prevent a charge from building between adjacent servers.  Follow good grounding practices always.
Comment: To be on safer side i wanted to confirm. Generally we had a practice to keep space between servers and someone told me that if we stack server without gap it will electrostatic which can damages ethernet ports/memory etc .
Answer: As long as your server units are earthed via their mains connection you will be fine while running. If you need to hot swap parts you should take full ESD precautions, i.e. wrist band. As you would anyway.


Css Responsivo não funciona corretamente

Question: Estou com um problema onde estou fazendo um display responsivo onde o de desktop está ficando por cima do @MEDIA SCREEN e no celular não está pegando o responsivo.
.portfolio-modal .close-modal {
position: absolute;
right: 25px;
width: 180px;
top: 5px;
height: 75px;
background-color: transparent;
    cursor: pointer;
}

@media (max-width: 479px){
            .portfolio-modal .close-modal {
    width: 50px;
}
}

Comment: Nas 6 ultimas linhas você está fazendo uma sobrescrita, media all inclui midia screen, sugiro que leia esse conteúdo do MDN falando  sobre Media Query https://developer.mozilla.org/pt-BR/docs/Web/Guide/CSS/CSS_Media_queries, Cuide também da sua formatação, após abrir media você precisa utilizar {}
Comment: é que estou achando estranho, pq somente essa classe não está pegando o responsivo o resto está.
Comment: Esse código não vai funcionar mesmo, está faltando a } fechando a primeira media e {} abrindo e fechando a segunda...
Comment: estava fechado só esqueci de colocar aqui no final. Atualizei como está o codigo.
Answer: O correto seria assim
@media screen and (min-width: 480px) {
    body {
        background-color: lightgreen;
    }
}

Entendeu faltou o '{' depois do media, isso serve para delimitar o que faz parte da regra.
http://www.w3schools.com/css/css_rwd_mediaqueries.asp
http://www.w3schools.com/cssref/css3_pr_mediaquery.asp
Links auxiliares para o seu estudo.

Fiz um teste aqui e funcionou o código, veja:
<!DOCTYPE html>

    <title></title>

Se não funcionar a outra coisa impactando no se css
Comment: não funcionou amigo, deu a mesma coisa
Comment: atualize o css que está na sua perguta, lembrando que não de passei uma solução e sim um exemplo de como deve ser, ok
Comment: atualizei lá... acho que está certo mas algo está fazendo não pegar.
Comment: tente assim @media (max-width: 479px) {, tire a segunda media query ela tambem pode estar te causando problemas, deixe so uma, da maneira que de mostrei.
Comment: atualizei amigo, mesmo assim não estou conseguindo.
Comment: editei minha resposta da uma conferida
Comment: Sim agora deu certo obrigado amigo, só no HTML fica meio feio, mas o importante é funcionar OBRIGADO.
Comment: Na verdade o problema era o `mediatype` que estava a ser omitido `screen`.


Derivation Verification for an Algebraic Expression

Question: This problem comes from a MathOverFlow thread. Inside the thread the user Per Alexandersson mentions how they learned a technique to "simplify" $\sqrt{7+\sqrt{3}}$ from the book Algebra for Beginners, by Todhunter.
Greg Martin replied with the following formula:
$\sqrt{a+\sqrt b} = \sqrt{\frac{a-\sqrt{a^2-b}}{{2}}}+\sqrt{\frac{a+\sqrt{a^2-b}}{{2}}}$
I have three questions around this,
Question 1: Is the below derivation correct? If not, could someone show me how to patch it up?
Derivation:
\begin{align}
\sqrt{a+\sqrt b} &= \sqrt{\frac{a-\sqrt{a^2-b}}{{2}}}+\sqrt{\frac{a+\sqrt{a^2-b}}{{2}}} \\
\left(\sqrt{a+\sqrt b}\right)^{2} &= \bigg(\sqrt{\frac{a-\sqrt{a^2-b}}{{2}}}+\sqrt{\frac{a+\sqrt{a^2-b}}{{2}}}\bigg)^{2} \\
{a+\sqrt b} &= \frac{a-\sqrt{a^2-b}}{{2}} + 2\bigg(\sqrt{\frac{a-\sqrt{a^2-b}}{{2}}}\sqrt{\frac{a+\sqrt{a^2-b}}{{2}}}\bigg) + \frac{a+\sqrt{a^2-b}}{{2}} \\
{a+\sqrt b} &= \frac{a-\sqrt{a^2-b}}{{2}} + \frac{a+\sqrt{a^2-b}}{{2}} + 2\bigg( \sqrt{\frac{a-\sqrt{a^2-b}}{2}\cdot \frac{a+\sqrt{a^2-b}}{2}}\bigg)  \\
{a+\sqrt b} &= \frac{a-\sqrt{a^2-b}+a+\sqrt{a^2-b}}{2}+  2\bigg(\frac{\sqrt{b}}{\sqrt{4}}\bigg) \\
{a+\sqrt b} &= \frac{2a}{2} +  2\bigg(\frac{\sqrt{b}}{2}\bigg) \\
{a+\sqrt b} &= a +  \sqrt{b}
\end{align}
Question 2: I assume that the above is if each step is reversible. But my question is (assuming the derivation is correct), how do we know each step is reversible when there are square roots involved?
Question 3: Regardless if the above derivation is correct or not, could someone show me another derivation and include the steps/explanations of how these are equal? I figure another approach might enlighten me as to how the longer expression was derived from  $\sqrt{a+\sqrt b}$.
Comment: You can easily adapt your derivation into an obviously valid chain of equations: $$\left(\sqrt{\frac{a-\sqrt{a^2-b}}{{2}}}+\sqrt{\frac{a+\sqrt{a^2-b}}{{2}}}\right)^{2} = \cdots = a + \sqrt{b}.$$ Then you just have to take the square root of both sides at the end, and the logic of the argument is clear. (By the way, instead of choosing the size of the parentheses yourself, as \bigg( ... \bigg), you should have left it up to MathJax, by using \left( ... \right).)
Comment: Looks good to me. To show it's reversible just start from one side, say the LHS. Simplify it down to $a + \sqrt{b}$, then build back up to the top step-by-step to get the desired equation.
Comment: $\sqrt{}\;$ means the principal (non-negative) square root
Comment: I find [this method](https://math.stackexchange.com/a/816527/242) more convenient.
Comment: @JackPfaffinger: Thanks. My main concern is with the reverse direction. For instance: if I square -1 I get 1. If I squared 1, I get 1. If I take the square root of 1, then how do I know if I initially squared the positive 1 or the negative 1? Does this type of concern creep up in the derivation I posted? I want to ensure my reverse direction is valid, including the parts with the square roots.
Comment: This and related questions have been asked here many times, e.g. [see here.](https://math.stackexchange.com/questions/196155/strategies-to-denest-nested-radicals) along with its long list of Linked questions.
Answer: The equation
$$\sqrt{a \pm \sqrt b} = \sqrt{\frac{a + \sqrt{a^2-b}}{{2}}} \pm \sqrt{\frac{a - \sqrt{a^2-b}}{{2}}} \tag{1}$$
is really two equations with proper choice of signs.
What we mean by that is that each square root of a positive real has two values, one positive and one negative.
There is one square root on the left side and on the right side is the sum/difference of two square roots. But given $\,0<b<a^2\,$ positive and the positive square root on the left, then the first square root on the right is greater than the second square root. Their sum must be the same as the left square root with the $+$ sign and the difference must be the same as with the $-$ sign.
When we replace $\,b\,$ with $\,-b,\,$ equation $(1)$ becomes
$$\sqrt{a \pm \sqrt -b} = \sqrt{\frac{a + \sqrt{a^2 +b}}{{2}}} \pm \sqrt{\frac{a - \sqrt{a^2+b}}{{2}}} \tag{2}$$
which is the well known formula for the square root of a complex number. In both cases, the equations can be verified by squaring both sides and simplifying and accounting for negative square roots as needed.
Answer: Answer 1: Your thoughts are correct.
Answer 2: If the signal of both sides are equal, then the step of squaring both sides (say, the first step in your proof) is invertible.
Answer 3: The way the author expects you to derive this equation might be to find an $x$ and $y$ such that
$$
\begin{align}
x^2+y^2&=2a\tag{1}\label{1},\\
xy&=\sqrt{b}\tag{2}\label{2}.
\end{align}
$$
Then,
$$
\sqrt{a+\sqrt{b}}=\sqrt{\frac{2a+2\sqrt{b}}{2}}=\sqrt{\frac{(x+y)^2}{2}}=\frac{|x|}{\sqrt{2}}+\frac{|y|}{\sqrt{2}}.
$$
This is how you simplify $\sqrt{7+\sqrt{3}}$. Solving $(1)$ and $(2)$, you will find that the $x$ and $y$ are exactly $\sqrt{a-\sqrt{a^2-b}}$ and $\sqrt{a+\sqrt{a^2-b}}$.
Comment: I think your problems is in how to get the first equation from the second. Generally, if you have $x^2=y^2$, then either $x=y$ or $x=-y$ is true. You should observe the signal of $x$ and $y$ to tell which one is true. On the other hand, $x=y$ does imply $x^2=y^2$.
Comment: Thanks for the answer. My question is: if you start the proof in the reverse step, then how do you know the signs of both sides are equal in the end?


Does it make sense to calculate Q2 and R2 values on PLS-DA models?

Question: Since PLS-DA is a computational technique which deals with outcomes expressed as a categorical variable (e.g. "Yellow","Brown","Black","Green") I cannot understand how it is possible to calculate Q2 and R2 values. In facts, these values are calculated based on the difference between the real outcome and the outcome predicted by the model after removal of some features; this procedure seems correct with continuous outcomes but how is it possible to perform a difference between "Green" and "Yellow" for instance? Many thanks.
Comment: there is a definition of Q2 on this page http://www.moleculardescriptors.eu/tutorials/T5_moleculardescriptors_models.pdf
Comment: Maybe the difference between "green" and "yellow" (or any other non-identical pair) can be taken as 1, as opposed to 0 in case of identical pairs? But in any case, it would be helpful to clarify what Q2 and R2 values are (I am familiar with $R^2$, but have never encountered "Q2") and to provide some larger context for your question.
Answer: The R2 and Q2 are calculated using the labels in numerical form (-1 and 1 or 0 and 1 instead of green and yellow).
However this measure are not perfectly suited for classification.
I believe that this paper will (partly) answer your question and provide an alternative to the Q2:
Discriminant Q2 (DQ2) for improved discrimination in PLSDA models
Westerhuis et al. Metabolomics Vol. 4, Number 4, 293-296
http://link.springer.com/article/10.1007%2Fs11306-008-0126-2


Fix Java warning on Jenkins startup with default Debian package install

Question: I've installed Jenkins on a Debian system using the instructions here:
https://www.jenkins.io/doc/book/installing/linux/#debianubuntu
It works fine, but gives a warning in the log on every startup:
"Java is not in the PATH nor configured with the javaPath setting, Jenkins will try to guess where is Java,this guess will be remove in the future"
What's the correct way to fix this warning?
I'm assuming adding something to /etc/default/jenkins, but I'm not 100% sure exactly what.
(tagging Ubuntu too, as the issue/fix should be the same there, as the Jenkins packages are common)
Comment: The is a message from inside `/etc/default/jenkins`. It's a shell script. You can examine it and see. It expects a env JAVA_HOME, or goes searching /usr/bin/java, /etc/alternatives/java, etc. You can edit and set a propoerty there or  in a jenkins.conf and.load it.
Answer: You need to create JAVA_HOME environment variable or add java path to PATH variable.
Assuming you have openjdk-8 installed you need to issue the commands:
to create JAVA_HOME variable
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64

and to add it to PATH
export PATH=$PATH:$JAVA_HOME/bin


Creating a site tour

Question: I created a site that allows people to create user accounts, login and communicate with other users, or view certain content. The site is completely finished accept for one thing. I am worried that users are going to get confused, or not know about all of the features that are on the site, so what I wanted to do, was to create a walk through tutorial of the site. I noticed there is a module for Drupal 6 that looks like it does almost exactly what I am trying to do, but I can't seem to find anything similar for Drupal 7, and I was wondering if anyone else has had any better luck. Also, I am I don't want the tutorial there permanently. I want it only there for the first few times that the user logs in, and then after that, to simply have a link saying "take site tour" on the bottom. Does anyone know of a module that can do that?
Comment: As alternative solutions, you could create a screencast or use the advanced help module.
Answer: This module can do the same: Guidance
For controlling first time, you can use Rules module.
Answer: Check out the Guiders-JS module. It is a guide / walk-through for your site's pages.
The Guider can show the page parts and give a short explanation about each part's functionality and purpose. This module is for anyone who is looking for a walk-through, guide, intro, or just a sequenced messaging system.
Comment: is there a way to have the next button go to another page?
Comment: one thing I'm wondering, is how do I make it so that it only happens the first time the user logs in?
Comment: Honestly I have never used the module. Only knew about it. Your going to have to hit the module's issue queues for further help.
Answer: There is also Joyride JQuery for Drupal Site Tours module for Drupal 7 and Drupal 8 ships with Tour module! :)

Creating a site tour


What counts as tonal music?

Question: This question was sparked by comments in Sources of harmonic ambiguity in tonal music:
By the user lightning:

EDIT: I would consider anything which is based on a pitch-class hierarchy to be tonal, including pieces based on pentatonic or modal scales, bitonal pieces, pieces with a lot of dissonance or chromaticism, and pieces with chord progressions that are not standard for Classical functional harmony. I'd draw the line at pieces which do not in any way reinforce any pitch-class as central.

By the user Basstickler:

The definition you've provided for tonal definitely includes a lot of things that are definitively not tonal. Also, what is your idea of ambiguity? Are you looking to destablize the piece to make it sound unclear where it may go after a given chord?

So what does and does not count as tonal music? Does bitonality (or higher polytonality) count? What about modal music, music based on blues scales, or music based on the Phrygian Dominant or Double Harmonic scales (note that the Phrygian Dominant scale is the fifth mode of the harmonic minor scale)? What about music with no authentic cadences and no plagal cadences--or worse, music that seemingly contains no chord progressions that fit common practice period harmony?
Food for thought--maybe figuring out whether these pieces count as tonal or not may help answer this question:

In the Dorian mode
Mostly based on the Phrygian Dominant and/or Double Harmonic scales
Bitonal
May not contain any chord progressions that fit common practice period harmony
May not contain any chord progressions that fit common practice period harmony, manages to do this with 4 chords or less
Heavily chromatic, likely contains few chord progressions that fit common practice period harmony
Very heavily chromatic
Heavily chromatic
Answer: (topo's answer is very good, but I wanted to offer a few other thoughts.)
To understand what "tonal music" is, we have to first define what we mean by "tonality."
The go-to scholarly source on defining it is Brian Hyer's article "Tonality" in The Cambridge History of Western Music Theory. Towards the beginning of his article he states the main difficulty (as I see it):

A further complication (and recurrent tension) has to do with whether the term refers to the objective properties of the music – its fixed, internal structure – or the cognitive experience of listeners, whether tonality is inherent in the music or constitutes what one recent author describes as "a form of consciousness."

But I think he settles on a very good definition shortly thereafter:

the systematic organization of pitch phenomena in both Western and non-Western music.

What's important here is the phrase systematic organization. By this I think Hyer means two things:

First, that the music is hierarchical, and one pitch (the tonic) is more important than all others.
And that this pitch is the focal point on which the music comes to rest.

Hyer might mean a third point, which is the notion of monotonality. If we're privileging one pitch as tonic, then that tonic should be the tonic of the entire piece (hence monotonality, meaning "only one tonic"). This doesn't mean the piece can't modulate, but that it will (with some exceptions) begin and end in the same key.
This means that the definition can be very broad; we can use cadences, but we don't need to; we can use tertian harmony, but we need not; we can use scales, but we certainly don't have to; we can write in major or minor, or octatonic or hexatonic, or something completely different altogether; and so on. What's important is the role of a single tonic pitch that is hierarchically more important than all of the others. There may be different types of tonality (and this different types of tonal music), but it's still tonality; Mozart is definitely different from Wagner, who is very different from Debussy, but they still wrote tonal music. (Note: some may disagree with this paragraph!)
And here maybe it's helpful to discuss how some have defined different types (or "uses") of tonality. Robert Bailey, when studying Wagner, discusses four types:

Classical tonality, which is that defined by the tonic-dominant polarity. (I return to this at the end.)
Expressive tonality, which is when chords move up and down by second. Some call this "truck-driver tonality," because the chord switches sound like a revving engine.
Associative tonality, where particular tonal cues are used as extra-musical references that might not be related to the current stretch of tonality.
And directional tonality, where a piece begins and ends in different keys. (Contrast this with monotonality, above.)

But even with that knowledge of tonality, there are still disagreements on what is and is not "tonal music." Some, for instance, separate "tonal" music from "modal" music, while others still view modal music as being tonal.
But it may be important to note that two historical theorists, Fétis and Choron, announced "the beginning of tonality" at the appearance of a dominant-seventh chord in a piece by Monteverdi around 1590. Many modern theorists insist on the presence of the dominant in order to define tonality; indeed, they believe that the tonic-dominant polarity is the defining characteristic of tonal music. This mindset largely comes from the work of Austrian music theorist Heinrich Schenker. His influence on our understanding of "tonality" is so vast that college courses on his theories are often simply called something like "Analyzing Tonal Music."
Comment: It depends on who you ask. Some view tonal music as an evolution from modal, but Harold Powers famously says they are on "different epistemological planes" and that it's useless to view a progressive relationship from one into the other.
Comment: I commend this answer as sounding much less grouchy than my answer~
Comment: @topomorto I didn't find any grouch in your answer at all! I really liked your answer, but there were a couple of things I wanted to add. But now I keep thinking of more and more things to add, and my answer is becoming more and more disorganized as I go...
Comment: Something I didn't quite get from the wikipedia article was a sense of whether the term 'tonal' has identifiably evolved from one reasonably-specific meaning to another over time, or if (like 'modal' ?) it has lurched from one confusing meaning to another, or if it has always just been confusing...
Comment: Yes, I remember Schenker all too well- he was considered God at the UC Berkeley department of music in the seventies.  But I still don't think there's any way of drawing a meaningful line between "tonal" music and anything else.  It's a complex continuum, not a yes/no.
Answer: As per my own comment on that question - it's not a word that has a very precise meaning! Wikipedia will tell you the same...

At least eight distinct senses of the word "tonality" (and corresponding adjective, "tonal"), some mutually exclusive, have been identified...
  (emphasis mine)

Various different ideas that some people seem to associate with 'tonality' are...

The idea that there is a central pitch that a piece gravitates around
The idea that there is a hierarchy of relationships between other notes in the scale used and that central pitch
Use of any scale
Use of the diatonic scale
Use of triadic harmony
use of particular musical devices (e.g. particular cadences and harmonic motions, such as dominant to tonic)
User of the major/minor system

and you can probably pick out more meanings from that Wikipedia article.

So what does and does not count as tonal music?

No-one is going to be able to say with any authority, because (for better or worse) there is no central authority who decides what musical words mean, and the population of musicians and musicologists haven't really thrashed out a single useful meaning.
My advice would be - if someone uses the word, be kind and try to infer from context what they mean - but be careful when using it yourself, as it's a word that often adds confusion rather than clarity.
Comment: @ScottWallace I wonder if Dekkadeci might add [Cauliflower](https://soundcloud.com/scott-wallace-189088488/cauliflower) to his list of examples...
Comment: I was wondering myself if I could consider it tonal or not.  Since it always comes back to what sounds like a root chord, I guess it could be considered tonal.  But since it only does so because it's dictated by the repetition of a pattern, maybe it should be considered forced tonality.  I don't know.
Comment: @ScottWallace I've heard of forced rhubarb but had to check if there's such a thing as forced cauliflower (there is, apparently...)
Comment: Yep.  This is a good example of the impossibility of drawing a clean line across a very complicated landscape.  Although pretty much everyone would put "Twinkle Twinkle Little Star" and "De Profundis" by Schoenberg into "tonal" and "atonal" categories respectively, it gets a lot messier elsewhere.  For instance- is just music (Harry Partch, or my own stuff) ever "tonal"?  There simply cannot be any clear place to draw a line.
Answer: Others have mentioned the general ambiguity of the term, so I thought I might offer my response, which is a little less academic and probably somewhat subjective, though informed by my experiences in academia.
Broadly speaking, I think of Tonality and Functionality somewhat interchangeably, which may be wrong in a technical sense that I'm not very familiar with.  However, when viewed from the lens of Tonal vs. Atonal, my definition may be less valuable.  So I generally consider a piece that is using Functional harmony, ie, Dominant to Tonic as the primary cadential movement, to be Tonal.  Other forms of music, such as Modal or Non-Functional, would not be considered Tonal and would go by the names just mentioned.
This belief may be based on my having studied from a book called "Tonal Harmony with an introduction to Twentieth Century Music".  The majority of what was covered in this book has to do with Functional Harmony and the distinction in the title about an "introduction to twentieth century music" implies that the remaining topics covered would not be Tonal music.  The book covers a decent amount of the Romantic era as well, which starts to stretch tonality a bit, such as with pieces like Voiles by Claude Debussy, which is largely a study of the Whole Tone scale (not to take away from its musical value; Debussy is one of my favorites).  This piece would certainly not be considered Atonal, as there is some emphasis on some pitches over others, particularly the pedal tone, but it doesn't conform to any of what is studied in the book up to that point.
I think that when I most often find myself using the term Tonal, it is in opposition to Modal but I also tend to use Functional more frequently, which does seem to have a more agreed upon definition.  The distinction I draw from this is that describing the Tonality of a piece generally suggests that the piece is in Major or Minor and using Functional Harmony, where describing the Modality of a piece generally suggests that we could be using any Mode and if that Mode is either Ionian or Aeolian that it is not using Functional Harmony.
I generally prefer to use the term Functional Harmony over Tonal and, to be honest, my comment on the referenced question doesn't really seem to be as agreed upon as I had thought at the time I made it.

What counts as tonal music?


limit access to some configuration pages (manage display and manage fields)

Question: I have editor and administrator role in my website, the editor role must have "Administer vocabularies and terms" permission (in admin/people/permissions page),
How can I restrict editors from "manage display" and "manage fields" without uncheck "Administer vocabularies and terms" , so they can't access to this page : admin/structure/taxonomy/VOCABULARY_NAME/display/?
Answer: I would probably go into one of my custom modules and:
invoke a hook_permission() with my new needed permission (administer display and fields) that will be granted only to admin.
Then invoke hook_menu_alter() to alter the access control on the menu path the taxonomy module creates.
This way on install admin will be granted automatically the permission and only the roles granted this permission will be able to access that page.
Comment: with hook_menu_alter, the link will be hidden but, if copy/paste the link, the page displays !!
Comment: changing access arguments in hook_menu_alter do the trick, thanks !


Two ECS tasks connectivity in one EC2 Host

Question: I have 2 ECS Services running with EC2 launch type and bridge networking mode. each service is having 1 task and both tasks are running on same EC2 container host.
on the Same ECS host, API container in 1st task is trying to communicate DB container in 2nd task by host name and port number( ex: http://abc-def:5000). what are the ways to achieve this ?
Answer: Your options are:

Put everything in a single task definition. Then you can use the link attribute to enable container A to communicate with container B like so B:port. Notice that link does not support circular relations meaning if A can talk with B, B will not be able to do that as well.

Switch to network mode host. This way you can communicate with localhost.

Proper service discovery with a tool like Consul or AWS ECS Service Discovery. I have no experience with the latter. See here.

Put your tasks behind ALB and use this load balancer to communicate between tasks.


put on google map some point with different color

Question: I want put the three point in google map with lat long but i want each point have different color.
This is my code, At the moment this code set one color to all point
    function initMap() {

        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 11,
            center: {lat: 39.585938, lng: 47.909219}
        });

        heatmap = new google.maps.visualization.HeatmapLayer({
            data: getPoints(),
            map: map
        });

        var gradient = [
            'rgba(255, 0, 0, 0)',
            'rgba(255, 0, 0, 1)'
        ]
        heatmap.set('gradient', gradient);
    }

    function getPoints() {
        return [
            new google.maps.LatLng(39.585938, 47.909219,20),
            new google.maps.LatLng(39.585938, 47.909220,20),
            new google.maps.LatLng(39.585938, 47.909221,20),
            new google.maps.LatLng(39.585938, 47.909222,20),
        ];
    }

Comment: Your code is currently using a heatmap.  Do you want markers?
Answer: You can define custom markers using the strokeColor property:
Example :
strokeColor: "red",

Reference : https://developers.google.com/maps/documentation/javascript/markers
var marker = new google.maps.Marker({
    id: "some-id",
    icon: {
        path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
        strokeColor: "red",
        scale: 3
    },
    map: map,
    title: "Any-title",
    position: myLatlng
});

References :
https://developers.google.com/maps/documentation/javascript/symbols


Question about conditioning on sequences of random variables, where the sequence is related by a function $f$

Question: Let $A_k, B_k$ be two sequences of random variables, where $A_k = f(B_k)$
Then is it true that
$$\mathbb{E}[A_{k+1}|A_0, \ldots, A_k] = \mathbb{E}[f(B_{k+1})|B_0, \ldots, B_k]$$
If so, what is the justification for the equality?
Answer: No. In general, the conditioning might be irrelevant (if the sequence is iid), which means that the question is if $E(B)=E(f(B))$ true for any function $f$. In the general case, this is false:
Suppose $B_k=\pm 1$ (w.p. $p\neq 0.5$ to be $1$) and $f(x)=\vert x \vert$. Then $A_k=1$ and $E(A_k)=1$. But $E(B_k)=p-(1-p)\neq 1$.


Chrome adding inline css

Question: I have a website with a sidebar, see following code snippet:

    <% if(Model.Count > 0){ %>

IE adds a margin-top: 0px (which causes the website to display properly), Chrome adds a margin-top: -676px. That margin-top is not defined in the belonging css.
I can´t figure out where that is coming from.
Can someone help?
Comment: Its probably coming from the the javascript code which is written for sidebar in your js file
Comment: check browser developer tool properly
Comment: if you want to remove the margin-top try `#sidebar{margin-top:0 !important}` in your css
Comment: If the website is live, could you share he URL?
Comment: Bhuwan, that helped me out!
Unfortunately (or fortunately ;) ) that revealed the *.js to be causing the problems. In IE the sidebar is moving when scrolling, in Chrome it is not.
Answer: There isn't enough information to know where this margin is coming from, however Chrome's dev tools allow you to see where certain styles are coming from.

Press CTRL+SHIFT+I to open the dev tools
Press CTRL+SHIFT+C to enter element selector mode
Click the element in question
Refer to the screenshot below to find out where the margin is coming from

Hope this helps :)
Comment: Definitely helpful, but in that specific css it lists margin: 0.

I think I found a belonging part in the sidebar.js, but I wonder why IE renders the page as it should and Chrome does not.

Chrome adding inline css


Changed the password start getting "The remote server returned an error: (401) Unauthorized" error

Question: I have a remoting service which uses the Windows Auth. Been working fine for a while but yesterday my windows account has been lockout and after it has been unlocked and the password changed I have been having issues since.
It just didn't let me in with the following error:
"System.Net.WebException: The remote server returned an error: (401) Unauthorized."
May be my old password / credentials somehow stuck in a credential cache in my local PC or something like that.
Any ideas how to fix that? Thanks.
Answer: What are you using on the client side?  A web browser?  The browser SHOULD handle the 401 by displaying a dialog box for you to type in the correct username and password.
If the problem is because of something cached on the local PC, can you try it from a different computer?
Comment: I don't use browser - have a client applicaiton.
I found the culprit. The credentials do actually cache when windows ask for a username first time it accesses the network resource (e.g. a network share). After I restarted my computer and it tried to connect to network share it poped up the dialog box you mentioned and after I specified the new password - the problem has disappeared.


Filling form with user entered values after submit

Question: How do I fill a custom form with the values entered from the users before the form was submitted? I have saved the $form_state values, but when I put them back into $form_state on loading, the form fields aren't filled.
Comment: Are you talking about remembering the user values in the next form load?
Answer: Drupal 7
If you are not redirecting and want to preserve the values in the Form API fields add $form_state['rebuild'] = TRUE; on the submit handler.
/**
 * FORM submit handler.
 */
function FORM_form_submit($node, &$form_state) {
  // Rebuild the form and keep the filter values.
  $form_state['rebuild'] = TRUE;
}

Drupal 8
In Drupal 8 you would use $form_state-> setRebuild();
See public function FormState::setRebuild for more detail.
Custom submit handlers in Drupal 8 are dealt with differently — here is some useful discussion on Drupal 8 submit handlers.
Comment: This should be the accepted answer (for Drupal 7 at least).
Answer: I think you want to put them in $form['element_name']['#default_value'] not $form_state. What you're describing sounds odd, though. Why are you adding a user's information back into a form after they already entered it?
Comment: This is for scenario where user entered data was invalid and he has to fix his mistakes. Drupal default behaviour is to render empty form again when it would be more userfriendly to fill form with submitted values. #default_value works, but right now it means i have to manually save data and then put it back into form elements. I hoped there was some sort drupal way for doing it for me or at least making it easier.
Comment: if you call form_set_error() correctly, user-entered values will remain- even the invalid field input.
Answer: Values entered in a form should be validated in a form validation handler. When the validation handler finds values that are invalid, it should call form_error() or form_set_error(); in that case, the form would be presented back to the users with the values they entered. The only form field that is reset is the password form field, for which presenting the previously entered value would not have any sense, since the users would just see a string made of "•" (or the character that replaces the input used by the browser).
The purpose of form submission handlers is not to validate the entered values, but to save them, or using them to create the required output.
Answer: When form submit fails you must set $form_state['redirect'] to false. By default after submit form is reloaded and form fields cleared out. But when redirect is set to false form will not be redirected and form fields will remain filled.
Comment: This does not work if I add another line with this in the submit handler: $form_state['storage']['confirm'] = true;
Comment: If I can set storage along with redirect then it'd resolve my thread: http://drupal.stackexchange.com/questions/18333/storing-permanent-value-in-form-while-in-validation-handler
Comment: In short how do I remember the fact in the next form reload that the reload is due to redirect being set to false in submit handler last time?


Is there a technical name for $f$ such that $(g \circ f)(a_1, a_2,\cdots)$ yields $g(a_1, a_2, \cdots)$?

Question: Is there a technical name for a function $f$ such that $(g \circ f)(a_1, a_2,\cdots) \rightarrow g(a_1, a_2, \cdots)$? That is, is there a name for a function $f$ such that the result of composing $g$ with $f$ is $g$ invoked with $f$'s arguments?
EDIT: Accidentally reversed the order of operations and put $f \circ g$ when I meant $g \circ f$ (i.e. $g(f(\cdots)$).
Comment: Wouldn't $f$ have to be the identity function $f(a_1,a_2,\ldots)=(a_1,a_2,\ldots)$?
Comment: $f$ is forced to be the identity only if we require $g\circ f=g$ for *all* $g$. If this identity is only required to hold for a single $g$ (which is not injective) it is possible for $f$ to differ from the identity.
Comment: [Identity operator](http://en.wikipedia.org/wiki/Identity_function)?
Comment: Example: $g(x,y)=(1,1)$ then for any $f(x,y)$ we have $g\circ f(x,y)=g(f(x,y))=(1,1)=g(x,y)$.
Answer: To add to Bill's answer: in certain contexts we would say that "$f$ is a symmetry of the function $g$" or that "$g$ is invariant under $f$".
For example, if $g(x) = x^2$ and $f(x) = -x$, we say that $g$ is symmetric under reflection and $f$ is the reflection operation.
Another example, if $g(x) = \sin x$ and $f(x) = x+2\pi$, we say that $g$ is periodic with period $2\pi$, or that $g$ is invariant under translation by $2\pi$, or that $g$ is invariant under $f$.
Comment: "Symmetry" or "invariant" is definitely better terminology than what I gave in my answer. Calling something an "identity of $g$" (referring to a single element instead of a whole set) is kind of weird. :)
Comment: A related concept (with lots of fun applications for dynamical systems) is that of an *equivariant*. We say that "$g$ is equivariant under $f$" if for all arguments $x$ we have $(g\circ f)(x) = (f\circ g)(x)$. For an example take $g(x)=x^3$ and $f(x)=-x$.
Comment: @Chris: wouldn't that be '$g$ commutes with $f$'?
Comment: Yes; http://en.wikipedia.org/wiki/Equivariant_map
Comment: @Bill: there are however times when left/right identity "sound" better. For example, let $g(x,y)$ be independent of $y$. And let $f(x,y) = (x,0)$ be the projection map. Sure you can say that $g$ has a symmetry. But the operation $f$ itself, being a projection map, I tend to think of as a "generalised" identity operator (since it *is* the identity operator for the subspace $X\times\{0\}$). This tend to be more relevant in (linear) algebraic contexts though.
Answer: In general for a binary operation $\circ$...
If $f \circ g=g$, then $f$ is a left identity for $g$ and if $g \circ f = g$, then $f$ is a right identity for $g$.
If $\circ$ is composition and $f$ is a right identity for all functions $g$, then $f$ must be the identity function: $f(x_1,\dots,x_n)=(x_1,\dots,x_n)$. The same is true if we change "right" to "left".
In fact, if $g$ has a left inverse (which is true iff it is one-to-one), then $\mathrm{id}=g^{-1} \circ g = g^{-1}\circ g\circ f= \mathrm{id}\circ f=f$.
If $g$ is not one-to-one, there are potentially many functions (other than the identity) such that $g\circ f=g$.
When "left" is replaced by "right", "one-to-one" should be replaced by "onto".


How to displayed fixed menus, extracted from the main menu?

Question: I am using a Bartik subtheme, and would like to split the main menu into 4 smaller menus, and display them in the four footer columns, side by side. I would like the same menus to be displayed on all pages.
How would I do this?
Answer: If you go to admin/structure/menu/add and add four menus (Footer 1, Footer 2 ...), four blocks of the same name will also be created. Then go to your Main Menu and move the links into the new menus you have created.
Place these blocks where you want them at admin/structure/block and modify your stylesheets to make sure they display the way you want.
Comment: Thank you @Triskelion
If I then update the Main Menu items, will the changes also be reflected in my newly created menus?
Comment: No. You move or copy the menu items into the new menus, and maintain the individual menus separately.
Comment: Thanks again @Triskelion
Is there any way of only maintening one menu set? Also, how would I go about copying/moving the menu items? Do you mean add new links?
Comment: Go to admin/structure/menu/manage/main-menu, edit the link you wish to move, and under 'Parent Link' choose the new menu. If you have a hierarchy of menu items, moving the parent will move the entire tree.


If $A$ and $B$ are normal such that $AB=0$, does it follows that $BA=0$?

Question: If $A$ and $B$ are normal linear transformation on the finite-dimensional complex inner product space $X$ such that $AB=0$, does it follows that $BA=0$?
Comment: Yes, look at the answer.
Comment: Did you try anything on that problem? If you tried, show us where you stuck.
Answer: Let $AB=0$. We have $B^*BAA^*=BB^*A^*A=B(AB)^*A=0$.
This shows $Im(AA^*) \subset \operatorname{ker}(B^*B)=\operatorname{ker} B$, hence $BAA^*=0$ and thus also $AA^*B^*=0$, which shows $Im(B^*) \subset \operatorname{ker}(AA^*)=\operatorname{ker} A^*$, hence $A^*B^*=0$ and thus $BA=0$.
Answer: An alternate solution, described in a pedagogical way, is as follows.
(This proof avoids the image and the kernel/null-space argument used in the previous answer, and works in both finite and infinite dimensions, and for both real and complex spaces like the previous answer.)
The answer to the question is "yes, $BA = 0$".
Proof: We are given that $AB = 0$, and we see that $AA^* = A^*A$ (since $A$ is given as normal) and $BB^* = B^*B$ (since $B$ is given as normal).
For an arbitrary vector $x$, we find that $\Vert BAx \Vert^2$ $= (BAx, BAx)$ $= (A^*B^*BAx, x)$. We set out to inspect how $A^*B^*BA$ acts on an arbitrary vector, and discover that $A^*B^*BA$ is in fact $0$. How? If $y$ is an arbitrary vector, we observe $\Vert A^*B^*BA y \Vert^2$ $= (A^*B^*BA y, A^*B^*BA y)$ $= (AA^*B^*BA y, B^*BA y)$ $= \big(A^*(AB)B^*A y, B^*BA y\big)$ $= (0y, B^*BA y) = 0$.
It follows that $\Vert BAx \Vert^2 = (A^*B^*BAx, x) = (0x, x) = 0 \implies BA = 0$.


Javascript - I can't find my mistake.(radio buttons)

Question: I want to create an online test,but there is something wrong with my first question.The code below doesn't work and returns "your score is 0" even when the right answer is checked.

<!DOCTYPE html>
sssdsdsdsd

Mypage.com
<title> myPage</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<input type="radio" name="question1" id="q11" value="false">Question 1-first option

<input type="radio" name="question1" id="q12"  value="true" > Question 1- second option

<input type="radio" name="question1" value="false">Question 1- third option

<button onclick="showScore()">Show my score</button>

Comment: You added script that is executing before the document has been fully loaded, meaning your check of the radio buttons is doing nothing
Comment: **Move** your score calculation **inside** your `showScore()` function. You're *almost* there.
Comment: Change the Java tag to JavaScript
Comment: @Barranka: [codereview.se] takes working code and reviews it to make it better, it's not designed to fix broken/not-currently-working code.
Answer: The immediate reasons why things are not working as you want are listed.

You set the value of the total before the elements are parsed and rendered.  HTML will parse from top to bottom.  Therefore you want to move your script to the bottom.
If you need to set the value of the option box in the markup, use checked instead of value attribute.

You should have something like the snippet below.

<!DOCTYPE html>
sssdsdsdsd

Mypage.com
<title> myPage</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<input type="radio" name="question1" id="q11">Question 1-first option

<input type="radio" name="question1" id="q12"  checked="true" > Question 1- second option

<input type="radio" name="question1">Question 1- third option

<button onclick="showScore()">Show my score</button>

Answer: This block:
var total=0;
var yourmark="your score is  ";

if(document.getElementById('q12').checked) {
  total=total+1;
}else {
 total=total;
}

runs at the beginning of of the page, as it is loading. At this point total is, in fact 0. When you click the button, all you're asking for is the value of 'total. At no point are you updating the value oftotal` after you change the options.
The simplest solution, as PM 77-1 suggested, is to move the calculation inside the function, so that total is calculated every time you need an updated answer.

<!DOCTYPE html>
sssdsdsdsd

Mypage.com
<title> myPage</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<input type="radio" name="question1" id="q11" value="false">Question 1-first option

<input type="radio" name="question1" id="q12"  value="true" > Question 1- second option

<input type="radio" name="question1" value="false">Question 1- third option

<button onclick="showScore()">Show my score</button>

Answer: http://codepen.io/anon/pen/vgJuA
So, leave var total = 0 as global variable outside the functions and create a function checkAnswer() .
Your javascript part now will be:
var total = 0;
function checkAnswer() {
    //total is the global Variable for the score
    if (document.getElementById('q12').checked) {
        total = total + 1;
    } else {
        total = total;
    }
    return total;
}

function showScore() {
    var yourmark = "your score is  ";
    alert(yourmark + checkAnswer());
}

Hope it helps!


Weka printing sparse arff file

Question: I was trying out the sparse representation of the arff file as shown here. In my program I am able to print the the class label "B" but for some reason it is not printing "A".
    attVals = new FastVector();
    attVals.addElement("A");
    attVals.addElement("B");
    atts.addElement(new Attribute("class", attVals));

    vals[index] = attVals.indexOf("A");

The output for the program is like -
 {0 6,2 8}      ---  I should get {0 6,2 8,3 A}

But when I do
vals[index] = attVals.indexOf("B");

I get proper output -
 {0 6,2 8,3 B}

For some reason it is not taking the index 0. Can someone tell me why this is happening?
Answer: This is a very popular problem. The Sparse format by definition does not store 0 values.
Weka ARFF format page clearly says that:

Warning: There is a known problem saving SparseInstance objects from
  datasets that have string attributes. In Weka, string and nominal data
  values are stored as numbers; these numbers act as indexes into an
  array of possible attribute values (this is very efficient). However,
  the first string value is assigned index 0: this means that,
  internally, this value is stored as a 0. When a SparseInstance is
  written, string instances with internal value 0 are not output, so
  their string value is lost (and when the arff file is read again, the
  default value 0 is the index of a different string value, so the
  attribute value appears to change). To get around this problem, add a
  dummy string value at index 0 that is never used whenever you declare
  string attributes that are likely to be used in SparseInstance objects
  and saved as Sparse ARFF files.

You have to put a dummy attribute in the first place. Just modify your code to:
attVals = new FastVector();
attVals.addElement("dummy");
attVals.addElement("A");
attVals.addElement("B");

Let me know if you need any further help.

Weka printing sparse arff file


Livewire/Alpine Dom template not updating

Question: first time using Livewire with Alpine and its a real pain to debug. Alpine console errors are so vague, is there anyway to make them more specific and verbose?
I digress.
I'm updating an array on livewire component which, when not empty, should be showing in the DOM. Everything works and when viewed in the console i can see that the changes are being made. inside the console everything is happening as it should. The trouble is, nothing i happening in the browser!

        <input id="search-toggle" type="search" pclass="block w-full bg-gray-100 focus:outline-none focus:bg-white focus:shadow text-gray-700 font-bold rounded-lg pl-12 pr-4 py-4 shadow-xl" wire:model.debounce.750ms="searched_term"  />

    @if($filtered_variable)
    <template>

                    @foreach ($filtered_variable as $index => $value)

                    @endforeach

    </template>
    @endif

Class Searchbar extends Component
{
    public $first_array;
    public $searched_term;
    public $filtered_array;

public function mount()
{
    $db_content = Stuff::where(function ($query) {
        $query->where('thing', false)
            ->orWhereNull('thing');
    })
        ->with('variable_eg')
        ->get();

    $this->first_array = $db_content;
    $this->searched_term = '';
    $this->filtered_array = [];
}

public function render()
{
    return view('livewire.searchbar');
}
public function updated($name, $value)
{

    if (empty($this->searched_term)) {
        return '';
    }
    $this->filtered_array = array_filter($this->first_array, array($this, 'filter'));

public function filter($element)
{
    $title = strtolower($element['title']);
    if (strpos($title, $this->searched_term) !== false) {
        return true;
    }
}

}
inside the console I can see that my alpine/livewire component is receiving the filtered_value just as expected. But nothing is happening on the browser. How can I force rerender?
Comment: updated to show Livewire
Comment: which alpine version do you use? use the latest one (https://firstname.lastname@example.com/dist/alpine.min.js) , it has proper error messages for debugging
Comment: @Irfan currently using 2.4.1. HAs it been updated since then?
Comment: @BenKemp yes, of course, the latest version is 2.8.0
Answer: To update (refresh/rerender) your component you can use a listener
protected $listeners = ['refreshComponent' => '$refresh'];

Then when the refreshComponent event is emitted, it will refresh the component without running any other actions.
There is a Github discussion in the Livewire repo describing this.
Regarding your updating and filter methods (just as a hint):
There are also special methods like updatingFoo, updatedFoo that run before/after an item foo is updating. See the Lifecycle Hooks.


Help me find the function behind this data?

Question: I have a function $f(x, y)$ and I have another (non-mathematical) algorithm capable of inefficiently generating the exact same results as in in a 'brute force' manner. Since I have been able to find no good 3-D graphing software at the time, I have used my algorithm to generate several tables. of the function. In each table I have a fixed $y$ value in the function, noted with each, and I input the $x$ values 1 - 10. Using Desmos Graphing Calculator, I have graphed each of these tables here. The higher-y lines increase much much faster than the lower-y lines, which makes it difficult to see it all at once. You can change the scale of the x and y axes in the top left, and clicking on the icon of a table turns it off or on. The $y$ of each line is as follows: black - 1, green - 2, blue - 3, red - 4, yellow - 5, purple - 6. So what I'm looking for is to find a $f(x)$-type function in each line, and then using those the overall f(x, y) function for all the lines. So far I have not been able to find patterns except in 1 and 2 where they are obviously $f(x) = 1$ and $f(x) = x$. If anyone is able to find an $f(x)$ for any of the functions that I haven't or is able to find the overall $f(x, y)$ that would be great. Also, if needed I can provide arbitrary data from my brute force algorithm, just ask if it's needed and tell me the range of x and y.
Comment: After wolfram found the interpolating polynomials given below, only #4 and #6 seem likely. Perhaps you messed up on #3 and #5 on computation?
Comment: Also, can you post the $f(x,y)$ functions here too?
Answer: FOR REFERENCE ONLY THIS IS ONLY AN ANSWER BECAUSE A COMMENT CANNOT CONTAIN AS MANY CHARACTERS
For #3, the interpolating polynomial=
$$\frac{-x^9}{5670}+\frac{11 x^8}{1260}-\frac{5 x^7}{27}+\frac{11 x^6}{5}-\frac{4333 x^5}{270}+\frac{1111 x^4}{15}-\frac{121634 x^3}{567}+\frac{469633 x^2}{1260}-\frac{15536 x}{45}+128$$.
For #4:$$\frac{2x^3+x}{3}$$
For #5:$$-\frac{167 x^9}{45360}+\frac{517 x^8}{2880}-\frac{5665 x^7}{1512}+\frac{20999 x^6}{480}-\frac{676811 x^5}{2160}+\frac{1362551 x^4}{960}-\frac{9137729 x^3}{2268}+\frac{4931819 x^2}{720}-\frac{1964948 x}{315}+2272$$
For #6:$$\frac{11x^5+5x^3+4x}{20}$$
Comment: interesting... perhaps the odd numbers being the more complex ones is not a coincedence?
Comment: I have verified that the polynomials for 4 and 6 do indeed predict the data perfectly. I have not had the time to input the other polynomials.


Price higher that I have set

Question: I set the price of a drupal commerce product in 17 euros with "Include tax in this price" of VAT 10%. But I don't understand why when I view the display product I saw 21,39 euros.
I've looked at the "Manage display" of this product type. The Price field is formatted as "Formatted amount" and chosen "Display the calculated sell price for the current user.". If I change the format to the other option "Display the original price as loaded." when I see the display product node appears the price as 17 euros.
I don't understand where it's changing the price and how can I can configure.
Where, in the configuration, can I avoid this price change ?
Answer: This just means you have some product pricing rule or promotion enabled on the site that raises the price by that amount. It's unrelated to your tax setting. This is why you only see the high price when you use a display formatter that calculates the price prior to display.
There's no way for anyone to diagnose this for you without access to your site. You should just start by looking at Administration > Store > Configuration > Product pricing rules to see what pricing rules are active and how they're manipulating prices.
Comment: I look at Product pricing rules, I find 3 rules: Unset the price of disabled products in the cart, Calculate taxes: VAT and Calculate taxes: Sales tax. I didn't set all those rules. I had installed the commerce installing all modules I didn't used the Kickstart.
Comment: If i disable the VAT rules the prices looks as is set. I don't understand the behavior, because the price includes a 10% VAT. But when the VAT rule is enabled the price is increased in a 25,82%. I checked that the tax rate is correctly set.

Price higher that I have set


Como agrupar documentos por valor de um campo e retorná-los em uma lista no aggregate (mongodb)?

Question: Tenho uma collection com os seguintes documentos:
{
  "name": "mario",
  "idade": 12,
  "peso": 50
}
{
  "name": "mario",
  "idade": 15,
  "peso": 60
}
{
  "name": "roberto",
  "idade": 20,
  "peso": 70
}
{
  "name": "roberto",
  "idade": 10,
  "peso": 40
}

Quero gerar o seguinte resultado com uma query unica, se possível:
{
  "mario": [
    {
      "name": "mario",
      "idade": 12,
      "peso": 50
    },
    {
      "name": "mario",
      "idade": 15,
      "peso": 60
    }
  ],
  "roberto": [
    {
      "name": "roberto",
      "idade": 20,
      "peso": 70
    },
    {
      "name": "roberto",
      "idade": 10,
      "peso": 40
    }
  ]
}

O objetivo é usar o valor do campo name como chave de um dicionario cujo seu valor seja uma lista que contenha todos os documentos que possuem o mesmo valor para o campo name.
Tentei uma query assim:
people = database.db.get_collection('peoples').aggregate([
            {'$match': {'name': {'$exists': True}}}, // existem alguns documentos que nao possuem o campo
            {'$group': {'$name': {'$match': {'name': '$name'}} } }
        ])

Mas a operação é impossível:
pymongo.errors.OperationFailure: The field name '$name' cannot be an operator name, full error: {'ok': 0.0, 'errmsg': "The field name '$name' cannot be an operator name", 'code': 40236, 'codeName': 'Location40236', '$clusterTime': {'clusterTime': Timestamp(1657199053, 9), 'operationTime': Timestamp(1657199053, 9)}

ps: modifiquei um pouco o contexto do codigo para simplificar.
Answer: Espero que ajude.
db.collection.aggregate([
{
    $group:{
        _id: '$name',
        data:{$push:'$$ROOT'}
    }
},
 {
    $replaceRoot: {
        newRoot: {
            $arrayToObject: {
                $let: {
                    vars: { data: [ { k: { $toString: "$_id" }, v: "$data" } ] },
                    in: "$$data"
                }
            }
        }
    }
}])

Result:
{
"mario" : [
    {
        "_id" : ObjectId("62e40ed210d96f0f62490933"),
        "name" : "mario",
        "idade" : 12,
        "peso" : 50
    },
    {
        "_id" : ObjectId("62e40ed210d96f0f62490934"),
        "name" : "mario",
        "idade" : 15,
        "peso" : 60
    }
]
}, {
"roberto" : [
    {
        "_id" : ObjectId("62e40ed210d96f0f62490935"),
        "name" : "roberto",
        "idade" : 20,
        "peso" : 70
    },
    {
        "_id" : ObjectId("62e40ed210d96f0f62490936"),
        "name" : "roberto",
        "idade" : 10,
        "peso" : 40
    }
]

}


How to display the user's image in a Message Template?

Question: I activated the sub-module "Message Example" of the module "Message".
I added the token in the "Example - User register" message template :
[message:author:user_picture:thumbnail]

When a message is created, it displays the url of the user's image.
How to display the user's image in a Message Template ?
Answer: You can use the following token: [message:author:user_picture] i.e. same as yours with the thumbnail subsection
UPDATE:
In order to get the image styles to work I had to switch to "Full HTML" text filter, then while editing the "Source" I added this line:

And it worked for me like this.
Comment: I just tested and there is nothing posted, not even the link
Comment: Strange because this works in my installation
Comment: It works. The problem is that when there is a default image, it is not displayed. Now how to display with the image style thumbnail ? Because the images are displayed in 100x100 with the original dimension (they are heavy).
Comment: @m1lbt I updates my answer, please check it


First principal component for two variables?

Question: Proof that if two variables (X, Y) have covariance S= $\begin{pmatrix}
  a & b\\
  c & d
\end{pmatrix}$, then proof that if c $\neq$ 0, then the first principal component is $\sqrt{\frac{c^2}{c^2+(V_1-a)^2}X}+\frac{c}{|c|}\sqrt{\frac{(V_1-a)â}{c^2+(V_1-a)^2}Y}$
Where $V_1$ is the variance explained by the first principal component.
I tried finding the eigenvalues and eigenvector of S, but couldn't, so I tried substituting $V_1$ and trying to find another solution, but I didn't get anywhere.
Answer: This is just computing the top eigenvector and eigenvalues of a 2x2 symmetric matrix and interpreting it in the context of PCA. For a generic 2x2 matrix $A := \begin{bmatrix} a & b \\ c & d\end{bmatrix}$ we can find the eigenvalues by
$$
p_A(\lambda) = \det\left(A - \lambda I\right)
$$
$$
= (a-\lambda)(d-\lambda) - bc \\
= \lambda^2 -\lambda (a+d) + ad - bc \\
= \lambda^2 - \operatorname{tr}(A)\lambda + \det A.
$$
Setting this to zero yields
$$
\lambda = \frac{\operatorname{tr}(A) \pm \sqrt{(\operatorname{tr} A)^2 - 4\det A}}{2}.
$$
For PCA we'll be interested in $\lambda_1$, the largest eigenvalue.

For the eigenvectors, we need to solve the system
$$
Sv = \lambda v \\
\iff (S - \lambda I)v = \mathbf 0
$$
with $v \in \mathbb R^2$ and $\lambda$ being an eigenvalue. The eigenvalues are chosen to be such that $S - \lambda I$ is singular which means without even needing to do the arithmetic this'll row reduce to
$$
\begin{bmatrix} a-\lambda & b \\ 0 & 0\end{bmatrix}v = \mathbf 0
$$
since $b \neq 0$ so for an arbitrary eigenvalue I'll need to have $(a-\lambda)v_1 + bv_2 = 0$. And again because $b \neq 0$ by assumption we'll get
$$
v_2 = \frac{\lambda - a}{b} v_1.
$$
I want to choose my eigenvectors to be unit vectors so
$$
v_1^2 + \left(\frac{\lambda - a}{b} \right)^2v_1^2 = 1 \\
\implies v_1^2 = \left(1 + \left(\frac{\lambda - a}{b} \right)^2\right)^{-1} \\
= \frac{b^2}{b^2 + (\lambda - a)^2}.
$$
Eigenvectors can be scaled so I can just take the positive square root. I'll then have
$$
v_2 = \frac{\lambda - a}{b}\sqrt{\frac{b^2}{b^2 + (\lambda - a)^2}}.
$$
After some rearranging and using $\lambda=\lambda_1$ we have everything we need to finish the result so I'll leave it here.