LEFT JOIN issues

Question: I have a views to display a list of company nodes. The company content type has one boolean field 'field_company_exclude_jobs_home'. This field is to indicate whether this company should be excluded from this views list.
If this field has been checked, then the company should be removed from result. The easy way is to add a filter for this boolean field in views. The thing is by default this field doesn't have value. So the configuration from views filter is not a good solution.
The raw views sql look like this.
<code>        SELECT node_field_data.nid AS nid, RAND() AS random_field
        FROM
        {node_field_data} node_field_data
        LEFT JOIN {node__field_company_exclude_jobs_home} node__field_company_exclude_jobs_home ON node_field_data.nid = node__field_company_exclude_jobs_home.entity_id AND (node__field_company_exclude_jobs_home.deleted = '0' AND node__field_company_exclude_jobs_home.langcode = node_field_data.langcode)
        WHERE (( (node_field_data.status = '1') AND (node_field_data.type IN  ('company')) AND (node__field_company_exclude_jobs_home.field_company_exclude_jobs_home_value <> '1') ))
        ORDER BY random_field ASC
</code>
What I need is when company doesn't have a row record at table node__field_company_exclude_jobs_home, this company should also returned.
Is this something possible to be done at views sql query alter level? Btw, this can be done at views_pre_render() level to exclude companies already. I'm just curious is this possible for a sql query level.
Answer: There's something my colleague has figured out to make this work in a query level.
Add two filters in view ui.
<code>WHERE (( (node_field_data.status = '1') AND (node_field_data.type IN  ('company')) AND (node__field_company_exclude_jobs_home.field_company_exclude_jobs_home_value <> '1' or node__field_company_exclude_jobs_home.field_company_exclude_jobs_home_value is '') ))
</code>
Views ui doesn't have option for filter to allow NULL value. So the second condition "is ''" is made through views_query_alter() level.
<code>$query->where[2]['conditions'][1]['value'] = NULL;
$query->where[2]['conditions'][1]['operator'] = 'IS';
</code>

LEFT JOIN issues


WebDriver FirefoxDriver, executar click em checkbox

Question: Estou criando um robô para logar em uma pagina, marcar um checkbox e efetuar um download de um arquivo de exportação. Porem não estou conseguindo executar o checked em um checkbox. Estou usando Selenium WebDriver com FirefoxDriver com o método via XPath:
    IWebDriver driver = new FirefoxDriver();
                driver.Url = "";

                driver.Manage().Window.Maximize();
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);

    driver.FindElement(By.XPath
    ("//div[@class='d-flex flex-row']//input[@type='checkbox']")).Click();

Imagens do site:
Comment: dá algum erro ou só não clica?
Comment: @LucasMiranda só não clica!
Comment: Já tentou clicar no `span` ou  no `svg`? Isso ja aconteceu comigo, quando não consigo clicar diretamente no `input` de um `checkbox` tento clicar no elemento que esta a cima dele
Comment: @Tmilitino não estou muito familiarizado com montar o xPath corretamente! Usando o exemplo de cima vc poderia me mostrar como ficaria o xPath para clicar no span ou svg?
Answer: Como falei no comentário,  o seu código ficaria mais ou menos assim, só mudaria o elemento que iria procurar. Como o input esta "encoberto" por outros elementos fica mais difícil realizar algum tipo de ação com ele.
 IWebDriver driver = new FirefoxDriver();
                driver.Url = "";

                driver.Manage().Window.Maximize();
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);

    driver.FindElement(By.XPath("//span[@class='jss78']")).Click();

Obs: olhando melhor o HTML não dá para clicar no svg porque ele está marcado como oculto hidden=True.
Você pode aprender mais sobre XPATH neste link


Warning: Task "karma" not found when running grunt test

Question: http://www.sitepoint.com/kickstart-your-angularjs-development-with-yeoman-grunt-and-bower
After following this interesting guide about Angular, Yeoman, Bower and Grunt I was able tot bootstrap an Angular application.
Everything works fine except the testing with Karma. When I run:
grunt test

I get the following error:
Warning: Task "karma" not found. Used --force, continuing.

Done, but with warnings

I checked if I have installed Karma, but that is installed. For Grunt it appears you need to install grunt-karma. So I tried that throughout the following command:
npm install grunt-karma --save-dev

This gives me errrors like:
errno: 53,
code: 'ENOTEMPTY',
path: 'C:\\tmp\\phantomjs\\phantom-1.9.2-windows-.zip-extract-' ..

I am on Windows and executing commands from the powershell.
Hope someone can help.
Edit karma.conf.js and gruntfile
// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function(config) {
  config.set({
    // base path, that will be used to resolve files and exclude
    basePath: '',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'app/bower_components/angular/angular.js',
      'app/bower_components/angular-mocks/angular-mocks.js',
      'app/bower_components/angular-resource/angular-resource.js',
      'app/bower_components/angular-cookies/angular-cookies.js',
      'app/bower_components/angular-sanitize/angular-sanitize.js',
      'app/scripts/*.js',
      'app/scripts/**/*.js',
      'test/mock/**/*.js',
      'test/spec/**/*.js'
    ],

    // list of files / patterns to exclude
    exclude: [],

    // web server port
    port: 8080,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};

Gruntfile
    // Generated on 2013-11-02 using generator-angular 0.5.1
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {
  grunt.loadNpmTasks('grunt-karma');
  require('load-grunt-tasks')(grunt);
  require('time-grunt')(grunt);

  grunt.initConfig({
    yeoman: {
      // configurable paths
      app: require('./bower.json').appPath || 'app',
      dist: 'dist'
    },
    watch: {
      coffee: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.coffee'],
        tasks: ['coffee:dist']
      },
      coffeeTest: {
        files: ['test/spec/{,*/}*.coffee'],
        tasks: ['coffee:test']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer']
      },
      styles: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
        tasks: ['copy:styles', 'autoprefixer']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },
    autoprefixer: {
      options: ['last 1 version'],
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          base: [
            '.tmp',
            '<%= yeoman.app %>'
          ]
        }
      },
      test: {
        options: {
          port: 9001,
          base: [
            '.tmp',
            'test',
            '<%= yeoman.app %>'
          ]
        }
      },
      dist: {
        options: {
          base: '<%= yeoman.dist %>'
        }
      }
    },
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/*',
            '!<%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: '.tmp'
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/scripts/{,*/}*.js'
      ]
    },
    coffee: {
      options: {
        sourceMap: true,
        sourceRoot: ''
      },
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/scripts',
          src: '{,*/}*.coffee',
          dest: '.tmp/scripts',
          ext: '.js'
        }]
      },
      test: {
        files: [{
          expand: true,
          cwd: 'test/spec',
          src: '{,*/}*.coffee',
          dest: '.tmp/spec',
          ext: '.js'
        }]
      }
    },
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: '<%= yeoman.app %>/bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false
      },
      dist: {},
      server: {
        options: {
          debugInfo: true
        }
      }
    },
    // not used since Uglify task does concat,
    // but still available if needed
    /*concat: {
      dist: {}
    },*/
    rev: {
      dist: {
        files: {
          src: [
            '<%= yeoman.dist %>/scripts/{,*/}*.js',
            '<%= yeoman.dist %>/styles/{,*/}*.css',
            '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
            '<%= yeoman.dist %>/styles/fonts/*'
          ]
        }
      }
    },
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>'
      }
    },
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        dirs: ['<%= yeoman.dist %>']
      }
    },
    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },
    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },
    cssmin: {
      // By default, your `index.html`  will take care of
      // minification. This option is pre-configured if you do not wish to use
      // Usemin blocks.
      // dist: {
      //   files: {
      //     '<%= yeoman.dist %>/styles/main.css': [
      //       '.tmp/styles/{,*/}*.css',
      //       '<%= yeoman.app %>/styles/{,*/}*.css'
      //     ]
      //   }
      // }
    },
    htmlmin: {
      dist: {
        options: {
          /*removeCommentsFromCDATA: true,
          // https://github.com/yeoman/grunt-usemin/issues/44
          //collapseWhitespace: true,
          collapseBooleanAttributes: true,
          removeAttributeQuotes: true,
          removeRedundantAttributes: true,
          useShortDoctype: true,
          removeEmptyAttributes: true,
          removeOptionalTags: true*/
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>',
          src: ['*.html', 'views/*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },
    // Put files not handled in other tasks here
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            'bower_components/**/*',
            'images/{,*/}*.{gif,webp}',
            'styles/fonts/*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: [
            'generated/*'
          ]
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },
    concurrent: {
      server: [
        'coffee:dist',
        'compass:server',
        'copy:styles'
      ],
      test: [
        'coffee',
        'compass',
        'copy:styles'
      ],
      dist: [
        'coffee',
        'compass:dist',
        'copy:styles',
        'imagemin',
        'svgmin',
        'htmlmin'
      ]
    },
    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      }
    },
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },
    ngmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>/scripts',
          src: '*.js',
          dest: '<%= yeoman.dist %>/scripts'
        }]
      }
    },
    uglify: {
      dist: {
        files: {
          '<%= yeoman.dist %>/scripts/scripts.js': [
            '<%= yeoman.dist %>/scripts/scripts.js'
          ]
        }
      }
    }
  });

  grunt.registerTask('server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'copy:dist',
    'cdnify',
    'ngmin',
    'cssmin',
    'uglify',
    'rev',
    'usemin'
  ]);

  grunt.registerTask('default', [
    'jshint',
    'test',
    'build'
  ]);
};

