How to find and edit the named range that a VBA variable is referring to?

Question: My work has a Macro that we use to split combined mailing addresses out into multiple columns, but it is a little sloppy. I am looking to tighten up some of the search parameters, but I am not  the one who initially wrote it so I am trying to figure some things out.
The thing I am looking at now is updating the city list in the Macro so that it will identify more cities. The trick is when I look at the Sheet that the process refers to, I cannot find an array or list with cities that the macro is checking against. It just has a bunch of sub processes that look empty to me. I am new to a lot of this so maybe I am missing something obvious.
The part of the module that references the worksheet looks like this:
CityList = shtCity.Range("CityList").Column

And the is no code in the module of the worksheet (shtCity)
I don't really know what I am looking at, so please let me know if there is any other information that I can collect to help resolve this.
Comment: "CityList" is a named range on the worksheet which has code name of `shtCity` (the name on the sheet tab may be different).  Go to that sheet, select the Formulas tab, and open the "Name Manager" dialog.  That will show you where the named range is located.  If all of those Sub's are empty then you can delete them from the sheet code module - they're not doing anything.
Comment: The `CityList = shtCity.Range("CityList").Column` is actually storing the Column number of the named range **CityList**, which may not be efficient for codes later on. You should look for codes in a normal Module, not the Sheet/ThisWorkbook module.
Comment: When you open the VBE (Alt+F11) look at the Project Explorer at the left side. If it isn't there, tap Ctrl+R to show it. Look for **+ Module** and double click it to show what module code sheets are available.
Answer: Punch the following into the immediate window to see exactly where that range lives.
Debug.Print Range("CityList").Address

Alternative #1 - instead of using a debug.print you could put the same into a MSG box immediately before the module references that range
Alternative #2 - open shtCity and choose CTRL+F3 to see the named ranges.


Time signature inconsistent

Question: I'm trying to write the first measure of the Moonlight in Lilypond

From my very basic knowledge the first measure is 4 x 3 x 1/8 = 3/2 long, but the special symbol (alla breve) seams to be a 2/2.
  What I'm missing?

The lower part (bass), on the other side, is fine.
If someone knows Lilypond, here is my start
<code>\version "2.19.82"

musicA = {
  \key e \major
  \time 2/2
  \overrideTimeSignatureSettings 3/2 3/8 #'(1 1 1 1) #'()
  \relative c' { g8 fis c' e g,8 c e g,8 c e g,8 c e }
}

musicB = {
  \clef bass
  \key e \major
  \time 2/2
  c1
}

\new PianoStaff {
  <<
    \context Staff = "up" {
      \accidentalStyle default
      \musicA
    }
    \context Staff = "down" {
      \accidentalStyle default
      \musicB
    }
  >>
}
</code>
All the notes are wrong, but I think/hope to know enough to correct it myself.
Comment: triplets, dude!  :-)
Comment: It appears you're new to sheet music.  I would recommend learning a bunch of stuff about notation and reading sheet music before trying to generate your own in LilyPond .
Answer: The notes in the upper staff are tuplets. As an aid towards your eventual goal, here is some sample code to create what you're looking for:
<code>\version "2.19.82"

musicA = \relative c' {
  \key cis \minor
  \time 2/2
  \omit TupletNumber
  \override TupletBracket.bracket-visibility = ##f
  \tuplet 3/2 4 { gis8_\markup { \italic { sempre \dynamic pp e senza sordino } }
                  cis e gis,[ cis e] gis, cis e gis,[ cis e] } |
}

musicB = \relative c, {
  \clef bass
  \key cis \minor
  \time 2/2
  <cis cis'>1 |
}

\new PianoStaff {
  <<
    \context Staff = "up" {
      \accidentalStyle default
      \musicA
    }
    \context Staff = "down" {
      \accidentalStyle default
      \musicB
    }
  >>
}
</code>
This compiles:
Answer: The notes on the treble clef are triplets. That's all.
Comment: Music notation always leaves stuff out, stuff that (in that period) the composer deliberately left up to the performer to decide.  But sometimes, like this, it abbreviates in a way that annoys computer programmers and language lawyers but is completely reasonable to the everyday performer.
Comment: If I'm not misinterpreting what you just wrote, yes, that's the way it is. If you need to check anything with some established version, [here](http://ks.imslp.net/files/imglnks/usimg/1/19/IMSLP51726-PMLP01458-Beethoven_Werke_Breitkopf_Serie_16_No_137_Op_27_No_2.pdf) is the scan from a Leipzig publisher, which is identical to every version I've ever seen of this piece. Just to know: are you familiar with triplets? If not, you may want to look that up.
Comment: do you mean a triplet of 1/8 is 1/4 long instead of 3/8?
Answer: Triplet eighths are 2/3 the duration of a real eighth, so if you don't want to put every note in a triplet you can also give all notes a scaled duration. So your music would be
\relative c' { gis8*2/3 cis e gis, cis e     % etc
Remember to remove any other explicit durations so that implicit durations prevail from the first note here.

Time signature inconsistent


hook_node_access() returning NODE_ACCESS_DENY is ignored

Question: I am trying to block the current user from performing any action (view, update, delete) on a node. The user should only be able to view, update, delete the node being displayed if he is the owner of the node, or the owner of the node is a subuser of his (I am using the Subuser module).
The function below returns the correct value for the various tests I performed, but when the function returns NODE_ACCESS_DENY, the access isn't denied. The user can still see the node.
Is there something I am missing?
function mymodule_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;
  if (is_object($node)) {
    if ($node->type == 'my_content_type') {
      // Determine the current uid and, if the user doesn't have the right role, deny the access
      if (is_array($account->roles) && in_array('vip', $account->roles)) {
        $current_uid  = $account->uid;
      } elseif ( is_array($account->roles) &&
                !in_array('administrator', $account->roles)) {
        return NODE_ACCESS_DENY;
      } else {
        return NODE_ACCESS_ALLOW;
      }

      // Determine the node owner.
      $node_owner = $node->uid;

      // If the node owner is the same as the current user, allow to view the node
      if ($current_uid == $node_owner) {
        return NODE_ACCESS_ALLOW;
      }

      // If not, check if the node owner is a subuser of the current vip user
      $node_owner_profile = user_load($node_owner);
      if (isset($node_owner_profile->field_parent[LANGUAGE_NONE][0]['value'])) {
        if ($node_owner_profile->field_parent[LANGUAGE_NONE][0]['value'] == $current_uid) {
          return NODE_ACCESS_ALLOW;
        } else {
          return NODE_ACCESS_DENY;
        }
      } else {
        return NODE_ACCESS_DENY;
      }
    }
  }

  return NODE_ACCESS_IGNORE;
}

Comment: Install the Devel module, and add the node access blocks to your main content area (forget exactly what they are called).  What do they say?  Also keep in mind that hook_node_access() isn't called for everything.  The grant system is better, in general, for ACL.
Answer: There is an error in the code you are showing: A variable is initialized inside a if() control block, but it is used outside that block.
$current_uid is initialized from the following code.
if (is_array($account->roles) && in_array('vip', $account->roles)) {
  $current_uid  = $account->uid;
}

It is then used from the following code.
// If the node owner is the same as the current user, allow to view the node
if ($current_uid == $node_owner) {
  return NODE_ACCESS_ALLOW;
}

That code only works if the account object passed to the hook has the vip role, or if the node has been created from the anonymous user (whose ID is 0). Differently, $current_uid will be set to NULL.
Also, the code I shown in the second snippet does not do what the comment says: It allows the logged-in user to view, edit, update, and delete the node; it does not just allow the logged-in user to view the node.
The only operation that code is not allowing is creating a node of that content type, since in that case Drupal would pass the content type string in $node and the code is checking $node is an object.
To achieve what the comment is describing, the correct code is the following one.
if ($current_uid == $node_owner && $op == 'view') {
  return NODE_ACCESS_ALLOW;
}

I would rather use the following code.
function mymodule_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;
  if (is_object($node)) {
    if ($type == 'my_content_type') {
      $current_uid = $account->uid;
      $node_owner = $node->uid;
      if (is_array($account->roles)) {
        if (!in_array('vip', $account->roles) && !in_array('administrator', $account->roles)) {
          return NODE_ACCESS_DENY;
        }
        elseif (in_array('administrator', $account->roles)) {
          return NODE_ACCESS_ALLOW;
        }
      }
      else {
        return NODE_ACCESS_IGNORE;
      }

      if ($current_uid == $node_owner && $op == 'view') {
        return NODE_ACCESS_ALLOW;
      }

      $node_owner_profile = user_load($node_owner);
      if (isset($node_owner_profile->field_parent[LANGUAGE_NONE][0]['value'])) {
        if ($node_owner_profile->field_parent[LANGUAGE_NONE][0]['value'] == $current_uid) {
          return NODE_ACCESS_ALLOW;
        } else {
          return NODE_ACCESS_DENY;
        }
      } else {
        return NODE_ACCESS_DENY;
      }
    }
  }

  return NODE_ACCESS_IGNORE;
}

Keep in mind that, when the logged-in user has the bypass node access permission, hook_node_access() implementations are not invoked.
hook_node_access() implementations are also not invoked for page listing nodes, for example RSS feeds, or the default front page whose path is node.
Testing whether the value returned by a hook_node_access() implementation is respected by using an account with bypass node access permission or accessing the default front page does not have the expected result, especially in the case the expected result is that the operation is not allowed.
Instead of checking the roles of the user account, I would rather check if the user has a specific permission. hook_node_access() implementations are allowed to use user_permission().
Comment: Thank you for your detailed answer. However, I've made the suggested changes, without any positive result. I've put `drupal_set_message()` messages before each return statement in order to see what the function returns. In all test cases the returned value was correct. But even when `NODE_ACCESS_DENY` was returned, the user could still see the node. I haven't granted _bypass content access control_ permission to any role except _administrator_. I haven't implemented `hook_node_access` anywhere else on my website. Is it possible that another module could override my code?
Answer: My final solution is in fact a workaround. I have adapted the code as necessary and used it in template_preprocess_node The code is adding a new variable to the $variables array - called $access_allowed.
In node--content-type.tpl.php, I check that variable. If TRUE, I display the node. Otherwise, I redirect to the 403 page.
I know it's not as elegant as the solution using hook_node_access, but, for now, it works for me. If anyone finds a better solution, it would be great!
Thanks


Relacionamento ternário de entidades em um esquema relacional seria contra-normativo, e como fazer esse mapeamento em entity framework 6?

Question: Tendo como exemplo:

