db_query not returning expected results - updated

Question: I'm using raw SQL in a custom module (please don't tell me to use the query builder; this is a single static query that will never need to take params.) If I run the query directly in phpMyAdmin, it returns two records. When I run the module, it doesn't display anything.
function speaker_carousel_get_data() {
  error_log("calling get data");
  $query = db_query("SELECT
                    node.title AS node_title,
                    node.nid AS nid,
                    field_speaker_node.title AS field_speaker_node_title,
                    field_speaker_node.nid AS field_speaker_node_nid,
                    'node' AS field_data_field_job_title_node_entity_type,
                    'node' AS field_data_field_company_node_entity_type
                    FROM
                    {node} node
LEFT JOIN {field_data_field_speaker} field_data_field_speaker ON node.nid = field_data_field_speaker.field_speaker_target_id
LEFT JOIN {node} field_speaker_node ON field_data_field_speaker.entity_id = field_speaker_node.nid
WHERE ((node.status = ':status') AND (node.type = ':type') AND (node.title = ':title'))
ORDER BY node_title ASC", array(':status' => '1', ':type' => 'speaker', ':title' => 'April Carlisle'));
  print "
 .print_r($query). "
";
  return $query;
}

I had expected the print_r() to return an array of results, but instead it gives me this:
DatabaseStatementBase Object
(
    [dbh] => DatabaseConnection_mysql Object
        (
            [shutdownRegistered:protected] =>
            [target:protected] => default
            [key:protected] => default
            [logger:protected] =>
            [transactionLayers:protected] => Array
                (
                )

            [driverClasses:protected] => Array
                (
                    [SelectQuery] => SelectQuery
                    [MergeQuery] => MergeQuery
                    [DatabaseTransaction] => DatabaseTransaction
                    [InsertQuery] => InsertQuery_mysql
                    [DeleteQuery] => DeleteQuery
                    [DatabaseSchema] => DatabaseSchema_mysql
                )

            [statementClass:protected] => DatabaseStatementBase
            [transactionSupport:protected] => 1
            [transactionalDDLSupport:protected] =>
            [temporaryNameIndex:protected] => 0
            [connectionOptions:protected] => Array
                (
                    [database] => expo
                    [username] => myuser
                    [password] => mypassword
                    [host] => localhost
                    [port] =>
                    [driver] => mysql
                    [prefix] => Array
                        (
                            [default] =>
                        )

                )

            [schema:protected] => DatabaseSchema_mysql Object
                (
                    [connection:protected] => DatabaseConnection_mysql Object
 *RECURSION*
                    [placeholder:protected] => 0
                    [defaultSchema:protected] => public
                    [uniqueIdentifier:protected] => 4ffc5cb56dca11.89303530
                )

            [prefixes:protected] => Array
                (
                    [default] =>
                )

            [prefixSearch:protected] => Array
                (
                    [0] => {
                    [1] => }
                )

            [prefixReplace:protected] => Array
                (
                    [0] =>
                    [1] =>
                )

        )

    [queryString] => SELECT
                    node.title AS node_title,
                    node.nid AS nid,
                    field_speaker_node.title AS field_speaker_node_title,
                    field_speaker_node.nid AS field_speaker_node_nid,
                    'node' AS field_data_field_job_title_node_entity_type,
                    'node' AS field_data_field_company_node_entity_type
                    FROM
                    node node
LEFT JOIN field_data_field_speaker field_data_field_speaker ON node.nid = field_data_field_speaker.field_speaker_target_id
LEFT JOIN node field_speaker_node ON field_data_field_speaker.entity_id = field_speaker_node.nid
WHERE ((node.status = ':status') AND (node.type = ':type') AND (node.title = ':title'))
ORDER BY node_title ASC
)

1

What's going on? How do I get the results of the query?
EDITED AFTER SOME EXPERIMENTING
I've narrowed it down to the WHERE clause - if I set the query to the following, it works.
$sql = db_query("SELECT node.title AS node_title,
                  node.nid AS nid,
                  field_speaker_node.title AS field_speaker_node_title,
                    field_speaker_node.nid AS field_speaker_node_nid,
                    'node' AS field_data_field_job_title_node_entity_type,
                    'node' AS field_data_field_company_node_entity_type
                    FROM
                    node node
LEFT JOIN field_data_field_speaker field_data_field_speaker ON node.nid = field_data_field_speaker.field_speaker_target_id
LEFT JOIN node field_speaker_node ON field_data_field_speaker.entity_id = field_speaker_node.nid
                  ORDER BY node_title ASC")->fetchAll();

I don't know if the issue is with the where clause itself, or with the placeholders. Did I not format it correctly?
Comment: I did figure out the issue; the placeholders should not be in quotes (in the query, not the args array.) An example I was working from showed them formatted in single quotes, so that's what I did. I just assumed somehow Drupal was replacing things, but if they're in single quotes they're being passed my mysql as literal strings and obviously there are no results that match.
Comment: See [Database abstraction layer](http://api.drupal.org/api/drupal/includes%21database%21database.inc/group/database/7), where it is stated that placeholders should not placed between quotation marks. What you have written as comment is the answer for your own question; you should write an answer, and accept it.
Comment: Thanks for the link. I inherited Drupal along with my current job, and I've never had time to really get through best practices - I'm just trying to keep my head above water learning what I need as I need it.
Answer: I did figure out the issue; the placeholders should not be in quotes (in the query, not the args array.) An example I was working from showed them formatted in single quotes, so that's what I did. I just assumed somehow Drupal was replacing things, but if they're in single quotes they're being passed my mysql as literal strings and obviously there are no results that match.
The Database abstraction layer says:

Note that placeholders should be a "complete" value. For example, when running a LIKE query the SQL wildcard character, %, should be part of the value, not the query itself. Thus, the following is incorrect:
    SELECT nid, title FROM {node} WHERE title LIKE :title%;

It should instead read:
    SELECT nid, title FROM {node} WHERE title LIKE :title;

and the value for :title should include a % as appropriate. Again, note the lack of quotation marks around :title. Because the value is not inserted into the query as one big string but as an explicitly separate value, the database server knows where the query ends and a value begins.
Answer: $result = db_query('SELECT id, ...');

foreach ($result as $row) {
  // do something with $row->id;
}

Comment: I'd already tried that. When it didn't return anything, I switched it out for the `print_r()` to see what exactly was being returned. It's NOT returning anything I can loop through - see the original post.
Comment: To clarify, the query is in one function, the processing code in another function which calls the `speaker_carousel_get_data()` function. I just tried moving the processing code into the same function, and although the function is being called (an error log right before the query does print), when I try to loop through results after the `db_query` line, error logs added there don't happen. I'm not saying they print out with no value; they don't print at all, which means that the query isn't returning anything that can be looped through that way.
Comment: The return value from `db_query()` implements `DatabaseStatementInterface`, which in turn implements [`Traversable`](http://php.net/manual/en/class.traversable.php)...meaning it can be iterated over using `foreach`. You can loop over anything that implements `Traversable` so if your debug statements aren't displaying chances are your query is returning no results
Comment: Thanks, @Clive. But that begs the question - why isn't it returning results when run via the module, but the exact same query does return results when run in phpMyAdmin? What is Drupal doing to the query that makes it not return anything?
Comment: Hmmm I missed that bit, not really sure to be honest. You can dump the results of the query straight into an array using `fetchAll()` (i.e. `db_query('sql here')->fetchAll();`), try running that and using `print_r` to see if you get any data
Comment: Tried that, and this is what it returned (I used `` around the `print_r` to make it easier to read. `Array
(
)
1`
Comment: I wonder if the issue is the query. It's copied directly from a view (just a starting point; there's still a lot of changes I need to make to the query.) But it involves entity references, and maybe there's something funky happening. I'm going to try to simplify the select to see if it works then. If so, I know I need to find a different way to get the data. Nope; just tried reducing the query to selecting node.title and node.nid, with no where clause at all. Still doesn't return anything.
Comment: Editing OP because comment trail is getting long.


Moving a site, links/admin do not work

Question: I moved a drupal installation from one server to another.
Steps I followed:

Copied whole directory structure from old server.
Exported database from old server.
added files to newdomain/drupal
Imported database
edited settings.php with new database information.

As of right now the home page is working (Except for some broken non-db images, but I know the reason for that and can fix it) But none of the links to any of the nodes or any of the admin paths I know seem to exist. I get a 404 File Not Found error.
I wonder if it's related to the fact that this installation is in a subdirectory and the other one was not, but is that enough to make every page except the homepage not function?
Answer: Yes, that's possible. You can try to adjust the used base URL by setting the $base_url value in your settings.php .
Answer: The link to the modules and themes are hard coded in the system table in the database. Reset them by visiting 'admin/modules', clear the cache, make sure clean urls are on, and make sure any op code cache like APC is cleared if you are using that.
Comment: Have you tried mysite.com/?q=admin/modules or mysite.com/[new directory]/?q=admin/modules
Comment: You can clear the cache at 'admin/config/development/performance' but first you will need to turn off clean urls at 'admin/config/search/clean-urls'
Comment: I can't access admin on the new location, but would it work to do that on the old site and then re-export the database?
Comment: Ah that second url format allowed me to get to the login page, and then to where I need to go
Comment: I don't see anywhere to clear the cache, though.. I have the devel module installed, but don't see any option there, either.
Comment: just turning off clean urls seemed to do the trick
Answer: I had the same problem! The cause was a missing .htaccess file...it didn't get copied when I copied all the other site files. Once I copied that file into the test site, I was able to re-enable clean urls.
Answer: For windows server users:
 I had same issue. I added .htaccess file but no success. On windows server you need to

open IIS
click URL Rewrite
Import Rules
point to your .htaccess file in Site
import -> Remove any error shown
Apply Rules.

That should solve this issue.
Answer: If you have any languages configured, you might have to go into the database directly and reconfigure the URLs under the table:  languages, then change the settings under domain.
You can also configure these settings in the GUI under: /admin/config/regional/language if you can get to it.
DON'T FORGET to clear your caches afterward.

Moving a site, links/admin do not work


How to use pitch pipe app in different majors for singing?

Question: I have an app that can tell what what pitch I am singing but I have to give it a note such as C4. I know the notes/octaves in C major but I don't know what E4 would be in B flat major. Thank you in advance.
Comment: Welcome to Music SE. Could you please reformulate your question and specify the exact question more clearly?
Answer: E4 is the major 3rd in C. So in Bb the major 3rd would be D.
All you have to do is to transpose the interval to the key you are requesting. Bb is 2 semitones lower than C so the tone you are looking for is also 2 semi tones lower than E: this is D.


Should I include "Follow-up moment" as a fixed factor in my linear mixed model?

Question: I am performing a linear mixed model to asses whether pain scores differ between surgically treated patients who tested positive for a bacterial culture versus negative. I have 5 follow up moments but do not know if I should only include the follow up moment as a "repeated measure" or as a fixed factors as well.
As variables I have : Case_Id
Repeated : Followup moment (1,2,3,4 or 5)
Dependent: Pain score
Fixed factor: Bacterial infiltration (yes/no), AGE, BMI
Random factor: Subject (with intercept)
Comment: What is the difference between Case_ID and subject ?
Comment: @BartJonker Please register &/or merge your accounts (you can find
information on how to do this in the **My Account**
section of our [help]), then you will be able to
edit & comment on your own question.
Answer: What is actually repeated is the case_ID, since you have taken several measures by Case_ID from what I understand. So the Case_ID is the variable which should be a random factor.
If you were to build a linear mixed model, you would need to have one column "follow up moment" containing the values 1, 2, 3, 4 or 5. It would mean that you have all the pain scores in the pain score column. From what you describe, it seems that it is what you already have.
I suppose you are interested in the effect of the follow up moment, since you wanted to have it as an explanatory variable. Then the model formula in R should look something like :
<code>pain score~bacterial infiltration*follow up moment +(1|case_ID)
</code>
In SPSS unfortunately I cannot say, but the reasoning is the same.
I included an interaction term because the effect of the bacterial infiltration on the pain score might vary according to the follow up moment. I do not know how you would rather include age and BMI, probably as simple effects ?


Manually Calculating P value from t-value in t-test

Question: I have a sample dataset with 31 values. I ran a two-tailed t-test using R to test if the true mean is equal to 10:
t.test(x=data, mu=10, conf.level=0.95)

Output:
t = 11.244, df = 30, p-value = 2.786e-12
alternative hypothesis: true mean is not equal to 10
95 percent confidence interval:
 19.18980 23.26907
sample estimates:
mean of x
 21.22944

Now I'm trying to do the same thing manually:
t.value = (mean(data) - 10) / (sd(data) / sqrt(length(data)))
p.value = dt(t.value, df=length(lengths-1))

The t-value calculated using this method is the same as output by the t-test R function. The p-value, however, comes out to be 3.025803e-12.
Any ideas what I'm doing wrong?
Thanks!
EDIT
Here is the full R code, including my dataset:
# Raw dataset -- 32 observations
data = c(21.75, 18.0875, 18.75, 23.5, 14.125, 16.75, 11.125, 11.125, 14.875, 15.5, 20.875,
            17.125, 19.075, 25.125, 27.75, 29.825, 17.825, 28.375, 22.625, 28.75, 27, 12.825,
            26, 32.825, 25.375, 24.825, 25.825, 15.625, 26.825, 24.625, 26.625, 19.625)

# Student t-Test
t.test(x=data, mu=10, conf.level=0.95)

# Manually calculate p-value
t.value = (mean(data) - 10) / (sd(data) / sqrt(length(data)))
p.value = dt(t.value, df=length(data) - 1)

Answer: Use pt and make it two-tailed.
> 2*pt(11.244, 30, lower=FALSE)
[1] 2.785806e-12

Comment: The value needs to be positive, so if using this with a variable that could be negative, wrap in `abs`.
Comment: For a two tailed test, you're looking for the probability that the value is less than -11.244 or more than +11.244. lower=F tells R to compute the probability of the value being more than the first parameter. Otherwise, it gives you the probability of the value being less than the first parameter. As such, you could also do 2*pt(-11.244, 30). Personally, I usually do 2*pt(-abs(q), df=n-1) as R defaults to lower=T.
Comment: I think there is a detail missing: When to use lower=F? - Please see my question here: http://stats.stackexchange.com/questions/133091/manually-calculating-p-value-for-t-test-how-to-avoid-values-bigger-1
Answer: I posted this as a comment but when I wanted to add a bit more in edit, it became too long so I've moved it down here.
Edit: Your test statistic and d.f are correct. The other answer notes the issue with the calculation of the tail area in the call to pt(), and the doubling for two-tails, which resolves your difference. Nevertheless I'll leave my earlier discussion/comment because it makes relevant points more generally about p-values in extreme tails:
It's possible you could be doing nothing wrong and still get a difference, but if you post a reproducible example it might be possible to investigate further whether you have some error (say in the df).
These things are calculated from approximations that may not be particularly accurate in the very extreme tail.
If the two things don't use identical approximations they may not agree closely, but that lack of agreement shouldn't matter (for the exact tail area out that far to be meaningful number, the required assumptions would have to hold to astounding degrees of accuracy). Do you really have exact normality, exact independence, exactly constant variance?
You shouldn't necessarily expect great accuracy out where the numbers won't mean anything anyway. To what extent does it matter if the calculated approximate p-value is $2\times 10^{-12}$ or $3\times 10^{-12}$? Neither number is measuring the actual p-value of your true situation. Even if one of the numbers did represent the real p-value of your true situation, once its below about $0.0001$, why would you care what that value actually was?
Answer: The best way to calculate it manually is:
t.value = (mean(data) - 10) / (sd(data) / sqrt(length(data)))
p.value = 2*pt(-abs(t.value), df=length(data)-1)

You need the abs() function because otherwise you run the risk of getting p-values bigger than $1$ (when the mean of the data is bigger than the given mean)!
Answer: I really like the answer @Aaron provided, along with the abs comments. I find a handy confirmation is to run
pt(1.96, 1000000, lower.tail = F) * 2
which yields 0.04999607.
Here, we're using the well-known property that 95% of the area under the normal distribution occurs at ~1.96 standard deviations, thus the output of ~0.05 gives our p-value. I used 1000000 since when N is huge, the t distribution is nearly the same as the normal distribution. Running this gave me comfort in @Aaron's solution.


I can not to put a text when the editText has android:enabled="false" and android:focusable="false" attributes

Question: I want to have the android:enabled="false" and android:focusable="false" attributes to disable the typing for the editText. But also I want to set a text in that. I have the following code but when I rub the code, I can not see the text in the editText.
 <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:enabled="false"
        android:focusable="false"/>

And the after code:
  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    editText = (EditText) findViewById(R.id.editText);
editText.setText("How are you?");
    }

Answer: Your code will work fine. This is my working code.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
        android:layout_height="match_parent"        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <EditText
        android:id="@+id/edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:enabled="false"
        android:focusable="false"/>

</RelativeLayout>

// In MainActivity

private EditText edittext;

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edittext = (EditText)findViewById(R.id.edittext);
        edittext.setText("Hi");
    }

Answer: It might be possible that your textcolor and background color are blending so try to change textcolor or make sure that any other view is not on top of edittext


How do I use Ammo.btCompoundShape (JavaScript port of Bullet Physics)?

Question: I'm using Ammo.js, a direct JavaScript port of C++ Bullet Physics. The unfortunate result being that the documentation is C++, not great reading if your languages are Python and JavaScript.
I have the documentation for Ammo.btCompoundShape here but can't make sense of it.
I have a working code here where the Bone instance just falls through the floor, as you'll see. Don't worry about the naming of "Bone", at this stage in development it's just meant to test a compound shape of two blocks.

class RenderEngine {
  constructor(gameEngine) {
    this.gameEngine = gameEngine
    this.gameEngine.clock = new THREE.Clock();
    this.scene = new THREE.Scene();
    this.scene.background = new THREE.Color(0xbfd1e5);
    this.camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.2, 5000);
    this.camera.position.set(0, 30, 70);
    this.camera.lookAt(new THREE.Vector3(0, 0, 0));
    const hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.1);
    hemiLight.color.setHSL(0.6, 0.6, 0.6);
    hemiLight.groundColor.setHSL(0.1, 1, 0.4);
    hemiLight.position.set(0, 50, 0);
    this.scene.add(hemiLight);
    const dirLight = new THREE.DirectionalLight(0xffffff, 1);
    dirLight.color.setHSL(0.1, 1, 0.95);
    dirLight.position.set(-1, 1.75, 1);
    dirLight.position.multiplyScalar(100);
    this.scene.add(dirLight);
    dirLight.castShadow = true;
    dirLight.shadow.mapSize.width = 2048;
    dirLight.shadow.mapSize.height = 2048;
    const d = 50;
    dirLight.shadow.camera.left = -d;
    dirLight.shadow.camera.right = d;
    dirLight.shadow.camera.top = d;
    dirLight.shadow.camera.bottom = -d;
    dirLight.shadow.camera.far = 13500;
    this.renderer = new THREE.WebGLRenderer({
      antialias: true
    });
    this.renderer.setClearColor(0xbfd1e5);
    this.renderer.setPixelRatio(window.devicePixelRatio);
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(this.renderer.domElement);
    this.renderer.shadowMap.enabled = true;
  }
  renderFrame() {
    this.renderer.render(this.scene, this.camera)
  }
}

