How to enter multiple lines of commands from a register?

Question: How can I execute multiple lines of Vim Ex commands from a register? For example, if I copy some mappings I want to try, how can I execute these lines within the current buffer, from the register I've copied them to?
nnoremap <leader>b :tab split<cr>
nnoremap <buffer> ...
...

I've tried using : followed by <ctrl-r>" (assuming the lines are in the unnamed register) to paste the lines in command line mode, followed by hitting <cr>. The lines that are pasted appear to be separated by ^M, as opposed to newlines. The approach does not work.
I've also tried using q: to open the command-line window, followed by <ctrl-r>", and then hitting enter, but this only executes the current line, rather than all lines I've pasted.
I could paste the lines into a file, and then source that file, but I am looking for an alternative, more direct approach.
Answer: You can use :@" to run the contents of the default register as an Ex command.
See :help :@.


Summation functional on a Hamel basis

Question: Let $X$ be an infinite-dimensional Banach space. Is it possible to choose a Hamel basis $B$ of $X$ such that the linear functional defined by $f(b)=1$ ($b\in B$) was continuous?
Answer: My first thought was surely not. But actually the answer is yes.
Say $f$ is a non-zero bounded linear functional on $X$. Let $N$ be the null space of $f$. Now $X\setminus N$ certainly spans $X$, so there exists a Hamel basis $B\subset X\setminus N$.
So $f(b)\ne0$ for every $b\in B$; now modify $B$, replacing every element by an appropriate scalar multiple and you get $f(b)=1$.

Summation functional on a Hamel basis


How to setup nginx and a subdomain

Question: i have gitlab installed on my server and it works on all domains eg: git.lars-dev.de, lars-dev.de and *.lars-dev.de how I can run gitlab only on git.lars-dev.de and another subdomain on files.lars-dev.de?
my lars-dev conf:
server {
    listen   *:80; ## listen for ipv4; this line is default and implied
    #listen   [::]:80 default_server ipv6only=on; ## listen for ipv6

    root /var/www/webdata/lars-dev.de/htdocs;
    index index.html index.htm;

    server_name lars-dev.de;

    location / {
        try_files $uri $uri/ /index.html;
    }

    #error_page 500 502 503 504 /50x.html;
    #location = /50x.html {
    #   root /usr/share/nginx/www;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #   deny all;
    #}
}

and the gitlab configuration:
upstream gitlab {
  server unix:/home/git/gitlab/tmp/sockets/gitlab.socket;
}

server {
  listen *:80;         # e.g., listen 192.168.1.1:80; In most cases *:80 is a good idea
  server_name git.lars-dev.de;     # e.g., server_name source.example.com;
  server_tokens off;     # don't show the version number, a security best practice
  root /home/git/gitlab/public;

  # individual nginx logs for this gitlab vhost
  access_log  /var/log/nginx/gitlab_access.log;
  error_log   /var/log/nginx/gitlab_error.log;

  location / {
    # serve static files from defined root folder;.
    # @gitlab is a named location for the upstream fallback, see below
    try_files $uri $uri/index.html $uri.html @gitlab;
  }

  # if a file, which is not found in the root folder is requested,
  # then the proxy pass the request to the upsteam (gitlab unicorn)
  location @gitlab {
    proxy_read_timeout 300; # https://github.com/gitlabhq/gitlabhq/issues/694
    proxy_connect_timeout 300; # https://github.com/gitlabhq/gitlabhq/issues/694
    proxy_redirect     off;

    proxy_set_header   X-Forwarded-Proto $scheme;
    proxy_set_header   Host              $http_host;
    proxy_set_header   X-Real-IP         $remote_addr;

    proxy_pass http://gitlab;
  }
}

Answer: You probably got the git.lars-dev.de as the default domain. so any request that is not matched against an explicitly configured is sent there (e.g. files.lars-dev.de). Just try to specify it as a server_name under a separate server.
Read here about how to ensure what server_name is picked up first. Start from server_name *.lars-dev.de to catch all not explicitly configured subdomains.

How to setup nginx and a subdomain


node.js require issue

