How do I get trac 12.2 to work on RHEL5's httpd with CollabNet SVN 1.6.17 (which has its own httpd)?

Question: I installed CollabNetSubversion-client-1.6.17-1.x86_64.rpm, which installs httpd v2.2.19
# /opt/CollabNet_Edge/csvn/bin/httpd -v
Server version: Apache/2.2.19 (Unix)

I installed Trac-0.12.2.tar.gz.
On the Apache httpd that comes with RHEL5, which is running v2.2.3
# apachectl -v
Server version: Apache/2.2.3

I installed mod_wsgi, since that is what the trac website recommended.
python.conf settings for the 2.2.3 httpd:
Alias /trac/chrome/common /var/trac/htdocs/common
Alias /trac/chrome/site /var/trac/htdocs/site
<Directory "/var/trac/htdocs">
   Order allow,deny
   Allow from all
</Directory>
LoadModule wsgi_module modules/mod_wsgi.so
WSGIScriptAlias /trac /var/trac/cgi-bin/trac.wsgi
<Directory /var/trac/cgi-bin>
  SetEnv PYTHON_EGG_CACHE /tmp
  WSGIApplicationGroup %{GLOBAL}
  Order deny,allow
  Allow from all
</Directory>
<LocationMatch "/trac/[^/]+/login">
  AuthType Digest
  AuthName "trac"
  AuthDigestDomain /trac
  AuthUserFile /etc/httpd/trac.htpasswd
  Require valid-user
</LocationMatch>

I setup a trac project and configured it to point to an existing SVN repository.
The first error reported in trac.log was:
ImportError: No module named svn

http://trac.edgewall.org/wiki/TracSubversion#Troubleshooting has the answer, so I added symbolic links to the bindings that are in the CollabNet area:
cd /usr/lib64/python2.4/site-packages
ln -s /opt/CollabNet_Edge/csvn/lib/svn-python/libsvn .
ln -s /opt/CollabNet_Edge/csvn/lib/svn-python/svn .

Next error in trac.log (thanks for reading this far -- this is the real problem):
Trac[svn_fs] INFO: Failed to load Subversion bindings
Traceback (most recent call last):
  File "build/bdist.linux-x86_64/egg/trac/versioncontrol/svn_fs.py", line 267, in    __init__
  File "build/bdist.linux-x86_64/egg/trac/versioncontrol/svn_fs.py", line 68, in _import_svn
  File "/opt/CollabNet_Edge/csvn/lib/svn-python/svn/fs.py", line 19, in ?
     from libsvn.fs import *
  File "/opt/CollabNet_Edge/csvn/lib/svn-python/libsvn/fs.py", line 7, in ?
     import _fs
ImportError: /usr/lib64/python2.4/site-packages/libsvn/../../../lib/libsvn_subr-1.so.0:
  undefined symbol: apr_memcache_add_server

I found this page that speaks of the same problem: http://subversion.open.collab.net/ds/viewMessage.do?dsForumId=3&dsMessageId=313639
The advice given: "you probably need to use our Apache server or update yours to 2.2.11" (i.e., 2.2.19 to match the one in the CollabNet package).  Well, the CollabNet-bundled httpd server doesn't have mod_wsgi installed, and I'm not sure how I could build such and add it to their server -- so I don't like that option.  I'd rather not update our main httpd from 2.2.3 to 2.2.19 -- but is this really my only other option?
BTW, I tried downloading SVN 1.6.17 and building and installing swig-py -- to build the bindings, hoping to use them with the 2.2.3 httpd and trac.  However, I'm not sure this is safe/correct... SVN is tied to the 2.2.19 httpd, somehow, right?  Anyway, I couldn't get that to work either.  Any advice appreciated.
UPDATE: Following Graham's suggestion, I compiled a 2.2.19 httpd server (to replace the RH5 2.2.3 httpd) and now everything is working.  My first attempt with the 2.2.19 httpd failed.  I had to configure httpd with option --with-included-apr, then everything worked.
Comment: Can you please phrase this as a question?
Comment: Sure, good point.  The real question is how can I get trac to run on the RHEL5 httpd when CollabNet SVN is running on its own separate httpd, with a different version of httpd.
Answer: The binaries you are using were built against a newer Apache version and specifically a newer version of the APR libraries than your Apache 2.2.3 installation you are using. There is no way around the problem except for upgrading to Apache version which uses a new enough APR library.
Comment: Thanks Graham.  I started down this road near the end of the work day earlier today, but it is good to hear that I'm finally going down the right road now.


How to redirect via TemplateView.as_view to .html file

Question: I am trying to create an url which redirects to a simple static .html file using:
url(r'^impressum/', TemplateView.as_view(template_name='impressum.html'), name='impressum'),

As far as I understand the template_name argument takes the location of the .html file. I tried several variations of the above code, trying to redirect to the file but always get a 404 error when loading localhost:8000/impressum/
This is how my Folder directory looks. I tried "lwc/templates/impressum.html" and "templates/impressum.html". What am I doing wrong / how does this path direction work exactly
EDIT: below my TEMPLATE_DIRS settings:
TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
    )

Comment: Have you tried with `r'^impressum/$'` ?
Comment: The dollar shouldn't make a difference. However, it's a good idea to add it, otherwise the url pattern will work for `/impressum/other-url/` as well as `/impressum/`.
Answer: I managed to find my error:
this is how my urls.py looked:
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'joins.views.home', name='home'),
    url(r'^(?P<ref_id>.*)$', 'joins.views.share', name='share'),
    url(r'^impressum/$', TemplateView.as_view(template_name='impressum.html')),
)

I put the impressum url on the top and then it worked out. I remembered from a tutorial that there is a certain logic how django checks the urls line by line and if you have an url with an extension you have to put before the url without any in order to make it work
Answer: This might help now.
Template.as_view()

This function looks the default django library folder.
So, add your template directory to your django setting.
I guess you have setting in setting_old.py ( by default setting.py).
Because the function looks TEMPLATES directory first,
add your template directory, after the manage.py folder, to the setting like below.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            'templates',   # <- here
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Comment: As a complemment: "Thus, when (for example) the APP_DIRS option of a DjangoTemplates backend is set to True in TEMPLATES, a template location could be: /path/to/project/books/templates/books/publisher_list.html" https://docs.djangoproject.com/en/3.2/topics/class-based-views/generic-display/


Cox regression with controlled variables

Question: in my retrospective study I have continuous and categorical variables. These latter are divided in two or more sub-groups. I want to analyze their impact on overall survival. In particular, I'm interested in a  dichotomous variable (which I'm gonna call myVariable) and I suspect that its impact may be affected by age and sex. First, I categorized the continuous variables in 2 or more sub-categories and I performed a univariate analysis by the log-rank test with kaplan-meyer survival plots; myVariable was not significant.
On multivariate analysis, I used the Cox regression controlling for age and sex: I put age and sex in the first block and the other variables in the second, using the enter method. I included myVariable in the second block, to verify if it became significant after controlling for age and sex. Although I had previously categorized age and other continuous variables, I now used the original uncategorized data, when possible.
1 Is this procedure correct?
2 On Cox regression myVariable became significant. Strangely, age was not significant on log-rank test but became significant on Cox regression. How comes?
3 I'm using SPSS. In the "variable view" I set variables as string or numeric as appropriate. However, each variable is set as "Nominal". Is that important? In other words, can it affect the results?
Thank you for your advices.
Andrea
Answer: I don't understand why you're categorizing your continuous variables. There are two ways a variable can be handled in a Cox model.
With covariate adjustment, you just estimate a hazard ratio comparing units of your variable. If continuous age is included in the model, then the hazard ratio is interpreted as a ratio of hazards comparing individuals differing by one year in age, at risk for disease, holding all other variables constant. This can handle continuous and categorical variables alike, it just depends on how they're coded.
$\lambda(t| \mbox{MyVar}, \mbox{Age}) = \lambda(t| \mbox{MyVar}=0, \mbox{Age}=0)\exp\left(\beta_1\mbox{MyVar} + \beta_2 \mbox{Age} \right)$
With stratification, you need fixed values. This allows a unique baseline hazard to be estimated among the various values of the variable. This is preferred when the proportional hazards assumption is not met for this variable in adjustment. You need considerably more observations to use stratification and it's rarely such an issue that it needs to be considered.
$\lambda(t| \mbox{MyVar}, \mbox{Age}) = \lambda_\mbox{Age}(t| \mbox{MyVar}=0)\exp\left(\beta_1\mbox{MyVar} \right)$
So, to answer your questions:

No I don't think splitting age into arbitrary categories is the right way to go about things.
Parameter estimates don't "become significant", if you compare models that do and don't adjust for certain covariates, the interpretation of the model coefficients change between models, they're not the same coefficients examined under different lights. Avoid this kind of language altogether. If age is a confounding variable, it's not significance of this variable (or the main effect) that warrants our use of it in a multivariable regression model. Instead we adjust for age regardless because it gives us the correct, unbiased, adjusted measure of the relationship between myVariable and failure time.
Yes, it's hugely important. Age is continuous. You have to code it as such in order to adjust it as such.
Comment: In a cohort of matched pairs, and we develop a Cox PH model stratified by each matched pair (exposed and unexpos.). The model outputs a unadjusted Risk Ratio, with 95% CI. When we add covariates to the model, we obtain an adjusted Risk Ratio. In my example, the uRR and aRR are relatively unchanged, but the aRR has much larger CIs. Am I correct to report then on the uRR?


How can I pattern match tokens similar to a regular expression?

Question: I'm looking for a way (algorithm / open source project / ???) to pattern match tokens by constructing a pattern similar to a regular expression or use similar principals.
I'll try to describe my question through examples. Let's say I have the following SQL INSERT statement:
INSERT INTO [dbo].[Table] (Column1) VALUES (@Column1);

And let's also say I was able to parse that SQL into tokens (I can), they would look like this:
+-------------------+-------+
| INSERT            | token |
| INTO              | token |
| QUOTEDIDENTIFIER  | token |
| DOT               | token |
| QUOTEDIDENTIFIER  | token |
| LEFTPARENTHESIS   | token |
| IDENTIFIER        | token |
| RIGHTPARENTHESIS  | token |
| VALUES            | token |
| LEFTPARENTHESIS   | token |
| VARIABLE          | token |
| RIGHTPARENTHESIS  | token |
| SEMICOLON         | token |
+-------------------+-------+

So assuming I have a stream of tokens and I want to match any INSERT statement (and this was the only valid syntax for one) I would write a theoretical regex-esque pattern like this:
INSERT\s+INTO\s+
QUOTEDIDENTIFIER\s*DOT\s*QUOTEDIDENTIFIER\s*LEFTPAR\s*IDENTIFIER\s*RIGHTPAR
\s*VALUES\s*LEFTPAR\s*VARIABLE\s*RIGHTPAR\s*;

But I know that an INSERT statement can come in various forms like:
INSERT INTO Table (  Column1) VALUES (@Column1  )
INSERT INTO Table (Column1, Column2) VALUES (@Column1, @Column2  );
INSERT INTO [dbo].[Table] (Column1, Column2) VALUES (@Column1, @Column2  );