class PhysicsEngine {
  constructor(gameEngine, physicsEngine) {
    this.gameEngine = gameEngine
    let collisionConfiguration = new Ammo.btDefaultCollisionConfiguration(),
      dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration),
      overlappingPairCache = new Ammo.btDbvtBroadphase(),
      solver = new Ammo.btSequentialImpulseConstraintSolver();
    this.tmpTrans = new Ammo.btTransform();
    this.physicsWorld = new Ammo.btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration);
    this.physicsWorld.setGravity(new Ammo.btVector3(0, -10, 0));
  }
  updateFrame() {
    this.physicsWorld.stepSimulation(this.gameEngine.clock.getDelta(), 10);
    this.gameEngine.objects.forEach(object => {
      const ms = object.ammo.getMotionState()
      if (ms) {
        ms.getWorldTransform(this.tmpTrans)
        const p = this.tmpTrans.getOrigin()
        const q = this.tmpTrans.getRotation()
        object.mesh.position.set(p.x(), p.y(), p.z())
        object.mesh.quaternion.set(q.x(), q.y(), q.z(), q.w())
      }
    })
  }
}

class GameEngine {
  constructor(renderEngine, physicsEngine) {
    this.objects = []
    this.renderEngine = new RenderEngine(this, renderEngine)
    this.physicsEngine = new PhysicsEngine(this, physicsEngine)
  }
  run() {
    this.physicsEngine.updateFrame()
    this.renderEngine.renderFrame()
    requestAnimationFrame(() => {
      this.run()
    });
  }
  add(object) {
    this.objects.push(object)
    return this.objects.length - 1
  }
  remove(objectIndex) {
    this.objects[objectIndex] = false
  }
}

