how to update a field schema

Question: I am trying to add a field (middle name) into the field_schema of the contrib addressfield module (I initially didn't want to hack it, but was unsucessful in adding a field in from my custom module.). The module has the following hook_field_schema()
function addressfield_field_schema() {
  $columns = array(
    'country' => array(
      'description' => 'Two letter ISO country code of this address.',
      'type' => 'varchar',
      'length' => 2,
      'not null' => FALSE,
      'default' => '',
    ),
    'administrative_area' => array(
      'description' => 'The administrative area of this address. (i.e. State/Province)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'sub_administrative_area' => array(
      'description' => 'The sub administrative area of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'locality' => array(
      'description' => 'The locality of this address. (i.e. City)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'dependent_locality' => array(
      'description' => 'The dependent locality of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'postal_code' => array(
      'description' => 'The postal code of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'thoroughfare' => array(
      'description' => 'The thoroughfare of this address. (i.e. Street address)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'premise' => array(
      'description' => 'The premise of this address. (i.e. Apartment / Suite number)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'sub_premise' => array(
      'description' => 'The sub_premise of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'organisation_name' => array(
      'description' => 'Contents of a primary OrganisationName element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'name_line' => array(
      'description' => 'Contents of a primary NameLine element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'first_name' => array(
      'description' => 'Contents of the FirstName element of a primary PersonName element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'last_name' => array(
      'description' => 'Contents of the LastName element of a primary PersonName element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'last_name' => array(
      'description' => 'Contents of the LastName element of a primary PersonName element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'data' => array(
      'description' => 'Additional data for this address.',
      'type' => 'text',
      'size' => 'big',
      'not null' => FALSE,
      'serialize' => TRUE,
    ),
  );

  return array(
    'columns' => $columns,
    // TODO Add indexes.
  );
}
I found this post online for doing a field_schema update https://drupal.org/node/150215, but I don't know what the field name or table name is, its not listed in the file.
How can I do this?
My ultimate goal is to make a standalone plugin file to be used by addressfield, but I needed to update the schema first.
Answer: The field will be named whatever you named it when you added it. If you can't remember, go to the "Manage fields" UI page for the relevant entity type/bundle and you'll be able to find it there.
The table names will be based on that field name; if the field is called field_my_field then the two database tables are:

field_data_field_my_field
field_revision_field_my_field
Comment: oh, so in my case, I am using drupal commerce and it created an addressfield with the machine name commerce_customer_address, and the table name field_data_commerce_customer_address, and I do see all those columns there. So when I do this update, its only for that instance of the field? it won't exist for other addressfields (ie: I have another named membership), unless I do the update on both field instances?
Comment: No, stop!! Fields are global; _instances_ of those fields are not. It's not possible to have a type of field which has different columns depending on what it's attached to. That would be the use case for a new field type altogether. Your DRY sensibilities might be alarmed at that, but that's how things are in Drupal 7
Comment: Sorry, thats not what I meant. I meant that the addressfield module creates a field type 'postal_address'. I am creating different instances of that field type. Would there still be the same columns?
Comment: Yes - the columns that make up a field are global. So if you add a new column, every entity/bundle that attaches that field type will potentially (important word there) have that extra column. However, I guess you can control the widget form based on the entity/bundle combination, and just not render the input control for that column when it's not appropriate.
Comment: So, when using fieldname in db_add_field, I could really use any instance of the field_type 'postal_address' and it would do the same thing?

how to update a field schema


Show that no non-constant polynomial can generate only prime numbers

Question: This problem is taken from "Mathematics for Computer Science" (Lehman, Leighton, Meyer, 2018).
Problem

For $n = 40$, the value of the polynomial $p(n) := n^2 + n + 41$ is not prime, as noted in Section 1.1. But we could have predicted based on general principles that no non-constant polynomial can generate only prime numbers.
In particular, let $q(n)$ be a polynomial with integer coefficients, and let $c:=q(0)$ be the constant term of $q$.
(a) Verify that $q(cm)$ is a multiple of $c$ for all $m \in \mathbb{Z}$.
(b) Show that if $q$ is nonconstant and $c > 1$, then as $n$ ranges over the nonnegative integers $\mathbb{N}$ there are infinitely many $q(n) \in \mathbb{Z}$ that are not primes. Hint: You may assume the familiar fact that the magnitude of any nonconstant polynomial $q(n)$ grows unboundedly as $n$ grows.
(c) Conclude that for every nonconstant polynomial $q$ there must be an $n \in \mathbb{N}$ such that $q(n)$ is not prime. Hint: Only one easy case remains.

Solution attempt
(a) The polynomial can be expressed as $q(n) = c + a_1n + a_2n^2 + \cdots + a_kn^k$. So, $q(cm) = c + a_1cm + a_2c^2m^2 + ... + a_kc^km^k$. Since all terms of $q(cm)$ are divisible by $c$, $q(cm)$ is a multiple of $c$ for all $m \in \mathbb{Z}$.
(b) As $n$ ranges over the nonnegative integers, it will range over infinitely many values of the form $n=cm$ ($m \in \mathbb{Z}$). As shown in (a), for each $n=cm$, $q(cm)$ is a multiple of $c$. Therefore, assuming that the magnitude of $q(n)$ grows unboundedly as $n$ grows, this means that $q(n)$ will take infinitely many non-prime values.
(c) Item (b) covered the cases where $c > 1$. For nonconstant $q$, two cases remain: $c < -1$ and $-1 \leq c \leq 1$.

For $c < -1$, a similar argument to (b) applies: as $n$ ranges over the negative integers, it will range over infinitely many values of the form $n=cm$ (where $m$ is a negative integer). For each of these values, $q(n)$ is a multiple of $c$. Therefore, assuming that the magnitude of $q(n)$ grows unboundedly as $n$ grows, this means that $q(n)$ will take infinitely many non-prime values.

For $c -1 \leq c \leq 1$, $q(0) = c$ is an example of root that is not prime.

Therefore, for every nonconstant polynomial $q$, there must be an $n \in \mathbb{N}$ such that $q(n)$ is not prime.
Is this proof correct?
Thank you in advance.
Comment: You handle the cases  $c=\pm 1$ by arguing that $\pm 1 =p(0)$ is not prime.  That's ok, but in discussing this result it is more common to prove that $p(n)$ takes on infinitely many composite values.   After all, a polynomial that took on only prime values for sufficiently large $n$ would be almost as useful as one which only took on prime values.    You've almost done that, but you still have to show this in the case $c=\pm 1$.
Comment: A different approach. If $q(x)$ produces only prime numbers then $q(x+1)$, which can be written $q(x+1)=xp(x)+q(1)$ for some $p(x)$, produces only prime numbers.  Compute $q(nq(1)+1)$ and use the fact that $q(1)$ is a prime to conclude.
Comment: [this duplicate](https://math.stackexchange.com/questions/304330/proof-of-lack-of-pure-prime-producing-polynomials) and others you can easily find by searching might give you ideas if you get stuck on that last detail.
Comment: @lulu isn't it mentioned in part C that n belongs to only set of natural numbers? How can we put n=0 there?
Comment: @Alex Many people, including (apparently) the OP, say that $0\in \mathbb N$.  But, really, the important point here is that the goal is to show that $p(n)$ is composite for infinitely many natural numbers...not to just find a single composite $p(n)$.
Answer: I think your proof is fine.  As the commenters say, there are other proofs for it.  But it seems clear that the the scheme that the book set up intended for you to find the "easy case" that you found.


How do you play this chord from Étude 14 by Philip Glass

Question: I am learning Étude 14 by Philip Glass but I found a very weird combination of notes that I cannot play naturally (and unnaturally). Do I need to practice some weird finger stretching or there is something I could mix with left hand? I also tried (never done in my life) using only finger 1 to play both G and A-flat at the same time but it is not "natural", very uncomfortable and difficult to make it sound good.
Here is someone playing it but I cannot distinguish the fingers properly.
Minute 1:43

Edit
@Tim I had the impression you were really dissapointed for not being able to play the chord. I uploaded a video just for you to see how I solved my "physical limitation" by taking @Brian Chandler 's advise on using my thumb with two notes
Comment: I play this 1-1-2-5, with the thumb knuckle on the Ab and tip on the G. Your ability to do this will depend on the size of your thumb and the action of your piano. Try coming in from above the black keys with your hand higher than normal.
Answer: Finger numbers: G:1, Ab:2, C:3, G:5. It's a bit of a stretch but not impossible. The thumb-pinky distance is only 1 octave.
Something like this: (excuse the Behringer MS-1 synth)
Comment: Sadly, that is impossible for me. My pinky only reaches F. Played piano for 60yrs, and still can't reach that ! I'm sure I'm not alone.
Comment: @Tim How about if you try to do it with a bit of a diagonal twist and reach forward with your pinky about an inch over the key?
Comment: No chance! Just about reach the F# key, and by then, index is well up on the left of the C# key. I have a student who could reach the top G with their ring finger, but that's another story.
Comment: @Tim Still not sure if we're trying the same way. :) I added a picture.
Answer: You have four choices (in descending order of preference):

finger it 1,2,3,5 if your hand is big enough (the stretch might come easier with practice)
use your thumb on G and Ab (might also take some practice)
leave out the lower G
move on to another piece
Answer: Here are six solutions, offered in order of radicalness.

Play it 1-2-3-5, placing your hand away from your body and toward the back end of the keys. Twisting toward finger 1 or finger 5 will make the chord harder to play.

Since the 1-2-3-5 fingering isn't working for you, the next best option is to leave out the lower G. Since it's doubled at the octave -- and since that top G is more important to the overall sound -- it's a reasonable option to omit it and play the remaining Ab-C-G with 1-2-5. In conjunction with this, you could try adding a G to the left hand. It would sound an octave lower than the written G -- and the timing could prove challenging, but see if you like the sound of the chord re-voiced in this way.

Another option, but IMO less harmonically sound, is to omit the Ab. Here, too, since the Ab consistently appears in the left hand, it could be left out of the right. However, the strength of the right-hand dissonance between Ab and G is sacrificed with this option.

An option with even greater impact on the sound, would be to shift the left hand up one octave, allowing it more easily to pick up notes from the right hand. Obviously this is not how Glass wrote it, so a more radical solution. It can be musically justified by the difference in sound between the measures with right-hand arpeggiation versus right-hand block chords. The effect would be to further distinguish the measures from each other by making the left hand in the block-chord measures relinquish its roll as accompaniment and be more of a participant in the block chords. (The left hand would play the arpeggio measures in the octave written.)

Try taking advantage of the fact that the left and right hands alternate much of the time. In principle, the left hand could leap up to grab one or two of the lower right-hand notes in between playing its own part. Given the tempo of the piece and the overall demands on the left hand, this is unlikely to prove practical, but I include it here to foster flexibility and creativity in approaching fingering issues.

Finally, you could try rolling the right-hand chords. This is given as the last option, because it would change the stylistic meaning of the piece. As with the third option, you as the performer would be making a significant aesthetic decision as well as a practical one. Chord-rolling is standard fare in Romantic-era music, but that Romantic feel is unidiomatic (even antithetical) for Glass. That doesn't mean it would sound bad; it just means that when you make your Carnegie Hall debut, the newspaper critics might complain.
Comment: Unless you have quite big hands 1-2-3-5 is likely to be an unhealthy stretch.
Answer: There is another way to the good suggestions above: play the G and Ab with your thumb. There are even two ways of doing this; first thing I thought of was to play the Ab with the tip of your thumb, and the G with the second joint. This requires practice to avoid smudging, and depends on the thickness of your thumb. It also leaves quite a big stretch to the top G. The second way is to use the tip of your thumb on the G and Ab; you sort of wedge it in the corner, so the left side presses the white key, and the right side presses on the top left corner of the black key. This sort of unorthodox fingering is plausible, I think, because of the nature of the music, with repeated chords. Please give it a try!
Comment: I don't know how to play the Ab with the thumb tip and the G with a knuckle without completely losing my ability to play the high G (especially since my hands can only span an octave max accurately). I need to play both notes like your second method.


'System.OutOfMemoryException' was thrown

Question: While Compiling the WPF Application for many times in a day it give following error
'Exception of type 'System.OutOfMemoryException' was thrown.'
Can anyone know why this error occured and how to remove that error.
But if visual studio is restarted then there is no such problem.
thanks in advance
Comment: Not quite enough information to answer...
Comment: But you can ask for further information if you don't understand the question. I think there is no need to give -ve marking . What more information you need ????
Comment: Is there anymore info in the build log? you seem to have only provided one line...is your Studio Service Packed? Are you using any third party code?
Comment: This the the exception which is given in the Description of the error window.
Comment: From the View menu, pick 'output', or use CTRL+W,O to show the output window. In the output window, select 'Build' in the Show output from dropdown. VS will now display progress of the build process which may give you some clue as to what aspect of the build may be causing the memory leak.
Answer: It could be that your compiler has a memory leak, or that a plugin of your compiler has a memory leak.
There is not your fault, though. It's most probably your compiler's fault. You are encouraged to reproduce the problem and send it to your compiler vendor for a detail investigation.
Answer: This happens to me frequently with visual studio 2008. I just assume there's a memory leak somewhere due to poor coding on Microsoft's part. Whenever i see this error I close down and reopen visual studio and it compiles without a hitch.
Comment: My code is not at all bug free. Nobody's is, and I think that's the point..

My code is not yet running, visual studio is. The out of memory error was caused by visual studio running out of memory while trying to *compile* my code. This error goes away when visual studio is closed and reopened. This series of events show that a memory leak on Visual Studio's part (or an associated tool) is the most likely scenario.
Comment: Ah, I guess the "poor coding" bit was uncalled for. Creating a compiler as large as Visual Studio can not be easy, so I apologize for that comment. The Microsoft Engineers I have meet are all top notch. Do I still believe the problem lies in visual studio? Yes. Do I believe that is a sign of poor coding? No, it's a sign of not being perfect, which no one is.
Answer: It sounds like you are saying that after compiling a WPF application many times in Visual Studio you receive an OutOfMemoryException error.  Can you elaborate further on where exactly this error shows up?

In the Designer
In the output window
etc ...

It's possible that there is a bug in either a 3rd party hosted control on the designer or in Visual Studio itself.  If you are not using any 3rd party controls then I encourage you to file a bug on connect for the issue.

http://connect.microsoft.com
Answer: Is your machine up to the minimum specification for developing WPF applications
Comment: The OP problem is that the `OutOfMemoryException` was thrown when the machine was compiling the code many times over, so it's more likely a memory leak issue rather than machine spec issue
Comment: Agreed, but VS will run in machines of lower spec than the recommendation. While it appears to work it will cause OOM exceptions eventually. The question is too vague and there is not enough information provided for anyone to answer...


Illegal choice error in log file

Question: I got this error in my log file.  It was on a select element for an exposed View filter:
Illegal choice 24alert(0) in field_item_type_tid element.
Is it someone trying to hack my site?
Answer: Someone (or something) is trying to submit a value for field_item_type_tid that isn't in the list of allowed options for that field (as prepared by the form API prior to rendering the form/element).
The FAPI is objecting to that attempt (as it should; it's a security feature), so the user will receive the standard "Illegal choice" error message.
It might be an attempt at a hack, it might be something weird instigated by a user/browser extension, or it might be the result of some javascript trying to change the allowed values on the client-side, without informing the backend that the options need to change.
Without analysing the page and all the involved parameters it's only speculation, though. It might be being caused by any of the above, or perhaps some other external factor.
Comment: Thanks Clive.  It was a select drop down list of specific, and somehow several attempts at stuffing some JavaScript as a parameter for the filter of that view, so it looks like a hack attempt.  I blocked the IP address.

Illegal choice error in log file


How to classify unseen data as anomaly

Question: I trained a CNN model with 6 different classes (labels are 0-5) and I am getting more than 90% accuracy out of it. It can correctly classify the classed. I am actually trying to detect anomaly with it. So what I want is, if any data comes which my model has never seen before or never been trained on similar data then it will be classified as anomaly while the other data point will be classified normally (from 0-5) same as before. I do not have any abnormal data to train my model, I just have the normal data. So the rule would be, if any incoming data point does not belong to any of the six classes then it is anomaly.
How can I do it?
Comment: Is this image data, or another kind of data?
Comment: It is Image data.
Comment: Is the goal only to do anomaly detection, or to do joint classification (for known classes) and anomaly detection (for out-of-distribution inputs)?
Comment: Only anomaly detection will do. Classification for known classes are not necessary.
Answer: In a typical CNN there is a layer where all the data is merged into a 1d-vector, just before the classifier that maps onto classes. This vector representation ("embedding") can be used to create an "out-of-distribution" detector. This can be done by applying a standard outlier detection method to those vectors, for example Local Outlier Factor. Or even train a reconstructing autoencoder.

How to classify unseen data as anomaly


In the midasr package in r, how is the AR* model different than the AR model?

Question: At the end of the ?midas_r documention example what is the fourth parameter option in the mls() of the lagged dependent variable "*" doing that is different that the "regular" AR(1) model above?
I've searched through the documention and online and can't seem to arrive at an answer as to what it's doing exactly.
<code>.
.
.
##Fit AR(1) model
mr_ar <- midas_r(y.ar ~ trend + mls(y.ar, 1, 1) +
             fmls(xx, 11, 12, nealmon),
             start = list(xx = rep(0, 3)))

##First order MIDAS-AR* restricted model
mr_arstar <-  midas_r(y.ar ~ trend + mls(y.ar, 1, 1, "*")
                 + fmls(xx, 11, 12, nealmon),
                 start = list(xx = rep(0, 3)))
</code>
Answer: Pretty sure I found out what it is.
It's the Smooth Transition Autoregressive (STAR) model.
Not entirely sure how this works within the MIDAS context and because the MIDAS documentation on this practically non-existent for this I can't read to discover what the midasr package is doing exactly.


ember build fails, no such file or directory lstat ...funnel-input_base_path-XXX.tmp/0//index.html

Question: The file it tries to find doesn't exist and neither does the
funnel-input_base_path-XXX.tmp folder.
It's no use to create one manually as the XXX part is randomly generated.
<code>[folatt@ArkOS_Dev genesis]$ ember build
(node:22373) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
WARNING: Node v6.2.1 has currently not been tested against Ember CLI and may result in unexpected behaviour.
version: 1.13.13
Could not find watchman, falling back to NodeWatcher for file system events.
Visit http://www.ember-cli.com/user-guide/#watchman for more info.
Build failed.
ENOENT: no such file or directory, lstat '/home/folatt/workspace/arkos/genesis/tmp/funnel-input_base_path-mFnZOm63.tmp/0//index.html'
Error: ENOENT: no such file or directory, lstat '/home/folatt/workspace/arkos/genesis/tmp/funnel-input_base_path-mFnZOm63.tmp/0//index.html'
    at Error (native)
    at Object.fs.lstatSync (fs.js:976:18)
    at symlink (/home/folatt/workspace/arkos/genesis/node_modules/symlink-or-copy/index.js:60:26)
    at Function.symlinkOrCopySync [as sync] (/home/folatt/workspace/arkos/genesis/node_modules/symlink-or-copy/index.js:55:5)
    at Funnel._copy (/home/folatt/workspace/arkos/genesis/node_modules/ember-cli/node_modules/broccoli-funnel/index.js:398:19)
    at Funnel.processFile (/home/folatt/workspace/arkos/genesis/node_modules/ember-cli/node_modules/broccoli-funnel/index.js:381:8)
    at Funnel.applyPatch [as _applyPatch] (/home/folatt/workspace/arkos/genesis/node_modules/ember-cli/node_modules/broccoli-funnel/index.js:298:12)
    at Funnel.<anonymous> (/home/folatt/workspace/arkos/genesis/node_modules/ember-cli/node_modules/broccoli-funnel/index.js:250:10)
    at Array.forEach (native)
    at Funnel.processFilters (/home/folatt/workspace/arkos/genesis/node_modules/ember-cli/node_modules/broccoli-funnel/index.js:249:9)
</code>
ember-cli-build.js
<code>/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var Funnel = require('broccoli-funnel');

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    'ember-cli-selectize': {
      'theme': 'bootstrap3'
    }
  });

  // Use `app.import` to add additional libraries to the generated
  // output files.
  //
  // If you need to use different assets in different
  // environments, specify an object as the first parameter. That
  // object's keys should be the environment name and the values
  // should be the asset to use in that environment.
  //
  // If the library that you are including contains AMD or ES6
  // modules that you would like to import into your application
  // please specify an object with the list of modules as keys
  // along with the exports of each module as its value.

  app.import('bower_components/moment/moment.js');
  app.import('bower_components/lightbox2/src/js/lightbox.js');
  app.import('bower_components/lightbox2/src/css/lightbox.css');
  app.import('bower_components/multiselect/js/jquery.multi-select.js');
  app.import('bower_components/multiselect/css/multi-select.css');
  app.import("bower_components/codemirror/lib/codemirror.css");
  app.import("bower_components/codemirror/lib/codemirror.js");
  app.import("bower_components/codemirror/mode/css/css.js");
  app.import("bower_components/codemirror/mode/htmlmixed/htmlmixed.js");
  app.import("bower_components/codemirror/mode/javascript/javascript.js");
  app.import("bower_components/codemirror/mode/markdown/markdown.js");
  app.import("bower_components/codemirror/mode/php/php.js");
  app.import("bower_components/codemirror/mode/python/python.js");
  app.import("bower_components/codemirror/mode/ruby/ruby.js");
  app.import("bower_components/codemirror/mode/shell/shell.js");
  app.import("bower_components/codemirror/mode/xml/xml.js");
  app.import("bower_components/font-awesome/css/font-awesome.css");
  app.import("bower_components/fira/fira.css");
  var fontAwesome = new Funnel('bower_components/font-awesome/fonts', {
      srcDir: '/',
      destDir: 'fonts'
  });
  var firaEot = new Funnel('bower_components/fira/eot', {
      srcDir: '/',
      destDir: 'assets/eot'
  });
  var firaOtf = new Funnel('bower_components/fira/otf', {
      srcDir: '/',
      destDir: 'assets/otf'
  });
  var firaTtf = new Funnel('bower_components/fira/ttf', {
      srcDir: '/',
      destDir: 'assets/ttf'
  });
  var firaWoff = new Funnel('bower_components/fira/woff', {
      srcDir: '/',
      destDir: 'assets/woff'
  });
  app.import("bower_components/lightbox2/src/images/close.png", {destDir: '/img'});
  app.import("bower_components/lightbox2/src/images/next.png", {destDir: '/img'});
  app.import("bower_components/lightbox2/src/images/prev.png", {destDir: '/img'});
  app.import("bower_components/lightbox2/src/images/loading.gif", {destDir: '/img'});
  app.import("bower_components/multiselect/img/switch.png", {destDir: '/img'});
  app.import('bower_components/bootstrap/dist/js/bootstrap.js');
  app.import('bower_components/bootstrap/dist/css/bootstrap.css');
  app.import('bower_components/bootstrap/dist/css/bootstrap.css.map', {
    destDir: 'assets'
  });
  app.import('bower_components/bootstrap-contextmenu/bootstrap-contextmenu.js');

  return app.toTree([fontAwesome, firaEot, firaOtf, firaTtf, firaWoff]);
};
</code>
package.json
<code>{
  "name": "genesis",
  "version": "0.7.1-3",
  "description": "Web management frontend for arkOS servers",
  "private": true,
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "start": "ember server",
    "build": "ember build",
    "test": "ember test"
  },
  "repository": "",
  "engines": {
    "node": ">= 0.10.0"
  },
  "author": "arkOS",
  "license": "GPLv3",
  "devDependencies": {
    "broccoli-asset-rev": "^2.2.0",
    "broccoli-funnel": "^0.2.8",
    "ember-cli": "1.13.13",
    "ember-cli-app-version": "^1.0.0",
    "ember-cli-babel": "^5.1.5",
    "ember-cli-content-security-policy": "0.4.0",
    "ember-cli-dependency-checker": "^1.1.0",
    "ember-cli-ember-uploader": "0.0.1",
    "ember-cli-htmlbars": "^1.0.1",
    "ember-cli-htmlbars-inline-precompile": "^0.3.1",
    "ember-cli-ic-ajax": "0.2.4",
    "ember-cli-inject-live-reload": "^1.3.1",
    "ember-cli-qunit": "^1.0.4",
    "ember-cli-release": "0.2.8",
    "ember-cli-selectize": "0.4.3",
    "ember-cli-simple-auth": "0.8.0",
    "ember-cli-simple-auth-token": "0.7.3",
    "ember-cli-sri": "^1.2.0",
    "ember-cli-uglify": "^1.2.0",
    "ember-data": "1.13.15",
    "ember-disable-proxy-controllers": "^1.0.1",
    "ember-export-application-global": "^1.0.4"
  }
}
</code>
As a side issue, why am I warned about watchman if it's an OS X program if I understand correctly and I'm using Arch Linux? [Solved]
As another side issue is the "re-evaluating native module sources is not supported" message. graceful-fs module isn't being used and installing it (to the latest version) does not make the warning message go away.
Comment: You can use [watchman](https://aur.archlinux.org/packages/watchman/)
Comment: Thanks! That solved one annoyance.
Comment: Is clearing the tmp (and maybed dist) folder is helping? Sounds like this folder got corrupted somehow.
Answer: I eventually went for upgrading all devDependencies, including ember.
I run into many deprecation problems, but at least I got out of this one.
Comment: Can you elaborate on upgrading devDependencies? I've been facing the same issue as above with my project. Thank you


What is the $hf_mig$ directory for in Windows Server 2003?

Question: What is the <code>$hf_mig$</code> directory for in Windows Server 2003, and can I delete it?
Answer: Its name means "hotfix migration".  It's for tracking versioning information about hotfixes to keep from accidentally breaking or downgrading your system.  No, you definitely should not delete it.
Answer: Here's a good explanation of the topic: What is the "$hf_mig$" Folder for And Can I Delete It?


Display link after complete countdown time

Question: I am using Field Timer module.
Is there any option to display a link after finishing countdown ?
Answer: Alternatively you can achieve that using the jQuery Countdown module
Example for development usage:
In this example, we display an alert box saying "You are done!" after counting down from 10...
<?php
  echo '
10 seconds!
';
  jquery_countdown_add(".countdown", array("until" => 10, "onExpiry" => "finished"));
  drupal_add_js("function finished() { alert('You are done!'); }", 'inline');
?>


What Can I Do When My App Is Rejected Due to Inconsistent App Signatures?

Question: I have integrated the HMS Core SDK for a game, and recently, and submitted a game update for review in AppGallery, but it is rejected because the app signature differs from that of my released game. Does anybody know the reason?
Comment: I'm voting to close this question because [Why can't I ask customer service-related questions?](https://meta.stackoverflow.com/questions/255745/why-cant-i-ask-customer-service-related-questions/255746#255746)
Answer: 1.Check whether the current app version is the same as the previous version.
View the fingerprint certificate in the project.
a. Open the CLI and run the keytool -list –v –keystore [file path] command.
b. Enter the keystore password.
c. View the current signing certificate fingerprint.

View the APK signature.
a.  Run keytool -printcert -jarfile xxx.apk (APK file path).
b.  The following information is displayed.

c.   You can view the SHA-256 certificate fingerprint of the current APK. Check whether this value of the two app versions is consistent.
Then check whether the two fingerprints are consistent with that in your project.

If the certificate fingerprints are inconsistent, this can be caused by two different reasons. The first one is that the two APKs have been packaged using different signature files. If they are inconsistent, you should first check whether the .jks or keystore files used for app signing in the project are consistent. Or, you can check whether you have used keystore files from different environments or platforms.
Example:

The .jks or keystore files used for the debug and release environments are different. You need to ensure that each .jks or keystore file matches the environment. For example, you cannot configure the .jks or keystore file in debug to the release environment.

If the .jks or keystore files are consistent, you need to check whether an automatic process has been used for packaging and signing. If so, check whether DEX file encryption has been used, which can lead to inconsistent signatures.


Only the first argument to query_posts() is used

Question: I'm probably missing something obvious here as i'm just learning php, but just wondering why only the first parameter works when I use query_posts
e.g here it uses $paged properly, but doesnt exclude categories..
query_posts('posts_per_page=5&paged=' . $paged, "cat=-16,-15,-14"   );

Here it is vice versa,
query_posts( "cat=-16,-15,-14", 'posts_per_page=5&paged=' . $paged   );

Is there are proper way i'm supposed to include these that im missing?
Thanks
Answer: I think you want:
query_posts('posts_per_page=5&paged='.$paged.'&cat=-16,-15,-14');

They way you have it you are calling query_posts with two arguments, when that function only takes a single one.
Comment: Thank you Nathan, that worked, just wondering what the purpose of the `&` before cat is? Sorry Im just eager to learn so I can start figuring this stuff out myself :)
Comment: The & is used to delimit(separate) the paramaters you want to pass in the string. In your example you actually have three paramaters: `posts_per_page`, `paged`, and `cat`. Take a look at http://en.wikipedia.org/wiki/Query_string, this is the same way that urls are constructed.
Comment: After you get used to making custom calls to query posts in Wordpress, I would highly recommend you switch over to [WP Query](http://codex.wordpress.org/Class_Reference/WP_Query) as there is a measurable performance increase, and it doesn't mess with any of the Wordpress Globals. [More information here](http://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts)
Comment: thanks maiorano84, I am still unsure of the difference between the two, but am going to read that now


Given Coordinates of Map

Question: type Coordinate = (XCoord, YCoord)
type XCoord = Coord
type YCoord = Coord
type Coord = Integer

coordInBound :: Coordinate -> Bool

coordInBound (XCoord, YCoord) =

XCoord

        |x >= 0 && x <= 9 = True
        |otherwise = False
YCoord

        |y >= 0 && y <= 9 = True
        |otherwise = False

I'm Trying to write a function that returns True if the coordinates are in a 10 by 10 grid from 0,0 -> 9,9
Answer: Since XCoord and YCoord are just integers, you can simply check if both are in range of [0, 9]:
type Coordinate = (XCoord, YCoord)
type XCoord = Coord
type YCoord = Coord
type Coord = Integer

coordInBound :: Coordinate -> Bool
coordInBound (x, y) =
  x >= 0 && x <= 9 && y >= 0 && y <= 9

main = print $ coordInBound (9, 0)

But if you wish XCoord and YCoord were types, then you'd need the following type definition and usage:
data XCoord = XCoord Int
data YCoord = YCoord Int
type Coordinate = (XCoord, YCoord)

coordInBound :: Coordinate -> Bool
coordInBound (XCoord x, YCoord y) =
  x >= 0 && x <= 9 && y >= 0 && y <= 9

main = print $ coordInBound (XCoord 9, YCoord 0)

Comment: `foo | condition = True | otherwise = False` can be shortened to just `foo = condition`.
Answer: Try breaking the problem into two pieces: Is the x coordinate in bounds? Is the y coordinate in bounds? And combining those together to figure out if they're both in bounds.
xInBounds :: XCoord -> Bool
xInBounds x | x >= 0 && x <= 9 = True
            | otherwise = False

yInBounds :: YCoord -> Bool
???

What you have right now won't compile because, among other things, the names of variables in patterns (XCoord, YCoord) can't start with capital letters. Names that start with capital letters in haskell are reserved for types like Coordinate and constructors like True. Variables have lower case names like coordInBound.
With xInBounds and yInBounds try to complete coordInBound using lower case variable names
coordInBound :: Coordinate -> Bool
coordInBound (x, y) = ???

Given Coordinates of Map


Porque o método index() não reconhece o redirecionamento [CI]?

Question: Estou acompanhando um curso e parei em um problema que não consigo resolver. Neste link é possível cadastrar um usuário e ao terminar o cadastro ele deveria ir para esta página mas a única coisa que acontece é um erro 404.
routes.php
$route['default_controller'] = 'dashboard';
$route['usuario/{:num}'] = "usuario/index/$1";
$route['404_override'] = '';

Usuario.php

TÁ INSERINDO NO BANCO

public function cadastrar()
{
    $data['nome']       = $this->input->post('nome');
    ...

    if( $this->db->insert('usuario', $data) ){
        redirect('usuario/1');
    } else {
        redirect('usuario/2');
    }

}

NÃO ESTÁ REDIRECIONANDO

public function index($indice=null)
{
    $this->load->view('includes/html_header');
    $this->load->view('includes/menu');
    if($indice==1){
        $data['msg'] = "Usuário foi cadastrado com sucesso";
        $this->load->view("includes/msg_sucesso", $data);
    } elseif ($indice==2) {
        $data['msg'] = "Não foi possível cadastrar o usuário. Tente novamente.";
        $this->load->view("includes/msg_erro", $data);
    }
    $this->load->view('listar_usuario');
    $this->load->view('includes/html_footer');

}

Os includes também estão corretos e por mais que não estivessem, acho que redireciona da mesma forma. Porque será não está redirecionando, está enviando essa página pro 404?
Answer: Verifica no arquivo config/config.php se o valor da chave base_url do vetor $config está definido corretamente de acordo com a url do seu site/sistema:
//Site local
$config['base_url'] = 'http://localhost/';

//Servidor remoto
$config['base_url'] = 'http://meusite.com.br/';

A função redirect do CI utiliza o valor configurado na $config['base_url'] para gerar a url para onde será redirecionado o sistema e caso ela esteja configurada de forma errada o sistema será redirecionado para uma página não existe e assim retornando o erro 404(Página não encontrada).


What Database Host Entry Should be used to Install Drupal on WAMP Server?

Question: I'm installing Drupal 7 on my Windows Server 2012 running WAMP.  Apache is listening on port 99.  I copied defaul.settings.php to settings.php and began the install process.
When I get to the database page, I enter the following in database host:
wamp/bin/apache/Apache2.4.4/bin/php.ini

I also supplied the correct MySQL credentials, created an empty Drupal database and verified that MySQL is running.
I receive the error:
Warning: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: No such host
is known. in DatabaseConnection->__construct() (line 304 of
C:\wamp\www\Drupal\includes\database\database.inc).
In order for Drupal to work, and to continue with the installation process, you must
resolve all issues reported below. For more help with configuring your database server,
see the installation handbook. If you are unsure what any of this means you should
probably contact your hosting provider.

Failed to connect to your database server. The server reports the following message:
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is
known. .

What must be done to get the install to talk to my database?
Comment: Why did I get -3 on this question?
Comment: Can you upload a screenshot of the database configuration page and the values you are entering?
Answer: Why would you enter the path to a php configuration file as the database host? You're running MySQL on the same server, correct? Then enter localhost or 127.0.0.1.
Comment: If you're trying to connect to MySQL, why would you specify Apache's port?
Comment: I tried localhost and also localhost:99 as that's the port on which Apache is listening. Both yield the same result.


What are the Pager and Hash plugins for lightGallery?

Question: I came across the Pager and Hash plug-ins for lightGallery: http://sachinchoolur.github.io/lightgallery1.2/docs/api.html#lg-pager
The docs tell how to enable them. But what are they for? What's their use?
Answer: As far as I know, the pager displays the 'current-image/total-images' in the upper left corner (ex. 4/34 on the fourth item).
The hash plug-ins creates unique URL's with hash(#) id's for every item(slide=) of the gallery or galleries(lg=).
Example: www.foo.com/bar/foobar.php#lg=1&slide=0.
Where 'lg=1' refers to the first gallery and 'slide=0' refers to the first item inside that (lg=1) gallery. Every item has it's own unique URL.
Comment: And also adds some dots which collide with the slider. This is not a "pagination" like i thought.


What is $\lim \sup_{n \to \infty} \sum_{k=1}^{n} (-1)^k \left(\frac{1}{2} -\frac{1}{k} \right)$?

Question:
Let $a_{n}=(-1)^n \left( \dfrac{1}{2} -\dfrac{1}{n}\right)$ and let $b_n=\sum\limits_{k=1}^{n} a_{k}, \forall \ n \in \mathbb{N}$.
Then what is $\lim \sup b_{n}$ and $\lim \inf b_{n}$?

$\begin{align}
\lim_{n \to \infty} b_{n} &= \sum_{n=1}^{\infty} (-1)^n \left( \frac{1}{2} -\frac{1}{n}\right)\\ &= \sum_{n=1}^{ \infty} (-1)^n \frac{1}{2} -\sum_{n=1}^{\infty}(-1)^n \frac{1}{n} \\ &=\sum_{n=1}^{\infty}(-1)^n \frac{1}{2} -\log 2
\end{align}$
So $\lim \inf b_{n}= \frac{-1}{2}-\log 2$ and $\lim \sup b_{n}= -\log 2$
Is it correct?
Answer: Seems like you committed a small mistake
\begin{align}
\lim_{n \to \infty} b_{n} &= \sum_{n=1}^{\infty} (-1)^n \big( \dfrac{1}{2} -\dfrac{1}{n}\big)\\
&= \sum_{n=1}^{ \infty} (-1)^n \dfrac{1}{2} -\sum_{n=1}^{\infty}(-1)^n \dfrac{1}{n} \\ &=\sum_{n=1}^{\infty}(-1)^n \dfrac{1}{2}+\log 2
\end{align}
Which implies that
as
$b_{2n}=\log 2+\frac{1}{2}$
$b_{2n+1}=\log 2-\frac{1}{2}$
$\lim \inf b_{n}=\log 2- \frac{1}{2}$
$\lim \sup b_{n}=\log 2 + \frac{1}{2}$
Comment: **Welcome to Mathematics Stack Exchange!** A quick [tour](https://math.stackexchange.com/tour) will enhance your experience. Here are helpful tips to [write a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question/9960#9960) and [write a good answer](https://stackoverflow.com/help/how-to-answer).


Why does getting an IP address throw an exception?

Question: Background:
My program starts up and it must obtain the IP address of the machine it is running on.
It is the "server" in a client-server architecture that receives incoming tcp-ip messages.
I should also add the machine :

Has multi-ip addresses available
Is running Windows 2008 R2 Server

Here is the code that obtains the IP address:
<code>    public bool IsNetworkAvailable
    {
        get
        {
            return System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
        }
    }

    public string thisIP { get; private set; }
    public void GetThisIP()
    {
        if (!string.IsNullOrEmpty(thisIP))
        {
            return;
        }

        thisIP = "*";

        if (IsNetworkAvailable)
        {
            using (System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket(
                System.Net.Sockets.AddressFamily.InterNetwork,
                System.Net.Sockets.SocketType.Dgram, 0))
            {
                socket.Connect("184.108.40.206", 65530);
                System.Net.IPEndPoint endPoint = socket.LocalEndPoint as System.Net.IPEndPoint;
                thisIP = endPoint.Address.ToString();
            }
        }
    }
</code>
Here is the error message:
<code>(0x80004005): A socket operation was attempted to an unreachable network 18.104.22.168:65530
at System.Net.Sockets.Socket.Connect(IPAddress[] addresses, Int32 port)
</code>
SOLUTION:
I have changed my code to what rodcesar.santos suggested in this:
Get local IP address
here is my (modified) code (and it works)
<code>            System.Net.NetworkInformation.UnicastIPAddressInformation mostSuitableIp = null;

            var networkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();

            foreach (var network in networkInterfaces)
            {
                if (network.OperationalStatus != System.Net.NetworkInformation.OperationalStatus.Up)
                {
                    continue;
                }

                var properties = network.GetIPProperties();

                if (properties.GatewayAddresses.Count == 0)
                {
                    continue;
                }

                if (mostSuitableIp != null)
                {
                    break;
                }

                foreach (var address in properties.UnicastAddresses)
                {
                    if (address.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        continue;
                    }

                    if (System.Net.IPAddress.IsLoopback(address.Address))
                    {
                        continue;
                    }

                    if (mostSuitableIp == null && address.IsDnsEligible)
                    {
                        mostSuitableIp = address;
                        break;
                    }
               }
            }

            thisIP = mostSuitableIp != null ? mostSuitableIp.Address.ToString() : "";
</code>
Comment: If it works on all but one machine, it's likely a problem with the machine itself, not the code.
Comment: There's obviously an issue with the setup on that machine preventing the socket from opening. Can you [just do this](https://stackoverflow.com/a/6803109/3608792) instead?
Comment: Can you ping that IP from the machine?
Comment: Dan Wilson : from your link, there is another entry "There is a more accurate way when there are multi ip addresses available on local machine. Connect a UDP socket and read its local endpoint" ... this is why I am doing what I am doing...
Comment: S. Monteleone - yes it pings just fine... (it's IP is 192.168.0.189 ... so it's within our local DNS )
Answer: After reading the accepted answer @ A socket operation was attempted to an unreachable host,
I assume that the specific client-computer than receives this error has a somewhat faulty network.
Quoting @Stephen Cleary

This error indicates that the network was not connected or not configured correctly. It is definitely an error on the client machine, not your server.
  There isn't much you can do to "solve" the problem. Pretty much all you can do is upgrade the client's network drivers and check for connection problems (maybe they're barely within wireless range, or the Ethernet cable is missing its locking tab).
Comment: I will check this out and research further... thanks
Comment: @user3174075 - If this turns out to be the answer, please don't forget to accept it.
Comment: @user3174075, is it possible that the problem computer does not have access to IP addresses not on the local network, due to a network, firewall, or antivirus configuration?  The hardcoded address in your sample code is not on the same subnet with the 192.168.0.189 address you gave in the comments. You also said the local computer has multiple addresses, are any of those on the same subnet as the hardcoded address?
Comment: no firewall, no anti-virus ...  what is strange is the code works on other machines...
Answer: <code>            System.Net.NetworkInformation.UnicastIPAddressInformation mostSuitableIp = null;

            var networkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();

            foreach (var network in networkInterfaces)
            {
                if (network.OperationalStatus != System.Net.NetworkInformation.OperationalStatus.Up)
                {
                    continue;
                }

                var properties = network.GetIPProperties();

                if (properties.GatewayAddresses.Count == 0)
                {
                    continue;
                }

                if (mostSuitableIp != null)
                {
                    break;
                }

                foreach (var address in properties.UnicastAddresses)
                {
                    if (address.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        continue;
                    }

                    if (System.Net.IPAddress.IsLoopback(address.Address))
                    {
                        continue;
                    }

                    if (mostSuitableIp == null && address.IsDnsEligible)
                    {
                        mostSuitableIp = address;
                        break;
                    }
               }
            }

            thisIP = mostSuitableIp != null ? mostSuitableIp.Address.ToString() : "";
</code>


repeated measures in irregular interval

Question: I have glucose measurements of some patients who are visiting in a hospital, which is measured over 4 years time. Each of the patients have more than one record every year. The interval between this records are not same.. i.e. multiple hemoglobin measures of patients in irregular intervals. Can someone please give me a hint on how to find annual mean of glucose measures of total patients. Which function can be used in R to perform this. Thanks
Answer: I would use lmer in the package lme4. You could then put the patient ID as a random effect.
http://www.inside-r.org/packages/cran/lme4/docs/lmer
Answer: This is arguably more of a question for SO, so it can be migrated.
Let's simulate [glucose] data for $3$ patients and $4$ years with missing values initially coded as 0 - we'll call it dat:
   years    p1    p2    p3
1      1 116.4 106.5  97.4
2      1 101.0 127.4 119.2
3      1   0.0 135.2 102.1
4      1   0.0 108.3 128.3
5      1   0.0 117.0 122.3
6      2 139.3 129.3 130.2
7      2  96.5 103.7 133.0
8      2 100.9 120.9 104.3
9      2   0.0   0.0 114.9
10     2   0.0   0.0  96.6
11     3 118.1 130.3 113.5
12     3   0.0 117.0 116.5
13     3   0.0 134.0 126.9
14     3   0.0   0.0 108.7
15     3   0.0   0.0  97.2
16     4 129.4 139.6 104.6
17     4 117.4   0.0 104.8
18     4 139.8   0.0 111.0
19     4 118.1   0.0   0.0
20     4  97.3   0.0   0.0

Before calculating, it is convenient to turn zeros into NA's:
dat[dat==0] <- NA; dat
   years    p1    p2    p3
1      1  95.8 138.2 122.2
2      1 111.2 117.2 100.6
3      1    NA 124.3 102.1
4      1    NA 115.6  95.7
5      1    NA 121.5 111.4
6      2 102.3 137.0 123.9
7      2 110.1 112.9 119.1
8      2 114.9 100.2  99.1
9      2    NA    NA 120.6
10     2    NA    NA 130.6
11     3 104.1 126.8 102.0
12     3    NA  99.9 131.3
13     3    NA 135.5 135.0
14     3    NA    NA 131.5
15     3    NA    NA 138.0
16     4 120.5 116.0 112.5
17     4 136.5    NA 136.1
18     4 124.6    NA 129.3
19     4  98.2    NA    NA
20     4 134.2    NA    NA

1. Annual mean per patient:
(mean_per_year <- round(aggregate(dat[,2:4], list(dat$years), mean, na.rm = T), 2))
  Group.1    p1     p2     p3
1       1 103.5 123.36 106.40
2       2 109.1 116.70 118.66
3       3 104.1 120.73 127.56
4       4 122.8 116.00 125.97

2. Annual mean across patients:
round(rowMeans(mean_per_year[,2:4]), 2)
[1] 111.09 114.82 117.46 121.59

3. Total mean:
round(mean(as.matrix(dat[,2:4]), na.rm = TRUE), 2)
[1] 118.01
Comment: Thanks Antoni, one doubt is, as the same patient has  multiple measurements, shouldn't we consider the correlation of values of same patient.
Comment: Just imagine every point trying to be the geometric center in the data cloud. Identical points would have double 'gravitational' force - count as two. Please check the 'accepted' mark on the side of my answer if it addresses you initial question.

repeated measures in irregular interval


How to route internet through VPN with Windows Server 2008 R2 on Amazon VPC?

Question: I have a server on Amazon EC2-VPC. I want to connect through VPN to it AND have all my internet traffic routed THROUGH this server, to guarantee my privacy.
I have two network interfaces on the server, one connected to the internet and one on private network.
VPN connections will get an IP address on the private network, and the server will need to act as a NAT to them.
Everything I find on the internet are guides to disable internet going through the VPN. I want it to go through it.
Thanks in advance.
Comment: What VPN software are you using?
Comment: @NathanC I am using default windows VPN, no additional software necessary (or wanted). I have been able to configure it half-successfully, though I need to set up DNS addresses manually. Will follow with an update on the question if I am able to resolve it.
Comment: were you able to get this done? I am trying to get this set up, could you possibly replay with what your setup was if you were? Thanks! (Cant comment on your original post due to user level)
Comment: @Bajan I have since give up to solve the DNS issues; I have reached a point where it works for my needs. What I needed to do was to first create the connection on the client, then go on the adapter configurations and manually add DNS servers there (I used Google's Public DNS, 126.96.36.199). In the server, what I did was just the default VPN configuration, following the wizards, setting up a NAT, etc. Since this post I have been really busy so no time to post a complete tutorial, but will do this in the other weekend.
Comment: @Bajan A little too late, but I have achieved a fully-working setup using the tutorials on this answer. http://serverfault.com/a/598486/142576
Answer: For future lurkers, I have been able to achieve a working setup by using SSTP and a WinServer 2012 Azure VM. These were the tutorials:
Setting up the server
http://blogs.msdn.com/b/lighthouse/archive/2013/07/30/how-deploy-sstp-and-l2tp-vpn-in-windows-azure-windows-server-2012.aspx
Setting up Vista/2008 clients
http://technet.microsoft.com/en-us/library/cc731352(v=ws.10).aspx


What is $\oplus$ in set theory?

Question: I always thought that $\oplus$ was an operator meaning "xor" in logic. Maybe it does, but how does it work for sets? I've got a question on an assignment due in an hour that asks me to define the set $A\oplus B^{c}$ where
$$\begin{align}U=\{1,2,3,4,5,6,7\}\\A=\{3,4,5,6\}\\B=\{1,3,5,7\}\end{align}$$
I only know of the intersect, union, and compliment operators currently. Not sure why he's asking this question when I don't recall him mentioning this at all in class.
Comment: This is a good example of why it is desirable to begin assignments well before the deadline, so that questions about notations/definitions/etc. can be asked with sufficient time left over to understand the concept once a clarification is received.
Comment: "a xor b" would probably mean items in either a or b but not in both (by definition, xor is (a\b)u(b\a)).
Comment: I sort of agree with @Tunococ, though in set theory, it is usually called *symmetric difference*, and denoted with the symbol $\triangle$.
Comment: I tend to think your understanding of "xor" is correct, considering the example given.
Comment: If this was in a course on algebra, the book/instructor might have wanted to emphasize the "ring" structure of sets, and hence chose $\oplus$ for that reason. (In turning a "Boolean algebra" into a "Boolean ring," the symmetric difference is the additive function of the ring...)
Comment: This site is not here to answer questions like "What does some_mathematical_term mean". See the asking-help, in particular, "Search, and research". If you search and find a definition on a reputable site that you cannot understand, by all means explain why and ask for an explanation. @PJTraill
Answer: The operation is often denoted by $\triangle$ and called symmetric difference, i.e.
$$
A\triangle B=(A\setminus B)\cup (B\setminus A)=\{x: (x\in A)\oplus (x\in B)\}.
$$
Comment: Yes, but it also shows a definition using $\oplus$ (the right-most definition in my answer), and hence this _could_ be what your lecturer meant.
Comment: Wikipedia shows "Symmetric Difference" using $\ominus$ though, as an alternative - not $\oplus$.

What is $\oplus$ in set theory?


Data set to experiment with multivariate count regression

Question: I have a model for predicting multiple count variables (multivariate count regression) given some covariates. Are there any publicly available datasets I could experiment with?
Comment: Can you clarify this a little bit? EG, have you developed a new type of analysis for this situation, &  want to compare how it behaves relative to standard methods on a known (perhaps classic) dataset?
Comment: yes, i have a new method and i would like to see how it performs on some real world data (classic/new). if you know some dataset(s) and could point to me that, it would be a big help.
Answer: If you have money to pay for it, you can get exactly this kind of data from HLDI: http://www.iihs.org/research/hldi/composite
I don't know how much they charge or what their T&Cs are, but I know that it's good data and it's very comprehensive :-)
Answer: You can use insurance data. For example, in third party insurance for every policyholder "claim frequency" of different "claim types"  is a multivariate count.
In this article a multivariate Poisson regression model suggested by the authors.
Comment: I asked the authors but they said the data can't be shared due to restrictions. Do you know of any publicly available datasets?
Answer: If you are a R user - For biological count data, you can have a look at the data in the R packages mvabund, vegan, labdsv.


Certain types of tangent values

Question: I was messing around with values of the tangent function and came across something interesting. For example, we have
$$\tan^2(\frac{\pi}{4\cdot2}) = \dfrac{\sqrt{4} - \sqrt{2}}{\sqrt{4} + \sqrt{2}}, \tan^2(\frac{\pi}{3\cdot4}) = \dfrac{\sqrt{4} - \sqrt{3}}{\sqrt{4} + \sqrt{3}}, \tan^2(\frac{\pi}{1\cdot1}) = \frac{\sqrt{1} - \sqrt{1}}{\sqrt{1} + \sqrt{1}}.$$
All of these values satisfy
$$\tan^2(\frac{\pi}{m\cdot n}) = \dfrac{\sqrt{m} - \sqrt{n}}{\sqrt{m} + \sqrt{n}}.$$
How could I go about to find all pairs $(m,n)$ which satisfy the equation?
Answer:
Incomplete answer: I can't proceed through the last step but I think for those with higher level math knowledge, it might be proceedable.

Consider$$\tan^2\left(\frac{\pi}{m\cdot n}\right) =\frac{\sin^2\left(\frac{\pi}{m\cdot n}\right)}{\cos^2\left(\frac{\pi}{m\cdot n}\right)}=\frac{1-\cos^2\left(\frac{\pi}{m\cdot n}\right)}{\cos^2\left(\frac{\pi}{m\cdot n}\right)}$$
Let$$x={\cos^2\left(\frac{\pi}{m\cdot n}\right)}$$
Then
$$ \frac{1-x}{x}=\dfrac{\sqrt{m} - \sqrt{n}}{\sqrt{m} + \sqrt{n}}$$
Simplifying
$$2x=\frac{\sqrt{m} + \sqrt{n}}{\sqrt m}$$
Note that
$$\cos\left(\frac{2\pi}{m\cdot n}\right)+1=2x$$
Hence,
$$\cos\left(\frac{2\pi}{m\cdot n}\right)=\frac{\sqrt{m} + \sqrt{n}}{\sqrt m}-1=\sqrt{\frac nm}$$

Certain types of tangent values


Como alterar o Texto e o ícone de um label usando JS ou JQuery - Asp.Net MVC

Question: Preciso setar a Descrição (EnderecoTipoDescricao) e o ícone (icon fa-home) no evento change de um SELECT. Para cada row o field "EnderecoTipoDescricao" possui um id cujo índice é incrementado: id="panel-title[i] indo de 0 até ... . Ao selecionar uma opçao no select, eu pego o Índice da row e com ele poderei setar o id field id="panel-title[i] correspondente à row. Não sei como setar o texto e o ícone da descriçao corrente conforme a opçao selecionada no selec (entrega ou Outro). Alguém sabe como fazer?
RAZOR

@Model.PessoasEnderecosViewModel[i].EnderecoTipoDescricao

    Tipo de Endereço
    <select asp-for="PessoasEnderecosViewModel[i].EnderecoTipoId" asp-items="@Model.PessoasEnderecosViewModel[i].EnderecosTipos" data-id="@Model.PessoasEnderecosViewModel[i].EnderecoTipoId" title="Selecione uma opção" class="form-control sel-endereco-tipo"><option value=""></option></select>

JS
$('#div-enderecos').on("change", ".sel-endereco-tipo", function (e) {
    e.preventDefault();

    //Pegar o índice
    var rowIndice = $(this).closest('.row').index();

    //Setar o texto e o ícone do field  panel-title[rowIndice ]???????????
});

OPÇOES NO SELECT
1 - ENTREGA (MUDAR O ÍCONE PARA icon fa-truck)
2 - OUTRO (MUDAR O ÍCONE PARA icon glyphicon glyphicon-pushpin)
Comment: Pergunta não ficou clara, cade o `SELECT` nessa pergunta? o que realmente quer fazer?
Answer: Depois de muito pesquisar, encontrei uma solução para meu problema e espero que isso possa ajudar a quem precisar futuramente:
SOLUÇÃO:
$('#div-enderecos').on("change", ".sel-endereco-tipo", function (e) {
    e.preventDefault();

    var rowIndice = $(this).closest('.row').index();

    //Setar o Field
    var selectoption = document.getElementById("PessoasEnderecosViewModel_" + rowIndice + "__EnderecoTipoId");
    var optionText = selectoption.options[selectoption.selectedIndex].text;
    var enderecoTipoId = $("#PessoasEnderecosViewModel_" + rowIndice + "__EnderecoTipoId").val();
    var txt = document.getElementById('panel-title[' + rowIndice + ']');

    $("#PessoasEnderecosViewModel_" + rowIndice + "__EnderecoTipoDescricao").val(optionText);

    switch (enderecoTipoId) {
        case '1':
            txt.innerHTML = ' ' + optionText + '';
            break;
        case '2':
            txt.innerHTML = ' ' + optionText + '';
            break;
        case '3':
            txt.innerHTML = ' ' + optionText + '';
            break;
        case '4':
            txt.innerHTML = ' ' + optionText + '';
            break;
        case '5':
            txt.innerHTML = ' ' + optionText + '';
            break;
        case '6':
            txt.innerHTML = ' ' + optionText + '';
            break;
        case '7':
            txt.innerHTML = ' ' + optionText + '';
            break;
    }

});


Should I loosen the tension on the bow for a break?

Question:
According to Violin for Dummies, we should loosen the horsehair before put violin back in the case.
However, I always give myself about an hour break after I play violin for 1 to 2 hours.
Should I leave the horsehair tight for an hour or loosen it and tighten it back after the break? Will it damage the bow if I leave it tight?
Comment: And, slightly off the topic of the question, but most of the damage I see to violin bows come from badly designed cases that put pressure on the side of the bow when they are clipped into the bow holder inside the case. The cheap thermoplastic cases seem to have the worst problem with this.
Comment: A carbon fiber or fiberglass bow will not react to being left tightened the same way that a wooden bow will.  The fiber bows are manufactured with the curve built in, and will not distort under constant pressure as quickly as a wooden bow will, so it is less important to slacken the tension, especially for short periods of time. That being said, it is better to stay in the habit of slackening when you aren't using the bow...
Comment: @AlphonsoBalvenie- yes, badly designed clips can damage bows.  I'm afraid that a fair amount of damage also comes from badly done hair jobs.  It happens rarely, but many bows come to me with wedges that have split the head, or wedges glued in with SuperGlue (those are fun), or the frog slide mangled by someone having removed the eyelet using the screw as a wrench, and so forth.  If you have a good bow, go to a good shop with it.
Answer: As a bowmaker, I would like to temper these answers a bit.  Yes, if you leave a bow under tension too long, it will lose its camber (bend) faster.  So that's true: one should get in the habit of loosening the bow.
But- one, all bows lose camber eventually, even if they are loosened religiously, unless they meet some other untimely end beforehand, because they are under tension when being played.  This happens very slowly, and is usually correctable, at least with wooden bows: the stick can be reheated and rebent (by a luthier, or you can try it yourself on a cheap bow), and this can be done several times with no noticeable loss of stiffness.  I've rebent original baroque bows over two hundred years old, and they work fine.
So I wouldn't necessarily panic about having left the bow for an hour- or even a day- under tension, if it's not at extreme temperatures.  It's not going to damage the bow more than playing does anyway.
And second- the screw, eyelet, frog, and especially the stick where these parts touch it, does wear every time the bow is tightened or loosened.  Not much, but a bow which is worn out at the frog end is substantially harder to repair than merely rebending the stick.  So I would say don't be neurotic about loosening the bow every time you take a short break.
If you are really serious about reducing the wear and tear of tightening and loosening the bow, you can do what I do: take the tension off the hair by straightening the stick a bit- say, by pushing it against your knee with one hand- and turning the screw with the other.  This way there is no pressure on the mating surfaces while adjusting, and everything will last much longer.  Again, you might want to practice on a cheap bow.
As long as I'm on bow maintainance: you can extend the lifetime of the eyelet, that is the nut in the frog the screw goes into, by about a factor of ten if you take the screw out and put a drop of oil or grease on its tip about once a year or two.  This should be done by whoever hairs your bow, but it very often is not.
Answer: I'd add to Dr. Mayhem's list:
You never know when something will interrupt your plans.  You might be 20 mins into a planned 1-hour break, and then the doorbell rings, you welcome a friend, ... next thing you know you're going out for lunch and completely forgetting the tensioned bow.  By making a habit of loosening the bow every time you get up, you'll never forget to do so at the end of a practice or peformance session.
Comment: Also, it's easy to overestimate the "damage" caused by leaving the bow under tension.  I've seen quite a few historical bass bows with clip-in frogs, where someone got tired of them popping out all the time, and simply screwed them to the stick.  These bows are _always_ under tension, except when they get rehaired, and they keep their camber amazingly well for many years.
Comment: Flip it around.  In what scenario will loosening the bow cause you problems?  One scenario gives you zero chance of damaging your bow.  The other gives you more than zero.
Comment: Zero chance of damaging your bow is not quite correct.  As I pointed out in my answer above, every time you tighten or loosen the bow, you add wear to the screw, the eyelet, and most importantly, to the stick.  This is what kills or severely damages bows eventually, if they don't get dropped first.
Comment: @ScottWallace any references for that?  As with compound archery bows,  detensioning when not in use has always been considered less damaging to the elastic parts (the stick in our case) than the act of applying tension.   Screw and eyelet are pretty much indestructible, not to mention easily replaced.
Comment: @CarlWitthoft- all I can say is that I've been making and repairing bows for nearly fifty years, and I've repaired hundreds of them.  Yes, screws last a very long time.  Eyelets don't last that long- perhaps ten to twenty years.  This is assuming they are lubricated- they can go much faster if left dry.  And the hole the screw goes in gets bigger with time, also on the order of decades, but eventually it will make the bow unplayable.  Compound bows, as far as I know, don't have screws that turn in the wood, so they are not really comparable to musical bows.
Answer: I would always loosen it off for that one hour break, for two reasons:

Over time, tension will eventually damage the bow. Keeping tension on when you don't need to will just shorten the lifespan of the bow. Maybe not by much, but:
It is so easy to slacken and then re-tension the bow, that you might as well just get used to doing it.


Why are large MLB contracts backloaded?

Question: Many MLB contracts are backloaded. For example, Alex Rodriguez will be making over $30 million USD per year at the end of his deal in 2017, much higher than the average annual value.
I understand that clubs sometimes do this to ease the burden on the luxury tax at the beginning, but as players age, they typically decline, causing all of those dollars committed at the end of the contract to be an albatross. Why do we not see clubs front-loading contracts, where they will pay the most for a player while he is in his prime?
Comment: Presumably the overall payroll will be increasing over that period as well so that the total percentage allocated is relatively consistent.
Comment: @JacobG not necessarily, some contracts are backloaded to an extent that no payroll increases are going to keep pace with it. The Marlins this year have done that.
Answer: There are many good reasons and many bad reason to back load a longterm deal for a baseball player. Lets start with the good:

Revenues/luxury tax limits are likely to be higher later on.
You have more time to plan for the expense, rather than having to pay it now.
You might be able to trade all or part of that contract to another team, thus sharing the cost of the later years of the deal.
You can amortize some of the premium you pay right now to a player over a longer term.
There is always a chance the player might retire before the deal is up allowing you out of the final years.
However, the primary reason for back loading a deal is to give you a competitive advantage during the player's prime. If you can pay them a lower rate right now you have more money (and luxury tax room) available to surround your high dollar free agent with the talent needed to compete.

Finally there are plenty of reasons not to do this

You end up paying a premium for past performance.
You end up chewing up a huge chunk of your payroll for a player that is well past his prime and cannot produce at the level his salary dictates
The player becomes impossible to trade, and very difficult to release. Because contracts are guaranteed, the player is assured of seeing every dime of his contract regardless of whether he is playing or not, this means that making a case to ownership to release a player owed 18+ million at the end of his deal is very difficult (Alfonso Soriano is a great example of this).
You can saddle a potentially competitive team with an albatross of a contract by serious limiting payroll flexibility if you manage to compete longer than your expected window.

All of this to say that backloading a contract is not always a negative, if you have a limited payroll and a limited window to compete then you might want to use a backloaded deal in order to be even more competitive than a balanced deal would allow you to be. However this comes with some serious risk if you either do not manage to win a world series or if you manage to stay competitive longer than you planned. This is a challenging business situation and I do not see this as quite a cut and dried situation as the media sometimes makes it out to be. However, it can go incredibly badly if it is done poorly or too often (see 2010-13 Chicago Cubs).
Answer: In finance, it's called the time value of money. That is, $1 million paid in 2020 doesn't cost quite as much as $1 million paid in 2013 because the team can earn interest on the money.
In "selling" contracts to their players, teams dangle the largest total number of dollars. Then they try to compensate by pushing back those dollars in time with players that don't understand the above paragraph.
A really smart player might settle for fewer dollars paid earlier, but few players would be willing to do this.
Comment: This actually has very little to do with why contracts are backloaded. It's *a* possible reason, but only really accounts for a few percentage points of what can sometimes be huge sums of money backloaded onto deals.
Comment: If you assume baseball revenues will continue inflating as they have been, it's actually largely because of this reason - it's not just a few percentage points.
Comment: See [Max  Scherzer and when 210 million isn't 210 million](http://www.fangraphs.com/blogs/max-scherzer-and-when-210-million-isnt-210-million/) by Dave Cameron of Fangraphs - the deferred money in Scherzer's contract (half of it!) caused the contract to be the equivalent of a $170 million 'flat' contract in net present value, a drop of almost 20%.  This is admittedly something of an extreme example, and a 'normal' backloaded contract is less significant, but it definitely can make a difference - and this is ignoring baseball salary/revenue inflation, only considering money inflation.
Answer: A new baseball contract can be depreciated at 100% in the first year. This would give Jeff Loria a tax deduction of 325 million in 2015 for Stanton when he is only paying 6.5 million. If Loria has another associated business which makes 325 million, he will pay no taxes on 325 million while only laying out 6.25 million.
This allows him to state that he is losing money at baseball, when in fact he is not, and allows him to avoid about 100 million on taxes at the same time.
He can then move the contract to someone else who needs a deduction.
Nice game!

Why are large MLB contracts backloaded?


composition api computed return value in setup function before setup return value

Question: I am trying to edit a post using state manager vuex, in vue3 using compostion API and here is my code:
<template>

      Edit Post

    <form v-else @submit.prevent="validation">

          Title
          <input
            v-model="formData.title"
            type="text"
            class="form-control"
            @input="formData.titleErr = false"
            id="title"
            placeholder="Please inter the title"
          />

            This title is not valid

          content
          <textarea
            class="form-control"
            id="content"
            placeholder="Please enter the context"
            rows="7"
            v-model="formData.content"
            @input="formData.contentErr = false"
          ></textarea>

            This content is not valid

        <button
          type="submit"
          value=""
          class="btn btn-primary"
          @click="validation">
          Edit
        </button>

    </form>

</template>

And here is the script

The problem is that I need the value of postInfo which is taken from the store, however, the data is not updated correctly. The first time the page is rendered, all the inputs are empty, the other times the data is related to the last rendered time. maybe the problem is that the computed value is not envoked when the first render happened because setup is not returned any thing yet.
by the way here is the store
import axios from "axios";
import Swal from "sweetalert2";

const postsModule = {
  namespaced: true,
  state: {
    posts: [],
    singlePost: {},
  },
  getters: {
    setPosts(state) {
      return state.posts;
    },
    setSinglePost(state) {
      return state.singlePost;
    },
  },
  mutations: {
    getPosts(state, posts) {
      return (state.posts = posts);
    },
    getSingle(state, post) {
      return (state.singlePost = post);
    },
  },
  actions: {
    // get post list
    async fetchPosts({ commit }) {
      const res = await axios.get(`http://localhost:3004/posts`);
      const data = res.data;
      commit("getPosts", data);
    },
    // view each post
    async fetchSinglePost({ commit }, id) {
      const res = await axios.get(`http://localhost:3004/posts/${id}`);
      commit("getSingle", res.data);
    },
    //  delete single post
    async deleteSinglePost({ commit }, id) {
      const res = await axios.delete(`http://localhost:3004/posts/${id}`);
      commit("updateAfterDelete", res.data);
    },
    // create post
    async createSinglePost(context, newPostData) {
      await axios.post(`http://localhost:3004/posts`, newPostData);
      Swal.fire({
        title: "Thanks!",
        text: "submission is done",
        icon: "success",
        confirmButtonText: "Cool",
      });
    },
  },
};
export default postsModule;

Is there any solution for it to sync the computed value correctly through any render? I mean when the first component is rendered the inputs values are not empty.
Comment: Just don't render the component until you have data to correctly render it
Comment: Either with v-if in a parent where you dispatch an action, or use async component and suspense and dispatch an action in this component
Comment: dear@Estus Flask
Thanks How should i use use async component?
Answer: Since you're using async calls in your setup, you can change the setup to an async setup and then await those inner async calls to make sure the data is loaded before you return it to your template. Just make sure to use a Suspense tag in the parent component. Here is a good post explaining the solution, Why did I get blank (empty) content when I used async setup() in Vue.js 3?


Analyzing Ryuichi Sakamoto's "Self Portrait"

Question:

Listen From 00:56

The [E] part is in C Major key
and I can't understand the C#m7-5 chord at bar 3
what is this chord ?
Where did it come from? and what is its function ?
Answer: As far as I can tell, the C♯m7♭5 is basically just a variation on the Cmaj7 chord before it, but changing the note C to the note C♯, thereby changing the chord's quality and creating a really cool sound. I've heard this called a "slide progression" before, and I think this is the same idea. In terms of function, this adds some tension that can be resolved, or more likely, linked to a subdominant chord. Also, I'd have to disagree with your analysis of the B♭/C chord, I'd call that  some form of a C7 chord with extensions (it functions as a dominant chord).
Comment: How could that happen ? Where is that C# note coming from ?
Comment: is it some type of line cliche ?
Comment: How could b9 (C#) appear in a 1 tonic chord ? And how could this be a extension it looks more like the chord has changed
Comment: When I said "extension", I didn't mean like a 9th or something, I meant that the C chord's C note is changed to a C♯.
Comment: Well, it is really close to C, and my guess is the explanation is that changing the C to a C♯ makes a new chord; therefore the composer just takes the entire structure of the previous measures but changing the Cs to C♯s to be cool. I wouldn't analyse that note as being like a ♭9 or anything, I'd say it's the root of a chord which was arrived at by sliding the note below it up.
Comment: @HyunYooPark Initially, I considered this as an idea, but the next chord after it is D♭7, where the E becomes an F, the G becomes an A♭, and the B♭ becomes a C♭. I'd hesitate to call three notes changing at once a line cliche, especially since it's not a stationary chord with only one note being moved up. Especially since the root is moving. So no, I wouldn't call it a line cliche, though it does seem similar to me.
Comment: But from C Maj to C#m7-5 is a 1 half note movement so can we call this a cliche ? not C#m7 to Db7
Comment: If you want to call it a line cliche, just be aware that usually line cliches are on a stationary chord, and this chord by definition is not stationary because the root is the one moving.
Answer: I would call this (and the Db7 that follows) passing chords to get from I (of V, since we've modulated to C major) to V7 (of I, which is F major).
Peculiarly, this means we're just moving from C to C7, and the passing chords are obtained by just a few half-step tweaks, but they're untethered harmonically, helping to ensure that there's no stable harmonic sense until we get back to F. In other words: the fact that you can't find a clear harmonic function for this chord is a feature!


Referencing Django's versioned static resources

Question: When I run python manage.py collectstatic, it makes a copy of each image, JavaScript, and CSS file with a hash in the filename:
Post-processed 'css/theme.css' as 'css/theme.afeb1fc222a9.css'
Post-processed 'css/custom.css' as 'css/custom.585e1b29ff9a.css'
...

I'm assuming this is just a way of making a versioned filename for better caching; the client or CDN can be told to cache this file indefinitely, because if I make a change, the hash will differ, and I'll just reference the new version by the new name.
However, I'm not clear on how I'm supposed to reference this URL. The documentation on serving static files just says,

In your templates, either hardcode the url like /static/my_app/example.jpg or, preferably, use the static template tag to build the URL for the given relative path by using the configured STATICFILES_STORAGE storage (this makes it much easier when you want to switch to a content delivery network (CDN) for serving static files).

I went through my templates and dutifully switched every static resource (including the CSS files) from a hardcoded URL to a {% static "..." %} template tag, assuming it would map to the versioned filename where appropriate. But it doesn't.
I'm also using WhiteNoise for serving the resources, and I'm not entirely sure how it affects things, but it also says,

Want forever-cacheable files and compression support? Just add this to your settings.py: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

But I have that in my settings file and it also doesn't seem to do anything with these versioned filenames.
Comment: You are looking in the wrong place. Django by itself does not have this behaviour; Whitenoise is responsible for compressing these files and also for serving them. If something is not working, you should read the [Whitenoise documentation](http://whitenoise.evans.io/en/stable/django.html) on how to get it working with Django.
Comment: @DanielRoseman It seems that it's done by the [ManifestStaticFilesStorage](https://docs.djangoproject.com/en/2.0/ref/contrib/staticfiles/#manifeststaticfilesstorage) which is Django, not WhiteNoise. (WhiteNoise's storage backend inherits the behavior.)
Answer: If DEBUG is True then the static url will be 'css/theme.css' instead of
 'css/theme.afeb1fc222a9.css'
Comment: It seems that it's done by the [ManifestStaticFilesStorage](https://docs.djangoproject.com/en/2.0/ref/contrib/staticfiles/#manifeststaticfilesstorage) storage backend, which does specify that `DEBUG` has to be `False`. Thanks!


Como transformar string em array de caracteres?

Question: É possível transformar string em array de caracteres?
Só achei com o método .split(param);
Eu gostaria de converter uma string em um array de caracteres, um caracter em cada índice.
Gostaria que 'oi'  se converte-se em   var[0] = 'o', var[1] = 'i'
Como fazer isso?
Comment: Mas se o split já faz isso, você quer o que além disso?
Answer: Para separar uma String por caracteres podes usar '' como separador.
var string = 'oi';
var array = string.split(''); // ["o", "i"]

Answer: Além do split('') que o Sergio recomendou, também é possível acessar cada caractere diretamente pelo índice, mesmo sem converter para array. Por exemplo:
var str = 'teste';
str[2] === 'e' // false
str[2] === 's' // true

Answer: Depende do que você entende por "caractere".
As outras respostas funcionam muito bem no "mundo ASCII", mas hoje em dia a definição de caractere se tornou tão complicada que acho que vale a pena explorar algumas possibilidades.

Isso não quer dizer que as outras respostas estão erradas, apenas que há mais casos a serem considerados além do que já foi apresentado. Até porque há muitas situações nas quais você não vai precisar se preocupar com o que vem a seguir (mas ainda sim acho válido conhecer, pois se um dia precisar, está aí).

Mas antes, apenas para acrescentar mais uma opção às demais respostas, você pode usar Array.from:

console.log(Array.from('oi'));

Agora vamos aos casos em que tudo isso falha:

function test(s) {
    console.log(`Testando string ${s}:`);
    console.log('split=', s.split(''));
    console.log('spread=', [...s]);
    console.log('Array.from=', Array.from(s));
}

test('á'); // funciona, todos os arrays terão apenas um caractere ("á")
test('á'); // ops, todos os arrays tem 2 elementos

O que acontece é que o primeiro "á" está normalizado na forma NFC, e o segundo, na forma NFD. Para entender em detalhes o que é isso, sugiro ler aqui, aqui e aqui. Mas de forma bem resumida, o caractere "á" pode ser representado de duas formas: NFC ou "composta" (ou seja, como um único caractere, o "á") e NFD ou "decomposta" (como dois caracteres: a letra "a" sem acento e o próprio acento, separadamente). Ao serem mostrados na tela, ambos são iguais, mas se você "escovar os bits", verá que um deles possui na verdade dois "caracteres" (que ao serem mostrados na tela, são "combinados" em um só). Só que todos os métodos acima (split, spread, Array.from) levam isso em conta na hora de montar o array, e é por isso que no segundo caso cada array tem dois elementos.
Uma alternativa é normalizar para NFC, usando o método normalize:
console.log('Array.from=', Array.from(stringQualquer.normalize('NFC')));

A menos, é claro, que você de fato queira ter os acentos separados das letras, aí você normaliza para NFD.
Mas isso ainda não resolve todos os casos...

Emojis
Emojis são caracteres? A discussão não vem ao caso, mas o fato é que hoje podemos ter strings assim:

let poo = '';
console.log(poo);

Sim, um emoji direto no código. E nesse caso, split não funciona mais:

function test(s) {
    console.log(`Testando string ${s}:`);
    console.log('split=', s.split(''));
    console.log('spread=', [...s]);
    console.log('Array.from=', Array.from(s));
}

test('');

Tanto spread quando Array.from geram um array contendo apenas um elemento: o "caractere"  (PILE OF POO). Mas split gerou um array com dois elementos. Isso acontece porque internamente o JavaScript guarda as strings em UTF-16 (ou UCS-2, veja mais detalhes aqui) e caracteres cujo code point é maior que 0xFFFF acabam sendo "decompostos" em duas partes (o chamado surrogate pair - o algoritmo é descrito aqui, caso tenha ficado curioso).
No caso do PILE OF POO, seu code point é 0x1F4A9, que em UTF-16 é convertido para o surrogate pair 0xD83D e 0xDCA9, e são esses valores que estão no array gerado por split:

console.log(''.split('').map(c => c.codePointAt(0).toString(16)));

Este comportamento do split é explicado em mais detalhes aqui.
No fim, não importa se emojis são considerados caracteres ou não. O fato é que, se você tiver uma string contendo emojis e quiser gerar um array a partir dela, o que é "melhor": que cada elemento do array seja um emoji, ou que os emojis sejam quebrados em surrogate pairs? Claro que a resposta ainda será "depende" (pode ter um caso de uso em que você precise saber dos surrogate pairs), mas entendo que na maioria dos casos você provavelmente vai querer um array de emojis.

"Então basta usar spread ou Array.from, e normalizar para NFC, que tudo funciona, certo?"

Errado
Geralmente os emojis correspondem a um code point (como o PILE OF POO, que é 0x1F4A9), mas nem sempre é o caso. Os emojis de famílias, por exemplo, são combinações de outros emojis.
Ex: uma família com pai, mãe e 2 filhas é na verdade uma combinação do emoji de um homem, uma mulher e dois emojis de menina. Para juntá-los, é usado o caractere ZERO WIDTH JOINER (também chamado apenas de ZWJ - e essas sequências de emojis separados por ZWJ são chamados de Emoji ZWJ Sequences).
Ou seja, o emoji de "família com pai, mãe e 2 filhas" é na verdade uma sequência de sete code points:

MAN
ZERO WIDTH JOINER
WOMAN
ZERO WIDTH JOINER
GIRL
ZERO WIDTH JOINER
GIRL

Esta sequência de code points pode ser mostrada de diferentes maneiras. Se o sistema/programa usado reconhece esta sequência, é mostrada uma única imagem da família:

Mas se esta sequência não é suportada, os emojis são mostrados um ao lado do outro:

E nesse caso, nenhum dos métodos já vistos acima funciona:

function test(s) {
    console.log(`Testando string ${s}:`);
    console.log('split=', s.split(''));
    console.log('spread=', [...s]);
    console.log('Array.from=', Array.from(s));
}

test(String.fromCodePoint(0x1f468, 0x200d, 0x1f469, 0x200d, 0x1f467, 0x200d, 0x1f467));

Repare que split gerou um array com 11 elementos. Isso porque cada emoji (homem, mulher e os 2 emojis de menina) foi quebrado em um surrogate pair, totalizando 8 elementos. Mais os três ZWJ, totaliza 11. Já o spread e Array.from retornaram arrays com 7 elementos cada (cada um dos emojis mais os ZWJ).
Vale lembrar que o ZWJ não é usado somente com emojis. Vários outros alfabetos acabam usando-o em alguns dos seus "caracteres", como por exemplo o क्‍ष (em Devaganari, usado na Índia), que é composto por 4 code points (sendo um deles o ZWJ):

let s = 'क्‍ष';
console.log([...s].map(c => c.codePointAt(0).toString(16))); // ["915", "94d", "200d", "937"]

Essas sequências de code points que são interpretados como se fossem uma coisa só são chamados de Grapheme Clusters, e o JavaScript não possui uma forma nativa de obtê-los. Neste caso, o jeito é usar alguma lib.

Enfim, qual método usar vai depender de cada caso. Se você sabe que suas strings só tem caracteres ASCII, por exemplo, não precisa se preocupar com nada disso. Mas se tiver acentos, emojis e caracteres em outros idiomas, aí deve-se pensar no que você de fato precisa, e usar o método mais apropriado para cada caso.
Answer: Em versões mais recentes do ECMAScript, você também pode utilizar o operador de espalhamento, que irá converter a string, que é um iterável, em um array.
Assim:

const string = 'oi';
const array = [...string];

console.log(array);


Prove: affine transformation maps "line at infinity" to "line at infinity"

Question: I'm studying Computer Vision and my lecturer stated that:

The affine transformation maps "line at infinity" to "line at infinity".

I'm trying to prove it as part of my preparation for the final exam. My lecturer suggested to check the points on the line for that. Also in the lecture, it was explained that "line at infinity" is a line of form $I_{\infty}=\begin{bmatrix}0 & 0 & 1\end{bmatrix}^{T}$ (where $T$ is transpose). So for any ideal point (has $0$ in the third coordinate) $p=\begin{bmatrix}x & y & 0\end{bmatrix}^{T}$:
$$
I_{\infty}^{T}p=\begin{bmatrix}0 & 0 & 1\end{bmatrix}^{T}\begin{bmatrix}x & y & 0\end{bmatrix}^{T}=0
$$
It was in the context of projective spaces.
How can I prove the above theorem of Affine transformation that maps "line at infinity" to "line at infinity"? Tried to look online but only found a statement here (page 5).
Also, I guess that the definition of "Ideal points" and "line at infinity" are much more broad then the one I got from the lecture, but since I need to stick to those definitions, how one can prove the above statement? (It's Computer Vision course after all)
Comment: We can define the projective plane as the union of the affine plane with the set of directions in the affine plane, where a *direction* is the collection of lines parallel to a given line. We call these directions *points at infinity*. So, all you really need to prove is that affine transformations map parallel lines to parallel lines.
Comment: A correct way to express it is : Each time you take out **any** line from the projective plane, you get a specific "affine space". Speaking about "the" line at infinity can be considered as an abuse of language: it is because you have taken a certain system of coordinates that the "the" can be acceptable, but any other line would do the job with adapted coordinates.
Answer: Mo Pol Bol's comment is comprehensive and effective. Here I just want to highlight the theory behind that comment, if that can shed more light on the situation in general.
Let ${\cal A}(E)$ be an affine space over the $K$-vector space $E$ (where $K$ is a field).
The canonical projective extension of ${\cal A}(E)$ is the projective space ${\cal P} (E\times K)$. The function
$$ J = \left\{ \begin{matrix}
{\cal A}(E) & \longrightarrow & {\cal P}(E\times K)\\[1ex]
P & \longmapsto & [P-O,1]
\end{matrix}
\right.
$$
where $O$ is any fixed point of ${\cal A}(E)$, and $[P-O,1]$ is an abbreviation for $\langle(P-O,1)\rangle$, is an immersion of ${\cal A}(E)$ into ${\cal P}(E\times K)$. The set
$$ l_\infty := {\cal P}(E\times K) \setminus J({\cal A}(E)) $$
is an hyperplane of ${\cal P}(E\times K)$, called the improper hyperplane or the hyperplane at infinity of ${\cal A}(E)$. Obviously it is a line if the affine space is an affine plane.
It is easy to see that
$$ l_\infty = \{[a,0]\;\;:\;\;a\in E, \;a\neq 0\}. $$
Each affinity $f : {\cal A}(E) \longrightarrow {\cal A}(E)$ extends to a projectivity $\tilde f :{\cal P}(E\times K) \longrightarrow {\cal P}(E\times K)$:
$$ \tilde f([a,t]) = [df(a), t] \qquad\qquad \big(a\in E,\;t\in K,\; (a,t)\neq(0,0)\big), $$
where $df$ is the linear part of $f$. $\big[$Remember that a function $f : {\cal A}(E) \rightarrow {\cal A}(E)$ is affine iff there is a linear function $L : E\rightarrow E$ such that $f(P)-f(Q)=L(P-Q)$ for all $P,Q\in {\cal A}(E)$. We denote $L$ by $df.\big]$
Now the conclusion is almost obvious:
$$ \tilde f([a,0]) = [df(a),0]\qquad\qquad \forall\,a\neq0 $$
so
$$ \tilde f(l_\infty) = l_\infty $$
because $df$ is bijective, being $f$ an affinity.


Brown-Forsythe using python

Question: I'm analysing what's the pattern of sales of a product. For that I grouped the sales by week (1st week, 2nd week, 3rd week and 4th week).
The sample sizes differ significantly from each other, so do the variances. For this reason I would to perform a Brown-Forsythe test.
As I'm doing this with Pyhton, I'm struggling to find a library that has provides this functionality.
Do you know something or do I have to do this manually?
Answer: You can do it in SciPy. It ostensively does not have a Brown-Forsythe test built in... but it does have a Levene test. And it takes a centre parameter, which lets you specify if you want to use the mean or the median.
If you use median, well, that's a Brown-Forsythe, just hidden under a different name.

Brown-Forsythe using python


Proving that a given line is tangent to a hyperbola

Question: The question is: a line $x \cos\theta + y\sin\theta = p$ is given such that $a^2\cos^2\theta - b^2\sin^2\theta =p^2$.
I have to prove that it touches a hyperbola  $\frac{x^2}{a^2} - \frac{y^2}{b^2} = 1$. I do not see how to proceed. I thought I could proceed by eliminating $p$ by squaring the line equation and equate both but I don't get an idea what to do next. What do I need to show to prove that it touches that hyperbola?
Answer: The tangent at $(x_1,y_1)$ to the hyperbola is
\begin{align*}
\frac{xx_1}{a^2} - \frac{yy_1}{b^2} = 1
\end{align*}
If this is the given line, we have
\begin{align*}
\frac{x_1/a^2}{\cos \theta} = \frac{-y_1/b^2}{\sin \theta} = \frac{1}{p}
\end{align*}
Hence $x_1 = \frac{a^2\cos\theta}{p}, y_1 = -\frac{b^2\sin\theta}{p}$. Since this lies on the curve, we have
\begin{align*}
a^2\cos^2\theta - b^2\sin^2\theta = p^2
\end{align*}
Comment: But how do i use the condition and the given line to get a relation that proves it to be lying on the given hyperbola?
Comment: Use $\frac{x_1^2}{a^2} - \frac{y_1^2}{b^2} = 1$.
Answer: HINT:
Replace  $x$ with $\dfrac{p-y\sin\theta}{\cos\theta}$ in $$\dfrac{x^2}{a^2}-\dfrac{y^2}{b^2}=1$$ to form a Quadratic Equation in $y$
Each value of $y$ represents the ordinate of the respective intersection.
For tangency, the two value of the ordinates must be same i.e., the the Quadratic Equation of $y$ must have equal roots.
Can you take it from here?
Comment: Yes that's another method