meaning of async in this code

Question: <code>var response = $.ajax({
            url: "/Master/chkDuptindustryid",
            type: "POST",
            data: "{ 'systemid':'" + systemid + "'}",
            async: false,
            contentType: "application/json; charset=utf-8",
            success: function (response) {
</code>
Comment: It will run synchronously, so it will wait for it to execute.
Comment: Did you check http://api.jquery.com/jQuery.ajax/ ?
Answer: Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called.  If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.
The first A in AJAX is Asynchronous. That function returns before the AJAX call returns (or at least it can).  There are only two options:
Make the AJAX call synchronous (not recommended) with the async: false option; or
Change your way of thinking. Instead of returning HTML from the function you need to passin a callback to be called when the AJAX call succeeds
Answer: What is says: you can do a synchronous call instead of asynchronous one, which is a default.
http://api.jquery.com/jquery.ajax/

By default, all requests are sent asynchronously (i.e. this is set to
  true by default). If you need synchronous requests, set this option to
  false. Cross-domain requests and dataType: "jsonp" requests do not
  support synchronous operation. Note that synchronous requests may
  temporarily lock the browser, disabling any actions while the request
  is active. As of jQuery 1.8, the use of async: false with jqXHR
  ($.Deferred) is deprecated; you must use the success/error/complete
  callback options instead of the corresponding methods of the jqXHR
  object such as jqXHR.done() or the deprecated jqXHR.success().
Answer: Taken from http://api.jquery.com/jquery.ajax/

async (default: true)
  Type: Boolean
  By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

Sp basically, it would force the request to be made synchronously and lock the browser.
Answer:
async (default: true) Type: Boolean By default, all requests are sent
  asynchronously (i.e. this is set to true by default). If you need
  synchronous requests, set this option to false. Cross-domain requests
  and dataType: "jsonp" requests do not support synchronous operation.
  Note that synchronous requests may temporarily lock the browser,
  disabling any actions while the request is active. As of jQuery 1.8,
  the use of async: false with jqXHR ($.Deferred) is deprecated; you
  must use the success/error/complete callback options instead of the
  corresponding methods of the jqXHR object such as jqXHR.done() or the
  deprecated jqXHR.success().

source

meaning of async in this code


drawing balls from an urn

Question: Suppose there are 7 golf balls in an urn and you draw balls in 3 stages without replacement.  First you draw 2, then 3, and then the remaining 2.  How many ways are there to do this?
I believe the answer would be ${7\choose 2}{5\choose 3}$ but I am making this question up so  would like to verify the answer.
Comment: A definite improvement. Is there anything in particular making you unsure of your answer? Can you explain the reasoning by which you arrive at it?
Answer: Your answer appears correct.
In particular, the number of ways will be the number of ways of choosing groups of 2,3 and 2 from a set of 7.
This is the multinomial coefficient ${7 \choose 2, 3, 2} = \frac{7!}{2!\, 3! 2!}$.
As you state in your question, its value is equal to ${7\choose 2}{5\choose 3}$, which you can arrive at via a number of different routes.

drawing balls from an urn


Base table not found ... my_site.key_value_expire doesn't exist

Question: I was having some issues with syncing a site to Acquia via their devdesktop application, and so I started doing some troubleshooting -- including trying to copy the database over to a new site. At some point during the process, I must have installed/uninstalled something that the site didn't like. The frontend of the site is still functional, but the admin side is toast, giving me the "The website encountered an unexpected error. Please try again later." error on every page. I tried repairing the key_value table, but phpmyadmin fails, stating that "The storage engine for the table doesn't support repair".
I've seen suggestions in other similar issues on how to properly drop and recreate this table. I'm hoping that somebody can provide similar help here, assuming that that is the issue.
If it's helpful, here's the full log that is returned via drush when I try to do something like drush pm-disable modulename. I have the feeling that it's mostly not applicable to this issue, but I figured it wouldn't hurt to include it.
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'jakesfireworksdev_dev.key_value_expire' doesn't exist in                                                                                [error]
/Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Statement.php:59
Stack trace:
#0 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Statement.php(59): PDOStatement->execute(Array)
#1 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Connection.php(610): Drupal\Core\Database\Statement->execute(Array, Array)
#2 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php(81): Drupal\Core\Database\Connection->query('DELETE FROM {ke...', Array, Array)
#3 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Query/Delete.php(55): Drupal\Core\Database\Driver\mysql\Connection->query('DELETE FROM {ke...', Array, Array)
#4 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/KeyValueStore/DatabaseStorage.php(165): Drupal\Core\Database\Query\Delete->execute()
#5 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/modules/update/update.module(642): Drupal\Core\KeyValueStore\DatabaseStorage->deleteAll()
#6 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/modules/update/update.module(258): update_storage_clear()
#7 [internal function]: update_themes_uninstalled(Array)
#8 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Extension/ModuleHandler.php(402): call_user_func_array('update_themes_u...', Array)
#9 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Extension/ThemeInstaller.php(269): Drupal\Core\Extension\ModuleHandler->invokeAll('themes_uninstal...', Array)
#10 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Extension/ThemeHandler.php(173): Drupal\Core\Extension\ThemeInstaller->uninstall(Array)
#11 /Users/mrweiner/.composer/vendor/drush/drush/commands/core/drupal/environment.inc(320): Drupal\Core\Extension\ThemeHandler->uninstall(Array)
#12 /Users/mrweiner/.composer/vendor/drush/drush/commands/core/drupal/pm_8.inc(83): drush_theme_uninstall(Array)
#13 /Users/mrweiner/.composer/vendor/drush/drush/commands/pm/pm.drush.inc(1237): _drush_pm_uninstall(Array)
#14 /Users/mrweiner/.composer/vendor/drush/drush/includes/command.inc(422): drush_pm_uninstall('rdfui')
#15 /Users/mrweiner/.composer/vendor/drush/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#16 /Users/mrweiner/.composer/vendor/drush/drush/includes/command.inc(199): drush_command('rdfui')
#17 /Users/mrweiner/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#18 /Users/mrweiner/.composer/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#19 /Users/mrweiner/.composer/vendor/drush/drush/drush.php(12): drush_main()
#20 {main}

Next Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'jakesfireworksdev_dev.key_value_expire' doesn't exist: DELETE FROM {key_value_expire}
WHERE  (collection = :db_condition_placeholder_0); Array
(
    [:db_condition_placeholder_0] => update
)
 in /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Connection.php:671
Stack trace:
#0 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Connection.php(635): Drupal\Core\Database\Connection->handleQueryException(Object(PDOException), 'DELETE FROM {ke...', Array,
Array)
#1 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php(81): Drupal\Core\Database\Connection->query('DELETE FROM {ke...', Array, Array)
#2 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Query/Delete.php(55): Drupal\Core\Database\Driver\mysql\Connection->query('DELETE FROM {ke...', Array, Array)
#3 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/KeyValueStore/DatabaseStorage.php(165): Drupal\Core\Database\Query\Delete->execute()
#4 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/modules/update/update.module(642): Drupal\Core\KeyValueStore\DatabaseStorage->deleteAll()
#5 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/modules/update/update.module(258): update_storage_clear()
#6 [internal function]: update_themes_uninstalled(Array)
#7 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Extension/ModuleHandler.php(402): call_user_func_array('update_themes_u...', Array)
#8 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Extension/ThemeInstaller.php(269): Drupal\Core\Extension\ModuleHandler->invokeAll('themes_uninstal...', Array)
#9 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Extension/ThemeHandler.php(173): Drupal\Core\Extension\ThemeInstaller->uninstall(Array)
#10 /Users/mrweiner/.composer/vendor/drush/drush/commands/core/drupal/environment.inc(320): Drupal\Core\Extension\ThemeHandler->uninstall(Array)
#11 /Users/mrweiner/.composer/vendor/drush/drush/commands/core/drupal/pm_8.inc(83): drush_theme_uninstall(Array)
#12 /Users/mrweiner/.composer/vendor/drush/drush/commands/pm/pm.drush.inc(1237): _drush_pm_uninstall(Array)
#13 /Users/mrweiner/.composer/vendor/drush/drush/includes/command.inc(422): drush_pm_uninstall('rdfui')
#14 /Users/mrweiner/.composer/vendor/drush/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#15 /Users/mrweiner/.composer/vendor/drush/drush/includes/command.inc(199): drush_command('rdfui')
#16 /Users/mrweiner/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#17 /Users/mrweiner/.composer/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#18 /Users/mrweiner/.composer/vendor/drush/drush/drush.php(12): drush_main()
#19 {main}

Answer: It turns out that the table I was attempting to repair was key_value, and not key_value_expire which is what was throwing the error. I'm not sure what happened to the table, but it seems like something caused it to be deleted. I was able to import the key_value_expire table from another database and the error halted.


Load theme tpl after form submit

Question: From a custom module in Drupal 7 I am trying to load a template after I submit and process my form.
I can load the theme fine from a page callback:
function mymodule_theme() {
  $themes = array(
    'mymodule_report' => array(
      'template' => 'themes/mymodule_report',
      'arguments' => array(),
    ),
  );
  return $themes;
}

function mymodule_menu() {
  $items = array();
  $items['reports/performance'] = array(
    'title' => 'My Module Performance Report',
    'page callback' => '_mymodule_report',
    'access arguments' => array('mymodule_client'),
  );
  return $items;
}

function _mymodule_report() {
  return theme('mymodule_report');
}

All of that works fine (e.g I can go to www.mysite.com/reports/performance and my tpl loads.).  The problem is when i submit a form, after I process the form I want to pass the form data to the template, and load the same template page.
I modified the hook_theme like this:
function mymodule_theme() {
  $themes = array(
    'mymodule_report' => array(
      'template' => 'themes/mymodule_report',
      'variables' => array('parameters' => NULL),
    )
  );
  return $themes;
}

And in my submit handler for my form after I gathered all my form values into an object ($submission), I added this at the end:
 return theme('mymodule_report', array('parameters' => $submission));

All that happens is my form reloads...what am I missing?
Comment: @Jack-PL while editing to improve formatting is usually a good thing, editing **code** should be avoided - except putting it into a code block if it isn't. Things like proper line breaks can be cause and solution to errors, so only OP is really supposed to edit them.
Answer: So I found a solution that works...of course if there's another or better way, I'd love to know.
I added this to my form:
  if (!empty($form_state['nnjob_mtbf']['mtbf_results'])) {
    $form['result'] = array(
      '#markup' => $form_state['nnjob_mtbf']['mtbf_results'],
    );
  }

And then to my form submit handler:
  $form_state['nnjob_mtbf']['mtbf_results'] = theme('nnreport_client_perf_report', array('parameters' => $submission));
  $form_state['rebuild']=TRUE;

And voila, template loads like a champ.

Load theme tpl after form submit


Drush install fails within Vagrant Puppet

Question: I originally posted this on SO but thought I'd probably get more traction on the Drush side of things from you guys.
I've just gotten a new MacBook running Mavericks.
Unfortunately, I can't get our current project running on it.
We're using Vagrant and Puppet and during the vagrant up phase, I get a message telling me err: /Stage[main]/Drush::Git::Drush/Exec[first drush run]: Failed to call refresh: /usr/bin/drush status returned 255 instead of one of [0] at /tmp/vagrant-puppet-1/modules-0/drush/manifests/git/drush.pp:32
I can successfully vagrant ssh into into the instance but it's clear that Drush doesn't exist.
The only difference between the 2 systems is the operating system. All other files are from the same git repo and same branch.
Any insight would be welcome as this is a total ball-ache.
Thanks,
Steven
Comment: Could you post your drush module? Not sure it'll help as it works on another machine, but might be useful to see what it's trying to do
Comment: Sure - it wasn't myself that originally setup the Vagrant/Puppet config so I'm a little in the dark. Here's the drush.pp that's being referenced https://gist.github.com/stevieg83/def440cc4002640da17a
Answer: The drush.pp you are using is out of date.  I have used that one successfully in the past, but just a few days ago, Drush switched to using Composer to install, so running drush status will no longer download the console table.  Instead, you must run composer install after pulling Drush, or just install Drush via composer.  See the Drush project page for details.
The Drush Puppet module you mention will need to be updated to adjust for this change in procedure.
Note:  The drush.pp you are using would probably work if you told it to check out one of the Drush 6.x tags instead of using master (the default).  Haven't tried that, though.
Comment: Thanks Greg. It looks like that may exactly have been it. I don't think the other guys in the team have actually done a rebuild of the vagrant instance. I changed to branch 6.x and so far it looks to be working as expected.


how to put arguments into contextual filters

Question: In this post http://drupal.org/node/228959 says that i need to add an code to the argument of view2,
I add a contextual filter in views 3, but where is the spot to place the following code?
<code>if (arg(0) == 'user' && is_numeric(arg(1))) {
    return array(arg(1));
}
</code>
Answer: There's a comment in that article down below with a code to import for D7 and Views 3.
If you import that code into your Views 3 and then study the Contextual Filters and the Relationships you should get a good idea on how to achieve this.
Comment: i see, so there ain't a easier way to do it


Question on the proof that jump times of a Poisson process are totally inaccessible

Question: I am reading the proof that the jump times of a Poisson process are totally inaccessible from the following post : https://almostsuremath.com/2010/06/24/poisson-processes/#scn_pp_def1
From definition 9 in https://almostsuremath.com/2009/11/30/predictable-stopping-times/#scn_pst_def1
a stopping time $\tau$ is totally inaccessible if $P(\sigma=\tau<\infty)=0$ for all predictable stopping times $\sigma$.
In the proof below, the author shows that, using the compensated process $M_t=X_t - \lambda t$ being a martingale, that the jump times of a Poisson process $X$ are totally inaccessible, by showing that $P(\Delta X_\tau \neq 0)=0$ for each predictable stopping time $\tau$.
My questions are:

In the proof, how are we able to replace $\tau$ by $\tau \wedge t$? How does this not hurt generality here?

In the final equalities, how are we able to take the limit outside of the expectation in computing $E[M_\tau - M_{\tau_n}]$?
Answer: For 1: Suppose that $\tau \wedge t$ is totally inaccessible for all $t>0$ and let $\sigma$ be a predictable stopping time.  By the monotone convergence theorem for sets, $P(\sigma = \tau < \infty) = \lim_{t \rightarrow \infty} P(\sigma = \tau \wedge t < \infty)$.  But for all $t > 0$ we have $\tau \wedge t$ is totally inaccessible, so $P(\sigma = \tau \wedge t < \infty) = 0$, and hence $P(\sigma = \tau < \infty) = 0$ as well.
For 2: This follows from the fact that $M_{\tau_n} = \mathbb{E}[M_\tau | \mathcal F_{\tau_n}]$ and $\{\mathbb{E}[X|\mathcal B]: \mathcal B \text{ is a sub-$\sigma$ algebra}\}$ is a uniformly integrable class of random variables for any integrable $X$.
Comment: I assume you mean $t\to \infty$ in the limit?
Comment: Yes, sorry about that.  It's fixed now.


How to enable / disable a module in settings.local.php

Question: I'm using a settings.local.php for my local development environment. This is a Drupal 7 site.
I've seen a few references to this via google search, but none of the examples are working for me. I don't want to install a module to make this work if it is possible to accomplish the same result by adding a couple lines to the settings.local.php file.
I use this file all the time for a number of sites so I know it is being read properly. I've also used it to set variables (file_temporary_path, for example) and that works too. It is just enabling / disabling modules I'm having trouble with.
Any thoughts / suggestions?
Answer: I ended up using the Habitat module (https://www.drupal.org/project/habitat).
It has a UI that allows you to enter the names of modules you want turned off or on in each environment you have. Things like making sure Devel is ON in a local or DEV environment, and Views UI is OFF for a LIVE site.
It is simple to use and I haven't had any issues with it yet on the sites on which I have installed it.


Function preprocess_views_view if not logged in

Question: I have added two javascripts for one page only using preprosess in template.php. The two scripts seem to work well.
The jquery version I include on this page/view is interfering with admin overlay and other stuff for the editor. I'd like to apply this preprosess only if the user is not logged in.
/**
 * Equal height row javascript + jquery 1.10.2 - in page-view (my-view-page)
 */
function mytheme_preprocess_views_view(&$vars) {
   $view = $vars['view'];
   // Make sure it's the correct view
  if($view->name == 'myview') {
     // add needed javascript
     drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/jquery-v1-10-2.js');
     drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/equal-height-row.js');
  }
}

Is it possible to correct this function to make sure the scripts are not served to logged in users? Or does it require a different approach like preprocess_html?
(For now there is not going to be registered users other than editors)
(Using Drupal 7.25 and custom subtheme of Responsive Bartik)
Answer: Sure, add either:
global $user;

to your function and check its uid status or wrap the drupal_add_js in an IF block using the Core API function user_is_logged_in()
For exmaple:
$user_is_not_logged_in = (user_is_logged_in() === FALSE);
if ($user_is_not_logged_in) {
  if ($view->name == 'foo') {
    /* drupal_add_js(...); */
  }
}

EDIT:
So the full thing (doing your homework for you) would look like this:
/**
 * Equal height row javascript + jquery 1.10.2 - in page-view (my-view-page)
 */
function mytheme_preprocess_views_view(&$vars) {
   $view = $vars['view'];
   // Make sure it's the correct view
  if($view->name == 'myview') {
    if (!user_is_logged_in()) {
      // add needed javascript
       drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/jquery-v1-10-2.js');
       drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/equal-height-row.js');
    }
  }
}

Comment: I would say the extra variable is probably not needed though, you could just do if (!user_is_logged_in()) { // do stuff. }
Comment: @tenken Sorry for any silly questions - but are this going inside the `function mytheme_preprocess_views_view(&$vars)`?
Comment: see my edit. I wrote out english describing the solution so you might better learn something. by giving you something to copy and paste; you learn less.
Comment: @tenken I appreciate your effort on this. I've already tried this solution based on your first suggestion, and the javascripts does not show for any visitor. My original code works, but serves the javascripts to all visitors.
Comment: Sorry. My testing method where not right. I finally got it working. Thank you for your patience


Binary Search tree, node deletion crash

Question: I coded a Binary Search tree. Every function works just fine, but the "deletenode". This method is supposed to delete the node which *p is pointing at.
However if the node is a leaf it prints the tree without the node and crashes.
If the node is no leaf it doesnt even print the tree and crashes.
I dont see any possible way to recreate the problem in less code, because i dont know where the problem is supposed to be. I'm Sorry.
Maybe someone can load it up and see where the problem is, because im really desperate.
<code>#include <stdio.h>

void *malloc(size_t size);
void free(void *ptr);

struct tnode {
    int content;
    struct tnode *left; /* left subtree */
    struct tnode *right; /* right subtree */
};

struct tnode *talloc(void) /* reserves memory*/
{
    return (struct tnode *) malloc(sizeof(struct tnode));
}

struct tnode *addelement(struct tnode *p, int i)   /* addelement: adds new node */
{
    int cond;
    if(p == NULL) {
        p = talloc(); /* make a new node */ p->content = i;
        p->left = p->right = NULL;
    } else if(p->content == i) {
        return p;
    } else if(i < p->content) /* goes to the left side */ p->left = addelement(p->left, i);
    else /* goes to the right side */ p->right = addelement(p->right, i);
    return p;
}

struct tnode *addtree(struct tnode *top, struct tnode *p) /* adds subtree to main tree*/
{
    if(p == NULL)
        return top;
    else
        return addtree(addtree(addelement(top, p->content), p->right), p->left);
}

int printtree_preorder(struct tnode *p) /* prints tree in preorder*/
{
    if(p != NULL) {
        printf("%d \n", p->content);
        printtree_preorder(p->left);
        printtree_preorder(p->right);
    }
    return 0;
}

int printtree_inorder(struct tnode *p)  /* prints tree in inorder*/
{
    if(p != NULL) {
        printtree_inorder(p->left);
        printf("%d \n", p->content);
        printtree_inorder(p->right);
    }
    return 0;
}

int printtree_postorder(struct tnode *p)    /* prints tree in postorder*/
{
    if(p != NULL) {
        printtree_postorder(p->left);
        printtree_postorder(p->right);
        printf("%d \n", p->content);
    }
    return 0;
}

struct tnode *searchnode(struct tnode *p, int nodtodelete) /* pointer is set on the node which is supposed to be deleted  */
{
    if(p == NULL) {
        printf("Baum ist leer oder Element nicht vorhanden \n");
        return 0;
    }
    if(p->content == nodtodelete) {
        return p;
    }
    if(p->content < nodtodelete) {
        return searchnode(p->right, nodtodelete);
    }
    if(p->content > nodtodelete) {
        return searchnode(p->left, nodtodelete);
    }
}

struct tnode  *deletenode(struct tnode *p, struct tnode *pBaum) /* Is supposed to delete the node which the *p is pointing at */
{
    if((p->left == NULL) && (p->right == NULL)) {
        free(p);
        printf("Ist Blatt \n");
        return pBaum;
    }
    if((p->left == NULL) && (p->right != NULL)) {
        struct tnode *rechterTeilbaum = p->right;
        free(p);
        pBaum = addtree(pBaum, rechterTeilbaum);
        return pBaum;

    }
    if((p->right == NULL) && (p->left != NULL)) {
        struct tnode *linkerTeilbaum = p->left;
        free(p);
        pBaum = addtree(pBaum, linkerTeilbaum);
        return pBaum;
    }
    if((p->left != NULL) && (p->right != NULL)) {
        struct tnode *rechterTeilbaum = p->right;
        struct tnode *linkerTeilbaum = p->left;
        free(p);
        pBaum = addtree(pBaum, rechterTeilbaum);
        pBaum = addtree(pBaum, linkerTeilbaum);
        return pBaum;
    }
}

int main() {
    struct tnode *Baum = NULL;
    struct tnode *tmpPos = NULL;

    Baum = addelement(Baum, 10);
    Baum = addelement(Baum, 30);
    Baum = addelement(Baum, 20);
    Baum = addelement(Baum, 35);

    tmpPos = searchnode(Baum, 35);

    if(tmpPos != 0) {
        printf("Zu loeschendes Element: %d \n", tmpPos->content);
        Baum = deletenode(tmpPos, Baum);
    }

    printf("Inorder Ausgabe\n");
    printtree_inorder(Baum);

    printf("Postorder Ausgabe\n");
    printtree_postorder(Baum);

    printf("Preorder Ausgabe\n");
    printtree_preorder(Baum);
}
</code>
Comment: Ask yourself: how does an inner node get notified if one of its children gets removed? I.e. how will it know, if its `right` or `left` pointers are still valid once you called `deletenode`? Your programme crashes, because during printing at some point you're trying to dereference a dangling pointer.
Comment: @BeyelerStudios if i call 'deletenode' the memory which 'p' is pointing at is cleared in every case. So if im correct this will also delete the 'left' and 'right' pointer which causes them to be invalid. If im wrong though, feel free to tell me how i can solve my problem
Comment: You're wrong. Please read a tutorial on pointers i.e. look up *dangling pointer*: raw pointers are not updated magically (they are simple memory addresses), you need to invalidate `left` and `right` of the parent of the deleted node yourself.
Comment: @BeyelerStudios because i just started working with pointers I'm not really sure how to do that. Do you mind giving me an example for my code specificly? I tried setting  'p = NULL;' after evey 'free(p)' but that didnt work.
Answer: In the deletenode function, you aren't checking to see if p is NULL before you try to dereference it. Are you segfaulting?
Comment: yeah forgot to add the NULL check, but im not segfaulting.
Comment: Im compiling everything with CodeBlocks, i dont get any errors or warnings. It just tells me that the .exe stopped working and crashes. If you compile it yourself you most likely will see the same.

Binary Search tree, node deletion crash


Port forwarding vs UPnP

Question: I am wondering what the security implications are between running UPnP or Port Forwarding on my Netgear R6300 router are.... is one better than the other?
If I have UPnP turned on and this test passes successfully (https://www.grc.com/su/UPnP-Rejected.htm), do I have anything to worry about?
Google brings up tons of links, but I wanted to ask some experts.
I ask this because I see things like this in my router log:
<code>[LAN access from remote] from 18.104.22.168:18574 to 192.168.0.100:51413, Monday, Jun 18,2012 22:18:11
[LAN access from remote] from 22.214.171.124:24386 to 192.168.0.100:51413, Monday, Jun 18,2012 22:18:11
[LAN access from remote] from 184.108.40.206:60509 to 192.168.0.100:51413, Monday, Jun 18,2012 22:18:11
[LAN access from remote] from 220.127.116.11:33358 to 192.168.0.100:51413, Monday, Jun 18,2012 22:18:10
</code>
Thanks...
Comment: You're comparing apples and oranges. uPnP is a communications mechanism that enables devices on a network to set up port forwards for themselves. As such, it's a security nightmare, and has no place on even a well-managed home network let alone a professional network.
Answer: Use manual port forwarding to accomplish what you need.
Enabling UPnP support destroys most of purposes of firewall/NAT, as infected machine now has simple and universal interface to redefine firewall at will (in effect disabling any security)
and your logs are okay, it says that service running on local machine in LAN on port 51413 has been accessed from various IPs from the Ineternet (probably due to application using uPnP to enable access from outside to that port. Or manual forwarding setup)

Port forwarding vs UPnP


How to find the image of this linear transformation?

Question: Let $T\colon\mathbb{R}^3\to\mathbb{R}^3$ be a linear transformation such that $T\begin{pmatrix}x\\y\\z\end{pmatrix}=\begin{pmatrix}2x+2y-z\\2x+5y-2z\\4x+4y-2z\end{pmatrix}$. I am asked to find the image of $T$.
So, let $p=\begin{pmatrix}p_1\\p_2\\p_3\end{pmatrix}$ be in the image of $T$.
$$
T\begin{pmatrix}x\\y\\z\end{pmatrix}=p \implies \begin{pmatrix}2x+2y-z\\2x+5y-2z\\4x+4y-2z\end{pmatrix}=p \implies \begin{matrix}2x+2y-z=p_1\\2x+5y-2z=p_2\\4x+4y-2z=p_3\end{matrix}
$$
Clearly, $p_3=4x+4y-2z=2p_1\implies p_3=2p_1$. Now, I think if I can show that $p_1$ and $p_2$ does not depend on each other I can prove that the plane $p_3=2p_1$ is the image of $T$.
I do not know how to proceed from here.
Comment: This is a system of linear equations; what happens when you use a standard technique for solving systems of linear equations, such as row reduction/Gaussian elimination?
Answer: You can write
$$T\left(\begin{array}{c} x\\ y\\ z\end{array}\right)=\left(\begin{array}{rrr} 2 & 2 & -1\\ 2 & 5 & -2\\ 4 & 4 & -2\end{array}\right)\left(\begin{array}{c} x\\ y\\ z\end{array}\right).$$
Take a basis of $\mathbb{R}^3$. For example, the canonical basis $B=\{\vec u_1(1,0,0),\vec u_2(0,1,0),\vec u_3(0,0,1)\}$, and compute:
$$T\left(\begin{array}{c} 1\\ 0\\ 0\end{array}\right)=\left(\begin{array}{c} 2\\ 2\\ 4\end{array}\right),\quad T\left(\begin{array}{c} 0\\ 1\\ 0\end{array}\right)=\left(\begin{array}{c} 2\\ 5\\ 4\end{array}\right),\quad T\left(\begin{array}{c} 0\\ 0\\ 1\end{array}\right)=\left(\begin{array}{c} -1\\ -2\\ -2\end{array}\right).$$
As every vector in $T(\mathbb{R}^3)$ can be written as a linear combination of $T(\vec u_1)=(2,2,4)$, $T(\vec u_2)=(2,5,4)$ and $T(\vec u_3)=(-1,-2,-2)$, you know that $T(\mathbb{R}^3)$ is the linear span of these vectors:
$$T(\mathbb{R}^3)=\big\langle(2,2,4),(2,5,4),(-1,-2,-2)\big\rangle.$$
However, the above set is not a basis of $T(\mathbb{R}^3)$ because the vectors are dependents (you can check that with Gauss or the determinant). You can remove any one of the vectors and then you'll have a basis of the image.
Answer: Note that
$$T\begin{pmatrix}x\\y\\z\end{pmatrix} = \begin{pmatrix}2&2&-1\\2&5&-2\\4&4&-2\end{pmatrix}\begin{pmatrix}x\\y\\z\end{pmatrix}\qquad\forall\:\begin{pmatrix}x\\y\\z\end{pmatrix}\in\mathbb R^3$$
So image of $T$ is the colspan of this matrix (which is of rank $2$). Can you proceed now?


Como configurar idiomas em Asp.net Core

Question: Estou a configurar o AddLocalization
   Então o problema é que os Resources estão numa biblioteca de classes em separado do projecto e eu não sei configurar.
   services.AddLocalization(options => options.ResourcesPath = "Resources");

Comment: Com o namespace completo não resolve? Ex.: "adota-me.shared.Linguagens"?
Answer: Para configurar os idiomas em asp.net core utilizei a seguinte configuração:
No ficheiro Startup
  public void ConfigureServices(IServiceCollection services) {
   services.AddLocalization(opts => {
    opts.ResourcesPath = "Resources";
   });

   services.AddMvc()
    .AddViewLocalization(

     LanguageViewLocationExpanderFormat.SubFolder,
     opts => {
      opts.ResourcesPath = "Resources";
     })
    .AddDataAnnotationsLocalization()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  }

Coloquei os ficheiros de tradução aqui como mostra na imagem

Para no controlador acessar a tradução utilizei
private readonly IStringLocalizer<HomeController> _localizer;

public HomeController(IStringLocalizer<HomeController> localizer)
{
    _localizer = localizer;
 }

Seguidamente para aceder a um texto especifico utilizei
 ViewData["Contact"] = _localizer.GetString("Contact").Value;

Passo para a  ViewData["Contact"] o campo com o nome Contact que se encontram nos ficheiros:

Controllers.HomeController.en.resx
Controllers.HomeController.pt-PT.resx

Estes ficheiro por sua ordem:

Views.Shared._Layout.pt-PT.resx
Views.Shared._Layout.en.resx

Afectam o ficheiro _Layout.cshtml
Dentro do ficheiro _Layout.cshtml  podemos para traduzir-mos dentro desse ficheiro sem existir controlador utilizamos razor
@inject IViewLocalizer Localizer

E para colocarmos uma variavel de tradução utilizamos por exemplo:
@Localizer["MenuHome"]

sendo que "MenuHome" é o nome da variável declarada no ficheiro Views.Shared._Layout.en.resx e Views.Shared._Layout.pt-PT.resx
Depois para ver as paginas nos diferentes idiomas basta acessar o link do seu site:
https://linkdosite/NomeControlador/NomeAction?culture=en
Para mostrar a tradução neste caso em ingles

Como configurar idiomas em Asp.net Core


Flattening data with Firebase

Question: After reading the documentation here:
https://www.firebase.com/docs/ios/guide/structuring-data.html
I am working on flattening my data. Here is the issue I am facing at the moment, in the code below:
    let firebaseDBNameUnit = ["titleString": "name1"],
    firebaseNameRef = topRef.childByAppendingPath("MyApp/Name")
    firebaseNameRef.childByAutoId().setValue(firebaseDBNameUnit) // *
    let firebaseDBContentUnit = ["contentString": "very long content 1 11 111 1111 etc... blah blah blah"],
    firebaseContentRef = topRef.childByAppendingPath("MyApp/Content")
    // The following line is where my question is:
    firebaseContentRef.childByAutoId().setValue(firebaseDBContentUnit)

I would like to change the last line in the code above, to use an ID which is the same as the one produced in the line marked *. How can I do that?
In order to create a relationship between Name and Content, I could of course create a field of my own, but it would be so much better to use the ID already provided by Firebase.
Answer: When you call childByAutoId() it returns a reference to the new location. If you capture that in a variable, you can use it:
let unitRef = firebaseNameRef.childByAutoId()
unitRef.setValue(firebaseDBNameUnit)

...

firebaseContentRef.childByAppendingPath(unitRef.key).setValue(firebaseDBContentUnit)

Comment: OK. I already accepted the answer, right after reading and testing it (Didn't you notice?). I thought that would do it all. Anyway I also upvoted it just now.

Flattening data with Firebase


Modificar elemento HTML através de funções JQuery

Question:

[IMAGE]

[EFEITO]

[TEXTO]

 ...

Instrução jQuery parcial:
$(".title-date").on('mouseover', function(){

    // função

}).on('mouseleave', function(){

    // função

});

Como, através das funções mouseover e mouseleave posso fazer o paragrafo p.title-date modificar o background de #index-mascara lembrando que ele pode modificar só o elemento corrente e não os outros?
Answer: Troque de:

[EFEITO]

Para:

[EFEITO]

E para chegar em ".index-mascara" a partir de ".title-date" use:
var mascara = jQuery(this).parent('.index-title-date').prev('.index-mascara');

Agora que você tem acesso ao elemento basta aplicar as ações que quiser.


What is the cumulative binomial distribution, on the probability of "at least one"

Question: I know that the probability mass function of the binomial distribution is
$f(k,n,p) = \Pr(k;n,p) = \Pr(X = k) = {n\choose k}p^k(1-p)^{n-k}$
This functions returns the probability of getting exactly k successes within n trials, with p being the probability of success for each trial.
The cumulative function is
$F(k;n,p) = \Pr(X \le k) = \sum_{i=0}^{\lfloor k \rfloor} {n\choose i}p^i(1-p)^{n-i}$
where $\displaystyle \scriptstyle \lfloor k\rfloor \,$  is the "floor" under k, i.e. the greatest integer less than or equal to k. But this cumulative function gives, as I understood, the probability of having the number of successes between 0 and k.
How to get a cumulative function which gives me, at least one success, that is, the probability of having the number of successes between 1 and n.
For example, someone throws an even dice. After throwing 1000 times, what's the probability of getting at least once, the number 6?
Comment: Why do you use the floor function? In my opinion it is not necessary, since k is an integer
Answer: Hint

$$P(X\geq k) = 1-P(X \lt k)$$

Solution

$$P(X\geq 1) = 1-P(X\lt 1) = 1- {1000\choose 0}\left(1\over 6\right)^0\left(1-{1\over 6}\right)^{999} = 1-({5\over 6})^{999}\approx 1$$ This "trick" is pretty obvious as it stands and it's pretty common to use it when dealing with calculating the cumulative probability of at least $m$ successes of big data sets when $m\ll n$


How to order an ndb query by a repeated field that can be empty

Question: I have an ndb model with a repeated property:
class MyModel(ndb.Model):

  foo = ndb.KeyProperty(repeated=True)

I want to do an inequality filter on foo, which means that I need to order by foo:
query = MyModel.query()
query = query.filter(MyModel.foo != my_key)
# I don't actually care about doing this, but I have to because of the inequality filter.
query = query.order(MyModel.foo)

I want the query to include entities where foo is empty.  It works if I put a dummy field into foo:
def _pre_put_hook(self):
  if not self.foo:
    self.foo.append(ndb.Key('Dummy Kind', 'Dummy ID'))

But that doesn't seem like a clean way to do this.  Is there a better way?
Answer: When the Datastore stores properties with repeated=True in it's indices, it stores one row for each value. What this means is that if you have an empty repeated property, it will not show up in your EntitiesByProperty index. This means it isn't possible to query for an empty repeated property.
There are a couple of options, but they each have their own tradeoff:
Add a dummy value.
This method you suggested has the benefit that your existing query will give you the desired results. However, you have to deal with cleaning up the dummy key when you go to add real data.
Use a ComputedProperty.
You could add a new property for the size of the foo property:
class MyModel(ndb.Model):
  foo = ndb.KeyProperty(repeated=True)
  foo_len = ndb.ComputedProperty(lambda self: len(self.foo))

However, to get entities that have a foo value that doesn't match my_key or are empty, you'll have to write two queries to get the results:
ndb.gql("SELECT * FROM MyModel WHERE foo != :1", my_key)
ndb.gql("SELECT * FROM MyModel WHERE foo_len == :1" 0)

Note that if foo were not repeated, having the following query would give you the desired results:
ndb.gql("SELECT * FROM MyModel WHERE foo != :1", my_key)

Even without the empty list case, you need to be careful when using repeated properties. In particular, only one of the repeated properties has to match your key. So a model as defined below will still match your query since my_key2 != my_key:
MyModel(foo=[my_key, my_key2])


What is the Theory behind a I iii IV iv progression and is there any songs that use it?

Question: I am currently writing a piece for guitar but this chord progression stuck out to me because I couldn't find any songs that use it. I'm looking for some songs or a song using the progression to help build my understanding.
For example as to the progression in question, The piece I'm writing is in the key of A, so it's A major, C# minor, D major, and then D minor. I am not very advanced in music theory but I wonder if the last chord is borrowing the F in the D minor from another key. Any help would be appreciated. I know there are some songs that use a  I III IV iv  progression but I'm concerned with the 3 chord.
Comment: I think a good related question is "Why would does I/III/IV/iv seem to be more common than I/iii/IV/iv?"
Answer: I iii IV iv
Some theory ideas to apply...

In German theory I and iii both express the tonic
In functional harmony I is tonic, iii, IV, and iv are all pre-dominant
iv is the borrowed sudominant chord, it's mode quality changes to minor, but functionally it still is a subdominant
the bass of the segment iii IV is a half step ascent from scale degree ^3 to ^4, depending on the voice leading it also includes the half step ascent from ^7 to ^1, the leading tone to tonic, both of which have a lot of "pull"
melodic lines tend to continue movement in the direction of a chromatic alteration

In a typical analysis, or for people who mistakenly think that harmony is derived from the circle of fifths, the progression iii IV doesn't seem to "work" because it isn't root progression by descending fifth. And depending on the voiced leading it can have parallel fifths which isn't allowed in Church style counterpoint. These are the two reasons someone might think theory says iii IV doesn't work.
Assuming all chords are in root position and in your example key of A major we could make one small alteration to iii IV by raising the G# of iii to A and then the progression becomes I6/3 IV which is root progression by descending fifth. Combine this with the German idea that I and iii both express the tonic,
and the strong "pull" you can get from the scale degree movements of iii IV, and you could say the two progressions are roughly analogous. Theoretically you can collapse I iii into simply tonic and I iii IV then is simply tonic subdominant.
Functionally your progression is tonic, pre-dominant, pre-dominant, pre-dominant. There is nothing functionally "wrong" with that. You just don't show what happens next.
Is your progression supposed to repeat? Like this? |: I iii IV iv :\.
If yes, then my two assessments show basically the same thing, the progression loops around from tonic to subdominant. That works just fine.
The part IV iv doesn't really require special attention changing the modal quality of a chord like that is very common. But notice that if it loops back to the tonic IV iv I then the chromatic alteration to the subdominant continues the downward descent. So, in A major, D Dm A contains the chromatically descending line F# F♮ E.
You could says that I iii IV iv is just an elaboration of I IV where the inserted iii provides pull up to IV and iv provides a more emphatic drop down to I. It goes up to the subdominant then it goes down to the tonic.
Despite the potential to mistake iii IV as a "music theory problem", music theory actually will explain very nicely why |: I iii IV iv :| is a satisfying progression.

I forgot, there is another way to "explain" the origin of a iii chord in this progression. It's way easier to show in notation...

If the G# is considered a passing tone over a first inversion I6 it coincidentally forms a root position iii. Technically there is no duration limit on a passing tone. So just play it very long and the iii chord become prominent. That established the sound of root movement I III IV, which is just the roots regardless of voicing details. Dispense with the "learned style", Church music voice leading proprieties, which is what pop music does, and you can play I iii IV iv with some sense of an "origin" or "rationalization" about why the progression "works." It isn't necessary to think this way. It's just a way you could square old counterpoint derived harmony with pop harmony.
Answer: Yes, the D minor is 'borrowed' from the parallel key of A minor, but there's no real reason why there should be a real reason a particular chord fits in a sequence. But we tend to find one!
D>Dm is a common enough change, usually returning to root chord of A. A>C♯m again in fairly common, as is C♯,>D in key A.
Producing a list is not within the remit of this site, but I'm sure there are plenty of songs which use this sequence. Good luck with it!
Answer: A quick dig brings up:
Girls - "Laura" (Key of C)
"5 O'Clock" - TPain and others (Key of F)
That T-Pain song was a massive hit in its day, so I wouldn't have any "concern" about your progression not working.
One of the more knowledgeable members of the forum can correct me here, the IV - iv would be a "minor plagal cadence". Especially if you end the song IV - iv - I. I think that term would be preferred over "borrowed chord from minor".
Comment: I would like to add that I meant concerned with in the context of focusing mostly on that topic


Looking for a good web penetration testing client

Question: I'm implementing mod_security on an apache server. In order to test the effectiveness of the protection, I am looking for a client that can generate a set of predefined malicious HTTP requests. I will test the requests with and without mod_security enabled and based on the logs see what percentage of malicious requests has been blocked.
Do you know any good tools to generate a set of predefined malicious HTTP requests?
Answer: There's several free/open source options out there.  A close friend of mine who's a Web applications pen tester uses none of these (with exception to Nessus, but only the Professional Feed) as their toolset is quite a bit more sophisticated and contains many unpublished zero day exploits.  However, they're very expensive and require certain certifications/qualifications to purchase.
While these tools may not be on the bleeding edge as far as pure, zero-day vulnerability scanning goes, there's still alot of older, well-known vulnerabilities that are exploited daily, so this will certainly give you a pretty good idea of what's potentially vulnerable on your system, exploit or not (i.e. finding unscrubbed parameters, any misconfigurations, etc.).

Nessus (the Professional Feed is > $1000/yr, but the free version still has quite a few vulnerabilities)
Metasploit Framework
Wapiti
Nikto2
SkipFish

Couple of things that you may not be aware:

Full scans can take days sometimes weeks to complete, depending on the size of the site, the network (see below), and the breadth/depth of scan rules  Plan accordingly.
Some of the scanners have throttling features but because of the sheer volume of requests, it's better to:
a) test your Web application on a fast network (LAN);
b) obviously this Web application shouldn't be in production and if so, I'd be running it with a test data set;
c) have plenty of resources for logging (or disable it altogether).

You may also want to periodically check the online vulnerability databases for known exploits out there; I do a periodic search for any open source Web applications I'm hosting and disable or patch as required (I'm looking at you Joomla).


Solving for Z when Z^T Z = A using R

Question: First time question asker here! Thanks in advance for any suggestions! So here's the issue. I start with a matrix Z which is samples by features. I create a covariance matrix $A = Z^T Z$. Then I perform eigenvalue decomposition on A, so $A = QDQ^T$. My goal is then to solve for Z in terms of Q and D. Here's the
algebra showing how I solve for z which results in:
$$Z = \sqrt(D)Q^T$$
*This post (https://math.stackexchange.com/questions/2858299/solve-xtx-a-for-x/2859023) confirms that this math checks out, at least I think.
The problem comes when I try to code the above as a toy example in R
<code>#1. Create toy data
z <- matrix(c(1,2,3,4), nrow = 2)
print(z)

#2. Calculate symmetric matrix A
A <- t(z) %*% z

#3. Eigenvalue decomposition
ev <- eigen(A)
Q <- ev$vectors
l <- ev$values
D <- diag(l)

#4. Re-multiply to obtain A again, as a sanity check
A_new <- Q %*% D %*% t(Q) # Should equal A

#5. Get expression for z
z_new = sqrt(D) %*% t(Q)  # Should equal z
</code>
A_new should equal A, and it does
A and A_new:

5
11

11
25

BUT I also think z_new should equal z, and it does not!
Z:

1
3

2
4

Z_new:

2.2108796
4.9978076

-0.3346813
0.1480529

Why doesn't Z == Z_new?! Is the math wrong? Is the code wrong? I've never been so stumped!
Ultimately, what I'm trying to do is subtract out the variance that is explained by the first principal component from the original dataset Z. So my plan is to set the first eigenvalue (entry 0,0 of the D matrix) to 0, and then multiply back out and resolve for Z. If there's an easier way to do that directly, or if my method is
Thank you all
Comment: You're calculating something like a square root, and they are not unique.  Imagine `Z` is a scalar:  then `A = Z^2`, so both `+Z` and `-Z` would be solutions.  With matrices there are even more solutions, e.g. you can change the signs of any the `D` elements without affecting the results.
Comment: You got a reply in a comment on SO. If you have ***a*** (*not the*) square root $Z^{1/2}$ of $Z$ then $Z^{1/2} U$ is another square root for any orthogonal matrix $U$.
Comment: ah, I see the issue, thank you.
Answer: Seems like the premise for $Z$ does not correspond to the answer on math stackexchange that you refer to: the idea is to start from $A$ and decompose it into $Z^TZ$. Here, you define $Z$ first ($Z$ corresponds to $X$ in math stackexchange), then calculate $A$ based on $Z$ and then again decompose $A$ into $Z^TZ$. There's a circulatory reference here.
Nevertheless, z and z_new both satisfy the decomposition $A=Z^TZ=Z_{new}^TZ_{new}$, which leads to the conclusion that $Z$ is not unique, i.e. for a $Z$ that satisfies the decomposition, there is a $Z^*=BZ$ that also satisfies it. I'm not sure about the theory on this (if it is generally the case or not). EDIT: comment of @Stephane Laurent on OP indicates that it holds generally for a matrix root.
In R, after your code:
<code>B = solve(z,z_new)
z_new %*% B # is equal to z
</code>
Comment: thank you, it makes sense! Follow up question: order doesn't seem to matter, but why doesn't order matter? You could do B = solve(z, z_new) or B = solve (z_new, z), and still z_new %*% B = z. Is that always true?
Comment: Well, let's see. That would mean that $ZB=Z_n$ and $Z_nB=Z$ are both true. Solving the first for $B$ yields $Z=Z_nB^{-1}$, hence it must hold that $B=B^{-1}$, i.e. $B$ is an [involutory matrix](https://en.wikipedia.org/wiki/Involutory_matrix). This is the case for the matrix in your example, but does not generally hold (basically coincidence). Try for example replacing 4 with 7 in your matrix, you'll get different results.
Comment: *solving the first for $Z$

Solving for Z when Z^T Z = A using R


R: Replacing Strings with their Most Common Variant

Question: I'm looking to standardise a set of manually inputted strings, so that:
index   fruit
1   Apple Pie
2   Apple Pie.
3   Apple. Pie
4   Apple Pie
5   Pear

should look like:
index   fruit
1   Apple Pie
2   Apple Pie
3   Apple Pie
4   Apple Pie
5   Pear

For my use case, grouping them by phonetic sound is fine, but I'm missing the piece on how to replace the least common strings with the most common ones.
library(tidyverse)
library(stringdist)

index <- seq(1,5,1)
fruit <- c("Apple Pie", "Apple Pie.", "Apple. Pie", "Apple Pie", "Pear")

df <- data.frame(index, fruit) %>%
  mutate(grouping = phonetic(fruit)) %>%
  add_count(fruit) %>%
  # Missing Code
  select(index, fruit)

Answer: We can use str_remove to remove the .
library(dplyr)
library(stringr)
data.frame(index, fruit) %>%
    mutate(fruit = str_remove(fruit, "\\."))
# index     fruit
#1     1 Apple Pie
#2     2 Apple Pie
#3     3 Apple Pie
#4     4 Apple Pie
#5     5      Pear

If we need to use phonetic and find the most frequent value
Mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

data.frame(index, fruit) %>%
   mutate(grouping = phonetic(fruit)) %>%
   group_by(grouping) %>%
   mutate(fruit = Mode(fruit))
# A tibble: 5 x 3
# Groups:   grouping [2]
#  index fruit     grouping
#  <dbl> <fct>     <chr>
#1     1 Apple Pie A141
#2     2 Apple Pie A141
#3     3 Apple Pie A141
#4     4 Apple Pie A141
#5     5 Pear      P600

Comment: Is there any flexibility benefit to creating the `Mode` function?
Comment: @rsylatian  It can be reused a s a block in other functions.
Answer: Sounds like you need group_by the grouping, then select the most frequent (Mode) item
df%>%mutate(grouping = phonetic(fruit))%>%
     group_by(grouping)%>%
     mutate(fruit = names(which.max(table(fruit))))

# A tibble: 5 x 3
# Groups:   grouping [2]
  index     fruit grouping
  <dbl>    <fctr>    <chr>
1     1 Apple Pie     A141
2     2 Apple Pie     A141
3     3 Apple Pie     A141
4     4 Apple Pie     A141
5     5      Pear     P600

Answer: Another way could be:
fruit %>%
 enframe() %>%
 mutate(grouping = phonetic(fruit)) %>%
 add_count(value, grouping) %>%
 group_by(grouping) %>%
 mutate(value = value[match(max(n), n)]) %>%
 select(-n) %>%
 ungroup()

   name value     grouping
  <int> <chr>     <chr>
1     1 Apple Pie A141
2     2 Apple Pie A141
3     3 Apple Pie A141
4     4 Apple Pie A141
5     5 Pear      P600


Saxophone vs. Clarinet differences for Traditional Jazz

Question: I play with a jazz band that plays Trad and Dixieland, and I play tenor sax.  After searching for overviews on differences between playing style (note bending, arpeggios, note sequences) for these two instruments, I don't find anything.
I would think obviously you don't want to just play what the clarinet plays on a sax, or vice versa.  Can someone give an overview of the general differences or a resource on this?
-- EDIT --
A good comment made is that sax is not a dixieland instrument, but if you go to New Orleans you will see saxes and clarinets together, playing "Dixieland" tunes.  I realize there may be a more precise definition of Dixieland than I am aware of or maybe there's a slow blend over to "Trad Jazz".
So, a better way of asking the question by example:
Here is an example of a Sax player (no clarinet here), and I'm wondering how the clarinet (technically speaking) would voice this differently to take advantage of its specific timbre etc..  To me the sax is more lyrical and melody-focused:

And here is one (albeit very slow) with both instruments:
Answer: I hate to be negative, but there isn't a sax in a Dixieland band. In ensemble choruses trumpet takes the tune, clarinet arpeggios over the top, trombone fills in the middle with plenty of trademark glissandi.  And if you want the Dixieland style, that's it.
I've just spent some time on YouTube hoping to prove myself wrong.  I couldn't find a Dixie band with a sax, other than a couple of novelty numbers.
Answer: Depends on style, particular tunes played, and the make up of the band. See recordings by Sam Morgan Band! There is some saxophone on Louis Armstrong Hot Fives and Sevens ( Jimmy Strong on "Knee Drops" for example). Recordings by Kid Thomas with Manny Paul on tenor,  saxophonist Sammy Rimington, of course the great tenor man Bud Freeman playing with Eddie Condon ("Chicago" style), folks like Tom Fischer, Sarah Spencer (in England now)Brian Ogilvie and Brian Carrick are some tenor(also alto and clarinet) players in the style. Bechet of course, and Firehouse Five with George Probert on soprano sax. And then, currently leading the New Orleans "renaissance" of this music, bands like Tuba Skinny and The Shotgun Jazz Band  prominently feature saxophones, playing VERY traditional New Orleans
 jazz. The term "dixieland" seems to have fallen out of favor, as it
conjures up visions of guys in striped shirts and straw hats, and the
young people in NOLA are decidely not of that "corny" ilk, yet are really
 playing a lot of the same repertoire faithfully, and are in fact
expanding upon it creatively. See http://playing-traditional-jazz.blogspot.com for so much more on this. The gentleman above did not search youtube enough, because there are TONS of videos from New Orleans with saxophones playing trad "dixieland" music.
 I've played in New Orleans recently a few times, and saxophone is very welcome!  tbn/clarinet/tpt is still the basic frontline, and maybe preferred with some groups,but it is very often deviated from. Frontline of tenor, cl, and trumpet is common for example, with tenor doing some of what was traditionally tbn-the music happily is much more flexible. Here's an example, "Sobbin Blues" the King Oliver tune, and it doesn't get more traditional than that:
Comment: thanks for sharing your expertise! This strikes me as the start of a great answer. To give a full answer, could you address the question on stylistic differences?
Comment: Here's a terrific site that gives a breakdown of historically to date, the various styles : http://www.prjc.org/tjen/styleguide.htm what you need to bear in mind though, is what I said earlier, is that what's currently being played in New Orleans, NYC, and Sacramento for example are "melting pots",  or melding of the styles. To me which is quite appropriate, given the origins of the music to begin with!
Comment: thanks! One of the site's goals is for answers to not rely on external sources. Links are subject to rot, and this happens a lot. If you could summarize some of the ideas from that style guide and add it into your answer (so that the answer doesn't require navigating to an external link), that would be great!


Set default domain user groups on user/computer creation

Question: Currently on our domain, when a new user is created, they are automatically added to the Domain User group which is fine.
Also, when a new computer is added to the domain, the Domain Admin group is automatically added to the local Administrators group.
Where do I configure these settings? For example, when a new computer is added to the domain, I want to automatically add the Domain User group to the local computer's Network Configuration Operators group so that domain users can edit their IP address if they need to (when travelling on hotel networks).
Thanks
Answer: You can use the Restricted Groups feature in a Group Policy to enforce membership of local groups on workstations/servers.
http://support.microsoft.com/kb/279301
http://www.frickelsoft.net/blog/?p=13
Comment: +1 - That's the best way to do it.
Comment: Thats sort of confusing, even though it says "Restricted Group" feature it still allows me to add domain groups to local groups?
Comment: @drpcken: Yes, the policy you create will *restrict* the members of the local group(s) to the collection(s) you specify.  You can add  domain groups (and/or local groups) to local groups on a workstation/server.  This ensures the defined collections are members of specified local groups *and* will *restrict* the addition of unapproved members to these local groups.
Comment: Be careful to note that using Restricted Groups will REPLACE the members of the current groups with the groups you specify. It will not ADD the members to the group in ADDITION to the current members.
Comment: @joeqwerty: Actually you can use Restricted Groups either in an  append *or* overwrite manner.  The *"Members of this group"* section will overwrite members, the *"This group is a member of"* section will append members.


After starting a thread how could we keep the run function running? I have bunch of ideas but I'm not sure which is more professional?

Question: In a Thread After calling the start() as you know it will call the run() function in the Runnable class. In the run() function I want the thread stays as long as it receive the "Bye" message from the client. If i put them in the while loop it takes heaps of memory i think and I'm not using the power of thread. By the way i don't want my thread sleep in the run function by calling Thread.sleep(6000); Is there any other way to stay there in the run function?

If the answer is join where and how and use it? Should I pop it at the beginning of the run function and it stays there until I send the "Bye" from client?
Should I say while((request=in.readLine())!=null){? It did not work because I think it will lose the connection with the client or better say client losing the connection?
Should I say while(Thread.isAlive) and then kill the threat when I receive the "Bye" by calling Thread.stop which is little bit dangerous?

Here is my simplified code:
while(true)
        {
            ClientWorker w;
            try
            {
                w = new ClientWorker(serverSocket.accept());
                    Thread t = new Thread(w);
                    t.start();
                }
......  }

    class ClientWorker implements Runnable {
        public ClientWorker(Socket incoming)
        {
            myList = my;
            this.incoming = incoming;
        }
    public synchronized  void run()
    {
         in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
.
.
..
...
}

Comment: I am really lost as to what problem you are trying to solve here.  I would start with the simplest solution possible and not try to solve problems which might never happen to start with.
Comment: @PeterLawrey May be my question is not clear. I'm trying to stay int the run function. that's set.
Comment: what is stopping you staying in the run() method? e.g. using the while loop you suggested.
Comment: @PeterLawrey I did not wanted to use while because it goes through all the codes in the run function and it's kind of loop. I'm looking for something for instance in ServerSocket we have a function called request() which is waiting for a call from the server!
Comment: So you want to have a listener for events like a when a new line can be read?  You can write one if you like.
Answer: In the simplest case just let your run method do its work and terminate when appropriate, something like this:
public void run() {
    boolean running = true;
    while(running) {
        running = doWork();
        if (Thread.interrupted()) {
            return;
        }
    }
}

Here the process stops when the doWork() method returns false. It is also good style to allow your  thread to be interrupted, especially if it needs to run for a long time, see this tutorial. For any of this to work, doWork() should return regularly. Note you cannot restart threads, once the run method has returned the thread is reclaimed by the system.
If you need more control over your threads you could create separate Worker and ThreadManager classes.
To let the ThreadManager terminate the Worker, create a volatile boolean field in your Worker which is checked periodically:
public class Worker extends Thread {

    private volatile boolean running;

    public void run() {
        running = true;
        while(running) {
            running = doWork();
            if (Thread.interrupted()) {
                return;
            }
        }
    }

    public void stopRunning() {
        running = false;
    }
}

The Worker ends when interrupted or when the work is completed. Also the ThreadManager can request the Worker to stop by invoking the stopRunning() method.
If your thread runs out of work it could also call the wait() method on the ThreadManager. This pauses the thread until it is notified that there is new work to do. The ThreadManager should call notify() or notifyAll() when new work arrives (ThreadManager is used as a monitor in this example).
With this approach you can keep the Worker simple and only concerned with doing the work. The ThreadManager determines the number of threads and makes work available to them but does not need to know details of the actual work. One step further would be to split out 'work' into a separate class too, which you could call Job. An example of this can be found in my webcrawler example. This could be useful for passing new work from the ThreadManager to the worker thread.
EDIT: clarification: If the thread doesn't do any work and just needs to wait for some condition, don't use an iteration to wait, but use either wait/notify (see the webcrawler example I gave) or a simple callback when the condition arises.
Comment: @ManudeHanoi In the example code I gave the Thread returns from the run method if there is no more work, so no incessant calls to Thread.isInterrupted() will happen. I already clarified my answer regarding busy waiting after your first 'this is bad' comment. If there is no work to be done the thread should call `wait()` which yields the underlying system thread to the pool but can still resume its task when `notify()` (or `notifyAll()`) is called. As I mentioned, this is demonstrated in the web crawler example I linked.
Comment: Does anyone know of a way to do this without busy waiting? Maybe a condition variable? I'm not sure of the java syntax for that.
Comment: See the webcrawler example above, it uses the java wait/notify mechanism to avoid busy waiting. Another approach is the Observer pattern which uses an asynchronous callback to notify waiters of an event.
Comment: this is bad, running in a loop is CPU consuming
Comment: @ManudeHanoi 'Busy waiting' (https://en.wikipedia.org/wiki/Busy_waiting) is bad, meaning a thread is iterating just to check for a certain condition. My example is not a busy wait situation; the thread is doing work in the doWork() method. The periodic returning of doWork() allows the thread to check for `Thread.isInterrupted()` and`running == false`, allowing the thread to be managed by an external process. This is considered good practice in thread programming.
Comment: @AdriaanKoster If the thread had work to do, keeping it alive would be trivial. The issue is how to keep the thread alive and low on CPU when it's got nothing to do in order to avoid the cpu expensive creation of new threads each time there is work to do.
In the case the thread has no work to do the incessant calls to "Thread.isInterrupted()" will consume CPU
Comment: with the below solution of semaphore at least we can hope that the waiting is done in a sensible manner
Answer: I know this is late, but this is a much better implementation and avoids heavy CPU usage by busy waiting - Allows context switching when the thread is waiting for a signal.
Setting the semaphore to a value of 0 ensures that when the thread attempts to acquire permission to continue, it does not get it and waits.  When you release the semaphore, the count is increased by 1, allowing the thread to continue and the count is decreased back to 0.
In main:
Semaphore sem = new Semaphore(0);
Worker t = new Worker(sem);
t.start();'

// The thread is now running but waiting, signal the semaphore to start work
sem.release();

The Thread
public class Worker(Semaphore sem) extends Thread {

    public void run() {
        sem.acquire();
        doWork();
    }
}

Comment: Why not just use wait/notify for this?
Answer: just return from the run() when you get "bye"
Comment: But what if I want to stay in the run? The while loop is fine or?
Comment: yeah while loop is fine. run the while loop and whenever you get "bye" call return.
Comment: Do you mean while loop inside the run method?
Comment: yeah. while have to be inside the run method


read.table that delete 0 of each rows in r

Question: I have a file in which every row is a string of numbers. Example of a row: 0234
Example of this file:
00020
04921
04622
...

When i use read.table it delete all the first 0 of each row (00020 becomes 20, 04921 -> 4921,...). I use:
example <- read.table(fileName, sep="\t",check.names=FALSE)
After this, for obtain a vector i use as.vector(unlist(example)).
I try different options of read.table but the problem remains
Comment: You can specify `colClasses`
Answer: The read.table by default checks the column values and change the column type accordingly.  If we want a custom type, specify it with colClasses
example <- read.table(fileName, sep="\t",check.names=FALSE,
           colClasses = "character", stringsAsFactors = FALSE)

When we are not specifying the colClasses, the function use type.convert to automatically assign the column types based on the value
read.table # function
...
...
 data[[i]] <- if (is.na(colClasses[i]))
        type.convert(data[[i]], as.is = as.is[i], dec = dec,
            numerals = numerals, na.strings = character(0L))
 ...
 ...

Answer: If I understand the issue correctly, you read in your data file with read.table but since you want a vector, not a data frame, you then unlist the df. And you want to keep the leading zeros.
There is a simpler way of doing the same, use scan.
example <- scan(file = fileName, what = character(), sep = "\t")


Autorização via token com AngularJS

Question: Vi que para setar o campo 'Authorization' do cabeçalho com Angular usa-se:
<code>$http.defaults.headers.common.Authorization = "Bearer " + token
</code>
ou
<code>$http.defaults.headers.common.Authorization = "Basic " + token
</code>
Qual a diferença entre o 'Bearer' e 'Basic'? E por que quando vou fazer a requisição via Postman não preciso concatenar o token com algum dos dois?
Answer: Autenticação Basic e Digest são dedicados a autenticação usando um "login" e uma "senha".
Autenticação Bearer é dedicado a utilização de token para se autenticar.
A dúvida do Postman depende da forma que você está autenticando no caso do Basic não precisaria passar nenhum token mas no "Body" da requisição seria necessário informar o "login" e "senha".
Comment: No postman, seto apenas na aba de header o 'Authorization' : 'token'
Comment: Acho que não estamos nós entendendo, utilizo a aba "Headers" do Postman não a aba "Authorization".
E na aba "Headers" tenho que colocar a "key" Authorization e no "value" tenho que por "Bearer token" ( Bearer "espaço" token)
Comment: Exatamente isso que vc disse: Na aba "Headers", eu coloco na key 'Authorization' com o valor 'token' [sem bearer] e me retorna normal.
Comment: Você tem acesso ao servidor? O Bearer é definido pela especificação OAuth2 pode ser alguma configuração na aplicação que faz você conseguir acesso mesmo sem por o Bearer na frente do token.
Comment: Até tenho, mas acho que agora vc matou a questão. Porque provavelmente a aplicação não tenha sido desenvolvida usando o padrão OAuth.

Autorização via token com AngularJS


Is every correlation matrix positive definite?

Question: I'm talking here about matrices of Pearson correlations.
I've often heard it said that all correlation matrices must be positive semidefinite. My understanding is that positive definite matrices must have eigenvalues $> 0$, while positive semidefinite matrices must have eigenvalues $\ge 0$. This makes me think that my question can be rephrased as "Is it possible for correlation matrices to have an eigenvalue $= 0$?"
Is it possible for a correlation matrix (generated from empirical data, with no missing data) to have an eigenvalue $= 0$, or an eigenvalue $< 0$? What if it was a population correlation matrix instead?
I read at the top answer to this question about covariance matrices that

Consider three variables, $X$, $Y$ and $Z = X+Y$. Their covariance
  matrix, $M$, is not positive definite, since there's a vector $z$ ($=
(1, 1, -1)'$) for which $z'Mz$ is not positive.

However, if instead of a covariance matrix I do those calculations on a correlation matrix then $z'Mz$ comes out as positive. Thus I think that maybe the situation is different for correlation and covariance matrices.
My reason for asking is that I got asked over on stackoverflow, in relation to a question I asked there.
Comment: Near-duplicates: [Is every correlation matrix positive semi-definite?](http://stats.stackexchange.com/q/125412/22228) which has less focus on the definite versus semi-definite angle, and [Is every covariance matrix positive definite?](http://stats.stackexchange.com/questions/56832/is-every-covariance-matrix-positive-definite) which is relevant because a covariance is essentially a rescaled correlation.
Comment: If, for example, two attributes are one thing, only having different names, the matrix is singular. If two attributes add to a constant, it is again singular, [et cetera](http://stats.stackexchange.com/q/70899/3277).
Comment: If a covariance matrix is singular correlation matrix is singular as well.
Answer: Correlation matrices need not be positive definite.
Consider a scalar random variable X having non-zero variance.  Then the correlation matrix of X with itself is the matrix of all ones, which is positive semi-definite, but not positive definite.
As for sample correlation, consider sample data for the above, having first observation 1 and 1, and second observation 2 and 2.  This results in sample correlation being the matrix of all ones, so not positive definite.
A sample correlation matrix, if computed in exact arithmetic (i.e., with no roundoff error) can not have negative eigenvalues.
Comment: May be worth mentioning [the possible effects of missing values on the sample correlation matrix](http://stats.stackexchange.com/a/56833/22228). Numerical fuzz isn't the only reason to get a negative eigenvalue in a sample correlation/covariance matrix.
Comment: Yes, I didn't make it explicit, but I was assuming, per the question statement, "with no missing data".  Once you get into the wild, wacky world of missing data and adjustments therefor, anything goes.
Comment: Yes, sorry, you're quite right the question said "no missing data" - just thought it worth mentioning somewhere since future searchers might be interested even if the OP's appetite is sated!
Answer: The answers by @yoki and @MarkLStone (+1 to both) both point out that a population correlation matrix can have zero eigenvalues if variables are linearly related (such as e.g. $X_1 = X_2$ in the example of @MarkLStone and $X_1 = 2X_2$ in the example of @yoki).
In addition to that, a sample correlation matrix will necessarily have zero eigenvalues if $n<p$, i.e. if the sample size is smaller than the number of variables. In this case covariance and correlation matrices will both be at most of rank $n-1$, so there will be at least $p-n+1$ zero eigenvalues. See Why is a sample covariance matrix singular when sample size is less than number of variables? and Why is the rank of covariance matrix at most $n-1$?
Comment: True 'dat.  I suppose I could have and should have provided this info as well, but my goal was to produce a counterexample to refute the OP's hypothesis, thereby showing its invalidity  Nevertheless, you should  adjust your second sentence to be "In this case covariance and correlation matrices will be at most rank n−1, so there will be at least (p−n+1) zero eigenvalues."
Answer: Consider $X$ to be an r.v. with mean 0 and variance of 1. Let $Y=2X$, and calculate the covariance matrix of $(X,Y)$. Since $2X=Y$, $E[Y^2]=4E[X^2]=\sigma_Y^2$, and $E[XY]=2E[X^2]$. Due to the zero mean configuration, the second moments are equal to the suitable covariances, for instance: $\mbox{Cov}(X,Y)=E[XY]-EXEY=E[XY]$.
So the covariance matrix will be:
$$ \Lambda = \left(\array{1 & 2 \\ 2 &  4 }\right),$$ having a zero eigenvalue.
The correlation matrix will be:
$$ \Lambda = \left(\array{1 & 1 \\ 1 & 1 }\right),$$ having a zero eigenvalue as well. Due to the linear correspondence between $X$ and $Y$ it is easy to see why we get this correlation matrix - the diagonal will always be 1, and the off-diagonal is 1 because of the linear relationship.
Comment: Just for math-challenged readers like myself, let me point out that the `2` in $\Lambda$ is the $cov(X,Y)= \mathbb{E}(XY)-\mathbb{E}(X)\mathbb{E}(Y)= 2\mathbb{E}[X^2]=2\left(\sigma_X^2+[E(X)]^2\right)$ this last equality resulting from: $E(X^2)=\text{Var}(X)+[E(X)]^2$.
Comment: +1 for your post. I wanted to make it easy to follow for everyone by including the $diag \Lambda^{-1/2}\,\Lambda\, diag \Lambda^{1/2}$ formula, but the comments format won't allow it. Do you think there is any valid point in including it in your post?
Comment: @AntoniParellada , I'm not exactly sure what you mean - the covariance here is a direct calculation. But I will edit and make that clearer. Thanks.


jQuery scope problem

Question: I am trying to create a sort of generic xml parser, like this:
Part 1:
An object with filter is created:
var product = {

  holder : {
    id: '',
    title: '',
    text : '',
    price: ''
  },

  filter : {
    id: '',
    test: function( elementHolder ) {
      if( elementHolder.id == product.filter.id ) {
        return true;
      }
      return false;
    }
  }
}

Part 2:
The xml parser:
/*
 * Generic XML parser
 * Parses the url into elementHolder objects
 */
var xmlParser = {

  parseXml: function( url, node, element, functie ) {

    var i = 0;       // result counter

    var result = []; // the result array
    /*
     * Open the xml file
     */
    jQuery.get( url, function( data ){

      /*
       * Loop through the results, if we have a filter, apply it.
       */
      jQuery( data ).find( node ).each( function(){
        /*
         * Copy the element holder
         */
        var elementHolder = element.holder;
        var elementData = jQuery(this);

        /*
         * Fill the copied holder with the xml data
         */
        elementData.children().each(function() {
          elementHolder[ this.nodeName ] = jQuery(this).text();
        });

        /*
         * if the filter applies, add the holder to the result
         */
        if( element.filter.test( elementHolder ) ) {
          result[i] = elementHolder; $i++;
        }

        // console.log( result );

      });

      /*
       * If there is a callback ( prevents the result from parsing before it is ready )
       */
      try {
        if (typeof functie == "undefined") {
          throw 'There is no callback function specified.';
        }
      } catch( e ) { alert( e ); return; }

      functie( result );

    });

  }

}

Part 3:
Calling on document ready:
product.filter.id = 11;

  /*
   * parsen
   */
  var productXml = 'test.xml';
  xmlParser.parseXml( productXml, "product", product, function( data ) {
    console.log( 'result:' );
    console.log( data );
  });

Part 4:
The test.xml:
<data>
  <products>
    <product>
      <id>1</id>
      <title>test 1</title>
      <text>text 1</text>
      <price>1.00</price>
    </product>
    <product>
      <id>2</id>
      <title>test 2</title>
      <text>text 2</text>
      <price>2.00</price>
    </product>
    <product>
      <id>3</id>
      <title>test 3</title>
      <text>text 3</text>
      <price>3.00</price>
    </product>
  </products>
</data>

It all works fine except for one thing;
The result get overwritten each loop by the newly created holder, does anyone have any ideas how to fix this? ( i think it is does have something to do with the scope ).
Thanks !
Answer: I found the solution
The part:
var elementHolder = element.holder;

Doesnt create a copy of the object, just another reference;
I found the solution to that on this page:
http://my.opera.com/GreyWyvern/blog/show.dml/1725165
Object.prototype.clone = function() {
  var newObj = (this instanceof Array) ? [] : {};
  for (i in this) {
    if (i == 'clone') continue;
    if (this[i] && typeof this[i] == "object") {
      newObj[i] = this[i].clone();
    } else newObj[i] = this[i]
  } return newObj;
};

var elementHolder = element.holder.clone();

Comment: This function bugts firefox, its even better to use this function:

function clone( obj ){
    if(obj == null || typeof(obj) != 'object')
        return obj;
    var temp = new obj.constructor();
    for(var key in obj)
        temp[key] = clone(obj[key]);
    return temp;
}
Answer: Stab in the dark - but I think you need a closure in your inner loop.
change this
elementData.children().each(function() {
  elementHolder[ this.nodeName ] = jQuery(this).text();
});

to this
elementData.children().each(function( e, n, t ) {
  return function()
  {
    e[n] = t;
  }
}( elementHolder, this.nodeName, jQuery(this).text() ));

Comment: Well, the part that says:

elementData.children().each(function() {
  elementHolder[ this.nodeName ] = jQuery(this).text();
});

does work, the replacement code provides empty objects, should it really solve the problem that the object that does get passed into the result div is overwritten ?

jQuery scope problem


Guardar nome do ficheiro com espaços em branco html/php

Question: Tenho o seguinte botão que vai para um ficheiro:
Download XLS

No ficheiro download_file.php tenho o seguinte:
<?php
header("Content-Type: application/octet-stream");

$file = $_GET["file"];
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
}
fclose($fp);

?>

Funciona tudo correctamente, o ficheiro é descarregado. Mas o objectivo é o ficheiro ficar guardado com o seguinte nome "BD Fugas Gespost.xls" e está a ficar guardado como "ficheiro_xls%2FBD+Fugas+Gespost.xls". Já experimentei como está em cima usar o %20 para substituir o espaço, mas não resulta
Comment: acho que o seu problema esta na linha que você fala: `file=ficheiro_xls/BD%20Fugas%20Gespost.xls` e depois lê: `$file = $_GET["file"];`. O problema não está no PHP, mas sim na instrução que você passa à ele. Veja se é necessário constar esse `ficheiro_xml/`.
Comment: @FredDutra, não é necessário constar o ficheiro_xml/
Answer: Primeiro, decida qual é o Content-Type desejado, você tem 3 headers com Content-Type, e deve ter um só.
Como o nome do seu arquivo já está codificado, você pode tirar o urlencode do $file:
header("Content-Disposition: attachment; filename=" . $file );

entretanto, como tem nome de pasta no $file, talvez seja o caso de pegar só o nome do arquivo:
header("Content-Disposition: attachment; filename=" . basename( $file ) );

Alternativamente:
Eventualmente você poderia fazer diferente, sem o encode no link:
Download XLS

mantendo o urlencode no header:
header("Content-Disposition: attachment; filename=" . urlencode($file));

e talvez alterando a abertura do $file, mas aí depende de como está o nome verdadeiro do arquivo no filesystem:
$fp = fopen( urldecode( $file ), 'r' );

Comment: desse modo o ficheiro não é gravado com extensão
Comment: @pc_oc uma coisa que pode estar atrapalhando é a barra
Comment: Editei, experimente a solução com basename().
Comment: @Bacco, acho que o problema é que ele passa `file=ficheiro_xls/BD%20Fugas%20Gespost.xls` e depois lê: `$file = $_GET["file"];`. O problema não está no PHP, mas sim na instrução que ele passa ao PHP.
Comment: @FredDutra É capaz. Mais ou menos o que eu sugeri na 2a opção, fazer sem encoding prévio.
Comment: @Bacco, com o basename ele tenta gravar apenas o ficheiro com o nome "BD", ou seja, chega ao espaço e não via buscar o resto do nome do ficheiro
Comment: @pc_oc você não misturou as 2 soluções né? Cuidado que na resposta eu sugeri ou tirar o encode, ou mudar o URL. Não faça as duas coisas simultaneamente. Se for o caso, edito a resposta para separar melhor as idéias. Que OS vc está usando?
Comment: @Bacco estou a usar windows8.1. Usando a alternativa, ele está a substituir o " " por "+".
Comment: + e %20 são a mesma coisa em URLencode, é normal isso. Se chegou até aí tudo bem. Deu problema pra abrir o arquivo? Acrescentei o urldecode no $file. Se puder, teste com `basename( urldecode( $file ) )` no header também.
Comment: tem tambem o rawurlencode e o rawurldecode que são parecidos com urlencode e urldecode, porém tratam o "+" diferentemente.
Answer: Utilize o str_replace do PHP.
str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
Primeiro você fará o seguinte:
str_replace("ficheiro_xls%2F", "", $variavel);
Dessa  forma você tira esses caracteres iniciais do nome.
Depois repita a operação substituindo o + por , assim: str_replace("+", " ", $variavel);
Documentação: Str_replace.
Dica: não acho uma boa usar reg. exp. porque você terá que fazer dois ou três passos para alcançar o mesmo resultado que você terá com o srt_replace.
Comment: já tentei assim e o ficheiro é guardado com o mesmo nome. penso que o problema pode estar em alguma configuração do download_file.php
Answer: Cara, tenta isso:
        <?php
        header("Content-Type: application/octet-stream");

        #Tente usar este aqui.
        #Em um index terá o nome do arquivo completo, como veio do GET, mas sem barra ao contrario
        #E no outro, um outro array onde conterá, a(s) pasta(s) do arquivo, e no ultimo index o nome do arquivo
        $arrFile = array(
          str_replace("\\","/", $_GET["file"]),
          explode("/",str_replace("\\","/", $_GET["file"]))
          );

        header("Content-Disposition: attachment; filename='" . urldecode(end($arrFile[1]))."'";
 #Aqui em cima, você deveria usar o URLDECODE, pois a url já veio com os caracteres especiais, não precisaria "encodar" denovo
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header("Content-Description: File Transfer");
        header("Content-Length: " . filesize($arrFile[0])); #Aqui você usa o caminho completo do arquivo
        flush(); // this doesn't really matter.
        $fp = fopen($arrFile[0], "r"); #Aqui você usa o caminho completo do arquivo
        while (!feof($fp))
        {
            echo fread($fp, 65536);
            flush(); // this is essential for large downloads
        }
        fclose($fp);

        ?>

Comment: Obrigado pela ajuda! Com este código o download não começa, ou seja, sou reencaminhado para a página download_file.php e o download não começa


Are these wrong signs because of a book error or wrong procedure?

Question: I was solving these DEs
$\frac{dx}{dt} = -y+t$
$\frac{dy}{dt} = x-t$
Doing it by elimination they become
$x''+x = t+1$
$y''+y = t-1$
...for $x$ and $y$ respectively. If I solve those I get
$x = c_1\cos(t) + c_2\sin(t) + t + 1$
$y = c_1\cos(t) + c_2\sin(t) + t - 1$
Now, it makes sense to me that the general solution (Cos and Sin part) is the same for both cases, but the solution says
$x = c_1\cos(t) + c_2\sin(t) + t + 1$
$y = c_1\sin(t) - c_2\cos(t) + t - 1$
And this happens with the solutions of a few other problems too, so I'm not quite convinced it's just a print error. Am I doing something wrong?
Comment: @Moo So to verify I should check $Cos(t)c2-Sin(t)c1+1 = -Cos(t)c1-Sin(t)c2-t+1-t$ ? What do I do if they're not? Find a value of c1 and c2 that makes them equal and correct the ones I got?
Comment: @Moo So I can just make the signs of the terms with constants be positive or negative when I want in order to make LHS = RHS? That looks pretty cheaty. I guess that would mean that there are several different ways to write an answer.
Answer: Let's check your answers:
$$x = c_1\cos t + c_2\sin t + t + 1\\y = c_1\cos t + c_2\sin t + t - 1$$
So $$x' = -c_1\sin t + c_2 \cos t + 1$$
while $$-y + t = -c_1\cos t - c_2\sin t + 1$$
The only case where these two are the same for all $t$ is when $c_1 = c_2 = 0$.
Now, let's try the given solution:
$$x = c_1\cos t + c_2\sin t + t + 1\\y = c_1\sin t - c_2\cos t + t - 1$$
$x'$ is the same as before, but $$-y + t = -c_1\sin t + c_2\cos t + 1$$ which is equal to $x'$.
And $$y' = c_1\cos t + c_2\sin t - 1$$ which is also $x - t$.
So their solution works and yours does not.
"Makes sense to me" is not the best means of evaluating your work. You may have overlooked something, like the impact of that minus sign in $$\frac d{dt}\cos t = -\sin t$$
and that differentiating cosine and sine swaps which functions are associated with $c_1$ and $c_2$.
Answer: What you are doing wrong is taking the constants $c_1$ and $c_2$ you used to write the "general" solution for $x(t)$ and re-using them to write the general solution for $y(t)$.
Even though you separated $x$ and $y$ they still have to satisfy your original "mixed" equations. By re-using $c_1$ and $c_2$ you are assuming that if, say through the addition of some initial conditions, we find that the co-efficient on the $sin$ term in $x$ is 3, then the the co-efficient on the $sin$ term of $y$ must also necessarily be 3. Nothing justifies this.
Here's what you should do:

Separate them, just like you did
Write the general solution for $x(t)$, using $c_1$ and $c_2$
Then write the general solution for $y(t)$, using new co-efficients $c_3$ and $c_4$
Substitute these solutions back into the original equations to see what restrictions this places on the $c$'s. If this yields something complicated all you can do is state this as a requirement for your $x$ and $y$ to be solutions. Or it might be simple and let you re-write some of the $c$'s in terms of others, and you can eliminate those $c$'s completely.

I haven't worked out the details, but I'll bet that in your case the last step will give you $c_1 = c_3$ and $c_2 = -c_4$, so eliminating $c_3$ and $c_4$ will give you the given solution.


Powershell - external command's parameter not accepted

Question: This seems like a simple problem but I am unable to fix it
Running dfsutil command in shell returns result

C:\Windows\system32>dfsutil link "\server.domain.com\DFSRootname\Sharename"
Link Name="Sharename" State="OK" Timeout="1800"
        Target="\server1\sharename" State="ONLINE"  [Site: site1]
        Target="\server2\sharename" State="OFFLINE"  [Site: site2]
Done processing this command.

Trying to do the same in powershell

PS>
$path = "\\server.domain.com\DFSRootname\Sharename"
$dfsutil = "dfsutil"
$option = "link"

PS C:\Windows\system32> dfsutil link $path

DFS Utility Version 5.2 (built on 5.2.3790.3959)
Copyright (c) Microsoft Corporation.  All rights reserved.

Unrecognized option "ink"

Same with using Invoke-Expression

PS C:\Windows\system32> Invoke-Expression "$dfsutil $option $path"

DFS Utility Version 5.2 (built on 5.2.3790.3959)
Copyright (c) Microsoft Corporation. All rights reserved.

Unrecognized option "ink"
Answer: The following syntax works for me on PS v2/v3.  I'm preceding the command with a <code>&</code> the Call Operator:
<code>$path = "\\ad.example.org\root\share"
$dfsutil = "dfsutil"
$option = "link"

& $dfsutil $option $path

Link Name="share" State="OK" Timeout="1800"
Target="\\fs1.example.org\share" State="ONLINE"  [Site: default-site]

Done processing this command.
</code>
Comment: Thank you Scott. This is what I expected to happen. Seems like problem only happens on my Windows 7 PS3 install. Command works fine on Windows 2008 R2 host wint PS2 it works fine
Answer: Seems like installation problem with my Windows 7 PS3 install. Command works fine on Windows 2008 R2 host with PS2


Does a manifold with zero simplicial volume necessarily admit a map $f$ with $|\deg f| > 1$?

Question: Let $\|M\|$ denote the simplicial volume of an oriented closed connected manifold.
If $f : M \to N$ is a continuous map between two oriented closed connected manifolds of the same dimension, then $|\deg f|\|N\| \leq \|M\|$. In particular, if $M$ admits a self-map $f$ with $|\deg f| > 1$, then $\|M\| = 0$. Is the converse true? I suspect that the answer is no, but I haven't been able to find a counterexample.

Is there an oriented closed connected manifold $M$ with $\|M\| = 0$ but which does not admit a self-map $f$ with $|\deg f| > 1$?
Answer: For instance, if $M$ is a compact Nilmanifold, it has zero simplicial volume. On the other hand, there are nontrivial finitely-generated torsion-free co-hopfian nilpotent groups $\Gamma$ (see for instance here). Taking $M$ a compact Nilmanifold with the fundamental group $\Gamma$ we obtain an example of a manifold with zero simplicial volume an no self-maps of degree $>1$. (Any such map would induce an epimorphism $\Gamma\to \Gamma'$, where $\Gamma'<\Gamma$ is a finite index subgroup. That would contradict the co-hopfian property of $\Gamma$.
Comment: Why do nilmanifolds have zero simplicial volume? Also, why does the existence of an epimorphism $\Gamma \to \Gamma'$ contradiction the co-hopfian property?
Comment: @MichaelAlbanese: Compact manifolds with amenable fundamental groups have zero simplicial volume (this is in Gromov's 1982 paper). Each quotient of a f.g. nilpotent group $N$ by an infinite subgroup has strictly smaller rational cohomological dimension. Hence, it cannot be isomorphic to a finite index subgroup of $N$.
Comment: How can I see that the quotient of a finitely generated nilpotent group by an infinite subgroup has strictly smaller rational cohomological dimension? Also, is it clear why the kernel of $\Gamma \to \Gamma'$ would have to be infinite?
Comment: @MichaelAlbanese: For the second question: This group is torsion-free, hence, contains no nontrivial finite subgroups. For the first question, the key is that the cohomological dimension of a f.g. torsion-free nilpotent group $G$ is the dimension of its associated Lie algebra $L(G)$ and the latter is functorial: A homomorphism $\phi: G_1\to G_2$ induces a homomorphism $L(\phi): L(G_1)\to L(G_2)$. If $\phi$ is not injective, $L(\phi)$ is not injective either.


Boas práticas com testes PHPUnit

Question: Estou começando em testes, e queria saber se estou seguindo corretamente, uso laravel, e tive alguns dilemas para desenvolver um teste de um service que tenho. Ele faz algumas operações num app via API, só que como não tenho como fazer um "mock" dessa api eu tive que fazer o teste "sequencial" ( em produção )para poder usar os valores que usava antes:
<?php

namespace Tests\Feature;

use App\Exceptions\AppConnectionException;
use App\Exceptions\AppErrorException;
use App\Exceptions\AppNullException;
use App\Services\App\AppService;
use App\Services\App\Responses\Card;
use Tests\TestCase;

class AppServiceTest extends TestCase
{
  /** @var AppService */
  private $appService;
  /** @var int */
  private $pipeId,$destinationPhase;

  protected function setUp(): void {
    parent::setUp();
    $this->appService = new AppService();
    $this->pipeId = 533822;
    $this->destinationPhase = 3656118;

  }

  /**
   * @test
   * @throws AppConnectionException
   * @throws AppErrorException
   * @throws AppNullException
   */
  public function test(){
//  CREATE
    $title = 'teste '. now()->toTimeString();
    $fields = ['nome_completo'=>'igor'];

    $card = $this->appService->createCard($this->pipeId,$title,$fields);
    $this->assertInstanceOf(Card::class,$card);
    $this->assertEquals($title,$card->title);

//  SHOW CARD
    $card = $this->appService->showCard($card->id);
    $this->assertInstanceOf(Card::class,$card);
    $this->assertIsArray($card->rawData); // TODO: melhorar acerto verificando os fields criados acima

//    UPDATE FIELD
    $fielid = array_keys($fields)[0];
    $newvalue = $fielid . " updated";
    $mutation = $this->appService->updateField($card->id,$fielid,$newvalue);
    $this->assertTrue($mutation);

//    MOVE CARD
    $card = $this->appService->moveCardToPhase($card->id,$this->destinationPhase);
    $this->assertInstanceOf(Card::class,$card);
    $this->assertEquals($card->currentPhase['id'],$this->destinationPhase);

  }

}

Eu imagino que cada teste deve ser individual, certo ? esta sequencia é muito errado ?
Answer: Para melhorar estes testes é mais indicado separá-los em vários métodos, assim tudo fica mais organizado e é possível ter uma noção melhor de tudo que está sendo testado. Segue a classe refeita:
<?php

namespace Tests\Feature;

use App\Exceptions\AppConnectionException;
use App\Exceptions\AppErrorException;
use App\Exceptions\AppNullException;
use App\Services\App\AppService;
use App\Services\App\Responses\Card;
use Tests\TestCase;

class AppServiceTest extends TestCase
{

  private $appService;
  private $pipeId;
  private $destinationPhase;
  private $card;
  private $fields;

  protected function setUp(): void
  {

    parent::setUp();
    $this->appService       = new AppService();
    $this->pipeId           = 533822;
    $this->destinationPhase = 3656118;
    $this->fields           = ['nome_completo'=>'igor'];

  }

  public function testCardCreation(): void
  {

     $title      = 'teste '. now()->toTimeString();
     $this->card = $this->appService->createCard($this->pipeId, $title, $this->fields);

     $this->assertInstanceOf(Card::class, $this->card);
     $this->assertEquals($title, $this->card->title);

  }

  public function testShowCard(): void
  {

     $card = $this->appService->showCard($this->card->id);

     $this->assertInstanceOf(Card::class, $card);
     $this->assertIsArray($card->rawData); // TODO: melhorar acerto verificando os fields criados acima

  }

  public function testCardUpdate(): void
  {

     $fielid   = array_keys($this->fields)[0];
     $newvalue = $fielid . " updated";
     $mutation = $this->appService->updateField($this->card->id, $fielid, $newvalue);

     $this->assertTrue($mutation);

  }

  public function testCardMove(): void
  {

     $card = $this->appService->moveCardToPhase($this->card->id, $this->destinationPhase);

     $this->assertInstanceOf(Card::class, $card);
     $this->assertEquals($card->currentPhase['id'], $this->destinationPhase);

  }

}

Answer: Começa dividindo o teste em testes menores, pra ficar mais fácil de visualizar:
public function testCreate(){
    // code
  }

  public function testShowCard(){
    // code
  }

  public function testUpdateField(){
    // code
  }
  function testMoveCard(){
    // code
  }

A partir daí começa a definir atributos pra sua classe de testes, e, para definí-los, crie uma função chamada setUp (ela será chamada antes de cada teste).
Em caso de dúvidas, sempre se lembre: cada função deve ser responsável por testar UMA funcionalidade do projeto. Aí fica mais fácil de verificar em qual funcionalidade o erro ocorreu. E leia a documentação do PHPUnit e do Laravel para aprimorar os testes.
Bons estudos ;)

Boas práticas com testes PHPUnit