class Box {
  constructor(gameEngine, properties) {
    this.gameEngine = gameEngine
    this._initPhysics_(properties)
    this._initRendering_(properties)
    this.id = gameEngine.add(this)
  }
  _initPhysics_(properties) {
    const pos = properties.pos
    const quat = properties.quat
    const scale = properties.scale
    const mass = properties.mass
    const group = properties.group
    const interactionGroup = properties.interactionGroup
    const physicsWorld = this.gameEngine.physicsEngine.physicsWorld
    const transform = new Ammo.btTransform()
    transform.setIdentity()
    transform.setOrigin(new Ammo.btVector3(pos.x, pos.y, pos.z))
    transform.setRotation(new Ammo.btQuaternion(quat.x, quat.y, quat.z, quat.w))
    const motionState = new Ammo.btDefaultMotionState(transform)
    const colShape = new Ammo.btBoxShape(new Ammo.btVector3(scale.x * 0.5, scale.y * 0.5, scale.z * 0.5))
    colShape.setMargin(0.05)
    const localInertia = new Ammo.btVector3(0, 0, 0)
    colShape.calculateLocalInertia(mass, localInertia)
    const rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, colShape, localInertia)
    const body = new Ammo.btRigidBody(rbInfo)
    physicsWorld.addRigidBody(body, group, interactionGroup)
    this.ammo = body
  }
  _initRendering_(properties) {
    const pos = properties.pos
    const scale = properties.scale
    const color = properties.color
    this.mesh = new THREE.Mesh(new THREE.BoxBufferGeometry(), new THREE.MeshPhongMaterial({
      color
    }))
    this.mesh.position.set(pos.x, pos.y, pos.z)
    this.mesh.scale.set(scale.x, scale.y, scale.z)
    this.mesh.castShadow = true
    this.mesh.receiveShadow = true
    this.gameEngine.renderEngine.scene.add(this.mesh)
  }
}

class Bone {
  constructor(gameEngine, properties) {
    this.gameEngine = gameEngine
    this._initPhysics_(properties)
    this._initRendering_(properties)
    this.id = gameEngine.add(this)
  }
  _initPhysics_(properties) {
    const pos = properties.pos
    const quat = properties.quat
    const scale = properties.scale
    const mass = properties.mass
    const group = properties.group
    const interactionGroup = properties.interactionGroup
    const physicsWorld = this.gameEngine.physicsEngine.physicsWorld
    const compoundShape = new Ammo.btCompoundShape()
    this._addSection_(compoundShape, {
      pos,
      quat,
      scale,
      offset: {
        x: 0,
        y: 0,
        z: 0
      },
      rotation: {
        x: 0,
        y: 0,
        z: 0,
        w: 0
      }
    })
    this._addSection_(compoundShape, {
      pos,
      quat,
      scale,
      offset: {
        x: 0,
        y: 0,
        z: 0
      },
      rotation: {
        x: 0,
        y: 0,
        z: 0,
        w: 0
      }
    })
    const transform = new Ammo.btTransform()
    transform.setIdentity()
    transform.setOrigin(new Ammo.btVector3(pos.x, pos.y, pos.z))
    transform.setRotation(new Ammo.btQuaternion(quat.x, quat.y, quat.z, quat.w))
    const motionState = new Ammo.btDefaultMotionState(transform)
    compoundShape.setMargin(0.05)
    const localInertia = new Ammo.btVector3(0, 0, 0)
    compoundShape.calculateLocalInertia(mass, localInertia)
    const rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, compoundShape, localInertia)
    const body = new Ammo.btRigidBody(rbInfo)
    physicsWorld.addRigidBody(body, group, interactionGroup)
    this.ammo = body
  }
  _initRendering_(properties) {
    const pos = properties.pos
    const scale = properties.scale
    const color = properties.color
    this.mesh = new THREE.Mesh(new THREE.BoxBufferGeometry(), new THREE.MeshPhongMaterial({
      color
    }))
    this.mesh.position.set(pos.x, pos.y, pos.z)
    this.mesh.scale.set(scale.x, scale.y, scale.z)
    this.mesh.castShadow = true
    this.mesh.receiveShadow = true
    this.gameEngine.renderEngine.scene.add(this.mesh)
  }
  _addSection_(compoundShape, properties) {
    const pos = properties.pos
    const quat = properties.quat
    const scale = properties.scale
    const offset = properties.offset
    const rotation = properties.rotation
    const transform = new Ammo.btTransform()
    transform.setIdentity()
    transform.setOrigin(new Ammo.btVector3(pos.x + offset.x, pos.y + offset.y, pos.z + offset.z))
    transform.setRotation(new Ammo.btQuaternion(quat.x + rotation.x, quat.y + rotation.y, quat.z + rotation.z, quat.w + rotation.w))
    const motionState = new Ammo.btDefaultMotionState(transform)
    const colShape = new Ammo.btBoxShape(new Ammo.btVector3(scale.x * 0.5, scale.y * 0.5, scale.z * 0.5))
    compoundShape.addChildShape(transform, colShape)
  }
}

Ammo().then((Ammo) => {
  const gameEngine = new GameEngine(THREE, Ammo)
  const plane = new Box(gameEngine, {
    pos: {
      x: 0,
      y: 0,
      z: 0
    },
    quat: {
      x: 0,
      y: 0,
      z: 0,
      w: 1
    },
    scale: {
      x: 50,
      y: 2,
      z: 50
    },
    mass: 0,
    group: 1,
    interactionGroup: 1,
    color: 0xa0afa4
  })
  const box1 = new Box(gameEngine, {
    pos: {
      x: 0,
      y: 5,
      z: 0
    },
    quat: {
      x: 0,
      y: 0,
      z: 0,
      w: 1
    },
    scale: {
      x: 2,
      y: 2,
      z: 2
    },
    mass: 1,
    group: 1,
    interactionGroup: 1,
    color: 0xa0afa4
  })
  const box2 = new Box(gameEngine, {
    pos: {
      x: 0.75,
      y: 8,
      z: 0.75
    },
    quat: {
      x: 0,
      y: 0,
      z: 0,
      w: 1
    },
    scale: {
      x: 2,
      y: 2,
      z: 2
    },
    mass: 1,
    group: 1,
    interactionGroup: 1,
    color: 0xa0afa4
  })
  const bone1 = new Bone(gameEngine, {
    pos: {
      x: -0.75,
      y: 10,
      z: -0.75
    },
    quat: {
      x: 0,
      y: 0,
      z: 0,
      w: 1
    },
    scale: {
      x: 2,
      y: 2,
      z: 2
    },
    mass: 1,
    group: 1,
    interactionGroup: 1,
    color: 0xa0afa4
  })
  console.log("gameEngine", gameEngine)
  gameEngine.run()
})
canvas, body, html {
  margin: 0px;
  padding: 0px;
  overflow: hidden;
}

The two Box instances land on the floor (plane), bone1 falls through. I assume I did something wrong with the Ammo.btCompoundShape. There are no errors. What's the correct way?
Comment: I don't know solution but try change scale bone.y from 2 to 15 and camera.y from 30 to 0 and look at scene after it, the plane looks like water.
Comment: Check out [this tutorial](https://medium.com/@bluemagnificent/intro-to-javascript-3d-physics-using-ammo-js-and-three-js-dd48df81f591) about Ammo.js. Seems to cover this.
Answer: The bone actually does not fall through completely, it stops in the middle of the plane.
Reason: You are transforming two times:

motionState is transformed
compoundShape is transformed again inside of _addSection_

This way the compoundShape does collide and does not fall through, but the visible colShape is offset (from the reference position of compoundShape) to be inside the plane.
You can see that if you try and change this line inside _addSection_:
transform.setOrigin(new Ammo.btVector3(0, 0, 2.0))

Solution:
Do not transform two times. E.g. transform only the motionState, but not the compoundShape.
E.g. remove these two lines:
_addSection_(compoundShape, properties) {
    const transform = new Ammo.btTransform()
    transform.setIdentity()
    // -- disable second transform: --
    // transform.setOrigin(new Ammo.btVector3( ... ))
    // transform.setRotation(new Ammo.btQuaternion( ... ))

    const colShape = new Ammo.btBoxShape(new Ammo.btVector3(scale.x * 0.5, scale.y * 0.5, scale.z * 0.5))
    compoundShape.addChildShape(transform, colShape)
}

Another remark:
localInertia is also applied to two times:

compoundShape.calculateLocalInertia(mass, localInertia) and
const rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, compoundShape, localInertia).

This obviously works, but is probably not intentional. It doesn't fail because it is 0,0,0. If you indeed want two inertia, I also think you can not use the same localInertia object for both of them, but you should create a second object e.g. localInertiaCompoundShape, but I'm not sure.


Affine space with a single element

Question: I was thinking that if an affine space is consisted of a single element, this has to be the zero element. Is that correct ?
Comment: Rather, the associated vector space has to be the trivial vector space.
Answer: Well, technically no: any singleton is canonically an affine space trhough the only possible action of $k^0$ $$\{p\}\times\{0\}\to \{p\}\\ (p,0)\mapsto p$$
In fact, if you think about it, every point of $p\in\Bbb R^2$ is considered a zero-dimensional affine subspace of $\left(\Bbb R^2,\overrightarrow{\Bbb R^2}\right)$, not only the origin.
It is true, though, that its space of translations must be $\{0\}$.

Affine space with a single element


Pool: called shots and combinations

Question: According to WPA rules,

In games in which the shooter is required to call shots, the intended ball and pocket must be indicated for each shot if they are not obvious.

However, I don't understand from this description if you are allowed to pocket some other legal ball, but not the called one, only strike the called ball.
Let's say the position is like this, with ball (1) sitting over a corner pocket X and the cueball (C) blocked by another legal ball (2), and let's say I have no other legal balls on the table (for example, only (8) left for me after these in an 8-ball game):
<code>X \----------------
\(1)    (2)  (C)
|
|
</code>
My options would be either to play a combination shot striking (2) and potting (1), or potting (1) by playing a kick shot off the rail not visible on this diagram.
If the game is call-shot, can I nominate ball (2) and pocket (X), yet still pot (1) with the combination shot outlined above?
Answer:
However, I don't understand from this description if you are allowed to pocket some other legal ball, but not the called one, only strike the called ball.

You are allowed to pocket other legal balls.  But if you don't pocket your called ball, your shot has failed.
From the same rule:

Details of the shot, such as cushions struck or
other balls contacted or pocketed are irrelevant.

If the game is call-shot, can I nominate ball (2) and pocket (X), yet still pot (1) with the combination shot outlined above?