Question: I am implement following this.
//to_s.js
(function(){
String.prototype.to_s = function(){
        var str = this.toString();
        var convert = function(s){
            return eval(s);
        };

        while(/#{(\w+)}/.test(str)){

            // bad  because I use eval...

            var matchStr =RegExp.$1;

            var str = str.replace(/#{(\w+)}/,convert(matchStr));

        }
        return str;
    };
})();

module.exports = String.prototype.to_s;

// test/to_s_test.js

require("./../to_s");

var name = 33;

"hello #{name}".to_s();

I run to_s_test.js, but it happend error that 'name is undefined'.But I don't know why it happen.But change 'var name = 33' to name = 33 , It works... Do you have any idea? Thanks in advance.
Answer: It will only work without var because eval occurs in another context, and therefore only globals may be accessed using your method. A global is automatically created when you do not declare the variable; however, in node.js, variables declared in modules are not global.
This is why, as I previously mentioned, attempting to make languages conform to other languages' idioms is a bad idea.

node.js require issue


breeze.config.MetadataHelper is not a constructor error with Durandal and Breeze

Question: I am working on a SPA using Durandal v2.1 and Breeze v1.5. This is the first time I am using these libraries. I am creating the metadata for Breeze by hand, thus I'm using the Metadata-Helper plugin as explained in the documentation for Breeze. For this I am relying on examples found here. When I run the application I get the following error:
Error: Failed to load root module (viewmodels/shell). Details: breeze.config.MetadataHelper is not a constructor.
The error seems to occur in the metadataFactory.js file that I use to create the metadata with this line of code (see the metadataFactory.js file further down in the post):
helper = new breeze.config.MetadataHelper(namespace, keyGen);

All the examples I have seen clearly show that the above is a valid instruction, so I am not able to understand what the problem is.
This is my main.js:
requirejs.config({
    'paths': {
        'durandal': '../durandal',
        'plugins': '../durandal/plugins',
        'transitions': '../durandal/transitions',
        'text': '../durandal/amd/text',

        'jquery': '../../Scripts/jquery-2.1.3.min',
        'jqueryUI': '../../Scripts/jquery-ui-1.11.2.min',
        'knockout': '../../Scripts/knockout-3.2.0',
        'bootstrap': '../../Scripts/bootstrap.min',
        'breeze': '../../Scripts/breeze.min',
        'breezeMetadataHelper': '../../Scripts/breeze.metadata-helper',
        'Q': '../../Scripts/q.min',

        'toastr': '../../Scripts/toastr.min',
        'moment': '../../Scripts/moment',

        'logger': '../services/logger',
        'hubService': '../services/hubService',
        'datacontext': 'dataservices/datacontext',
        'metadataFactory': 'dataservices/metadataFactory',
        'constants': 'models/constants',
        'menu': '../shared/viewmodels/menu',
        'menuItem': '../shared/viewmodels/menuItem'
    },
    'shim': {
        'bootstrap': {
            'deps': ['jquery']
        },
        'select2': {
            deps: ['jquery', 'style!Content/select2-bootstrap'],
            exports: 'select2'
        },
        'breeze': {
            deps: ['knockout', 'jquery', 'Q']
        },
        'breezeMetadataHelper': {
            deps: ['breeze']
        }
    },
    urlArgs: 'bust=' + (new Date()).getTime()
});

define(['durandal/system', 'durandal/app', 'durandal/viewLocator', 'logger'], function (system, app, viewLocator, logger) {

    //>>excludeStart('build', true);
    system.debug(true);
    //>>excludeEnd('build');

    logger.log('Loading main module');

    app.title = 'ERWS';

    app.configurePlugins({
        router: true,
        dialog: true,
        widget: {
            kinds: ['grid'] // durandal-grid widget (https://github.com/tyrsius/durandal-grid)
        }
    });

    app.start().then(function () {
        viewLocator.useConvention();
        app.setRoot('viewmodels/shell', 'entrance');
    });
});

This is my shell.js file:
define(function (require) {
    'use strict';

    var logger = require('logger');
    logger.log('Loading shell module');

    var ko = require('knockout');
    var router = require('plugins/router');
    var app = require('durandal/app');
    var constants = require('constants');
    var model = require('models/userInfo');

    var entity = {
        contentBody: ko.observable(''),
        appName: constants.AppName,
        copyrightText: constants.CopyrightText,
        userName: ko.observable(''),
        userImage: ko.observable('')
    };

    var loadData = function () {
        var data = model.entity;

        if (data) {
            entity.userName(data.UserName);
            entity.userImage(data.UserImage);
        } else {
            logger.log('Error loading user info');
        }
    };

    return {
        dashboard: entity,
        activate: function () {
            loadData();
        }
    };
});

And this is the metadataFactory.js which I use to create the metadata, based on the example I have found here:
/*
 * Creates BreezeJS Metadata
 *
 * Usage:
 *    // assume you include this service as 'metadataFactory'
 *
 *    // create a new EntityManager
 *    var manager = new breeze.EntityManager("your-service-endpoint");
 *
 *    // get the MetadataStore from the manager and fill it
 *    var store = manager.metadataStore;
 *    metadataFactory.fillMetadataStore(store);
 *
 */
define(function (require) {
    'use strict';

    var logger = require('logger');
    logger.log('Loading metadataFactory module');

    var breeze = require('breeze');

    var addType, date, dt, bool, helper, id, identity;

    function addCommunityInfo() {
        addType({
            name: 'CommunityInfo',
            defaultResourceName: 'CommunityInfos',
            autoGeneratedKeyType: identity,
            dataProperties: {
                id: { type: id },
                groupsTotal: { max: 3, nullOk: false },
                regionsTotal: { max: 3, nullOk: false },
                landExtensionTotal: { max: 7, nullOk: false },
                parcelsTotal: { max: 4, nullOk: false }
            }
        });
    }

    function addDevicesInfo() {
        addType({
            name: 'DevicesInfo',
            defaultResourceName: 'DevicesInfos',
            autoGeneratedKeyType: identity,
            dataProperties: {
                id: { type: id },
                deviceServers: { max: 3, nullOk: false },
                deviceAdBoards: { max: 3, nullOk: false },
                deviceControllers: { max: 3, nullOk: false },
                deviceTotalUnits: { max: 3, nullOk: false }
            }
        });
    }

    function addGroupInfo() {
        addType({
            name: 'GroupInfo',
            defaultResourceName: 'GroupInfos',
            autoGeneratedKeyType: identity,
            dataProperties: {
                id: { type: id },
                groupName: { max: 50, nullOk: false },
                acronym: { max: 5, nullOk: false },
                dateOfAffiliation: { type: date, nullOk: false },
                inworldDescription: { max: 50, nullOk: false },
                webDescription: { max: 50, nullOk: false },
                yourRoleValue: { max: 50, nullOk: false },
                landOwnedSize: { type: id },
                landOwnedValue: { max: 50, nullOk: false },
                numberOfRentals: { max: 50, nullOk: false },
                presentInRegions: { max: 50, nullOk: false },
                numberOfParcels: { max: 50, nullOk: false },
                numberOfDevices: { max: 50, nullOk: false },
                userRole: { max: 50, nullOk: false },
                inWorldKey: { max: 50, nullOk: false },
                created: { type: date, nullOk: false },
                updated: { type: date, nullOk: true }
            },

            navigationProperties: {
                regions: { type: 'Region', hasMany: true },
                devices: { type: 'Device', hasMany: true },
                rentals: { type: 'Rental', hasMany: true }
            }
        });
    }

    // shorten for brevity....

    // Initialize the metdataFactory with convenience fns and variables
    function init(metadataStore, serviceName) {

        var store = metadataStore; // the metadataStore that we'll be filling
        store.namingConvention = breeze.NamingConvention.camelCase;

        // namespace of the corresponding classes on the server
        var namespace = 'FieryRed.ErcApplication.Core.ViewModel.Admin';

        // 'Identity' is the default key generation strategy for this app
        var keyGen = breeze.AutoGeneratedKeyType.Identity;

        // Breeze Labs: breeze.metadata-helper.js
        // https://github.com/Breeze/breeze.js.labs/blob/master/breeze.metadata-helper.js
        // The helper reduces data entry by applying common conventions
        // and converting common abbreviations (e.g., 'type' -> 'dataType')
        helper = new breeze.config.MetadataHelper(namespace, keyGen);      <===================== My problem seems to be caused by this line of code
        helper.addDataService(store, serviceName);

        // addType - make it easy to add the type to the store using the helper
        addType = function (type) {
            return helper.addTypeToStore(store, type);
        };

        // DataTypes we'll be using
        dt = breeze.DataType;
        date = dt.DateTime;
        id = dt.Int32;
        bool = dt.Boolean;

        identity = breeze.AutoGeneratedKeyType.Identity;
    }

    /*** Implementation ***/
    function fillMetadataStore(metadataStore, serviceName) {
        init(metadataStore, serviceName);

        addCommunityInfo();
        addDevicesInfo();
        addGroupInfo();
        // etc.
    }

    // The metadata definition service
    return {
        fillMetadataStore: fillMetadataStore
    };
});

Answer: My guess is that you did not call require for "breeze.metadataHelper". You can confirm that it was (or wasn't) loaded by setting a breakpoint in your metadataFactory.js and seeing if it is present on breeze.config. If it isn't, then you didn't load it.
You might require it explicitly at the top of metadataFactory.js if that's the only place you use it. Or make metadataFactory.js depend upon it. Either should work although I haven't checked myself.
p.s.: You may find that you're over thinking your require configuration. Defaults could trim this substantially. Also "breeze.metadataHelper" already tells require that it depends upon breeze.
Comment: Thank you Ward. That was the problem. I didn't realize I needed to 'require' breeze.metadataHelper. As for over-thinking the configuration, I am not surprised. I'll refine things as I get more confident with require.js.


Telekrik SideDrawer issue - Cannot read property 'showDrawer' of undefined

Question: I was implementing Telerik's SideDrawer component and got a error JS: ERROR TypeError: Cannot read property 'showDrawer' of undefined.
I am using this tutorial
https://www.nativescript.org/blog/a-deep-dive-into-telerik-ui-for-nativescripts-sidedrawer
My XML is ,
<Page xmlns:lv="nativescript-telerik-ui/listview" xmlns:sd="nativescript-telerik-ui/sidedrawer" loaded="pageLoaded" unloaded="pageUnloaded" xmlns="http://www.nativescript.org/tns.xsd" navigatedTo="onNavigatedTo">            <ActionBar title="RadSideDrawer Demo" class="action-bar" >
    <ActionItem tap="toggleDrawer" ios.systemIcon="4" android.systemIcon="ic_menu_btn_add" ios.position="left" />
</ActionBar>
        <sd:RadSideDrawer id="sideDrawer" drawerLocation="Left">

            <sd:RadSideDrawer.drawerContent>
                <StackLayout class="sidedrawer-left">
                    <StackLayout class="sidedrawer-header">

                    </StackLayout>
                    <StackLayout class="sidedrawer-content">

                    </StackLayout>
                </StackLayout>
            </sd:RadSideDrawer.drawerContent>

        </sd:RadSideDrawer>

and javascript file is
var view = require("ui/core/view");
var drawer="";
exports.toggleDrawer = function() {

    drawer.showDrawer();
};
exports.onNavigatedTo = function() {
    drawer = view.getViewById(page, "sideDrawer");
};

Using Latest version tns-android,tns-core-mocules,telekriki-ui...
What am I missing? Any help will be appreciated..
Comment: I think you should review basic NS programming - take a look at some samples etc. For example, like how to access the current page from within onNavigatedTo().
Answer: I also have this problem; it did not happen in previous versions; it works well on ios; only android is having trouble.
If the first time is executed, there is no error, and sidedrawer has the value.
But in the second run, it returns an error and returns "undefined"
Answer: You need to get a reference to the page before doing getViewById()
so your onNavigatingTo will look like
exports.onNavigatedTo = function(args) {
    const page = args.object;
    drawer = page.getViewById(page, "sideDrawer");
};

Telekrik SideDrawer issue - Cannot read property ‘showDrawer’ of undefined


Calculate size of pixel array of image using RGBA32 pixel format

Question: I have a simple image that stores the width, height, pixelformat, and some other things that I'm not sure about, and then followed by the pixel data.
I've been told the pixel format is RGBA32, and that the rest of the data is just the pixel data.
What's the formula for calculating it?
From my understanding, 8 bits are required for each of the RGBA colors, so 4 bytes are required for each pixel.
So then I would conclude the size of the pixel array is width * height * 4, but that wasn't enough.
Comment: How do you know that wasn't enough? Why don't you post the extra data that you have?
Comment: Who / what is providing you this image? If this is a specific image format, I would guess that there is possibly some kind of header or checksum or metadata or comments.
Comment: I have width and height of 64 * 64  and total pixel data size of 21760. When I read 21760 bytes and display it, it looks fine. When I only read 64 * 64 * 4, it's wrong.
Comment: Can you provide a sample of the data? The first 10 bytes or so should be particularly critical as if it is a standard image format, there is likely a header.
Comment: I reverse binary formats but I've never done image formats so this image was provided by a friend as a "training" format since it's supposed to be a really easy format. The header simply starts with two integers for the width and height, along with 3 other integers that are just -1's, followed by the pixel data. I think he just quickly threw something together. I imagine there's a simple formula to use to figure out the size of the data I need to read.
Answer: A 64px by 64px BMP with RGBA32 will typically be 16440 bytes (presuming BITMAPV3INFOHEADER). 56 bytes for the header, 16384 bytes for the pixel data (which is 64*64*4). The header size can vary though and be as large as 124 bytes (BITMAPV5HEADER) presuming a standard BMP.
I would guess that you've got one or more of the following to account for your extra ~5376 (21760 - 16384) bytes:

Integrity check(s) (checksum, CRC, etc)
A longer header than you currently assume
Pixel alignment which isn't 4 bytes
Metadata (comments, EXIF data, GPS data, etc)
ICC Color Profile
A data gap

In any case, I would first check the last 16384 (64 * 64 * 4) bytes of data which is likely where your image data is (if this format at all takes after the BMP format and doesn't have some trailing metadata or ICC profile or integrity check). On a side note, RGBA data is typically stored with the alpha byte first (ARGB).
Might be worth taking a look at this diagram of the BMP file format just to familiarize yourself with a common image format's structure.


Finding points of Continuity of functions

Question: There are three functions where I have to show the points of continuity of. While I think it makes a lot of sense, I'm struggling with the notation. I apologize for the lengthy post.
$(1)$ $f: \mathbb{R} \rightarrow \mathbb{R}$ with $f(x) = 1 \space for\space \lvert x\rvert \lt \sqrt{3}$ and $f(x) = -1 \space for\space \lvert x\rvert \geq \sqrt{3}$
$(2)$ $f: [0,\infty) \rightarrow \mathbb{R}$ with $f(x) = x^2\lfloor\frac{1}{x}\rfloor \space$ for $x \ne 0$ and $f(0) = 0$
$(3)$ $f:\mathbb{Q} \rightarrow \mathbb{R}$ with $f(x) = 1 \space for\space \lvert x\rvert \lt \sqrt{3}$ and $f(x) = -1 \space for\space \lvert x\rvert \geq \sqrt{3}$
$(1)$ I've tried solving the following: The possible points of discontinuity could be $\sqrt{3}$ and $-\sqrt{3}$. I'm really not sure how to put this formally. If we evaluate for $x = \sqrt{3}$:$\space$for values less than $\sqrt{3}$ we get 1. For values $\geq$$\sqrt{3}$ we get $-1$.
Comparing the left and right limits we get: $\lim_{x\to \sqrt{3},\space x \lt \sqrt{3}}=1 \ne -1 =\lim_{x\to -\sqrt{3},\space x \geq \sqrt{3}}$
So there is a point of discontinuity there. The same thing can be done for $-\sqrt{3}$. Therefore, since I'm asked for the points of continuity, we get $\mathbb{R}\setminus\{\sqrt{3},-\sqrt{3}\}$
For $(2)$ I'm not really sure. I've tried plotting it and realised, that after $x=1, \space \lfloor\frac{1}{x}\rfloor$ will always be $0$, therefore $f(x) = 0$ for $x>1$. However, this obviously is not a proof and for values between $0$ and $1$, this function seems to have many points of discontinuity.
How can I try to show this or even calculate all the points of discontinuity?
For $(3)$ I have to admit I can't really make much sense of. Since the inputs are rationals the outcome will be different from $(1)$. Is there an easy way to calculate or prove this? Does $\sqrt{3}$ being irrational have something to do with it?
Thanks in advance for your patience and apologies for my lack of knowledge and the mistakes I probably made while calculating $(1)$
Answer: 1)) You already showed that at points $\pm \sqrt{3}$ the function $f$ is discontinuous. It remains to show
that $f$ is continuous at $x\ne \pm \sqrt{3}$. This holds because for each such $x$ there exists $\varepsilon>0$ such that
$f$ is constant on an interval $(x-\varepsilon, x+\varepsilon)$. Remark that since $\sqrt{3}$ is irrational, such $\varepsilon$
exists for each rational $x$, so the function $f$ in (3) is continuous too.
2)) If $x\ne 0$ and $1/x\not\in\Bbb N$ then there exists $\varepsilon>0$ such that
$\lfloor 1/y\rfloor=\lfloor 1/x\rfloor=\operatorname{const}$ when $y\in (x-\varepsilon, x+\varepsilon)$. Then
$f(y)= y^2\lfloor 1/x\rfloor $ for such $y$, so $f$ is continuous at $x$.
If $1/x\in\Bbb N$ then it is easy to check that $\lim_{y\to x+} f(y)=x^2\lfloor 1/x\rfloor=f(x)$,
but $\lim_{y\to x-} f(y)= x^2(\lfloor 1/x\rfloor+1) \ne f(x)$, so $f$ is discontinuos at $x$.
Finally, if $x=0$ then $$0=\lim_{y\to x+} f(y)\le \lim_{y\to x+} y^2\frac 1{y}=\lim_{y\to x+} y=0,$$
so $f$ is continuous at $x$.
Comment: Thanks! Could you elaborate more on why $(3)$ is so similar to $(1)$? Doesn't it change anything if we have it from $\mathbb Q \rightarrow \mathbb R$?
Comment: @23408924 The function $f_3=f$ from (3) is the restriction of the function $f_1=f$ from (1) onto a set $\Bbb Q$ contained in the set of continuity points of $f_1$, so $f_3$ is continuous.


Writing music in DAW: what's your workflow?