So I could easily make a theoretical regex-esque pattern that would match all token variations of these statements but how can I actually do that?
Why don't I actually use regular expressions? Because I already have the parsed tokens in a stream, seems like there should be a solution to this. I swear I've seen something similar before.
Comment: This seems like an awfully inefficient way to do this.  Why didn't you parse into some sort of P code, or even and AST with genuine objects?
Comment: The name for what you want is a parser.  Tokenization is only the first step of parsing.
Answer: Don't use Regular Expressions for this.
What you're attempting to do is lexical analysis and the tool more appropriate for this job is a lexical analyzer or lexer.
If Python is your thing, I've used PLY and had success with it. They're are a samples scripts available too that you can reference. If not, most modern languages have libraries or modules available for lexical analysis.


Capoing a dulcimer changes the mode - what does this mean for me practically?

Question: I have a "woodrow instrument", which is a diatonically fretted dulcimer you play like a guitar.
When getting it from the maker he said "Here's something cool, if you capo the instrument you get a different mode." I know there are 7 modes, and that generally they are associated with certain feelings in the music, but I don't know how to use that information. Is it as simple as, learn a song, capo, play the song as written and it will sound different? Or is it that different songs will be available to me?
This is not my main instrument but I would like to use the opportunity to learn as much as I can about the music theory of this.
Answer: 'You play like a guitar'. Well, yes and no!
The guitar part involves the plucking, which is similar to how a guitar may be plucked.
However, the fretting is rather different from a guitar. (Hence this re-answering!).
A dulcimer is not fretted like a guitar, where each fret is a semitone from the next, when pressed down. Looking at a dulcimer's fretboard, there are several frets missing!
That's because each fret is in its particular place to make a major diatonic scale as it goes towards the bridge.
It's a bit like leaving out frets 1, 3, 6, 8 and 10. Putting in only the frets which provide the seven notes on a major scale, the eighth being half way along the fingerboard, just where the 12 fret of a guitar would be.
So, saying that putting a capo on the first fret on a dulcimer is similar to playing the notes from there up as a Dorian scale instead of the Ionian (major) from open. Put that capo on fret 2, and play up a fret at a time - you have Phrygian mode. It makes sense not to try changing to another string at any point. Let's face it - with effectively three strings, tunes a P5 apart, it wouldn't work too well anyway.
Therefore, it could be construed that each fret position is making a different mode available. Open = Ionian, 1st - Dorian, 2nd = Phrygian, 4th = Lydian, 5th = Mixolydian etc. And wherever the capo iss, is root.
Comment: @Ben - given that you know how Dorian (for example) works, and you wanted to play a tune in that particular mode, you'd capo fret 1, and that note will be your root. Tune the string to D, you would have E Dorian mode as you go up and down the 'board. Merely transposing a melody into a mode *can* work, but that's not really the essence of modes. Certain songs are in certain modes, so if you wanted to play a song that was in, say, Lydian, then you'd put capo on fret 3. Then all the remaining frets would 'belong' to that mode.
Comment: Would E Dorian and F Dorian count as the same mode or different modes, then?
Comment: "play like a guitar" was a reference to the fact that unlike a mountain/lap dulcimer, the "woodrow" specifically is played against the body oriented like a guitar. What you are saying echoes what the maker said. Still leaves my question of, what can I do with this information? "Is it as simple as, learn a song, capo, play the song as written and it will sound different? Or is it that different songs will be available to me? "
Comment: @Dekkadeci - assume a string is tuned open to note D. Put capo on fret 1, and you have the remaining frets constituting E Dorian. Capo fret 2, and it's F# Phrygian, if that helps. You couldn't play F Dorian with that tuning!
Answer: What are the strings tuned to?
If it is DAd, then using no capo, ie open strings, you'll be playing in D Mixolydian (not D Major). If you put a capo on Fret 1, you'll be playing in E minor; if using a Capo at Fret 3 you'll be playing in G major. If capo is at fret 4, you'll be playing in A Dorian.
The letter gives you the root note (and therefore the name) of the key. The word after the letter tells you the mode or shape of that key's scale ~ which is all about how the tones and semi-tones are sequenced. (Each mode has its own characteristic sequence, which gives a mode it's distinct feel).
You can feel this if you run through a Major (= Ionian mode) scale, then run through the minor (= Aeolian mode) scale, with both having the same root note, eg D).
Typically, traditional tunes are written in a 7-note modal scale.  Most Dulcimer tunes are written in Mixolydian, or Aeolian (that is another name for a minor scale), with some in Dorian, and some in Ionian (that last one is another term for a Major Scale).
Because the Dulcimer is not chromatic, (i.e. it does not have all 12 possible notes as, say, a piano does), it is limited to 1 Major scale, 1 minor scale, 1 Dorian scale, and 1 Mixolydian scale, determined by which fret you apply a Capo to, and the notes the open strings are tuned to. So as well as knowing the root note of a tune (it's usually the last note played), you need to establish its mode to know if it can be played on the Dulcimer in its particular tuning.
Some sources which may help you get more understanding of this are:
Stephen Smith on Modes and MD tuned to DAd
Bonnie Carol on Keys, Modes & tunings for MD
Musicfolk on modes and tunings for MD
A search on the web will provide insights into modes (not specifically for, but still relevant to Dulcimer), including some great demos on Youtube.
Happy Exploring,


Recursively execute a locally defined python script on remote machines

Question: I'm interested in writing a script so that the only copy of the script resides on my local machine, but the script executes on remote machines, possibly with the remote machines executing the script on other remote machines (i.e., 2 or more levels of recursion in the distributed invocation tree).
One way to achieve this would be to copy the script to the remote machines in one step and then perform remote execution via ssh in a second step, passing appropriate parameters to the script, which will pass different parameters for each remote invocation, each of which would be performed via something like:
subprocess.call(['ssh', <user@address>, 'python scriptname.py <params>'])

Is it possible to achieve this in one step without first copying the python script. Obviously, I'd still have to transmit the code in the script as part of the remote call in some way, but it would be preferable not to have to run two separate commands and perhaps even a third to clean up the file from the remote machine after the script is run.
Answer: No, you won't be able accomplish this in one step (except for python -c 'print "hello world"' maybe). But fabric might make your life a little easier.
Comment: Thanks, I have a proof of concept using `-c` and passing the script source code as an argument for use in the recursive calls.
Answer: The Python binary does have a -c option that lets you pass in valid Python code as an argument. For example:
$ python -c "print 'hello'; print 'world'"

prints
hello
world

Your script may have dependencies or be too complex for this, but it does handle more trivial commands.
Answer: I know that sshuttle does this "bootstrapping" as part of its normal execution. It assumes the existence of a Python interpreter on the remote end of an ssh connection, and uploads code to run.
I haven't investigated the code to find out exactly what it does, but it should be reasonably straightforward to find.
Answer: Check out Fabric.  It's the Python tool to "write and execute Python functions, or tasks, to automate interactions with remote servers." #


Which classifiers work well with unbalanced data?

Question: I have a binary classification problem which is very unbalanced - it can have 98% of data from one class.  Which classifiers work well with this sort of data?
I have an unlimited supply of training data, since I produce it using a pseudo random number generator.  However, I found that to get a neural network to produce decent results, I had to generate balanced (50:50) data.  This is the equivalent of over-sampling.  The problem with this approach is that the training data is then not representative of real life.
Answer: Some options:

Do not use accuracy alone as a metric. That way, we would get 98% accuracy with everything classified as the majority class, which would not mean anything. Precision & Recall might be a better one.
You could try using a Cost sensitive classifier through which you can state the cost of misclassification of the different classes.
Use an SVM but penalize one of the classes which can be done using LibSVM
boost the number of minority class training examples by artificially creating new samples from the existing samples.
resample the set, to have a proportional number of samples in both the classes (probably not an option in your case)
Answer: Just to add to @tdc's reply: the problem with skewed data is that models tend to over-fit and result in biased models. For some of them there are modifications to the original formulation that help correcting that bias. For example, there are alternative formulations of naive Bayes, kNN which deal with this problem.
As he points out: the problem is that usually one attempts to maximize the accuracy. And that makes the classifier "focus" on the most populous classes, since that yields better accuracy.


wit.ai Bot Engine Stories connected to hubot

Question: I am trying to get the new wit.ai Bot Engine connected to hubot with Javascript.
Unfortunately I am not a JS Developer so I'm struggling.
Here's the code I have:
'use strict';
const Wit = require('../../../node-wit').Wit;

const firstEntityValue = (entities, entity) => {
  const val = entities && entities[entity] &&
    Array.isArray(entities[entity]) &&
    entities[entity].length > 0 &&
    entities[entity][0].value
  ;
  if (!val) {
    return null;
  }
  return typeof val === 'object' ? val.value : val;
};

const actions = {
  say: (sessionId, msg, cb) => {
    console.log(msg);
    cb();
  },
  merge: (context, entities, cb) => {
    const loc = firstEntityValue(entities, "location");
    if (loc) context.loc = loc;
    cb(context);
  },
  error: (sessionId, msg) => {
    console.log('Oops, I don\'t know what to do.');
  },
    'fetch-weather': (context, cb) => {
    // Here should go the api call, e.g.:
    // context.forecast = apiCall(context.loc)
    context.forecast = 'sunny';
    cb(context);
  },
};

const client = new Wit('MY_TOKEN_HERE', actions);
client.interactive();

module.exports = function(robot) {

   robot.respond(/hey\s+(.+$)/i, function(msg){

        var match = msg.match[1];
        msg.send("I've heared: " + match);

        console.log(match)
        process.stdout.write(match);
    });
}

The script listens to "hey botname" and outputs what was written after this. My Problem is I have no clue how to get this input sent to the wit client. Using this script in bash without the hubot stuff works fine towards wit as this is based on the quick start example from wit.ai.
The other issue I'm facing is that I would like to have hubot listen in a private channel with every user and have it respond to every message without prefix. Just as the node example does in the console.
Help is highly apprechiated!
Answer: Ok, after fiddling a while I made this work.
Here's what my hubot script looks like now:
'use strict';
const Wit = require('../../../node-wit').Wit;

var room;

const firstEntityValue = (entities, entity) => {
  const val = entities && entities[entity] &&
    Array.isArray(entities[entity]) &&
    entities[entity].length > 0 &&
    entities[entity][0].value
  ;
  if (!val) {
    return null;
  }
  return typeof val === 'object' ? val.value : val;
};

const actions = {
  say: (sessionId, msg, cb) => {
    console.log(msg);
    room.send(msg)
    cb();
  },
  merge: (context, entities, cb) => {
    const loc = firstEntityValue(entities, "location");
    if (loc) context.loc = loc;
    cb(context);
  },
  error: (sessionId, msg) => {
    console.log('Oops, I don\'t know what to do.');
    room.send('Oops, I don\'t know what to do.')
  },
};

const client = new Wit('MY_TOKEN_HERE', actions);
//client.interactive();

module.exports = function(robot) {

  robot.listen(function(msg) {

        var userID = msg.user.id;
        var roomID = msg.user.room;

        // is this a direct chat(private room)?
        if(roomID.indexOf(userID) >= 0){
          if(typeof msg.text == "string"){
              client.pxMessage(msg.text);
          }
        }

        return true;
      },
      function(response){

          // save room for replys
          room = response;
      });
}

additionally I made an awful hack to wit.js to get this work. I added the following function as I was not able to use the available methods to get this working. Basically callbacks and session were holding me back:
this.pxMessage = (message) => {
      const sessionId = uuid.v1();
      const context = {};
      const steps = 5;

      this.runActions(
        sessionId,
        message,
        context,
        (error, context) => {
          if (error) {
            l.error(error);
          }
          rl.prompt();
        },
        steps
      );
  }

If someone would take this further and implement it properly I would love to see the result. This hack works and we now have a really smart bot in our rocket.chat who understands natural language and learns every day.
Answer: You can directly use this module, it seems to be working well: https://www.npmjs.com/package/hubot-wit
I have just now finished integration. You just need to provide the environment variable WIT_TOKEN and it works beautifully!


Postfix: Keep mails in Backup-Queue even if next hops says 500

Question: We have lost some mails because the next smtp hop (internal server) had a broken configuration  and replied with 500 "won't relay".
Is there a way to configure postfix to keep the mails in some backup queue and don't drop this mail?
Answer: You can set soft_bounce = yes in main.cf (reference).


Implementing redirection on node viewing without affecting solr search indexing

Question: My logic demands that for a specific content type provided a node (Ex) node/123 has one if its CCK field named web link with a URL value like http://someothersite.com in it, viewing the given node mysite/node/123 should redirect to the respective URL http://someothersite.com given in that field.
I've implemented this with a custom module's hook_nodeapi view case to check the value of the field and perform the redirect. However doing so has inadvertently affected my apachesolr search indexing which invokes the hook on view condition (through node_build_content) to generate the node for being indexed.
This has forced me to currently skip such specific nodes from not being indexed, however I wish to know if there's a better way of programatically implementing the aforementioned redirect without hook_nodeapi to keep the sanity of search indexing intact.
Answer: How about doing this in hook_init() instead, eg, something along the lines of...
function YOURMODULE_hook_init() {

   $mgo=menu_get_object();

   if (!empty($mgo->type) && $mgo->type=='THE_TYPE_YOU_ARE_LOOKING_FOR') {

      if (!arg(2)) { // eg so we ignore node/###/edit etc
        if (!empty($mgo->field_THE_FIELD_YOU_ARE_REDIRECTING_TO[0]['value'])) {
          drupal_goto($mgo->field_THE_FIELD_YOU_ARE_REDIRECTING_TO[0]['value']);
        }
      }
   }

}

Caveat:  I've never used apachesolr, so you may need to wrap this with further logic to make sure you are running when a user actually goes to the page, eg, arg(0)=='node' and is_numeric(arg(1)) kinda stuff.
ADDITION:
You might be able to just check args inside nodeapi() as well, eg:
if (arg(0)=='node' && is_numeric(arg(1)) && !arg(2)) {
  // do your magic
}

Comment: Thanks for the elaborate and well thought response, I was shying to use `hook_init` and was curious to know if there was some hook that would be better suited or tailor made for the occasion that I might have missed googling or finding from the API..


Como "limpar" variáveis estáticas?

Question: Em C++ as variáveis estáticas são muito importantes. Vamos supor que eu queira fazer um fatorial que usa recursão.
unsigned long long int RecursionFatorial(unsigned int fator)
{
    static long long int FatReturn;
    if(fator == 0)
    {
        unsigned long long int FatReturn_ = FatReturn;
        FatReturn = 0;
        return FatReturn_;
    }
    else
    {
        if(FatReturn == 0) FatReturn = 1;
        FatReturn *= fator;
        RecursionFatorial(fator - 1);
    }
}

O código roda e dá o resultado esperado, mas o código fica maior: é preciso criar novas variáveis (não estáticas) para poder resetar as variáveis que são estáticas, checar se a nova é zero para poder alterar o valor (primeira chamada) e causa ocupação de memória desnecessária. Como devemos fazer a boa utilização de variáveis estáticas e depois limpá-las?
Comment: Uma curiosidade interessante é que a razão que FORTRAN 77 não permitia recursão é precisamente porque as variáveis locais e o valor de retorno das funções era armazenadas em locais estáticos ao invés de usarem a pilha.
Comment: Na verdade, este uso que você fez de variáveis estáticas não é recomendado. Se duas threads chamarem a sua função em paralelo o resultado não vai ser definido.
Answer: Uma variável estática (declarada dentro de um método) irá manter seu valor entre chamadas sucessivas. Se você não deseja manter o valor entre chamadas sucessivas, por que não simplesmente usar variáveis locais (não estáticas)? O fatorial recursivo poderia ser implementado de forma mais simples (inclusive sem variáveis locais ou estáticas):
unsigned long long int RecursionFatorial(unsigned int fator)
{
    if(fator == 0)
    {
        return 1;
    }
    else
    {
        return fator * RecursionFatorial(fator - 1);
    }
}

Answer: Se você precisa disso, tem algo errado no seu design.
Variáveis estáticas em funções devem ser usadas para armazenar um estado global, não um estado momentâneo da operação.
Em primeiro lugar, você não precisa de um estado para uma função recursiva. Você pode usar o valor de retorno diretamente:
unsigned long long fatorial(unsigned fator) {
    return fator == 0 ? 1 : fator * fatorial(fator-1);
}

Outra forma comum é usar um parâmetro para guardar o estado:
unsigned long long fatorial(unsigned fator, unsigned long long resultado = 1) {
    return fator == 0 ? resultado : fatorial(fator - 1, resultado * fator);
}

Mas se você insiste em ter um estado, você pode usar um objeto. Afinal objetos foram feitos para terem estados:
struct Fatorial {
    unsigned long long resultado ;
    Fatorial() : resultado (1) {}
    unsigned long long calc(unsigned fator) {
        if (fator > 0) {
            resultado *= fator;
            calc(fator-1);
        }
        return resultado;
    }
}

Fatorial().calc(4) // 24

Note que está uma bagunça e é de longe o ideal para uma recursão.
Agora respondendo a pergunta de fato:
unsigned long long fatorial(unsigned fator, bool reset=true)
{
    static unsigned long long resultado;
    if (reset) resultado = 1;
    if (fator > 0) {
        resultado *= fator;
        fatorial(fator-1, false);
    }
    return resultado;
}

Comment: No comecinho: "Vamos supor que eu queira fazer um fatorial[...]"
Comment: Não entendi.  eu supus que você estava a fazer algo similar a um fatorial. O que disse em minha resposta se aplica.
Comment: Sim, ela está correta. Você disse sobre o design, mas é só um exemplo ;)
Comment: Sim. Mas se você está a usar variáveis estáticas para o estado de funções recursivas, *sejam ou não fatorial*, tem algo errado com o seu design. Considere uma alternativa.