Yes.  But if (2) doesn't fall, you did not complete the shot and don't get to remain at the table.
Given this is 8-ball, you could call the (1).  Then if only the (1) is pocketed or both the (1) and the (2) are pocketed, you would have made the shot and can continue.
Comment: So, I don't have to *strike* the ball I have nominated, I still can play any legal ball? I may be confusing this with snooker, which rules I know quite well (even if never played, I have watched it a lot). There if you nominate pink, for example, you have to *strike* it first, and only it may be potted (you don't need to nominate a pocket). Your answer seems to imply that in pool the nominated ball only needs to be *potted*, but the first ball *struck* may be any other legal ball. Is that correct?
Comment: That becomes a question about the specific game.  Yes in 8-ball you may strike with the cue a ball you don't intend to pocket, but it still must be one of your group.  See WPA rule 3.9 "Wrong ball first".  Also look up "combination shot" (unfortunately used but not defined in the WPA rules).
Comment: As I understand it, the rules about the called shot apply generally to all variants of pool, e.g. that linked bit of WPA rules is in a section preceding 8-ball, 9-ball and so on. For example, in straight pool any ball is legal. Which would mean I can still strike any ball, I only need to *pot* the nominated ball (directly or via a combination, etc.) to the nominated pocket. That was basically my confusion, what the nomination meant exactly.

Pool: called shots and combinations


How to resample from uneven strata

Question: I've got records from patients with different cancers. Naturally, common cancers were registered often, and the cases in this group are then overrepresented and vice versa for the rare cancers.
Let's say that I have:

20 patients cancer 1
160 patients cancer 2
80 patients cancer 3

-> are these strata uneven?
I would like to iteratively sample a set with an equal amount of sufficient cases from each cancer to test on.
However, if I pick 20 cases from each cancer, this won't cover cancer 2, and I will include the same patients from cancer 1 in each iteration.
Is this a problem?
If so, how would I solve this problem?
If I use sampling with replacement, I do not necessarily pick the same 20 cases from cancer 1, but wouldn't I need more iterations ensure cases from the larger strata are covered enough?
- edit -
I actually need to find features from one particular cancer that are different from the other cancers. I've got thousands of features, couple hundreds of samples from different cancers in different proportions, this is all public data. I'm worried that a standard t-test or some kind of linear model for each feature between cancer of interest vs the rest will be biased because of the distribution of cancer types in 'the rest'.
-> That's why, following the idea described in the methods here, I wanted to subsample the cancers. But this means I would need to iterate over selections of samples, I guess - And that's where the authors of the paper stop providing information.
Then I will need to validate these results in our own samples, and finally we'll need to try and detect these features in specific human samples before we create any kind of model.
So now that this is clear:
I think I need a t-test and I think this requires to subsample the cancers. Is this indeed necessary, is this a problem, and if so, how do I solve this?
Answer: Removing data you already collected is bad statistical practice, and is usually only done when you are (1) using classification when you should be doing prediction or (2) you are using an improper accuracy scoring rule.  The sampling you indicated is guaranteed to make whatever method you use for predictions to fail when tried on new observations.  See http://fharrell.com/post/classification and http://fharrell.com/post/class-damage .  I'd be interested to know where you learned such a confusing approach.  This is getting to be a common statistical misconception.
But I just re-read your question.  If you are using a proper probability accuracy scoring rule and are re-sampling just to do an internal validation and not to develop the model, you may be OK to do stratified bootstrapping.  There you do the bootstrap individually within each stratum and just combine all the samples.
Comment: WIthout having time to study that paper, I still lean towards the feeling that subsampling should not be part of the main algorithm but might be used during bootstrap validation.  A global statistical model with penalization that is particular to your problem is going to be the best solution.  Short of that, some sort of repeated rank ANOVA (e.g., Kruskal-Wallis test) could be contemplated, where you quantify continuous features by how they separate the entire set of possible cancers.
Comment: I understand that it is a bad approach, but I need a set that has equal amounts of samples from each stratum - because I need to model another biological situation, different from the one where we collect samples at their natural occurrence rate.
I got the idea from [this article](https://genomebiology.biomedcentral.com/articles/10.1186/s13059-016-1143-5#Sec14), first paragraph from the methods section, in which authors only give the same description as I did, but they did not provide further information about their reasoning, their methods, nor did they include a discussion about it.
Comment: Ahh, I see why you provided these links. The ultimate goal is indeed to make a classifier or prediction model. But not by taking a subsample to my liking of this particular data - I will edit my original post.
Comment: Okay, I'll look into what I can find out. Thank you for the input!

How to resample from uneven strata


State Space Model Specification (KFAS)

Question: I am using KFAS to fit a dynamic logistic model of the form;
$\hat{y} = \bf \beta_t x + \epsilon$
$\beta_t = \beta_{t-1} + \eta$
So the regression parameters change over time, and act as latent variables to be estimated by the filter.
Can state space models of this form generally accept situations where we have multiple observations per time period? I believe they can, but I can't figure out how to specify this in KFAS (or any other R package for that matter).
I've tried the below code, but KFAS thinks that this means there are 22 time periods - there are actually only ten.
<code>library(KFAS)
y = c(1,0,0,0,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1)
i = seq.Date(from = as.Date("2014-01-01"), as.Date("2014-01-10"), length.out = 22)
x = rnorm(n = 22, mean = 1, sd = 2)

a =   model = SSModel(y ~
                    SSMregression(~x),
                  distribution = "binomial")

fit = fitSSM(a, inits = c(0,0))
</code>
Answer: as you have given 22 normally generated values to x , KFAS would take 22 time periods only. What else do u expect?
You can add multiple observation in rformula.
SSMregression(rformula, data, type, Q, index, R, a1, P1, P1inf, n = 1,
  remove.intercept = TRUE, state_names = NULL, ynames)

State Space Model Specification (KFAS)


Image of Hilbert's Space filling Curve

Question: I am trying to find the image of $[0,1/2)$ in Hilbert's Space Filling Curve.
What I thought is $[0,1/2]\times$ $[0,1]$ \ $[1/4,1/2]\times[1/2,3/4]$.
Is my understanding correct?
The sets considered are as usual. From $[0,1]$ to $[0,1]^2$.
Comment: Why isn't it $[0,1/2]\times[0,1]\setminus\{(1/2,1/2)\}?$
Answer:
What I thought is ...

From the definition of Hilbert Curve;
for each parameter $t \in I := [0,1] $ a sequence of nested intervals
$$I \supset [a_1, b_1] \supset \dots \supset [a_n, b_n] \supset \dots $$
exists, such that each interval is obtained by splitting its predecessor into four parts of equal size.
Any such sequence of intervals can be mapped one by one to a sequence of nested 2D interval. These nested intervals will converge to a uniquely defined point $ h(t) \in Q:= [0,1]\times[0,1]$.
The point to point mapping is determined by the iteration of the curve.

Iteration 0 :

$$[0,1] \longmapsto [0,1]\times[0,1]$$

Iteration 1 :

$$ [0,\frac{1}{4}] \longmapsto [0,\frac{1}{2}]\times[0,\frac{1}{2}]\\
[\frac{1}{4},\frac{1}{2}] \longmapsto  [0,\frac{1}{2}]\times[\frac{1}{2},1]\\
[\frac{1}{2},\frac{3}{4}] \longmapsto [\frac{1}{2},1]\times[0,\frac{1}{2}] \\
[\frac{3}{4},1] \longmapsto [\frac{1}{2},1]\times[\frac{1}{2},1] \\
$$
and so on. The following image shows the said iterations of the hilbert curve   (src Why does the Hilbert curve fill the whole square?)
That answers your question.

Image of Hilbert's Space filling Curve


Real World Challenge: Large difference between training and testing set accuracy

Question: I have a classification dataset of ~100,000 rows and ~200 features. Within the dataset my predictor variable (Y) is an integer value between 0-55, therefore I am trying to predict 1 of 56 possible classes. I split my training/testing set into 80/20% and performed an extensive 10-fold cross validation exercise to tune the parameters and fit the final model. I end up a very high accuracy (and F1) score in the training set (~90%) but a very slow accuracy (and F1) score in the testing set (~10%).
EDIT 1: The training and testing set are split randomly. About 150 of the features are binary features (0 or 1) and the others are continuous values which I center and scale to be between 0 and 1.
I have tried numerous learning algorithms (SVM, NN, logistic regression, PCA + SVM) and believe that the 10-fold CV should have eliminated overfitting as best as possible. However, nothing that I try seems to yield any meaningfully different results.
Can anyone suggest new ways to increase accuracy of the testing set?
Caveats:
1) This is real world data so getting more of it is very expensive and time consuming.
2) We need these 56 classes so cannot simply eliminate any.
Thanks and any suggestions are appreciated.
Comment: Thanks for clarifying. I did a very large grid search for these parameters so I do not think that is the problem. I am pretty confident that the learning parameters are calculated correctly.
Comment: Just to be sure: you split the sets **randomly** into training and test? Then you realize the cross-validation only with data from the training set, right?
And what is the range you're using for your parameters? Maybe you could find better parameters outside the range you have defined.
Comment: Thanks for the reply! Yes, the sets are split randomly. About 150 of the features are binary features (0 or 1) and the others are continuous values which I center and scale to be between 0 and 1. I am not sure I understand your last comment, can you please elaborate.
Comment: When I say the parameters I mean the learning parameters, for example the regularization strength for the logistic regression. For what values you test them with your cross-validation?
But I think that's not the problem anyway, otherwise your F-score for the training set should be small too.
Answer: There may be many reasons for this. Below is a non-exhaustive list of bullet points; i.e. me thinking out loud.

Is your predictor variable (with the class labels) ordinal or nominal? If it is the former, how do you calculate accuracy? e.g. do you incorporate the fact that $Y_{predict} = 50$ is better than $Y_{predict}=10$, when $Y_{real} = 55$?
What are the label distributions for the 56 classes in the test and training sets? I understand that viewing and analysing a 56*56 confusion matrix is painful but the answer to your question is most likely in the analyses of the confusion matrices for the trainig and test sets. By collapsing the confusion matrices, you can get proportions of specific agreements, etc. per class label and then combine this information with the class distributions of your training and test sets. To sum up, accuracy on its own gives you a very limited view of the whole picture.
Attached to the first item, if you have selected the test data without shuffling the row indices, you may be suffering from temporal trends; e.g. if your test data is the most recent 20%, the class distributions for the data collected during this period may be different.
Also, is your data incomplete? If so, how do the ratios of incompleteness for the test and training sets compare? The more incomplete your subset, the less predictive information you have.
Comment: Thanks Zhubarb for your thoughts! To answer your questions: 1) The predictor variable is nominal so ordering is not important. In fact, it was actually chosen in a arbitrary manner. 2) This is an interesting point that I will look more into.
3+4) The data has no temporal effect and is not incomplete . We have sufficient statistics in each class so I believe the learning algo is able to learn what each class represents.