Question: I'm just curious how people write music in DAW when they have no input MIDI devices. Piano roll isn't particularly convenient to write music, and built-in score editors seem to be so so, too.
I used to write notes in Guitar Pro and then export it as midi and import in my DAW. However, I find this approach increasingly inconvenient as I'd like to be able to edit notes in place.
I've heard one can use external editors by means of VST and synchronize data between them and DAW.
So how do you usually write down your notes when you have no real input device? Do you use piano roll or built-in score editor or something? And what DAWs do you find the most convenient for this process?
Comment: I suggest you edit your title to include the "no midi input" part because that's probably a very small subset of people compared to **all** people that write music in a DAW. That said, the obvious answer to me—if the piano roll and score editors don't work for you—is to buy a MIDI keyboard. Even if you don't have much of a budget there are some really cheap ones that will work in a pinch.
Answer: Maybe there's a 'virtual keyboard'.   Else you'll just have to do what musicians have always had to do, write marks on the (virtual) paper.  As you say, all sequencers have a 'piano roll' method, some have a notation one.  Would an 'external editor' offer anything that wasn't in a good DAW?
Comment: Actually I've just tried Cubase Elements 9 and it's much better than anything else I've tried before, it has a decent score editor and a very convenient drum editor, I think I'll stick to it
Answer: basically my workflow is simple,

Chords,
Melody,
Layering the melody and chords,
Adding main drums on it,
Put some fx,
Mixing
if overall is good, Mastering


How to get access to the selected element?

Question: I use d3.js and I created an "option" window that allows me to choose between the index i of some elements of, let's say, an array with the length of 4 elements. The user Andrew Reid helped with this code in another thread, so all credits to him:
var data = [10,20,30,40];

var color = d3.schemeCategory10; // color array built in

//// Add the select and options:
var select = d3.select('body')
  .append('select')
  .on('change',function() { update(this.value) });

var start = select.append('option')
  .html("select: ");

var options = select.selectAll('.option')
  .data(data)
  .enter()
  .append('option')
  .attr('class','option')
  .attr('value',function(d,i) { return i; })
  .html(function(d,i) { return i; });

//// Add the circles (and svg)
var svg = d3.selectAll('body')
  .append('svg')
  .attr('width',500)
  .attr('height',200);

var circles = svg.selectAll('circle')
  .data(data)
  .enter()
  .append('circle')
  .attr('cx',function(d,i) { return i * 30 + 50; })
  .attr('cy',50)
  .attr('r',10)
  .attr('fill',function(d,i) { return color[i]; });

// Update everything:
function update(i) {
  data.splice(i,1); // remove that element.

  // Update and remove option from the select menu:
  options.data(data).exit().remove();

  // Remove that circle:
  circles.data(data).exit().remove();

  circles.attr('cx',function(d,i) { return i * 30 + 50; })
    .attr('fill',function(d,i) { return color[i]; });

  // reset the select menu:
  start.property('selected','selected');
}

With the help of the  line  .html(function(d,i) { return i; }); the "option" window shows up the indexes and allows me to click on it.
My goal:
For example the "option" window shows up the numbers of the indexes:
0, 1, 2, 3

Now I click on the index "2" and i want to use that index "2" in other functions. My question is, how can I save that clicked number in a variable a and use this variable, for example, in a splice function:
data.splice(i, a)

In the code currently the splice function is data.splice(i,1).
Comment: Where do you perform this `array.splice(i, a)`?  Is it on the click event of the option?  This question looks like an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem).
Comment: @DerickKolln it's impossible to help you without seeing how the event handler calls the other function. Please post a [MCVE](http://stackoverflow.com/help/mcve) (emphasis on the **minimum**!) code.
Comment: Thanks. But I'm not following this: it's slice or splice? (they are different). And you are **already** passing the index `i` correctly! That number `a` is not the index.
Comment: Are you looking to take two values (i,a) from one select menu every change (which may be problematic if you chose any value that is over half as large as the data array length), or simply take either a value or index from a select menu and store it in a variable for later ("Now i click on the index "2" and i want to use that index "2" in other functions")? With the latter option, is there an associated trigger of a function? Apologize for my denseness, I'll blame it on something to do with daylight savings time kicking in where I'm at.
Comment: Hey Mark, it is not a click event of teh option. It is a seperate outside function.
Comment: It is splice, sorry for confusion. Yeah, i know, that it is correctly, but my goal is to click a number on that "option" window based on the index (0,1,2,3) and then the splice function uses the chosen number automatically to remove this number of elements. For example: If i click on "4" in the "option" window, then it should be automatically `data.splice(i, 4)`. That's  why i am looking for a way to store the clicked index number in a variable `a`. And the result of the splice function would be `data.splice(i, a) `.
Comment: No need to apologise, Andrew. I am happy for anyone who spends his freetime to help bad programmers like me. I am looking for the latter option with a index only. There is no associated trigger of a function written now, because i thought that a solution could be a simple storage in a global variable. But maybe i could be wrong.
Answer: You can pass the option text to your update function from your onchange function as:
this.options[this.selectedIndex].text

So you'd end up with:
var select = d3.select('body')
  .append('select')
  .on('change',function() { update(this.value, this.options[this.selectedIndex].text) }); // note: since you are setting value equal to the index, you can also use this.value instead of this.selectedIndex

function update(i, a) {
  data.splice(i,a);
  ...
}

How this works: in your code you use d3 to append an HTML select element (Select object) with several HTML option elements (Option object) in it.
Then on the select element, the onchange function (which is a standard event of the select element) then passes the select element to its function handler, so in that function this represents the actual select element, and therefore this.value (Select value property) corresponds to the value of the select element (i.e. the value of the currently selected option in the select element).
The options property of the select element, i.e. this.options (Select options collection), gets you a list of all of the option elements within that select. Using the selectedIndex property of the select element, i.e. this.selectedIndex (Select selectedIndex property), you can grab the currently selected option element from the list as this.options[this.selectedIndex].
Since the this.options collection is a list of Option elements (Option object), to get the actual text of that option you can use .text on it. And that's how you end up with this.options[this.selectedIndex].text.
Comment: I think you need to append your options to your select.
Comment: Hm yeah I see you're right. When you tried using selectedIndex what happened? Did you get an error of some kind?
Comment: Ok I think I found the issue! My answer was slightly off. It should be `this.options[selectedIndex].text`.
Comment: No problem! I updated my answer with the `.text` fix as well as an explanation of how it all works. If it answers your question, it'd be great if you could mark my answer as accepted by clicking the check mark next to it :)
Comment: Thanks! And it's literally just a built in property of the HTML option object - see [https://www.w3schools.com/jsref/prop_option_text.asp](https://www.w3schools.com/jsref/prop_option_text.asp)
Comment: thanks for the help, i tried it but it did not work. I just looked at the definition and it says "The selectedIndex property returns the index number of the selected option in that instance of a select box." My question is, when using  `selectedIndex`, is there HTML and a select box required? Because in my code both is not used.
Comment: I think it is already appended in the code or you mean a different thing?
  `var options = select.selectAll('.option')
  .data(data)
  .enter()
  .append('option')`
Comment: Your idea was very great, i just wonder if there is another solution?
Comment: Wow, thank you Erika, this works great. Can you explain me, what is the trick behind it when you add `.text`? I have not understood it right i guess.
Comment: Yes, i just accepted it. Can i ask you maybe for a short explanation of that using of `.text`.?
Comment: oh wow, so "Return the text of the selected option in a drop-down list" works for numbers also. Thanks so much!


cant figure out why "Contains" will not work. I am getting an error asking if i am missing a directory or assembly reference.?

Question: Console.Write("Enter letter grade for class #{0}\n" +
   "(use A, B, C, D or F. Type 0 after all classes entered.): ", counter += 1);
char userInput = char.Parse(Console.ReadLine());

if (!"ABCDF".ToCharArray().Contains(userInput))
{
    Console.WriteLine("Enter valid letter");
    continue; // Start's the do loop over
}

Why does Contains give me an error asking if i am missing a directory or assembly reference?
Comment: Look at the top of your file. There's a bunch of `using System;`, etc, up there. You're missing `using System.Linq;`. You can't use the LINQ extension methods without first telling C# that you want to use them.
Comment: read the error again.  it is not asking if you are missing a *directory*
Comment: directive* my mistake..
Comment: well, are you missing a *`using directive`*?
Comment: I am very new at this, I dont know what that means..
Comment: I got it to work..Thanks everyone for all of your help!
Answer: Instead of converting the string to char[], you can do this:
 if(!"ABCDF".Contains(userInput))
 {
      Console.WriteLine("Enter valid letter");
 }

Comment: that had an error with converting 'char' to 'string'
Comment: For me it is working just fine, but you can change it to userInput.ToString()


Can we use z-test when the population standard deviation is known but the sample size < 30?

Question: Let's say I know the population standard deviation, but the sample size is small (≤30). Can I use the z-test? The reason I ask is that I see two different statements.

We can use the z-test, if we know the population standard deviation AND the sample size is >30.
As long as we know the population standard deviation, we can use the z-test. The sample size does not matter (above or under 30).

What do you think and why? Thanks.
Comment: Yes if $X \sim N(\mu,\sigma^2)$ for known $\sigma$. (Is it plausible to know the population standard deviation but not the mean?)  But if it has another distribution then it depends on whether a normal approximation would be close enough: in some cases it may be, while in others not
Answer: What is the hypothesis here? What does $X$ follow?
If $X\sim\mathcal N(\mu, \sigma^2) $ with $\sigma$ being known, and $\mathcal H_0: \mu=\mu_0, $ then, of course, one can resort to the test statistic $$z:=\frac{\bar x-\mu_0}{\sigma/\sqrt n}.\tag 1$$
Comment: Yes, that's exactly the hypothesis I was referring to. So it does not matter even if n≤30, correct? Thanks.
Comment: This is an exact test. So, yes.
Comment: The question does not assume a Normal population distribution.
Comment: @whuber that's why I asked at the outset. What the specifics are. It seems it is indeed the case as OP said above.
Comment: I suspect the OP might not realize you made this extra (very strong) assumption.
Comment: I also bore the same concern as you (and as even Henry wrote). That's why both in Henry's comment and my answer, it was explicitly mentioned __if__ $X\sim\mathcal N(\mu, \sigma^2), $ then.... Otherwise the question itself is ambiguous.


Problema com a conexão PDO e mysql_query

Question: Olá, criei o arquivo conexao.php da forma abaixo:
   <?
   $conn= new PDO("mysql:host=localhost;dbname=site", "root", "");

   $count = ('SELECT * FROM conteudo');
   $stmt = $conn->prepare($count);

   $stmt->execute();
   $result = $stmt->fetch(PDO::FETCH_ASSOC);
   return $result;
   ?>

E aqui eu dou somente o include do arquivo conexao.php?
    <?php include "conexao.php"; ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="Contentype" content="text/html; charset=iso-8859-1" />
    <title> Painel Adm. Conteudo</title>

    <link rel="stylesheet" type="text/css" href="/css/normalize.css">

    <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
    <link rel="stylesheet" type="text/css" href="/css/result-light.css">

    <div id="texto001" align="left" style=" font-family:Verdana, Geneva, sans-serif;
    color:#000000; font-size:12px; float:none; width:<? echo $res['larg_tex001'];?>px;
    height:<? echo $res['altu_tex001'];?>; position: absolute; left: <? echo $res['hori_tex001'];?>px;
    top: <? echo $res['vert_tex001'];?>px;">

     <?php echo $res['texto001'];?>

    <img width="<? echo $res['larg_img001'];?>" height="<? echo $res['altu_img001'];?>"
    align="left" src="upload/<? echo $res['img001'];?>" style="position: absolute;
    left: <? echo $res['hori_img001'];?>px; top: <? echo $res['vert_img001'];?>px;" />