Podemos abstrair a relação de diversas formas, uma delas seria colocando relação de N p/ N entre projeto e habilidades necessárias, enquanto outra pra empregado e habilidades possuintes, assim como uma pra empregado e projeto em que está alocado. Essa seria a forma correta de realizar essa relação ou uma ternária realmente é a mais apropriada?
Pergunto isso pois estou mexendo com esse tipo de relação em um sistema legado que estou tendo que migrar, aproveito pra perguntar, como faço o mapeamento de uma relação ternária com Entity Framework 6?
Tentei realizar o mapeamento dessa forma, em código de exemplo:
             this.HasMany(e => e.Skill)
                 .WithMany(s => s.Employees)
                 .Map(eps =>
                     {
                         eps.MapLeftKey("ID_EMP");
                         eps.MapRightKey("ID_SKILL");
                         eps.ToTable("EMP_SKILL_PROJ");
                     });

             this.HasMany(e => e.Projects)
                 .WithMany(p => p.Emplyees)
                 .Map(eps =>
                     {
                         eps.MapLeftKey("ID_EMP");
                         eps.MapRightKey("ID_PROJECT");
                         eps.ToTable("EMP_SKILL_PROJ");
                     });

Repeti esse mapeamento em todas as três classes, da forma que foi necessária de acordo com o contexto de cada.
Mas obviamente obtive a seguinte exceção:

One or more validation errors were detected during model generation:
  ProjectSkill: Name: The EntitySet 'ProjectSkill'
  with table 'EMP_SKILL_PROJ' was already defined. Each EntitySet must
  refer to a unique schema and table.
ProjectEmployee: Name: The EntitySet 'ProjectEmployee' with
  table 'EMP_SKILL_PROJ' was already defined. Each EntitySet
  must refer to a unique schema and table.
Comment: Nesse caso precisa montar a relação e a exposição em um entidade intermediária
Answer: Um exemplo para que isso funcione é criar uma entidade intermediária explicita e fazer as operações de atualizações nessa entidade intermediária, exemplo:
Modelos:
public partial class Employee
{
  public Employee()
  {
     EmployeeSkillProject = new HashSet<EmployeeSkillProject>();
  }
  public int Id { get; set; }
  public string Name { get; set; }
  public virtual ICollection<EmployeeSkillProject> EmployeeSkillProject { get; set; }
}

public partial class Project
{
  public Project()
  {
     EmployeeSkillProject = new HashSet<EmployeeSkillProject>();
  }
  public int Id { get; set; }
  public string Description { get; set; }
  public virtual ICollection<EmployeeSkillProject> EmployeeSkillProject { get; set; }
}

public partial class Skill
{
  public Skill()
  {
     EmployeeSkillProject = new HashSet<EmployeeSkillProject>();
  }
  public int Id { get; set; }
  public string Title { get; set; }
  public virtual ICollection<EmployeeSkillProject> EmployeeSkillProject { get; set; }
}

todos esses modelos tem relação de coleção com o modelo EmployeeSkillProject com o seguinte modelo exemplo:
public partial class EmployeeSkillProject
{
  public int EmployeeId { get; set; }
  public int SkillId { get; set; }
  public int ProjectId { get; set; }
  public string Description { get; set; }
  public virtual Employee Employee { get; set; }
  public virtual Project Project { get; set; }
  public virtual Skill Skill { get; set; }
}

e nesse modelo existe a agregação dos outros três modelos. Para configurar um Contexto com a configuração desse modelo acima:
public partial class Ex001Context : DbContext
{
  private const string ConnectionString = "String de conexão";
  public Ex001Context()
     :base(ConnectionString)
  {
     Database.SetInitializer<Ex001Context>(null);
     Configuration.LazyLoadingEnabled = false;
     Configuration.ProxyCreationEnabled = false;
  }
  public virtual DbSet<Employee> Employee { get; set; }
  public virtual DbSet<EmployeeSkillProject> EmployeeSkillProject { get; set; }
  public virtual DbSet<Project> Project { get; set; }
  public virtual DbSet<Skill> Skill { get; set; }
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
     modelBuilder.Entity<Employee>().ToTable("Employee");
     modelBuilder.Entity<Project>().ToTable("Project");
     modelBuilder.Entity<Skill>().ToTable("Skill");
     modelBuilder.Entity<EmployeeSkillProject>().ToTable("EmployeeSkillProject");

     modelBuilder.Entity<Employee>()
        .Property(x => x.Name)
        .IsRequired()
        .HasMaxLength(50)
        .IsUnicode(false);

     modelBuilder.Entity<EmployeeSkillProject>()
        .HasKey(e => new { e.EmployeeId, e.SkillId, e.ProjectId });

     modelBuilder.Entity<EmployeeSkillProject>()
        .Property(x => x.Description)
        .IsRequired()
        .HasMaxLength(50)
        .IsUnicode(false);

     modelBuilder.Entity<EmployeeSkillProject>()
        .HasRequired(x => x.Employee)
        .WithMany(p => p.EmployeeSkillProject)
        .HasForeignKey(x => x.EmployeeId);

     modelBuilder.Entity<EmployeeSkillProject>()
        .HasRequired(x => x.Project)
        .WithMany(p => p.EmployeeSkillProject)
        .HasForeignKey(p => p.ProjectId);

     modelBuilder.Entity<EmployeeSkillProject>()
        .HasRequired(x => x.Skill)
        .WithMany(p => p.EmployeeSkillProject)
        .HasForeignKey(p => p.SkillId);

     modelBuilder.Entity<Project>()
        .Property(x => x.Description)
        .IsRequired()
        .HasMaxLength(50)
        .IsUnicode(false);

     modelBuilder.Entity<Skill>()
        .Property(x => x.Title)
        .IsRequired()
        .HasMaxLength(50)
        .IsUnicode(false);
  }
}

e na utilização básica por exemplo de adicionar:
using (Ex001Context db = new Ex001Context())
{
   Employee employee = new Employee();
   employee.Name = "Employee 2";

   Skill skill = new Skill();
   skill.Title = "Skill 2";

   Project project = new Project();
   project.Description = "Project 2";

   EmployeeSkillProject employeeSkillProject = new EmployeeSkillProject();

   employeeSkillProject.Employee = employee;
   employeeSkillProject.Skill = skill;
   employeeSkillProject.Project = project;
   employeeSkillProject.Description = "Employee, Skill, Project 2";

   db.Employee.Add(employee);
   db.Skill.Add(skill);
   db.Project.Add(project);
   db.EmployeeSkillProject.Add(employeeSkillProject);

   db.SaveChanges();
}

Dessa forma tem um modelo prático, de fácil entendimento e que pode crescer com outros tipos de relações, e é de fato bom ratificar que a partir do momento que seu modelo sai do padrão do ORM no muitos para muitos, no caso citado é bom fazer a entidade que controla essas relações.


Python - Ordered List of Dictionaries, With a Size Limit?

Question: This is a requirement for a chat application project that I'm creating with Python, Flask, Socketio, and Javascript:
"Messages View: Once a channel is selected, the user should see any messages that have already been sent in that channel, up to a maximum of 100 messages. Your app should only store the 100 most recent messages per channel in server-side memory."
So, what I think I should be doing is creating a list of dictionaries. Like this:
messages = [ {"user":"Dave", "message":"Hello", "time":"12-24-2018"}, {"user":"John", "message":"Test", "time":"12-21-2018"} ]

My questions are..

How do I append to/access a list of dictionaries like this?
How do I limit the size of the list, and replace the oldest element with the second oldest element as I add to it?
Is this the best practice for storing a fixed size of data server side?
Comment: You'll want to use a `threading.Lock`, `list.append`, and `list.pop`. The requirements seem to infer that you'll just store this list in memory, so I don't understand your third point
Comment: 1. appending to list of dictionaries is simple. Create a new dictionary of single message like `msg = {"user":"Dave", "message":"Hello", "time":"12-24-2018"}`
and then `messages.append(msg)` to add the message to the list.

2. Limiting the size of the list: Slice the list of messages as:
`messages = messages[-100:]`

3. This point is unclear, can you explain a little more?
Answer: One possible solution is to use the double-ended queue implemented in the standard library's collections package - collections.deque.
Deques are similar to lists, but support efficient appending and popping from both ends, are threadsafe, and can be specified to have a maximum length.
For example:
>>> dq = collections.deque(maxlen=5)
>>> for i, x in enumerate('abcde'):
...    dq.append({x: i})
...
>>> dq
deque([{'a': 0}, {'b': 1}, {'c': 2}, {'d': 3}, {'e': 4}], maxlen=5)

If you add an element to a deque which has maxlen set, and which is already at maximum size, an element is removed from the other end of the deque:
>>> dq.append({'f': 5})
>>> dq
deque([{'b': 1}, {'c': 2}, {'d': 3}, {'e': 4}, {'f': 5}], maxlen=5)

>>> dq.appendleft({'z': 25})
>>> dq
deque([{'z': 25}, {'b': 1}, {'c': 2}, {'d': 3}, {'e': 4}], maxlen=5)

It's worth noting that Python's json module doesn't handle deques, so if you want to dump the deque to json you'll need to provide a function that converts the deque to a list:
>>> json.dumps(dq)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ...
TypeError: Object of type deque is not JSON serializable
>>> def jdq(o):
...     return list(o)
...
>>> json.dumps(dq, default=jdq)
'[{"z": 25}, {"b": 1}, {"c": 2}, {"d": 3}, {"e": 4}]'

To recreate the deque from a json array, just pass the deserialised list to a new deque:
>>> L = json.loads('[{"z": 25}, {"b": 1}, {"c": 2}, {"d": 3}, {"e": 4}]')
>>> dq = collections.deque(L, maxlen=5)
>>> dq
deque([{'z': 25}, {'b': 1}, {'c': 2}, {'d': 3}, {'e': 4}], maxlen=5)


drupal template files in different folders for different content types

Question: I'm trying to get Drupal to scan multiple directories to find template files for pages and nodes. I have a content type called "contest". I have a node with the path of "http://mysite.com/contest/test
I'd like to have a folder structure like:
templates
    page
        page.tpl.php
        page-front.tpl.php
    node
        node.tpl.php
    contest
        contest.tpl.php
        contest-test.tpl.php

Drupal is not finding contest tpl's.
Answer: See http://drupal.org/node/1089656 for more information on the possible file names that Drupal will recognize by default.
Drupal will not recognize contest.tpl.php as it is not one of the patterns that it recognizes.  If contest.tpl.php is an override of node.tpl.php then you should name it node--contest.tpl.php
If you want to override a page template in the same manner, see this previous post: https://stackoverflow.com/questions/5194109/drupal-7-candidate-page-tpl-name-for-particular-custom-content-type-entry/5194364#5194364
Answer: It is not possible to have a different directory for each template file that is specific for a content type, as Drupal will look for those template files in the same directory where the base template file is.
For example, if the template file is one of the suggested files for node.tpl.php, then both node.tpl.php and the suggested template file must be in the same directory.


SQL: Combine values per ID into one variable

Question: I have following table:
ID  Var
01  Value1
01  Value2
01  Value3
02  Value4
02  Value2
02  Value3
03  Value1
03  Value2

and would like to convert it into following format:
ID  Vars
01  Value1, Value2, Value3
02  Value4, Value2, Value3
03  Value1, Value2

What SQL command can I use to do this?
Comment: look at `group_concat`.
Comment: `SELECT ID, GROUP_CONCAT(Var) AS Vars FROM yourTable GROUP BY ID`
Answer: You are looking for group_concat():
select id, group_concat(var separator ', ') as vars
from t
group by id;