What does it mean to sort an array/matrix by the argmax as the key?

Question: I am struggling to understand the mechanism behind a function around the topic of sorting in numpy.
    import numpy as np
    arr = [[8, 5, 9],
            [3, 9.5, 5], [5.5, 4, 3.5], [6, 2, 1],
            [6,1,2],[3,2,1],[8,5,3]]
    res = sorted(arr, key=np.argmax)

This gives me the following result:
    print(res)
    [[5.5, 4, 3.5], [6, 2, 1], [6, 1, 2],
      [3, 2, 1], [8, 5, 3], [3, 9.5, 5], [8, 5, 9]]

I am an R user and not very familiar with Python. I might have some clue about the role of the 'key' argument, but for this example specifically I ask for your help.
In a simple case if the key argument is defined as a function which returns the first element, then the sorted, sorts the array based on its first element, but I cannot see how this works with the argmax.
Thanks,
Answer: The argmax function returns the indice of the biggest element. It is used as a key in the sort function.
If you print this:
print([np.argmax(x) for x in arr])

you get:
[2, 1, 0, 0, 0, 0, 0]

which explains the sorting. Last elements appear first in your result, first element appears last because it has the highest criteria, and second element appears just before.
Of course this is a "weak" sorting since the criteria often returns the same value and thus the result depends on the order of the initial list (edit: this is called a stable sorting, see interesting Bakuriu comment)
Comment: The term weak sorting doesn't exist. The property you are describing is *stable* sorting where the relative order of the elements is preserved for equal keys. Note that python sorting guarantees that, but other algorithms do not (and randomized ones like quicksort may yield different results for different executions on the same input).
Comment: Does that mean that the difference between zeros are negligible? and they could have appeared in any other order?Now I know,Thanks, I just saw your edit.
Answer: np.argmax gives you the argument of the maximum value. In your example, it is acting on each individual list of 3 items, for example
>>> np.argmax([8,5,3])
0
>>> np.argmax([1,2,3])
2


Graph with chromatic number $4$ that is not a supergraph of $K_3$