Porém estou recebendo as seguintes mensagem abaixo:

Pergunto aos amigos o que esta faltando para funcionar no WAMPSERVER?
Se os amigos puderem me ajudar a solucionar esse problema, ficarei muito agradecido.
Abraços a todos, e no aguardo de uma ajuda de vocês.
Answer: Crie uma conexão:
$conn= new PDO("mysql:host=HOST;dbname=NOMEDOBD", "USUARIO", "SENHA");

Crie um statement:
$count = 'SELECT COUNT(*) FROM livro';
$stmt = $conn->prepare($count);

e execute o statement:
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;

Comment: Esse statement faço no mesmo arquivo da conexao ou crio um outro arquivo?
E  executo onde na minha mysql_query, ou seja na pagina conteudo?
Pois bem eu fiz isso e parou de me enviar as mensagens, porém não me traz mais nada, a página fica totalmente vazia.
Teria como vc. me demostrar como ficaria os aquivos conexao e onde será feita a busca.
Desde já meus agradecimentos e desculpe-me, pois sou muito leigo em PHP e estou tentando aprender.
Comment: Tudo junto nesta mesma ordem, abre conexão cria o statement com a query desejada e executa. Esquece o que fez, você juntou PDO e mysql_query, ambas não coesistem, ou é da forma que fiz `PDO` ou mysql_query.
Comment: Eu editei a minha pergunta com as suas orientações. Seria isso?
Comment: Amigo Ricardo, resolvido, além das suas dicas estarem corretas, eu estava usando , ou seja estava esquecendo o 'PHP' depois da ? para buscar os dados.
Cara muito obrigado pela aula.
Comment: @MuriloCabral Disponha!
Answer: Você não está fazendo uma conexão com PDO e sim com mysql.
A mensagem diz que a função mysql_connect() está depreciada, e que será removida do PHP. O ideal é você utilizar PDO ou mysqli.
Um exemplo simples de conexão com PDO:
$conexao = new PDO("mysql:host=HOST;dbname=NOMEDOBD", "USUARIO", "SENHA");

Comment: OK Igor, eu fiz a conexão PDO como me ensinou e como faço o mysql_query, pois agora estou recebendo essas duas  mensagens:

        Deprecated: mysql_query(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\site\conteudo.php on line 3.
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\site\conteudo.php on line 4.


How to use a Ruby-style map on a Java vector?

Question: I have a feeling this is a question that Google could quickly answer if I knew the Java terminology for what I want to do, but I don't, so in Stack Overflow I trust. :)
I have a vector of Objects, and I want an array of Strings containing the string representation of each element in the vector, as generated by calling toString() on each element.
In Ruby (or Perl, or Python, or Scheme, or any of the millions of other languages with a map method), here's how I'd do it:
vector.map(&:to_s) do |string|
  # do stuff
end

How can I do the equivalent in Java? I'd like to write something like this:
Vector<Object> vector = ...;
String[] strings = vector.map(somethingThatMagicallyCallsToString);

Any ideas?
Comment: As an orthogonal point, this *might* be useful info: http://stackoverflow.com/questions/1386275/why-java-vector-class-is-considered-obsolete-or-deprecated. Your best bet is to use an `ArrayList` (if possible).
Comment: It may also depend on the result you want to have. Do you need it to be `String[]` or would an iterator be sufficient?
Comment: @Howard: An iterator should be fine.
Comment: @Jits: Thanks for the info on `ArrayList`; I wasn't aware of `Vector`'s unfortunate synchronisation behaviour.
Answer: If you're OK bringing in Guava, you can use its transform function.
Iterable<String> strings = Iterables.transform(vector, Functions.toStringFunction());

transform's second argument is an instance of the Function interface. Usually you'll write your own implementations of this, but Guava provides toStringFunction() and a few others.
Comment: Yes, that's an unfortunate namespace collision. Lisps were calling the list transformation "map" long before Java was born, so I blame Bill Joy personally for this confusion. ;)
Comment: Awesome! This is exactly what I was after. Strange that they called it `transform`. ;)
Comment: @Josh "Map" is overloaded, what with `java.util.Map` meaning something quite different. I think `transform` better describes it anyway, but it's not the most common name for it.
Answer: One approach could be:
Vector<Object> vector = ...;
ArrayList strings = new ArrayList();
for (Object obj : vector) {
  strings.add(obj.toString());
}
return strings.toArray(new String[1]);

Comment: I certainly **could** do it this way, but it is quite clunky compared to a map. :)
Comment: clunky but safe, I like it


docker php:7.1-fpm-alpine fails to build GD

Question: Trying to build from the official php:7.1-fpm-alpine image, using the following excerpt in my Dockerfile:
FROM php:7.1-fpm-alpine

RUN set -ex \
    apk add --no-cache --virtual .build-deps \
    freetype-dev \
    libjpeg-turbo-dev \
    libpng-dev \
\
    && docker-php-ext-configure gd \
        --with-freetype-dir=/usr \
        --with-png-dir=/usr \
        --with-jpeg-dir=/usr \
    && docker-php-ext-install gd \
    && apk del .build-deps

When attempting to build this with docker build, GD fails during ./configure with the following error:
configure: error: jpeglib.h not found

I can confirm that jpeglib.h exists and is exactly where I think it should be (indeed, exactly where it is in Debian variants):
$ docker run -it --rm php:7.1-fpm-alpine /bin/sh
>$ apk add --no-cache libjpeg-turbo-dev \
   && find /usr -type f -name 'jpeglib.h'
   ...
   /usr/include/jpeglib.h

But if I take exactly the same command used in the dockerfile and run it interactively inside the container, it builds flawlessly. No errors.
Is this a bug, or am I missing something?
Answer: The problem was a blindingly simple syntax error; the apk call following the set command needs to be preceded by &&, otherwise the interpreter is treating the entire apk call as a set of arguments to set. In that case, the packages aren't added, therefore jpeglib.h didn't exist.
When I typed the command into the shell, I used the correct syntax, so it passed without error.
Answer: yes, you should write like this
RUN set -ex \
    && apk add --no-cache --virtual .build-deps \


Writing DWORD to memory overwrites only 1 byte instead of 4

Question: I have
typedef unsigned int DWORD;

void write_str(string str, char** buf) {
    DWORD len = str.size();
    **buf = len;
    *buf += sizeof(len);
    memcpy(*buf, str.c_str(), len);
    *buf += len;
}

This code, and only 1 byte is overwriten in **buf = len; if i have i.e. 7 in len while 4 should be, since sizeof(DWORD) = 4
Comment: Only 1 byte is assigned to `**buf` because that's all it can hold.
Comment: Oh, I'm so blind :(, thanks. Post it as answer, I'll close question.
Answer: Fix:
DWORD *tmpptr(*buf);
*tmpptr = len;

C++ is automatically casting len to a char, since that is what *buf is.
Answer: As buf is a char **, **buf is a char. It can hold only a single byte. Therefore, only a single byte is written to it.
Answer: You have the parameter
char** buf

Meaning that **buf is a char, which is very likely a single byte.
Answer: 1 byte is overwritten since the destination type is char (the type of **buf is char). This is correct. But the expression *buf += sizeof(len) has no meaning in my opinion.


Permutations and terminology ("subpermutations"?)

Question: I will start with example. I have two permutations (of 5 elements) - (1 2) and (1 2)(3 5 4). When the first permutation changes something, the second do the same change (but it can do anything with fixed elements of the first).
What's the best way (terminology) to call or understand such relation between two permutations?
[EDIT]
Here is how to check for such relation in GAP:

ForAll(Orbits(Group(p1)), i -> i in Orbits(Group(p2)));

If true, then p2 contains all cycles of p1.
Comment: Call the first one $\sigma$ and the second $\tau$. What you're saying is that every cycle of $\sigma$ is a cycle of $\tau$.
Answer: I guess you're saying that the first permutation is the restriction of the second one to a subset left invariant by the second one.
Comment: Did you mean "restriction of the second one to a subset left invariant by the **first** one"?

Or something like that - because the second permutation in my example doesn't have any invariant subset, imho.
Comment: @IlmārsCīrulis, the second permutation $\tau$ leaves exactly the two sets $\{1,2\}$ and $\{3,4,5\}$ invariant, the orbits of $\langle \tau \rangle$. In your case, the first permutation $\sigma$ is the restriction of $\tau$ to $\{1,2\}$.
Comment: Oh, a different kind of invariant. My apologies.
Can you give context where such terminology is used?

My original context was thinking about graph symmetries (automorphisms), where I thought that symmetry (1 2)(2 5 4) "includes" symmetry (1 2). But I didn't find anything like that. (And nothing about permutations too.)


Can I report fixed and random effects outcomes in one paper?

Question: I am a health economist working with panel data for a paper I am working on, I use Hausman tests to determine if I should use fixed or random effects estimators in my analysis, for some outcomes random effects are supported, for others fixed are. For the main table of results in my paper would it be acceptable to report the results of the fixed effects models for those outcomes that the hausman suggests should use a fixed effects estimator and the results of the random effects estimator for those outcomes that a random effects estimator is suggested for? Are there any examples of this approach in the literature?
Best.
Answer: The Hausman test merely tests whether the fixed-effect model provides results that are statistically different from those of the random-effect model.
I would keep in mind that FE models are always more flexible, because you don't impose any assumption on the distribution of the unobservables. Conversely, if you were sure that the distribution of the unobservables are correct, the RE model would be preferable, as RE estimates are more efficient in this case.
As, in economics, we are rarely sure about the distribution of the unobservables, I would personally show the results in FE in one table for all outcomes, and report in another table the results with RE for those outcomes for which the Hausman test does not reject the null hypothesis. Of course, here, we're in the realm of judgement and opinion, and I'm just giving my own. Your solution, which consists of mixing methods for different outcomes, may be viewed by referees as a way to conceal some results.


Windows 8 - Firewall Issues from Command Line

Question: I created the following script basically to block absolutely everything and only allow through what I want, however it's not allowing through what I like in regards to the internet. Can anyone see an issue with my rules? Currently they are pretty generic.
@ECHO OFF

ECHO ========================================= Brendan Thompson - Firewall Policy - v1.0 =========================================

ECHO ----------------------------------------- Removing All Firewall Rules -----------------------------------------

ECHO Deleting all Incoming Firewall Rules
netsh advfirewall firewall delete rule name=all dir=in profile=any

ECHO Deleting all Outgoing Firewall Rules
netsh advfirewall firewall delete rule name=all dir=out profile=any

ECHO Delete all Remaining Firewall Rules
netsh advfirewall firewall delete rule name=all

ECHO ----------------------------------------- Initial Profile Setup -----------------------------------------

ECHO Block all Incoming and Outgoing Traffic on Domain Profile
netsh advfirewall set domainprofile firewallpolicy blockinbound,blockoutbound

ECHO Block all Incoming and Outgoing Traffic on Private Profile
netsh advfirewall set privateprofile firewallpolicy blockinbound,blockoutbound

ECHO Block all Incoming and Outgoing Traffic on Public Profile
netsh advfirewall set publicprofile firewallpolicy blockinbound,blockoutbound