Three notes:

You change the separator using the SEPARATOR keyword; the default is comma without a space.
If you care about the ordering, then use ORDER BY var.
If you want to remove duplicates, then use group_concat(distinct var).
Answer: You can use GROUP BY with group_concat, e.g.
SELECT ID, GROUP_CONCAT(Var)
FROM table
GROUP BY ID;

Here's the documentation for GROUP_CONCAT.


Models combinations

Question: My goal is time series forecasting. I have created a number of models to make predictions. I know that forecast quality can be improved by combining predictions from different models(linear combinations of forecasts, stacking etc) So the question is : How to  determine how  should i subset and combine my common models?
Are there some common or recommended approaches? Or it is mostly  question of intuition, lack and large number of attempts?
Answer: There are many ways to do what you want. The simplest is to take the average of all individual forecasts (empirically, it doesn't showed to be worse than theoretically optimal combinations). Another way is to make in-sample forecasts:

Split you data (from time 1 to T) into estimation period (from 1 to M) and validation period (from M+1 to T);
Use rolling windows or expanding windows schemes to produce forecasts on the validation period, and thus producing T-M forecast errors $y_{t}-y^{(forecast)}_{t}$.
Use this forecast error series to calculate some relevant measure (for instance, Root Mean Squared Forecast Error or Mean Absolute Error). You can construct weights in such a way that best individual models receive more weight. For example,
$weight_{k}=RMSE^{-1}(model_{k})/ \sum_{i} RMSE^{-1}(model_{i})$.

There are more elaborated techniques such as Dynamic Model Averaging or Selection that will do what you want. The estimation can be tricky if you are not familiar with bayesian inference though. Here the weights are the predictive probability of an individual model.
It should be mentioned that the Model Confidence Set is also used in several applied studies.
I hope it helps your studies!
Answer: Simple average works best. It's been shown empirically, but you can see it yourself. This phenomenon even has a name: forecast combination puzzle.
All the weight optimization schemes are a waste of time.
Here is one recent paper explaining this puzzle: Gerda Claeskens, Jan R. Magnus, Andrey L. Vasnev, Wendun Wang, The forecast combination puzzle: A simple theoretical explanation, In International Journal of Forecasting, Volume 32, Issue 3, 2016, Pages 754-762, ISSN 0169-2070,
Answer:
I know that forecast quality can be improved by combining predictions from different models

I suggest you review the concept of bias variance trade off, and understand currently you are under-fitting or over-fitting.
Note that, average models will increase bias and decrease variance. It will improve the performance when you are over-fitting data.

Models combinations


Jekyll - how to auto regenerate after menu.yaml changes?

Question: When I am developing with Jekyll, this is my watch task:
"watch": "bundle exec jekyll serve --incremental --config _config.yml",

Which works fine for normal page editing. However if I change a menu entry in something like _data/menu.yaml technically all pages would need to be regenerated. (Since all contain that menu…), yet only a few files get regenerated (and I even have no clue according what rules…).
  Server address: http://127.0.0.1:4000/
  Server running... press ctrl-c to stop.
  Regenerating: 1 file(s) changed at 2017-12-21 10:46:54

  Filename                                     | Count | Bytes | …
  ---------------------------------------------+-------+-------+-…
  feed.xml                                     |     1 | 2.54K | …
  sitemap.xml                                  |     1 | 2.80K | …
  css/main.sass                                |     1 | 0.38K | …
  _posts/2017-07-07-a-fancy-July-post.md/      |     1 | 0.16K | …
  _posts/2017-11-15-last-week-today.md/        |     1 | 0.00K | …
  _posts/2017-10-20-late-October-is-here.md/   |     1 | 0.00K | …

  ...done in 2.074543555 seconds.

Thus, all the time I have to stop, clean (rm -rf _site) and then fully build/start the watch again, to have an updated menu on the pages.
Is there a better way to do this? Am I missing some configuration?
Comment: Try with jekyll serve --force_polling
Comment: @marcanuy `--force_polling` [is a cure](https://github.com/jekyll/jekyll/issues/2926#issuecomment-55629052) when you are running out of [file handles aka 'inodes'](https://serverfault.com/questions/707490/how-to-determine-which-processes-have-most-inodes-opened) for regular file watching. This is not the cause of trouble here. Number of total files is rather small. (And I sorted this kind of error on a different occasion, when a different tool ran out of them...) The symptoms would afaik also be different ("watch not triggered", rather than "dependencies ignored").
Answer: --incremental is an experimental (unfinished) feature. Remove it from your task, as well as --config that is set to default, thus useless.
"watch": "bundle exec jekyll serve", will do the trick.
Comment: A slightler 'leaner' way is to stick with `--incremental` and `touch` the file(s), that references the yaml-File, i.e. `touch _includes/header.html`


No bash, qual é a diferença entre <, << e <<<?

Question: Estou aprendo agora a mexer com bash (Terminal do Ubuntu) e gostaria de entender a diferença entre esses três operadores.
Acho que < está relacionado à arquivos, mas não sei explicar o que ele faz descritivamente. Acho que é para mandar o valor do arquivo para o comando a ser executado.
Exemplo:
cat < index.php
#Exibe o conteúdo do arquivo

Quando uso <<, fica abrindo uma nova linha, sem executar o comando anterior (não entendi o que ele faz direito).
Exemplo:
cat <<
>
>

E o <<< me pareceu estar relacionado à expressões.
Exemplo:
cat <<< "O número é $((13 + 2))"
O número é 15

Então, em qual caso uso <, <<, ou <<<?
Qual é a finalidade de cada um?
Como se chamam?
Comment: Relacionado a [What are the shell's control and redirection operators?](http://unix.stackexchange.com/questions/159513/what-are-the-shells-control-and-redirection-operators). Tem outros bem interessantes também, como `<>`.
Comment: segue os links, além de uma ótima explicação ainda contém exemplos [Here Documents](http://linux.die.net/abs-guide/here-docs.html) [Here Strings](http://linux.die.net/abs-guide/x15683.html) [I/O Redirection](http://linux.die.net/abs-guide/io-redirection.html)
Answer: < Redirecionamento de entrada
Para comandos que esperam por uma entrada (normalmente teclado), você pode redirecionar um arquivo para a entrada (assim como você fez com o cat < index.php). Outro exemplo:
nc -l 8888 < /etc/fstab

<< Redirecionamento de entrada de string
É a mesma coisa, porém ao invés de passar um arquivo, você digita diretamente a string (em múltiplas linhas). Você acaba a entrada com um CTRL + D , ou da seguinte forma:
cat << FIM
bla bla
bla
FIM

Normalmente utilizado para imprimir mensagens na tela com indentação.
<<<
Não consegui achar uma definição para isso, mas uso como um redirecionador da saída de um comando, como se fosse um pipe invertido. Exemplo:
grep -i label <<< cat /etc/fstab

Comment: Esse exemplo do `<< ` me lembra muito o `HereDoc Syntax` do PHP
Comment: @WallaceMaxters em bash tem o "Here Document" (`<<EOF`) também, o PHP provavelmente se "inspirou" nessa parte assim como outras em coisas além do C, não conheço a história de decisões por trás do PHP :), só estou supondo. PS: o `<<<` se chama "Here String", assim como o `<<` se chama "Here doc" e o "Tab Suppression" (`<<-`, com o hífen) se eu não me engano apara espaçamentos no 'começo de linhas'. Depois vou testar, pq são coisas que usei muito pouco só pra confirmar se não confundi algo.
Answer: Basicamente:
< - Operador de entrada, o comando antecedente recebe o que for passado apos o '<';
<< - Operador de entrada, com append, você pode usar para mais de uma linha de entrada. Não vejo muita utilidade;
Paras as saídas idem
> - Operador de saída, a saída será direcionada para o que estiver a frente do '>'
Note que, em Linux, tudo são arquivos, então, se você deseja que a saída de um comando seja direcionada direto para uma tela auxiliar, você pode usar este comando, veja isso, apenas um exemplo.
>> - Saída com append, quer dizer que se a saída for para um arquivo, o mesmo será incrementado com a saída atual.
Já o outro operador, <<<, não vi muita utilidade, mas seria utilizado para ler entradas em string.

A wikipedia cita isso.
Este outro artigo é mais informativo.
E para quem está começando com o bash, vale a pena ver este.
Comment: @Dherik, vou postar alguns exemplos!
Comment: Acho que faltou só o `<<<`
Comment: Na verdade inverti ali, mas ja vou editar. Mas veja que o comantário do @Dherik acima esclarece todos os pontos.
Comment: @CelsoMarigoJr, coloque mais algumas informações destes operadores e até com um exemplo de cada. Aí a sua resposta fica melhor ainda. Eu, pessoalmente,  gosto de algo mais sucinto, mas não sei o que o Wallace espera :)
Answer:
< é o redirecionador de entrada, envia um arquivo para a entrada padrão (stdin) do comando
<< se chama "here documents", em geral é usado para escrever uma string inline no script e enviar ela para a stdin do comando. A string se encerra pelo token que segue o << aparecendo sozinho no início de uma linha:
$ xargs ls <<FIN
/tmp
FIN
<<< se chama "here strings", expande a expressão que segue o operador e a envia para a stdin do comando

Obs.: o exemplo do operador <<< dado pelo @cemdorst não é bom, ele funciona porque apenas a expressão imediatamente após o operador (no caso do exemplo, o cat) é passado como stdin do grep, o nome /etc/fstab é passado como argumento normal para o grep.
Há algumas variações, a documentação deles é bem descrita na manpage do bash (procure "Here Documents", "Here Strings").
Basicamente a utilidade deles é passar texto para a stdin de outros comandos, já que nisso (processamento de texto recebido via stdin) se baseia muito da programação em shellscript. Sem o "here documents" por exemplo, seria necessário usar comandos echo mais xaropes, ou criar arquivos externos extras além do script que se estiver escrevendo.


Tratar dados coletados através de uma api JSON

Question: Estou coletando dados fornecidos por uma API em JSON.
Com o código abaixo eu consigo visualizar que os dados foram coletados dentro do Subscribe.
Mas fora dele, dentro do próprio arquivo .TS eu não consigo manipular estes dados.
Eu tentei utilizar o promise, mas acho que não utilizei de forma correta, pois também não tive resultado positivo.
Como eu poderia tratar esses dados antes de apresentar na tela?
getHour() {
this.hourService.getData()
  .subscribe(
    posts => this.posts = posts,
    error => this.errorMessage = <any>error,
  () => console.log(this.posts));

  console.log(this.posts);
}

Comment: Você pode colocar o retorno desse console.log?
Comment: Opá, sim, já adicionei
Comment: Opa eles so estão disponíveis dentro do subscribe mesmo. Isso pq a chamada http e assíncrona.
Comment: Entendi, e para eu utilizar esses dados fora do subscribe eu precisaria utilizar um async ou await?
Comment: O rxjs e observables e outra forma diferente do async await para lidar com assincronizidade.
Comment: mas se esta dentro do subscribe, pq nao altera os dados, ja que ele foi recebido de forma correta? ou voce usa a sugestao do @EduardoVargas
Comment: @fsi o Eduardo explicou mais abaixo. Já estava achando o que ele disse tbm.
Answer: Pensa assim cara, quando vc fazer o hourService.getData uma requisição http e disparada quando ela for concluída o Código dentro do subscribe e executado(se for tudo bem com a requisição)
 getHour() {
    this.hourService.getData()
      .subscribe( //http disparado
        posts => this.posts = posts, //quando a requisição terminou e deu certo
        error => this.errorMessage = <any>error,//quando a requisição terminou e deu errado
      );

      console.log(this.posts);//aqui o http ainda não terminou por isso o undefined
}

Comment: Obrigado, foi exatamente o que aprendi sobre isso.

Estou usando um promise para utilizar os dados depois que eles foram coletados e atribuídos dentro do subscribe.
Answer: Você pode guardar esse retorno dentro de uma variável global.
var posts = this.posts;

Comment: opá, legal, mas a variável sempre fica vazia em tempo de execução.

Eu tento utilizar os dados em outra função ou mesmo usar esta variável para depois apresentar na tela, e a mesma sempre fica vazia.
Comment: declara a variável fora da função, dentro de um scopo global e dentro da função apenas atribua o valor a ela.


create a macro variable based on a condition SAS

Question: I have the following table
data have;
    input x1;
    datalines;
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    ;
run;

and I'm trying to create a macro variable which allocates the number of distinct entries up to a maximum of ten so I can automatically create the right number of bins for a histogram later (max 10 bins)
the code i'm currently trying to leverage is as follows but I'm unsure how to allocate the macro variable when there are more than 10 distinct observations
PROC SQL NOPRINT;
    SELECT COUNT(DISTINCT X1)
        INTO: BIN_X1
        FROM HAVE
        HAVING (COUNT(DISTINCT X1) LE 10);
QUIT;

How do I allocate the macro variable to be 10 if there are more than 10 distinct obs?
Comment: It sounds like you may want to use PROC RANK here with GROUPS=10?
Comment: I will read up about PROC RANK
Answer: Just use the SAS function min(,) to truncate the count to a maximum of 10.
proc sql noprint;
  select min(count(distinct x1),10)
    into :bin_x1 trimmed
  from have
  ;
quit;

So the SQL aggregate function count() will see how many distinct values of X1 exist in the dataset and then the SAS function min(,) will select the min of that number and 10.
Note that the SAS functions (min,max,etc) take two or more arguments and work just on those arguments for the current observation, but the SQL aggregate functions (min,max,etc) take only one argument and aggregate the values that argument represents across multiple observations.
Comment: nice, p.s. does the trimmed statement have any impact?
Comment: The `timmed` keyword will remove the spaces caused by converting a number to text so that it can be stored in a macro variable.
Comment: I've been looking for this my whole life
Answer: Are you trying to put 10 in a macro list, then you can use outobs= to limit the records. Question is which 10 records do you want when there are more than 10?
PROC SQL outobs=10;
SELECT X1
    INTO: BIN_X1 separated by ","
    FROM HAVE;
    QUIT;

    %put &Bin_x1;

Comment: I'm looking to count the total number of distinct observations, if there are more than ten distinct obs i.e. above there is a range of 11 distinct entries then i'd force the variable to be 10
Comment: So implementing automatic binning? Use NLEVELS within PROC FREQ to get the number of distinct values and then use macro logic to determine if you need to bin and then how you want to bin. there are some written macros around if you're not interested in rolling your own: http://support.sas.com/resources/papers/proceedings17/0969-2017.pdf


ios:How to an animation while i send request to my sever to control the refresh image rotate 360°

Question: so as the title, when the net request callback, stop the animation in this way:if the request immediately back, it will stop after 360 degrees rotated to recovery before the animation working. if it's the time is so lang, it will stop after 360 * (integer number) degrees.
What can i do to control it perfect?
My programming language is Objective-C.
Answer: Last night i solved this,but it's not perfect
First,creat an animation:
<code>- (void)initAnimation{
[CATransaction begin];
CGFloat angle = 1000000 * 360 * M_PI/180.0;
refreshAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
refreshAnimation.byValue = @(angle);
refreshAnimation.duration = 1.0 * 1000000;
refreshAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
refreshAnimation.removedOnCompletion = YES;

[CATransaction commit];
</code>
}
Second,before send request, add the animation to the imageView:
<code>    - (void)sendRequst{
[refreshImageView.layer addAnimation:refreshAnimation forKey:@"rotationAnimation"];
[self sendRequstToSever];
</code>
}
Finally,when the server feedback,remove the animation and set the imagView to the original position:
<code>- (void)changeAnimationStatus{
[refreshImageView.layer removeAnimationForKey:@"rotationAnimation"];
[UIView animateWithDuration:0.30 animations:^{
    refreshImageView.transform = CGAffineTransformRotate(self.view.transform, 0.0);
}];}
</code>
Answer: <code>CGFloat angle = 2 * M_PI;
refreshAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
refreshAnimation.delegate = self;
refreshAnimation.removedOnCompletion = NO;
refreshAnimation.repeatCount = CGFLOAT_MAX;
refreshAnimation.additive = YES;
refreshAnimation.byValue = @(angle);
refreshAnimation.duration = 0.9 ;
refreshAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animationStamp = [[NSDate date] timeIntervalSince1970];
[btn.layer addAnimation:refreshAnimation forKey:@"rotationAnimation"];
</code>
Then use the time to resolve this


Can I record more than 2 tracks at once using a Behringer Q802USB?

Question: I have a Scarlet 2i2, which I use to record Guitar, Bass, Vocals, and Drums. But I hate only being able to use two mics at once to record the drums. Will using the Behringer Q802USB allow me to mic the drums better? Also, if I use the mixer, what role will the 2i2 play in the recording process? I use Abelton Live btw. Basically what I am asking is whether or not the Behringer mixer would be a wise purchase for this use and if so, did I waste my money on the 2i2.
Comment: Oh and also, to avoid using too many tracks to record drums, can I run everything being recorded by the behringer into one of the inputs on the 2i2 to make everything being recorded from the drums on one track after I mix it on the Behringer? Thanks.
Comment: Well, whatever you do, check Behringer mixers user reviews, from what I remember, they know to be noisy.
Answer:
Will using the Behringer Q802USB allow me to mic the drums better?

The Q80 has two mic inputs and preamps, so does the 2i2. This means that you can have a 3 mic setup using both inputs in the Q80, and connecting that mix to the 2i2, using its remaining input for another mic (using the Q80 as mixer and the 2i2 as interface).
You could also try a 4 mic dual interface setup (using both devices as interfaces). It's possible with some interface combinations. I've never tried though.
So, in short, yes it will allow to mic better (as in more mics), but not by much. Probably not worth it.

Also, if I use the mixer, what role will the 2i2 play in the recording process?

Same as before, the role of an interface (providing conversion and I/O).

Basically what I am asking is whether or not the Behringer mixer would be a wise purchase for this use

I don't think it's worth it. If you want to do big multitrack recordings save for a 6 (at least) channel interface with hybrid inputs (so you can connect mics, line, and instrument to any input) with preamps for each input.
Some examples: Behringer U-PHORIA UMC1820, TASCAM US-16x08, M-Audio M-Track Eight, and PreSonus AudioBox 1818VSL.
But it depends in which sound you are going for. If what you have in mind can be achieved with 4 or 3 mics, then it will be probably worth it. Some styles (jazz comes to my mind) record drums with as few as two mics! And they sound beautiful.
You can do a lot of great stuff with 2, 3, and 4 mics. The problem is that you lose flexibility with such a small setup. Some drum sounds (specially in rock) are achieved through close-miking almost every element separately.

Oh and also, to avoid using too many tracks to record drums

I don't think there's such thing as "too many tracks to record drums". You use the necessary to achieve the sound you are looking for. Two mics can be the magic number, 9 mics can be too in another scenario. Don't get fixated in "i'm using too much or too few tracks" as long as you like the sound.

can I run everything being recorded by the behringer into one of the inputs on the 2i2 to make everything being recorded from the drums on one track after I mix it on the Behringer?

The Q80 can't record, but you can use its output (whatever you are mixing through it) and connect it to whatever compatible input you want, including the 2i2.
Comment: Thanks! I was saying too many tracks because abelton live limits you to 8 tracks. Yeah i will definitely get a mixer with more inputs. I recorded an ep with only 2 mics on drums and it was good but not as clear as I had in mind. It worked for that EP but what I am working on now needs a little more clarity and precision with the drum mics. Thanks!
Answer: If you need more mics, I suggest you get an audio interface with more mic inputs. There are some decent options with 4 mic inputs for a decent price. If you try to use two audio interfaces at the same time... you are asking for trouble.
A second consideration is the mics... What kind of mics are you using? If you use cardiod mics, they normally have a very noticeable proximity effect. That means that it is more difficult to get a balanced/natural sound if the source is large (drum sets, piano...), so you need more mics. Then you might get more easily into phasing problems... but that's another issue.
Normally, I'd say that just a pair of omni-directional mics can give you decent results also with drums, given that the room you record in is not too bad (omnis will pick up more room). Downside is that good mics are expensive, if you need to buy them.
Comment: Summarizing: If you are using cardiod mics, I would stay with the scarlett, and try to get a pair of omni-directional microphones --maybe somebody can lend them to you without buying them?


back-button doesn't work properly ionic famework

Question: I have this flow in my ionic app... login.html page(which is a "ion-view")->side-menu page(side-menu from ionic framework)->page2.html page(which is a "ion-view"). Now i want to implement "ion-nav-bar" with "ion-nav-back-button" in it. Normally when i want to go back from page2.html the app should sent me to side-menu page....instead, my app, sent me to login page. Seems like side-menu does not have "ion-view" in it and it is not recorded in app flow.  Any suggestion how can i solve that ? thank you
Answer: There is no a state for side menu, you can not 'go back' to open side menu.
In the normal, for the login view, you should disable the state temporally. Then the app will not 'go back' to login view. You can do it like this:
<code>$scope.doLogin = function () {
        Auth.login($scope.loginData, function () {
            console.log('login success');
            $ionicHistory.nextViewOptions({
                disableBack: true
            });
            $state.go('home');
        });
    };
</code>
And you can also clear the view history of ionic to avoid going back with:
<code>$ionicHistory.clearHistory();
$state.go('user.home');
</code>


How to generate 2 correlated Beta random variables

Question: I was wondering if it might be possible to generate 2 correlated $Beta$ random variables?
In other words,  I want to generate two Beta random variables which can be said to have come from two Beta distributions whose correlation is known to be "$\rho =$ some number"?
In R, I tried a simple linear transformation approach to achieve this:
set.seed(0)
X1 = rbeta(1e4, 5, 1) ; X2 = rbeta(1e4, 6, 1) ;  X3 = rbeta(1e4, 7, 1) ; a = -.5

Y1 = X1 + (a*X2) ; Y2 = X2 + (a*X3) ## Y1 and Y2 are meant to be correlated

cor(Y1, Y2)

plot(Y1~Y2, col = densCols(Y1, Y2) ) ; abline(lm(Y1~Y2), lty = 3, lwd = 2)

But the linear transformation approach above is particularly unprincipled. If you change a to .5, then the meant-to-be $Beta$ random variables go beyond 1:

P.S. There is apparently a principled way to do this as shown HERE.
Comment: *Exactly* how do you want the variables to be correlated?  There are myriad ways to construct them, so we need further restrictions.  A general method is to use a copula; another method would be to select a suitable [Dirichlet distribution](https://en.wikipedia.org/wiki/Dirichlet_distribution).
Comment: The interesting paper at https://arxiv.org/pdf/1406.5881.pdf  develops a bivariate distribution with beta marginals, that admits of all correlations in $[-1,1]$.  They do not give an simulation algorithm but that shouldn't be to difficult.
Comment: Proportions don't necessarily have Beta distributions. In fact, for a fixed denominator that would be a mathematical impossibility: the proportion is discrete while a Beta variable is continuous.  You could immediately adopt the [solution I posted yesterday](https://stats.stackexchange.com/questions/284996) about generating correlated Binomial variates, because those provide nice models of the counts that you *really* need for the t-test: you can't (validly) do a t-test on proportions alone.
Comment: Indeed, the method I proposed for generating correlated binomials seems to fit your situation perfectly, because it constructs them as sums of correlated binary ("dichotomously scored") random variables. Thus, all you have to do is decide how much correlation you want among the pre- and post-responses, item by item, and you're on your way.
Comment: There is nothing preventing `Y1` or `Y2` from being outside $(0,1)$ so they cannot be beta distributed?
Comment: If those proportions are based on substantially varying denominators, or if some of them approach closely to $0$ or $1$, then the t-test will be suspect because such data constitute *prima facie* evidence that one or more underlying assumptions of the t-test do not hold.  In any event it is *far* better to base the tests on the actual counts using (say) a generalized linear model.
Comment: No, I haven't. Please summarize what you take away from that paper!
Comment: @rnorouzian Can you explain why you think the method is not stable. Where are you seeing the problem?
Comment: @Kjetil That's a nice paper: it outlines several different solutions (and the simulation method will vary with the nature of the solution).  But please note that when the Beta distributions have different shapes, it will not be possible to achieve correlations arbitrarily close to $+1$.
Comment: Do you want to know the correlation between them, or you just want them to be correlated in some way?
Comment: @rnorouzian If you want people to solve this problem with minimal effort for you, then show them this behavior. Display the plots, and clearly state the problems you are facing.
Comment: @whuber, I just need to generate two Beta random variables which can be said to have come from two Beta distribution whose correlation is known to be "rho = some number"?
Comment: Do you care about the parameters of those variables or not?  What ranges of $\rho$ do you need to handle?  Are you concerned *only* about two Beta variables or will you be working with more than two?
Comment: @whuber, **(1)** Regarding shape parameters, I want to obtain the mean and variance of each mother Beta distribution. So, this means the shape parameters are only important in computing these two moments. More specifically, I want the two variances of the mother Beta distributions to be equal but means be different. **(2)** I just need to handle $ .3 =< \rho <= .9 $.
Comment: @whuber, what I need the above for is for a virtual (simulated) paired-samples t-test study in my field. I need to produce `n` proportions for the pre-test stage, and `n` proportions for the post-test stage. But I want to assume that the proportions in the pre-test and the post-test are positively correlated by some known degree in the mother populations.
Comment: @whuber, I appreciate your comment, in the actual study that I'm trying to simulate, researchers use a measurement tool that only produces proportions, so are you suggesting that **two** sets of, say, **30 proportions** obtained **from a pre-test and a post-test** can not be compared with each other using a paired-samples t-test? If so, what alternative test, do you recommend?
Comment: @whuber, wow, you helped me tremendously by this comment. So, generating correlated random data for this situation would be what, binomial? To be clear, the measurement tool in my case, is a test comprised of $n$ dichotomously scored items?
Comment: @whuber, thank you so much, just quickly which glm test in particular you're suggesting to compare the two sets of pre- and post counts?
Comment: It sounds like a good setting for applying logistic regression.
Comment: @whuber, I just posted a question [**HERE**](https://stats.stackexchange.com/questions/285191/distribution-of-scores-by-a-measurement-tool), do you think there is anything I can improve in my question to add more clarity?
Comment: Related to https://stats.stackexchange.com/questions/441924.
Comment: @rnorouzian, Your link  in the "p. s." remark doesn't work.
Comment: Related to https://stackoverflow.com/questions/31459291.
Answer: As others have said, the number of possible answers here is endless. We can ignore the issue of the actual distribution. Obviously, for shift and scale distributions, the regression approach is the easiest method to generate correlated data, but it's not an omnibus. Beta RVs are not shift/scale distributions, as you have clearly noticed, if you add 1 to a Beta random variable, it is no longer Beta distributed. The copula method is the most theoretically sound approach for which there are several papers, code examples, and R packages.
In R, a very interesting method is just to sort arrays. Back to your case, simulate independent Beta random variables stored in a matrix. and for a desired correlation, choose a number of rows proportional to that correlation and jointly sort those rows. To gain a closer match, you can iteratively sort more or less rows until convergence is met. Sorting the vectors maintains the univariate distributional properties.
The below example is by no means an efficient implementation, but rather an illustrative example.
## initial setup
set.seed(123)
n <- 100
x <- matrix(rbeta(n*2, 2, 2), n, 2)

## user supplied desired correlation
p <- 0.5

## np is the number of rows to sort, npprev and npnext to evaluate convergence
npprev <- n*p
np <- n*p
xnew <- x
xnew[1:np, ] <- apply(xnew[1:np, ], 2, sort)
pest <- cor(xnew[,1], xnew[ ,2])

## add 1 row to sort if under correlated, subtract 1 row if overcorrelated
npnext <- np + sign(p-pest)

## iterative until exact match OR alternating pattern reached
while (pest != p & npnext != npprev ) {
  npprev <- np
  np <- npnext
  xnew <- x
  xnew[1:np, ] <- apply(xnew[1:np, ], 2, sort)
  pest <- cor(xnew[,1], xnew[ ,2])
  npnext <- np + sign(p-pest)
}


Understanding proof of: Every tournament on n vertices has an acyclic set of size $log_2(n)+1$

Question: I have the following proof that I am trying to understand. I understand every part except why $A \cup \{v\}$ is an acyclic set. I get that $A$ is an acyclic set, but what guarantees that introducing $v$ does not introduce a directed cycle?
Answer: Introducing $v$ cannot create a cycle because all edges between $v$ and $A$ are directed in the same direction: we chose $A$ from the subset $N^{-}(v)$.
A cycle that contains $v$ would have to use an edge oriented from $A$ to $v$ and an edge oriented from $v$ to $A$, which do not both exist. A cycle that does not contain $v$ - well, that goes back to the induction hypothesis, since that would just be a cycle in $A$.
Comment: I was reading $N^-(v)$ as $N-v$ i.e. the induced sugraph without the vertex $v$ instead of the subgraph induced on the endpoints of the out-edges of $v$, and this is what caused confusion.


unable to link my custom content type nodes to a menu I created

Question: I created a custom content type (pics). I can add this new "pics" content to my site (and if I want to, it can appear on front page, but I don't want to...) with no problem. But I would like those new added contents appear in my new menu (called Photos).
When I created my new content type I got a " machine name" : "pics". Then I created a new menu called "photos" and I put this name into the path field like this: http://www.example.com/drupal/pics
But it doesn't work this way. The menu will be empty with a Page not found message.
I'm new to drupal, so please bare with me.
Please let me know the solution.
Comment: you don't need to say thank you in a question, or use a signature (-Sam).  How did you create the menu? is it a regular menu? a Views menu? a custom hook_menu() page? something else?  we need more information please
Comment: Structure/Menus/Main Menu/Add link
Comment: I'm not sure what to put at the "path" section (of my menu called Photos) to be able to put every node created by add content type /pics).I want any user of the site to be able to use this add content type/pics feature and I want all these contents go under my created menu: Photos. This way you can see together under 1 menu all the contents that users created...
Comment: so you want a separate menu listing for each user? or a single menu with ALL of the content?  either one is a bad idea and will overload the menu system, slowing the site down considerably as content continues to be created
Comment: I wanted a single menu for all contents that were created by clicking on add content/pics. So all the "pics" contents will be under the menu "Photos". I understand what you are saying with system overload, but at least theoretically it would be good to know how to achieve this type of organization.
Answer: By default, Drupal 7 does not create a filtered list of content. You're going to want to use Views Page to create a list of content.
Delete the menu item you created, then install https://www.drupal.org/project/views and its dependency https://www.drupal.org/project/ctools
If you have Drush installed...
drush dl views
drush -y en views views_ui

In your browser, go to /admin/structure/views
Click "Add new view".

View Name: Photos
Show [Content] of type [Pics]
[X] Create a page

Page title: Photos
Path: pics
Display format: Table

Click "Continue & edit" to customize

For information on Views, see https://www.drupal.org/documentation/modules/views
Comment: Thanks everyone! jonpeck "view" solution works for me the best.
Comment: Yes, that was the best answer to my question. The view helped a lot to achieve what I wanted.
Answer: Getting around the error message:
You're getting that error like 'Page not found message', because when creating a menu item like you tried to do, Drupal expects the path that you enter to exist. If however you would specify node/xyz (with xzy = actual node ID of the node you want the menu item to point to), then Drupal would find that path, and you should not get such error message.
Possible alternative:
Create a new node, or edit an existing one, and specify these values while in the edit form of that node:

the path you want the node to use (= 'drupal/pics' in your case).
the menu item you want to be created for it (within menu 'photos').

After saving such node, you should get the desired result also.
Curious to hear if either of both approaches answer your question ...
Answer: based on your comments, this works - this code assumes a content type Article, adjust as necessary:

create a parent menu item within the main menu (PICS), set Show as Expanded TRUE, set the Parent to Main Menu

in the content type set up, set the Menu Settings to Main Menu, with PICS as the parent

There are modules that will do this, but if all you need is a simple menu entry override, you can use this custom module:

custom_menu_entry.info
name = Custom Menu Entry
core = 7.x
description = Automatically Creates an Entry on Node Save
package = custom

custom_menu_entry.module
<?php
/**
*   Custom Menu Entry Module - Force a menu entry to be created on node save
**/
function custom_menu_entry_node_insert($node)
{
    if($node->type == 'article')
    {
        $node->menu['enabled'] = true;
        $node->menu['link_title'] = $node->title;
    }
}

This will force the menu entry to be created on node save, but again it is unwise in your particular use case - A view is a more suitable option.


How to target cloned element in DOM (jQuery)

Question: Here is my markup:

180

Click me

130

Click me

270

Click me

So I've cloned and appended some of the .box divs in jQuery from .main to .container using this code:
$(document).ready(function(){
"use strict";
    $(".box_button").click(function(){

        var box_content = $(this).parents('.box').clone(); //Box is cloned
        var price = $(box_content).find(".box_price");

        $(price).toggleClass('box_price sc_box_price'); //Class changed to sc_box_price
        $(box_content).append('.container'); //Box is appended
    });
});

Before appending, I changed the class of the child element .box_price to .sc_box_price.
I have another code, which is supposed to calculate the sum of all .sc_box_price and append it to .cost.
$(document).ready(function(){
"use strict";

    var box_price = $(".sc_box_price");
    var total = 0;

    $(box_price).each(function(){
        total += parseInt($(this).text());
    });
    $('.cost').prepend("
"+total+"
");
    console.log(total);
});

For some reason I am unable to target .sc_box_price. Perhaps it is because .sc_box_price is not actually added to the DOM? How do I fix this?
Comment: Please check that you do not change class only after the item has been cloned. I'm expecting changes to the original object after cloning will not reflect on the clone.
Comment: Don't you want instead: `$(box_content).appendTo('.container');` ??? And fyi, `box_content` is already jq object, so no need to wrap it again, e.g: `var price = box_content.find(".box_price");` and btw, `price` is already jq object, etc...
Answer: Instead of append() your need to use appendTo to append your cloned box.
There is difference between appendTo and append i.e
take this new thing and appendTo an already existing thing
vs
take already existing thing and append this new thing

Thats why you need to use appendTo()
now after appending add your other code into the onClick event after appendTo statement Also instead of appending a div everytime your can just change the text of the cost div. I suppose this is what your want.

$(document).ready(function(){

    $(".box_button").click(function(){

        var box_content = $(this).parents('.box').clone(); //Box is cloned
        var price = $(box_content).find(".box_price");

        $(price).toggleClass('box_price sc_box_price'); //Class changed to sc_box_price

        $(box_content).appendTo('.container'); //Box is appended

         var box_price = $(".sc_box_price");
          var total = 0;

          $(box_price).each(function(){
              total += parseInt($(this).text());
          });

          $('.cost').text(total);

          });

});
.cost {
  color: red;
}

180

Click me

130

Click me

270

Click me

Answer: There are many erros in your code. What was the idea? Something like this:

$(document).ready(function(){
"use strict";
    $(".box_button").click(function(){

      var box_content = $(this).parents('.box').clone();
      var price = box_content.find(".box_price");

      price.toggleClass('box_price sc_box_price');

      $('.container').append(price);
      //box_content.append('.container'); //Box is appended

      var box_price = $(".sc_box_price");
      var total = 0;

      box_price.each(function(){
        total += parseInt($(this).text());
      });

      $('.cost').html("Total:"+total);
    });
});

180

Add to Cart

130

Add to Cart

270

Add to Cart

  Cart:

Answer: Your append call is backwards.  Try this.
Please note, though, that the appended "Click me" elements will have no click events associated with them. Is this your intention?
Also, I think you may want to use an html call on $('.cost') instead of append.

$(document).ready(function(){
"use strict";

    $(".box_button").click(function(){

        var box_content = $(this).parents('.box').clone(); //Box is cloned
        var price = $(box_content).find(".box_price");

        $(price).toggleClass('box_price sc_box_price'); //Class changed to sc_box_price
        // $(box_content).append('.container'); //Box is appended
        $('.container').append(box_content); //Box is appended

        calculate_price();
    });
});

function calculate_price() {
    var box_price = $(".sc_box_price");
    var total = 0;

    $(box_price).each(function(){
        total += parseInt($(this).text());
    });
    $('.cost').html("
"+total+"
"); // formerly: $('.cost').append
    console.log(total);
}

180

Click me

130

Click me

270

Click me


Knowing what chord to play next?

Question: This is a question I've had for a long time but I've never really found the answer other than following some suggestions on chord sequences like 1,3,2,5 and 1,4,5, but I'm sure there must be another way of coming up with a sequence of chords that work together.
I usually write my melodies first and try to work out what chords work with it based on the notes I'm playing. Occasionally I try to write some harmonies first when I compose, but with either approach, I'll reach a point where I'm dumbfounded on where I can go next.
Let's take a simple example, I'm writing a comedy orchestral track now starts with C major, then goes to Gb major (essentially shifting key). I've written some lines on top of those chords, but now I can't find where to go next.
Is there any musical theory I should be drawing on to find out where to go next?
Answer: Nearly every melody line has underlying harmonies (chord) which reflect the notes in each bar. E.g., in a bar of C-E-F-G, there are notes which make Cmaj., so that chord will fit in that bar.
In a bar with, for example, an F and A, this will give you more scope - F, Dm, G9 come to mind.
Often there's a note which won't fit a chord, and if it's on a weak part of the bar, it won't count towards that chord. Weaker parts could be 2nd or last beat, or maybe the 'and' between beats. 1st and 3rd (in 4/4) are places to look for components of a chord. When you move out of key, as in C - G♭, there are no common notes, so either change chord within the bar, or possibly use a B♭ note, which could fit both C7  and G♭
Really need that sample.
Comment: Ok, I've got a quick mp3 I put together and a pdf of the melody line - as the melody moves across different instrument groups, I've put it all into one line so it's easier to see what's going on. As I'm still learning how to write music properly, I apologise in advance if this isn't the way to write the melody correctly (I left the key signature as C major)! My question is I don't know what chords I could play next after the Gb major at the end of this sequence. I haven't come up for a melody for it yet btw. mp3: http://bit.ly/comedy-mp3 and the pdf: http://bit.ly/comedy-melody
Comment: When you write out music try to keep to ##  OR bb.Mixing them mixes up the reader ! There are occasions when an accidental MUST be # or b specifically, for technical reasons, but not in this tune. Quite like the arrangement. You've moved a tritone - the Devil's interval. Used a lot in jazz. What's next depends on the next bit of tune.Down one semitone may keep the 'jaunty' feel.

Knowing what chord to play next?


Ratio and Proportions Question

Question: Can someone please answer this with proper explanation.
At sahara shopping centre, a person can purchase as much articles at a time as his or her age that is a person of a years age can purchase only n similar articles at a time .Amisha is younger to her elder brother who has just entered into his twenties. One day Amisha went to the Sahara Shopping centre, she purchased same toffees at a particular rate on the ground floor. But when she reached on third floor she found that she could purchase double the no. of toffees with the same amount as she had spent on the ground floor. Also to purchase the same no. of toffees on the third floor she had to spend Rs. 2 less than that of on the first floor. How many toffees did she buy?
Comment: This is hard to follow, and it doesn't appear that enough information has been given.  If I understand the rules (unlikely) then it's possible that $A$ bought one on the ground floor and two on the next, or two on the ground floor and four on the next.  Why not?  Do purchases on different levels count as "at a time" or not?   As I read it, all we know is that the toffees got cheaper on the upper floor.
Comment: Well, I am confused too. Actually I posted this on behalf of a friend. This questions was part of a mock test and the answer there is 12.  But with no explanation.
Comment: $12$, huh.  So the theory is that she bought $4$ on the ground floor and $8$ on the upper floor.  But I don't even see a way to reverse engineer that solution.  I think a lot of information has been left off.
Answer: <code>   Rupees      per rupees
</code>
Ground   X     x       Y      = XY
Third    X     x       2Y     = 2XY
|
|-->  X/2    x       2Y     = XY
<code>   X - X/2 = 2 => |X = 4|
</code>
If the X=4 then multiple of 4 must be obtain from option , which gives the no. Of toffes did she get at last. And multiple of 4 is 12.
So the answer is 12, even though data is insufficient for value Y in it.

Ratio and Proportions Question


Drupal ajax call within form

Question: I am trying to call ajax call within form. here is my code
<?php

function clicktell_form_alter(&$form, &$form_state, $form_id) {
    //print_r($form);

    if($form_id=='user_register_form') {

        $form['choice_wrapper']['poll_more'] = array(

            '#type' => 'submit',

            '#value' => t('More choices'),

            '#description' => t("If the amount of boxes above isn't enough, click here to add more choices."),

            '#weight' => 1,
            "#executes_submit_callback" => FALSE,

            '#ajax' => array(

                'callback' => 'poll_choice_js',

                'wrapper' => 'poll-choices',

                'method' => 'replace',

                'effect' => 'fade',

            ),);

    }
}

function poll_choice_js($form, $form_state) {
    print_r($form_state);
    return $form['choice_wrapper']['choice'];

}

when i click on more choice button it is not calling poll_choice_js function. i checked this in firebug but didn't get any result
Thanks
Comment: What is `choice_wrapper` ?
Comment: nothing. we can ignore it
Answer: For the ajax callback  and hook_form_alter() to function you should clear the caches from the performance link.
Also you should change the following
return $form['choice_wrapper']['poll_more'];

Comment: no it is not working
Answer: Use  return
function poll_choice_js($form, $form_state) {
    return('something');
    return $form['choice_wrapper']['choice'];
}

Drupal ajax call within form


isometry on compact space

Question: I need to prove that an isometry $f$ on a compact metric space $X$ is necessarily bijective. I've got most of the proof,  but I can't figure out why any point in $X-f(X)$ would necessarily have to have some open neighborhood disjoint from $f(X)$.
Comment: Spoiler found by Google (first hit on searching the title of the question): http://at.yorku.ca/cgi-bin/bbqa?forum=homework_help_2003;task=show_msg;msg=0875.0001
Comment: In other words, you want to know why the image of the compact set $X$ under the continuous map $f$ is closed in the metric space $X$?
Comment: @yrudoy: Have you seen any theorems involving compact spaces and continuous maps, or involving compact subsets of metric (or Hausdorff) spaces?
Comment: @yrudoy: A compact subset of a Hausdorff space is closed. i.e. the complement is open...
Comment: Aha, no need to post it. The proof is standard.
Comment: @lhf Unfortunately, it just states "Take x in $X \ f(X), 0 < epsilon < dist(x,f(X))$". Why is it that $dist(x,f(X))>0$?
Comment: @Jonas: Sure. But I can't think of one that would guarantee it, though I wouldn't be surprised if I was overlooking something.
Comment: @yrudoy: $f$ is an isometry.  You should be able to show that it is uniformly continuous using the definition.
Comment: got it. I was using the topological definition of continuity and it isn't immediately apparent from that angle.
Comment: BTW, here is a sort of converse: http://math.stackexchange.com/questions/12285/isometry-in-compact-metric-spaces
Answer: $f(X)$ is compact. If $x_0\notin f(X)$, because $X$ is separated for all $x\in f(X)$ exists two disjoints open sets $U_x$ and $V_x$ such that $x_0\in U_x$ and $x\in V_x$. We can find $n\in\mathbb N$ and $x_1,\cdots,x_n\in f(X)$ such that $f(X)\subset \bigcup_{j=1}^nV_{x_j}$. Now put $U:=\bigcap_{j=1}^nU_{x_j}$.
Comment: @Henno: this is an answer to the question "I can't figure out why..." (i.e. just a proof that $f(X)$ is closed).
Comment: What is the contradiction? Where do you use the isometry?
Comment: I red too fast the problem. I tought that Henno wanted a neighborhood of $x_0$ disjoint form a neighborhood of $f(X)$.

isometry on compact space


How do I amend this notch error for a boxplot?

Question: I have included notches in my boxplot with regards to the following code:
> boxplot(dframe1$High.calcium..diet, dframe1$Low.calcium.diet,         # The basic boxplot command
+ varwidth = FALSE,                        # width of boxes represents sample size
+ notch = TRUE,                           # add a notch indicating 95% confidence intervals
+ names = c("High Calcium diet", "Low Calcium diet"),                     # labels the different boxes
+ col=c("violet", "light green"),          # colours the different boxes
+ xlab = "Diet",                  # adds an x-axis label
+ ylab = "parathyroid hormone per 100 ml blood",      # adds a y-axis label
+ cex.lab = 1.6,                          # adjusts the size of the axis labels
+ cex.axis = 1.3,                         # adjusts the size of the axis numbering
+ las = 1)
Warning message:
In bxp(list(stats = c(12.7, 14.4, 16.2, 18.25, 23.1, 15.1, 40.2,  :
  some notches went outside hinges ('box'): maybe set notch=FALSE
>

However, I receive the warning as above, but I do not want to set notch to FALSE, as I want the notches. How would I fix this?
And this is the data that goes with it:
High calcium  diet  Low calcium diet
14.5    52.7
18.2    44.4
15  125
14.3    66.4
25.7    23.3
17.3    88.3
23.1    38.8
16.2    42.9
12.7    15.1
18.3    41.6
13.2    53.2

Comment: I would probably start by looking at the range of the hinges in `box`
Comment: @koekenbakker , I would post that as an answer.  You could also point out that if the OP doesn't care about the ugly notches and just wants to get rid of the warnings they can use `?suppressWarnings` ...
Comment: There is nothing really to fix here, it just tells you that some notches went outside the boxes. But there is nothing wrong with that, it's just what your data produces.
Answer: It means that the confidence interval (i.e. size of the notches) is larger than the interquartile range (IQR). The size of the notches depends on your data: +/-1.58 IQR/sqrt(n) see ?boxplot.stats.
If you take a larger sample (increase n), the size of the notches may decrease.
You can also decide to plot boxplots without notches and manually add markers to your confidence limits.
Create boxplot without notches:
boxplot(dframe1, notch=F, ylim=c(0,125))

Retrieve confidence intervals of both columns in data frame:
ci_high = boxplot.stats(dframe1[,1], do.conf=T)$conf
ci_low  = boxplot.stats(dframe1[,2], do.conf=T)$conf

Add these to plot:
points(x=c(1,1), y=ci_high, col=2, pch=8)
points(x=c(2,2), y=ci_low, col=2, pch=8)


Error trying to write a value to a cell in an Excel worksheet in C#

Question: I am trying to write my column names to an Excel worksheet using:
for (int i = 0; i < intColumnCount; i++)
{
    strColumnName = dataPHLIP251.Columns[i].ToString();
    excelWorksheet.Cells[2, i].Value = strColumnName;
}

But I keep getting

System.Reflection.TargetInvocationException: 'Exception has been
thrown by the target of an invocation.'

I have tried it with and without the Value on the Cells.  How do I get around this problem?
Comment: You have to specify the library you are using for working with Excel
Comment: Are you using Excel interop? That's a very expensive way of creating Excel files. `xlsx` is a ZIP package containing XML files using a well defined format. You could create them yourself but libraries like EPPlus or NPOI allow you to load data with headers with as little as `sheets.Cells.LoadFromDataTable(myDT,true);`, `LoadFromCollection(someArray)` or even `LoadFromDataReader`
Comment: Yes I am using Excel interop.
Comment: I can add a date to a cell using   excelWorksheet.Cells[1, 1] = strDate; which works fine but when I try adding the column names I get the exception.
Comment: A similar problem I once had, but for which I can't recall the library I was using, was about the column index, which started from `1` not from `0`. Just saying...
Answer: I think the problem is that excel interop is not handeling cells like arrays in terms of access.
0 = out of range. Try:
excelWorksheet.Cells[2, i+1].Value = strColumnName;

If that is not the case, please provide the code where you generate the excelworksheet instance and in which line exactly the Exception is thrown.
Answer: I think reason is still not clear with this code line. You should check the inner exception for this error which may have further explanation for causing this error.
Piece of code you shared has nothing to do with this. For better explanation please share more code.


Jackson Mapper Serialize/Deserialize ObjectId

Question: My POJO is :
import org.jongo.marshall.jackson.id.Id;

public class User {

    @Id
    private String id;
    private String name;
    private int age;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

I get user from mongo database and want to output him into a file with jackson mapper
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter().writeValue(new File("c:/user.txt"), user);

and I get something like this in my file
{
    "name" : "John",
    "age" : 23,
    "_id" : {
      "time" : 1358443593000,
      "inc" : 660831772,
      "machine" : 2028353122,
      "new" : false,
      "timeSecond" : 1358443593
    }
}

I need id field to be stored into a file as string because when i deserialize this object my id field in pojo looks something like this
{
   "time":1358443593000,
   "inc":660831772,
   "machine":2028353122,
   "new":false,
   "timeSecond":1358443593
}

Any help will be apreciated
Comment: _id is an id generated by mongodb
Comment: This cannot be all the code. Where did the `_id` attribute come from?
Comment: Does this answer your question? [java spring MappingJacksonJsonView not doing toString on mongodb ObjectId](https://stackoverflow.com/questions/9065042/java-spring-mappingjacksonjsonview-not-doing-tostring-on-mongodb-objectid)
Answer: Answering my own question. Found solution here Spring 3.2 and Jackson 2: add custom object mapper
I needed custom object mapper and ObjectId serializer.
public class ObjectIdSerializer extends JsonSerializer<ObjectId> {

    @Override
    public void serialize(ObjectId value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeString(value.toString());
    }
}

public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {
        SimpleModule module = new SimpleModule("ObjectIdmodule");
        module.addSerializer(ObjectId.class, new ObjectIdSerializer());
        this.registerModule(module);
    }

}

Comment: You can use the [`ToStringSerializer`](https://fasterxml.github.io/jackson-databind/javadoc/2.2.0/com/fasterxml/jackson/databind/ser/std/ToStringSerializer.html) provided by jackson.
Comment: Is their any other setting I need to make apart from writing this two classes. because it is still not working for me.
Comment: Should I do any other additional steps? this doesn't work for me. I use it like below:

CustomObjectMapper oMapper = new CustomObjectMapper();

    return oMapper.convertValue(obj, Map.class);
Answer: I found an easy attempt using springboot 2.5.4.
Just by adding a Jackson2ObjectMapperBuilderCustomizer bean will do the trick.
@Configuration
public class JacksonMapperConfiguration
{
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        return builder -> builder.serializerByType(ObjectId.class, new ToStringSerializer());
    }
}

Answer: Here is a simple solution for serialization if you don't have a model for the object being stored:
client.getDatabase("db").getCollection("collection").find().onEach { it["_id"] = it["_id"].toString() }

"onEach" is a kotlin function. If you use Java, then change it to a simple foreach.
It's not efficient to iterate over the entire list just for the id. Only use it for small lists where performance is less important than short code.


How do I  keep the sum of related nodes' specific field values in a field?

Question: I have two different content types: "Parent" and "Child".
On Parent nodes, there is a multi-value reference field where I keep some Child nodes of this node. Every child node has a field "Integer" and I keep some integer values in it.
What I want is keeping the sum of those Integer values of all child nodes of a Parent inside a field "Sum".
So I will have:

Parent 1 (sum=11)

Child one (integer=3)
Child two (integer=6)
Child three (integer=2)

Is it possible?
Answer: I managed to do this with Rules module, to keep it short.

By default, gave 0 to the value of integer for Parent content type.
Added a rule to calculate the value of Parent's integer field by summing up the values of child nodes and setting it to Parent's integer value. Event is creating new content
Added a rule to recalculate the value of Parent's integer field when adding or updating a Child content. For this, I am calculating the difference of new and old integer values of Child node. Then, adding this value to Parent's integer value.

If anyone is interested, I can also give the details of the rules.
Below is an export of the second rule:
<code>{ "rules___aa_test" : {
"LABEL" : "__aa_test",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "node_update" ],
"IF" : [
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_parent_story" } },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_time_left" } },
  { "entity_has_field" : { "entity" : [ "node:field-parent-story" ], "field" : "field_time_left" } }
],
"DO" : [
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "node:field-time-left" ],
        "op" : "-",
        "input_2" : [ "node-unchanged:field-time-left" ]
      },
      "PROVIDE" : { "result" : { "difference" : "Difference" } }
    }
  },
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "node:field-parent-story:field-time-left" ],
        "op" : "+",
        "input_2" : [ "difference" ]
      },
      "PROVIDE" : { "result" : { "result" : "Calculation result" } }
    }
  },
  { "data_set" : {
      "data" : [ "node:field-parent-story:field-time-left" ],
      "value" : [ "result" ]
    }
  }
]
</code>
}
}