Como "limpar" variáveis estáticas?


Regression: centered vs. uncentered predictors

Question: I'm trying to understand how/why centering predictors in a 2 predictor regression model would change the coefficients
Lets say I have 2 centered predictors and an interaction term, predicting a continuous Y variable that is not centered, and I have gone through the process of calculating all the regression coefficients (b0-3).
Now, the question is, if I were to uncenter the 2 predictors, how would the coefficients change (if at all)?
From my understanding, the distribution of data points would not change, nor would the regression plane. However, by centering/uncentering we change the (X1, X2, Y) value of each datapoint. I don't believe this would change the b3 interaction coefficient because the relationship between the simple slopes would not be affected. The coefficients for the intercept and the 2 predictors, however, should change because we've essentially changed the scale for each of the predictors.
Can anyone shed some light on why/how this happens? and how do you determine the magnitude/direction of these changes?
Comment: When there is no interaction term  centering just change the intercept  not the other coefficients. When there is an **interaction** term then the coefficient will change after you centering. I think this can be proved mathematically, intuitively,  you can think when you centering (add or decrease some value)  the effect of one variable on the other variable is not linear then the coefficient before the centering and after centering will change.
Comment: See also [When conducting multiple regression, when should you center your predictor variables & when should you standardize them?](http://stats.stackexchange.com/q/29781/17230).
Answer: The literature related to models with curvilinear, second-order or higher terms is among the more contradictory and controversial areas in statistics. Modern development of these topics goes back to the 60s with Jacob Cohen's work on the relationships between correlation, ANOVA and multiple regression. More recently, Aiken and West's (A&W) Multiple Regression goes into much greater methodological detail about these issues but important contributions have also been made by political scientists such as Harvard's Gary King who argues for substantive interpretation of the output, as opposed to the simple reporting of p-values and significance.
Main effects only models are most typically defined as the constant effect of one variable across values for the other variables in the model. With higher-order term (interaction) models, this is not the case. The coefficients of higher-order models represent the effects of the predictors at the mean of the other predictors and requires centering to make the *mean" be the same – at zero – for all predictors.  A&W take pains to note that, e.g., in the social sciences, many predictors are rated on an interval scale (e.g., 1 to 7) where zero has no meaning. If the data isn't centered in these instances, then the evaluation of a higher-order model will occur at a value that isn't even on the scale.
A&W compare models with raw, uncentered inputs vs appropriately mean-centered predictors and find that, while the coefficients for main effects only models will not change, the main effects coefficients in higher order models do change, and potentially change dramatically.


$\lim_{x \to 1} \frac{x^k - 1}{x - 1}$ using $\delta, \epsilon$

Question: Hi all,
 I think I have a pretty good start to the problem I listed above, but wanted some help with manipulating the end. I believe (from a hint) that I can somehow use the Difference Power Formula to simplify it more.
Proof:
 We look at the point $x_0 = 0$, and look at a potential limit $L=k$.
Suppose $\epsilon > 0$ and $\delta = $____
We must show that for all $|x-x_0| < \delta$, it holds that $|f(x) - L| < \epsilon$.
Suppose $|x-x_0| \to |x-1| < \delta$.
Then $|f(x) - L| \to |\frac{x^k-1}{x-1}-k| \to |\frac{x^k-1-k(x-1)}{x-1}|$.
Does anyone have any suggestions on how I can continue from here? Thanks in advance!
Answer: Let $y=x-1$.  Then, we can write
$$\frac{x^k-1}{x-1}=\frac{(1+y)^k-1}{y} \tag1$$
Applying the binomial theorem to the right-hand side of $(1)$ reveals that
$$\begin{align}
\left|\frac{x^k-1}{x-1}-k\right|&=\left|\sum_{\ell=2}^k \binom{k}{\ell}y^{\ell-1}\right|\\\\
&\le |y|\sum_{\ell=2}^k\binom{k}{\ell}|y|^{\ell-2}\tag 2
\end{align}$$
Now, we restrict $|y|$ such that $|y|\le 1$.  Then, we see that
$$\sum_{\ell=2}^k\binom{k}{\ell}|y|^{\ell-2}\le 2^k$$
Therefore, given $\epsilon>0$ we have
$$\left|\frac{x^k-1}{x-1}-k\right|<\epsilon$$
whenever $|x-1|<\delta=\min\left(1,\epsilon/2^k\right)$.
Answer: Hint: We can use $\frac{x^k -1}{x-1} = x^{k-1} + \ldots + x + 1$. Then together with the triangle inequality we find:
\begin{align}
  \Big|\frac{x^k -1}{x-1} - k\Big|
  &= |x^{k-1} + \ldots + x + 1 - k| \\
  &  \le \sum_{j=1}^{k-1} |x^j - 1| \\
  &= |x-1|\sum_{j=1}^{k-1}|1+x+\ldots+x^{j-1}| \\
  &<\delta\cdot \sum_{j=1}^{k-1}|1+x+\ldots+x^{j-1}|
\end{align}
And the last sum is obviously bounded if we request without loss of generality that e.g. $\delta\le 1\implies x\in[0,2]$


Finding a substitution for the integral of $\frac{dx}{2\sqrt{x+3}+x}$

Question: The question wants me to make a substitiution to express $\frac{dx}{2\sqrt{x+3}+x}$ as a rational function and then evaluate. I tried a few different $u's$ (such as $\sqrt{x+3}$ and $2\sqrt{x+3}+x$, but I can never seem to get all of the $x's$ gone. I'm left with $\frac{1}{2u+x}$, which I don't know if it is allowed.
What should I put as the substitution?
Comment: Well, if you let $u=\sqrt{x+3}$, you can note for a start that $x=u^2-3$. You'll also need to replace the $\,dx$ by a $\frac{dx}{du} \,du$.
Answer: Sometimes with substitution problems there's an extra "rearrangement" step you have to do.  Here's a simpler example:
$$
\int x^3 \sqrt{x^2 + 1} \: dx
$$
If you make the substitution $u = x^2 + 1$ (picking a radical or something under a radical is often a good first guess), you'll turn the integral into
$$
\frac{1}{2} \int x^2 \sqrt{u} \: du.
$$
In order to get rid of the last $x^2$, you must go back and rearrange your original substitution rule:
$$
u = x^2 + 1 \implies u - 1 = x^2
$$
and plug that in:
$$
\frac{1}{2} \int (u - 1) \sqrt{u} \: du.
$$
Now the integral can be solved using the power rule.
Returning to your original problem, you have
$$
\int \frac{1}{2\sqrt{x+3} + x} \: dx
$$
and if you make the substitution $u = \sqrt{x+3}$ ($\implies$ $du = \frac{1}{2\sqrt{x+3}} dx$), you have the rearrangements
$$
u^2 - 3 = x \quad \text{and} \quad dx = 2 \sqrt{x+3} \: du = 2u\:du.
$$


When CVMetalTextureRef should be released?

Question: I am creating id<MTLTexture> object from CVPixelBufferRef the following way:
id<MTLTexture> CreateMTLTexrure(CVMetalTextureCacheRef texture_cache,
                                CVPixelBufferRef pixel_buffer,
                                MTLPixelFormat metal_pixel_format, size_t plane,
                                int height, int width) {
  CVMetalTextureRef texture_ref;

  CVReturn err = CVMetalTextureCacheCreateTextureFromImage(
      kCFAllocatorDefault, texture_cache, pixel_buffer, NULL,
      metal_pixel_format, width, height, plane, &texture_ref);

  if (err != kCVReturnSuccess) {
    // throw error
    return nil;
  }

  id<MTLTexture> texture = CVMetalTextureGetTexture(texture_ref);

  //
  // Q: is it safe to do CVBufferRelease(texture_ref) here?
  //
  return texture;
}

When CVMetalTextureRef object should be released?
Is it safe to release it after MTLTexture is obtained?
Answer: Yes it is safe.
According to this sample code from Apple Documentation Archive, it is released right after it was assigned, like so:
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
    CVReturn error;

    CVImageBufferRef sourceImageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    size_t width = CVPixelBufferGetWidth(sourceImageBuffer);
    size_t height = CVPixelBufferGetHeight(sourceImageBuffer);

    CVMetalTextureRef textureRef;
    error = CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, _videoTextureCache, sourceImageBuffer, NULL, MTLPixelFormatBGRA8Unorm, width, height, 0, &textureRef);

    if (error)
    {
        NSLog(@">> ERROR: Couldnt create texture from image");
        assert(0);
    }

    _videoTexture[_constantDataBufferIndex] = CVMetalTextureGetTexture(textureRef);
    if (!_videoTexture[_constantDataBufferIndex]) {
        NSLog(@">> ERROR: Couldn't get texture from texture ref");
        assert(0);
    }

    CVBufferRelease(textureRef);
}