Question: I've been trying to find a graph in which the chromatic number is equal to $4$ but it cannot be a supergraph of $K_3$.
I tried with an $11$-gon and join vertices every two vertices, (excuse me If my explanation is not clear, I'm learning English) anyway the resulting graph has chromatic number equal to $3$ and I thought that it was going to be the same with every cyclic graph.
Any examples?
Thanks.
Comment: Why tag this question with `planar-graphs`?
Comment: Smallest one is the [Grötzsch graph](https://mathworld.wolfram.com/GroetzschGraph.html).
Comment: Your Question would be improved by adding context.  It's present form, that of a bare problem statement without context, is disfavored by the Math.SE community.  You could give a report of your own efforts to construct such a graph and where you met with difficulty, or you could explain why the problem is important or interesting to you.  And there are many other ways to supply context, something that would allow Readers to respond in useful detail congruent with your level of study.
Comment: Dude, what do you want from me? I'm just trying to learn some math by myself, I'm posting the problem exactly as the book says, I'm pretty sure that these questions are easy for a lot of people here. Not everything has to be "relevant for the community", some people just want help with a book problem, maybe others want to solve really hard stuff, I'm not one of them.
Comment: That's awesome!
Answer: Start with a $13$-gon.  For each independent triple of vertices $\{a,b,c\}$in the $13$-gon, add a vertex $v_{\{a,b,c\}}$ and edges connecting $v_{\{a,b,c\}}$ to each of $a,b,c$.  Call the resulting graph $K$.
Here by independent triple of vertices we mean three distinct vertices in the polygon, none of which are connected by an edge of the polygon.
Then $K$ is $4$-colourable: simply $3$-colour the $13$-gon, and colour all the $v_{\{a,b,c\}}$ with the fourth colour.
Also $K$ is triangle free: the $13$-gon is triangle free, so a triangle would have to involve a vertex $v_{\{a,b,c\}}$.  However ${\{a,b,c\}}$ are independent, so there is no such triangle.  Thus $K$ is not a supergraph of $K_3$.
It remains to show that $K$ is not $3$-colourable.  Suppose we have a $3$-colouring of $K$. Then for any independent triple ${\{a,b,c\}}$ of vertices in the polygon, they cannot all be different colours, as that would leave no choice of colour for $v_{\{a,b,c\}}$.
Pick a vertex $x$ in the polygon.  Call its colour $c_1$.  Opposite $x$ is an edge, with at least one end vertex not coloured $c_1$.  Call this vertex $y$, and its colour $c_2$.  Let $c_3$ denote the remaining colour.
Now the only vertices that may be coloured $c_3$ are the four vertices adjacent to $x,y$, as if any other vertex $a$ were coloured $c_3$, then ${\{x,y,a\}}$ would be an independent triple all coloured differently, which cannot happen.
Conversely, at least one of those four vertices must be coloured $c_3$, as a $13$-gon is not $2$-colourable.  Call this vertex $z$.
Now if we exclude $x,y$, the four vertices adjacent to them, which may be coloured $c_3$, and the remaining four vertices adjacent to those, we are left with one vertex $u$ on one side of the polygon, and two adjacent vertices $v,w$ on the other.

All three of $u,v,w$ are coloured by $c_1$ or $c_2$.  As $v, w$ cannot be the same colour, one of them must be coloured differently to $u$.  Thus $\{u,v,z\}$ or $\{u,w,z\}$ are an independent triple, all coloured differently, which cannot happen.
We conclude that $K$ is not $3$-colourable.
Comment: Thanks man! You know how to approach a newbie, and I'm sad I didn't continue with that approach, lesson learned, don't give up that easily. I'll add the context
Comment: Thanks, I'm curious about how you get to the answer, I tried with an 11-gon and join vertices every two vertices, (excuse me If my explanation is not clear, I'm learning English) anyway the resulting graph has chromatic number equal to 3 and I thought that it was going to be the same with every Cyclic graph. Thanks for answering the question, now I can continue with the next one.
Comment: My thought process started exactly the same as you.   I thought of starting with a polygon and adding "diagonal" edges.  Like you, I got nowhere with this.  Then I thought of adding new vertices, connected to triples of vertices from the polygon, so that those triples could not all be different colours.  Then  I thought if I am doing that, I might as well add all the ones which do not create a triangle.
Comment: The people on this site like some "human context" in the questions.  I think you put everything they want in the comments.  Do you mind if I copy and paste your comments into the main question? This should make everyone happy.


How to solve initial value problem of non linear first order ODE if one solution is given?

Question: We have given Nonlinear ODE as $y'=y+e^x-e^{-x}y^2$ and one of its solution is given by $y(x)=-e^x$.
Is it possible to find solution of IVP with $y(0)=6$?
If it is linear ODE then by equating constant we can get solution.
But how to solve problem if it is non linear ODE?
Any help will be greatly appreciated.
Answer: This is a Riccati equation. The second solution approach consists in setting $y=e^x\frac{u'}{u}$ so that
\begin{align}
y'&=e^x\frac{u'}{u}+e^x\frac{u''}{u}-e^x\frac{u'^2}{u^2}=y+e^x\frac{u''}{u}-e^{-x}y^2
\\
&=y+e^x-e^{-x}y^2
\\[1em]
\implies
u''=u\implies u&=Ae^x+Be^{-x},~~y=e^x\frac{Ae^x-Be^{-x}}{Ae^x+Be^{-x}}
\end{align}
where pairs $(A,B)$ with the same ratio give the same solution. Your given solution corresponds to $A=0$, $B=1$.

For the solution with $y(0)=6$ you want $u(0)=1$, $u'(0)=6$, thus $u(x)=\cosh(x)+6\sinh(x)$.
Answer: This is a Riccati equation, using the $y=-e^x+\frac{1}{v}$ substitution,
then
$$\frac{dy}{dx}=-e^x-\frac{1}{v^2}\frac{dv}{dx},$$
plugged into the
$$\frac{dy}{dx}=y+e^x+e^{-x}y^2$$
you can get
$$\frac{dv}{dx}+3v=e^{-x}$$
this is in
$$ \frac{dv}{dx}+pv=q$$
form. You can use an integrating factor to solve this.
Answer: $$y'=y+e^x-e^{-x}y^2$$
Lutz and Dinush have answered your question. Note that you can also easily solve it this way:
$$(y'-y)=e^x-e^{-x}y^2$$
$$(ye^{-x})'=1-(e^{-x}y)^2$$
Then substitute $u=ye^{-x}$
$$u'=1-u^2$$
This DE is separable.
Comment: looks good to me
Comment: Thank you @Dinush ....


Unable to fix a 'float' object is not callable error

Question: I keep getting the error: TypeError: 'float' object is not callable on this section of code.
for data in list:
    latitude = float(data[1])
    longitude = float(data[2])
    distance = ((6371*math.pi)/180)(math.sqrt((-35.276159-latitude)**2+(149.120893-longitude)**2))
    print(distance)

When I print the type of latitude and longitude, they both return 'float'.  Any help with what I could be doing wrong would be much appreciated!
Comment: Looks like you have used `float` as a variable in your code
Comment: Please post an [MCVE](https://stackoverflow.com/help/mcve). What is `data`, `list`, etc.?
Comment: first of all don't name your list object with list variable, and can you give some example what is in (list variable)
Comment: Also don't forget to format your code correctly - at the moment your code doesn't run.
Answer: You are iterating over your sequence and are calling the item data; this got you confused that data is the sequence.
You are also missing an operator between two expressions in parenthesis: distance = ((6371 * math.pi) / 180) MISSING OPERATOR HERE (math.sqrt((-35.276159 - latitude) ** 2 + (149.120893 - longitude) ** 2)) - this corresponds to (float)(float) after partial evaluation, which is attempting to call a float.
for item in seq:
    latitude = float(item)
    longitude = float(item)
    distance = ((6371 * math.pi) / 180)**2 + (math.sqrt((-35.276159 - latitude) ** 2 + (149.120893 - longitude) ** 2))
    print(distance)

Note:
Please do not use python keywords (list) to name variables.
Comment: @akshat This answer is correct - (thing1)(thing2) is the syntax for attempting to call thing1 with parameters thing2. Rakesh's comment is incorrect - float has not been used as a variable, it has been used as a function.
Comment: why will that lead to `TypeError: 'float' object is not callable`. See @Rakesh's comment, that seems much more probable


Global Spec functor and base change

Question: Let $f:X \rightarrow Y$ be any morphism of schemes, $A$ be a quasi-coherent sheaf of $\mathcal{O}_X$ algebra (Or Noetherian schemes, coherent sheaf if you want), S be a scheme over $Y$ defined by $A$ using the global Spec. Now can we conclude that $X \times_Y S$ is isomorphic with the scheme defined by $f^*A$ ¿ I think that will be true to check locally but not that definite with that.
Answer: Question: "Now can we conclude that $X×_Y S$ is isomorphic with the scheme defined by $f_∗A$? I think that will be true to check locally but not that definite with that."
Answer: If $f: X:=Spec(B) \rightarrow S:=Spec(A)$ and if $A_S$ is any quasi coherent sheaf of $\mathcal{O}_S$-algebras it follows $R:=\Gamma(S,A_S)$ is an $A$-algebra with $A_X \cong \tilde{R}$ the sheafification of $R$. Let $T:=Spec(A_S)$. It follows
$$X\times_S T\cong Spec(B\otimes_A R).$$
And $f^*(A_S) \cong \tilde{B\otimes_A R}$ is the sheafification of $B\otimes_A R$, hence
$$Spec(f^*A_S) \cong Spec(B\otimes_A R) \cong X\times_S T.$$
This construction globalize.
If $A_X$ is a quasi coherent sheaf of $\mathcal{O}_X$-algebras, there is a map
$$f^{\#}: \mathcal{O}_S \rightarrow f_*\mathcal{O}_X$$
hence $f_*A_X$ is a quasi coherent sheaf of $\mathcal{O}_S$-algebras and you may construct $\pi: Spec(f_*A_X)\rightarrow S$ which is a scheme over $S$
Note: The push forward $g_*F$ of a quasi coherent sheaf $F$, where $g: Y \rightarrow Y'$ is a map of schemes, is not always quasi coherent. It is quasi coherent when $Y$ is Noetherian.
Comment: There is a disagreement between the question and this answer here: the OP writes $f^*A$, the pullback, while you write $f_*A$, the pushforward. As such, this is not currently an answer.

Global Spec functor and base change


How to get dovecot to reload an SSL certificate with minimal impact

Question: I have been unable to find any documentation on how to force Dovecot to reread a certificate when its updated.
At the moment I'm doing
 /bin/systemctl restart dovecot

Does anyone know if this causes an outage during the restart, or if dovecot cleanly terminates old sessions and allows new ones to launch with the new config?    Can anyone advise the best practice for forcing dovecot to reload its SSL certificate with minimal impact?
Answer: If you're using letsencrypt, you can add a deploy hook to do this automatically when certbot renews your certs. Deploy hooks live in:
/etc/letsencrypt/renewal-hooks/deploy/

Create a file (name doesn't matter - I named mine reload-dovecot) with the following contents:
#!/bin/sh
do
if [ "$domain" = mail.example.com ]
then
systemctl reload dovecot
fi
done

Replace mail.example.com with the actual name of your mail server. Make sure the file is set to be executable.
You may want to create a similar script to reload postfix.
Answer for dovecot taken from here: https://www.xhalford.com/using-hook-scripts-with-certbot/#:~:text=Luckily%2C%20Certbot%20comes%20with%20the,renewal%2Dhooks%2Fdeploy%2F%20.
You can also use certbot itself to create the hooks:
sudo certbot renew --force-renewal --deploy-hook "postfix reload; service dovecot reload"

See thread here: https://community.letsencrypt.org/t/certbot-dovecot-postfix-certificate-renewal-issue/72226/11
Note: the example in the thread uses service postfix reload - this didn't work for me on Ubuntu 20.x.
Comment: In your example script it shouldn't be `$domain`, but `$RENEWED_LINEAGE` or `$RENEWED_DOMAINS`. As mentioned in the [certbot docs](https://eff-certbot.readthedocs.io/en/stable/using.html)
Answer: Just reload it instead. There is no reason to restart and interrupt everyone's service.
systemctl reload dovecot

Answer: The script code given in @z0lo's answer is not working. Here is an updated version that does work (with mail.example.com that has to be replaced by your mail server):
#!/bin/sh
if [ "$RENEWED_DOMAINS" = "mail.example.com" ]
then
    systemctl reload dovecot
fi


Is it technically possible to play Chopin`s op. 10 No 1 etude at 176 bpm on Casio PX-160 piano?

Question: Is it technically possible to play Chopin`s op. 10 No 1 etude at 176 bpm on Casio PX-160 piano?
Comment: What problems do you expect to run into?
Comment: Curious - is a Casio PX-160 piano the only keyboard instrument you have access to?
Comment: @player777 Although the question that you kept is the most important to you, it's kind of a shame since some of the deleted ones were easier to answer. I'm not familiar with the exact model and am not a pianist, but I imagine that a keyboard's action limits the tempo first for repeated notes, and in a quick scan of the score I don't notice those. 176 bpm x 4 notes per beat / 60 = 11.7 notes per second. It sounds like a tempo that would challenge the performer's ability, but in my opinion ought to be possible on a digital piano with good action. (Whether it's _fun_ or _useful_, now...
Comment: This doesn't answer your question, but might help: I have a Kawai CE 220 digital piano, which I like very much for its realistic action. I'm able to repeat a single pitch in 16th notes on it at 125 bpm. I assume that means, if I had the technique, I could play arpeggios much faster.
Comment: Key action response is definitely slower than on Roland FP and acoustic Kawai. I went to the piano shop and tried. Sadly have no Steinway or similar. Can you play that at 176 on Casio PX? I can`t overcome 155 bpm with my current level of technique. Acoustic pianos in our local music shops have a faster key response and easier action. I thought Casio was better.
Comment: Just following up a year later ... was the answer helpful? Is more information needed?
Answer: TL;DR
Yes

Caveat: I have not been able to access a Casio PX-160 to positively confirm this answer.
Is it possible to play Chopin's Etude Op. 10 No. 1 at 176bpm?
Yes. It requires outstanding technique, but it can be done.
Can it be done on a Casio PX-160?
Yes. The only technical issue would be the small handful of repeated notes. For example, the first two notes of the piece:

The execution of these repeated notes would test any keyboard's response time. However, the PX-160 is of good enough quality, this should not be an issue.
There would likely be musical issues, as opposed to issues of pure technique. Here the main issue would be the dynamic range of the keyboard. Can it produce the kind of subtle dynamic shading of an acoustic piano or higher-end keyboard? Probably not. But the question is about technical possibility, so this issue can be set aside.
Is 176bpm the "right" speed in the first place?
Metronome markings from that era of music are notoriously unreliable. And one also has to remember that pianos of that era had a much lighter touch, the key depths were shallower, and the overall power in terms of volume and sustain were lower compared to modern instruments. All of those factors would facilitate fast playing in comparison to heavier-action modern pianos. Even taking 176 as definitively correct, it must be reconsidered in modern terms.
Comment: Not to mention, the idea of playing _metronomically_ is one to challenge, even in such a moto-perpetuo-style piece. A metronome marking is a reference point, but doesn't mean that you are to play metronomically, especially when the words "Chopin" and "rubato" have such an entangled relationship.
Comment: @AndyBonner It has been famously noted that the rubato associated with Chopin is a "give and take" in time. So if you were to apply rubato on this piece (played at ~176 bpm), you might need the key action to be able to tolerate, say, ~200 bpm.


I need to access individual elements of a node in my module

Question: I have the following query that fetches all the nodes of a certain type.
function shop_home_page() {
  $render = array();
  $sql = 'SELECT nid FROM {node} n WHERE n.type = :type AND n.status = :status';
  $result = db_query($sql,
    array(
      ':type' => 'music_albums',
      ':status' => 1,
    )
  );

  foreach ($result as $row) {
    $node = node_load($row->nid);
    $render['my_list'][] = node_view($node, 'teaser');
   }
  return $render;
}

How do I display in my page node elements such as $node-title, $node-body? I tried as $render['my_list'][] = node->title but it doesn't seem to work.
I also need to add a form with a buy button to each element. How do I attach it?
Answer: 1) You can use code like the following:
$render['my_list'][] = array('#markup' => '
'.$node->title.'
');
$render['my_list'][] = array('#markup' => $node->body['und'][0]['value']);

2) Forms can be added similarly to node_view():
$render['my_list'][] = drupal_get_form('mymodule_buy_form_'.$node->nid, $node->nid);

I'm assuming you want the forms built with a single function, but with different id-s to work correctly (attached $node->nid for that). I also added an extra argument ($node->nid) since you may want to add it to every form in a hidden field to determine which form got submitted. Then you use hook_forms() to get the same builder function called for all the buying forms:
function mymodule_forms($form_id, $args) {
  $forms = array();
  if (strpos($form_id, 'mymodule_buy_form_') === 0) {
    $forms[$form_id] = array(
      'callback' => 'mymodule_buy_form',
    );
  }
  return $forms;
}

The form builder function for this example:
function mymodule_buy_form($form, &$form_state, $nid) {
  $form = array();
  $form['nid'] = array(
    '#type' => 'hidden',
    '#value' => $nid,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

And a submit handler:
function mymodule_buy_form_submit($form, &$form_state) {
  drupal_set_message('Form for node '.$form_state['values']['nid'].' submitted.');
}

Comment: I have build up the form builder but the problem if I am keeping a composite function name like this: drupal_get_form('mymodule_buy_form_'.$node->nid, $node->nid);
I am constantly getting error, callback not found or invalid, while if I am using this name: drupal_get_form('mymodule_buy_form', $node->nid) it works but it adds these ids to the  : pix-product-buy-form, pix-product-buy-form--2 very strange. Can you help me up further? Thanks
Comment: You're probably going wrong somewhere. I added further examples into my answer that should get you a working solution. Add the missing code into your module file, replace all 'mymodule' occurrences with your actual module name, clear caches and then test it out.
Comment: Thanks a lot. You are great! I added also the product picture: $render['my_shop_list'][] = array('#markup' => "field_cover['und'][0]['filename'].">"); I think also rather that retrieving the product list via sql to do it using a view + views_get_view_result() function.
Answer: This looks like it could be done with a view, using view type node list. Display type should be fields and then you select node title and teaser as fields as well as an additional field which has to be rewritten to build a buy button (depending on what action the button shall trigger).
Comment: That is a very good idea,but despite the fact I installed webform and created a webform which has a submit...there is no way I can make a submit button display in views


Prove that a direct product of semiprime rings is a semiprime ring. Is it true for prime rings?

Question:
Prove that a direct product of semiprime rings is a semiprime ring. Is it true for prime rings?

Help me a hint.
Thank for any insight.
Comment: See this M.SE question http://math.stackexchange.com/questions/101214/ideal-in-the-product-of-two-rings
Comment: Can you explain more precisely to me? My question is more complicated than it.
Answer: One of many equivalent definitions of "prime ring" is that for any two ideals $I,J$ of the ring, $IJ=0$ implies that $I=\{0\}$ or $J=\{0\}$.
Let $R$ and $S$ be nonzero rings and look at $R\times S$. Can you find a pair of nonzero ideals whose product is zero?

To prove that a product of finitely many semiprime rings is semiprime, you can use the following characterization of semiprime rings: a semiprime ring is one with no nonzero nilpotent right ideals.
You already know (or can easily prove) that the right ideals of $\prod_{i=1}^n R_i$ are of the form $\prod_{i=1}^n T_i$ where $T_i$ is a right ideal of $R_i$. Consider what it would mean for a right ideal of the product to be nilpotent.
Comment: $I\times\left\{ 0\right\} $ and $\left\{ 0\right\} \times J
 $. Is it true?
Comment: @chuyenvien94 Lacking psychic powers, I don't know what you what $I,J$ to be :) Relate it to $R\times S$.
Comment: Can you make your hint more precise?
Comment: @chuyenvien94 No, I don't think that's necessary. Think about it! What you wrote suggests you have the right idea already... You just haven't explained it properly yet.
Comment: $I$ is an ideal of $R$ and $J$ is an ideal of $S$
Comment: @chuyenvien94 If you pick $I$ and $J$ to be both zero ideals, then you haven't proven anything. Can you pick some more carefully?
Comment: I take Ix0 and Jx0 with I,J are nonzero ideals of R,S resp.
Comment: @chuyenvien94 OK: close enough! Really you should just say $R\times 0$ and $0\times S$. Those are the only nonzero ideals that you can count on. If $R$ and $S$ are simple, there is no other choice.
Comment: @chuyenvien94 Thanks for patiently working on it :)
Comment: You told "prime ring"? Evidently, direct product of prime rings can  not be prime ring. It's only true for semiprime
Comment: @chuyenvien94 That's correct! You've shown the product of two nonzero rings can't ever be a prime ring. Semiprime rings are safe, though. Semiprime rings are exactly those which have no nonzero nilpotent right ideals. You can think about this and discover why a product of finitely many semiprime rings also has this property. I hope you're aware that the ideals of the direct product are just direct products of ideals of the individual rings.
Comment: @chuyenvien94 Sorry, I focused only on the second half of the question initially. I added more for the first half.


MySQL error code 1093 when trying to delete rows

Question: I'm doing a homework assignment where the instructions are "Delete all players who live in the same town as player 57 but keep the data about player 57." There is a table called "Players" that has PlayerNo and Town as columns well as various other data. I tried the following query:
delete from players
where town = (select town from players where playerno = 57)
and playerno <> 57;

But am receiving the following error message:
"Error Code: 1093. You can't specify target table 'players' for update in FROM clause"
How do I fix this?
Comment: @Alejandro: I didn't downvote, but probably because of "shows no research effort". If you search for that error message you will quickly find the reason. It's even enough to read the manual carefully (a lost skill nowadays) which clearly states "*You cannot delete from a table and select from the same table in a subquery*"
Answer: You may rephrase your delete query using an inner join:
DELETE
FROM players p1
INNER JOIN (SELECT town FROM players WHERE playerno = 57) p2
    ON p2.town = p1.town
WHERE
    p1.playerno <> 57;

By the way, the reason for the 1093 error is that MySQL might be in the process of modifying the players table at the same time your subquery is attempting to reference it.  One workaround is to wrap that subquery in another subquery:
DELETE
FROM players
WHERE town = (SELECT town
              FROM (SELECT town
                    FROM players
                    WHERE playerno = 57) t ) AND
      playerno <> 57;

This trick works because MySQL will first materialize the subquery before the update runs, to avoid the 1093 error.
Answer: You can resolve the problem by simple query:
delete players.*
from players
join players players_town on
    players.town = players_town.town and
    players_town.playerno = 57
where players.playerno <> 57;

Test SQL here


Show that this is isomorphic to $\mathbb P^1(C)$

Question: Consider the curve
$$u^2+v^2+w^2= 0$$ in $\mathbb P^2(\mathbb C)$. How do I show it is isomorphic to $ \mathbb P^1 ( \mathbb C)$?
Comment: This equation is not homogeneous, perhaps you meant $w^2$ in place of $w^3$?
Answer: The required isomorphism from $\mathbb P^1$ to the conic $V\subset \mathbb P^2$ with equation $u^2+v^2+w^2=0$  is :$$f: \mathbb P^1\stackrel \cong \to V:[x:y]\mapsto [u:v:w]=[2xy:y^2-x^2:i(x^2+y^2)]$$
Edit
The inverse isomorphism $f^{-1}:V\stackrel \cong \to \mathbb P^1$ is given by : \begin{cases}
&f^{-1}([u:v:w])=[x:y]=[u:v-iw]\quad \operatorname {if} \quad[u:v:w]\neq [0:1:-i]=:\omega \\
&f^{-1}(\omega)=[1:0]\\
\end{cases}
The isomorphism $f^{-1}$ is the projection of the conic $V$ from its point $\omega$ onto the line $w=0$ identified with $\mathbb P^1$ via $[x:y:0]\leftrightarrow[x:y]$, and all the calculations leading to the formulas above were dictated by this geometric picture.


What is the likelihood that a degree 3 monic polynomial will have 3 real roots.

Question: The discriminant of a monic cubic polynomial $x^3 + bx^2 + cx + d $ is given by the expression $b^2 c^2 - 4 c^3 - 4 b^3d + 18 bcd - 27 d^2$. If this expression is positive then all the roots are real. Right?
I did some experiments in Mathematica with random monic cubics whose coefficients are in the interval $[-n,n]$.  It appears that as $n$ gets bigger the likelihood that the discriminant is positive increases. Here is a list of the number of random monic cubics with positive discriminant from a sample of 1000 where the coefficients are in the interval $[-10^k, 10^k]$ for $k = 1,2,...,15$.
$\{432, 560, 601, 620, 616, 634, 638, 627, 620, 618, 631, 617, 618, 630, 648\}$.
Does the likelihood go to some limit?
Answer: The dominant terms are $b^2c^2$ and $4b^3d$ because they are the only terms that are around $N^4$, instead of $N^3$ or smaller.
The chance that $b^2c^2-4b^3d>0$ equals the chance that $c^2>4bd$.
This includes the $50\%$ chance that $bd<0$.
Now suppose $b,c,d$ are all positive.  Let $b=Nx$, $c=Nz$, $d=Ny$, so $x,y$ and $z$ are all between $0$ and $1$.
First, suppose $b$ and $d$ are fixed.  The chance that $c^2>4bd$ equals the chance that $2\sqrt{bd}<c<N$, or $2\sqrt{xy}<z<1$.  It equals zero if $2\sqrt{xy}>1$, otherwise it equals $1-2\sqrt{xy}$.
To get the overall probability, I average over all possible values of $b$ and $d$.  Equivalently, I integrate over $x$ and $y$.
$$B=\int_0^1\int_0^1 \max(0,1-2\sqrt{xy})\, dx\,dy\\
=\int_0^{1/4}\int_0^11-2\sqrt{xy}\,dx\,dy+\int_{1/4}^1\int_0^{\frac1{4y}}1-2\sqrt{xy}\,dx\,dy\\
=\int_0^{1/4}1-\frac43\sqrt{y}\,dy+\int_{1/4}^1\frac1{4y}-\frac43\sqrt{\frac1{64y^2}}\,dy\\
=\frac14-\frac19+\frac1{12}\log(y)_{1/4}^1=\frac5{36}+\frac{\log2}6$$
I broke it into two pieces at $y=1/4$ because $1-2\sqrt{xy}$ is always positive if $y<1/4$ and $0<x<1$.
The overall chance is then $50\%+50\%B=0.6272$.
Remark: This is the same value as Travis' calculation The probability that a random (real) cubic has three real roots for a general quadratic where the leading coefficient is also between $-N$ and $N$.  I expect that is because the $x^3$ term tends to be negligible if $x$ is one of the two roots of the quadratic.
Comment: Thanks! I do not understand your analysis.  I realize that you cannot explain the entire argument but maybe you could tell me what you mean by "Replace b with Nx , d with Ny.  What does Nx and Ny mean?  Is there some reference that you could recommend to help me learn how to solve problems of this nature?  Also, I ran a simulation with 100,000 random cubics with coefficients in [-10^15,10^15] and sure enough 62749 had a positive discriminant.  Thanks again.


Find all eigenvalues of a matrix that holds $A = A^{5}$

Question: I need to find all eigenvalues of a matrix that holds $A = A^{5}$. I have no idea where to start. Any directions please?
Comment: The fileld is $\Bbb C$ or $\Bbb R$?
Comment: If $P$ is a polynomial such that $P(A)=0$, then the eigenvalues of $A$ must be roots of $P$.
Comment: the field is $c$
Comment: It's not possible to find the eigenvalues  of  $A$ exactly, given just that $A^5=A$. _Exactly_ what does the question ask you to do?
Comment: You can't really find *all* the eigenvalues; what you can prove is, at most, that the eigenvalues live in the set of roots of $\lambda^5=\lambda$.  For instance, the zero matrix satisfies the condition, but its only eigenvalue is $0$.
Answer: Hint. Any eigenvalue $\lambda$ of $A$ will solve the equation $\lambda^5=\lambda$ because
$$0=(A^{5}-A)v=(\lambda^5-\lambda)v$$
where $v$ is an eigenvector with respect to $\lambda$.
Answer: Hint:
$$
\lambda^5-\lambda=0 \quad \iff \quad \lambda(\lambda-1)(\lambda+1)(\lambda^2+1)=0
$$


Erro ao fazer deploy no servidor glassfish

Question: Projeto não rada no servidor apos deploy.  glassfish 4.1
Projeto cdi, jsf,primefaces,jpa

Erro de sistema: WELD-000335: Context is already active java.lang.IllegalStateException: WELD-000335: Context is already active at org.jboss.weld.context.AbstractConversationContext.activate(AbstractConversationContext.java:233) at org.jboss.weld.jsf.WeldPhaseListener.activateConversations(WeldPhaseListener.java:108) at org.jboss.weld.jsf.WeldPhaseListener.beforePhase(WeldPhaseListener.java:85) at com.sun.faces.lifecycle.Phase.handleBeforePhase(Phase.java:228) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:99) at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:121) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282) at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545) at java.lang.Thread.run(Thread.java:745)

<dependency>
    <groupId>org.jboss.weld.servlet</groupId>
    <artifactId>weld-servlet</artifactId>
    <version>1.1.10.Final</version>
    <scope>compile</scope>
</dependency>

Comment: O weld que você utiliza é do glassfish certo? provided? tem algum PhaseListener na aplicação executando algum procedimento no startup?
Comment: Dilnei, não sei dizer. Não sabia que existe uma versão para o glassfish. Estou usando essa dependência:
'
org.jboss.weld.servlet
weld-servlet
1.1.10.Final
compile
''
Comment: É que assim brother, o servidor é javaEE full então ele implementa uma versão da spec JavaEE que é JavaEE 7, esses servidores são diferentes dos servlets container, eles ja tem o CDI nativo, faz assim: remove esta dependência e declara a API do CDI, assim:

```
javax.enterprise
cdi-api
provided
```
Comment: Obrigado Dilnei! vou fazer isso. Posto o resultado
Comment: Dilnei, deu certo.Mais uma vez muito obrigado!!
Comment: De nada Sidnei, parabéns por ter conseguido, abração.
Comment: @DilneiCunha é legal que inclua uma resposta à pergunta, o OP pode aceitá-la, ajudando outros que possam ter o mesmo problema :)
Comment: Ok @Bruno César, adicionado como resposta, quando não há uma resposta o post seria deletado? tem alguma doc sobre o uso do markdown aqui nos comentários? pois muitos comandos não funcionam, outro dia também tentei uma edição pós 5 min. e não foi possível, achei ruim esta parte, no geral gostei muito deste fórum, eu venho lá do GUJ, mas confesso que vocês estão anos luz a frente deles, gosto da seriedade do stack, das respostas que muitas veses são bem científicas e sem aquele monte de discução inútil que não possui embasamento técnico algum, de qualquer forma, Parabéns a todos.
Answer: Quando utilizamos servidores javaEE full não precisamos declarar de forma explicita a lib do weld(compile), pois o servidor já implementa uma das versões do JavaEE, esses servidores são diferentes dos servlets container, eles já possuem o CDI nativo, então a solução é:
Remova esta dependência:
<dependency>
    <groupId>org.jboss.weld.servlet</groupId>
    <artifactId>weld-servlet</artifactId>
    <version>1.1.10.Final</version>
    <scope>compile</scope>
</dependency>

e adicione a API do CDI como provided, ex:
<dependency>
    <groupId>javax.enterprise</groupId>
    <artifactId>cdi-api</artifactId>
    <scope>provided</scope>
</dependency>


How do I test the Convergence/ divergence of this series?

Question: Given series is $$\sum U_n=\sum_{n=1} ^\infty \frac{n^3-n+1}{n!}$$
I need to test its convergence.
I thought about using ratio test for the same but I am stuck on how to proceed after I reach a step where:
$$\lim_{n\to\infty}\frac{U_n}{U_{n+1}}=\lim_{n\to\infty}\frac{(n^3-n+1)(n+1)}{(n+1)^3-n}=\to\infty$$
How do I proceed from here? Some guidance would be appreciated
Comment: Your ratio test is flipped!
Comment: This is a overly trivial question for a ~4k user. You should be able to check by yourself that $\sum_{n\geq 1}\frac{n^k}{n!}$ is an absolutely convergent series for any $k\in\mathbb{N}$. Maybe compute its value, too.
Answer: You idea is correct but you computed the limit of the inverse of the quotient in ratio test.
This is the real relation:

$$\frac{U_{n+1}}{U_n} \rightarrow 0<1$$ thus the series converges.
Answer: $$\begin{align}\sum U_n=\sum_{n=1} ^\infty \frac{n^3-n+1}{n!}\\=\sum_{n=1} ^\infty \frac{(n-1)n(n+1)}{n!}+\sum_{n=1} ^\infty\frac{1}{n!}\\=\sum_{n=2} ^\infty\frac{n+1}{(n-2)!}+\sum_{n=1} ^\infty\frac{1}{n!}\\=\sum_{n=3} ^\infty\frac{1}{(n-3)!}+\sum_{n=2} ^\infty\frac{3}{(n-2)!}+\sum_{n=1} ^\infty\frac{1}{n!}\end{align}$$
Clearly you can see each of these sums converges.


AutoMySQLBackup: Create a single file for each database

Question: I'm backupping my databases with automysqlbackup.
This works fine - but unfortunately I do not get a single file for each database but a cumulative file called
daily_all-databases_2016-04-15_12h01m_Friday.sql.gz
.
├── daily
│   └── daily_all-databases_2016-04-15_12h01m_Friday.sql.gz
├── latest
├── monthly
├── tmp
└── weekly

I would like to get a single archive for each database.
How can I do that?
Answer: You should be able to use the SEPDIR config parameter. It will create separate directories for each database, with an own file inside of it.
From the Ubuntu manpage (but should work on CentOS just the same):

SEPDIR=yes
  Separate backup directory and file for each DB? (yes or no)

Alternatively, it's very simple to write up a bash script yourself that does this. Something like this should do:
mysql -u user -p pass -B -e "SHOW DATABASES"|sed 1d|while read db
do
    mysqldump -u user -p pass $db|gzip>"/home/db_backup/$db.sql.gz"
    if [[ $? != 0 ]];then
        echo "Backup of database $db FAILED!"
    fi
done

Obviously replace user and pass with their respective values.
Comment: Didn't see the `sepdir` parameter on my install, but doing this manually with just `mysqldump` would ignore the advantage of `automysqlbackup` in the form of incremental backups with automatic rename and deletion of old files.
Comment: @Sven True, it's just an illustration of very simple dumping script. It's just an alternative in case the sepdir parameter doesn't offer what OP is looking for.


Diminished and augmented key signature

Question: Now I know that augmented chords and diminished chords are dissonant normally. Arpeggiate it and it is much more consonant. 3rd octave and it is much more consonant.
But can you actually have something in the key of C augmented? If so would it be based on this scale: C C# D# E F G G# B C which is an octotonic scale similar to the diminished scale except it is based off of augmented chords instead of diminished?
This would have all of the first four sharps except for F#.
Likewise can you have something in the key of C diminished? If so would it be based off of the diminished scale?
Comment: There are no diminished or augmented keys in standard usage.  https://www.hearandplay.com/main/there-are-no-diminished-and-augmented-keys
Answer: It's not a standard usage. There are 12 keys (or a few more due to treating C# and Db as different.) Keys have two modes, major and minor.  Other tonal organizations are possible but the usual (CPP) terminology isn't used in their descriptions.
The term "key" is not synonymous with scale. Scale (from the Italian for "ladder") is a collection of notes taken in ascending (or descending) order. Key tends to refer to the harmonic relationships used in a composition. The usual terminology doesn't really apply well to music outside the Common Practice Period.
Comment: Keys have two modes is an inaccurate wording. Keys are classified into two distinct concepts which are _major_ or _minor_. Both major an minor have seven modes which predate the concept of key which is why when we talk about modes we talk about Ionian and Aeolian instead of major and minor.
Comment: You have keys that range from zero to seven sharps and flats. It would be more accurate to say there are 14 keys.
Comment: @NeilMeyer - would that extrapolate to 28 with respect to minors too? 14 key signatures, maybe?
Comment: @Dom - we talk about Ionian and Aeolian for modes not because they predate the concept of key, but because Heinrich Glarean (the father of "modal theory") decided they should have Greek names like the church modes.
Answer: Olivier Messiaen (1908-1992) did exactly that. If you add A to your scale, you complete the augmented triad F A C#. Your scale now contains 9 pitches per octave. This set of 9 is exactly the same as that of one of Messiaen's modes of limited transposition, specifically mode 3. The set of 9 pitches yields 3 modes: which mode you get depends on which pitch you start a scale on. In your example, with A added to your scale, the intervals go STSSTSSTS. The example in wikipedia goes TSSTSSTSS, and the other mode goes SSTSSTSST.
Messiaen used it a lot in Un reflet dans le vent from his early collection of Preludes for piano.
As for your idea of a scale of C diminished: if you combine diminished chords on C and G you get the scale C C# D# E F# G A Bb. This is Messiaen's mode 2. Messiaen used this in many of his works (including that Prelude, briefly). It also crops up in works by some earlier composers, e.g. this chord-sequence over a pedal G in "Le Gibet" from Ravel's Gaspard de la nuit.
Answer: "C diminished" could be Locrian C (C Db Eb F Gb Ab Bb) which has a lowered 5th (probably tricky to use, on account of <C Eb Gb> being dissonant) and lowered 2nd scale degree (easier to handle, see the Neapolitan chord for common uses, or consider the Db as borrowed from the subdominant Aeolian F) as compared to the Aeolian C mode (C D Eb F G Ab Bb a.k.a. C minor).
Answer: Short answer: yes and no.
No, it's not at all a standard usage. There are no augmented and diminished key signatures.
Yes, you can do whatever you want. Microtones, even... it's all cool. So if you have a need for this, you certainly can do it.
Some scales will fit these chords better. I don't quite follow your augmented scale idea... it would make more sense written in flats perhaps... but I'm not sure why you have F,G against the G# of the augmented chord... just seems a bit odd to my ear but I'm just imagining not playing it aloud. Lydian can work over an augmented chord, but be careful of that 5th.
on the other hand, a whole tone scale would fit the bill easily... for the diminished, locrian will make sense. Both of these scales leave you out in the middle of nowhere tonally because there's no perfect fifth, but that's also the idea.
Key understanding: diminished chords are highly dissonant and demand resolution. Augmented chords are very ambiguous. Two very different animals.
Comment: Not really, @user5747140. Common practice tended to see both as needing resolution, but *both* are highly ambiguous. When you get down to the actual levels of dissonance, diminished chords are very mildly dissonant at best - the diminished fifth is more ambiguous than dissonant. It was the extreme ambiguity that required resolution.
Comment: I'd have said the opposite with regard to your last para.
Comment: The weight of CP usage certainly agrees with what I wrote.
Answer: For theory which deals with music using the common harmonic vocabulary from about 1700 to mid 1800s, the keys are: C major, D major, E major, F major, G major, A major, B major, F# major, C# major, F major, Bb major, Eb major, Ab major, Db major, Gb major and Cb major.  Also the minor keys of all the above, that is, C minor, D minor, etc. Total 32 keys.
There is a scale corresponding with each of the major keys and 2 standard versions with each of the minors (harmonic and melodic).    Each scale has a basic triad (3 note chord) formed on each note of the scale and the triads are either major, minor, diminished or augmented.
The vast majority of modern popular music sticks with this system because it is what most people generally grow up hearing.  Most people never hear anything else. You CAN do anything you want, but the further from the common practice vocabulary you go, the smaller your audience becomes.
Comment: Recount your number of keys, you've written F major twice.

Diminished and augmented key signature