Hearing and differentiating tones

Question: I've had some basic classical (piano and organ) music training, and I even had to do an exam, where we were given an A, and we had to write down a simple melody which was played on a piano. I don't find it hard as long as the music I have to listen to is clear and not polyphonic. However, as soon as there are more than 2-3 voices at the same time, i find it hard to differentiate.
I also find it difficult to even recognize heavily distorted chords on an electric guitar for example; even though a friend of mine who plays guitar says amplified electric guitar should be even easier to hear. I can't relate to the more 'heavy' music, because it often sounds like static, I can't hear it as tones.
Is this a hearing problem, is it lack of training/experience or should I consult a doctor?
Answer: It's not a problem, it's just lack of training. You need more interval training for your ears. Since you can't make out polyphonic melodies, try training polyphonic intervals.
Like an example, play C+E -- F+A -- G+B -- C+E and other similar examples. After a while, try something a bit more difficult. Also, try to change the intervals. In the example I gave you ,all of the intervals were major thirds. Try out all of the intervals.
Also, it would be good to practice chords. Listening to chords, since chords are 2,3 or more notes being played at the same time. That will help you.
For the distorted part, I have the same problem. I find it more difficult to make out a distorted chord rather than a clean one. I think that is normal. Maybe your friend has been playing distorted chords for some time, so he is used to them.
If you practice chords and intervals for quite some time and you still can't make out polyphonic melodies, then maybe you should consider going to a doctor or something. But you must remember you have to be patient with this. Actually with music in general.
(and keep in mind that Rome wasn't build in a day)
Comment: I mean the notes. Play simple notes together like C with E that is followed by F with A etc.. Start with 2 notes chords and then go to 3 and 4 and maybe even more. Classical orchestras usually have 4 different notes/voices if I'm not mistaken. To learn how to tell apart all of them will take a lot of practicing. But I suggest you start off with something easier before moving to 4 note chords
Comment: Thanks, fist of all. I'm not sure I understand you correctly: with C+E, do you mean the notes or the chords?
I mostly recognize intervals correctly when I hear notes following each other, often even if two notes are played at the same time. However in a normal band- orchestra- or whatever setting, this is rarely the case, and there are many fast changes of notes who usually overlap and are often played by different instruments, that's when I get completely confused.
Answer: The problem with distorted guitar sounds is that all the harmonics are accentuated. A pure (clean) guitar note will have some basic harmonics sounding, but they will be 'recognised' and will give you a note to quantify. Given two notes, the harmonics will be heard from both, and depending what the interval is, it will be easy or hard to specify the notes. A fifth (or fourth) will sound fairly clear, as the harmonics from each will 'blend'. However,most other intervals will produce loads of harmonics which clash, thus confusing your ear.This is one of the reasons that power chords work better than others.
Could be that your ears are pretty much highly tuned, and the harmonics are confusing them.Amplified guitar does not necessarily equal distorted guitar.
Obviously, practise listening to chords/intervals, but use other instruments as well as the guitar sounds. And bear in mind that those guitar noises are not always 'musical'...
Comment: @Matteaus - highly tuned , as in perfect (but maybe not absolute !) pitch. The ability to hear notes and sing or play them back on an instrument accurately.
Comment: So basically overtones and such are louder in a distorted guitar? And I am somewhat untrained to recognize them? Thanks, that's quite a reassuring information, I was beginning to think that something was wrong with my hearing.

I'm not sure I understood the 'highly tuned' part though.

Hearing and differentiating tones


Can the Median and mean be "zero"?

Question: I have a data set with 32 variables. I take the summary of these variables. I found that some of these variables have a Mean or Median equal to zero. Is that Ok? Can I still work with this data set? Why they are equal to zero?
My data is Ionosphere (I worked with the variables 3:34). The data is available online from KEEl. The description of the data is:
<code>Ionosphere data set

1: Description.

This data set is a modified version of the Ionosphere database present in the UCI repository. The second attribute has been removed due it only a single value (0) was present for it.

The task is to determine if a given signal is Good (g) or Bad (b).

2: Type.            Classification
3: Origin.          Real world
4: Instances.       351
5: Features.        33
6: Classes.         2
7: Missing values.  No

8: Header.

@relation ionosphere
@attribute Pulse1 integer [0, 1]
@attribute Pulse3 real [-1.0, 1.0]
@attribute Pulse4 real [-1.0, 1.0]
@attribute Pulse5 real [-1.0, 1.0]
@attribute Pulse6 real [-1.0, 1.0]
@attribute Pulse7 real [-1.0, 1.0]
@attribute Pulse8 real [-1.0, 1.0]
@attribute Pulse9 real [-1.0, 1.0]
@attribute Pulse10 real [-1.0, 1.0]
@attribute Pulse11 real [-1.0, 1.0]
@attribute Pulse12 real [-1.0, 1.0]
@attribute Pulse13 real [-1.0, 1.0]
@attribute Pulse14 real [-1.0, 1.0]
@attribute Pulse15 real [-1.0, 1.0]
@attribute Pulse16 real [-1.0, 1.0]
@attribute Pulse17 real [-1.0, 1.0]
@attribute Pulse18 real [-1.0, 1.0]
@attribute Pulse19 real [-1.0, 1.0]
@attribute Pulse20 real [-1.0, 1.0]
@attribute Pulse21 real [-1.0, 1.0]
@attribute Pulse22 real [-1.0, 1.0]
@attribute Pulse23 real [-1.0, 1.0]
@attribute Pulse24 real [-1.0, 1.0]
@attribute Pulse25 real [-1.0, 1.0]
@attribute Pulse26 real [-1.0, 1.0]
@attribute Pulse27 real [-1.0, 1.0]
@attribute Pulse28 real [-1.0, 1.0]
@attribute Pulse29 real [-1.0, 1.0]
@attribute Pulse30 real [-1.0, 1.0]
@attribute Pulse31 real [-1.0, 1.0]
@attribute Pulse32 real [-1.0, 1.0]
@attribute Pulse33 real [-1.0, 1.0]
@attribute Pulse34 real [-1.0, 1.0]
@attribute Class {g, b}
@inputs Pulse1, Pulse3, Pulse4, Pulse5, Pulse6,
Pulse7, Pulse8, Pulse9, Pulse10, Pulse11, Pulse12, Pulse13, Pulse14,
Pulse15, Pulse16, Pulse17, Pulse18, Pulse19, Pulse20, Pulse21,
Pulse22, Pulse23, Pulse24, Pulse25, Pulse26, Pulse27, Pulse28,
Pulse29, Pulse30, Pulse31, Pulse32, Pulse33, Pulse34

@outputs Class
</code>
This is an example of one variable (20 observations out of 351).
<code> 1  0.605
 2 -0.517
 3  0.546
 4 -1
 5  0.344
 6 -0.0457
 7  0.746
 8  0
 9  0.904
10 -0.337
11  0.907
12  1
13  0.937
14  1
15  1
16 -1
17  0.942
18  1
19  0.786
20  0
</code>
Comment: You have provided a very little information about your data set and it is very difficult to say if the mean and median of the variables can be zero or not unless we know the variables, still I don't see why we cannot have mean and median zero. We can have mean and median zero.
Comment: Does the interval notation $[-1, 1]$ and $[0, 1]$ used by your unnamed software have the standard mathematical meaning?
Comment: @PrasadDalvi Thank you for your comment and sorry for my little information. I will provide much more details about my data.
Comment: Much better to give an example. Ionosphere and KEEI won't mean much to most readers without their doing a web search.
Comment: @NickCox Thank you for your comment. I have added a description of the data with their domain.
Comment: @NickCox I used R software. The values of each variable are between these numbers. For example, the value of each variable is between -1, 1.
Comment: Thanks for the confirmation. Where does the `@attribute`, ` @relation` etc. come from?
Comment: @NickCox The `@attribute` means the variables. `@relation` means the name of the data. `@input` and `@outpu` are the variables and the class that we need to classify the data, respectively.
Comment: It would be surprising if the *sample* mean of a purely continuous variate were exactly zero, unless the data had been artificially centered. It's not at all clear from the scanty (and not very clearly explained) information here whether this is the case.
Answer: There is no rule that the mean and median cannot be zero.
This can be expanded a little:

A variable that is always zero will necessarily have mean and median zero.
A variable that can in principle be only zero or positive can only have mean zero if all values in practice are zero. On the other hand, such a variable can and will have median zero if more than half of the values are zero. Such variables are very common and include counts and indicators (commonly, variables that are 1 or 0).
Point 2 applies also to variables that can in principle be negative or zero, although such variables seem less common.
A variable that can be negative, zero, or positive can also have mean and median zero.
It's even possible to have mean and median zero for a variable that cannot be zero, as contemplation of $-1, -1, 1, 1$ will make clear.

Being puzzled by this implies that looking more closely at your data (graphs of distributions, other summary statistics) is needed.
Comment: I guess you mean first qua**r**tile. But all the arguments used for median apply also with modification to any other quantile.
Comment: Thank you so much for your help. Is that OK for 1st Quantile as well?
Answer: If you have a random variable following a standard normal distribution, then we would expect its mean to be 0 so this is perfectly possible.

Can the Median and mean be "zero"?


jQM Theme does not work properly on front page

Question: I've started to use Drupal recently, and installed the jQuery Mobile module and the jQM Theme in order to make a Mobile site / Web app.
I'm having some troubles getting it to work properly.
The thing is, that when I go to my sites front page, I get this view:

However, if I click on, let's say 'Store Locator', I get this view:

So my problem is, that it seems like the jQuery Mobile stuff (js or css) does not load correctly on the front page.
If I inspect the page, it seems to be the right template, but somehow the js og css isn't loaded correctly.
Has anyone had the same problem?
Comment: in which browser have you tested it? (e.g. in which browser have you made the screenshots above?)
Answer: Are you including the CSS/JS via your themes .info file? If so, the CSS/JS should be included in the order specified there. The only other thing you should check is that if you have a page override for the homepage (page-front.tpl.php) and verify you have the correct JS/CSS in place in there as well.
Good luck
Comment: Hmm.. I quite new to all this, so I have to get my head around all the .info .module files and structures.. But the funny thing is, that the frontpage somehow loads some of the styling, cuz if I disables styles, it looks completely different.. So it's kinda weird..


Why am I getting a java.lang.Charsequence cannot be applied to a char error?

Question:  }else if(readUserEmail.contains('a')){
        System.out.print("true");

Why am I getting a java.lang.Charsequence cannot be applied to a char error? In this case readUserEmail is a string of an email.
Answer: The contains method of the String class takes a CharSequence as an argument, but you are providing a character literal as indicated by using single quotes.
Change your 'a' to "a". Double quotes are for String (which implements the CharSequence interface) and single quotes are for characters.


A cada rodada loop var troca

Question: Estou desenvolvendo um sisteminha em shell que tem um formulario para adicionar alguns campos.
Quantidade Produto ValorUnitario etc...
Preciso que a cada volta que o loop da ele troque uma váriavel, para assim eu chamar ele no formulario!
No caso é os prev, a cada rodada ele troca para prev1, no outro prevdois troca para prevdois1, ai na outra rodada, prev2, prevdois2 e assim por diante, isto porque eu vou chamar estas váriaveis para salvar em um formulario. alguma ajuda?
while [ "$sair" != "sair" ]; do
i=$((i+1))
for filter in Produto Quantidade Descricao PrecoUnitario PrecoTotal; do
    read -p "${filter}: " ${filter}$i

**prev=$Produto
prevdois=$Quantidade**
done
    read -p "Deseja sair? [sair] ou enter para continuar: " sair
done

Comment: Você quer adicionar na frente 1, 2, 3 .... da string do prev?
Comment: ISSO! pode ser! é que eu preciso chamar estas variaveis diferentes em cada round para um formulario!
No caso vamos dizer que na primeira passada o prev vale abacate
prev=abacate na segunda prev ele vale abacaxi 2prev=abacaxi
E assim por diante!
Comment: Eu nunca vi essa sintaxe de colocar asteriscos `*` antes do nome da variável
Comment: Isso pq eu botei negrito aqui no site kkkkk, descartar!
Não consegui me expressar direito!
Eu preciso que a cada loop a variavel troque e fique fixa!
Para eu conseguir chamar no formulario... já que são produtos diferentes.
Sacaram? a saida vai ser em um arquivo HTML, problema que a saida como é de se esperar é sempre a ultima rodada. e eu precisava que ficasse independente...
Exemplo:

$prev
$prevdois

$prev
$prevdois
Answer: Use eval com o seu contador i:
eval prev$i=$Produto
eval prevdois$i=$Quantidade

Quando i = 1, o resultado acima será:
prev1=$Produto
prevdois1=$Quantidade

No entanto, ainda que possível fazer dessa forma, sugiro que dê uma olhada em arrays para executar esta tarefa.

A cada rodada loop var troca