ECHO ----------------------------------------- Domain and Private Profile - Incoming Application Exceptions -----------------------------------------
netsh advfirewall firewall add rule name="APP - BROWSER - Internet Explorer" dir=in action=allow profile=domain,private program="C:\Program Files\Internet Explorer\iexplore.exe"

ECHO ----------------------------------------- Domain and Private Profile - Outgoing Application Exceptions -----------------------------------------
netsh advfirewall firewall add rule name="APP - BROWSER - Internet Explorer" dir=out action=allow profile=domain,private program="C:\Program Files\Internet Explorer\iexplore.exe"

ECHO ----------------------------------------- Domain and Private Profile - Incoming Port Exceptions  -----------------------------------------
netsh advfirewall firewall add rule name="PORT - GENERAL - HTTP (80) - TCP" dir=in action=allow protocol=TCP localport=80
netsh advfirewall firewall add rule name="PORT - GENERAL - HTTP (80) - UDP" dir=in action=allow protocol=UDP localport=80

ECHO ----------------------------------------- Domain and Private Profile - Outgoing Port Exceptions  -----------------------------------------
netsh advfirewall firewall add rule name="PORT - GENERAL - HTTP (80) - TCP" dir=out action=allow protocol=TCP localport=80
netsh advfirewall firewall add rule name="PORT - GENERAL - HTTP (80) - UDP" dir=out action=allow protocol=UDP localport=80

Any ideas what's going wrong that would cause me not to be able to browse the web? :S
--Brendan
Answer: You need to allow DNS outbound (dst udp/53). I would suggest enabling the windows firewall logging on all profiles and review the log "c:\windows\system32\logfiles\pfirewall.log" to see what is being blocked.
Your outbound IE rules also need "localport" switched to "remoteport"
Answer: Your rules are wrong. For Incoming Port Exceptions, you must allow traffic from port 80 to High port(1024 - 65535).
And for Outgoing Port Exceptions, you must allow traffic from High port(1024 - 65535) to port 80
Your traffic look like this
- Begin: You send HTTP request

  YourPC(High port) ----> (80)Webserver

- Then : Webserver send HTTP respone

  YourPC(High port) <---- (80)Webserver

Your rules does't allow these traffic, It only allows traffic to your machine port 80.