You could also look at the WebRTC source code from Google Chromium repository, they also release CVMetalTextureRef the same way.
- (BOOL)setupTexturesForFrame:(nonnull RTCVideoFrame *)frame {
  RTC_DCHECK([frame.buffer isKindOfClass:[RTCCVPixelBuffer class]]);
  if (![super setupTexturesForFrame:frame]) {
    return NO;
  }
  CVPixelBufferRef pixelBuffer = ((RTCCVPixelBuffer *)frame.buffer).pixelBuffer;
  id<MTLTexture> lumaTexture = nil;
  id<MTLTexture> chromaTexture = nil;
  CVMetalTextureRef outTexture = nullptr;
  // Luma (y) texture.
  int lumaWidth = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0);
  int lumaHeight = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0);
  int indexPlane = 0;
  CVReturn result = CVMetalTextureCacheCreateTextureFromImage(
      kCFAllocatorDefault, _textureCache, pixelBuffer, nil, MTLPixelFormatR8Unorm, lumaWidth,
      lumaHeight, indexPlane, &outTexture);
  if (result == kCVReturnSuccess) {
    lumaTexture = CVMetalTextureGetTexture(outTexture);
  }
  // Same as CFRelease except it can be passed NULL without crashing.
  CVBufferRelease(outTexture);
  outTexture = nullptr;
  // Chroma (CrCb) texture.
  indexPlane = 1;
  result = CVMetalTextureCacheCreateTextureFromImage(
      kCFAllocatorDefault, _textureCache, pixelBuffer, nil, MTLPixelFormatRG8Unorm, lumaWidth / 2,
      lumaHeight / 2, indexPlane, &outTexture);
  if (result == kCVReturnSuccess) {
    chromaTexture = CVMetalTextureGetTexture(outTexture);
  }
  CVBufferRelease(outTexture);
  if (lumaTexture != nil && chromaTexture != nil) {
    _yTexture = lumaTexture;
    _CrCbTexture = chromaTexture;
    return YES;
  }
  return NO;
}

Comment: It's weird they did not bother to add just a single line about that to `CVMetalTextureGetTexture` documentation.


matlab variable shared to another function

