Losing solutions in $\cos{x}+\cos{2x}=0$

Question: I'm trying to solve $\cos x=-\cos2x$, $-\pi<x\leq\pi$, WITHOUT USING the double angle formulae, here's my current working:
$$\begin{align*}\cos x&=-\cos2x\\
\cos (x\pm2k\pi)&=\cos (2x\pm(2k+1)\pi)\\
\implies x\pm2k\pi&=2x\pm(2k+1)\pi\\
x&=2x\pm\pi\\
x&=\pm\pi\\
\therefore x&=\pi\text{  , in the given range of $x$}\end{align*}$$
Graphically it's obvious I've missed two other solutions, $x=\pm\frac{\pi}{3}$, however I do not know why because I have not, to my knowledge, carried out any illegal operations such as dividing by zero.
Could someone point out my mistake please and give an edited solution? Thanks!
Comment: $k$ on the left and right sides should not be the same.
Comment: Your implication is wrong.
Comment: @AlexSilva I graphed them on Desmos for integer values of $k$ and they always lined up with the original graphs? Or am I missing something?
Answer: Use that
$$\cos x=-\cos2x \iff \cos x=\cos(\pi-2x)$$
and that
$$\cos \alpha = \cos \theta \iff \alpha = \theta +2k\pi \, \lor \, \alpha = -\theta +2k\pi \quad k\in \mathbb{Z}$$
Refer also to the related

Solving $\cos(3x) = \cos(2x)$
Comment: Ah okay, so from what I gathered (being still in highschool I'm not completely familiar with the if and only if implication so I've probably misinterpreted this answer), I came up with $\pm x+2k\pi = k\pi \pm 2x \implies k\pi = \pm x,\pm 3x$, which works but obviously only for odd-values of k, however k exists as an integer (and likewise works as an integer for my first statement in this comment)?
Comment: @AdamBromiley The simbol $\lor$ stays for logical "or".
Comment: @AdamBromiley Then we have $$x=\pi-2x+2k\pi$$ or $$x=-(\pi-2x)+2k\pi$$ From here we can find all the solutions. Refer also to the given example. Do not hesitate to ask for any other clarification. Bye
Comment: Ah okay I get that now, apart from the one implication on the first line of your answer, why is there not a $k$ in $\cos(\pi -2x)$? Surely it is true for any odd multiples of pi?
Comment: @AdamBromiley The first line is always true, we use that to transform the given equation in an other equivalent in order to eliminate the minus sign in front. Then we can use the second identity to find the solutions.
Comment: Oh right okay, think I understand it now, cheers!
Comment: You are welcome! Bye
Answer: $$\cos(x+\pi)=\cos(2x)\iff x+\pi=2k\pi\pm2x.$$
Hence
$$x=(2k+1)\pi\lor x=(2k+1)\frac\pi3.$$


Why does Drush crash with "SQLSTATE[HY000] [2002] No such file or directory"?