Bayesian regression with singular $(X'X)$ - Is the posterior well-defined?

Question: SE community, I hope to get some insights into the following problem.
Given a simple linear regression model $$Y=X\beta+\epsilon\text{ , where } Y\in\mathbb{R}^T,X\in\mathbb{R}^{T \times N}.$$
Under a Gaussian likelihood function with homoscedastic error terms the conditional distribution of the dependent variable takes the form
$$Y|\beta,h \sim N(X\beta,h^{-1}I).$$
I assign a conditional (uninformative) conjugate prior for $\beta$ and $h$
$$\beta|h \sim N(0,cI), h\sim G(s^{-2},v)$$
were $c\rightarrow\infty, v\rightarrow0$. It is a standard result that the marginal posterior distribution of $\beta$ is multivariate t with
$$\beta|D\sim t_N (\hat{\beta},\hat{\Sigma},T).$$
What happens if $(X'X)$ is singular? In standard regression I would go for the generalized Moore-Penrose Pseudoinverse $(X'X)^+$ instead of using $(X'X)^{-1}$. However, in this case the posterior variance $\hat{\Sigma}:=c(X'X)^{-1}$ would be singular as well and I doubt that the $t$-Distribution is still well-defined. Is this correct?
And even further distracting to me: Assume I am not really interested in the posterior distribution of $\beta$ but just a linear combination $z:=A\beta$ where $A\in\mathbb{R}^{N-1 \times N}$, and $|A\hat{\Sigma}A'|\neq 0$. I would be able to sample from that distribution although its construction is based on something that is not really defined (the distribution of $\beta$). Is there a way to handle this? Or is there an essential mistake in my question that makes my whole point obsolete?
Comment: At best, non-informative priors provide helpful results when the data uniquely identify model parameters - This observation is basically why we have ridge regression and its relatives instead of solely relying on OLS. But if the data are not sufficiently informative, typically one will either go the regularized regression route (ridge, etc) or the fully Bayes route. In the full Bayes route, just define proper, informative prior distributions over your data and the problem will be tractable.
Comment: Thank you for your comments so far! I get the point that the posterior of $\beta$ is not properly defined. However, does this really cause problems for the random variable  $z $ which is at least theoreticaly well defined?
Comment: Well. what confuses me is that the posterior of $z$ seems plausible although the way to a solution is not satisfying at all. I am currently searching for a way to rewrite the regression equation, because I am optimistic that it would be possible to obtain directly regression parameters $z$ instead of wasting time on searching for $\beta$. However, although this seems possible in my specific case, I am still left with the question what it means if a 'bad' model is nested in a functioning one...
Comment: If your design matrix is highly or perfectly multicollinear, it contains very little information to update your priors with, which means at least for some parameters the resulting posterior will very much resemble the prior you've started with (for more details [see Poirier](https://www.jstor.org/stable/3533214)). If you started with an improper prior, [you'll get an improper posterior](https://stats.stackexchange.com/q/497759).
Answer: The major problem with your question is that taking limits does not straightforwardly extend to measures and probability distributions. There are many different types of convergence associated with measures.
Hence, considering the conjugate
$$\beta|h \sim \mathcal{N}(0,cI), h\sim \mathcal{G}(s^{-2},\nu)$$
and letting $\nu$ and $c$ go to $0$ and $\infty$, respectively, does not have a proper or unique mathematical meaning.
Now, if you consider the improper prior
$$\pi(\beta,h)\propto\frac{1}{h}$$
there is no posterior distribution associated with the likelihood
$$L(\beta,h|X,y)=\exp\{-h(y-X\beta)^\text{T}(y-X\beta)/2\}h^{T/2}$$
because the potential posterior does not integrate in $\beta$ conditional on $h$. There is no $$\hat{\Sigma}=(X^\text{T}X)^{-1}$$ either because the inverse does not exist and no well-defined distribution on $A\beta$.


Is there a nontrivial but short example where the separable degree is strictly less than the degree of a field extension?

Question: I consider the following theorem:
Let $E\supset F\supset k$ be a tower. Then $$[E:k]_s=[E:F]_s\cdot [F:k]_s.$$ Furthermore if $E$ is finite over $k$ then $[E:k]_s$ is finite and $$[E:k]_s\leq [E:k].$$

Now I am thinking about a nontrivial example where $$[E:k]_s<[E:k]$$ is strictly less.

But at the moment I can't think about one. So I thought maybe one of you have an example in mind which could be helpful.
Answer: Litterally any extension which is not separable. It has to happen in characteristic $p>0$, and the standard example is: $k=\mathbb{F}_p(X)$ and $E=\mathbb{F}_p(\sqrt[p]{X})$ (adjoining a $p$th root of $X$).
Comment: @aprozz In your example $[E:k]=2$. Think a little bit more about separability degree.
Comment: Seeing that $[E:k]_S=1$ is not completely trivial, but I think you should be able to figure out why taking a square root gives an extension of degree $2$.
Comment: Ah okei but now if I would take $p=2$ then $k=\Bbb{F}_2(X)$ and $E=\Bbb{F}_2(\sqrt{X})$ but then if I understood it correctly $[E:k]_S=2$ and $[E:k]=3$ or is this wrong?
Comment: Sorry why $[E:k]=2$ in my example so I mean does $E$ not have dimension $3$ over $k$?

And is $[E:k]_S=1$?
Comment: @CaptainLama sorry could you give me a hint? Because I think that I need to count all extensions of the embedding $\sigma:k\rightarrow L$ to an embedding of $E$ in $L$. Where $L$ is an algebraically closed field but I don't see how to count all possibilities


React-Native - How to create tabs dynamically in Native Base?

Question: I want to use Tabs from the native base library but I don't know how can I create tabs dynamically?
In the official documentation, the tabs are added manually. But how can I add tabs dynamically?
Comment: Use native base tabs component. it working perfectly in both platform https://docs.nativebase.io/Components.html#tabs-def-headref
Answer: you need to create array of tabs component using some loop then render the array of components
for Example :
<code>export default class ThemeTabsExample extends Component {
    makeTabs = ()=>{
      //make array of components which finally look like this one  :
      //[<CustomeTabComponent tabLabel='One' />,
      // <CustomeTabComponent tabLabel='two' />,
      // <CustomeTabComponent tabLabel='three' />
      // ]
     // hint :
     Output = []
     for ....
         Output.push(<CustomeTabComponent />)
    }
    render() {
        let Tabs = this.makeTabs(....) // you can use 'loop' here instead of calling Function
        return (
            <Container>
                <Content>
                    <Tabs>
                    {Tabs}
                    </Tabs>
                </Content>
            </Container>
        );
    }
}
</code>


Subtract char pointer from time_t

Question: I have date time in character pointer -
char *connectTime = "2013-10-19 01:10:00";

then I fetched current time that'll be disconnect time.
time_t disconnectTime;
disconnectTime = time(NULL);

Now, I want to subtract connectTime from disconnectTime. I googled but couldn't implement it.
Please help.
Comment: What you have is a string. You need to parse it into a `time_t` value first.
Comment: how to parse it into time_t ?
Comment: http://stackoverflow.com/questions/11671859/how-to-parse-a-string-to-a-ctime-struct Is this helpful?
Comment: Read [How to compare two time stamp in format "`Month Date hh:mm:ss`" to check +ve or -ve value](http://stackoverflow.com/questions/15555406/how-to-compare-two-time-stamp-in-format-month-date-hhmmss-to-check-ve-or-v/15556395#15556395)
Comment: Not really a duplicate as here the date/time given in string format shall be substracted from a `time_t`.
Answer: You can use strptime() to convert connectTime to a struct tm and then use mktime() on the latter to convert the it to a time_t.
char * connectTime = "2013-10-19 01:10:00";
struct tm tmConnect = {0};
time_t timeConnect;
char * pc = strptime(connectTime, "%Y-%m-%d %H:%M:%S", &tmConnect);
if ((NULL == pc) || ('\0' != *(pc + strlen(connectTime))) /* The second condition assume connectTime does not hold any more characters after "... 01:10:00". */
{
  perror("strptime() failed");
  /* handle error */
}
else
{
  timeConnect = mktime(&tmConnect);
}

To then calculate the difference in seconds use difftime(), as mentioned by in Grijesh Chauhan's comment:
time_t disconnectTime;
disconnectTime = time(NULL);
double diff = difftime(disconnectTime, timeConnect);

Comment: And for time diffidence/subtract use: [`double difftime (time_t end, time_t beginning);`](http://www.cplusplus.com/reference/ctime/difftime/)
Comment: Thanks all for quick response...
Comment: When I am using same code as written above then I am not getting correct difference. Minute is not working like connectTime is "2013-10-19 01:10:00" when i am subtracting then I am getting difference from "01:00:00" not from "01:10:00"
Comment: value of tmConnect is "01:00:00"
Comment: @user2794235: You are correct, there was a typo in the format passed to `strptime()` in my code snippet. I just corrected that.
Comment: @alk Still not getting correct result. This time I am getting "Thu Jan  1 05:30:00 1970" in timeConnect
Comment: @user23750: The format specifier for the seconds was wrong: `%s`. It is `%S`. Corrected after having checked `man strptime`.

Subtract char pointer from time_t


Examples of Limits of Linear ( on the Parameters) models?

Question: I am trying to find examples of datasets that cannot be modeled well using linear models.
I get that, e.g., polynomials cannot model data (say the likes of y=1/x) that settles or converges to a finite value, since polynomials " escape" to infinity at $\pm \infty$. So I have seen recommended to use models of the type :$$Ax^{b}$$ for said datasets.
Question 1:
Given that linearity is only required on the parameters ( and not on the variable(s)), why can't we use linear approximations to model these sets?
Question 2
Any other example(s) of data sets that cannot be modeled linearly ( meaning with generalized linear regression), preferably with some argument?
Comment: Do you mean some kind of series expansion?
Comment: Not sure I understood, Dave. Looking for examples of data sets for which $y=a_0+a_1\beta_1+a_2 \beta2+....+a_n\beta_n$, where $a_i$ are constant and $\beta_i$ are functions does not provide a good fit. If y were a polynomial, an example would be a data set whose y values approach 0, since polynomials will approach $\pm \infty$ as x values go to $\pm \infty$. Sorry if I was not clear.
Answer: Let any relationship
$$y = f(\mathbf x),\qquad \mathbf x= (x_1,...x_k)$$
Then the first-order Taylor expansion around some point $\mathbf x^0$gives
$$y = f(\mathbf x^0) + \frac{\partial f(\mathbf x^0)}{\partial x_1}(x_1 - x_1^0)+\dots+\frac{\partial f(\mathbf x^0)}{\partial x_1}(x_1 - x_1^0)+\dots R$$
Re-arrange
$$y = \left [f(\mathbf x^0) - \sum_{j=1}^{k}\frac{\partial f(\mathbf x^0)}{\partial x_j}x_j^0\right]\,+\,\frac{\partial f(\mathbf x^0)}{\partial x_1}x_1 +\dots +\frac{\partial f(\mathbf x^0)}{\partial x_k}x_k\,+\,R$$
The correspondence with the $a + b_1x_1 +...$ polynomial is obvious.
Going for the "translog" specification, will give you a second-order approximation to any function.
As for $y=Ax^b$ it is transformed into a polynomial by taking logarithms, $\ln y = \ln A + bx$, at least when positive variables are involved.
The question with these approximations is whether they are adequate for the purpose at hand. The fact that they may not capture correctly the whole range of the relation, may not be of consequence, if what you are interested is the characterization of the relationship in the "center". But if you are interested in characterizing the extremes, then more elaborate constructs may be required.
So the issue of choosing a functional form is not so much linked to "data set structure", but to the purposes of the research.


Residuals vs fitted values plot interpretation for "striped residuals"

Question: I tried to run a simple linear regression in R, and when I check for the linearity, my "Residuals vs Fitted" graph is like this:

Are the points randomly scattered? Or this showing a pattern because it is all aligned together vertically?
*The variables reli and ghq are suppose to be continuous, what I did, for example as ghq, I just summed up the ghq item 1 to 12 into total_ghq, and I did the same thing to total_reli scores. Example: for participant number 1, reli1=3,reli2=3,reli3=1,reli4=2,reli5=2 total_reli=11
Comment: Both variables appear to be discrete. This can lead to overplotting  (and it seems like it may have impacted your plot). That will make any patterns harder to discern; there are a variety of potential solutions to this, including jittering or using semi-transparent points (so that darker shades indicate more data). Please edit your question to explain what the variables are and how they're calculated/measured.
Comment: What distinct values occur for your two variables?
Comment: The variables reli and ghq are suppose to be continuous, what I did, for example as ghq, I just summed up the ghq item 1 to 12 into total_ghq, and I did the same thing to total_reli scores. Example: for participant number 1, reli1=3,reli2=3,reli3=1,reli4=2,reli5=2, total_reli=11
Answer: I don't see any particularly damning patterns in your residuals versus fitted values. Typically you would see some odd patterns like tight clustering in some regions and more dispersion in others, or some kind of nonlinearity issues which end up in curved LOESS lines (the red one shown above). Some examples of odd residuals can be shown here and here.
Yours do not look particularly problematic and so I agree with Peter that they are not an issue. The "striping" you see here is simply because they are likely discrete values so they do not have any "in-between points." The one caveat is that the right region of your residual plot looks less densely populated with values. This isn't inherently a problem, but may merit investigating to see why this is the case.
I will finally note that the aspect ratio of your plot is very wide (aka stretched out). Sometimes this will distort the LOESS line a bit. The pattern would be more clear if you increased the height a little, but I doubt there are any serious issues regardless.
Comment: thank you for your answers, but my variables reli and ghq are suppose to be continuous, what i did, for example as ghq, I just summed up the ghq item 1 to12 into total_ghq, and i did the same thing to total_reli scores, i have checked in the rstudio, both total_ghq and total_reli are shown as numerical values, what could possibly turn the variables into discrete?
Comment: Sum scores don't automatically make continuous scores, particularly for counts. If your data points have decimals but there are simply a very low range of available values, then the data can also act like discrete data even when it is essentially continuous in other contexts. If for example $x$ is a variable with decimal values but only has the values $[1,1.5,2,2.5]$, then the data will often behave like discrete values due their consequent binning into a very finite number of possible values. Summing them won't automatically cure that, as you can have a finite number of sum scores too.
Comment: my data points do not contain decimals, so is it summing up the items make the variables turn into discrete? And does it mean is wrong if i run the linear regression? Sorry im really new to statistic, thank you for your patience
Comment: Yes theyre discrete but theres nothing wrong with running discrete values in a regression (though as Peter noted youll need to also check that you meet the assumptions of regression)
Comment: understood, thank you very much
Answer: This is (almost certainly) due to your having one independent variable (total_reli) and that it takes on only a certain number of values, one for each column.  This is not necessarily a problem for OLS regression, and there is not much of a pattern in the plot.  Maybe total_reli is a count, or a rounded number or something like that.
Of course, you have to check the other assumptions as well.


FreeFem++: Tangential trace in boundary condition?

Question: I want to use Nédélec's elements in FreeFem++ to solve Maxwell's equations in 3D. My problem is that I don't find a way to write the boundary condition which is E × N = F. I tested:
on(0, Ehy * N.z - Ehz * N.y = Fx, Ehz * N.x - Ehx * N.z = Fy, Ehx * N.y - Ehy * N.x = Fz)
but an error is displayed, and the only thing it says is that there is an error "before token =". If I change the boundary condition to a random one like on(0, Ehx = Fx, Ehy = Fy, Ehz = Fz) it doesn't throw any error so I think the issue comes from the arithmetics operations in the condition.
Any idea?
Comment: Hey Jeremy, your second attempt in indeed the right one! May I ask you if you know how to implement Neumann boundary conditions for Nedelec elements?
Comment: Hi, actually it's not the right thing to do, as it won't work as expected. Please refer to the answer I added below to get the real solution to the issue. About Neumann conditions, it's difficult to give a solution without having them but, in general, this type of condition is included in the variational equation so there's no problem.
Answer: Writing on(0, Ehx = Fx, Ehy = Fy, Ehz = Fz) won't produce a compilation error, but it won't produce the right solution neither.
There is a workaround to get the right solution, with the right boundary condition: having a function f such that f × n = E × n. That way, you can write on(0, Ehx = fx, Ehy = fy, Ehz = fz) and it will work as expected.
If you only have F but you know exactly the boundary of the domain you can compute f = n × F. Basic operations will convince you that f × n = E × n.
Comment: Yep! That's right! Sorry, I misunderstood what you wrote above. What about Neumann conditions?


Fingerings for Chromatic Third Scales on the Piano

Question: Can someone enumerate the main fingerings for major (... → C-E → C♯-F → …) and minor (... → C-E♭ → C♯-E → …) chromatic third scales? I've heard that Czerny, Moszkowski, Chopin and Godowski each had unique fingerings of situational suitability. I'd also like to know which fingerings Rafael Joseffy used since I prefer his exercises.
Comment: Since everyone's hands and fingers are subtly different in their length and mobility, any fingering guide will be at best just a suggestion that someone feels is best - for them. Bearing that in mind, a player's best option is to slowly work out what fingering works best for *them*.
Comment: I've usually seen an alternating 1-3, 2-4 pattern, but occasionally I've come across some 1-4, 2-5 alternating pattern. As Tim says, it depends on your hands, and I've even altered fingering from what was written on chromatic third passages recently.
Comment: I understand and usually alter provided fingerings but it is nice not to have to start from scratch for the building block of a scale. There are so many possible fingerings, most to be avoided especially at high velocity.
Answer: I have found the fingerings that Rafael Joseffy uses for minor thirds. His fingering for major thirds does not seem to be publicly known.
Vladimir de Pachmann, Moritz Moszkowski, Ferruccio Busoni, and Alberto Jonas also have used the following fingering.
First line of numbers is RH and second line is LH:
31 42 51 32 42 31 42 31 42 51 32 42 31(2) 41 32 51 42 31 42 32 41 32 51 42 31
24 23 14 23 15 24 13 24 23 14 32 15 24    15 23 24 12 24 13 24 15 23 24 13 24
Note, the first notes are C and Eb


Reversing a switch statement

Question: I'm working on some inherited code and I've got a function that is converting between to formats of swing weight (a golf club term, for you non-golf folk). This function converts between a letter/float format (e.g., C3.1, E4.5, etc) to a decimal format (e.g., 20.15). It's not an intuitive conversion as you will see below in the switch statement that performs the conversion. My problem is that the code only has this one-way conversion (from C8.9 to 20.15), and now I need to reverse this (from 20.15 to C8.9), so if a solution to this is more apparent to anybody than it is to me, I'd love to hear your suggestion. If this is not the right place for this type of question, let me know and I'll move it.
    // lorythmicSwingWeight will be in the Letter/Float format, e.g. D3.0
    internal static decimal ioSW(string lorythmicSwingWeight)
    {
        string lSW_alpha = string.Empty;
        decimal lSW_num = 0.0m;
        decimal oSW = 0.0m;

        //parse first letter
        lSW_alpha = lorythmicSwingWeight.Trim().ToUpper().Substring(0, 1);
        //try to parse number
        decimal.TryParse(lorythmicSwingWeight.Substring(1), out lSW_num);

        switch (lSW_alpha)
        {
            case "A":
                if (lSW_num < 10)
                    oSW = (20000m * lSW_num + 1710329m) / 112300m;
                break;
            case "B":
                if (lSW_num < 4.0m)
                    oSW = (500m * lSW_num + 50371m) / 2963m;
                else if (lSW_num < 10)
                    oSW = (250m * lSW_num + 25449m) / 1497m;
                break;
            case "C":
                if (lSW_num < 1.7m)
                    oSW = (4000m * lSW_num + 409927m) / 21980m;
                else if (lSW_num < 5.3m)
                    oSW = (800m * lSW_num + 86909m) / 4660m;
                else if (lSW_num < 10m)
                    oSW = (200m * lSW_num + 21902m) / 1175m;
                break;
            case "D":
                if (lSW_num < 2.2m)
                    oSW = (10000m * lSW_num + 1242163m) / 61100m;
                else if (lSW_num < 5.0m)
                    oSW = (5000m * lSW_num + 621387m) / 30550m;
                else if (lSW_num < 8.5m)
                    oSW = (2000m * lSW_num + 248677m) / 12220m;
                else if (lSW_num < 10m)
                    oSW = (2500m * lSW_num + 310999m) / 15275m;
                break;
            case "E":
                if (lSW_num < 4.0m)
                    oSW = (100m * lSW_num + 13222m) / 601m;
                else if (lSW_num < 10m)
                    oSW = (10000m * lSW_num + 1317201m) / 59900m;
                break;
        }

        oSW = Math.Round(oSW, 2);
        return oSW; // this will spit out a decimal, e.g. 20.15
    }

Comment: @ryanyuyu I believe it's one-to-one, I have a chart that goes along with this.. it occurs to me now that instead of figuring out a clever way to do this, I could more easily just cross-reference the chart in a manner of speaking.
Comment: Is the reverse operation even a function?  By that I mean will every specific decimal format map to exactly one lorythmic weight?
Comment: if these are supposed to be logrythmic, why not use the `Math` class to perform actual logrythms?
Comment: @Aravol it's not logrythmic, lorythmic is not a typo.
Comment: @Andy got it. If you cross-reference a chart, be aware there are some pretty nasty quirks when it comes to comparing non-integer values in code, and you'll want to round more than perform a simple lookup
Comment: @Aravol good point, thanks for the tip
Answer: The problem with thing a reverse calculation is that, at least mathematically, there could be two results for any given input. Disclaimer: I am not a golf person, so this is taking it from a high-level logical analysis.
Because of the ambiguity, your best bet may be to simply run the calculation on the result per letter, thus getting an A__ result, a B__ result, a C__ result... ect. Since you have to perform some if checks in applying the math the first time, you might even need more than one such result per letter, but then start chucking results which don't match presumptions - this the result for an A with lWS_sum < 10 could be chucked if the reverse of that stage math (oSW = (20000m * lSW_num + 1710329m) / 112300m;) came out greater than ten.
From there, you'll have a list of possible results. Order them by string length, and take the first.
Comment: I'm not a golf person either, but this sounds like it should work just fine for this application

Reversing a switch statement


Transição de cores JavaScript

Question: Alguém sabe se é possível fazer um código em JavaScript para que uma página em meu site receba uma transição lenta onde depois de alguns segundos ela fique de outra cor...
Ou seja: quero que comece com opacidade 0 e depois de 1 minuto sua opacidade fiquem em 100% deixando tudo o que tem na pagina invisível.
Answer: Você pode criar uma animação com CSS para executar após x segundos, exemplo:

body {
    -moz-animation: hideMe 0s ease-in 5s forwards;
    /* Firefox */
    -webkit-animation: hideMe 0s ease-in 5s forwards;
    /* Safari and Chrome */
    -o-animation: hideMe 0s ease-in 5s forwards;
    /* Opera */
    animation: hideMe 0s ease-in 5s forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}
@keyframes hideMe {
    to {
       opacity:0;
    }
}
@-webkit-keyframes hideMe {
    to {
       opacity:0;
    }
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla imperdiet, metus sit amet placerat pharetra, nisi ipsum egestas lorem, ut luctus enim nisl a nulla. Quisque at ornare nulla, sit amet maximus turpis. Nulla congue luctus sem, id bibendum mauris pretium non. Ut pulvinar quam sed pharetra blandit. Etiam elementum massa tortor, sit amet vestibulum elit semper ac. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur porta mattis ligula, vel posuere est dignissim at. In ut efficitur felis. Duis sit amet pharetra nulla. Integer in risus ullamcorper, congue lacus vel, posuere augue. Curabitur fermentum nibh molestie libero rutrum, efficitur vulputate purus tempor. Mauris quis eleifend leo. Suspendisse sit amet nulla fringilla, consectetur sem ac, aliquet sapien. Etiam sed iaculis elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla imperdiet, metus sit amet placerat pharetra, nisi ipsum egestas lorem, ut luctus enim nisl a nulla. Quisque at ornare nulla, sit amet maximus turpis. Nulla congue luctus sem, id bibendum mauris pretium non. Ut pulvinar quam sed pharetra blandit. Etiam elementum massa tortor, sit amet vestibulum elit semper ac. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur porta mattis ligula, vel posuere est dignissim at. In ut efficitur felis. Duis sit amet pharetra nulla. Integer in risus ullamcorper, congue lacus vel, posuere augue. Curabitur fermentum nibh molestie libero rutrum, efficitur vulputate purus tempor. Mauris quis eleifend leo. Suspendisse sit amet nulla fringilla, consectetur sem ac, aliquet sapien. Etiam sed iaculis elit.

Neste exemplo o body ficará com opacidade 0 depois de 5 segundos.
Answer: Há diversas maneiras de se fazer isto usando jQuery,algumas são :
Você pode usar setTimeOut() do jQuery que chama uma função depois de um determinado tempo ou executa um código depois de um tempo(em milissegundos).
Exemplo :
function explode(){
  alert("Boom!");
}
setTimeout(explode, 2000);

Acima no código,a função explode() será executada em 2 segundos(2000 milissegundos).
Para melhor entendimento,aconselho você olhar aqui na documentação sobre esta função.
Você pode usar também animate() que também tem uma função parecida para poder executar um trecho de código ou função em um determinado tempo.
Exemplo :
var x = document.getElementById('home_page');

$(x).animate({opacity:1.0},2000);

No exemplo acima,a função animate() irá dar opacidade a home_page em 2 segundos(2000 milissegundos).
Para melhor entendimento lhe aconselho a dar uma olhada na documentação oficial aqui.
Answer: Se você quer deixar tudo invisível, então seria ao contrário, a opacidade começa em 1 e vai até 0.
É possível sim.
Eu aconselho utilizar a função $.animate da biblioteca JQuery UI.
Veja o seguinte código.

<!doctype html>

  <meta charset="utf-8">
  <title>Animação com animate</title>

Deixar conteudo invisível

      SEU CONTEUDO, BLA BLA BLA, MAIS CONTEUDO AQUI

<button id="button">Deixar invisivel</button>

A função animate faz parte da biblioteca jquery-ui, por tanto você deve incluí-la em seu projeto.
Com a função animate, você pode especificar uma quantidade de tempo (em milissegundos) que a transição vai ocorrer. No código acima, eu coloquei 1000 (1 segundo).
Dentro dos braços {...} você pode colocar as propriedades que você quer animar. Neste caso coloquei as propriedades backgroundColor (para alterar o fundo) e color (para alterar cor da fonte).
Comment: Obrigada pela ajuda!
Comment: como eu faco para que a animacao aconteca automaticamente depois de alguns segundos e nao apos clicar no botao? obrigada
Comment: Você pode declarar o `setTimeout(function(){//codigo de transicao aqui}, 2000);` sendo que neste caso, 2000 significa 2 segundos, já que o tempo é definido em milisegundos.

Transição de cores JavaScript


Show customized label color on bar chart

Question: I have customized the item label position so that the label appears outside the bar when it doesn't fit inside the bar as shown below.

How do I give a different color to the labels when the text is inside the bar. e.g white color text inside and black color text outside the bar. I have tried the below code but its showing black always. I want 20 to appear in white and 57 and 30 in black text
Note: This is a customizer class written for a Jaspersoft Studio bar chart
public class Test extends JRAbstractChartCustomizer {

    static class LabelGenerator extends StandardCategoryItemLabelGenerator {
        @Override
        public String generateLabel(CategoryDataset dataset, int series,
                int category) {
            return dataset.getRowKey(series).toString();
        }
    }

    @Override
    public void customize(JFreeChart chart, JRChart jasperChart) {

        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        plot.setRangeGridlinesVisible(false);

        BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setItemMargin(-1);
        renderer.setBaseItemLabelGenerator(new LabelGenerator());
        renderer.setBaseItemLabelsVisible(true);
        ItemLabelPosition p = new ItemLabelPosition(ItemLabelAnchor.INSIDE12,
                TextAnchor.CENTER_RIGHT, TextAnchor.CENTER_RIGHT,
                -Math.PI / 2.0);
        renderer.setBaseItemLabelPaint(new Color(255, 255, 255));
        renderer.setBasePositiveItemLabelPosition(p);

        ItemLabelPosition p2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
                TextAnchor.CENTER_LEFT, TextAnchor.CENTER_LEFT, -Math.PI / 2.0);
        renderer.setBaseItemLabelPaint(new Color(0, 0, 0));
        renderer.setPositiveItemLabelPositionFallback(p2);

        CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
    }
}

Answer: You can try using this:
import java.awt.Color;
renderer.setBaseItemLabelPaint(Color.WHITE);


loess.smooth, smooth.splines and sm.regression with more x variables

Question: I'd like to predict a y with several x values (x1, x2, x3, x4, x5, x6). A linear model is very simple, but i don't understand how can i use loess.smooth, smooth.splines and sm.regression with more x variables. I tried using a dataset or a matrix as x, but this way doesn't work.
x is a matrix 700x6, while y is a 700 element array.
sm1=sm.regression(x, y, h=0.5, add=F, ngrid=300, display="none")

Error in sm.check.data(x = x, y = y, weights = weights, group = group,
  : x has too many columns

ls1=loess.smooth(x, y, span=0.5)

simpleLoess(y, x, w, span, degree, FALSE, FALSE, normalize = FALSE,  :
  NA/NaN/Inf in foreign function call (arg 1)

I checked and there aren't any NA, Nan or Inf in x.
ss1=smooth.spline(x,y, spar=0.5)

Error in xy.coords(x, y) : 'x' and 'y' lengths differ
Comment: The first two won't work I don't think. From `sm.regression` docs: x is a vector, or two-column matrix, of covariate values. `loess.smooth` is for producing plots from a smoother. Again from the docs: Plot and add a smooth curve computed by loess to a scatter plot. I'm not sure about `smooth.spline`. It would help to see a sample of your data set (e.g. `dput(head(data))`.
Comment: You maybe need to get your strategy straight first, and if you expect help on SO you should post a data example. There are many regression approaches that support prediction with splines or locally estimated surfaces, but SO asks you to have thrashed out those details before posting. Perhaps CrossValidated.com could help if you described in more detail what you need rather than describing what doesn't work.
Answer: Those functions are simpler and designed for a pair of x and y variables. Suitable alternatives exist, such as in the forms of two functions named gam(), one in package mgcv which comes with R as a Recommended package, and the other in package gam which is an R version of the GAM software (gam()) in S-PLUS and the original implementation following Hastie & Tibshirani's "mono"graph on Generalised Additive Models (GAM).
Both fit so called additive models where the main assumption is that the terms in the model contribute in additively to the give the fitted response. If you want LOESS-based smooths in the GAM, try package gam, but mgcv has a wider range of penalised regression splines and has a more modern approach to smoothness selection in the individual splines.


Error when attempting to use a Linked table in MS access

Question: Our Intranet runs under asp/vb script / MS Access.
We have been experiencing issues with MSAccess and would like to replace it with MSSQL Server. Initially I thought I could just import the current data from Access into MSSQL and connect to them via linked tables. - so no need to touch the code.
However when I try to open a page that uses a linked table I get the following error:
Microsoft JET Database Engine error '80004005'
ODBC--connection to 'xxxx' failed.
/index.asp, line 80
xxxx is the User DSN I defined to link the tables. - This now uses SQL Server auth. but I had the same error when using window auth.
When opening the linked tables from within access everything is fine.
IIS 7.5 / ASP classic (vbscript) SQL Server 2008 R2
Does anyone have any ideas, I really want to avoid recoding anything and changing to use SQL server directly would involve a lot of that!
Answer: The first thing we need to do is determine whether it is possible to "see" a SQL Server linked table in a Jet/ACE database from outside of the Access application itself. My test database Database1.accdb contains a linked table

The following VBScript proves that I can "see" that table without being in Access itself:
Option Explicit
Dim con  '' As ADODB.Connection
Dim rst  '' As ADODB.Recordset
Const AccessLinkedTableName = "dbo_linkedTable"
Set con = CreateObject("ADODB.Connection")
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data source=C:\Users\Public\Database1.accdb;"
Set rst = CreateObject("ADODB.Recordset")
rst.Open "SELECT COUNT(*) AS n FROM [" & AccessLinkedTableName & "]", con
WScript.Echo "[" & AccessLinkedTableName & "] contains " & rst(0).Value & " row(s)"
rst.Close
Set rst = Nothing
con.Close
Set con = Nothing

When I run that script from my normal account I get the following
C:\Users\Public>cscript /nologo linkedTableTest.vbs
[dbo_linkedTable] contains 2 row(s)

So we know that it can work.
Your question raises two concerns, both related to the fact that ASP scripts normally run under their own IUSR_MachineName account.

You said that you used a "User DSN", but if you created that User DSN then nobody else can see it. You probably want to be using a System DSN instead.
If you are using Windows Authentication on the SQL server then you may have to grant access to the SQL Server database for the IUSR_MachineName account. (The alternative would be to use SQL Authentication and save the SQL credentials in the Linked Table definition, but saved passwords are not a very good idea.)


How to use the Dirichlet prior for estimating the multinomial parameters?

Question: I know that the multinomial distribution gives the likelihood of some vector D of occurrences to happen given a probability vector (parameters) P' i.e. P(D|P'). Now with a Dirichlet prior we are introducing a prior for those parameters. Up to my understanding, this Dirichlet prior is used for the posterior Dirichlet-Multinomial P''=P(P'|D) which gives the probability of the parameters.
If we took the MAP estimate of P'' we will get again P', but we already have P'. Shall we assume that the parameters P' are unknown in the multinomial distribution or...?
Comment: Your question & notation is not very clear. Is your question: why do we use priors?
Comment: @Tim yeah you can say that, but please stick to my question i.e. multinomial scenario and Dirichlet prior as I am not familiar with all distributions
Answer: Say that you have an urn with red, green, and blue balls, you draw $n$ balls from the urn with replacement. The distribution of the counts of the red, green, and blue balls, $(x_1, x_2, x_3)$, would follow multinomial distribution parametrized by probabilities $(\pi_1, \pi_2, \pi_3)$ such that $\sum_{j=1}^3 \pi_j = 1$ for drawing red, green, and blue balls respectively,
$$
(x_1, x_2, x_3) \sim \mathcal{M}(n, \,\pi_1, \pi_2, \pi_3)
$$
The values of $\pi_i$ are unknown and you want to estimate them from your data (counts of the drawn balls). There are different ways of estimating the probabilities, for example you could take the maximum likelihood estimate $\hat\pi_i = \tfrac{x_i}{n}$. Another possibility is to use Bayesian approach, where instead of looking only at the data, you also assume a prior for the probabilities and then use Bayes theorem to update the prior to obtain the posterior estimate of the parameters. In case of multinomial distribution, the most popular choice for prior is Dirichlet distribution, so as a prior for $\pi_i$'s we assume
$$
(\pi_1, \pi_2, \pi_3) \sim \mathcal{D}(\alpha_1, \alpha_2, \alpha_3)
$$
where $\alpha_1, \alpha_2, \alpha_3$ such that $\forall\,\alpha_i > 0$ are the parameters of the Dirichlet distribution. Because this is a conjugate prior, updating the prior to posterior is straightforward, because the posterior distribution of the estimated parameters is
$$
(\pi_1, \pi_2, \pi_3) \mid (x_1, x_2, x_3) \sim \mathcal{D}(\alpha_1 + x_1, \alpha_2 + x_2, \alpha_3 + x_3)
$$
If you want a point estimate for the probabilities, you can take mean of the posterior distribution
$$
\hat\pi_i = \frac{\alpha_i + x_i}{\sum_{j=1}^3 \alpha_j + x_j}
$$
If you want a practical example where it is useful, for example in natural language processing you can use Laplace smoothing, i.e. estimate the probabilities of occurrences of words using Dirichlet-multinomial model with uniform prior. It helps for the fact that when training and then predicting using a machine learning model, if in the test set you find a word that was not seen in training set, then with maximum likelihood approach you would conclude that the probability of observing such word is zero (it was not seen in training set), while in case of Bayesian estimate it is nonzero
$$
\hat\pi_i = \frac{\alpha_i + 0}{\sum_{j=1}^3 \alpha_j + x_j}
$$
This makes a difference in many cases, for example with Naive Bayes algorithm you multiply all the probabilities, so multiplying by zero would zero-out everything.
Comment: @MosabShaheen $\sim$ means "is distributed as". As about example, it was given in the answer above, just replace $(x_1, x_2, x_3)$ and $(\alpha_1, \alpha_2, \alpha_3)$ with some numbers.
Comment: @MosabShaheen (π1,π2,π3)∼D(α1,α2,α3) is the definition of *prior*. Posterior is defined in next equation. As about multiple instances, just use totals of all the instances, so $n$ is the total number of balls drawn and $x_1$ is the total number of blue balls that you drawn. You assume the data is i.i.d. so it doesn't matter that you draw them in multiple experiments. Sum of multinomials is mumtinomial.
Comment: @MosabShaheen it means that they are random variables that follow such distribution.
Comment: Nice explanation, thanks Tim. I understand from this is that we do not use the posterior if we already know the probabilities, rather we use it to estimate the probabilities π. However I am still confused, If you have one instance X(x1,x2,...) how can you estimate the probabilities π using only one instance X (i.e. this instance may be an anomaly and does not reflect the actual experiment. Shouldn't be an iterative approach. If so could you please mention it in your answer. Also when you write (π1,π2,π3)∼D(α1,α2,α3) what does this symbol "∼" mean (I am not a mathematician so pls bear with me)
Comment: thanks, I mean X(x1,x2,x3)  should be Xs (i.e. many instances) because we want to train using many instances not only one. I do not know if you mean by (x1,x2,x3)  a one instance but that's what I understood it. So shouldn't be many instances?
Comment: also you said (π1,π2,π3)∼D(α1,α2,α3) means "is distributed as". I think π should be distributed using the data and the prior not only the prior, is it correct (I mean we should not write π here rather we should write instead of π something else like (S1,S,S3) ∼D(α1,α2,α3) ) ?
Comment: thanks again. When we say (π1,π2,π3)∼D(α1,α2,α3) or "is distributed as" does it mean that π1,π2.. are the variables (or inputs) of these distribution or it means they are the output (the mass function) of this distribution ?
Comment: should the denominator for ̂i be \sum_{j=1}^{3} \alpha_{j} + x_{j} and not \sum_{j=1}^{3} \alpha_{i} + x_{i}
Comment: @vahndi right, thanks for supporting this!


In Django : How to serialize dict object to json?

Question: I have this very basic problem,
>>> from django.core import serializers
>>> serializers.serialize("json", {'a':1})
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/pymodules/python2.6/django/core/serializers/__init__.py", line 87, in serialize
    s.serialize(queryset, **options)
  File "/usr/lib/pymodules/python2.6/django/core/serializers/base.py", line 40, in serialize
    for field in obj._meta.local_fields:
AttributeError: 'str' object has no attribute '_meta'
>>>

How can this be done?
Comment: have a look on my answer please.
Answer: Also, since you seem to be using Python 2.6, you could just use the json module directly:
import json
data = json.dumps({'a': 1})

Comment: The Django serializers are for Django model objects and QuerySets. That's why it's looking for a _meta field.
Comment: And the native serializer doesn't do the job: TypeError:  firstname.lastname@example.com> is not JSON serializable
Answer: from django.utils import simplejson
data = simplejson.dumps({'a': 1})

Comment: That works great with python objects, but not so well with Django query sets.
Comment: @Ted: Of course not. To serialize query sets, do what the question shows.
Comment: Looks like the Django guys decided to stick with the built-in json module. As of the end of 2013, simplejson is deprecated and should be replaced with json. https://github.com/pythonforfacebook/facebook-sdk/issues/106
Answer: Libraries like json or simplejson are not really cool for the purpose of serializing django objects, when you can use the serializer from django.core in your views:
from django.core import serializers

def json_for_model_instance(request, pk):
    instance = YourModel.objects.get(pk=pk)
    serialized_instance = serializers.serialize('json', [instance, ])

    return HttpResponse(serialized_instance, content_type="application/json")


How can I access this nested array within my JSON object?

Question: I'm using PHP to return a json_encode()'d array for use in my Javascript code. It's being returned as:
{"parent1[]":["child1","child2","child2"],"parent2[]":["child1"]}

By using the following code, I am able to access parent2 > child1
$.getJSON('myfile.php', function(data)
{
   for (var key in data)
   {
      alert(data[key]);
   }
}

However, this doesn't give me access to child1, child2, child, of parent1. Alerting the key by itself shows 'parent1' but when I try to alert it's contents, I get undefined.
I figured it would give me an object/array? How do I access the children of parent1?
data[key][0] ?
Answer: The JSON returned should be:
{"parent1":["child1","child2","child2"],"parent2":["child1"]}

then you can access them as:
var data = {"parent1":["child1","child2","child2"],"parent2":["child1"]}
alert(data['parent1'][0]);
alert(data['parent1'][1]);
alert(data['parent1'][2]);

Comment: Unless my eyes deceive me, the only difference there is you've renamed parent1[] to parent1 and parent2[] to parent2. How would this fix the code? :/ The 'parents' are the names of inputs within my HTML form. The inputs are arrays and, therefor, are named with [].
Comment: OK, so you don't have to rename as I did.  But you can still access them as:

    for (var i = 0; i < data['parent1[]'].length; i++) {
       alert( data['parent1[]'][i]);
    }
Answer: You're only iterating one level into the object, so it's correct that you're only seeing the parents.  You'll need to descend into those keys to find the children.
// Generally, avoid the "foreach" form in JavaScript.
for (var i = 0; i < data.length; i++) {
  alert(data[i]); // Parent1[], Parent2[], etc

  var parent = data[i];

  for (var j = 0; j < parent.length; j++) {
    alert(parent[j]); // Child1, Child2, etc
  }
}

Aside, the [] suffix on Parent keys is okay.  It is valid JSON.
Answer: you can assign it in a variable as follows:
var  = data[key];
and then get the contents of the array by using the size of the array.
Hope that helps.


How to find dim of linear subspace

Question: In $\mathbb{R}^5$ we have linear subspace $X$ such $\dim(X)=3$ and let $V=\{A\in \mathbb{R}^{5,4} : \operatorname{im}(A)\subset X\}$. I need to find $\dim(V)$. If we knew that result doesn't depend on choice of $X$ we could choose $X = \operatorname{span}(\{ [1,0,0,0],[0,1,0,0],[0,0,1,0]\})$ and easily show that $\dim(V) = (5-3)\cdot4=8$. How to do it in general?
Comment: You're wrong: the answer should be
$$
\dim V = 3 \times 4 = 12
$$
In particular, the matrices which have a $1$ somewhere in the top $3 \times 4$ submatrix and a zero everywhere else form a basis of your space in the case of your example.
Answer: Hint: $V$ may also be characterized as the space of matrices whose columns are in $X$.

How to find dim of linear subspace