Question: Inside of one parent function, I have a callback function related to a button on a gui.
When the button is pressed, one of the things it does is define a variable (let's say X) that needs to be persistent so that later on, another sub function to the parent function can use X.
(i.e. callback functionA creates variable X.
later on, functionB requires variable X to be known, to know a specific path to take)
Is there any way to go about this?
I've read up on using handles to pass it to the second function, but I can't seem to figure out a way to do this.
Answer: Indirectly from Matlab guidata documentation:
in the first callback function:
function first_Callback(hObject, eventdata, handles)

% add some additional data as a new field called x
handles.x = 1;
% Save the change you made to the structure
guidata(hObject, handles)

in the second callback function simply use handles.x because handles is already passed as a parameter to the second callback, if they belong to the same parent figure.
function second_Callback(hObject, eventdata, handles)

% a will have the value 1
a = handles.x;

Note: Even though you are saving handles to hObject (which is the current object that has called the callback function), the handles structures is visible to other objects on the same figure. Saving handles structure to hObject and saving to the parent figure are virtually the same. Also you only need to use guidata if you make changes to the handles structure. If you only read the value of a handles member, you don't need to save it after that.
Comment: Sorry, just to make sure of something, and to clarify a little...
I actually have three pushButton uicontrols, all of which return the value (well two actually, let's say, x and y). When replaced in the function, the second (y) set as handles.y return the "error"

"Variable 'handles', apparently a structure, is changed but the value seems unused". Any ideas?
Comment: Remember that `handles` is a structure. You cannot refer to an undefined structure member. i.e. you first have to define `handles.x = 1` before you can say `a = handles.x`. If there are situations where your second button may want to read the value of `handles.x` before it's set, define `handles.x = 0` or similar default values in the figure load callback and save it using `guidata`
Comment: By figure load callback I mean `_OpeningFcn` callback function of your main figure.
Comment: I am having issues getting this to work, sorry, a little new to a lot of the concepts brought forward in matlab.
When I try to define a based off handles.x, it is tell me that there is not enough input arguments.
Comment: Can I get some more help here? In a small test file I attempted to work the handles, but I keep recieving the input argument error
Comment: "There is not enough input argument" usually means you are trying to call a function with fewer number of arguments that are allowed. You need to check the line of code the error message refers to to see what function is being called and what parameters are missing. This is a separate question that the one you posted here.


$a\in(0,\frac{1}{2})$, $\{x_{k}\}_{k\ge1}$ where $x_1=a$ and $2x_{k+1}=\left(\frac{x_k}{1-x_k}\right)^2$. Evaluate $\prod_{k=1}^\infty(1-x_k)$

Question:
For each $a\in(0,\frac{1}{2})$, we define a sequence $\{x_{k}\}_{k\ge1}$ where $x_1=a$ and $2x_{k+1}=\left(\frac{x_k}{1-x_k}\right)^2$. Evaluate $$\prod_{k=1}^\infty(1-x_k)$$

I first tried to use trigonometric substitution but couldn't find a suitable one so I found $x_2=\frac{a^2}{2(1-a)^2},x_3=\frac{a^4}{2(a^2-4a+2)^2}$. No pattern is visible to me to write $x_k$ explicitly in terms of k due to which I'm stuck here. What can be the way to proceed?
Comment: Looking at values of a (1/3,1/4,1/5,1/6,1/7,...) strongly suggests (i.e., not a proof) that the product is $\sqrt{1-2a}$ for $0<z<1/2$.
Answer: Given $x_1 =a \in\left(0, \frac{1}{2}  \right)$, the sequence is decreasing and bounded in $\left(0, \frac{1}{2}  \right)$ because
$$2(x_{n+1}-x_n)=\frac{x_n(2-x_n)(2x_n-1)}{(x_n-1)^2}<0 $$
The limit $l$ of the sequence is the solution of
$$2l = \left(\frac{l}{1-l}\right)^2  \implies l =0  \hspace{1cm} \text{(we note that } l<\frac{1}{2})$$
We have
$$
x_{n+1}-\frac{1}{2} = \frac{1}{2}\left(\frac{x_n}{1-_n}\right)^2-\frac{1}{2}=\left( x_n-\frac{1}{2} \right) \cdot \frac{1}{(1-x_n)^2}
\implies \color{red}{(1-x_n)=\sqrt{\frac{x_{n}-\frac{1}{2}}{x_{n+1}-\frac{1}{2}}}}
$$
then
$$\color{red}{\prod_{n=1}^{+\infty}(1-x_n)}=\lim_{n\infty}\sqrt{\frac{x_{1}-\frac{1}{2}}{x_{n+1}-\frac{1}{2}}} =\sqrt{\frac{a-\frac{1}{2}}{l-\frac{1}{2}}} \color{red}{= \sqrt{1-2a}} $$


redirect from and to subdomain with htaccess base on browser language

Question: I need to redirect my users in homepage base on their language.
I think I've to use
RewriteCond %{HTTP:Accept-Language}
but I can't figure out.
My last try:

RewriteEngine on
RewriteCond %{HTTP:Accept-Language} ^es [NC]
RewriteRule .* http://mydomain.com [R,L]

RewriteEngine on
RewriteCond %{HTTP:Accept-Language} ^en [NC]
RewriteRule .* http://en.mydomain.com [R,L]

RewriteEngine on
RewriteCond %{HTTP:Accept-Language} ^fr [NC]
RewriteRule .* http://fr.mydomain.com [R,L]

But this generate an infinite loop.
Folder structure

htdocs/index.php ->mydomain.com
htdocs/en/index.php  ->en.mydomain.com
htdocs/fr/index.php -> fr.mydomain.com
Answer: You need to make sure the HOST isn't already pointing to the correct place:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^mydomain.com$ [NC]
RewriteCond %{HTTP:Accept-Language} ^es [NC]
RewriteRule .* http://mydomain.com [R,L]

RewriteCond %{HTTP_HOST} !^en.mydomain.com$ [NC]
RewriteCond %{HTTP:Accept-Language} ^en [NC]
RewriteRule .* http://en.mydomain.com [R,L]

RewriteCond %{HTTP_HOST} !^fr.mydomain.com$ [NC]
RewriteCond %{HTTP:Accept-Language} ^fr [NC]
RewriteRule .* http://fr.mydomain.com [R,L]

Comment: The rules looks consistent, so they should all work the same. Try clearing your browser cache/history, or try a different browser to test it. When I use Chrome, I notice it will cache the original attempts, and not use the new redirect rules.
Comment: everything is fine with es language, but it goes on loop with english language...


Trigger on resource from resource

Question: Is it possible to change a resource from another resource. I like to change the background of StartButtonRed if the mouse is over StartButtonMain.
<code><ImageBrush x:Key="RedBackgroundActive" ImageSource="/Images/start_red_active.png" Stretch="Fill"/>

<Style x:Key="StartButtonMain" TargetType="{x:Type local:SimpleButton}">
    <Style.Resources>
        <ImageBrush x:Key="MainBackground" ImageSource="/Images/start_main_normal.png" Stretch="Fill"/>
        <ImageBrush x:Key="MainBackgroundActive" ImageSource="/Images/start_main_active.png" Stretch="Fill"/>
    </Style.Resources>
    <Style.Setters>
        <Setter Property="HorizontalAlignment" Value="Stretch"/>
        <Setter Property="VerticalAlignment" Value="Stretch"/>
        <Setter Property="Background" Value="{StaticResource MainBackground}"/>
        <Setter Property="Visibility" Value="Visible"/>
    </Style.Setters>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="{StaticResource MainBackgroundActive}"/>
            // Change the background of StartButtonRed to RedBackgroundActive
        </Trigger>
    </Style.Triggers>
</Style>

<Style x:Key="StartButtonRed" TargetType="{x:Type local:SimpleButton}">
    <Style.Resources>
        <ImageBrush x:Key="RedBackground" ImageSource="/Images/start_red_normal.png" Stretch="Fill"/>
    </Style.Resources>
    <Style.Setters>
        <Setter Property="HorizontalAlignment" Value="Stretch"/>
        <Setter Property="VerticalAlignment" Value="Stretch"/>
        <Setter Property="Background" Value="{StaticResource RedBackground}"/>
        <Setter Property="Visibility" Value="Visible"/>
    </Style.Setters>
</Style>
</code>
Comment: I'm not sure if this is exactly what you want, but check it out: http://msdn.microsoft.com/en-us/library/ms745683.aspx, specifically check out the section called "Extending Styles" and the `BasedOn` attribute.
Comment: @Coding Gorilla no but its good to know the BasedOn attribute.
Answer: You can't do this. Because styles are resources and triggers can only target FrameworkElements from within their own Template or using a Binding to an other actual FrameworkElement, you can't bind to another resource.
You could solve this with UserControl Triggers.

Trigger on resource from resource


limit fixed number of rows from a fixed number of categories

Question: For simplictiy sake, i will leave the fields which aren't relevant to the problem.
My table structure is,
News
news_id | parent_category | child_category
category
category_id | maincategory_name
subcategory
subcategory_id | subcategory_name
As it is already evident, category_id is linked to parent_id and subcategory_id is linked to child_category of the news table.

What I have right now
SELECT *
 FROM (

       SELECT news . * , @rn :=
       CASE WHEN @child_category = child_category
       THEN @rn +1
       ELSE 1
       END AS rn, @child_category := child_category
       FROM news, (

                   SELECT @rn :=0, @child_category := NULL
                   ) AS vars
                       ORDER BY child_category
                   ) AS T1

                        LEFT JOIN category ON parent_category = category.category_id
                        LEFT JOIN subcategory ON child_category =
                        subcategory.subcategory_id
                        WHERE rn <=12 AND parent_category = (SELECT category_id FROM
                        category WHERE maincategory_name='ukraine') AND
                        child_category!= (SELECT `subcategory_id` FROM subcategory
                        WHERE `subcategory_name` = 'kiev')
                        ORDER BY category.category_id DESC

The above sql works and fetches 12 rows from each category.
The problem
The problem i am facing now is, the query fetches data from every category. And I want to limit this category number to 2 or 3. e.g. If there is 8 subcategories in subcategory table, it'l fetch data from all of them. And I want to limit the fetching to a limit say, 3(any 3 categories).
I tried using an IN statement as in following,
SELECT *
     FROM (

       SELECT news . * , @rn :=
       CASE WHEN @child_category = child_category
       THEN @rn +1
       ELSE 1
       END AS rn, @child_category := child_category
       FROM news, (

                   SELECT @rn :=0, @child_category := NULL
                   ) AS vars
                       ORDER BY child_category
                   ) AS T1

                        LEFT JOIN category ON parent_category = category.category_id
                        LEFT JOIN subcategory ON child_category =
                        subcategory.subcategory_id
                        WHERE rn <=12 AND parent_category = (SELECT category_id FROM
                        category WHERE maincategory_name='ukraine') AND
                        child_category IN (2,4)
                        ORDER BY category.category_id DESC

where the IN range will be retrieve by a subquery. In logic, if i limit that subquery to 3 results, my job is done.  But as it turns out, IN statement doesn't support LIMIT clause within subquery.
So question is, what is a workaround on retrieving the datas (fixed but that i already figured out) from limited number of categories.

sameple data
News Table
| news_id | parent_category | child_category
|   1     |       1         |     1
|   2     |       1         |     2

Category Table
| category_id | maincategory_name
|      1      |      Ukraine
|      2      |      Russia
|      3      |      Belarus

subcategory table
| subcategory_id | subcategory_name
|        1       |     Kiev
|        2       |     Odessa
|        3       |     Moscow
|        4       |     Simferopol
|        5       |     Dnipropetrovsk

The result should be like this.....
Suppose Kiev, Odessa, simferopol and Dnipropetrovsk goes to maincategory 1 i.e. Ukraine and I want 2 categories excluding Kiev (i.e. result should contain either simferopol and Dnipro or Odessa and Dnipro or Odessa and simferopol )
The problem is, query will fetch all the 3 categories (or more if available) where as i want only 2 (or 3 at times).
FURTHER INFO

sql fiddle
create table News(news_id int, parent_category int, child_category int);
insert into News values (1,1,1), (2,1,2), (3,1,2), (4,1,4),(5,1,4), (6,1,5), (7,2,3), (8,1,5), (9,1,2);
create table Category(category_id int, maincategory_name varchar(100));
insert into Category values (1, 'Ukraine'), (2, 'Russia'), (3, 'Belarus');
create table Subcategory (subcategory_id int, subcategory_name varchar(100));
insert into Subcategory values (1, 'Kiev'), (2, 'Odessa'), (3, 'Moscow'), (4, 'Simferopol'), (5, 'Dinipro');

sample data

GOAL
From the above result I want to achieve the following:

Fetch result only from one main category (i.e. Ukraine here and remove the russia) but it can be easily done so no worries on that part.
Fetch Only 2 subcategories (Above set contains 3 subcategories. Odessa, simferopol and Dnipro. I want only any two of them). I can hardcode it to retreive it but i will be using this same query in other places too so hardcoding will defeat that purpose.
From each of the above 2 subcategories fetched above, maximum 5 rows should be obtained from each subcategory. (I have achieved that in the 1st query in my question).

From above 2 requirements, i have achieved no. 1 and no. 3. Where i am stuck is at number2.
From the result set, i am unable to fetch the result containing only 2 subcategories.
and result set outputs datas containinig all the categories available. (here, only 3 subcategories so result contains all the 3. If there will be 10 subcat, it will retrieve all the 10 subcat data). I hope now a bit more clear now.
Comment: @tombom more info added.
Answer: I'm afraid I may still don't get what you want. Why don't you simply use a GROUP BY?
/* SELECT * FROM ( */
SELECT
n.news_id,
c.maincategory_name,
sc.subcategory_name
FROM
News n
INNER JOIN Category c ON n.parent_category = c.category_id
INNER JOIN Subcategory sc ON n.child_category = sc.subcategory_id
WHERE maincategory_name = 'Ukraine'
GROUP BY maincategory_name, subcategory_name
ORDER BY RAND()
LIMIT 2
/* )q1 INNER JOIN with_whatever ON q1.news_id = with_whatever.Id */

The table with_whatever holds the data from which you want to get "maximum 5 rows should be obtained from each subcategory". Your sample data still doesn't reflect that. That's why I'm unsure, if it's what you're asking for.
Comment: I guess i am not able to explain it in a clear manner. I appreciate your effort. To make it simpler, can you run my 2nd query in the question in the fiddle? that's the exact result i want. Only problem is, inside that `IN` statement, the `(2,4)` should come from a subquery (From the subcategory table with referece to parentCategory) and not hardcoded. But the my subquery returns not only 2 but all the subcat that is available under the parent cat. I am unable to put a limit to 2 results inside that `IN` subquery.
Comment: @itachi And why 2 and 4? What's the criteria for that?
Comment: 2 and 4 refers to the subcategory_id in the subcategory table. The criteria is to select any 2 subcategories which falls under the main category. But each subcategory has one to many relationship with the main category table. Hence, main category needs to be specify each time.... I guess this approach has some troublesome areas. May be i need to rethink the design again....
Comment: You want the subcategory to be distinct, right? So I just added an `ORDER BY RAND()` so you don't get the same result over and over again. Then I don't see why my answer shouldn't be correct. Or I'm a bit retarded and really don't understand the question :)


Arguing a stationary distribution exists

Question: I am trying to show that there exists a stationary distribution when $q>p$ for the Markov process with one-step transition matrix
$$
\begin{bmatrix}
q  & p     & 0     &   0     & \dots     & 0  \\
q  & 0 & p & 0 &  \dots      & \dots \\
0 & q & 0 & p & \dots & \dots   \\
0  & 0 & q & 0 & \dots & \dots \\
\vdots  & \vdots       & \vdots & q & \dots & \dots \\
\vdots&\vdots&\vdots&\vdots&\dots& \dots& \\
0 & 0     & 0    & 0    & \ddots     & \ddots
\end{bmatrix}
$$
But, observing each resulting equality like
\begin{align*}
q\pi_{0} + q \pi_{1} &= \pi_{0} \\
p \pi_{0} + q \pi_{2} &= \pi_{1} \\
\dots
\end{align*}
I cannot establish a general pattern for each $\pi_{i}$ and then prove that they sum to $1$. Where am I going wrong? Or rather, am I just missing a pattern? It seems to be a formula that does not have a pattern.
Comment: The entries in the last row of your matrix don't add up to one.
Comment: @ByronSchmuland Oh no, I miswrote it. It is just supposed to continue like a normal random walk for the positive integers, one moment I'll edit.
Answer: The algebra is straightforward. We know $\pi P=\pi$ must be satisfied. The first equation gives us $\pi_1q=\pi_0p$. Take the equation: $\pi_2 q+\pi_0p=\pi_1$. A simplification gives us $\pi_2=(p/q)^2\pi_0$. Continuing this way, in general, you get: $\pi_k=(p/q)^k \pi_0$.
Summing up the $\pi$s to 1, you will find $\pi_0=1-p/q$. The other probabilities can be evaluated from this.


Getting OnPageChangeListener to change Text View

Question: I have a FragmentAdapter in a View Pager and it's all functioning correctly. Except, I need to a set an OnPageChangeListener so I can notify a TextView when the page has changed.
So this is what I have:
public class MainActivity extends FragmentActivity implements ViewPager.OnPageChangeListener{

    protected void onCreate(Bundle savedInstanceState) {

        ...

        tView1 = (TextView) findViewById(R.id.textView1);
        mViewPager = (ViewPager) findViewById(R.id.viewpager);

        ...
    }

    ...

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        tView1.setText("You are at position " + position);

    }

    @Override
    public void onPageSelected(int position) {

        tView1.setText("You are at position " + position);

    }

Except the 2 override "page" methods above don't even run when I swipe through pages. I have tried adding a print statement too, but nothing happens?
Any ideas why?
Comment: Are you setting the listener anywhere? setOnPageChangeListener(...)
Comment: I just implemented the methods?
Comment: That is not enough.... Do you know how listeners work?
Answer: add to your OnCreate
mViewPager.addOnPageChangeListener(this);

that's what's missing. You didn't pass the listener to the pager.
Comment: This causes my program to crash, there must be something else I'm doing wrong


Does drupal have another module that have the same feature as media watermark?

Question:
I am looking a watermark module that have a selection watermark just like in the image.
Unfortunately the media watermark module is support drupal 7.
Does drupal have another module that have the same feature as media watermark?
PS: I am using drupal 6.
Comment: I wish I find the alternative for Drupal 9
Answer: Try ImageCache Actions Module. I think this will help you...


What does the eigenspace E(1, A) mean?

Question: What does this notation stand for? The eigenspace $E(1, A)$ where $A$ is a $n \times n$ matrix.
Answer: I would take this to mean the space of eigenvectors of A which have an eigenvalue of 1 (including the zero vector). These eigenvectors form a vector space because the property of being an eigenvector with a given eigenvalue is preserved by scalar multiplication and by vector addition. The eigenspace of eigenvectors of A with an eigenvalue $\lambda$ is usuallly written as $E_\lambda(A)$, but $E(\lambda, A)$ works too.

What does the eigenspace E(1, A) mean?


Can i do command "service network restart" on dedicated server?

Question: If i do "service network restart" Linux command on my OpenVZ VPS host server (dedicated server where are virtual machines - VPSs hosted), how this can impact virtual machines? Can i loose SSH connectivity, why not?
Comment: It will interrupt the network connection of all virtual machines ...restarting "network" basically does a down/up cycle of your network interface. Is there really any reason to do this?
Answer: Can you restart the network service? (on the openvz host.. etc..)
Yes
What will happen?
Best case scenario: Nothing (horribly detrimental that is)
Worst Case: Loss of networking on the host. Loss of any connectivity to the host. Loss of any connectivity to the VMs. Critical Application failures on the VMs due to network connectivity issues. Corruption of databases etc.
The server could also explode killing everyone in the datacenter... (But there is just always a risk that the server was armed with a high yield nuclear device and the trigger was the service network restart command... Those are just risks most of us are willing to accept).
We can't tell you what will happen.
We don't know your VMs or their applications or even your network configuration. We don't recommend you do this unless you have a very VERY good concrete reason to do so... and even then we would urge you to find a way to do what you need without interrupting the network connectivity.


Why is my Javascript output for my Mad Lib blank? Possibly innerhtml issue

Question: I'm sure this is a simple fix but I don't see the problem. I was following a tutorial on making a JS Mad Lib and I wanted to experiment with the output. Adding more inputs. Well, when I put in all the inputs. It comes up blank. please keep in mind this is a project in progress and not the finished project. Any help is appreciated

    const userprompts = document.querySelector("#prompts");
    const story = document.querySelector("#story");
    const error = document.querySelector("#error");

    const submit = document.querySelector("#submit");
    submit.addEventListener("click", completestory, false);

    const reset= document.querySelector("#reset");
    reset.addEventListener("click", resetPage, false);

    document.querySelector('#name').focus();

    const thename = document.querySelector("#name");
    const firstverb = document.querySelector("#firstverb");
    const firstnoun = document.querySelector("#firstnoun");
    const adjective = document.querySelector("#adjective");
    const secondnoun = document.querySelector("#secondnoun");
    const adverb = document.querySelector("#adverb");
    const storyOutput = document.querySelector("#storyOutput")

    window.addEventListener("keydown", keydownHandler, false);

    function keydownHandler(event) {
      console.log("Enter key pressed");

    }

    function checkStory() {

    }

    function completestory() {
      let finishedstory = "";
      finishedstory += "There once was a person named " + thename.value + ". ";
      finishedstory += "One day, " + thename.value + "was " + firstverb.value + "out in the "
      + firstnoun.value + ". ";
      finishedstory += "All of a sudden, " + thename.value + "saw a " + adjective.value +
      "dragon!" ;
      finishedstory += thename.value + "thought for a second and did the only thing they could think of "
      + "They grabbed a " + secondnoun.value + ". " ;
      finishedstory += "With the " + secondnoun.value + "in hand. " + thename.value + adverb.value + "attacked the dragon.";
      finishedstory += "The dragon became very confused and left. The End";

      storyOutput.innerHTML = finishedstory();
    }

    function resetPage() {

    }
<!DOCTYPE html>

    <link rel="stylesheet" href="Mod3Layout.css">
    <meta charset="utf-8">
    <title>Sean's Mad Lib</title>

 Sean's Wacky Mad Lib

Please enter your prompts here

Enter a name here:
        <input id="name" type="text" placeholder="name">

Enter a verb here:
          <input id="firstverb" type="text" placeholder="verb 1">

Enter a noun here:
            <input id="firstnoun" type="text" placeholder="noun 1">

Enter an adjective here:
              <input id="adjective" type="text" placeholder="adjective">

Enter another noun here:
               <input id="secondnoun" type="text" placeholder="noun 2">

Finally, Enter an adverb here:
               <input id="adverb" type="text" placeholder="adverb">

             <button id="submit" type="button">Submit</button>

You did not answer all the questions. Please try
               again

Let's see what you wrote.

Hello Dave

        <button id="reset" type="button" name="Reset">Reset</button>

Comment: You're currently getting an error because `finishedstory` is not a function, but you're calling it; e.g., `finishedstory()`. It's actually just a `String` so try `storyOutput.innerHTML = finishedstory;` in your `completestory` function.
Comment: Thanks a lot. I knew it would be something simple
Answer: You were receiving the error Uncaught TypeError: finishedstory is not a function because of this line in your completestory function:
storyOutput.innerHTML = finishedstory();
As you defined it, finishedstory is a String; just change that line to storyOutput.innerHTML = finishedstory; and the error no longer gets triggered.

    const userprompts = document.querySelector("#prompts");
    const story = document.querySelector("#story");
    const error = document.querySelector("#error");

    const submit = document.querySelector("#submit");
    submit.addEventListener("click", completestory, false);

    const reset= document.querySelector("#reset");
    reset.addEventListener("click", resetPage, false);

    document.querySelector('#name').focus();

    const thename = document.querySelector("#name");
    const firstverb = document.querySelector("#firstverb");
    const firstnoun = document.querySelector("#firstnoun");
    const adjective = document.querySelector("#adjective");
    const secondnoun = document.querySelector("#secondnoun");
    const adverb = document.querySelector("#adverb");
    const storyOutput = document.querySelector("#storyOutput")

    function checkStory() {

    }

    function completestory() {
      let finishedstory = "";
      finishedstory += "There once was a person named " + thename.value + ". ";
      finishedstory += "One day, " + thename.value + "was " + firstverb.value + "out in the "
      + firstnoun.value + ". ";
      finishedstory += "All of a sudden, " + thename.value + "saw a " + adjective.value +
      "dragon!" ;
      finishedstory += thename.value + "thought for a second and did the only thing they could think of "
      + "They grabbed a " + secondnoun.value + ". " ;
      finishedstory += "With the " + secondnoun.value + "in hand. " + thename.value + adverb.value + "attacked the dragon.";
      finishedstory += "The dragon became very confused and left. The End";

      storyOutput.innerHTML = finishedstory;
    }

    function resetPage() {

    }
<!DOCTYPE html>

    <link rel="stylesheet" href="Mod3Layout.css">
    <meta charset="utf-8">
    <title>Sean's Mad Lib</title>

 Sean's Wacky Mad Lib

Please enter your prompts here

Enter a name here:
        <input id="name" type="text" placeholder="name">

Enter a verb here:
          <input id="firstverb" type="text" placeholder="verb 1">

Enter a noun here:
            <input id="firstnoun" type="text" placeholder="noun 1">

Enter an adjective here:
              <input id="adjective" type="text" placeholder="adjective">

Enter another noun here:
               <input id="secondnoun" type="text" placeholder="noun 2">

Finally, Enter an adverb here:
               <input id="adverb" type="text" placeholder="adverb">

             <button id="submit" type="button">Submit</button>

You did not answer all the questions. Please try
               again

Let's see what you wrote.

Hello Dave

        <button id="reset" type="button" name="Reset">Reset</button>


Proving there are infinite primes of some form $a+nd$

Question: I know by Dirichlet's theorem on arithmetic progressions that there are infinitely many primes of any type $a+nd$, where $a$ and $d$ are positive co-prime integers.
I come across many questions like - prove that there are infinitely many primes of form $4k+1, 6k+1, 6k+5, 8k+1,$ etc. where they use either quaratic residues or take some form of a number formed by the finite (assumed) set of primes of that form and then reach a contradiction.
I want to know how to tackle any such problem requiring to prove it for a certain form, it seems very non-trivial to me to begin.
Comment: There are informative answers at [this MO-question](https://mathoverflow.net/questions/16735/is-a-non-analytic-proof-of-dirichlets-theorem-on-primes-known-or-possible).
Comment: @DietrichBurde I don't want the proof of Dirichlet's theorem, I want how should we go about proving it for a certain form like $7k+3$ for eg.
Comment: You can use the "Euclidean proof" as in $4k+1$ etc. , if and only if Murty's criterion is met, see my answer. So the answer is, that you must use more analytic arguments involving $L$-series for cases like $7k+3$. Of course, all cases follow from Dirichlet's Theorem anyway.
Answer: A Euclidean proof, as for $4k+1,6k+1,6k+5,8k+1$ etc. is not always possible. In fact, we have the following Theorem:
Theorem 1. (Murty) A "Euclidean proof" exists for the arithmetic progression
$l \bmod k$ if and only if $l^2 \equiv 1 \bmod k$.
Proof: See here.
Comment: Very good :) :)
Comment: Thanks for the added reference
Comment: The introduction of this references discusses exactly what you have asked, if I understood correctly.
Comment: Yes, that was very specific to my query


Is there any any relationship between efficiency and confidence interval width?

Question: I do not understand the concept of the efficiency of a statistical test.
Is there some relationship to confidence interval width?
For example, suppose I have two statistical tests, A and B. Test A produces very wide confidence intervals, and test B produces very narrow confidence intervals. Does this have anything to do with the efficiency of the test?
Answer: Efficiency refers to the statistic and its distribution.  In your case with two distributions we should be estimating the same parameter and a fair comparison require an equal sample size.  Assuming this setup, the more efficient estimator will tend to have a smaller variance. So given the 1-1 correspondence between confidence intervals and hypothesis tests, the more efficient estimator should tend to have a shorter confidence interval.   I use the term "tend" because in any given case with finite sample size, it is possible for the more efficient estimator to have a larger variance.  The chance of this opposite occurrence becomes small as the sample size gets large.
Comment: Are you able to use the [site chat room](http://chat.stackexchange.com/rooms/18/ten-fold)?  If so, that would be a great place to discuss ways to use the site.
Comment: +1.  Good summary with excellent qualifying comments.  Since answering a question can be taken as *prima facie* evidence that it is sufficiently clear and has some interest or importance, might I suggest making a general practice of upvoting questions one has answered?
Comment: @whuber Thanks for the compliment. When I see others give good (correct an well-written answers I do sometimes use the upvote.  My hesitation is that I think I have daily limits and there are so many questions to potentially go through.
Comment: @whuber I have noticed that now that I have new privileges that I share with moderators I am not sure what to do to make use of them.
Comment: @whuber I tried meta CrossValidated and I think I was able to do some of these thing there.  I have used the chat room when there are excessive comments in a post but I didn't think it had anything to do with some of these moderating actions.


HyperV Eject passthru disk while VM is running

Question: I have a disk that I need to connect as a pass thru for one of my guest OSes, sbs 2011.  The guests internal backup program will backup to the disk, which I'm planning to attach to the VMS SCSI controller.  Since its a backup disk I also want to swap it.
I think what ill need to do, using powershell, is script the command to remove the pass thru from the VM, then use diskpart to take the disk offline m which will then allow me to remove the drive and add the other drive, and then reverse the steps I've outlined so the VM can backup again.
Does this sound correct?  If not, how should I go about this?
Answer: The drive will need to be offline on the host to mount it as a pass-through.  So, if it is mounted as a SCSI device on the VM, you should be able to remove it from the VM, it should disappear from the VM  You'd need to make sure it removes the disk gracefully though.  Do your swap and then replace the disk and reverse.  Sounds good in theory, but on the VM, you might have to import the foreign disk or put the disk back online.  Might have to work on the script to make it a bit smarter than simply forcing it.  But in theory it sounds like your idea will work.
If you are using it for backup, I'd want to see that it didn't hose up the disk.  One of those times you might want to test it to be sure.
Comment: Since it is based on 2008, it will, but might require using wbadmin from the command line to do it.  Once scheduled, it should work fine, but I am not 100% sure you can configure an SMB path as a destination.  You are looking for the -backupTarget command line switch.  I use it to backup our boxes to our Netgear ReadyNas 2100.  Works great.
Comment: Yes, will certainly be testing!  I'm hoping the sobs backup expects the disk to be removed (at least 2008 seems to work that way).  It never assigns a drive letter to the backup drive (removing it if there is one) so I think it should be ok.
Comment: Yeah, there is some voodoo there and I would test the heck out of it.  Might be better to just backup to a share on the drive instead of directly.  If you are using the Virtual NIC, then there should be only a small amount of overhead. I dunno, I don't think I would do it this way, but I've seen much crazier things in my day.
Comment: I don't think sbs allows backing up to a network share, but maybe 2011 is different.
Comment: Rather I meant to say I am not 100% sure you can configure the SMB path from the backup GUI.  It seems to be an odd limitation that the software can handle, but the GUI didn't or doesn't support.
Comment: I think its meant to simplify things for less experienced users.  After thinking about your answer I think ill leave the drive connected and add a second and mirror it.
Comment: Not sure if I agree with the "less experienced users" comment.  Even Windows Server won't let you do it.  I think it was an oversight on the part of the person doing the GUI and was just never addressed.  Keep in mind when the mirror breaks, you might have to manually reconnect them.  Though you might be able to automate this with an event trigger in task scheduler by searching for the drive being lost or removed/added.


Why is XPath failing to select anything from HTML?

Question: My HTML looks like
...
<lots of nested tags>

        ...

</lots of nested tags>
<lots of nested tags>

        ...

</lots of nested tags>
...

I've tried everything I can think of, by using XPath, to get a list of all <i class="icon-list" elements but I just cannot figure it out.
For instance I tried
//div[@class=\"brick-header\"]/ul/li/i[@class=\"icon-list\"]

but this gives me an empty list.
How do I do this?
Comment: What XPath did you try? This is a pretty straightforward XPath, so I am wondering were you did get stuck.
Comment: Why does your title ask about getting links but your example HTML show only `i` elements, no `a` elements or `href` links?
Answer: The following XPath will select all i elements of class icon-list regardless of ancestral elements:
//i[@class='icon-list']

Reasons your XPath might not be working

There is a namespace declaration to take into account.
Remedy: Declare proper namespace prefix and use it in the XPath (preferable), or test against the local name to avoid any namespace:
//*[local-name()='i' and @class='icon-list']

There are other classes listed along with icon-list.
Remedy: Use contains() rather than equality in the predicate:
//i[contains(concat(' ',@class,' '), ' icon-list ')]

JavaScript is building or changing the markup structure after your
XPath is running.
Remedy: Wait to apply test until document has finished loading and JavaScript has finished running.
Comment: I gave three reasons why it might not be working.  Perhaps your response might include how you've checked each of the reasons rather than merely saying "it didn't work".   To try to help further, I've added remedies for each of the potential issues.   Thank you.


Variable not resetting in function of event handler

Question: I have a page with 3 columns in it and varying amounts of text. These 3 columns need to be the same height. I have written a function that looks at the height of each column, checks which is tallest, and then sets all of their heights to that length.
I've got an event handler on the window.onresize event that runs this function. At the start of this function, the variable max_height is set to 0. The problem is, it never seems to get reset to 0 after being called multiple times. The new max_height just seems to keep being added to it, the heights of the columns grow taller on each resize. What am I missing?
function resizeHeights(){
    var callouts = $('.callout');
    var max_height = 0;
    callouts.each(function(i){
        if($(callouts[i]).height() > max_height){
            max_height = $(callouts[i]).height();
            console.dir(max_height);
            $(callouts[i]).height(0);
        }
    });
    callouts.each(function(i){
        $(callouts[i]).height(max_height + 50);
    });
}

$(window).on('resize', function(){
    resizeHeights();
});

Answer: Your code is setting max_height to the tallest column you have.  And, since you end up setting all your columns to max_height + 50, then each time you call this function, the columns will grow by 50 pixels.
The problem is that you are never able to see the "natural" height of the columns because once you've called this function once, the height is hard-wired to what you previously set it to and not allow to respond to layout changes due to the window changing size.
What you probably need to so is to clear the css height settings from all columns, then force a browser relayout (so the new natural height is calculated), then run the rest of the code in your function so you can see the natural height of the columns and based your manual height setting based on the new natural height values.
See this answer for how to force the browser to do a layout.
Answer: Try to rename ur variable max_height to ex. max_height2. Just to insure there is no conflicts with other global variable has the same name if there is.
Comment: A local variable always take precedence over a global with the same name so this cannot be the issue.
Comment: we are right,but we are a developer and should try every thing.
Comment: Not really.  It makes more sense to know which things could be causing it rather than making blind guesses or spending any time on things that actually can't be causing it.


How can i add a timestamp to my copy column excel VBA code that updates each day the time, ignoring past days?

Question: how can i output the current date into a cell?
Special feature:
I use a column as a template, where the current date should be entered daily. If I copy the column, the current date should be transferred. However, the date of previously copied columns is not allowed to change!
Example: Column A is the template. I have just copied it to Column C with VBA, now today's date should be displayed!
Column D I have already copied several days ago, there should be the old date in it, as correctly displayed!

goal is a kind of timestamp that stores the current date at the time of the copy into the cell
current VBA:
Sub ColumnCopyInsertNEW()

    Const ColumnsAddress As String = "D:E"
    Const LastColumnRow As Long = 2

    With Columns(ColumnsAddress)
        .EntireColumn.Hidden = False
        .Copy
        Dim cCount As Long: cCount = .Columns.Count
        .Cells(LastColumnRow, 1).End(xlToRight) _
            .Offset(1 - LastColumnRow, 1).Insert xlShiftToRight
        .EntireColumn.Hidden = False
    End With

End Sub

Answer: Date will give you today's date value.
Simply format to your needs
Range("C3").Value = Format(Date, "dd.mm.yyyy")
Comment: P.S.
Storing dates is always better in the column...
In your case, you will end up with a very unconfy sheet to use after 1month only...
Also, excel hates if dates are not stored in format dd/mm/yyyy...
Any date interactions with formulas inisde the excel, will be tricky using your date format


Trouble with thumb placement when practicing arpeggios on a piano

Question: I'm just now learning the correct fingering for when practicing scales and arpeggios. Scales are going quite well, but when I practice arpeggios, I seem to have a lot of trouble with my thumb placement. More specifically when I move to the second octave.
For example with a C major arpeggio, I press C > E > G with my thumb, indexfinger and middlefinger. But then I need to move my thumb all the way across to the next C underneath my hand. My wrist feels very uncomfortable when I do this. I also often press the C key very hard because I need to move my thumb very quickly in order to make it in time. Even if I try to start out slowly. I try to move my elbow to the right when doing this movement and it helps slightly, but it still feels uncomfortable in my wrist.
Does anyone have any tips on this issue that might help? Or is it really just practicing slowly until it gets better? The uncomfortable feeling makes me think I'm doing something wrong.
Answer: It's not so much making your thumb go underneath the fingers/palm as moving your whole hand. As soon as you've played the first C, the whole hand should have started to move right. By the time your middle finger hits the G, your thumb should be under that part of your palm. Whole hand then continues gently right, putting the thumb onto the next C.
The thump on that C is because you play the first three notes, then start to move your whole hand. Imagine instead your hand gently flowing to the right as each note gets played. As you then hit the second C, it stretches out so the other fingers are in line with the last three notes.
It all needs to be done in real slomo to start with, listening for even play on every note. Gradually, over a week, speed up, and you'll find it'll flow like it should.
When you come to play chromatics, the same trick works - concentrate on keeping the whole hand moving, with the wrist at the same height all the time.
Comment: It's way too soon to decide it's the preferred answer! There may well be other far better ones in the pipeline from people who have to do other things, like work for a living!
Comment: That's something you'll have to work out, dependent somewhat on how long your fingers are and how pliable your hand is. Trying to play legato, as arps are often played, requires the notes to flow into each other, not bleed into each other.
Comment: @Albrecht Hügli I always do some research before asking a question on here, but I was unable to find information on my specific situation. That is not to say that there isn't any. Perhaps my search term was incorrect or I used the wrong terminology.
Comment: Tipsi, this was not a critic. My comment was not finished, as I looked up the mailbox the comment has been posted. What I was going to say is that you'll find further advice when you look up here how to get speed in Chopin op. 10;1. I have found pdf of Cortot and Godowsky in IMLP and was surprised that they were  not mentioned in the answers to this questions.
Comment: @AlbrechtHügli - it's always possible to re-write a comment, add what's needed, post it, then delete the original comment.
Comment: @Tim you're right. I did it again. I'm used to stackoverflow for programming questions. Usually when you get a correct answer there, you'll accept that answer if it solves your problem. But music is very different, there are always different perspectives to seeing things and no answer is the be-all, end-all answer like it often is with programming.
Comment: Do I let go of the G key with my middlefinger before I press the second C with my thumb? Or should I simultaneously let go of G and press C? Because if I gently move my hand to the right, I will inevitably have to let go of G or do an awkward stretch with my hand.
Comment: the first point your mentioning is exactly what I would have given as advice too. I had no problems going up to the 3rd and the 5th but then I had the same problem as the OP. Last summer my grandchild started with piano lessons and he was playing the Chopin, Op. 10,1 in a very slow speed. I started to compete with him and looking for other analysis than mine I dropped to this SE site. And there have been already  similar questions and answers already given to this subject.
Comment: @Tim Alright, thanks for the answers. My fingers aren't short but they're not the longest either. I think with some practice I should be able let the notes flow into each other. Or at least I hope so. But my main priority now is practicing slowly and making sure there's no strain in my wrist.
Comment: yes, Tim, I know. Thank you.  But only 5 minutes. As you can see, I was in the same moment going to the question about reading  the bass clef and while commenting there this one here was closed. no problem! (as I write so slowly ;)
Comment: Check out an organ arrangement of *Tico Tico No Fuba*
Answer: The arm places the thumb.  Using just your arm and gravity - not your thumb's abductor, play your thumb down on C, then from the arm, lift up the arm and hand and leading with your elbow play the octave higher C.
Regarding your wrist pain, a lot of times when a pianist crosses the thumb under the palm, they anticipate the next finger position and twist the wrist.  This is called ulnar deviation going up and radial deviation going down.  Eventually, too much twisting can cause problems.  It will surely make you play unevenly and make your hands feel weak.  Get your playing into your arms before you start using your fingers (forearm muscles).
To help propel your arm, and thumb, use your pronator and supinator muscles to rotate the forearm.  They are located around your elbow.  With your arm in front of your chest, rotate left and right very fast.  Notice how fast you can move your thumb and pinky and notice that they don't fatigue at all.   Those are the muscles you should use to play the thumb.
Also, because of rotation, remember that every motion has an equal and opposite motion.  Using your pronator to play the first note with your thumb actually should start with supination.  The rotation in the opposite direction gives the finger power and speed without using any muscles that actually move the fingers.
Throw something. Notice that you first swing in the opposite direction you are throwing the object. You need that in your piano playing but up, down, in, out, left and right.  Try to play with a "still and quiet  hand" and you will indeed create tension.  Play from the arm and the hand will be still and quiet.
Answer: I assume you are using this fingering...

Obviously, you are having trouble with the transition from finger 3 to 1, the G4 to C5 move.
First thought: if playing the C major chord is considered easy, because so much beginner stuff is in C major, reconsider that all white key passages can be harder than a mix of black and white keys.
Try playing this arpeggio on B major. It should fit the right hand much more naturally. You can use this as a sort of transitional pattern to get the feel of passing the thumb under in an easier position. Compare it to the movement on C major.
Try playing the arpeggio descending as well as ascending. It shifts the which finger is last in the first position and first in the next. In other words, when ascending finger 3 is sort of 'holding' the first position, then finger 1 is in movement to get to the next position. When descending the finger roles are reversed, finger 1 is holding the first postion, finger 3 is in movement. It's a subtle difference, but it might help you get comfortable with the crossing under.
Also, you might try playing the full octave like this C4, E4, G4, C5 with fingering 1, 2, 3, 5. Then to change position you make a repeated note fingering on C5 using fingers 5, 1. Obviously, this doesn't directly practice passing the thumb under, but it will help with two things: help finger 1 spatially find C5, and contracting the hand to bring fingers 1 and 5 together. Both of those should help develop your hand and benefit crossing under.
Answer: I fully agree with Tim!
To get faster you have to move the whole hand (first looking and then  trying to play "blind" (closed eyes):

try to catch/touch  the 3 black keys over all octaves from down to up by your  1. finger on f# (right hand)
the same catch/touch with closed  the 2 black keys  starting with C#
when you have the orientation for finding the black keys try to find with closed eyes the key of C playing with your thumb and touching c# and d# with fingers 2 and 3 across all the octaves.
start to get more speed by playing the full triad (not arpeggio but the whole chord)
the same as ex. 4. but playing c-e-g-c by 1-2-3-5

look up for Chopin op. 10,1 in IMSLP, (also Godowsky and Cortot)
and look the advises in this SE
searching for Chopin etudes, CORTOT  and Godowsky.


Meaning of unusual residual plot

Question: I'm trying to use a residual plot in order to get a better understanding of my dataset and what I should be doing.
My data is a series of scored labels with a bunch of distance features used to predict them. I'm hoping to use linear regression.
When I generated my residual plot I ended up with the following unusual graph which I haven't seen before.

In my limited knowledge I'm aware that ideally a Residual plot should contain a cluster of points with a mean of 0. In a bad case scenario the plot is non random, most examples indicate a spiked residual error value at a given predicted value.
My graph however looks nothing like examples I have seen and I'm not certain how to interpret it. Could is perhaps be that my dataset is not suited for a regression model? What does the residual plot indicate about my data?
Additonal Information that may be useful:

r2 value: 0.32812704493994505
Comment: Consider an *ordinal* regression model.  It will automatically handle the nonlinearity.
Comment: It looks to me as if the model is missing some predictive factor, in part because the regression line does not pass through two groups of points on the plots. I suggest visually inspecting scatterplots of the raw data to see if a non-linear relationship might be apparent.
Comment: It sounds like a "scored label" might merely be an arbitrary assignment of numbers to distinguish different values of a response.  If so, your model is unlikely to work well (and the residuals show that).  Could you explain more about these "scores"?
Comment: Thanks for the advice about investigating scatterplots. A non-linear relationship did occur to me. The scores are indeed arbitrary. They represent the level of match between two users as labelled by someone based on some values. Is this not a application for a regression model? I've been sceptical about whether this would work from the onset however I was told to do it anyway. The only data available was a series of lists for each user consisting of roles they picked. These roles were then turned into distance values by way of turning them into a tree like structure and measuring distances.
Comment: It looks like you have a categorical predictor with five levels and one or more continuous predictors. Can you give more details about your model?
Comment: We originally created a model using the independant variable "Label" Which is an arbitrary level from 1 to 5 representing how good a match is.
Originally the model contained three features industry_distances, career_distances and location_distances. However recently (for reasons unknown to me)
we added 3 additional features with a integer value for the raw number of differences in the tree.
The features are calculated by generating a tree of distances and the final distance is calculated based on the similarity between two lists for each user.
Comment: Doing a little bit of reading I think the problem might be a learning to rank one, except we have zero analytics on the behaviour of our customers.
Comment: It's not so far as I can see spelled out anywhere else in this thread, but note that the usual definition residual $=$ observed $-$ fitted  or predicted implies that each distinct value of the observed falls on a line with a negative unit slope on a plot of residual versus fitted, As I see upwards slopes in your plot, I guess that your definition is fitted $-$ observed. Either way, parallel stripes on such a plot are diagnostic of a few distinct values of the response, 5 of them in your case.
Answer: It seems to me that you have 5 outcome values, 1 to 5. However, if you use ordinary linear regression in this case, your predicted values will not be constrained to take one of the values 1 to 5. This is why there are the 5 horizontal lines in the second graph, each with a spread of predicted values. This also explains the first graph: the two graphs are in fact equivalent, since the residual equals the predicted label minus the training label.
Instead of performing ordinary linear regression (which requires a continuous outcome variable), I'd instead perfom ordinal regression. I can advise you how to do this in R - could I ask what software you're using?
Comment: I'm currently using Python. I'm investigating using Ordinal Regression right now using the mord package. I'll let you know how it goes. Thankyou.
Comment: After some experimenting Ordinal Regression is indeed the way forward. Thankyou for your answer.

Meaning of unusual residual plot


Como eu consigo recuperar o File explorer no menu lateral do VS Code?

Question: Eu estou com um problema, no pc do escritório aquele ícone do file explorer que fica no menu lateral do vs code sumiu, mesmo abrindo o projeto ou a pasta do projeto ele não paparece.
Para aparecer eu uso o CTRL+SHIFT+E e vejo os arquivos que preciso, mas ao escolher o arquivo ele some novamente.
Eu queria deixar fixo.
Alguém sabe onde configuro isso?
Answer: Tenta utilizar Ctrl + B ou Menu View
[
Comment: Obrigado jovem @rxpha, todas as opções dão certo. Mas para fixar mesmo só deu certo clicando com o botão direito na lateral e selecionando a opção explorer.
Comment: e quando o explore não está na opção do botão direito?
Answer: Clique com o botão direito na lateral e selecione as opções que estão desmarcadas.
Comment: Obrigado @Felipe Moreira
Comment: Sem problemas, cara!