Comment: +1 for this: **npm install grunt-karma --save-dev**. Thanks.
Comment: It looks like your `c:\tmp\phantomjs\...` folder is not empty and `karma` is trying to install `phantom.js` to run. Can you empty the folder and then try?
Comment: Good suggestion. I tried it but it geives me the same error sad enough
Comment: Please provide your karma.conf.js & Gruntfile.js or whole project repo if it's hosted somewhere.
Comment: Have you added the karma task to the gruntfile?
Comment: @Juhana he shouldn't have to. `karma` task is registered automatically by generator-angular. Sjaak, correct me if I'm wrong.
Comment: I also added the karma task to the grunt file. But I think the problem is in the fact I can;t get grunt-karma installed.
Comment: By the way, I added some of my config files. I hope someone can spot the problem!
Answer: Download phantomjs package from https://github.com/Obvious/phantomjs
Unpack and copy it into node_modules of your project.
Run below command gain:
npm install grunt-karma --save-dev

Hope this help.
Comment: before running `npm install grunt-karma --save-dev` try to install the dependencies by running `npm install jasmine-core phantomjs --save-dev`
Comment: I'd recommend cloning the git repo and using `npm link` to it to your global `node_modules` folder... This way it's globally available. :)
Comment: Check that extracted folder name is `phantomjs`, not `phantomjs-master` :). I'm not sure yet when to use global or local modules, but `npm link` sounds like right way to do it.
Comment: I was following the tutorial at http://yeoman.io/codelab/write-unit-tests.html and hit the same problem. npm install grunt-karma --save-dev worked for me as well.
Answer: I had to turn off antivirus (Eset).
Comment: This sounds interesting, since I also use ESET
Comment: And I use mac :)
For me problem was karma and phantomjs was not installed

npm install grunt-karma --save-dev
npm install karma-phantomjs-launcher --save-dev
Answer: The only solution for me that work is:
    sudo npm install grunt-karma karma karma-phantomjs-launcher karma-jasmine jasmine-core phantomjs-prebuilt --save-dev

grunt test

or:
    grunt serve,
 it's work !


Converting from cylindrical to spherical coordinates?

Question: I am supposed to convert the point $(100, -\dfrac{\pi}{6}, 50)$ from cylindrical to spherical. The $\rho$ and $\theta$ are easy ( $\sqrt{100^2+50^2}, \dfrac{\pi}{6}$ respectively) but the $\phi$ is giving me trouble. Visualizing it, I can see that $\sin\phi$ should be $\dfrac{100}{\sqrt{100^2+50^2}}$. However, the book says that $\cos\phi = \dfrac{50}{\sqrt{100^2+50^2}}$. I can see how the book is right, but I can't see why my answer is wrong (I checked numerically)
Answer: Since $\sin^2 \phi +\cos^2\phi =1$, then $\sin \phi =\frac{A}{\sqrt{A^2+B^2}}$ gives the equivalent angle to $\cos \phi =\frac{B}{\sqrt{A^2+B^2}}$.
For the problem of interest, $A=100$ and $B=50$ and
$$\phi = \arcsin\left(\frac{100}{\sqrt{100^2+50^2}}\right)=\arccos\left(\frac{50}{\sqrt{100^2+50^2}}\right)$$
Comment: But the cosine answer evaluated to 1.5 (http://www.wolframalpha.com/input/?i=arccos%2850%2F12500%29) and the sin answer evaluated to .008   (http://www.wolframalpha.com/input/?i=arcsin%28100%2F12500%29)
Comment: Never mind, I realized I forgot to put the square root
Comment: @Ovi You had me concerned for a moment.  Yes, the square root is important.  ;-))
Answer: Both are correct, since
$\sin\phi$ = $\dfrac{a}{\sqrt{a^2+b^2}}\,,  \cos\phi = \dfrac{b}{\sqrt{a^2+b^2}}$ are different ratios of sides of the same right angled triangle.


differential equations: phase flows in 1 and 2 dimensions

Question: I was participating in a conversation about fitting a one dimensional ODE to a periodic time series. The data in question was the mauna loa dataset. One of the people on the thread was saying that this data could not be fit by a one-dimensional ODE. My background is statistics, so I have not looked at my Strogatz book in a while.
I just wanted to make sure that my logic was sound here. The reason that you cannot model this curve using a one dimensional ODE is that you cannot have oscillations in one dimension. I suppose you can't have the phase flow cross itself, and in one dimension that means the derivative cannot change from positive to negative--as would be necessary for an oscillation.

After looking at Strogatz again, it seems like one dimensional ODE seem to proceed towards an asymptote. But they key reason for this behavior is that in one dimension, the phase trajectory cannot reverse itself--so it has to either go to +/-infinity or stop at a fixed point. The figure below shows the time evolution for a one-dimensional ODE from chapter 2 of Strogatz.

Now I could model this dataset using a 2 dimensional ODE right, and that should not have any trouble with capturing the oscillation. If I remember in 2 dimensions we cannot have chaotic behavior.
Answer: One can  model this as the solution of a first-order ordinary differential equation!
Consider for example $\frac{dy}{dt} = a y(t)+ p(t)$ where $a$ is a constant and $p(t)$ is a periodic inhomogeneous forcing term.
Without $p(t)$ the solution is pure exponential growth.  The periodic forcing term $p(t)$ has the effect of imposing  an additional wave-like component to the full solution.
Comment: that is an interesting idea. Yeah, so the forcing term can introduce the period behavior, haha. But I get your point that without this forcing term, I would just get exponential growth.


GRE tunneling in vmware vsphere guest

Question: Is it possible to make a GRE tunnel between a dedicated linux machine and a vmware vsphere guest VM (running debian wheezy)?
Comment: The answer to this question is "Yes". But a one word answer is too short for a real answer, so I'm suggesting that you elaborate on your question with details on why you think it might not work and what your actual question is.
Comment: Unless your question is concerning the actual virtualisation itself, the answer to any "can I... on a virtual machine..." question is nearly always the same as it would have been if the question was asked about non-virtual machines.
Answer: Yes, of course it's possible.
A virtual machine runs the same kernel as a physical machine, has the same network stack, and the same concept of a network interface which its traffic goes in and out of.
The VMWare vSwitch is a software implementation of a network switch, so is the Linux bridge driver used in KVM.
If you search Google for "linux gre tunnel" you'll find many copy-paste examples.

GRE tunneling in vmware vsphere guest


Shader inputs to registers mapping