Question: I have an error when i try to update my db or install a module with drush.
[info] Try to validate bootstrap phase 5 [0.11 sec, 10.08 MB]
[info] Unable to connect to database with message: SQLSTATE[HY000] [2002] No such file or directory. More debug information is available by running drush status. This may occur when Drush is trying to bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See drush topic docs-aliases for details. [0.11 sec, 10.31 MB]
[info] Could not bootstrap at phase 5 [0.11 sec, 10.29 MB]
this is my drush status.
Drupal version : 9.5.4
Site URI       : http://default
DB driver      : mysql
DB hostname    : localhost
DB port        : 3306
DB username    : root
DB name        : DruCar
PHP binary     : /firstname.lastname@example.com/8.1.15/bin/php
PHP config     : /opt/homebrew/etc/php/8.1/php.ini
PHP OS         : Darwin
PHP version    : 8.1.15
Drush script   : /usr/local/bin/drush
Drush version  : 11.5.1
Drush temp     : /tmp
Drush configs  : /Applications/XAMPP/xamppfiles/htdocs/DruCar/recommended-project/vendor/drush/drush/drush.yml
Drupal root    : /Applications/XAMPP/xamppfiles/htdocs/DruCar/recommended-project/web
Site path      : sites/default
anyway, i cant install anything with drush en.
Thank you anticipate.
Comment: Get rid of XAMPP. Use [DDEV](https://ddev.readthedocs.io/en/stable/users/install/ddev-installation/). You don't need an UI, you need a tool that's optimised as a local Drupal/PHP development environment.
Answer: This is likely the well-known situation of using localhost for the database configuration, which is interpreted by some database extensions as an instruction to use a unix socket file, and then the unix socket file is not properly configured.  The usual solution is to use 127.0.0.1, the IPv4 address, instead of localhost in the database configuration. See https://serverfault.com/questions/295285/mysql-cannot-connect-via-localhost-only-127-0-0-1
Core has this issue, https://www.drupal.org/project/drupal/issues/2610858, which is attempting to improve error messaging about it, which may or may not impact Drush. Drush has had this question asked many, many times.
Answer: agre with answer from @cilefen
this is my example for local project. try doing the same, bottom line - use 127.0.0.1 instead of localhost in file

settings.local.php

$databases['default']['default'] = array (
    'database' => 'yourproject_local',
    'username' => 'root',
    'password' => 'yourpassword',
    'prefix' => '',
    'host' => '127.0.0.1',
    'port' => '3306',
    'driver' => 'mysql',
);

$settings['trusted_host_patterns'] = array(
    '^subdomain\.test\.yourise\.local',
    '^yoursite\.dev\.local$',
    '^subdomain\.something\.yourhosting\.com$',
    '^example\.at$',
    '^www\.example\.at$',
);

Comment: If you agree with a given answer, wait you can up-vote answers and up-vote the existing answer. There is no need to add an answer just to repeat what already said, especially when the existing answer provides links that explain why it happens.
Comment: of course, i've just added example how I use my settings.local.php file so maybe someone will use this snippet one day. I would like sometimes to get answers like that in my own questions.


Junit5 annotated functions not executing with Ktor and Gardle

Question: I am using Ktor 2.3.3, Kotlin 1.9.10 and Junit 5.10.0 with java version "20.0.2" 2023-07-18
I'm trying to get a server started and then execute a series of tests against it. Here's my test code:
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.testing.*
import kotlin.test.*
import org.junit.jupiter.api.Test
import org.slf4j.LoggerFactory
import io.ktor.server.engine.connector
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.AfterEach
import io.ktor.server.config.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import com.typesafe.config.ConfigFactory

class ApplicationTest {
    private lateinit var client: HttpClient

    companion object {
        val engine = TestApplicationEngine(createTestEnvironment {
            config = HoconApplicationConfig(ConfigFactory.load("application.conf"))
        })

        @BeforeAll
        @JvmStatic
        fun setup() {
            println("TESTING IS READY TO BEGIN!")
            engine.start(wait = false)
            engine.application.module()
        }
    }

    @BeforeEach
    fun init() {
        println("BeforeEach Initialising HttpClient!")
        client = HttpClient()
    }

    @AfterEach
    fun cleanup() {
         println("AfterEach closing client!")
        client.close()
    }

    @Test
    fun testRoot() = with(engine) {
        println("TEST CALLED!")
        with(handleRequest(HttpMethod.Get, "/")) {
            assertEquals(HttpStatusCode.OK, this.response.status())
        }
    }
}

When I run ./gradlew clean test --info I can see setup function being called but none of the other annotated functions execute. The log file indicates a server is started on http://0.0.0.0:8070 but there are no log messages indicating the test was run and the server remains running until it is shutdown.
2023-10-10 22:35:41.874 [Test worker] INFO  ktor.application - Configuring application...
2023-10-10 22:35:41.886 [Test worker] INFO  ktor.application - Configuring logger...
2023-10-10 22:35:41.893 [Test worker] INFO  ktor.application - Running database migration: false
2023-10-10 22:35:41.893 [Test worker] INFO  ktor.application - Configuring HTTP...
2023-10-10 22:35:41.977 [Test worker] INFO  ktor.application - Configuring security...
2023-10-10 22:35:41.979 [Test worker] INFO  ktor.application - Configuring response...
2023-10-10 22:35:41.998 [Test worker] INFO  ktor.application - Configuring routes...
2023-10-10 22:35:42.007 [Test worker] INFO  ktor.application - Authentication successful for route: api/v2/xxxx
2023-10-10 22:35:42.007 [Test worker] INFO  ktor.application - Routing to: api/v2/xxxx
2023-10-10 22:35:42.007 [Test worker] INFO  ktor.application - Application started.
2023-10-10 22:35:42.007 [Test worker] INFO  ktor.application - Application started in 0.135 seconds.
2023-10-10 22:35:42.007 [Test worker] INFO  ktor.application - Application started: io.ktor.server.application.Application@62a68bcb
2023-10-10 22:35:42.078 [DefaultDispatcher-worker-1 @coroutine#2] INFO  ktor.application - Responding at http://0.0.0.0:8070
2023-10-10 22:35:48.965 [KtorShutdownHook] INFO  ktor.application - Application stopping: io.ktor.server.application.Application@62a68bcb
2023-10-10 22:35:48.969 [KtorShutdownHook] INFO  ktor.application - Application stopped: io.ktor.server.application.Application@62a68bc

Here's the output from Gradle:
Skipping task ':compileTestJava' as it has no source files and no previous output files.
Resolve mutations for :testClasses (Thread[#1410,Execution worker,5,main]) started.
:testClasses (Thread[#1410,Execution worker,5,main]) started.

> Task :testClasses UP-TO-DATE
Skipping task ':testClasses' as it has no actions.
Resolve mutations for :test (Thread[#1413,Execution worker Thread 4,5,main]) started.
:test (Thread[#1413,Execution worker Thread 4,5,main]) started.
Gradle Test Executor 11 started executing tests.

> Task :test
Caching disabled for task ':test' because:
  Build cache is disabled
Task ':test' is not up-to-date because:
  Output property 'binaryResultsDirectory' file /Users/xxxx/Projects/xxxx/development/xxxx/build/test-results/test/binary has been removed.
  Output property 'binaryResultsDirectory' file /Users/xxxx/Projects/xxxx/development/xxxx/build/test-results/test/binary/output.bin has been removed.
  Output property 'binaryResultsDirectory' file /Users/xxxx/Projects/xxxx/development/xxxx/build/test-results/test/binary/output.bin.idx has been removed.
  Output property 'binaryResultsDirectory' file /Users/xxxx/Projects/xxxx/development/xxxx/build/test-results/test/binary/results.bin has been removed.
  Output property 'reports.enabledReports.html.outputLocation' file /Users/xxxx/Projects/cashi/development/croms_api/build/reports/tests/test has been removed.
file or directory '/Users/xxxx/Projects/cashi/development/croms_api/build/classes/java/test', not found
Starting process 'Gradle Test Executor 11'. Working directory: /Users/xxxx/Projects/xxxx/development/xxxx Command: /Library/Java/JavaVirtualMachines/jdk-20.jdk/Contents/Home/bin/java -Dorg.gradle.internal.worker.tmpdir=/Users/xxxx/Projects/xxxx/development/xxxx/build/tmp/test/work -Dorg.gradle.native=false @/Users/xxxx/.gradle/.tmp/gradle-worker-classpath12202243415355835399txt -Xmx512m -Dfile.encoding=UTF-8 -Duser.country=GB -Duser.language=en -Duser.variant -ea worker.org.gradle.process.internal.worker.GradleWorkerMain 'Gradle Test Executor 11'
Successfully started process 'Gradle Test Executor 11'

ApplicationTest STANDARD_ERROR
    SLF4J: Class path contains multiple SLF4J providers.
    SLF4J: Found provider [ch.qos.logback.classic.spi.LogbackServiceProvider@44be0077]
    SLF4J: Found provider [org.slf4j.nop.NOPServiceProvider@2205a05d]
    SLF4J: See https://www.slf4j.org/codes.html#multiple_bindings for an explanation.
    SLF4J: Actual provider is of type [ch.qos.logback.classic.spi.LogbackServiceProvider@44be0077]

ApplicationTest STANDARD_OUT
    TESTING IS READY TO BEGIN!
<============-> 92% EXECUTING [32s]
> :test > 0 tests completed
> :test > Executing test croms.ApplicationTest

I can't see anything indicating that @BeforeEach, @AfterEach or even @Test are executed.
When I add the ability to not run a server and alter the test to accordingly, the tests are run but I'd rather not have to mock the results and run the tests against a running server.
package croms

import croms.commons.helpers.getEnv
import croms.commons.plugins.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.config.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.cors.*

@Suppress("UNUSED_PARAMETER")
fun main(args: Array<String>) {
    embeddedServer(Netty, port = getEnv("PORT", 5000) as Int, module = Application::module).start(wait = true)
}

@Suppress("UNUSED_PARAMETER") // Referenced in application.conf
fun Application.module(testing: Boolean = false, startServer: Boolean = true) {
    if (startServer) {

        embeddedServer(Netty, port = getEnv("PORT", 5000) as Int) {
            log.info("Configuring application...")
            configureApplication()
            log.info("Configuring logger...")
            configureLogger()
            log.info("Running database migration: ${getEnv("MIGRATE_DATABASE")}")
            databaseMigration()
            log.info("Configuring HTTP...")
            configureHTTP()
            log.info("Configuring security...")
            configureSecurity()
            log.info("Configuring response...")
            configureResponse()
            log.info("Configuring routes...")
            configureRoutes()
            log.info("Application started.")
        }.start(wait = true)
    } else {
        log.info("Server not started, running in test mode")
    }
}

And the corresponding test:
package croms
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import io.ktor.server.engine.connector
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Test
import io.ktor.server.application.*
import io.ktor.server.config.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import com.typesafe.config.ConfigFactory
import io.ktor.server.testing.*
import kotlin.test.*

class ApplicationTest {

    @Test
    fun testRoot() {
            withTestApplication({ module(testing = true, startServer = false) }) {
            handleRequest(HttpMethod.Get, "/").apply {
                assertEquals(HttpStatusCode.NotFound, response.status())
            }
        }
    }

    @Test
    fun testSerialsStatistics() {
            withTestApplication({ module(testing = true, startServer = false) }) {
            handleRequest(HttpMethod.Get, "/api/v2/xxxx/serials-statistics").apply {
                assertEquals(HttpStatusCode.OK, response.status())
            }
        }
    }
}

Console output:
ApplicationTest > testRoot() PASSED

ApplicationTest > testSerialsStatistics() FAILED
    java.lang.AssertionError: expected:<200 OK> but was:<404 Not Found>

Comment: Can you reproduce the problem without starting the server?
Comment: Yes, a [mre] would help in this case
Comment: No. When I change Application.kt to have the option of not starting a server the tests are run:

@Suppress("UNUSED_PARAMETER") // Referenced in application.conf
fun Application.module(testing: Boolean = false, startServer: Boolean = true) {
    if (startServer) {

        embeddedServer(Netty, port = getEnv("PORT", 5000) as Int) {
            log.info("Configuring application...")

        }.start(wait = true)
    } else {
        log.info("Server not started, running in test mode")
    }
}

`ApplicationTest > testRoot() PASSED`
`ApplicationTest > testSerials() FAILED`
Answer: I think the problem was with the messy way the Application.kt was creating the server, this seems to have resolved the problem and cleaned up the code:
package croms

import croms.commons.helpers.getEnv
import croms.commons.plugins.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.config.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.cors.*

fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)

@Suppress("UNUSED_PARAMETER") // Referenced in application.conf
fun Application.module(testing: Boolean = false) {
        log.info("Configuring application...")
        configureApplication()
        log.info("Configuring logger...")
        configureLogger()
        log.info("Running database migration: ${getEnv("MIGRATE_DATABASE")}")
        databaseMigration()
        log.info("Configuring HTTP...")
        configureHTTP()
        log.info("Configuring security...")
        configureSecurity()
        log.info("Configuring response...")
        configureResponse()
        log.info("Configuring routes...")
        configureRoutes()
        log.info("Application started.")
}

ApplicationTest.kt
package croms
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import io.ktor.server.engine.connector
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.api.*
import io.ktor.server.application.*
import io.ktor.server.config.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import com.typesafe.config.ConfigFactory
import com.fasterxml.jackson.databind.ObjectMapper

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ApplicationTest {
    private lateinit var client: HttpClient

    @Test
    fun testRoot() = withTestApplication(Application::module) {
        val call = handleRequest(HttpMethod.Get, "/")
        with(call) {
            Assertions.assertEquals(HttpStatusCode.OK, response.status())
            val content = response.content
            val jsonNode = ObjectMapper().readTree(content)
            Assertions.assertEquals(false, jsonNode.get("status").asBoolean())
            Assertions.assertEquals(404, jsonNode.get("code").asInt())
            Assertions.assertEquals("الصفحة التي تبحث عنها غير موجودة", jsonNode.get("message").asText())
            Assertions.assertTrue(jsonNode.get("data").isObject)
        }
    }

    @Test
    fun testUnautherizedSerialsStatistics() = withTestApplication(Application::module) {
        val call = handleRequest(HttpMethod.Get, "/api/v2/xxxx/serials-statistics")
        with(call) {
            Assertions.assertEquals(HttpStatusCode.OK, response.status())
            val content = response.content
            val jsonNode = ObjectMapper().readTree(content)
             Assertions.assertEquals(401, jsonNode.get("code").asInt())
        }
    }
}

I need to mop up the deprecated functions but the test case is running as expected and producing reports:
> Task :compileKotlin
w: file:///Users/husseinbadakhchani/Projects/cashi/development/croms_api/src/main/kotlin/croms/commons/helpers/httpclient/HttpServiceImpl.kt:47:13 'handleResponseException(suspend (cause: Throwable) -> Unit): Unit' is deprecated. Consider using `handleResponseExceptionWithRequest` instead

> Task :compileTestKotlin
w: file:///Users/husseinbadakhchani/Projects/cashi/development/croms_api/src/test/kotlin/croms/ApplicationTest.kt:22:22 'withTestApplication(Application.() -> Unit, TestApplicationEngine.() -> R): R' is deprecated. Please use new `testApplication` API: https://ktor.io/docs/migrating-2.html#testing-api
w: file:///Users/husseinbadakhchani/Projects/cashi/development/croms_api/src/test/kotlin/croms/ApplicationTest.kt:36:47 'withTestApplication(Application.() -> Unit, TestApplicationEngine.() -> R): R' is deprecated. Please use new `testApplication` API: https://ktor.io/docs/migrating-2.html#testing-api

> Task :test

ApplicationTest > testRoot() PASSED

ApplicationTest > testUnautherizedSerialsStatistics() PASSED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

For more on this, please refer to https://docs.gradle.org/8.4/userguide/command_line_interface.html#sec:command_line_warnings in the Gradle documentation.

BUILD SUCCESSFUL in 4s


I want to convert array to object in java script like[ ["key1","ans1"],["key2","ans2"] ]=> {key1:"ans1",key2:"ans2"}

Question: I want to convert array to object in javascript like
[["key1","ans1"],["key2","ans2"]] => {key1:"ans1",key2:"ans2"}
Answer: Here you go;

    let res = {}
    let arr = [["key1","ans1"],["key2","ans2"]]
    for (let i = 0; i < arr.length; i++) {
        res[arr[i][0]] = arr[i][1]
    }

    console.log(res)

please comment if you need explanation.
Comment: Can you please explain what is wrong with my answer?
Comment: Your answer is correct for previous question. Could you please edit it for updated question.
Comment: Edited my answer and works fine with your new question.
Comment: Thank you very much. It is working. Again thankyou....
Comment: please leave an upvote also. Thanks!
Comment: also comment if you need explanation


Vue.JS $HTTP displaying data from an api

Question:  html>

    <title>Vue App</title>

{{ responseOptions| json }}

{{ origin | json }}

Hello,
Trying to figure out how the vue-resource $http access to an api works. So created this basic page and when I load it to the browser, all I get is an empty array. I followed the instruction posted on the official page (https://github.com/pagekit/vue-resource/blob/master/docs/http.md)
I'm able to display the response.status on the page so the script is communicating but the data is not displayed at all. If you visit the page (https://jsonplaceholder.typicode.com/users) data is there.
What am I doing wrong?
Please advise...
Comment: If you are using Vue 2, ready hook is depracated - use mounted instead, or even better option is go with created.
Also what is `this.$resource` ? There you should define `this.$http`
Answer: Check this example
https://jsbin.com/jeqekexiqa/edit?html,js,console,output
First I noticed you are using two versions of vue together, which is not good.I sticked in example with Vue 2.
Next, this.$resource is a bit strange thing for me, so I'm not sure what is suposed to do.You can use Vue.http globally, or this.$http if you want to use it directly into Vue instance.
In my example I defined array, where we would store data.Then I write method that would trigger http request and get JSON data from server, and store that data in items array in our data model.
But...that's not enough because our method is not triggered, so we call it immediately after Vue instance is created, by using created() lifecycle hook.
Later in template, we just do simple iteration with v-for to show that everything is working.
Comment: Thank you Belmin. Very generous with your answer. Helped me a lot.


sum of cubes using formula

Question: Given
\sum_{k=0}^{n}k^3 = \frac{n^2(n+1)^2}{4}

I need to compute the left hand side. I should make a list of the first 1000 integer cubes and sum them.
Then I should compute the right hand side and to the same.
Also, I am supposed to compare the computational time for the above methods.
What I've done so far is:
import time
start = time.clock()

list = []
for n in range(0,1001):
    list.append(n**3)
print(list)
print("List of the first 1000 integer cubes is:",list, "and their sum is:", sum(list))

stop = time.clock()
print("Computation time: ",stop-start, "seconds.")

a=0
for n in range (0,1001):
    a=(int)(n*(n+1)/2)
print ("Sum of the first 1000 integer cubes is:",a*a)

First part for the left hand side works fine, but the problem is the right hand side.
When I type n=4, I will get the same result for the both sides, but problem occurs when n is big, because I get that one side is bigger than the other, i.e. they are not same.
Also, can you help me create a list for the right hand side, I've tried doing something like this:
a=[]
for n in range (0,10):
    a.append(int)(n**2(n+1)**2/4)

But it doesn't work.
For the computational time, I think I am supposed to set one more timer for the right hand side, but then again I am not sure how to compare them.
Any advice is welcome,
Comment: Running a copy-paste version of what you are showing us, executes correctly from my command line.
Comment: What error are you getting? You should also use `int((n*(n+1))/2)**2)` It works fine for me.
Comment: "It does not seem to work" is not a sufficient problem description. Please describe how your code is failing; include the full traceback if you're getting an exception, or if you're just getting unexpected results, show the results you're getting and what you expect.
Comment: @CeliusStingher It says "can only concatenate list (not "int") to list"
Comment: @glibdud I've just added that.
I want to use formula based on mathematical induction to compute sum of cubes of first 100 integers.
Comment: Like Celius, the given code runs to completion for me without any errors.
Comment: @glibdud But when I try to compute the sum k**3 for k in range (0,100) and sum using formula, I don't get the same result. That  is weird.
Comment: Why don't you post that instead of the code that works. Open a new question with that code and the error, and maybe we can help you because the information the post contains is functional.
Comment: @CeliusStingher I've just edited my question, hopefully it looks better now.
Answer: Ok, I think what you tried in a for loop is completely wrong. If you want to prove the formula "the hard way" (non-inductive way it is) - you need to simply sum cubes of n first integers and compare it against your formula - calculated one time (not summed n times).
So evaluate:
n=100
s=0
for i in range(1,n+1):
    s+=i**3
###range evaluates from 1 till n if you specify it till n+1
s_ind=(n**2)*((n+1)**2)/4

print(s==s_ind)

Otherwise if you are supposed to use induction - it's all on paper i.e. base condition a_1=1^3=((1)*(2)^2)/4=1 and step condition i.e. a_n-a_(n-1)=sum(i^3)[i=1,...,n]-sum(j^3)[i=1,...,n-1]=n^3 (and that it also holds assuming a_n=your formula here (which spoiler alert - it does ;) )
Hope this helps.
Comment: Thank you, I just edited my question, hopefully this time it makes more sense.
Comment: still - the above holds - you don't do your formula in loop - you just compute it once, for predefined ```n``` - then you compare the sum of cubes in ```for``` loop and compare the processing times

sum of cubes using formula


Is it correct to make queries to DB in preprocess functions?

Question: I've just started using Drupal after long experience of using other framework.
When I do something new, I'm scaring to crash performance because of my incomprehension.
So, my problem:
I want to add dynamically some data from database to some existing page region.
For example, I want to add list of child terms to taxonomy term page. And I don't need to change any other things on this page, so I don't want to turn on View.
Is it normal to query data in preprocess functions?
My solution for D7 was like this:
<code>function mymodule_taxonomy_term_view_alter(&$build) {
  if ($build['#view_mode'] == 'full') {
    $children = taxonomy_get_tree($build['#term']->vid, $build['#term']->tid, 1);
    foreach($children as $term) {
      $build['children'][] = (array)$term;
    }
  }
}

function mymodule_preprocess_taxonomy_term(&$variables) {
  if($variables['vocabulary_machine_name'] == 'catalog') {

    if(count($variables['elements']['children'])) {
      $items = array();
      foreach($variables['elements']['children'] as $term) {
        $items[] = array(
          'data' => l($term['name'], 'taxonomy/term/' . $term['tid'])
        );
      }

      $variables['content']['children']['#markup'] = theme('item_list', array('items' => $items, 'title' => 'Text terms list', 'type' => 'ul', 'attributes' => array()));
    }
  }
}
</code>
Any comment are welcome.
Answer: No, it's not incorrect to query the database in a preprocess function. If the information is required to render the page, putting a query in a preprocess function is an acceptable choice. Plus, in this particular case taxonomy_get_tree() caches results, so there is very little cost associated with repeated fetches.
Regarding Views, yes there is some overhead associated with it, but it employs a sophisticated caching strategy, and is ultimately just so powerful and useful that most sites use it. You could probably solve this current problem with no custom code by using a Viewfield.
These questions provide a lot of interesting background on Drupal performance.
Comment: I agree; there is nothing wrong in querying the database in a preprocess function; if that would be wrong, then most of the Drupal functions should not be called, including the ones that cache the data, as by default Drupal caches the data using the database. It's then better to have such code in a preprocess function than in a template file.
Comment: «You could probably solve this current problem with no custom code by using a Viewfield.»      —
Thank you, that was useful)


trying to get hands on angular Routing concepts BUT when try to reload the page NOTHING HAS BEEN SHOWN up.

Question: I working on this in editor Bracket and I created bunch of files and file structure can be seen in under scripts tags under Index.html
the root folder names is projectAngular under which there is folder appCntrl -->controller--->(all the controllers files).Also Under folder views-->customers.html and under script==>[angular and angular route files]
Index.html is at root "projectAngular" folder
while trying to run this application I can only see BLANK screen. I check my script tags under index.html. appears good. Also under controller I think i gave dependencies also. I am not sure what exactly is happening here or the angular version i am using is outdated.
Pls HELP!!!! thanks
I created exact in Plunkr . Below is the URL
http://plnkr.co/edit/WVAglImSEKQkQA1BaAUZ?p=catalogue
index.html
<!doctype html>

  <title> Iterating over Data</title>

customer.html

Customers

 FILTER:
<input type="text" ng-model="customerFilter.name">{{customerFilter.name}}

    Name

    City

    OrderTotal

    Joined

    {{cust.name| uppercase}}

    {{cust.city | lowercase}}

    {{cust.orderTotal | currency}}

    {{cust.joined | date}}

    Total Customers: {{customers.length}}
customerController.js file
(function() {

  var customerApp = angular.module('demoApp', ['ngRoute']);

  // It helps angular to realize what params are being passed to controller if minification has replaced the variables
  customerController.$inject = ['$scope'];

  function customerController($scope) {
    $scope.sortBy = 'name';
    $scope.reverse = false;

    $scope.customers = [{
      name: 'kevin',
      city: 'San Farnando',
      orderTotal: '10.78',
      joined: '1990-12-10'
    }, {
      name: 'ketty',
      city: 'Seattle',
      orderTotal: '12.99',
      joined: '2003-4-7'
    }, {
      name: 'John',
      city: 'Texas',
      orderTotal: '6.787',
      joined: '2015-9-9'
    }, {
      name: 'Jackson',
      city: 'ohio',
      orderTotal: '12.00',
      joined: '2003-12-1'
    }];
    $scope.doSort = function(propName) {
      $scope.sortBy = propName;
      $scope.reverse = !$scope.reverse;
    };

  }
  customerApp.controller('customerController', customerController);
}());

appRoute.js
(function() {

  var customerApp = angular.module('demoApp', ['ngRoute']);

  customerApp.config(function($routeProvider) {
    $routeProvider
      .when('/', {
        controller: 'customerController',
        templateurl: 'views/customer.html'
      })
      .otherwise({
        redirectTo: '/'
      });
  });

}());

Comment: @BillPope  I tried it but its not working. Thanks.
Comment: I'm only adding this as a comment because I'm not sure if this will solve the problem or even if it's just nonsense, but, consider making the module's second argument an empty array in customerController.js . I've had problems with injecting on all pages except the app page
Comment: Maybe you can try a simpler example, like just one js and two static pages.
Answer:
The first thing you need to do is to make sure that:
angular.module('demoApp', ['ngRoute']);

is used only once.
In your controller, you need to use:
    var customerApp = angular.module('demoApp');

Adding the empty brackets instantiates a new angular module which you don't want to do here.

In your appRoute.js file, make sure the templateUrl points to the correct file.
Remove  and replace with .
Comment: @pankajparkar as far as the plunkr example is concerned, you might have to reroute the script tags. They're currently pointed to directories that don't exist
Answer: templateurl needs to be templateUrl.
Your plunkr has many mistakes:

You need to update the paths in plunkr to point at the root, there are no folders within plunkr.
Use external angular files, because otherwise, your plunkr size is too big and fails to load.

Updates to your plunkr that made it work.
Comment: it worked . I just pointed to angular CDN rather than pointing to file and corrected spelling.  Thanks


Como capturar o texto que um outro programa de console escreve na tela

Question: Meu programa de Windows Forms executa outro programa de console. Esse segundo escreve mensagens na tela durante a execução. Eu quero saber se tem como impedir que a execução do outro programa abra o console, e em vez disso, os printf do outro programa (que é escrito em C++) sejam exibidos no meu TextBox.
Exemplo prático: o Imagex é um programa de console da Microsoft. Um usuário criou o Gimagex que tem interface gráfica e executa o Imagex e todas as saídas de texto aparecem no Gimagex.
Answer: Antes de fazer process.Start() coloque true em process.StartInfo.RedirectStandardOutput e false em process.StartInfo.UseShellExecute
Supondo que quer receber o output do programa ConsoleApplication.exe numa ListBox faça assim:
public Form1()
{
    InitializeComponent();
    StartProcess();
}

public void StartProcess()
{
    Process p = new Process();
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = "ConsoleApplication.exe";
    p.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);

    p.Start();
    p.BeginOutputReadLine();
    p.WaitForExit();
    p.Close();
}

private void OutputHandler(object process, DataReceivedEventArgs e)
{
    if (!String.IsNullOrEmpty(e.Data))
    {
        listBox1.Items.Add(e.Data);
    }
}

Nota: Parto do principio de que ConsoleApplication.exe não necessita de qualquer intervenção(input) do usuário ao longo da sua execução.
Fontes:
ProcessStartInfo.RedirectStandardOutput Property
Process.BeginOutputReadLine Method
Comment: Nesse seu esquema o console ainda abre mas sem texto, mas o problema é que na linha que passa o texto para meu TextBox (que se chama "Saida") gera a exceção: `Operação entre threads inválida: controle 'Saida' acessado de um thread que não é aquele no qual foi criado.`. E sim, o executável de console não necessita de intervenção do usuário.
Comment: Abrir o console é mesmo assim. Em relação ao problema dos *thread* se você está a executar o meu código noutra *thread* não poderá aceder a nenhum componente visual. Use um [*Task* juntamente com um *IProgress*](http://blogs.msdn.com/b/dotnet/archive/2012/06/06/async-in-4-5-enabling-progress-and-cancellation-in-async-apis.aspx)


Truncated SVD: how do I go from [Uk, Sk, Vk'] to low-dimension matrix?

Question: I have a large word-frequency matrix (~6m unique words X ~4k documents) and I'm trying to use truncated singular value decomposition (SVD) to project it onto a matrix with fewer dimensions. I know how to get to $[U_{k}, S_{k}, V_{k}']$, but I don't know what to do then.
Each tutorial I find gives me a different answer. Here, for instance, I'm told to retain only the first $k$ rows of $S_{k}$ and $V_{k}'$ and then multiply $S_{k}V_{k}'$. In the scikit-learn implementation, however, they do it by multiplying $U_{k}S_{k}'$ (formula and code). (The book chapter they mention as source doesn't say anything about that.) In this previous answer they suggest $X'U_{k}$ instead (though they are talking about PCA, so maybe that doesn't apply here). Other answers haven't helped (here, for instance, they say we need to apply truncated SVD to the reduced matrix - which doesn't sound right, we use truncated SVD precisely to get to the reduced matrix, no?).
So, bottom line: how do I go from $[U_{k}, S_{k}, V_{k}']$ to a reduced data matrix? Which of the above formulas is the correct one (and why)?
Just to be clear: I'm not looking to reduce rank only (that I can do by multiplying $U_{k}S_{k}V_{k}'$ but it gives me the exact same dimensions I had before, which doesn't help me); I want to reduce the actual dimensions of the data matrix.
Answer: Let's say you have 4x2 X matrix, run SVD and get U,S,V:

U is 4x4
S is 4x2, where only the top 2x2 is not empty
V is 2x2

If you want to truncate to a single largest singular value:

remove all columns from U leaving only the first one, now U1 is 4x1
remove all columns from S leaving only the first one, now S1 is 1x1
remove all columns from V leaving only the first one, now V1 is 2x1

You can restore the X matrix by U1*S1*V1'
The dimensionality is greatly reduced because now you can use 4x1 U matrix instead of original 4x2 X matrix.
UPDATE: you also have neat equality: X*V=U*S, so you could use both X*V1 or U1*S1 as your reduced dimension matrices, or simply U1, which is similar to the score in PCA
Comment: look at this [PCA vs SVD](http://www.cs.princeton.edu/picasso/mats/PCA-Tutorial-Intuition_jp.pdf) tutorial, it explains how to estimate PCA through SVD. PCA may seem more intuitive for some people. It also discusses the dimensionality reduction
Comment: That's it then? I simply get U1 and use it instead of X? But then why do some tutorials suggest more complicated formulas, like $S_{k}V_{k}'$, $U_{k}S_{k}'$, and $X'U_{k}$? Or are all of these valid answers but somehow different in their properties? Could you point me in the direction of a book/tutorial/paper that explains why U1 works?


Tamanho tabela não diminui

Question: Uma tabela do mysql tinha 10.2Gb de dados,
Rodei um script que apagava dados antigos que já não eram necessários,
Após apagar metade dos dados dessa tabela, ela ainda continua com 10.2Gb.
Consumindo o HD do meu servidor.

Como ou o que faço para reduzir o tamanho dessa tabela ?
Comment: O banco não realoca memória quando você deleta um registro.
Answer: Quando você deleta um registro, está simplesmente avisando que aquele espaço está livre.
Seria impraticável um DB ficar encurtando o arquivo em produção, pois isso significaria rearranjar todos os dados internamente (similarmente a uma desfragmentação de disco).
Se realmente precisa disso, de alguma forma precisa "remontar" a tabela.
Solução built-in para InnoDB e MyISAM
O MySQL possui o OPTIMIZE TABLE, que entre outras coisas, reorganiza os dados internamente:
OPTIMIZE [NO_WRITE_TO_BINLOG | LOCAL] TABLE tbl_name [, tbl_name] ...

Ele funciona para a maior parte dos usos, e o comportamento muda um pouco entre InnoDB e MyISAM. Não funciona para outros engines, tenha isto em mente.

No InnoDB ele reorganiza índices e tabela no caso específico de você usar um arquivo por tabela (.ibd individual).

No MyISAM já é feita a desfragmentação completa.

https://dev.mysql.com/doc/refman/5.7/en/optimize-table.html

Solução "manual" para uso geral ou "controlado":
Se for um banco que pode ser parado por um instante, uma solução é simplesmente fazer um dump da tabela e recriá-la importando os mesmos dados:

FAÇA BACKUP E TESTE O BACKUP ANTES DE TENTAR ISTO!

mysqldump db_name t1 > dump.sql
mysql db_name < dump.sql

Para fazer em todas as tabelas:
mysqldump --all-databases > dump.sql
mysql < dump.sql

Se precisar manter o DB em produção, uma solução intermediária é criar uma tabela com a mesma estrutura, e usar um
 SELECT * FROM tabela INSERT tabela2

e ao final, renomear as tabelas, depois descartando a antiga.
O cuidado, neste segundo caso, é que você precisa dar um jeito de travar a original contra escrita, pois alguém pode inserir ou modificar um dado enquanto está ocorrendo o INSERT. Esta segunda solução é mais adequada quando você pode bloquear a escrita, mas precisa manter a leitura.

Tamanho tabela não diminui


Dismissed dialog fragment reappears again when app is resumed

Question: Hi I am developing an app that uses maps.
I am using Fragment Activity and a fragment named Fragment-A.
In Fragment-A there is a button, on clicking that button a Dialog Fragment pops up, displays a map with some location received previously from server.
Let us say this dialog fragment is DialogFragment-B.
It has a button to close, a button to navigate to google maps app to get directions.
If user navigate to DialogFragment-B and returns back to the Fragment-A, by clicking close button every thing is working fine.
But if the user clicks on back button the existing dialog fragment will close normally and the app functions normally.
But if the user then pressed home button or received a phone call and onResume is called even though the DialogFragment-B is dismissed earlier, it reappears and pressing close crashes the app with a null pointer exception
Here is my code to open the DialogFragment-B.
FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    android.app.Fragment prev = fm.findFragmentByTag(MY_MAP);
    if (prev != null) {
        ft.remove(prev);
    }
    MyMapFragmentDialog newFragment = MyMapFragmentDialog
            .newInstance(eachPost);
    newFragment.show(ft, MY_MAP);

In DialogFragment-B on clicking close button, I call MyMapFragmentDialog.this.dismiss();
Please if any one have encountered this issue and overcame, guide me through.
Comment: I think you're neglecting to commit the transaction: `ft.remove(prev).commit()` or add another line like `ft.commit();`
Comment: Try the `MyMapFragmentDialog` inside the if loop. The `prev` becomes null and you adding the fragment to it
Answer: I had the same issue and it was solved by making sure I call super.onDismiss(dialog) in the onDismiss method of my DialogFragment subclass.
Comment: I had the same problem, this fixed mine.
Comment: Correct me if I'm worng, I'll just try to provide an explanation.
As far as I understand the dismiss() method works when you use it in your parent activity (where you firsrt created the Dialog Fragment and used dialogFragment.show()).

super.onDismiss(dialog) does the same but within the Dialog Fragment class. 'super' just does it from its parent (the Activity where it was created).
Answer: Update: The answer by Kalina is a more elegant and simple solution - as I figured out later!
I am facing the same issue in one of my apps, and not finding the answer anywhere, went through the source code of the DialogFragment class, which is available at:
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.1_r1/android/app/DialogFragment.java#DialogFragment.onDismiss%28android.content.DialogInterface%29
and there, I found the probable reason written in a comment, within the source of onDismiss(DialogInterface dialog) method:
// Note: we need to use allowStateLoss, because the dialog
// dispatches this asynchronously so we can receive the call
// after the activity is paused.  Worst case, when the user comes
// back to the activity they see the dialog again.

What I understood from this is that dismissal is not saved to the instance state, and when the activity resumes, it promptly shows it again as part of the instance state restoration - assuming that the fragment was never dismissed.   Being an asynchronous event, there is no safe way to commit the dismiss without risking a
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

exception and consequent crash, which is probably why the authors of the class chose to do it this way.
The solution that worked for me was to separately monitor the state of the DialogFragment, by:

Storing it in a Class variable (referred to here as 'dialog')
Overriding the onDismiss(DialogInterface dialog) method, and
Setting a boolean dialogDismissed flag to true

-
@Override
public void onDismiss(DialogInterface dialog) {
   // dialogDismissed is a Class level variable in the containing Activity,
   // must be set to false each time the DialogFragment is shown
   dialogDismissed = true;
}

Note: if the DialogFragment is a separate Class, then  then a method in the Activity will need to be called from the onDismiss to do this, perhaps by setting up an Interface
This flag must then be checked in the activity onResume() and a dismiss forced (after checking that the dialog is not null):

-
@Override
public void onResume() {
super.onResume();
//...
if (dialogDismissed && dialog != null) {
        dialog.dismiss();
    }
}


Como fazer o texto rolar na tela do android

Question: Eu estou querendo colocar em uma tela um texto grande.
Porém estou com um pequeno problema na hora de ler mais, o texto é simplesmente cortado e não tem como rolar para continuar lendo.
Alguém me indica um método para fazer isso?
Exemplo 1:

Exemplo 2:
Comment: Veja esta resposta com a solução: http://pt.stackoverflow.com/a/147688/35406
Answer: Se eu entendi direito, basta colocar seu textview dentro de um Scrollview.
<code><ScrollView
  android:layout_width="match_parent"
  android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

          <TextView
              android:id="@+id/tv_long"
              android:layout_width="wrap_content"
              android:layout_height="match_parent"
              android:text="@string/really_long_string" >
          </TextView>
   </LinearLayout>
</ScrollView>
</code>


Changing factor levels with dplyr mutate

Question: This is probably simple and I feel stupid for asking. I want to change the levels of a factor in a data frame, using mutate. Simple example:
library("dplyr")
dat <- data.frame(x = factor("A"), y = 1)
mutate(dat,levels(x) = "B")

I get:
Error: Unexpected '=' in "mutate(dat,levels(x) ="

Why is this not working? How can I change factor levels with mutate?
Comment: Perhaps `dat %>% mutate(x=factor(x, labels='B'))`  BTW, the pipe operator is not correct in your code
Comment: It may be possible using `magrittr` or other packages, but why do you need to go through this route.  It is very easy to do `levels(dat$x) <- 'B'`
Comment: So, I can't use levels() in mutate? I need to explicitly encode the variable as a factor again? Hmm... (%<>% should be okay, it pipes and assigns the dat)
Comment: Yes, I want to mutate x. I thought "levels(x)" would be enough for mutate to figure out that I want to mutate x. I guess that's a design choice, as it works that way with "within".
Comment: Wouldn't this do more than change the levels of the factor. It actually changes the values of the factor itself. That seems dangerous and leads to some odd behavior. `dat <- data.frame(x = factor(c('A', 'B', 'A')), y = c(1:3));
levels(dat$x) <- c('b', 'a', 'b');
dat`
Comment: If you must use `levels`, you can do `mutate(dat, x = `levels<-`(x, "B"))`.
Answer: With the forcats package from the tidyverse this is easy, too.
mutate(dat, x = fct_recode(x, "B" = "A"))

Comment: Yes it is:

x <- factor(c("apple", "bear", "banana", "dear"));
fct_recode(x, !!!c(fruit = "apple", fruit = "banana"))
Comment: Is it possible to provide the vector of the new levels ?
Answer: I'm not quite sure I understand your question properly, but if you want to change the factor levels of cyl with mutate() you could do:
df <- mtcars %>% mutate(cyl = factor(cyl, levels = c(4, 6, 8)))

You would get:
#> str(df$cyl)
# Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...

Comment: If the levels do not match the original values, instead of `factor(cyl, levels = ...)`, you should do `factor(cyl, labels = ...)`.E.g. `factor(cyl, labels = c('four', 'six', 'eight')`.
Comment: This example is not clear because `cyl` is the same afterwards
Answer: Maybe you are looking for this plyr::revalue function:
mutate(dat, x = revalue(x, c("A" = "B")))

You can see plyr::mapvalues too.
Comment: @DavidTonhofer `dplyr` and `plyr` are known to have namespacing conflicts, but `plyr` has been deprecated for some time anyway
Comment: Loading both `dplyr` and `plyr` is not working for me. The respective functions stomp over one another.
Answer: You can use the recode function from dplyr.
df <- iris %>%
     mutate(Species = recode(Species, setosa = "SETOSA",
         versicolor = "VERSICOLOR",
         virginica = "VIRGINICA"
     )
)

Comment: Note that recode only works on vectors, see answer from PaulFrater for a version that works.
Comment: Which answer are you referring to?
Answer: From my understanding, the currently accepted answer only changes the order of the factor levels, not the actual labels (i.e., how the levels of the factor are called). To illustrate the difference between levels and labels, consider the following example:
Turn cyl into factor (specifying levels would not be necessary as they are coded in alphanumeric order):
    mtcars2 <- mtcars %>% mutate(cyl = factor(cyl, levels = c(4, 6, 8)))
    mtcars2$cyl[1:5]
    #[1] 6 6 4 6 8
    #Levels: 4 6 8

Change the order of levels (but not the labels itself: cyl is still the same column)
    mtcars3 <- mtcars2 %>% mutate(cyl = factor(cyl, levels = c(8, 6, 4)))
    mtcars3$cyl[1:5]
    #[1] 6 6 4 6 8
    #Levels: 8 6 4
    all(mtcars3$cyl==mtcars2$cyl)
    #[1] TRUE

Assign new labels to cyl  The order of the labels was: c(8, 6, 4), hence we specify new labels as follows:
    mtcars4 <- mtcars3 %>% mutate(cyl = factor(cyl, labels = c("new_value_for_8",
                                                               "new_value_for_6",
                                                               "new_value_for_4" )))
    mtcars4$cyl[1:5]
    #[1] new_value_for_6 new_value_for_6 new_value_for_4 new_value_for_6 new_value_for_8
    #Levels: new_value_for_8 new_value_for_6 new_value_for_4

Note how this column differs from our first columns:
    all(as.character(mtcars4$cyl)!=mtcars3$cyl)
    #[1] TRUE
    #Note: TRUE here indicates that all values are unequal because I used != instead of ==
    #as.character() was required as the levels were numeric and thus not comparable to a character vector

More details:
If we were to change the levels of cyl using mtcars2 instead of mtcars3, we would need to specify the labels differently to get the same result. The order of labels for mtcars2 was: c(4, 6, 8), hence we specify new labels as follows
    #change labels of mtcars2 (order used to be: c(4, 6, 8)
    mtcars5 <- mtcars2 %>% mutate(cyl = factor(cyl, labels = c("new_value_for_4",
                                                               "new_value_for_6",
                                                               "new_value_for_8" )))

Unlike mtcars3$cyl and mtcars4$cyl, the labels of mtcars4$cyl and mtcars5$cyl are thus identical, even though their levels have a different order.
    mtcars4$cyl[1:5]
    #[1] new_value_for_6 new_value_for_6 new_value_for_4 new_value_for_6 new_value_for_8
    #Levels: new_value_for_8 new_value_for_6 new_value_for_4

    mtcars5$cyl[1:5]
    #[1] new_value_for_6 new_value_for_6 new_value_for_4 new_value_for_6 new_value_for_8
    #Levels: new_value_for_4 new_value_for_6 new_value_for_8

    all(mtcars4$cyl==mtcars5$cyl)
    #[1] TRUE

    levels(mtcars4$cyl) == levels(mtcars5$cyl)
    #1] FALSE  TRUE FALSE

Answer: Can't comment because I don't have enough reputation points, but recode only works on a vector, so the above code in @Stefano's answer should be
df <- iris %>%
  mutate(Species = recode(Species,
     setosa = "SETOSA",
     versicolor = "VERSICOLOR",
     virginica = "VIRGINICA")
  )


Normal Distribution CLT Question

Question: I am working on a self-study question where

A study indicates that the typical American woman spends USD 340 per year for personal care products. The distribution of the amount follows a right-skewed distribution with a standard deviation of USD 80 per year. If a random sample of 100 women is selected, what is the probability that the sample mean of this sample will be between USD320 and USD350?

I made two attempts to answer the question: one using normal distribution and another using CLT. However, neither approach has helped me achieve the goal answer of 0.8882.
My Normal Distribution Approach

My CLT Approach

Appreciate some guidance and advice please
Comment: Please correct the typos in your question.
Comment: As per your drawing, "right skewed" means "positively skewed", i.e. that the _right_ tail is longer and probability mass concentrates to the _left_ of the density graph.
Comment: @Glen_b I've corrected the question. Do let me know if there's any more corrections needed.
Answer: The normal distribution approach given is failing to take into account how the standard deviation of the sample mean decreases with the sample size.
The CLT approach is looking good until you evaluate H(1.25).  Draw a picture of the area you are trying to calculate and try to figure out what is wrong.  Would it make sense to say that the area to the left of 1.25 was .1056?
Comment: Thanks for the advice Glen. Will make more conscious attempts to improve my problem solving methods. I am confident I will be able to continually improve and contribute to this awesome community which has really helped me a lot in my quest of self-learning stats.
Comment: thanks for the pointer. I get the hint. Since the question states that the distribution is right-skewed, therefore, we can't assume that the left and right area are the same.
Comment: That's not the only problem with that approach! You have simply *got* to stop throwing random calculations at these problems until you reproduce an answer. That's not how to understand what you're doing. You need to consider how to do the calculations that relate to the question. So if it's asking about the distribution sample averages, and your calculation doesn't consider the distribution sample averages, your answer can't be right. Since your first attempt didn't deal with the distribution of averages, it's a complete waste of time to even consider it.
Comment: jsk's first paragraph above is pointing out that in your first attempt you're not dealing with the distribution of averages. You need to ponder the error in ignoring the difference between a distribution for an individual and the distribution of some calculation based on more than one individual carefully, because you've made that error more than once, *even after that type of error has already been pointed out before*. Since the two approaches must give different answers, rather than do both and see if one was right, *figure out which one cannot be right before you start*.
Comment: @Glen_b Im complete clueless as how to determine the Z-value for measuring skewness. I was wondering if https://sites.google.com/site/fundamentalstatistics/appendix-b is something along the lines that I can look into?
Comment: I'm not sure what measuring skewness has to do with the question here; you're not even told how skew the distribution is.
Comment: @Glen_b not sure if i am understanding correctly, but what I inferred from jsk's inputs is that I will not be able to evaluate H(1.25) using the Z table since it is a skewed distribution, whereas the the Z table requires the graph to be symetric?
Comment: jsk's second paragraph relates to the distribution of averages, for which you apply the Central Limit Theorem (*which says what*??). In which case, skewness doesn't come into it *at all*. The problem is that your value is simply *wrong* there. Take a look at what jsk is telling you again, and then do as he or she suggested.
Comment: @Glen_b I can understand that the skewness will not come in at all given that it is CLT, therefore approximately normal. So in that sense, if I wanted to find P (320 < sample mean < 350), I will then be able to derive that P(-2.5 < z < 1.25), which in-turn results in H(1.25) - H(2.5). But what I noticed is that in the question it states that n = 100, where this 100 is the sample size of x and not sample mean (x-bar). Therefore, this is where my  dilemma lies
Comment: There are 100 observations in the sample from which the sample mean was calculated. You need to know about the distribution of that one sample mean (not the empirical distribution of the observed value of the sample mean, the distribution from which the sample mean is drawn). A single random variable still have a distribution, you don't need a collection of them. What does the CLT actually say?
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/14186/discussion-between-glen-b-and-user1275515)
Answer: Thank you for the support and advice Glen & JSK.
I'm managed to work out the answer which I thought I share with everyone (and also get some pointers if I had any steps wrong despite getting to the right answer).

Normal Distribution CLT Question


Using a real number X calculate quadratic equation using only addition, multiplication and subtraction

Question: As I understand, that I cant use discriminant in here, but how to solve then?

Given a real number X. Without the use of any other actions besides addition, multiplication and subtraction calculate:
  $5x^4$+$2x^3$-$8x$-$1$
Comment: @EverWondeR If this is the exact wording, it's no wonder you can't solve it. It is not a valid statement of a question.
Comment: I don't get it: calculate *what*?! There is no equation there, only a polynomial...
Comment: "calculate this polynomial" does not make much sense... do you mean you want to find the solutions to $5x^4+2x^3-8x-1=0$? The discriminant uses only multiplication, and subtraction so I don't see how it's ruled out... but I also don't see how that would help you solve the equation...
Comment: its not ruled out, it's just I get the impression of that, because thers no =0 at the end so im kinda confused..
Comment: I removed the quadratic equation tag because it looks like it was mistakenly applied to a 4th degree polynomial.
Comment: That's not a quadratic equation, it is a polynomial, and it is not a quadratic polynomial.
Comment: If we were actually given a specific number, then we could calculate $5x^4+2x^3-8x-1$ using addition, multiplication and substraction, but it's a pretty trivial problem.
Comment: @EverWondeR A polynomial of degree 4 is called a *quartic* polynomial.
Answer: One of the common ways to evaluate such polynomials is to write it as:
$$((5\cdot x+2)\cdot x\cdot x - 8)\cdot x - 1$$
This trick is used because it minimizes the number of multiplications.
Compare that to a more straight-forward approach: pre-calculating $y=x\cdot x$ then writing the polynomial as:
$$5\cdot y\cdot y +2\cdot y\cdot x -8\cdot x -1$$
That takes six multiplications (including calculating $y$,) compared to a mere $4$ multiplications in my original formula.
Comment: Hah ... neat aspect!
Comment: Thank you! Simple and clear!
Comment: A general polynomial $\sum_{i=0}^n a_ix^i$ in this way can be computed in $n$ multiplications and $n$ additions or subtractions. (Here, since one of the ceoffieients is zero, we have fewer additions.)
Answer: If the goal is to find the roots of the polynomial, then it won't be possible to do with only arithmetic operations: the solutions include square roots and cube roots.
Answer: Do you just want something like $-1 + x(-8 + x(x(2 + x(5))))$?
Answer: As written, you just multiply $x$ together four times, multiply that by 5, multiply $x$ together three times, multiply that by $2$, add to the previous, and so on
More efficiently you could do $x(x\cdot x(5x+2)-8)-1$


Probability Normal Approximation

Question: I am trying to understand this example for normal approximations:
In a particular faculty 60% of students are men and 40% are women. In a random sample of 50 students what is the probability that more than half are women?
Let the random variable $X$ be the number of women in the sample.
Assume $X$ has the binomial distribution with $n = 50$ and $p = 0.4$.
Then $E(X)=np=50\times 0.4=20$
$\operatorname{var}(X) = npq = 50 \times 0.4 \times 0.6 = 12$
so approximately $X \sim N(20,12)$.
We need to find $P(X > 25)$. Note - not $P(X >= 25)$.
so
$$
P(X > 25) = P(Z > 1.44)\\
= 1 - P(Z < 1.44)\\
= 1 - 0.9251\\
= 0.075
$$
I don't understand the line near the bottom beginning at $1-P(Z > 1.44)$. Where do you get the value for $P(Z > 1.44)$?
Comment: Traditionally, in the days of A&S, you would look up a table of standard normal values. Now your pocket calculator can handle even the original normal distribution, no questions asked.
Comment: How can i do Z < 1.44?
Comment: Check out this link: http://www.statisticshowto.com/what-is-the-continuity-correction-factor/
Answer: You should be using a continuity correction and finding $$p(X>25.5)$$
So if you are using a table of $z$ values, you will be finding $$1-\Phi(1.59)$$
Or if you have a new calculator with the Normal CD function, you can get a more accurate answer $0.05617559886$

Probability Normal Approximation


Composition of Taylor expansions of trigonometric functions and their inverses.

Question: I was trying to check whether $ arc sin (sin \theta) = \theta$ and $arc cos(cos \theta) = \theta $ is satisfied when I compose Taylor series expansion of these functions, i.e.:

For sine:

$$ x = sin \theta = \theta - \frac{\theta^3}{3!} + \frac{\theta^5}{5!} - ... $$
$$ arc sin x = x + \frac{1}{2 \cdot 3} x^3 + \frac{3}{2 \cdot 4 \cdot 5} x^5 + ... $$

For cosine:

$$ x = cos \theta = 1 - \frac{\theta^2}{2!} + \frac{\theta^4}{4!} - ... $$
$$ arc cos x = \frac{\pi}{2} - (x + \frac{1}{2 \cdot 3} x^3 + \frac{3}{2 \cdot 4 \cdot 5} x^5 + ...) $$
What I wanted to do was to substitute $x$ in the Taylor expansion of an inverse trigonometric function with the Taylor expansion for the respective trigonometric function, group the terms according to the power of $\theta$ and check if everything different than $\theta$ term disappears.
In case of the sine function, I indeed get $\theta = arc sin (sin \theta)$ with this approach. However, in the case of cosine it seems to me that the lowest non-constant term has to be of degree 2. But then it is impossible to get $\theta$ after grouping the terms. Why is this the case? Why does this approach work for sine and does not work for cosine? Am I making a computational mistake in my reasoning or is it somehow connected to the radius of convergence for the series?
Comment: In the arcsin case, $\theta=0$ corresponds to $x=0$, so what you did worked.  But in the arccos case, $\theta=0$ corresponds to $x=1$.  So you should expand $\arccos x$ in powers of $(x-1)$, not in powers of $x$.
Comment: @GEdgar Except that $\arccos$ has a branch point at $1$, so you'd need a Puiseux series (and use different branches ...)
Comment: Hmm, maybe to clarify my question a little bit more: it seems to me that if I take the formula for $cos\theta$ and input there a number, let's say $\theta  = \frac{\pi}{4}$ I will get a number (in this case $\frac{1}{\sqrt{2}}$). If I take the number I got and input it to the second formula, I will get $\frac{\pi}{4}$ again, right? If it's true, then why it doesn't work for the general formula?
Answer: $\cos$ is an even function, so $g(\cos(x))$ is an even function for any function $g$.  That is, $\cos(-x) = \cos(x)$, so $g(\cos(-x)) = g(\cos(x))$. Thus it is impossible to have $g(\cos(x)) = x$ in a neighbourhood of $0$.
Answer: Here is the Puiseux series as mentioned by Robert:
$$
\arccos(x) = \sqrt{2}(1-x)^{1/2}+\frac{\sqrt{2}}{12}(1-x)^{3/2}
+\frac{3\sqrt{2}}{5\cdot 2^5}(1-x)^{5/2} + \frac{5\sqrt{2}}{7\cdot 2^7}(1-x)^{7/2} +\frac{35\sqrt{2}}{9\cdot 2^{11}}(1-x)^{9/2}
+ \dots
\tag1$$
for $-1 < x \le 1$.  If we plug
$$
x = 1 - \frac{\theta^2}{2!} + \frac{\theta^4}{4!} - ...
\tag2$$
into $(1)$, we should get $\theta$.  At least for $0 \le \theta \le \pi/2$.
Comment: Yes, and with $-\sqrt{2}(1-x)^{1/2} - \frac{\sqrt{2}}{12} (1-x)^{3/2} - \ldots$ we get $\theta$ for $-\pi/2 \le \theta \le 0$.


Limit of function composition $\lim_{x \to 0}\ln(1+x)^{\frac{1}{x}} = \ln [\lim_{x \to 0}(1+x)^{\frac{1}{x}}]$

Question: $$\lim_{x \to 0}\ln(1+x)^{\frac{1}{x}} = \ln [\lim_{x \to 0}(1+x)^{\frac{1}{x}}]$$
While attempting to understand the approximation of $e$, I ended up at the above step where the RHS is derived from the following theorem.
If $f$ is continuous at $c$ and  $\lim_{x\rightarrow b} g=c$,  we have $\lim_{x\rightarrow b} f\circ g= f( \lim_{x\rightarrow b} g)$.
Here, $f= \ln x$,  $g=(1+x)^{\frac{1}{x}}$ and $b=0$. As $x\rightarrow b$, $g\rightarrow 1^\infty$. I have read online that one raised to the power of Infinity( and not undefined as $x\neq b$ ) is indeterminate. If that is true, $\ln$ cannot be continuous at $c$( indeterminate ). How can we then take the limit as shown in the picture?

Does, "If $f$ is continuous at $c$ and  $\lim_{x\rightarrow b} g=c$,  we have $\lim_{x\rightarrow b} f\circ g= f( \lim_{x\rightarrow b} g)$" hold if $f$ is not continuous at $c$ but its limit is c?
I believe it does as per the formal definition of the limit.
Comment: In your example chosen as $x\to b$ the function $g(x) \to e$ and not to $1^{\infty}$ and log is continuous at $e$. In general if $g$ is positive as $x\to a$ then $\log\lim_{x\to a} g(x) =\lim_{x\to a} \log g(x) $ irrespective of the fact whether $\lim_{x\to a} g(x) $ exists or not. There is a particular caveat here. In general the limit operation always commutes with the action of a continuous function.
Comment: When $f$ is not continuous then you have the following theorem: if $g(x) \to c$ as $x\to b$ and $g(x) \neq c$ as $x\to b$ then $\lim_{x\to b} f(g(x)) $ has same behavior as that of $\lim_{x\to c} f(x) $. Here we don't assume anything about continuity of $f$ or $ g$.
Comment: Below, I have tried to arrive at the result by making an assumption. I'm hoping to know if that is acceptable or not.
Comment: Can  anything be said about the second part of the question?
Comment: This makes me confident.
Answer: This is a very common confusion. Here's the thing: "indeterminate" does NOT mean "undefined" (or "does not exist"). Roughly speaking, we say that a limit is an indeterminate form if from the parts of the expression we can't automatically deduce the value of the limit. For example:

$\frac{6}{3}$ is not an indeterminate form, because it's definitely equal to $2$. This means that if you have a limit $\lim\limits_{x\to a}\frac{f(x)}{g(x)}$, where $\lim\limits_{x\to a}f(x)=6$ and $\lim\limits_{x\to a}g(x)=3$, then you can for sure conclude that $\lim\limits_{x\to a}\frac{f(x)}{g(x)}=2$.
But $\frac{0}{0}$ is an indeterminate form. This means that if you have a limit $\lim\limits_{x\to a}\frac{f(x)}{g(x)}$, where $\lim\limits_{x\to a}f(x)=0$ and $\lim\limits_{x\to a}g(x)=0$, then the result can be different depending on the specific functions $f$ and $g$. Note that I did NOT say "undefined"! Such a limit may turn out to be undefined, or to be equal to any real number, or to be infinite. For example:
$$\lim\limits_{x\to0}\frac{x^2}{x^4}=+\infty, \quad \lim\limits_{x\to0}\frac{x^2}{x^2}=1, \quad \lim\limits_{x\to0}\frac{x^4}{x^2}=0, \quad \lim\limits_{x\to0}\frac{18x^2}{2x^2}=9, \quad \text{etc,}$$
where all these limits, if you first look at their numerators and denominators separately, are of the form $\frac{0}{0}$.

Another way to rephrase this: calling a limit "indeterminate" is NOT the answer! It only means that we can't deduce the answer by (roughly speaking) basic observation. At this point the answer is still unknown to us; so we have to do some more work, possibly using more advanced techniques, to find the limit (or demonstrate that it doesn't exist).
As you correctly pointed out, $1^{\infty}$ is an indeterminate form. But you misinterpreted what that means. It only means that we don't know yet the answer to this particular limit (as opposed to seeing something like $2^3$, when we'd immediately conclude that the answer is $8$). We still have no idea whether $c$ exists or not! For this reason, we don't know yet whether the theorem applies here or not.
So we have to do some more work to find the inside limit $\lim\limits_{x\to0}(1+x)^{1/x}$. One way or another — (insert some solution here) — we can find that actually $\lim\limits_{x\to0}(1+x)^{1/x}=e$. So our $c=e$, and since $f(x)=\ln x$ is continuous at $c=e$, now we know that the theorem is perfectly applicable here.
Comment: The term indeterminate makes good sense to me now. I think I can now do it the following way. Let's assume that $f$ is continuous at $c$, and that the limit of $g$ exists at $x=0$ and is $c$. We know that $f'(1)$ is 1. The first principle of differentiation gets us to $\lim_{x\rightarrow 0}  f(g) =1$, where $f$ and $g$ are functions defined above. The theorem now tells us that $f(\lim_{x\rightarrow 0} g)=1$. It is reasonable to state that $\lim_{x\rightarrow 0} g=e$, as per the definition of the natural logarithm.
Comment: To confirm our assumption, we look at $e$. $f$ is indeed continuous at $e$, as per the definition of natural logarithm. Does this complete the proof?
Answer: Note that
$$\ln[(1+x)^{1/x}]=\frac{\ln(1+x)}x.$$
One really shouldn't apply L'Hospital's rule to this, but what happens if one does?
Comment: I haven't arrived at L'Hospital's rule yet. I cannot discuss this.
Comment: Could you draw the graphs of $y=\ln(1+x)$ and $y=x$ then, and see how they compare?
Comment: I can say that you have shifted $\ln$ one unit to the left. Both graphs pass through the origin.
Comment: Could you comment on my lines, "I have read online that one raised to the power of Infinity( and not undefined as $x\neq b$ ) is indeterminate. If that is true, $\ln$ cannot be continuous at $c$( indeterminate )"? I believe here is where my problem lies.


If $x$ and $y$ are asymptotically equal then $x(n)=y(n)+o(y(n))$.

Question: Show that
$x(n)\sim y(n)$ iff $x(n)=y(n)+o(y(n))$, where ' o ' here is "small o".
I used the following that I found from online source to prove it
$x(n)=y(n)(1+o(1))$, but I need to show it using definitions.
Can someone help me with this using definitions instead of my approach?
Comment: It should be $x(n)=y(n)+o(y(n))$.
Comment: @Gary oh right thanks for pointing that out
Answer: Suppose that $x(n)/y(n)$ is well defined for all sufficiently large values of $n$. Write $x(n) =y(n)+\varepsilon(n)$. Then
$$
x(n) \sim y(n) \Leftrightarrow \frac{{x(n)}}{{y(n)}} \to 1 \Leftrightarrow \frac{{y(n) + \varepsilon (n)}}{{y(n)}} \to 1 \\ \Leftrightarrow 1 + \frac{{\varepsilon (n)}}{{y(n)}} \to 1 \Leftrightarrow \frac{{\varepsilon (n)}}{{y(n)}} \to 0 \Leftrightarrow \varepsilon (n) = o(y(n)).
$$


Biased prediction (overestimation) for xgboost

Question: I run xgboost and elastic-net on the same dataset for a classification problem, say we have
y_train, y_test
y_train_xgboost_prediction, y_test_xgboost_prediction
y_train_elastic_net_prediction, y_test_elastic_net_prediction

I find xgboost gives prediction with mean a lot higher than actual label,
which is
average(y_train_xgboost_prediction) > average(y_train)
average(y_test_xgboost_prediction) > average(y_test)

While elastic-net gives prediction with average similar to average of actual label, which is
average(y_train_elastic_net_prediction) ~= average(y_train)
average(y_test_elastic_net_prediction) ~= average(y_test)

Actually xgboost has AUC higher than elastic-net, which model should we prefer in this case? How do we fix the bias in xgboost prediction?
Comment: Good question. Boosting methods usual do not give well calibrated probabilistic predictions (e.g. see Niculescu-Mizil & Caruana). That said, they can be calibrated on a follow up step (e.g. through isotonic regression). Choice of the model depends on what you want to do with it/use its estimates. Do we care more about the order or the marginal probabilities of our estimates? (Probably I should write this as an answer at some point.)
Comment: @usεr11852 - You should post that as an answer!
Comment: @jbowman: Done.
Comment: What objective did you use?
Comment: I used AUC at first. But I also want to keep the original scale of probability prediction. So I'm thinking to do some post-processing based on xgboost prediction.
Comment: XGBoost does not offer AUC as objective/loss. AUC is just an evaluation metric. Did you use "binary:logistic" as objective?
Comment: Yes, "binary:logistic" as objective and AUC as evaluation metric
Answer: What is described is not very surprising.
Boosting methods usually do not give well calibrated probabilistic predictions (e.g. see
Caruana et al. (2004) "Ensemble Selection from Libraries of Models",
Niculescu-Mizil & Caruana (2005) "Predicting good probabilities with supervised learning"). GLM-based methods provide more consistent marginal probabilities as they have a direct probabilistic connection.
That said, probabilistic estimates can be calibrated on a follow up step (e.g. through isotonic regression or beta calibration). Please note that these methods are usually applied on a separate hold-out sample. Check the paper from Kull et al. (2017) "Beta calibration: a well-founded and easily implemented improvement on logistic calibration for binary classifiers" irrespective of using beta calibration or not, it gives a very nice modern exposition of the matter.
The choice of the model depends on what we want to do with it/use its estimates. Do we care more about the order or the marginal probabilities of our estimates? If, for example, we care about the "fairness" of our prediction, the marginal estimates are more important. On the other hand, if we want to pick the "top X more probable" items for a particular treatment, AUC are more important. Probability calibration techniques try to bridge that gap to certain extent.


asp.net Web Reference build error

Question: Anyone knows what causes the following error?
<code>
The type or namespace name 'ObservableCollection' does not exist in the namespace 'System.Collections.ObjectModel' (are you missing an assembly reference?) c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\myweb\ea5ddc82\99690bad\App_WebReferences.7f8qgamu.0.cs
</code>
It turned out the there was a conflict with my IIS Virtual Directory.
So what I did was remove the application in my IIS.
Comment: This seem to be runtime error, right? Do you also get any warning during compilation?
Answer: You need to reference the correct assembly in your project that uses the ObservableCllection. In the case of ObservableCollection this dll was changed from .Net 3.5 to .Net 4.
Prior to .NET 4, ObservableCollection was in WindowsBase.dll and since .Net 4 it is in System.dll. So I guess it depends on the framework version you compile against.
Comment: I already added the reference to System.dll but the error is still there.. I also noticed that when I open the App_WebReference temp files, the System.Collections.ObjectModel.ObservableCollection does not highlight as normal reserved words

asp.net Web Reference build error


Do we need to have MLR (in same direction) for whole parameter space?

Question: Suppose $X$ is a single observation from a pdf, and I want to test some hypothesis: $H_0:\Theta=\Theta_0$ vs. $H_1:\Theta=\Theta_0^c$.
I want to check whether there exists a UMP level $\alpha$ test for testing these hypotheses.
Now, one of the approaches is definitely to use the concept of MLR, if it exists. But here, I have a doubt.
If I fix $\theta_1<\theta_2$ then the likelihood ratio is INCREASING.
If I fix $\theta_3<\theta_4$ then the likelihood ratio is DECREASING.
Here, $\theta_i$ are all distinct.
Can I still say that the family of pdf has MLR in $X$?
Comment: What does MLR mean?
Answer: No, you cannot.
In order for a random variable $t$ with pdf $g(t|\theta)$ to have a MLR, it must be true that for every $\theta_j > \theta_i$, then $\frac{g(t|\theta_j)}{g(t|\theta_i)}$ is either nonincreasing or nondecreasing.
In your case, where $\theta_1<\theta_2$, your LR is increasing, so it is not nonincreasing.  In your case, where $\theta_3<\theta_4$, your LR is decreasing, so it is not nondecreasing.  Thus, your LR is neither nonincreasing nor nondecreasing for all $\theta_j > \theta_i.$  Since it is neither nonincreasing nor nondecreasing, you cannot say that your family of pdfs has MLR.
Hope this helps!


How can I run code in parallel to p5js draw loop?

Question: I'm trying to run a flocking simulation like this one from the coding train.
I was thinking I might be able to speed things up by running my code in a separate asynchronous loop in parallel to the p5 draw loop. My simulation code could update the positions of the boids and the p5 code could draw the boids. That way, the draw loop wouldn't have to be slowed down by the simulation code and my code wouldn't have to be slowed down by the drawing.
A) Do you think that would actually speed up the simulation or at least allow p5 to draw at a higher frame rate? and B) How would you run the two in parallel?
Thanks for your help!
Answer:
Do you think that would actually speed up the simulation?

That depends on, if the simulation code is very expensive the probably yes.

How would you run the two in parallel?

Use an asynchronous function with an endless loop. e.g:
function setup() {
    // ...
    simulationLoop();
}

function draw() {
    // ...
}

async function simulationLoop() {

    while (true) {
        // calculate simulation

        await sleep(1);
    }
}

function sleep(ms) {
    return new Promise(resolve => {setTimeout(() => { resolve(true); }, 1); });
}

See How to "pause" during merge sort to visualize JS p5js where this technique is used to visualize the merge sort algorithm.
It is even possibly to create a loop with a fixed frequency by the use of setTimeout. e.g.:

var count = 0;

function setup() {
    createCanvas(500, 200);
    simulationLoop();
}

function draw() {
    background(0);
    stroke(0);
    fill(255);
    textSize(50);
    text(str(count), 10, 60);
}

async function simulationLoop() {

    while (true) {
        await new Promise(resolve => {
            setTimeout(() => {
                resolve(true);
                simulation();
            }, 1000);
        });
    }
}

function simulation() {
    count ++;
}

Another simple option is to use requestAnimationFrame():

var count = 0;

function setup() {
    createCanvas(500, 250);
    requestAnimationFrame(simulation);
}

function draw() {
    background(0);
    stroke(0);
    fill(255);
    textSize(50);
    text(str(count), 10, 60);
}

function simulation(deltaTime) {

    count = Math.trunc(deltaTime / 1000);

    requestAnimationFrame(simulation);
}


R adicionar uma coluna

Question: Exemplo básico de uma página tutorial
Exemplo
Temos
library(tidyverse)

##mpg

ggplot(mpg, aes(displ, hwy)) +
  geom_point(aes(color = class)) +
  geom_smooth(se = FALSE) +
  labs(title = "Fuel efficiency generally decreases with engine size")

Gera o gráfico
Nesta base temos duas colunas: cty e hwy
que representam o consumo na cidade e na estrada,
respectivamente.
manufacturer model      displ  year   cyl trans      drv     cty   hwy fl    class
   <chr>        <chr>      <dbl> <int> <int> <chr>      <chr> <int> <int> <chr> <chr>
 1 audi         a4           1.8  1999     4 auto(l5)   f        18    29 p     comp~
 2 audi         a4           1.8  1999     4 manual(m5) f        21    29 p     comp~

Tentei criar uma coluna da média , (cty+hwy)/2 e chamei de avgc para fugir de palavra reservada.
mpg %>% mutate(avgc = round((cty+hwy)/2))

   manufacturer model     displ  year   cyl trans drv     cty   hwy fl    class  avgc
   <chr>        <chr>     <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr> <dbl>
 1 audi         a4          1.8  1999     4 auto~ f        18    29 p     comp~    24
 2 audi         a4          1.8  1999     4 manu~ f        21    29 p     comp~    25

gera , mas não "persiste" pois se tento
ggplot(mpg, aes(displ, avgc)) +
  geom_point(aes(color = class)) +
  geom_smooth(se = FALSE) +
  labs(title = "Fuel efficiency generally decreases with engine size")

ocorre o seguinte erro
Error in FUN(X[[i]], ...) : objeto 'avgc' não encontrado

Pergunto :

O campo ficou como dbl , é isto ? Como se converte para int ?

Que erro cometi ? Pois pelo Help e Doc que achei parece estar certo

Obs , Analista de Sistema se aventurando no R Studio.
Answer: É porque você gerou a variável "avgc" mas não atribuiu ao objeto.
Observe que você digitou mpg %>% mutate(avgc = round((cty+hwy)/2))
Para ter salvo a nova coluna no dataset, precisaria usar o operador de atribuição OBJETO <- mpg %>% mutate(avgc = round((cty+hwy)/2)).
No exemplo abaixo, salvo a nova coluna no objeto "mpg2", para não alterar o objeto "mpg" original:
mpg2 <-  mpg %>% mutate(avgc = round((cty+hwy)/2))

Em seguida, replico o seu código, alterando apenas o dataset para "mpg2":
ggplot(mpg2, aes(displ, avgc)) +
  geom_point(aes(color = class)) +
  geom_smooth(se = FALSE) +
  labs(title = "Fuel efficiency generally decreases with engine size")

Resultado:
Comment: Erro bobo , valeu.

R adicionar uma coluna


Single query or stored procedure to fetch data

Question: I have created three tables
Here I would like to fetch all question_tags and answers related to a perticular question(id).
for that needed Single query or stored procedure
create table questions(id varchar(100),title varchar(140),body varchar(2000),
primary key(id));

create table question_tags(id varchar(50),tag_name varchar(50),question_id varchar(100),
primary key(id),foreign key(question_id) references questions(id));

create table answers(id varchar(50),answer varchar(2000),question_id varchar(100),
primary key(id),foreign key(question_id) references questions(id));

and following data in table
     mysql> select * from questions;
     +----+-------+-------------+
     | id | title | body        |
     +----+-------+-------------+
     | 1  | a     | hello       |
     | 2  | b     | hii         |
     | 3  | c     | bye         |
     | 4  | d     | how are you |
     +----+-------+-------------+
     4 rows in set (0.03 sec)

     mysql> select * from question_tags
     +----+----------+-------------+
     | id | tag_name | question_id |
     +----+----------+-------------+
     | t1 | java     | 1           |
     | t2 | mysql    | 1           |
     | t3 | jquery   | 1           |
     +----+----------+-------------+
     3 rows in set (0.00 sec)

     mysql> select * from answers;
     +----+-----------+-------------+
     | id | answer    | question_id |
     +----+-----------+-------------+
     | a1 | good      | 1           |
     | a2 | excellent | 1           |
     | a3 | ok        | 1           |
     +----+-----------+-------------+
     3 rows in set (0.00 sec)

Comment: So what is stopping you? What have you tried? Where is the question?
Comment: I dont know how to fetch multiple rows from different tables
Comment: Specifically, read about "outer joins".
Answer: I think you search for the JOIN [ON] Statement. For your Tablelayout it should be something like this:
SELECT `question_tags`.*, `answers`.*
FROM `questions`
   JOIN  `answers`
        ON `questions`.`id` = `answers`.`question_id`
   JOIN `question_tags`
        ON `questions`.`id` = `question_tags`.`question_id`
WHERE `questions`.`id` = {YOUR_ID}

Or only Question-Id, Answers, Tags:
SELECT `questions`.`id` AS `question_id`,
         `question_tags`.`tag_name`,
         `answers`.`answer`
FROM `questions`
   JOIN  `answers`
        ON `questions`.`id` = `answers`.`question_id`
   JOIN `question_tags`
        ON `questions`.`id` = `question_tags`.`question_id`
WHERE `questions`.`id` = 0

EDIT:
And for everything in one Row:
SELECT  `questions`.`id` AS  `question_id` ,
(
    SELECT GROUP_CONCAT(  `question_tags`.`tag_name` SEPARATOR ';')
    FROM  `question_tags`
    WHERE  `question_id` =0
) AS  `Tags` ,
(
    SELECT GROUP_CONCAT(  `answers`.`answer` SEPARATOR ';' )
    FROM  `answers`
    WHERE  `question_id` =0
) AS  `Answers`
FROM  `questions`
WHERE  `questions`.`id` =0

Please keep in mind that this isn't the best way for doing this. I can't provide you a Stored Procedure since i'm unfamiliar with SP in MySQL.
In my Opinion there is no way to select/return/display your desired format as a Table.
Comment: Thanks for your answer. how to do this with stored procedure so repeated data can be removed
Comment: THanks for your reply. This was me desired output
Answer: The query is:
select * from questions join question_tags on (questions.id = question_tags.question_id) join answers on (questions.id=answers.question_id);

Here is a fiddle; it greatly helps us assit you if you provide one with your question.
Please read about mySQL naming conventions (tables in signular) and about keyreferences (I have changed yours to integers but you can also auto_increment etc).


Pyomo time-dependant model?

Question: I'm quite new to pyomo but I'm having a hard time figuring how to create a time dependant model and plot it on a graph. By time dependant I mean just a variable that assumes different values for each time step (like from 1 to T in this case).
I used this very simple model but when I run the script I receive in output only one solution. How can I change that?
I also have errors related to the constraint function but I'm not sure what's wrong
(ValueError: Constraint 'constraint[1]' does not have a proper value. Found . at 0x7f202b540850>' Expecting a tuple or equation.)
I'd like to show how the value of x(t) varies in all timesteps.
Any help is appreciated.
from __future__ import division
from pyomo.environ import *
from pyomo.opt import SolverFactory
import sys

model = AbstractModel()
model.n = Param()
model.T = RangeSet(1, model.n)
model.a = Param(model.T)
model.b = Param(model.T)

model.x = Var(model.T, domain= NonNegativeReals)

data = DataPortal()
data.load(filename='N.csv', range='N', param=model.n)
data.load(filename='A.csv', range= 'A', param=model.a)
data.load(filename='B.csv', range= 'B', param=model.b)

def objective(model):
    return model.x

model.OBJ = Objective(rule=objective)

def somma(model):
    return model.a[t]*model.x[t] for t in model.T) >= model.b[t] for t in model.T

model.constraint = Constraint(model.T, rule=somma)

instance = model.create_instance(data)
opt = SolverFactory('glpk')
results = opt.solve(instance)

Answer: You can build up lists of the values you would like to plot like this:
T_plot = list(instance.T)
x_plot = [value(instance.x[t]) for t in T_plot]

and then use your favorite Python plotting package to make the plots. I usually use Matplotlib.

Pyomo time-dependant model?


Calcular diferença entre datas em Horas no R

Question: Tenho duas datas em formato data e hora.
Data1 <- 20/01/2018 20:33:58
Data2 <- 21/01/2018 20:23:48

A diferença, em horas, é de 23:49:50. Como é feito o cálculo desta diferença no R?
Além disso, preciso saber se esta diferença acima tem mais ou menos de 24 horas. Como faço para fazer esta verificação?
Answer: Você pode usar a função difftime, mas lembre-se que a datas devem estar em formato em Date-Time ou Date.
Para transformar character em Date-Time:
  Data1 <- "20/01/2018 20:33:58"
  Data2 <- "21/01/2018 20:23:48"

  # Converter
  Data1 <- strptime(Data1, "%d/%m/%Y %H:%M:%S")
  Data2 <- strptime(Data2, "%d/%m/%Y %H:%M:%S")

  class(Data1)
  > [1] "POSIXct" "POSIXt"

Calcular a diferença:
  difer <- difftime(Data2, Data1, units = 'hour')
  > Time difference of 23.99722 hours

Não sei o contexto que você quer utilizar, mas você pode usar um if else para saber se a diferença é maior ou menor que 24h.
  if(difer[[1]] > 24) {
    "fazer algo se mais que 24"
  }else{
    "fazer algo se menos que 24h"
  }

Comment: Meus campos estão em formato "character" e não estou conseguindo fazer a sua sugestão. Como converter caracter para data e hora(datetime)?
Comment: @BrunoAvila editei a resposta explicando como converter de `character` para `Date-Time`.


Complex Integration using Cauchy's Theorem

Question: The problem is the integration of
$$I=\int_{\left\lvert z-1\right\rvert=1} f(z) dz$$
where
$$f(z)=\frac{1}{z^3-1}$$
and the path goes $1$ loop in positive direction.
I tried to solve the problem using Cauchy's Theorem by finding $z$ that makes $f(z)$ denominator be $0$. That was $z=1$.
And I got struck.
I think the integral is needed to be treat somehow so that
$$\int_{C_a}\frac{1}{(z-\alpha)^n}dz = 2{\pi}i \text{ when } n=1$$
can be used.
My question is how should I continue with the integral?
Answer: Hint: From $z^3-1=(z-1)(z^2+z+1)$ look at the following function $g(z)=\frac{1}{z^2+z+1}$. Then from Cauchy's integral formula, since $1 \in \{ z : | z − 1| < 1\}$
$$g(1)=\frac{1}{2\pi i}\int_{|z−1|=1} \frac{g(z)}{z-1}dz=\frac{1}{2\pi i}\int_{|z−1|=1} \frac{1}{z^3-1}dz$$
Comment: The function $g(z)=\frac{1}{z^2+z+1}$ has poles at $-\frac12 \pm i\frac{\sqrt 3}{2}$.  Is either or both enclosed by $|z-1|=1$?  You might consider stating something about the analyticity, or lack thereof, of $g$ on $|z-1|\le 1$..
Comment: True, one in quadrant 2 and one in quadrant 3, both outside of $|z−1|\leq 1$, but my answer is only a hint.
Answer: The only pole of $f(z)$ on the circle is $z=1$
According to residue theorem
$$\oint _{\gamma }f(z)\,dz=2\pi i \operatorname {Res} (f,1)$$
And we have $\operatorname {Res} (f,1)=\lim_{z\to 1} \, \dfrac{z-1}{z^3-1}=\lim_{z\to 1} \, \dfrac{1}{z^2+z+1}=\dfrac{1}{3}$
Thus $\oint _{\gamma }f(z)\,dz=\dfrac{2 i \pi }{3}$
Hope this helps
Answer: Note:  The hint of @rtybase is essentially the answer to OPs question. Let's recall Cauchy's Integralformula:
If $a$ is in the interior  of $\gamma=\{z:|z-1|=1\}$ and a function $g$ is holomorphic in a region which contains the closure of the interior of $\gamma$, then
\begin{align*}
g(a)=\frac{1}{2\pi i}\oint_{\gamma} \frac{g(z)}{z-a}\,dz
\end{align*}

We have the following situation:
The function $f(z)=\frac{1}{z^3-1}$ has three simple poles at $z_0=1$ and  $z_{1,2}=-\frac{1}{2}\pm i\frac{\sqrt{3}}{2}$. The pole $z_0=1$ is in   the interior of $\gamma$. We can write $f(z)$ as
  \begin{align*}
f(z)=\frac{1}{z^3-1}=\frac{1}{(z-1)(z^2+z+1)}
\end{align*}
  and observe: Since $g(z)=\frac{1}{z^2+z+1}$ is holomorph in the interior  of  $\gamma$ we obtain
  \begin{align*}
g(1)&=\frac{1}{2\pi i}\oint_{\gamma} \frac{g(z)}{z-1}\,dz\\
&=\frac{1}{2\pi i}\oint_{\gamma} \frac{1}{(z-1)(z^2+z+1)}\,dz\\
&=\frac{1}{2\pi i}\oint_{\gamma} f(z)\,dz\\
\end{align*}
We finally conclude
  \begin{align*}
\oint_{\gamma} f(z)\,dz=2\pi i\, g(1)=\frac{2\pi i}{3}
\end{align*}
Answer: Determine which roots of the denominator are contained within the given curve $|z - 1| = 1$, find the residues at those roots, and calculate using the Residue Theorem.


Am I using `button.disabled = true;` incorrectly?

Question: I'm trying to build an interaction in Animate CC that plays movie clips, and the buttons disappear after they are clicked.
I'm trying to disable the other buttons temporarily while the movie clip plays over the main background, but it's not playing nice.
A code Snippet of the click handler:
exportRoot.btn_cook.addEventListener("click", cook_clickHandler.bind(this));
function cook_clickHandler(){
    exportRoot.cook.gotoAndPlay(1); //play the info clip
    exportRoot.btn_cook.visible = false; //hide button for no replays
    disableAll();
}

disableAll(); does the following for each button on the canvas:
if(exportRoot.btn_receive.visible == true){
    exportRoot.btn_receive.disabled = true;
}

I'm having some trouble trying to figure out how to use this properly. When I run through the interaction, I am still able to click on the buttons, even though I supposedly disabled them?
This demo won't load sound on GitHub, but it works otherwise. Click here to see it.
Comment: Poking at the URL (you must provide a [mcve] in the question itself!) it looks like your buttons are not buttons, so the `disabled` property is meaningless.
Comment: I can't reproduce the problem with this simplified example: http://jsbin.com/wezenom/1/edit?html,js,output
Comment: @Quentin it's a large file, and there's supposed to be a few seconds of audio at the beginning, so the buttons are there, they just don't come on the screen for a little bit :) sorry about that. I should have mentioned. I'm not sure why the error is happening. It could be due to it being animate cc. For whatever reason, when I play a movieclip over the buttons, it still lets you click the buttons.
Comment: also, maybe try an image button? these are classified as a button on animate cc, and they have an up state, down state, and over state... so, wouldn't they be buttons?
Answer: I had the same problem so I have another way to do it:
You can try to remove the eventListener click, like this:
if(!exportRoot.btn_receive.hasEventListener("click")){
    exportRoot.btn_receive.removeEventListener("click", cook_clickHandler);
}

When u want this to be enabled again, add the eventListener.
Comment: This seems to be the best solution, because I can't actually find a disabled property in the easeljs documentation. I think I initially used it because javascript does have disabled? thanks
Answer: The disabled attribute is a Boolean attribute. That means that just the presence of it is enough to cause the element to become disabled. It makes no difference what you set the value to. You need to remove the attribute from the element to remove the disabled effect.
Removing the event listener treats the symptom, it doesn't get to the heart of the issue.
Also (FYI), the visibility property gets values of "visible" or "hidden", not true or false.
Here is a simple example of how to apply and disable (no pun intended) the disabled attribute:

btnToggle.addEventListener("click", function(){

  var elems = document.querySelectorAll(".disableEnable");

  // Loop through each element in the class
  elems.forEach(function(element){

    // Check to see if the first element has the disabled attribute
    // the value of the attribute doesn't matter. If the attribute
    // is present, the element is currently disabled.
    if(element.getAttribute("disabled")){

      // Element is disabled, so enabled it by removing
      // the attribute (not by setting a value)
      element.removeAttribute("disabled");
    } else {
      // Element is enabled, so disable it by adding the disabled
      // attribute. Again, the value doesn't matter, but convention
      // says that we set a value of "disabled" to convey that it is
      // a boolean attribute.
      element.setAttribute("disabled", "disabled");
    }

  });

});
<button id="btnToggle">Disable / Enable</button>

<button class="disableEnable">Test Button</button>
<input class="disableEnable">
<input type="text" class="disableEnable">
Comment: Would this still work in animate-cc though? that uses a create-js api, which  seems different from regular javascript. I got the visibility bit from the documentation, here http://createjs.com/docs/easeljs/classes/Bitmap.html#property_visible


O que é Classe AsyncPostBackTrigger?

Question: Como devo usar e o que faz esse tipo de classe?
Answer: Define um controle e um evento opcional do controle como um gatilho de controle de postback assíncrono que faz o controle UpdatePanel ser atualizado. Referencia Microsoft Developer Network - Classe AsyncPostBackTrigger.
Basicamente, quando se utiliza UpdatePanel, os controles contido nele tem suas informações atualizadas sem dar um refresh na página, mas, existe uma técnica que ao declarar um AsyncPostBackTrigger de algum controle fora do UpdatePanel faça esse controle ter o mesmo comportamento dos que estão dentro do UpdatePanel.
Um exemplo seria a declaração dessa forma:
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <asp:Button ID="BtnDateTimeNowUpdate"
                runat="server"
                Text="Atualizar"
                OnClick="BtnDateTimeNowUpdate_Click" />

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="BtnDateTimeNowUpdate" />
            </Triggers>
            <ContentTemplate>
                <asp:Label ID="LblDateTimeNow" runat="server" Text=""></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>

</form>

nesse simples código, observe que o botão BtnDateTimeNowUpdate está fora do UpdatePanel, mas, tem o mesmo comportamento de como se estivesse dentro dele pela simples configuração presente no UpdatePanel:
<Triggers>
    <asp:AsyncPostBackTrigger ControlID="BtnDateTimeNowUpdate" />
</Triggers>

se essa configuração não estivesse assim, esse botão daria um refresh na página inteira que é o comportamento normal para WebForm.
Pode ser utilizado, quando um controle fora do UpdatePanel, tenha que interagir com os controles dentro do UpdatePanel.
Referencias

Classe AsyncPostBackTrigger
Introdução ao Controle UpdatePanel
ASP .NET - Criando seu primeiro Web Forms

O que é Classe AsyncPostBackTrigger?


Usar a mesma datalist para várias páginas

Question: Estou querendo fazer um sistema onde eu iria ter uma datalist com todos os meus options e em todas as páginas do meu site seria espelhado. Exemplo:
<input type="text" name="tCid" id="cCid" placeholder="Insira uma opção" list="cEst" />
<datalist id="cEst">
    <optgroup label="Séries Ativas">
        <option disabled>Opcao1</option>
        <option disabled>Opcao2</option>
        <option value="Opcao3">Opcao3</option>
        <option disabled>opcao4</option>
        <option disabled>Opcao5</option>
    </optgroup>
</datalist>

Nesse caso, vai ter um input para o usuário escrever uma opção e o selecionar. Só que eu quero que essa datalist seja única pra todas as páginas do meu site. Ou seja, quando eu tirar o disabled da Opcao1 e colocar value="Opcao1", ele deverá atualizar de todas as páginas do meu site que tenha essa tag datalist.
Comment: Porque não faz ela em um arquivo php?
Comment: Eu prefiro não fazer com php @AndersonHenrique
Comment: Angularjs então?
Comment: Pode ser qualquer JS @AndersonHenrique, mas você tem que me ajudar pois eu não sei como funciona ele.
Answer: Pra quem também quiser saber, fiz da seguinte forma:
Coloquei em um arquivo .txt todas as linhas de código que eu queria espelhar em todas as páginas.
Depois, eu usei o seguinte script para fazer acontecer:

Basicamente, eu fiz o script adicionar todo o arquivo .txt no lugar do código this.value, fazendo o que o PHP faria muito mais fácil, porém não quis fazer com PHP. Espero ter ajudado alguém