Question: I have a compiled pixel shader 4.0 (I don't have source code for that), with the following in the input signature:
// Name                 Index   Mask Register
// TEXCOORD                 4   xyz         4
// TEXCOORD                 8      w        4

There're are other input slots, I've only pasted the interesting lines of the signature.
As you see, the signature says both TEXCOORD4 and TEXCOORD8 input values go to v4 input register, the former one to xyz fields, the latter one to w field.
MSDN says the type of TEXCOORD[n] input is float4.
Which component of TEXCOORD8 input value goes to the v4.w field, x or w?
Answer: I don't think that mapping is specific to a particular component - the HLSL compiler is just attempting to map the inputs to a more efficient layout. I'm fairly certain the input signature for the shader is going to look something like:
float4 myPixelShader(float3 input_f3 : TEXCOORD4, float input_scalar : TEXCOORD8)
{
    // ...
}

so if you're looking to create a vertex shader that outputs to this particular shader, you could just mirror that layout in your output, so something like:
struct MyInterpolants
{
    float3 something : TEXCOORD4;
    float  something_scalar : TEXCOORD8;
}

MyInterpolants MyVertexShader(...)
{
    MyInterpolants o;

    float3 calc;
    float4 some_var;

    // Some code here that does something and fills elements of some_var and calc

    o.something = calc;
    o.something_scalar = some_var.z;

    return o;
}

should map just fine. It doesn't really matter which element of a local variable is mapped to that output, as long as you're passing a scalar and the signatures between the pixel shader input and vertex shader outputs match. So you could pass x, y, z or w to that scalar output and it'll work out the same.
Comment: You're right, thanks.
I'm not writing VS, I'm patching and recompiling these PS-es (automatically, the game has 3k compiled pixel shaders).
It's a bug in the HLSL decompiler I'm using. When I looked at the disassembled ASM code, indeed it only accessed either v4.xyzx/xxyz or v4.w/wwww But the decompiled HLSL contains code to access all of them, like w4.xww for a scalar argument, that fails to compile back.

Shader inputs to registers mapping


What type of regression model do I use?

Question: $y = \mathbf{X} \beta$ + $\epsilon$ + $m$
Where y, $\epsilon$, and $m$ are $n \times 1$ column vectors, $\beta$ is $p \times 1$ and $\mathbf{X}$ is $n \times p$.
$y$ is a noisy time-series signal modeled by linear combinations of a basis set $\mathbf{X}$ discribed by $\beta$.  $\epsilon$ is additive Gaussian noise.  $m$ is an estimate of the mismatch inherent in the reconstruction.  The columns of $\textbf{X}$ can't perfectly reconstruct $y$, even if it were noiseless.  Am I correct in my understanding that this can be called an errors-in-variables model?
So given y and $\textbf{X}$, what is $\beta$?
Here's the twist:  The true value of $\beta$ should either be 0 or 1, while all other variables are comprised of continuous data.  What I'd like to be able to do is find $\beta$ to be a value between 0 or 1 which corresponds to a probability the corresponding column of $\textbf{X}$ is present in the reconstruction.  A value in $\beta$ of 1 indicates that its corresponding column of x is present, 0 not.
Since the columns of $\textbf{X}$ can't perfectly reconstruct $y$ even if it were noiseless, basic methods like OLS give answers where elements of $\beta$ are above 1 and below 0, which for me are unphysical.
In other words, is there a way to constrain the results of a linear regression ($y = \mathbf{X} \beta + \epsilon + m$) to only admit $\beta$ values between zero and 1 in a way which they can be interpreted as a probability that $\beta$ equals one or not?  Perhaps through the use of a prior distribution?
If anyone has any keywords I can look into, or references to point out, that would be very appreciated!
P.S. If anyone can give a Bayesian interpretation.. Bonus points!  The people this is for love that stuff.
Thanks in advance!
Comment: You seem to have things inverted, linguistically.  **X** should be a matrix of variables while **B** is a vector of parameters to be estimated.
Comment: @PeterRabbit Might I suggest you edit the question to make it a little less confusing? Currently, $\beta$ seems to be referred to as both a parameter and a random variable. Which is it? Second, you state in some places that $\beta$ is constrained to be either 0 or 1, yet in other places that it is constrained to lie between 0 or 1 (the two are obviously VERY different).
Comment: Logistic regression is used when $y$ is binary variable.
Comment: Right.. It just seemed in the ballpark I guess.
Comment: I don't understand how your $\beta$ can be either 0 or 1, can you show some of your data and the way you estimate your parameters. From the details you have provided it seems that you are doing some  basic mistakes.
Comment: It is an odd situation.  What is the protocol for showing data on the site?  I'll try to explain though.  The matrix $\textbf{X}$ are the results from solving an inverse problem on a collection of signals from a simulation.  The parameters of the simulation were defined originally by $\beta$ (columns of a matrix $\textbf{B}$).  The goal is to do parameter estimation on an incident signal y.  Let me know if there is anything else you need to know!  I am just wondering if there is a way to say:  "This column of X is 90% likely to be present in y, and this other column is only 10% etc etc."
Comment: Your explanation doesn't make it clearer. What is matrix $B$?
Comment: Sorry, matrix $\mathbf{B}$ defines the input initial conditions of a simulation (parameters).  Step 1.  Given $\textbf{B}$ and $\textbf{Y}$, find $\textbf{X}$.  $\textbf{XB = Y}$.  I have a solution for this, which is $\mathbf{X}$.  Now, imagine a new signal comes in to a detector, not one of the original columns of $\textbf{Y}$ but a new one y with some noise added.  What are its parameters?  (Find $\beta$ as described).  Is this really a strange situation?  Having prior knowledge that $\beta$ is binary?
Comment: All that other stuff though I think I have worked out pretty solid.  The actual Q is as originally posted.  Thank you for considering the problem though!
Comment: Sorry for the confusion.  I am new to this field and havn't mastered the terminology.  In these comments I am trying to provide background information.  These comments do not further describe the problem I am asking about, which is as stated in the original question.  To perhaps further clarify my original question, is there a way to constrain the results of a linear regression ($y = \mathbf{X} \beta + \epsilon$) to only admit $\beta$ values between zero and 1?  Which can be interpreted as probabilities?
Comment: Sorry, I think I have edited to help fix the confusion.  $\beta$ is the solution to the regression problem.  The solution is only "physical" in my case, if its elements can only be either 0 or 1.  Due to the uncertainty in the situation, I am asking if it is possible find a solution which treats $\beta$ as a probability that a column of $\textbf{X}$ is present in $y$.  In that case, it should range between 0 and 1, where if an element of it is say, .9, that could be interpreted as saying that there is a 90% chance that its corresponding column of $\textbf{X}$ is present in the reconstruction.
Comment: From my understanding, treating it this way, means that you are treating it to be a random variable that you are making inferences on.  Sorry for my poor use of terminology.
Comment: You will be more successful in explaining your problem if you try to put it in *your* terms rather than in some abstract mathematical formulation or something else you imagine we're familiar with: that will limit the potential for confusion to *us*, rather than both parties! It sounds rather like you are trying to formulate a PCA rather than a regression problem, but without knowing anything about the problem you're really trying to solve, it's not possible to suggest alternative models.
Comment: >_< OK.  Should I just repost a new Q?  I fear this thread may be going down the drain, and further editing seems to just make this more confusing for everyone.
Answer: You can always force the $\beta$s to be between 0 and 1 by rewriting the likelihood in terms of $\beta_j = f(\beta^*)$ for some function $f$, e.g. $1/(1+\exp(-\beta^*))$. Then optimise the $\beta^*$s but report the $\beta$s.  However that won't automatically get you an interpretation in terms of the probability that $\beta$ is relevant to the regression.
So I think the first thing to do is  separate, conceptually speaking, the question of the probability that each $\beta_j$ is equal to zero i.e. not included/relevant from the value it should take if it is relevant.
As for models, the keywords are probably Bayesian and  automatic relevance determination.  Assume a Bayesian model with a hierarchical prior such that $p(\beta \mid \alpha) = \prod_j N(0, \alpha_j^{-1})$ and maybe a gamma prior on the $\alpha$s if you're going to sample.  As $\alpha_j$ goes to infinity, $\beta_j$ is more probably equal to zero.
Then integrate out (or optimise) the (ir)relevance parameters $\alpha$ during posterior inference to get predictions for $y$ and separately examine the $\alpha$s to give you an idea which $\beta$s are irrelevant.  For more details on these methods, the references I have to hand are MacKay (ms) or Tipping's work, and a tech report by Minka et al. discussing fitting stategies.
I've no idea what is your $m$ parameter(s), so I may have missed something to do with that.
Answer: If you use simple regression (say OLS), then $\beta$ can be converted to a t-stat, which then can be converted to a p-value, which ranges between $0$ and $1$; a p-value of $0$ for $\beta_i$ means a significant contribution of $X_i$ to $y$, whereas a p-value of 1 means no contribution of $X_i$ to $y$.
Does this help?
Comment: I thought just using OLS or something, but the actual values of $\beta$ _are_ 0 and 1 (From the data set I have). Also when I do that, many times I get negative values for $\beta$, which is not very good for what I'm doing.  I'll look into your suggestion of t-stat -> P-value though, I don't know anything about t-stats and p-values.  Thank you!
Answer: If you don't know anything about t-stats and p-values then you really need the help of a professional statitician on this project, or take some stats courses (what you are asking is beyond the intro courses) until you have enough knowledge to do this.
Along the way as you are learning (or discussing with a consultant), least squares regression with bounds on the slopes is just a case of quadradic programming and many stats and math programs have routines for doing quadradic programming.
If you want to do this (assuming "this" is well defined) using Bayesian methods then it is pretty straight forward, just choose priors that limit your parameters to the range desired (uniform or beta priors, possibly discrete priors).
You may also want to look at model averaging or Bayesian model averaging, these can give answers of the probability of an x variable being a predictor of the y variable.
We need to understand the problem better (and you need to understand the statistical modeling better) in order to give more specific advice.
Answer: No. This is not an errors in variables problem. That would refer to noise in the INDEPENDENT variables, i.e., X.
Your problem is a bound constrained OLS problem, where the variables are constrained to lie in the closed interval [0,1]. Can you truly interpret these numbers as probabilities? That seems a stretch, if you use a least squares in any form to do the estimation. The numbers are then simply linear combinations of the independent variables, NOT probabilities.
For the numbers to make sense as probabilities, you would arguably need to do some variety of maximum likelihood estimation. Of course, you can always feel free to interpret a number in any way you want, but if you want a meaningful result, it is best to use statistics properly. For that to work, you need to clearly define what it means for a column to be part of the model. A linear combination is NOT a probability.

What type of regression model do I use?


MvvmCross (iOS) can't bind property in UILabel derived class

Question: MvvmCross noob here. Does anyone know why I can't bind a property in a UILabel derived class?
var set = this.CreateBindingSet<LoginView, LoginViewModel>();
set.Bind(_serverValue).For(p => p.Text).To(vm => vm.ServerListSelectedItem);
set.Bind(_serverValue).For(p => p.Visible).To(vm => vm.IsServerListAvailable);
set.Apply();

private class ServerValue : UILabel
{
  public bool Visible
  {
    get { return !Hidden; }
    set { Hidden = !value; LoginView.LayoutControls(); }
  }
}

The text gets updated but the Visible property never does. Should I even expect that this should work?
Thanks,
Jon
Answer: MvvmCross uses Reflection - and Reflection is subject to .Net security rules.
Try making your control public rather than private to see if that helps -
 public class ServerValue : UILabel ...`

Beyond that, there is also a registered custom binding for Visible in MvvmCross by default - see https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.Binding.Touch/MvxTouchBindingBuilder.cs#L45
        registry.RegisterCustomBindingFactory<UIView>("Visible",
                                                    view =>
                                                    new MvxUIViewVisibleTargetBinding(view));

You may find that this conflicts with (and hides) your Visible property - custom bindings are checked before Reflection - so you may need to choose a different property name.
For more on binding to custom properties and more on custom bindings see N=19 and N=28 in http://mvvmcross.blogspot.com
Comment: It seems to have been the Visible property conflicting. I've renamed the property. Thanks.


2 assignment questions in complex analysis which couldn't be discussed

Question: These 2 questions were part of assignment given and couldn't be discussed due to pendamic. So, I am asking them here.

According to Riemann Mapping Theorem, any simply connected region other than $\mathbb{C} $ is conformally equivalent to Unit disc with centre z=0 . Is the result valid for $\mathbb{C} $ ?

I couldn't thinking of reasoning behind it and couldn't find anything related on google and Wikipedia.
2.Let f be homomorphic on a region $\Omega$ with no zeroes. If there is a homomorphic function $h$ such that $h'= f'/f$ show that $f$ has a homomorphic logarithm  on $\Omega$ . Also show that $h$ need not exist and give sufficient condition on $\Omega$ that ensures existence of $h$.

Attempt : I thought of integrating $h'= f'/f$ from which I got $h =\log f(z)$.

But question says that I am wrong as h need not exist. So, kindly tell me what mistake I am making and what is right way to do it.
Comment: 1. No... Liouville theorem forbids the existence of injective holomorphic maps $\mathbb{C} \rightarrow D$. 2. Differentiate $fe^{-h}$ to show that $f$ has a logarithm. But note that $f$ has a logarithm *if such a function $h$ exists*. In certain domains it's not hard to construct functions without a logarithm.
Answer: Hint for first question: Liouville's Theorem applies to $\mathbb C$ but not to regions like the open unit disk.
Logarithms in the complex plane are more complicated than logarithms of posotive numbers. Your argument using $log f$ does not make sense.
Show that derivative of $e^{-h}f$ is $0$ to prove that there is an analytic function $\phi$ such that $e^{\phi}=f$.
For the last part use the fact that the identity function $f$ on  $\mathbb C \setminus \{0\}$ is a counter example.  If $\frac {f'} f (z)=\frac  1 z$ is the derivative of some  analytic function then its integral over the unit circle would be $0$, but the integral is $2\pi i$.
A sufficient condition for existence of $h$ is simply connectedness of the domain .
Comment: Suppose there is  a one-to-one analytic function $f: \mathbb C \to D$ where $D$ is  the open unit disk. Apply Liouville's Theorem.  @Tim
Comment: @Tim $c$ need nit be $1$ but it is non-zero. Any non-zero complex number $c$ can be written as $e^{d}$ for some complex number $d$. So $f=ce^{h}=e^{d+h}$. What is the mistake in the last 3 lines? Please be specific.
Comment: The integral over a  closed contour of the derivative of a holomorphic function is always $0$. $\int_0^{1} h'(\gamma (t))\gamma '(t)dt =h(\gamma (t)|_0^{1}=h(\gamma (1))-h(\gamma (0))=0$. This is just FTC. @Tim
Comment: For 1st your hint was not sufficient for me to get the reason behind the negation. Can you please elaborate answer of 1st question?
Comment: "Show that derivative of $e^{-h} f$ is 0". By proving this I got $e^{-h} f = c $ . But how to prove constant  c is equal to 1? Also, it seems that in last 3 lines of your answer you have done some typo. Can you please check that? Thanks!!
Comment: I am sorry, there is no typo. Can you please tell why integral over unit circle should be zero? Which result you used?
Comment: Thank you very much for your help!!


Should I customize/replace any file?

Question: When downloading Drupal, I get .htaccess files which contain Apache directives, including security-related configuration directives.

Can Drupal 8 work, out of the box, with Nginx?

Where are the Nginx files equivalent to the Apache configuration files? If there isn't any file for Nginx, how can I know how to create them?
Answer: Nginx doesn't support .htaccess files without an extension. You could install that extension, but most don't.
Drupal doesn't include sample rewrite config for Nginx, so there are a few extra steps when setting up the vhost, but nothing major. You'll also need to make sure FPM is set up and configured correctly, but that goes without saying when using PHP with nginx.
There's a pretty sensible looking sample config on the Nginx site itself:
<code>server {
    server_name example.com;
    root /var/www/drupal8; ## <-- Your only path reference.

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    # Very rarely should these ever be accessed outside of your lan
    location ~* \.(txt|log)$ {
        allow 192.168.0.0/16;
        deny all;
    }

    location ~ \..*/.*\.php$ {
        return 403;
    }

    location ~ ^/sites/.*/private/ {
        return 403;
    }

    # Allow "Well-Known URIs" as per RFC 5785
    location ~* ^/.well-known/ {
        allow all;
    }

    # Block access to "hidden" files and directories whose names begin with a
    # period. This includes directories used by version control systems such
    # as Subversion or Git to store control files.
    location ~ (^|/)\. {
        return 403;
    }

    location / {
        # try_files $uri @rewrite; # For Drupal <= 6
        try_files $uri /index.php?$query_string; # For Drupal >= 7
    }

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }

    # Don't allow direct access to PHP files in the vendor directory.
    location ~ /vendor/.*\.php$ {
        deny all;
        return 404;
    }

    # In Drupal 8, we must also match new paths where the '.php' appears in
    # the middle, such as update.php/selection. The rule we use is strict,
    # and only allows this pattern with the update.php front controller.
    # This allows legacy path aliases in the form of
    # blog/index.php/legacy-path to continue to route to Drupal nodes. If
    # you do not have any paths like that, then you might prefer to use a
    # laxer rule, such as:
    #   location ~ \.php(/|$) {
    # The laxer rule will continue to work if Drupal uses this new URL
    # pattern with front controllers other than update.php in a future
    # release.
    location ~ '\.php$|^/update.php' {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        # Security note: If you're running a version of PHP older than the
        # latest 5.3, you should have "cgi.fix_pathinfo = 0;" in php.ini.
        # See http://serverfault.com/q/627903/94922 for details.
        include fastcgi_params;
        # Block httpoxy attacks. See https://httpoxy.org/.
        fastcgi_param HTTP_PROXY "";
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_intercept_errors on;
        # PHP 5 socket location.
        #fastcgi_pass unix:/var/run/php5-fpm.sock;
        # PHP 7 socket location.
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    }

    # Fighting with Styles? This little gem is amazing.
    # location ~ ^/sites/.*/files/imagecache/ { # For Drupal <= 6
    location ~ ^/sites/.*/files/styles/ { # For Drupal >= 7
        try_files $uri @rewrite;
    }

    # Handle private files through Drupal.
    location ~ ^/system/files/ { # For Drupal >= 7
        try_files $uri /index.php?$query_string;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found off;
    }
}
</code>
Comment: Absolutely, couldn't agree more. But I'm wondering if the 2 questions haven't been answered properly what sort of clarification you need? I'm happy to elaborate on something if there's confusion/ambiguity in the answer (not interested in the bounty, have far too many unicorn points as it is)
Comment: nginx doesn't support any file-based overrides natively, those directives go in the vhost. Any per-folder overrides also go in the vhost
Comment: I'm not sure what you're hoping the bounty will achieve? There isn't any more information to give you based on your question, it's a waste. If you don't understand what you're looking at with regards to the sample vhost in the answer, no amount of Drupal knowledge is going to help, that's all nginx config which like everything else, you need to learn separately
Answer: Drupal works with nginx, but it takes a great deal of research to get it right (and keep it right).  If you have the time and resources to do that well many people are very happy with the performance of their sites once up and running.
Because there is no official community supported documentation covering how to setup nginx, you don't get the reassurance that the security team has reviewed the setup (or anyone else really). If you search around you'll find many partial answers, but I've found that all are incomplete in some way and most contain security errors. As Pierre notes in the comment below there is a quiet group that has worked on this for D6 and D7 but not yet for D8.
One of the most common basic issues is that many are focused on getting Drupal to do all the things it is supposed to do (like generate images) but don't prevent things that are supposed to be blocked (like directly accessing .twig or .inc files). The more complex security issues – like recent changes to headers to mitigate certain types of attacks – are totally absent from any examples I've seen for nginx.
Also, if you run many sites you are likely to have times when you need to change the configuration of all your sites, which means an update to all vhosts. With Apache those changes are often just a matter of pushing out the new code base since the .htaccess files update Apache's behavior.
Comment: In addition, there is a community group for nginx, but it's rather quite.
https://github.com/perusio/drupal-with-nginx seems to be a good base (but complexe) nginx config for Drupal 7 and 6, but there is no version for Drupal 8.
Comment: If you look at the current .htaccess file you'll see near the end headers with comments that say things like  # Disable content sniffing, since it's an attack vector.  Those are fairly recent additions and not things I've seen accounted for in sample nginx settings (there are probably places that have them, just not where I've looked). The real issue is that you have to watch for changes to .htaccess with every update, and translate them to nginx.

Should I customize/replace any file?


Show $\mathcal{A}$ is $\sigma$-algebra for $X$ if and only if a statement over increasing sequence holds .

Question: Let $\mathcal{A}$ be an algebra for $X \neq \emptyset$. Show $\mathcal{A}$ is $\sigma$-algebra for $X$ if and only if the following statement holds:
$E_{i} \in \mathcal{A}$ and $E_{i} \subset E_{i+1}$ with $i \in \mathbb{N}$, then $\bigcup_{i=1}^{\infty} E_{i} \in \mathcal{A}$.
I was trying to prove this as follows:
$\Rightarrow$ If $\mathcal{A}$ is $\sigma$ algebra, then  by definition of $\sigma$ algebra we have that for any sequence $\lbrace  E_{i}\rbrace_{i \in \mathbb{N}}$ where $E_{i} \in \mathcal{A}$ for every $i \in \mathbb{N}$, then $\bigcup_{i=1}^{\infty} E_{i} \in  \mathcal{A}$ particulary if the sequence is increasing as the statement holds. So we are done.
$\Leftarrow$ Having the statement as hypothesis I want to prove that $\mathcal{A}$ is a $\sigma$ algebra. As $\mathcal{A}$ is an algebra for $X$ we already have that $X \in \mathcal{A}$ and $\mathcal{A}$ is closed under compliments. So, I only need to prove  $\lbrace  E_{i}\rbrace_{i \in \mathbb{N}}$ where $E_{i} \in \mathcal{A}$ is closed under enumerable union.
Case 1-  If the sequence is increasing then $\lbrace  E_{i}\rbrace_{i \in \mathbb{N}}$ where $E_{i} \in \mathcal{A}$ is closed under enumerable union as we are supposing the statement.
Case 2.- If the sequence is increasing then $\lbrace  E_{i}\rbrace_{i \in \mathbb{N}}$ where $E_{i} \in \mathcal{A}$ is decreasing.
Case 3.- If the sequence is is such $\lbrace  E_{i}\rbrace_{i \in \mathbb{N}}$ where $E_{i} \in \mathcal{A}$ is such is neither increasing or decreasing.
If my idea of proving this by cases how can I end up this proof as Im pretty up out of ideas to prove case 2 and case 3.
Other ways to prove this are welcome. Thanks
Comment: Having any sequence $\{E_i\}_{i \in \mathbb N}$, we can form a sequence $\{F_i\}_{i \in \mathbb N}$, where $F_i = \bigcup_{j=1}^i E_i$. Note that $\bigcup_{i=1}^\infty F_i = \bigcup_{i=1}^\infty E_i$, and $F_i \subset F_{i+1}$ for every $i \in \mathbb N$
Comment: I don't understand case 2, but "=>" is correct and as you noticed all you need to do for "<=" is to show that for any sequence $\{E_i\}_{i \in \mathbb N}$ we have $\bigcup E_i \in \mathcal A$, so everything seems correct to me.
Comment: Nice hint! Let me try your idea a few minutes and see If can end up the proof. Any gap in the other implication of my proof? @DominikKutek
Comment: Thanks!! The equality of unions you mentioned can be proved  straightforward  by two element contentions without problem.
Comment: You're welcome!
Answer: If $E_n, n \in \omega$ is any sequence in the algebra $\mathcal{A}$, define $$E'_n = \bigcup_{i \le n} E_i \in \mathcal{A}$$
as algebras are closed under finite unions. Also the sequence $E'_n$ is increasing in $n$ by definition, and it's easy to check that
$$\bigcup_n E_n = \bigcup_n E'_n \in \mathcal{A}$$
the last holding by the assumption on the increasing sequences of sets.  No need for case distinctions.


grpc number of active clients/channels

Question: I am implementing a simple grpc service discovery. One of the thing I would like to do is to keep track of how many clients are currently to the service and the service will report that to the service registry. Does grpc server api provide such information? I have come across a somewhat similar question  here. https://github.com/grpc/grpc-java/issues/779.
In point 1 of the response, it was mentioned to keep track of all incoming rpc via streaming api. How exactly do I do that?
Here's an example rpc  I want to implement, RegisterInstance will act as a "pinger" and server will use etcd's ttl to check liveness of service. And the registry will use the connected_client to determine which service ip to send back to client when there are more than one of the same service type registered on the registry. My issue is how can I obtain connected_clients from the service side?
syntax = "proto3";

package registry_grpc;

service ServiceRegistry{
    rpc GetInstance(ServiceRequest) returns(ServiceInstance) {}
    rpc RegisterInstance(ServiceInstance) returns(ServiceInstance) {}
}

message ServiceRequest{
    string service_type = 1;
}

message ServiceInstance{
    int32 id = 1;
    int32 connected_clients = 2;
    string service_type = 3;
    string host_address = 4;
    int32 port = 5;
}

edit
I have found that it's possible to intercept every incoming rpc calls. This way I can report for example number of incoming connections in the last second. I guess it can serve as a proxy for workload.
Answer: ServerBuilder has a addTransportFilter(), which allows you to install a ServerTransportFilter, where you get notifications when a connection (i.e. transport) is created and terminated.
Comment: what is the availability of this feature across all languages? In any case, it seems the way to do it is not the same for different languages. Does it give notification per connection or per rpc call? For example, in python, `add_generic_rpc_handlers` and in golang `UnaryInterceptor` can give notification per rpc call but not per connection.
Comment: Not sure about other languages. Java's `ServerTransportFilter` is notified per connection.

grpc number of active clients/channels


Using Panels and Views to override taxonomy listing - which argument to use?

Question: I'm using Panels to override the taxonomy display at taxonomy/term. I just enabled the term_view page that comes with Panels and it works great.
So going to mysite/colours/blue shows the Panels page no problem.
Now I want to add a View to the panel that lists the returned nodes. I create the view, and add a relationship 'Content: taxonomy terms on node' (selecting the required vocabulary 'colours').
The I add an argument (contextual filter) on 'Taxonomy term: name'. This works great in the view preview if I enter the value 'blue' but not if I enter 'colours/blue' (no results). And it doesn't work in the panel because 'colours/blue' are the arguments being passed to it.
How do I get the view argument to work with this URL?
Comment: +1 This will save me a lot of work by just supplying an argument for different output based on the same View. Thanks.
Answer: In the Views UI, each Content Pane has "argument settings". In there you have, at least, two options.

The easiest to configure, is "From panel argument", and its option in this case, "Second argument". This works fine in your situation.
The most flexible, that I always use, require more understanding of the Ctools context.

The argument setting then is "From context" and in this case "Taxonomy Term" -> "Name".
Save the View, go into the Panels UI, add the View Pane, not just a View.
Assuming your Panel Page now has a taxonomy term, which is always the case on the /taxonomy/term page, you will get a dropdown, most of the time with just one option, that lists the available terms that you pass on to the View.

If you for example had a path like /color/red/blue, because you wanted two terms, the second version will allow the re-use of the same View on the same page, with different content.
Comment: +1 This will save me a lot of work by just supplying an argument for different output based on the same View. Thanks.
Comment: @Letharion what do you exactly mean 'From panel argument'? The terminology is not really straightforward for me(my bad I know), but could you please be more specific? :)
Comment: "From panel argument" must be read in the context of the sentence before point 1. Does that make sense? Otherwise I don't know what you're asking.


Two different sites, two installations, no database or core sharing

Question: I've finished configuring a Drupal site using localhost (Mamp) but I have to wait some weeks until it gets uploaded to external host.
Now in the meantime I'd like to start developing another site that has nothing to do with the first one (different database, users, modules, etc). That is: I'd like to 'park' the old site and start creating the new one (new Drupal 7 installation) without affecting the first one.
I'm using Mamp 184.108.40.206 and the server route is default (Mamp--- htdocs)
Any hint on what to begin with?
Thank you
Comment: Strikes me this is more of a MAMP question than a Drupal question? In any event surely you can just create a tarball of your site's root directory ready for uploading and move it somewhere suitable. Then start your new site.
Answer:
put your drupal sites in separate subdirectories of htdocs, e.g .../htdocs/site1, ...htdocs/site2
access your sites using the mamp localhost url, e.g. http://localhost/site1

If you know how, you can also create virtualhosts in /Applications/MAMP/conf/apache/httpd.conf and edit /etc/hosts on your mac, so that you can access the sites with whichever url you choose, such as:
http://site1.local

Databases: just upload your databases using MAMP's phpmyadmin, and edit your sites' settings.php to use the respective databases.
Comment: Thank you, that worked out perfectly fine! Only I can´t access the Admin menu, but that seems to be a Chrome issue: Firefox runs it OK. Thanks again


Kolmogorov extension theorem for measures on the space of continuous functions

Question: In a text I am reading occurs the following:
One has a family of probability measures $(P_T)_{T\geq 0}$ such that $P_T$ is a measure on the measurable space $(C([0,T],\Bbb R^d), \mathcal B (C([0,T],\Bbb R^d)) )$.
It is stated that consistency of the family $(P_T)_{T\geq 0}$ is yielding a measure $P$ on $C([0,\infty),\Bbb R^d)$.

I think consistency means if we take $\pi^S_T: C([0,S],\Bbb R^d) \to C([0,T],\Bbb R^d)$,$f\mapsto f\vert_{[0,T]}$, then for every $S\geq T$ we have $P_T = P_S \circ (\pi_T^S)^{-1}$.
P seems to satisfy $P_T = P\circ(\pi_T)^{-1}$, where $\pi_T: C([0,\infty),\Bbb R^d) \to C([0,T],\Bbb R^d)$,$f\mapsto f\vert_{[0,T]}$

How is this done? My first thought was to apply the Kolmogorov extension theorem but I did not come far enough with it.
Answer: I apologize for this being so late, but I have a proposal for a solution.
I believe you can implement an outer measure construction of the desired $\mathrm P: \mathcal B(C([0,\infty), \mathbb R^d)) \rightarrow [0,1]$.
Define a premeasure $\mathrm P_\infty$ on the ring generated by the closed balls in $C([0,\infty), \mathbb R^d)$, induced by the following definition on said balls.
$$\mathrm P_\infty\big( C_\delta(x) \big) = \lim_{n\rightarrow\infty} \mathrm P_n\big( C_\delta(\pi_n(x)) \big)$$
where $\pi_T: C([0,\infty),\mathbb R^d) \rightarrow C([0,T], \mathbb R^d)$ is the restriction map $f \mapsto f|_{[0,T]}$ for each $T > 0$ and  $C_\delta(y)$ is the closed ball of radius $\delta$ around $y$ in the relevant topological space.

This intuition comes from the fact that, for any $x \in C([0,\infty),\mathbb R^d)$ and $\delta > 0$,
  $$ C_\delta(x) = \bigcap_{n=1}^\infty \pi_n^{-1}(C_\delta(\pi_n(x))), $$
  If the measure $\mathrm P$ in fact existed, the decreasing nature of the sets $\pi_n^{-1}(C_\delta(\pi_n(x)))$ would produce
  $$ \mathrm P\big( C_\delta(x) \big) = \lim_{n\rightarrow\infty} \mathrm P\big( \pi_n^{-1}(C_\delta(\pi_n(x)) \big) $$

The properties of the premeasure like $\sigma$-additivity are passed through the limit, as eventually inherited by the measures $\mathrm P_n$.
The induced outer measure of $\mathrm P_\infty$ can then be restricted to $\mathcal B(C([0,\infty), \mathbb R^d))$, and I believe this will be your desired measure $\mathrm P$.
In proving the restriction is a measure, I believe you will need your consistency property.


Twilio message sending with proxy server

Question: Following piece of code works without proxy
Message.creator(new PhoneNumber(number), messagingServiceId, smsMessage).create();
But I am unable to send the message when proxy is enabled.
Is there any specification from Twilio to send messages using proxy authentication?
Comment: Can you provide a bit of more code context please?
Answer: Twilio developer evangelist here.
I'm afraid I'm not a Java developer really, but I can point you in the right direction.
When you initialise Twilio you can also set a custom restClient. You can build a new restClient and pass a custom httpClient. By default, this is an instance of the NetworkHttpClient but you could extend that class to include your proxy credentials.
Underneath it all is the Apache HTTP Components client. In the docs there is an example of a client with a proxy which I suggest you take a look at.
Sorry I couldn't be more specific, but I hope this helps.
Comment: Thanks for quick response. Now I am able to send the message with proxy enabled
Comment: Fantastic! Since this helped, do you mind marking the answer as the solution. It will help others if they have the same trouble.


How to get a virtio disk to show up - kernel config

Question: I'm trying to set up a Gentoo guest on a virtio drive. When I boot the VM using an ubuntu livecd, I do have a /dev/vda on which I installed the system using LVM.
I compiled a 4.9.16-gentoo kernel enabling basically everything with virtio in the name that I could find, and then generated an initrd using dracut (since my root is on LVM), but when I boot I get dropped in the dracut shell and I can see there isn't any /dev/vda existing.
Since it works fine on the livecd, I must be missing something in my kernel config, any ideas ?
I googled a bunch but it seems hard to find a real list of what you need to get virtio to work, at least not up to date.
Here is the kernel config I'm using now, probably too much stuff enabled but I'm just trying to figure out what I'm missing https://datas.ulrar.net/config_virtio
Thanks
Answer: Figured it out, apparently virtio legacy is required. I've read that the "modern" implementation isn't ready and therefore isn't enabled by default in qemu, but Linux > 4 still renamed the actual stable implementation to legacy.
Sounds a bit silly, but enabled legacy virtio pci in the kernel works ..


Transposing when finding hypotenuse

Question: Background: I have just about high school knowledge of math, I am sorry if this is a stupid question.
In school, we learned that when transposing, this:

y = x * 3

would become

x = y / 3

I was reading up on trigonometry, and as I was reading the following:

If we look at the general definition -

we see that there are three variables: the measure of the angle x, and
  the lengths of the two sides (Opposite and Hypotenuse). So if we have
  any two of them, we can find the third.
In the figure above, click 'reset'. Imagine we didn't know the length
  of the hypotenuse H. We know that the sine of A (60°) is the opposite
  side (26) divided by H.

From our calculator we find that sin60 is 0.866, so we can write

Transposing:

which comes out to 30.02

(From http://www.mathopenref.com/sine.html)
As per the rules of transposition (that I probably got wrong), isn't it supposed to read

H = 26 * 0.866

What am I missing?
Answer: We first divide both sides by $H$: $$0.866=\frac{26}{H},$$
then we divide by $0,886$ on both sides: $$0.886H=26,$$
We receive this result: $$H=\frac{26}{0.866}.$$
Thus, the answer is $30.06.$
Answer: Transpose means to isolate the variable. In the problem given you are trying to isolate the $H$ variable. Using algebra:
our problem:
$$0.866 = \frac{26}H  $$
$$H\cdot 0.866 = \frac{26}H \cdot H$$
$$0.866H = 26$$
$$\frac{0.866H}{0.866} = \frac{26}{0.866}$$
$H = 30.02$ is the correct answer not $30.06$.
Multiplying both sides by $H$ cancels the $H$ in the quotient.
Dividing both sides by the coefficient of $H$ cancels the $0.866$ in the product.

Transposing when finding hypotenuse


Is this way safe to bootstrap Drupal from an external PHP script?

Question: I want to bootstrap Drupal from an external PHP file located in Drupal's root directory. The following code will do the job.
error_reporting(E_ALL);
ini_set("display_errors", 1);
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$html_1='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>HOW TO BOOTSTRAP DRUPAL FROM AN EXTERNAL PHP SCRIPT?</title>

';

$html_2 ='
';

global $user;

if ((user_is_logged_in()) && ($user->uid == 1)) {
    //only if this is the admin, do stuff. for example:
    print $html_1;

    print  t("
This User
\n") ;

    print "
Logged In
\n";
    print "
User ID: ".$user->uid."
\n";

    print $html_2;

} else {
    drupal_access_denied();
    module_invoke_all('exit');
    drupal_exit();
}

Let's say I want to create a script that lets the admin export nodes of a certain content type. And let's assume I don't want to write a custom module or use views. I know that my way of doing that is the wrong way. I'm trying this in order to learn bootstraping Drupal from an external php script. If I put my script in Drupal's root directory, and I don't change anything in the .htaccess file, will the script cause any security issue?
So I want to know if this example safe, i.e. if the code doesn't have any security issues. So my question is about the security of the process.
Comment: If you have physical access to disk where Drupal is, talking about security is void. Your script will do what you write, no limits, and Drupal will not stop it. If you read, you read. If you write, you write. Whatever, wherever you want.
Comment: Can this script be called from other server?
Comment: It depends on where you put it and how you configure your webserver. Neither is it a Drupal question.
Comment: [Views data export](https://www.drupal.org/project/views_data_export)
Comment: @Shad81 If you've security question, you may try ask at: http://security.stackexchange.com/, but you need to specify what exactly concerns you have as it's a bit too broad. No system is secured in 100% and you know about security implications after the fact. As far as you're doing everything the same as Drupal does, you're less affected. Just replicate how it's done in `index.php` and you should be safe.
Answer: Why not to use drush to handle Drupal boostrap as demonstrated below?
So the file can contain a minimum content like (no need to call Drupal bootstrap):
<?php
drupal_set_message('Foo');

then run it as:
$ drush scr foo.php
Foo

Comment: I'm doing this as a learning task. The admin may run the PHP script via his browser.


Adding a space between string words

Question:
Write a function named string_processing that takes a list of
strings as input and returns an all-lowercase string with no
punctuation. There should be a space between each word. You do not
have to check for edge cases.

Here is my code:
import string

def string_processing(string_list):
    str1 = ""
    for word in string_list:
        str1 += ''.join(x for x in word if x not in string.punctuation)
    return str1

string_processing(['hello,', 'world!'])
string_processing(['test...', 'me....', 'please'])

My output:
'helloworld'
'testmeplease'

Expected output:
'hello world'
'test me please'

How to add a space in just between words?
Comment: Just put space in your code in that line `str1 += ' ' + ''.join(x for x in word if x not in string.punctuation)`
Comment: @YasserKhalil This will add an unwanted space at the start of the string
Comment: Do not post you assignments verbating expecting people to do your homework. Instead, state what you tried and where you're stuck.
Answer: You just need to keep all the words separate and then join them later with a space between them:
import string
def string_processing(string_list):
    ret = []
    for word in string_list:
        ret.append(''.join(x for x in word if x not in string.punctuation))
    return ' '.join(ret)

print(string_processing(['hello,', 'world!']))
print(string_processing(['test...', 'me....', 'please']))

Output:
hello world
test me please

Answer: Try:
import string
def string_processing(string_list):
    str1 = ""
    for word in string_list:
        st = ''.join(x for x in word if x not in string.punctuation)
        str1 += f"{st} "  #<-------- here

    return str1.rstrip() #<------- here

string_processing(['hello,', 'world!'])
string_processing(['test...', 'me....', 'please'])

using regex:
import re
li = ['hello...,', 'world!']
st = " ".join(re.compile('\w+').findall("".join(li)))

Answer: Using regex, remove every non-letter and then join with a space:
import re

def string_processing(string_list):
    return ' '.join(re.sub(r'[^a-zA-Z]', '', word) for word in string_list)

print(string_processing(['hello,', 'world!']))
print(string_processing(['test...', 'me....', 'please']))

Gives:
hello world
test me please

Comment: I didn't think of removing non letter :-? Nice one +1
Answer: We can use the re library to process the words and add a space between them
import re
string = 'HelloWorld'
print(re.sub('([A-Z])', r' \1', string))

Output:
Hello World

Comment: This doesn't answer the original question
Answer: The following code could help.
import string
def string_processing(string_list):

    for i,word in enumerate(string_list):
        string_list[i] = word.translate(str.maketrans('', '', string.punctuation)).lower()

    str1 = " ".join(string_list)

    return str1

string_processing(['hello,', 'world!'])
string_processing(['test...', 'me....', 'please'])

Adding a space between string words


SVM - running time for detecting if data is linearly separable?

Question: If my understanding is correct, one way to check if a set of $m$ data points is linearly separable is to use support vector machines to find a maximum margin hyperlane for separating the data; the data is linearly separable if and only if such a hyperplane exists.
If the data consists of $m$ pairs $(x_1, y_1), \ldots, (x_m,y_m)$, with $x_i \in \{0,1\}^n$ and $y_i \in \{0,1\}$, do we know what the worst case running time is for finding whether or not a maximum margin hyperlane exists?
Comment: [Linear SVM can be trained in sublinear time](http://papers.nips.cc/paper/4359-beating-sgd-learning-svms-in-sublinear-time.pdf). The complexity of exact kernel SVM ranges from $O(n^2)$ to $O(n^3)$, depending on the strength of regularization, where $n$ is the size of your training set.
Answer: Most of the work on SVM algorithms focuses on the soft-margin case and so isn't really applicable here.$\newcommand\R{\mathbb R}$
But the question of finding the existence of a linear separator can be solved instead as a linear program:
Let $X_+$ be the matrix whose rows are the positive instances (the $x_i$ with $y_i = 1$), and $X_-$ the matrix whose rows are the negatives.
Then our question is:
is there a $\beta \in \R^n$ and $b \in \R$ such that
$X_+ \beta > b$ and $X_- \beta < b$?
This is a linear feasibility problem in $n+1$ dimensions with $m$ linear constraints. Since your $X$ are binary, the LP can then be represented in $O(m n)$ bits; as an upper bound, Karmarkar's algorithm then runs in
$$O(m^2 n^{5.5} \log(m n) \log(\log(m n)))$$
time.
Better bounds are certainly possible depending on the setting. For example, if the dimension $n$ is low, Megiddo (1984) gives an algorithm that takes fewer than $2^{2^{n+3}} m$ steps, or another which takes fewer than $\frac{2^{(n+1)^2}}{\prod_{k=1}^{n-1} k!} m (\log m)^{(n+1)^2}$.
Comment: Class answer. +1


Using Apache Camel to transfer S3 files based on S3 event notifications

Question: I have an application (running on an EC2 instance) that parses new log files arriving in an S3 bucket. I have setup S3 notifications, on this bucket, to put a message in SQS queue on PUT request. The aim is to transfer a newly arrived log file from S3 to the EC2 instance.
I think Apache Camel would be an ideal candidate for this problem. I have following questions/observations on the solution and would greatly appreciate some feedback on that:

We can have a Camel route to read messages from SQS and then extract the object key from the JSON message. Is it possible to use this object key in another Camel route (using S3 component)  that copies this object from S3 to local FS? From the looks of it seems that the Camel S3 component is only capable of processing new objects in a bucket since it takes only bucket name in the URI. Thus it might not be possible to copy a specific key from a S3 bucket. Also I am not sure if its possible to have dynamic URIs in Camel since object name would be different each time.
If Camel S3 component is indeed capable of processing new objects arriving in a S3 bucket then we dont need S3 notifications altogether. But this has a problem (since its stateless) that if for some reason this application goes down then it will miss the objects that arrived during downtime.
Another possibility is to use Camel for reading messages from SQS, process those messages and copy object from S3 using a normal Java class. But this kind of doesnt fully utilize the strengths of Apache Camel.
Answer: Having a SNS to decouple the file processing and file transfer is good. But do you really need this? It will add the complexity of your application. If you just want to processing the incoming files to the S3 bucket without miss, the simplest way is to create a bucket say "incoming" and another call "processed". Each time you application can scan the incoming bucket and process it, after done put the file to the processed bucket.
One thing you need to take care of is to flag the file under processing to avoid conflict. You can put special suffix to it.
Also AWS provide third way to do "Event Notifications" call " Lambda function". You can also take a look of that. It can enable some simple handler which do not need writing extra application yourself.


Using Drupal as client of a web service

Question: I need to use Drupal as client for a web service, for extracting data and showing it in a view or as content. (The format use is JSON or REST.)
I use a Web Service Client module in Drupal 7, and the Services module in Drupal 6, but I don't know how to use them. I read the documentation but I don't get any result.
Can anyone help on this issue, or tell me how to use these modules? Is there any other module for this purpose?

A possible solution: I find a module called XML VIEWS but this module convert only XML files.
Now, I programing in this module for convert the JSON to XML.
In this files: xml_views_plugin_query_xml.inc
In this function: Execute
Anyone have another solution?
Comment: There were some good presentations on this at austin (11)drupalcamp: http://vimeo.com/33785095 http://vimeo.com/33091201
Answer: Drupal has specific functions that can help with communicating with a web service, and handling JSON input.
Drupal 7 has the following functions:

drupal_http_request() is the function to make a HTTP request to a remote site, and it handles GET, POST, PUT or any other HTTP requests; it also handles redirects.
drupal_http_build_query() transform an array in an rawurlencode()-d string.
drupal_json_decode() decodes a JSON string in PHP code.
drupal_json_encode() encode a PHP variable into a string that is handled by JSON.

With those functions you can write your own custom module to make requests to a site implementing a web service.
If there are some restrictions about the number of requests that can be done to the web server, you can use the Drupal functions to cache the result obtained from the web server:

cache_get(), to get the data saved in the cache
cache_set(), to save the data in the cache

To notice that Drupal supports more than one cache bin, and modules can use their own cache bins, when necessary.
Drupal supports also cache items that are automatically removed at the successive cache swipe (see the description for the CACHE_TEMPORARY constant). Implementing hook_flush_caches(), the modules allow to the administrator users to clean the cache used by the module when the "Clear" button on the "Performance" page is clicked, or any times a module calls drupal_flush_all_caches().
In Drupal 7, cache data for frequently used data are associated with a static variable handled with drupal_static(). When the data is really frequently used when outputting the same page, code similar to the following one is used:
  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['implementations'] = &drupal_static(__FUNCTION__);
  }
  $implementations = &$drupal_static_fast['implementations'];

  // …

  // Fetch implementations from cache.
  if (empty($implementations)) {
    $implementations = cache_get('module_implements', 'cache_bootstrap');
    if ($implementations === FALSE) {
      $implementations = array();
    }
    else {
      $implementations = $implementations->data;
    }
  }

The code is part of module_implements().
Comment: Did you try https://www.drupal.org/project/wsclient? I'm interested if this module helps with ws client implementation
Answer: Every time I have needed to consume a webservice, I have just created a PHP class based around file_get_contents or curl in conjunction with json_decode or simplexml_load_string.
The class then gets accessed in a module via a getter function that uses drupal_static, or the $static pattern for Drupal 6.
I then use this inside my custom blocks, menu callbacks, etc, as needed.
EDIT
@kiamlaluno's answer is correct and demonstrates a way to do this all through the Drupal API.  The primary reason I don't do this is that I prefer to abstract the webservice class in a way that allows me to use it in other applications.  There are advantages and disadvantages to this, so weigh your options.
Comment: Does that mean that I schedule to consume data from the webservice? Is there a solution as sitebuilder with modules?
Comment: I'm sorry, but I don't quite understand what you are trying to do.
Comment: In other words, i search a solution that doesn't involve a programing. A solution like a site builder with modules. But, if in my case involve programing i need the steps for do it.
Comment: Could you provide an example of abstract webservice class?

Using Drupal as client of a web service


Integral domain of a commutative ring

Question: Let $A$ be a commutative ring over an integral domain. Let $a, b \in A$ where $(a) = (b)$. Show that there exists invertible elements $x$ and $y$ in $A$ such that $a = bx$ and $b = ay$. Also show that $y$ is then the inverse of $x$ and that these elements $x$ and $y$ are unique (for $a$ and $b$ given).
I don't see how I can show the existence of invertible elements, $x$ and $y$. Also for the second proof if I substitute the two equations
$a = bx = ayx$ because of the integral domain of $A$ we have $1 = xy$ so then  $y$ is the inverse of $x$. I don't see after that how I can show that $x$ and $y$ are unique. If anyone as any idea let me know.
Comment: In an integral domain $R$ with fraction field $K$ we have a group homomorphism $K^* \to I(R), a\to aR$ (where $aR$ is a sub-$R$-module of $K$) whose kernel is $R^\times$. Thus $(a)=(b)$ iff $a=ub$ with $u\in R^\times$.
Comment: You already showed that $xy = 1$ which implies that $x$ and $y$ are units. For uniqueness, you can divide by $b$ of $a = bx = bx'$. I suppose that $a \neq 0$.
Answer: Not exactly sure what the semantics of "commutative ring over an integral domain" are all about, but if $A$ is an integral domain, and assuming $(a)$ denotes the principal ideal generated by $a$, that is,
$(a) = aA, \tag 1$
then since $A$ has a unit $1_A$,
$a = a1_A \in aA = (a), \tag 2$
and likewise
$b \in (b); \tag{2.5}$
thus from
$(a) = (b) \tag 3$
we infer that
$a \in (b), \; b \in (a), \tag 4$
and hence
$\exists x, y: a = bx, \; b = ay, \tag 5$
leading to
$a = (ay)x = a(xy), \tag 6$
or
$a(1_A - xy) = a - a(xy) = a - a = 0; \tag 6$
if we now hypothesize that
$a \ne 0, \tag 7$
the assumption that $A$ is an integral domain forces
$xy = 1_A, \tag 8$
that is, both $x$ and $y$ are invertible and
$y = x^{-1}, \; x = y{-1}. \tag 9$
The uniqueness of $x$ is seen via
$bx = a = bx' \Longrightarrow b(x - x') = 0 \Longrightarrow x - x' = 0 \Longrightarrow x = x', \tag{10}$
provided of course
$b \ne 0; \tag{11}$
thus $x$ is unique; a similar argument applies to $y$.
We observe that (7) and (11) are equivalent since both imply (8)-(9).  In the event that
$a = 0, \tag{12}$
we also have
$b = 0, \tag{13}$
since we have shown that
$a \ne 0 \Longleftrightarrow b \ne 0; \tag{14}$
this also follows from
$a = 0 \Longleftrightarrow (a) = aA = \{0\} \Longleftrightarrow bA = (b) = (a) = \{0\} \Longleftrightarrow b = 0. \tag{15}$
Comment: @ola:  it is necessary to cover the case $a = b = 0$; the way I wrote the proof assumed $a \ne 0$ at (7), so for the case of completeness I wanted to cover $a = b = 0$.  I admit the $a = b = 0$ case is a pretty simple addition.  Does this aswer you query?  Cheers!

Integral domain of a commutative ring


How to run a php file from bash script?

Question: I am working in a Windows machine. I need to run a script that will execute a php file. When I run where php to find my php executable location I get the following:
c:\xampp\php\phpe.exe
After that I tried something like this:
#!/bin/bash
#!/c:/xampp/php c:/xampp/htdocs/Bash/testingphp.php

I don't get any error, but I don't know if the script is doing something. Just for reference I am using cygwing to run the scripts. How do I know if my script is really working??
Thank you in advanced
Comment: Why are you using terms like `bash` and `cron` if you're using Windows? Is cygwin installed, or do you simply mean "scheduled tasks" and "batch"?
Comment: The binary might very well be `c:\xampp\php.exe` but that doesn't translate to a cygwin path of `/c:/xampp/php` (or `php.exe`). What path do you need to type at the cygwin prompt to run the php binary?
Comment: @EtanReisner I would say something like this: /cygdrive/c/xampp/php/php.exe
Comment: Then that's what you need to use in the shell script as well.
Comment: The part seems to work: /cygdrive/c/xampp/php/php.exe testing.php I didn't specify the path for my file because its located in the same folder as the script. @EtanReisner I get this Could not open input file: testing.php
Comment: you don't really need cron as long as your script is running you can do `/cygdrive/c/xampp/php/php.exe &
while sleep 60; do
 _cron_tasks_here_;
done`
Comment: @h2ooooooo I have cygwin, after my script is working I need to use cron to execute every so minutes
Comment: That second line is a comment. It is doing nothing. Get rid of the leading `#!` on the second line. That only has a meaning on the first line of a script. That being said why are you not just using a Windows scheduled task for this?
Comment: @EtanReisner I have to use windows scheduled task and cron as well.Once I remove the #! I get the following error /c:/xampp/php: No such file or directory. I check it and that directory is where php.exe is located
Answer: As stated by @Etan, your second line is a comment, but your paths are also incorrect. You need to use /cygdrive/c/, not /c:/. Here is the corrected script:
#!/bin/bash
/cygdrive/c/xampp/php /cygdrive/c/xampp/htdocs/Bash/testingphp.php

How to run a php file from bash script?


How to make expandable text on clicking more button in views?

Question: I have created a views with trimmed fields and displaying more button to show the full content.I want to do something like collapse text ie.,when i click on more button it has to expand and show the full text.Any help will be much appreciated on how to do this.Thanks in advance.
Answer: This will require some custom theming to accomplish:

In your view, don't trim the field, just show it all for now. This will mean if a user has JavaScript disabled they will still have access the all the content.
In order to enhance the interface as you've described for users with JavaScript enabled, you should take a look at this tutorial.
You will have to tweak things to get it working with your theme. If you're unsure about adding Javascript to a theme, check this out.
Answer: You could use CSS :active.
Something like this:
Styles:
.more-link p {display: none;}
.more-link:active p {display: block;}

HTML:

Hidden text

It is possible to use CSS transition to show text block smoothly.
Answer: There's a contributed module that does this, Readmore.  The other answers explain how to set this up yourself, but that's no longer necessary.
I've adding feature request to have this functionality added to Drupal Core. See Allow for expandable text with "Read more/less" links in Default field formatter for details.  Patches welcome!


Probability of X>Y based on single observation?

Question: I'm struggling a bit with a problem -more specifically on how to tackle the problem- and came for help or pointers. I'm an engineer with very little education in statistics but I'm really motivated in getting a better understanding of the resolution of such problems.
I have two independent players playing darts and I would like to express the probability that player 1 is better than player 2 based on a single measurement which consists of the sum of N throws of each player. For the sake of simplicity, I assumed that the outcome of a measurement depends only on one single parameter and I can already simulate without problem the density function of a N-throws based on that parameter. Intuitively, I already see that players having the same parameter value can generate measurements that are, on average, 50% better than the other player (one wins a match, then the other wins it etc.).
What I would like to do now is to answer the question about the probability of player 1 being better than player 2, or conversely, the probability that they are equally good based on a single match result.
How should I approach this problem ? I'm not necessarily looking for an analytical form as long as I can find a method to populate a table giving confidence in the assertion based on the two scores that can only take bounded values between 0 and 10*N.
Answer: A simple way to proceed is to do an hypothesis sign-test that is a binomial test. $H_0: p=0.5$ against $H_1: p>0.5$
You reject $H_0$ if your fixed p-value is less than a fixed %
For example, if you have $N=10$ throwns with the following winners
$$\{x,x,y,x,x,y,x,x,x,x\}$$
You set 1 if x and 0 if Y thus your result is 8 and being the probability that a $Bin(10;0,5)\geq 8=0.0547$ you can reject the hypothesis that $X\leq Y$ at any significance level greater than 5.47%


How do I read this ANSWER line in an nslookup

Question: I performed an SOA nslookup on a domain and I am little confused by the exact meaning of the output (see below...names have been changed to protect the innocent):
;; QUESTION SECTION:
;MYDOMAIN.COM.  IN SRV

;; AUTHORITY SECTION:
MYDOMAIN.COM. 10800 IN SOA dns23429.dizinc.COM. somename.hotmail.COM. 2010072201 86400 7200 3600000 86400

So I understand that "dns23429.dizinc.com" is the authoritative DNS server but what is the meaning of the entry after that ("somename.hotmail.COM")?  Is that another authoritative DNS server?  I didn't think you could have two authoritative servers.  In addition, why would it be on a machine at in the "hotmail.com" domain?  That seems kind of strange doesn't it?
Answer: The SOA start of authority record has several values.
From rfc1035
MNAME RNAME SERIAL REFRESH RETRY EXPIRE MINIMUM

MNAME  The <domain-name> of the name server that was the
  original or primary source of data for this zone.

RNAME  A <domain-name> which specifies the mailbox of the
  person responsible for this zone.

SERIAL  The unsigned 32 bit version number of the original copy
  of the zone. Zone transfers preserve this value. This
  value wraps and should be compared using sequence space
  arithmetic.

REFRESH  A 32 bit time interval before the zone should be
  refreshed.

RETRY  A 32 bit time interval that should elapse before a
  failed refresh should be retried.

EXPIRE  A 32 bit time value that specifies the upper limit on
  the time interval that can elapse before the zone is no
  longer authoritative.

So for that record.
MYDOMAIN.COM. 10800 IN SOA dns23429.dizinc.COM. somename.hotmail.COM. 2010072201 86400 7200 3600000 86400

MYDOMAIN.COM. - the name that the rest of the details apply to.
10800 - TTL for this specific record if the question was to an authoritative server.
IN - the class of records (IN = Internet)
SOA - the type of the record (SOA = start of authority)
dns23429.dizinc.COM - is the primary source of the zone
somename.hotmail.COM - is the email address (email@example.com) of someone responsible for the zone
2010072201 - is the serial number
86400 - is the refresh value (how often secondaries will try and reload the zone if no notifies are sent)
7200 - is the retry time (how long a secondary will wait between retries after a transfer failure)
3600000 - is the expiration time (how long a secondary will keep a copy of the zone if it cannot contact the primary server)
86400 - the default time to live for records.  That is the maximum value a record should be cached by any other DNS servers.
Comment: MINTTL doesn't mean that any more, it's now the _negative caching time_.  See RFC 2308.
Answer: "somename.hotmail.COM" is actually "firstname.lastname@example.com" as the email contact.


Alterar texto de TextView

Question: Suponhamos que tenho um texto dentro de uma TextView, existe a possibilidade de alterar android:text remotamente, sem mexer no xml, por meio de uma postagem em um banco de dados externo, por exemplo, uma frase jogada em em um banco que pode ser alterada a qualquer minuto, é possível faze-la aparecer no campo android:text sendo alterada a cada postagem?
(estou estudando um modo, mas me surgiu essa duvida se consigo fazer deste jeito)
Comment: Para alterar o texto do `TextView` recomendo dar uma olhada na documentação do método `setText` ( http://developer.android.com/reference/android/widget/TextView.html#setText(java.lang.CharSequence,android.widget.TextView.BufferType). Como uma recomendação sugiro o curso de Android da Udacity (https://www.udacity.com/courses#!/android). Boa sorte nos estudos.
Comment: Eu tenho pego o curso do Udacity, mas vou ler o artigo sobre o método setText. Obrigado.
Answer: Resumo:
depois de uns estudos, notei mais viável para realização utilizar a webview no xml do que alterar de uma textview.

Alterar texto de TextView


Some badges on meta

Question: I have a curiosity.
I see in the badges page of meta.magento.stackexchange.com a set of badges that in my opinion can't be earned.
Mainly all of them related to reputation points: Altruist, Benefactor,  Mortarboard, ...
Is this some kind of bug? Should those badges be listed there? Or there isn't a way to filter allowed badges per website?
Comment: You know, our 'meta' is not the most intense one. I guess some of those badges can be earned on SO meta.
Comment: @Tim. Yeah..I saw that the meta on SO is just like any other SO website, with it's own rep points. It's not the case here, that's why it seamed strange to me that those badges even exist here.
Comment: I don't think SE stuff will separate badges on per site basis, especially for websites which are still in beta.
Comment: Maybe I should ask this on meta.stackoverflow.com
Answer: I found an answer here provided by Bill The Lizard. Not completely satisfying but it will do for now.

I'd think that removing them would be even more confusing. Meta sites
  are where you go to learn about a Stack Exchange site. As such, I
  think we want all the badges listed there. The fact that some of the
  badges can't be awarded on the Meta site is irrelevant. (There's one
  badge that can't be awarded on Stack Overflow, but it's still listed
  just for the sake of having a complete list.)

Some badges on meta


Samba file server as domain member: error when joining domain

Question: I would like to set up samba 4 to share a local directory, so that domain users are allowed to mount the directory. I don't want domain users to be able to log in the linux machine, they should only be able to use the shared directory.
There are 3 machines involved:

dc: A windows server 2012 acting as domain controller.
workstation: A windows workstation, that is actually the same machine than dc but this is only because i don't have 2 windows and
should not matter.
samba: A linux server with a directory (/srv/rw) that should be shared on the network

I want that, when a domain user is logged in on "workstation", he can see the share on "samba", without being prompted for login/password. I followed this tutorial: http://linuxtot.com/add-a-simple-samba-file-server-as-a-domain-member/
When i try to join "samba" (the machine) to the domain, i get an error:
root@samba:~# net ads join -S rootdomainname.com -U "Administrator%password"
kinit succeeded but ads_sasl_spnego_krb5_bind failed: Server not found in Kerberos database
Failed to join domain: failed to connect to AD: Server not found in Kerberos database

I can see on the network an error with kerberos during the net ads join command:

What does "Kerberos database" refers to ? Is that the one in the AD ?
Also, i don't have any file "/etc/krb5.conf" on my linux machine, is that normal ? Some tutorials refer to this file.
Any idea what the problem is ?
Comment: why the downvote ?
Answer: Out of nowhere it suddenly worked:
do NOT specify -S rootdomainname.com in net ads
Comment: Emm.... AFAIK `-S` is the "server" key to point to specific DC, not to domain itself?