Which football matches had the highest combined number of goals?

Question: I would like to know football match with highest number goals scored for both teams combined in both international football, and the top European leagues like the English Premier League, La Liga etc.
Answer: International match: Australia hold the record for the most goals in an international match for a victory over American Samoa (11th April 2001) in Oceanian 2002 World Cup qualifiers. Australia 31 vs Samoa 0 with combined total of 31.
Sources: goalprofits, youtube, CBC SPORTS, Wikipedia
World Cup Match: Austria v Switzerland (1954) combined goal scored 12 with Austria 7 vs Switzerland 5
Sources: Wikipedia, FIFA, Youtube
English Premier League: Portsmouth 7 vs Reading 4 for combined total of 11 in 29th September 2007
Sources: whoateallthepies, skysports, BBC, therawstraw
Champions League: Borussia Dortmund 8 vs Legia Warsaw 4 for combined 12 goals in 22/11/2016.
Sources: DW, dailymail
La Liga: Athletic Bilbao 9 vs Racing Santander 5 (5 February 1933) with combined total of 14
Sources: wikipedia, espn
Bundesliga: With combined total of 12,

Borussia Mönchengladbach 12–0 Borussia Dortmund (matchday 34 of 1977–78)
Borussia Dortmund 11–1 Arminia Bielefeld (1982–83)
Bayern Munich 11–1 Borussia Dortmund (1971–72)
Borussia Dortmund 9–3 1. FC Kaiserslautern (1963–64)

FC Köln 8–4 Tennis Borussia Berlin (1976–77)

Sources: Wikipedia, bundesliga
Serie A: AC Milan 9 vs Atalanta 3, 1972/1973, for a combined total of 12
Sources: wikipedia, youtube, thegentlemanultra
Ligue 1: Sochaux 12 vs Valenciennes 1, 1935–36 for combined total of 13
Sources: wikipedia, footballdatabase
Update
Scottish Cup: Arbroath 36 vs Bon Accord 0 for combined total of 36 in 1885/86
Sources: goalprofits, wikipedia
UEFA Cup Winners' Cup: Sporting Club de Portugal 16 vs APOEL FC 1 for a combined total of 17 in 13/11/63, European Cup Winners' Cup first round first leg
Source: UEFA, Youtube
FA Cup: Preston North End 26 vs Hyde United 0 for combined total of 26 in 1887
Sources: bleacherreport

Some website shows Australia win over Samoa as 32-0.
I'm not sure about Ligue 1 that was the biggest one that I have found.
Comment: According to [italian Wikipedia](https://it.wikipedia.org/wiki/Statistiche_della_Serie_A#Record_risultati) the Serie A match with more goals is Milan-Atalanta 9-3 (total 12 goals) played on  [15/10/1972](https://it.wikipedia.org/wiki/Serie_A_1972-1973)
Answer: There is also a relevant case: Federated States of Micronesia national under-23 football team.

Their performance was the worst recorded in international football as they lost all three games, conceding 114 goals (an average of 38 goals each game) in the process without scoring themselves. On two occasions, against Fiji and Vanuatu, they conceded a record number of goals in international competition. However, although these matches count as official records for the Pacific Games, since the games did not involve senior teams, they will not be recognised by FIFA as official world records. Despite the unofficial nature of their record defeats, numerous international media outlets have branded them the worst football team on the planet.

Micronesia 0 - 30 Tahiti (3 July 2015)
Micronesia 0 - 38 Fiji (5 July 2015)
Micronesia 0 - 46 Vanuatu (7 July 2015)

So in this case, the highest combined number of goals was 46 (46+0).
Comment: @Nij I brought the debate to Meta: [How should we format results?](https://sports.meta.stackexchange.com/q/811/11439).
Answer: I find this match that seems the world record with 149 goals during a single match.
The results is caused by a protest on a refereeing decisions.
All the 149 were caused by deliberately own goals.
It is possible to find info about this match also on Wikipedia's article AS Adema 149–0 SO l'Emyrne:

AS Adema 149–0 SO I'Emyrne was an association football match played on 31 October 2002 between two teams in Antananarivo, Madagascar. It holds the world record for the highest scoreline, recognized by The Guinness Book of Records. SO l'Emyrne intentionally lost the game against their arch-rivals AS Adema in protest over refereeing decisions that had gone against them during a four-team playoff tournament. The match surpassed the previous record for the highest scoreline of 36–0, set in 1885.


How would I assign a Javascript variable to another Javascript variable? (a little confusing, i know)

Question: So, I have had a problem recently!
I was trying to assign a value to a variables value (a little confusing, i know). I was trying to make a library system for my Discord bot, which uses JavaScript (Node.js)!
So, here's a part of the code that I was struggling with:
    flist.forEach(item1 => {
        liblist.forEach(item => {
            eval(item1 = require(item));
        });
    });

OK, so basically item1 has to be replaced with a library file's name (if a file is named cmdh, I use that as a variable name to assign require(item) to it)
Edit: the item1 is the file name, by the way.
Edit 2: Here's a part of the file util.js:
const Discord = require("discord.js");
const fs = require("fs");
function genEmbed(title, desc, col) {
    return new Discord.MessageEmbed().setTitle(title).setDescription(desc).setColor(col);
};
function log(inp) {
    console.log(`[UTIL] ${inp}`);
};

function loadDef() {
    log("Loading libraries...");
    dirlist = [];
    liblist = [];
    flist = [];
    fs.readdir("./libraries", (err, dirs) => {
        if(err) console.error(err);
        dirs.forEach(dir => {
            dirlist.push("./libraries/" + dir);
        });
        dirlist.forEach(dir => {
            fs.readdir(dir, (err, files) => {
                if(err) console.error(err);
                files.forEach(file => {
                    if(file.includes(".")) {
                        liblist.push(require(dir + "/" + file));
                        filename = file.split(".")[0];
                        flist.push(filename);
                    } else {
                        log(`${file} is a directory, ignoring...`)
                    };
                });
            });
        });
    });
    flist.forEach(item1 => {
        liblist.forEach(item => {
            eval(item1 = require(item));
        });
    });
    log("Libraries loaded!");
};

module.exports = {
    genEmbed,
    loadDef
};

Comment: Seems like you want to use `map` rather than `forEach`.
Comment: On a side note, please read why you shouldn't be using eval: https://stackoverflow.com/q/86513/8186898
Comment: what do you mean, tkausl?
Answer: If you are trying to assign a new value for each element in an array and return a new array with the updated values, you should use map instead of forEach.
If you want to return an array with the required libraries from liblist and store the result in flist, your code should look as follows:
    flist = liblist.map(item => require(item));

Essentially, map takes each value from an array, applies a function to it (in your case, require), and then returns a new array with the results of the function.
It should be noted that you also need to replace fs.readdir with fs.readdirSync, otherwise liblist will be empty when the code is called.

After our discussion on the chat I understood that you want to set the variables as globals in your main file. However, this is a bit hackish. To do that you need to modify the global object.
Note: I would advise you to statically require via const libraryName = require('./libraries/fileName.js') instead, as this way of dynamically defining libraries has no advantage in this case and only makes the code more complicated. Dynamically requiring libraries only makes sense when you, for example, add listeners via your libraries, but then you do not need to store them as globals.
Your full code for the utils file should now look as follows:
const Discord = require("discord.js");
const fs = require("fs");
function genEmbed(title, desc, col) {
    return new Discord.MessageEmbed().setTitle(title).setDescription(desc).setColor(col);
};
function log(inp) {
    console.log(`[UTIL] ${inp}`);
};

function loadDef() {
    log("Loading libraries...");
    libraries = {};
    const dirlist = fs.readdirSync("./libraries").map(dir => "./libraries/" + dir)
    dirlist.forEach(dir => {
        const files = fs.readdirSync(dir)
        files.forEach(file => {
            if(file.includes(".")) {
                filename = file.split(".")[0];
                libraries[filename] = require(dir + "/" + file);
            } else {
                log(`${file} is a directory, ignoring...`)
            };
        });
    });
    log("Libraries loaded!");
    return libraries;
};

module.exports = {
    genEmbed,
    loadDef
};

Now you still need to modify the code in your main file, as follows:
const libraries = loadDef()
global = Object.assign(global, libraries) // assign libraries to global variables

Comment: @MantvydasViršilas you just have to replace the code snippet you posted above with the code snippet here. I will edit my post to show the full file as well.
Comment: It should be noted that you also need to replace `fs.readdir` with `fs.readdirSync`, otherwise `liblist` will be empty when the code is called.
Comment: @MantvydasViršilas did you replace `fs.readdir` with `fs.readdirSync`?
Comment: I have like no idea how to use it, can you please give me the code of the fixed file?
Comment: I also replaced the code lines, didnt work either (the readdirSync)
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/209996/discussion-between-omnidan-and-mantvydas-virsilas).
Comment: @MantvydasViršilas please give some information on what exactly does not work - what is the expected output, and what happened?


Disable PHPSESSID from URL

Question:
Possible Duplicate:
My web host is adding ?PHPSESSID=fgh2h45… to the end of the URL
How I can remove PHPSESSID in Symfony2

I develloped my website with Symfony 2,so I tried to remove PHPSESSID from URLs and I put In  /web/.htaccess this code :
    SetEnv SHORT_OPEN_TAGS 0
SetEnv REGISTER_GLOBALS 0
SetEnv MAGIC_QUOTES 0
SetEnv SESSION_AUTOSTART 0
SetEnv ZEND_OPTIMIZER 1
SetEnv PHP_VER 5_4
DirectoryIndex app.php
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ app.php [QSA,L]
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
#remove PHPSESSID
RewriteCond %{QUERY_STRING} PHPSESSID=.*$
RewriteRule .* %{REQUEST_URI}? [R=301,L]
</IfModule>

then I remark the code above disable the PHPSESSID,but it creat another problem,I have app.php appears in all URLs of my website :
www.mysite.com/app.php/.....

So I dont know what I can do,I guess I have the new problem because I used a multiple RewriteRule.
Comment: @j0k Yea it's maybe the same subject but it's not the same problem...
Answer: Instead of rewriting the URL to remove PHPSESSID, configure php to use cookies for session:
in php.ini:
session.use_cookies=1
session.use_only_cookies=1
session.use_trans_sid=1

OR in .htaccess:
php_flag session.use_cookies 1
php_flag session.use_only_cookies 1
php_flag session.use_trans_sid 1

OR in php - in some file that is included in all the pages, before session_start():
<?php
ini_set("session.use_cookies", 1);
ini_set("session.use_only_cookies", 1);
ini_set("session.use_trans_sid", 1);
?>

And, last but not least, lets do this with mod_rewrite anyway:
<IfModule mod_rewrite.c>
RewriteEngine On

# first, remove PHPSESSID and redirect
RewriteCond %{QUERY_STRING} ^(.*)PHPSESSID=[^&]*(.*)$
RewriteRule .* %{REQUEST_URI}?%1%2 [R=301,L]

# then, silently rewrite everything to app.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ app.php [QSA,L]
</IfModule>

This way, only PHPSESSID=smth parameter is removed, the rest of the query-string is passed through.
Comment: `session.use_trans_sid` needs to be set to `0` (not `1`) to disable passing session ID in URL!
Comment: Your solution is correct,but Im using OVH so I dont have php.ini and for .htaccess when I do like your second solution I have error 500...
Answer: You are rewriting the URI to app.php before you are doing the redirect that removes the PHPSESSID from the query string. You want to do that before so that the %{REQUEST_URI} doesn't get rewritten.
Try replacing everything under DirectoryIndex app.php with this:
<IfModule mod_rewrite.c>
RewriteEngine On

# remove PHPSESSID first
RewriteCond %{QUERY_STRING} PHPSESSID=.*$
RewriteRule .* %{REQUEST_URI}? [R=301,L]

# rewrite to app.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ app.php [QSA,L]

</IfModule>

Comment: There will be side-effects with that.. if OP only wants to remove PHPSESSID parameter from uri, this approach will wipe the whole query-string...
Comment: @Jon Lin I tried your new code and that works fine till now,I dont know maybe app.dev appears again so I will wait because I did the same code before it didn't work but it working now!

Disable PHPSESSID from URL


Django: Annotation on Subquery

Question: I'm trying to annotate a queryset of Stations with the id of the nearest neighbouring Station using Django 2.0.3 and PostGIS (GeoDjango) functions.
Simplified Station model:
class Station(models.Model):
    name = models.CharField(max_length=128)
    location = models.PointField()
    objects = StationQuerySet.as_manager()

The problem I'm having is trying to compute the closest distance, which involves annotating a subquery which refers to the location in the outer queryset.
from django.db.models import OuterRef, Subquery
from django.contrib.gis.db.models.functions import Distance

class StationQuerySet(models.QuerySet):

    def add_nearest_neighbour(self):
        '''
        Annotates each station with the id and distance of the nearest neighbouring station
        '''
        # Get Station model
        Station = self.model

        # Calculate distances to each station in subquery
        subquery_with_distance = Station.objects.annotate(distance=Distance('location', OuterRef('location')) / 1000)

        # Get nearest from subquery
        nearest = subquery_with_distance.order_by('distance').values('id')[0]

        return self.annotate(
            nearest_station_id=Subquery(nearest)
        )

The line distance = Station.objects.annotate(distance=Distance('location', OuterRef('location')) / 1000) results in an error seen below:
from apps.bikeshare.models import Station
stations = Station.objects.add_nearest_neighbour()

Error:
Traceback (most recent call last):
  File "/home/gbrown/Envs/bikeshare-dev/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2847, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-3-cb35ea6d5d8b>", line 1, in <module>
    stations = Station.objects.add_nearest_neighbour()
  File "/home/gbrown/Envs/bikeshare-dev/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/gbrown/Development/transit_bikeshare/apps/bikeshare/querysets.py", line 162, in add_nearest_neighbour
    subquery_with_distance = Station.objects.annotate(distance=Distance('location', OuterRef('location')) / 1000)
  File "/home/gbrown/Envs/bikeshare-dev/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/gbrown/Envs/bikeshare-dev/lib/python3.5/site-packages/django/db/models/query.py", line 997, in annotate
    clone.query.add_annotation(annotation, alias, is_summary=False)
  File "/home/gbrown/Envs/bikeshare-dev/lib/python3.5/site-packages/django/db/models/sql/query.py", line 975, in add_annotation
    summarize=is_summary)
  File "/home/gbrown/Envs/bikeshare-dev/lib/python3.5/site-packages/django/db/models/expressions.py", line 452, in resolve_expression
    c.lhs = c.lhs.resolve_expression(query, allow_joins, reuse, summarize, for_save)
  File "/home/gbrown/Envs/bikeshare-dev/lib/python3.5/site-packages/django/contrib/gis/db/models/functions.py", line 58, in resolve_expression
    source_fields = res.get_source_fields()
  File "/home/gbrown/Envs/bikeshare-dev/lib/python3.5/site-packages/django/db/models/expressions.py", line 349, in get_source_fields
    return [e._output_field_or_none for e in self.get_source_expressions()]
  File "/home/gbrown/Envs/bikeshare-dev/lib/python3.5/site-packages/django/db/models/expressions.py", line 349, in <listcomp>
    return [e._output_field_or_none for e in self.get_source_expressions()]
AttributeError: 'ResolvedOuterRef' object has no attribute '_output_field_or_none'

Comment: Can you post the full stack trace?
Comment: @solarissmoke I've updated the question to include the full stack trace
Comment: Hmm. There was a bug around subquery/outerrefs pointing to foreign keys at some point. I wonder if this queryset would work now...
Comment: @MatthewSchinckel in case it's useful, I've got the exact same problem on Django 3.2, so I don't think it's been fixed.
Comment: It may have been fixed after 3.2
Comment: Still happens on Django 4.2.2 for me
Answer: Came up with a work around using a raw query to find the nearest station and select the id AND distance from the subquery, bonus explanation below:
class StationQuerySet(models.QuerySet):

    def nearest_neighbour(self):
        '''
        Creates a RawQuerySet of each station with the id and distance of the nearest neighbouring station
        '''
        # Have to execute the query in order to get the list of ids to inject
        ids = tuple(self.values('id').values_list('id', flat=True))

        return self.raw('''
               SELECT
                 A0.id   as id,
                 SUB.closest_id,
                 SUB.closest_distance
               FROM "bikeshare_station" A0
                 CROSS JOIN LATERAL (
                            SELECT
                              B0.id   as closest_id,
                              st_distance_sphere(A0.location, B0.location) as closest_distance
                            FROM "bikeshare_station" B0
                            WHERE A0.id != B0.id
                            ORDER BY A0.location <-> B0.location
                            limit 1
                            ) SUB
               WHERE A0.id IN %s;
           ''', [ids])

Usage
You can chain querysets calls together to filter down the queryset before finding the nearest neighbour:
query = Station.objects.filter(name='Albert Gate, Hyde Park')
closest_stations = query.nearest_neighbour()
station = closest_stations[0]
station.name
[out]: 'Albert Gate, Hyde Park'
station.closest_distance
[out]: 133.52459069
station.closest_id
[out]: 6369

SQL Explanation
This type of subquery is called a correlated subquery because it references columns in the outer query. In addition, I need to select multiple pieces of information about the nearest station (id, distance, etc.).
The subquery is placed in the FROM clause, which allows multiple columns to be selected. A LATERAL join is needed to allow the subquery to reference the sibling table in the FROM list. With the subquery returning a single row, a CROSS join can be applied to form a joined table based on the cartesian product rather than on a shared column.
The subquery uses the PostGIS <-> operator, which is much more efficient at ordering the table by distance between the stations, and st_distance_sphere, to do an accurate distance calculation between the points.
Comment: Yeah, it's not possible to do a LATERAL join in the ORM. It's certainly something I'd love to have.

Django: Annotation on Subquery


Removing a node with two children in a Binary Tree

Question: So this is the code that I have so far.  I think I've got the logic down for the most part but I'm stuck on the part with two children.. I've figured out what sort of algorithm I have to use to make it work (I've annotated with comments at the bottom of the function), I'm just not sure how to start... Can anyone point me in the right direction??
Heres what I have so far:
void BinaryTree::remove(int data){
// Is the data valid?
if(data < 0){
    cerr << data << " is not valid.  Must be a positive integer value."  << endl;
}
else{
    // Find the node
    BinNode* loc = root;
    BinNode* parent = nullptr;
    bool found = false;
    while(!found && loc != nullptr){
        if(data > loc->data){
            parent = loc;
            loc = loc->right;
        }
        else if(data < loc->data){
            parent = loc;
            loc = loc->left;
        }
        else found = true;
    }

    // If there is a parent, take care of the pointer
    if(parent != nullptr){
        if(loc->data < parent->data)
            parent->left = nullptr;
        else if(loc->data > parent->data)
            parent->right = nullptr;
    }
    // If there are children, save pointers to them
    BinNode* leftChild = nullptr;
    BinNode* rightChild = nullptr;
    if(loc->left != nullptr)
        leftChild = loc->left;
    if(loc->right != nullptr)
        rightChild = loc->right;

    // So now pointers to the children have been saved (if they exist) and
    // parent pointers have been taken care of (if they exist) the node can be deleted
    // If no children exist simply just delete the node and return
    delete loc;
    // If one child exists
    if(leftChild != nullptr || rightChild != nullptr){
        if(leftChild != nullptr){
            if(leftChild->data < parent->data)
                parent->left = leftChild;
            else if(leftChild->data > parent->data)
                parent->right = leftChild;
        }
        else if(rightChild != nullptr){
            if(rightChild->data < parent->data)
                parent->left = rightChild;
            else if(rightChild->data > parent->data)
                parent->right = rightChild;
        }
    }

    // Both children exist...this sucks.
    else if(leftChild != nullptr && rightChild != nullptr){
        // Find a minimum in the right subtree
        BinNode * min = root;
        BinNode * minParent = nullptr;
        while(min->left != nullptr){
            minParent = min;
            min = min->left;
        }
        // Replace value of the node to be removed with the found minimum
        loc = new BinNode(min->data);

        // Delete the remaining duplicate node
        if(minParent != nullptr)
            minParent->left = nullptr;
        delete min;
    }
}
}

Comment: This is a binary search tree (http://en.wikipedia.org/wiki/Binary_search_tree), not just a binary tree. See http://en.wikipedia.org/wiki/Binary_search_tree#Deletion
Comment: How would I perform a removal in a normal binary tree?
Comment: A binary tree has less structure than a binary search tree, so you can pick any leaf node and swap it into place. You're asking me, "If I know how to read an inscribed block of wood, how do I read a block of wood?" Answer: Any way you want.
Comment: ....lol ok thanks lemme delete my whole function...jk
I'll figure out how to fix this for a BST properly.
Comment: A binary search tree is a binary tree that keeps its elements in a certain order. Your code shows that you're using a binary search tree (since you check the order). The Wikipedia link should be helpful.
Answer: Here we are.  This seems to work.  If anyone has any suggestions as to how I can optimize this or a problem that I need to fix please speak up! Thanks!
void BinaryTree::remove(int data){
// Is the data valid?
if(data < 0){
    cerr << data << " is not valid.  Must be a positive integer value."  << endl;
}
else{
    // Find the node
    BinNode* loc = root;
    BinNode* parent = nullptr;
    bool found = false;
    while(!found && loc != nullptr){
        if(data > loc->data){
            parent = loc;
            loc = loc->right;
        }
        else if(data < loc->data){
            parent = loc;
            loc = loc->left;
        }
        else found = true;

    // If there are children, save pointers to them
    BinNode* leftChild = nullptr;
    BinNode* rightChild = nullptr;
    if(loc->left != nullptr)
        leftChild = loc->left;
    if(loc->right != nullptr)
        rightChild = loc->right;

    // So now pointers to the children have been saved (if they exist) and
    // parent pointers have been taken care of (if they exist) the node can be deleted
    // If no children exist simply just delete the node and return

    // Check if two children exist
    if(leftChild != nullptr && rightChild != nullptr){

        // Find a minimum in the right subtree
        BinNode * min = loc->right;
        BinNode * minParent = loc;
        while(min->left != nullptr){
            minParent = min;
            min = min->left;
        }
        // Replace value of the node to be removed with the found minimum
        loc->data = min->data;

        // Delete the duplicate
        if(minParent != loc)
            minParent->left = nullptr;
        else minParent->right = nullptr;
        delete min;
    }

    // If one child exists
    // Need to handle if it is the root here
    // change root pointer to remaining child
    else if(leftChild != nullptr || rightChild != nullptr){
        // If there is a parent, take care of the pointer
        if(parent != nullptr){
            if(loc->data < parent->data)
                parent->left = nullptr;
            else if(loc->data > parent->data)
                parent->right = nullptr;

        // Now loc can be deleted
        delete loc;
        if(leftChild != nullptr){
            if(parent != nullptr){
                if(leftChild->data < parent->data)
                    parent->left = leftChild;
                else if(leftChild->data > parent->data)
                    parent->right = leftChild;
            }
            // If it is the root
            else{
                root = leftChild;
            }
        }
        else if(rightChild != nullptr){
            if(parent != nullptr){
                if(rightChild->data < parent->data)
                    parent->left = rightChild;
                else if(rightChild->data > parent->data)
                parent->right = rightChild;
            }
            // If it is the root
            else{
                root = rightChild;
            }
        }
    }

    // If there are no children
    else if (leftChild == nullptr && rightChild == nullptr){
        // If there is a parent, take care of the pointer
        if(parent != nullptr){
            if(loc->data < parent->data)
                parent->left = nullptr;
            else if(loc->data > parent->data)
                parent->right = nullptr;
        }
        // If it is the root
        else
            root = nullptr;
        delete loc;
    }
}


Are military/missionary expat life-styles off topic?

Question: I'm thinking that military and missionary lives, and perhaps a few other types of work abroad, are more strongly defined by the organization sponsoring the stay abroad than the specific surrounding the stay is happening in.
Thus questions concerning military or missionary staff are best answered by understanding the military or church responsible, rather than the country they are stationed in.
Answer: I think these need to be taken on a case-by-case basis. I am guessing most overseas military personnel don't consider themselves expats and might actually get offended at being labelled as such. Military personnel tend to have a big support network while missionaries are often isolated. They all face many of the same issues expats face like getting used to weather, food, local customs and homesickness. I don't see why a missionary asking where to buy Vegemite in the States should make the question off topic.
Comment: +1 But I don't think we should be too concerned about the fact that people consider themselves as "expats" or not. For example, "expat" is often a word used by highly educated/well-paid professionals from rich countries but I see no reason to refuse questions from people interested in migrating that don't fit the stereotype.
Comment: The experience of a Java programmer and a Lisp programmer is also quite different but they both fit perfectly on Stack Overflow. The same applies here. Expats is not a label, it's just the name of a website. You couldn't call it "expats and overseas servicepersons and missionaries" because it would be too unwieldy. It's all stuff that can be laid out in more text somewhere than the text in the site's name.
Comment: +1 Yes, the experience of an airman stationed abroad at a base is quite different from that of an ESL teacher in a village in the same country, but not much more so than being an oil executive sent to manage operations near the port or a diplomat assigned to the capital. Also consider that families and SOs may accompany personnel sent overseas, and may be less insulated.
Comment: @GaëlLaurans I agree and didn't mean to imply that. I was trying to say that the overseas military people I know, and to an extent the missionaries, they don't immerse themselves in the culture. This could be my US centric view of military personnel.
Answer: I think en masse the life of a military personnel or people doing missionary work still qualifies as expat because they need to make a life in a different country.  Granted that military personnel normally live on the base rather then in the general population but there is no avoidance of interaction with the local people and culture, so I would say that these questions should be on topic.
Comment: Aren't soldiers deployed to Afghanistan stricly forbidden to leave bases other than on missions?
Comment: @vartec May be they are but Afganistan isn't the only overseas deployment spot available for US military personnel
Comment: Actually I wasn't referring only to US soldiers. For most European soldiers that's the only singificant overseas deployment.
Comment: https://en.wikipedia.org/wiki/List_of_countries_with_overseas_military_bases, while you are right about most countries some have presence outside their home base.  And they are not the only ones that may be interested.
Answer: If you're stationed abroad and have to do things like drive to work, obey the laws, keep your visa current and everything else, I don't really see how it would be a distinguishing factor.
Off-topic versions of these would tend to evidence themselves pretty quickly like:

This question is really about Habitat For Humanity, not really an expat thing.

or perhaps

This is more of a question about military life, it's not complicated by where you're stationed.

Our general litmus test of the question author needing to show us how their question takes a twist because of their status as an expat should be all we need to spot the difference.
I also might not be interpreting your question correctly, forgive me if I'm not, I read it a few times and I think this is what you were getting at.
Answer: I don't buy the premise. Yes, people who live abroad as part of an organization sometimes have access to infrastructure the average person abroad does not have, but that doesn't mean they are insulated from contact with the culture.
I've known enough of both missionaries and military folk to know that their support system is less substantial than you may think it is (especially the missionaries, who are often utterly alone), and their contact with the culture is deeper than you might expect.
Moreover, no matter how strong their existing support system is, they may still have issues that are best explored outside that system. Consider the case of a woman who is on birth control not primarily for contraception but to regulate her hormonal cycle. Whether military or missionary, in either case it may be embarrassing or even professionally detrimental for her to ask questions within her organization about sourcing birth control in the new country. Colleagues gossip, rumors spread.
Are we supposed to turn her away saying "No, I'm sorry, your experience is too defined by your organizational role. You're not expat enough for us."?
I worry that this site has a risk of becoming, to coin a word, expatronizing.
I understand that it is important in the early days to try to define clearly what the site is and is not about, but I think there is a very simple guiding principle for that, which draws on the premise underlying every StackExchange site: Will this question connect the questioner with an expert who can help them, and the expert with a question they feel inspired to answer?
There are cases where someone will come to this site and ask a question that no one has the expertise to answer, such as "What are the medical facilities like at the Rammstein Air Base?" And in those cases, we will tell them we don't have the expertise, and a military families' forum may have the information they need. But if they're asking "Will I be able to buy a car in Japan without relicensing myself under a Japanese driver's license?" this is the place to find that expertise, regardless of what organization is ostensibly structuring and "defining" their experience.
This is very similar to the situation StackOverflow faced with homework questions. There was debate for some time over whether those questions should be answered, how they should be tagged, etc. In the end, the homework tag was deprecated because the source of the question is not as relevant as its content. If the question offers a legitimate problem to a community of experts who have legitimate expertise to solve it, then it's a good question whether the asker is a student or a professional.
Sort-of-but-not-exactly expats are going to be the "homework questions" of this site. I hope we will choose to answer them on the basis of the quality of the question itself, not the specifics of the asker.

p.s. Full disclosure: I am definitely a "homework question" variety of expat myself. I've bought groceries hundreds of times while working and living in a place, but I've never established a permanent new home. I'll be on this site as more of a questioner than an expert most of the time, so I certainly have a bias of personal investment in the arguments I make above. The expat lifestyle I aspire to is more of a "live one or two years in one place, then move to an another, freelancing along the way" one that lacks the kind of permanent intention some of you seem to see as essential to being an expat. I'd like to feel welcome here, and I'd like to see students and missionaries and oil company contractors and military people welcome here, too.
Comment: Makes good sense the way you put it - clear analogy to the homework issue on stackoverflow. My question didn't have personal intentions, I'm just trying to figure out how this Q&A format works.
Comment: I understand, and it is absolutely not taken personally. We are both just participating in the necessary process of mapping out the site's boundaries. Totally healthy and normal!


Does the Spring-Flex 1.5 Sample work?

Question: The samples and documentation in question can be found here: http://static.springsource.org/spring-flex/docs/1.5.0.M1/
The reference doc ( here ) tells us to download the sample application:

Included in the project distribution
  is a collection of samples called the
  Spring BlazeDS Integration Test Drive.
  This samples project is set up to be
  built with Maven and then imported
  into Eclipse for running the
  application via WTP.

The samples in question, must either be spring-flex-testdrive-spring3.zip which is linked to in the document or spring-flex-testdrive-spring3.zip based on the notion that this is release 1.5.0.M1 (docs and samples).
After I configure maven as described with the proper environment variable:
MAVEN_OPTS="-Xms256m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=256m"

I then execute (per instruction) the command to install: mvn clean install from the extracted samples directory (in my case C:\spring-flex-testdrive ), I receive the following error:
C:\spring-flex-testdrive>mvn clean install
[INFO] Scanning for projects...
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project org.springframework.flex.samples:spring-flex-testdrive:1.5.0.M1 (C:\spring-flex-testdrive\pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM: Failure to find org.springframework.flex:spring-flex-parent:pom:1.5.0.M1 in http://maven.springframework.org/external was cached in the local repository, resolution will not be
reattempted until the update interval of spring-external has elapsed or updates are forced and 'parent.relativePath' points at wrong local POM @ line 5, column 10 -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException
C:\spring-flex-testdrive>

I have managed to get a "Spring BlazeDS" application working (with Flex), but now I'm at the point where I need to implement security, and if the samples would compile and run correctly, it'd be a huge help.  I am new to Maven, but any help would be greatly appreciated!
Thanks in advance StackOverflow community!
Comment: Well, I've yet to figure out any additional configuration changes I need to make.  I've tried to follow along with the [sonatype / flexmojos FAQ](https://docs.sonatype.org/display/FLEXMOJOS/FAQ#FAQ-1.3) , but I'm not really sure where I need to "manually" install my flex/flashbuilder jars ( license.jar ?) nor what I need to change about the root **pom.xml** .  Any more thoughts?

My env. vars are: http://pastie.org/1549766
Answer: Brian, please add the following snippet to the pom.xml in the root of the samples (from where you execute mvn clean install) and re-run Maven:
    <repository>
        <id>spring-milestone</id>
        <name>Spring Milestone Repository</name>
        <url>http://maven.springframework.org.s3.amazonaws.com/milestone</url>
    </repository>

Hope that helps.
Christian
Comment: thank you so much for the help - we're getting there!  I'm quite sure the application made it through the majority of the install.  Here's my latest output from Maven: http://pastebin.com/x8XFHjej

I thought that was pretty good, so I re-ran just **mvn install** and had the following output from Maven: http://pastebin.com/nBnFGzTG
Answer: I get the same error.  Spring Flex 1.5M2 will be out very soon.  So maybe give it another try with that.
Comment: Thanks @James Ward and @CK Lee , if nothing else, it's good to know I'm not the only one.  As soon as I work it out, I'll be sure we have all of the answers here.  I think I may need to place a license.jar file for FlexBuilder / FlashBuilder on my classpath , researching that now.
Answer: I would recommend that if go with Parsley for Actionscript/Flex framework.  It is more mature in may ways than Spring-Actionscript.  Moreover it is a required library for much of Cairngorm 3.  Good luck.
Comment: Thanks @Androider , but I was under the impression that a stack that included Java & Flex sort of assumed Spring as part of the standard implementation based on [Adobe's site](http://www.adobe.com/devnet/flex/flex_java.html) and [Spring's site](http://www.springsource.org/spring-flex) .

Anyone else have any thoughts on making this work?  I am new to Maven, but all of the samples seem to indicate it's pretty easy...
Comment: I thought you were talking about Spring-Actionscript.  sorry

Does the Spring-Flex 1.5 Sample work?


Creating a test set with imbalanced data

Question: I am working on a binary random forest using R. mu data set consists of 300 cases classes 1 and 2100 cases class 0. I am planning to evaluate my model using the model prediction and the AUC and for that I need a test date set. I would be able to create a test data set with approximately 300 samples but all the samples will fall on the class 0. Would this influence the performance evaluation of my model?
Another approach to this problem is to create a training data set with 70% of class 1 cases and 70% of class 0 and them when running my random forest code I will use sampsize command to get the same number of samples per tree in my model and eliminate the imbalance problem. The vector would be c( 210, 210). My test set for evaluating the model and calculating the AUC would be the remaining 30% cases of class 1- 90 samples- plus 90 unseen cases from class 0.
I am not sure about this as I am wasting a lot of data. But , I think it is better than creating a test set with 0 instances of class 1.
Answer: If your data set is unbalanced and separation is not perfect. Your RF-model will very sensibly predict all samples to be of the most prevalent class of the training set. Your RF model essentially implement a 'belief' of class distribution of future predictions equal to your training set being 2100:300. If you have reason to disagree(domain knowledge) or if the costs of false prediction are very unequal for the classes you may correct this belief. See the first link to a thread below, where this 'belief' is graphically depicted for a 3-class problem.
You are not "throwing data away" by setting sampsize = c(210,210) as all samples will be present in at least some trees. Perhaps increase ntree=1000 to make sure that happens. Sampsize = c(300, 300) will work fine also because of sample replacement in bootstrap. As you model the difference between the two classes, excessive extra examples of one class only, will not provide extra information.
When using stratification(sampsize) or classwight you're are probably only slightly improving prediction performance described as AUC of ROC. Instead the you essentially modify the prior belief of class distribution, such that the rare class will win more majority votes on the expense of many(not all) of these predictions being wrong.
To validate: Compute AUC of and plot the ROC of out_of_bag votes distribution vs. true class
If to compare with other models, embed all models in a repeated 10-fold CV and compute the AUC and ROC for all models.
Here's thread on the coding and plotting.
Here's a thread on classweights which I do not cover
Comment: Soren your answer is fab. Many thanks. Do you think that I don't need a test set to evaluate the performance of the model? You mentioned that c(300,300) will work just fine. I am not sure if it is a good idea to use the predictions from my training data to calculate the AUC.Would this not cause overfitting?
Comment: I run the code for above and as I was expecting the AUC very close to 1. I have decided to keep the test set for the performance evaluatetion but my question is:should I use the probabilities from the training and test set together to calculate the AUC? or is there any way to evaluate my test set using somehow the probalities from the training set? I would really appreciate any feedback on these two approches.
Comment: Thx :) You could use OOB-CV or a outer test-set validation as you like. If you also perform some feature selection or signal processing, you should wrap your entire pipeline in a CV of some kind. Otherwise OOB is just fine. Check out the definition of the output value "votes" in the randomForest, these are cross-validated already. I would plot these in a ROC plot as last lines of the referenced code-example. Such plot depicts your expected trade-of of specificity and sensitivity. An AUC could be calculated also.


Number theory with binary quadratic

Question: I found this questions from past year maths competition in my country, I've tried any possible way to find it, but it is just way too hard.
Given $$ \frac {x^2-y^2+2y-1}{y^2-x^2+2x-1} = 2$$ find $x-y$
I'm not sure if given choices is right... (A)2 (B)3 (C)4 (D)5 (E)6
I've tried to move them $$x^2-y^2+2y-1 = 2y^2-2x^2+4x-2$$
$$x^2-y^2+2y-1 - 2y^2+2x^2-4x+2 = 0$$
$$3x^2-3y^2+2y-4x+1=0$$
$$(3x-1)(x-1)-(3y-1)(y+1)+1=0$$
I've stuck in here, not sure if I've found x and y, or not...
EDIT: I've move other questions to other posts, thanks for helping me identifying the questions category.
Comment: lets try to keep it at one problem per post please.
Comment: Limiting to one question per question would help with your tagging woes, too :-)
Comment: @wuiyang All questions should have the tag contest-math. Furthermore 1,2,3,5,6,7 should have the tag algebra-precalculus. 4,8,9 should have the tag elemetary-number-theory. 7 should have the tag polynomials.
Comment: @dREaM i can't identify most of these question's category
Comment: @wythagoras thanks, I will edit the questions now
Comment: @wuiyang No, please post them in 9 seperate questions, each containing exactly one problem. Furthermore, please post your thoughts for each of the problems.
Answer: Recognize the squares of binomials in both the numerator and denominator to rewrite the equation as $$\begin{align}\frac{x^2-(y-1)^2}{y^2-(x-1)^2} &= 2, \end{align}$$ and thus, factoring, $$\require\cancel \begin{align}\frac{(x-y+1)\cancel{(x+y-1)}}{(y-x+1)\cancel{(y+x-1)}}&=2. \end{align}$$ Finally, let $t=x-y$ and multiply both sides by $1-t$ to have $$\begin{align} t+1&=2(1-t) \\ 3t&=1 \\ t&=\frac{1}{3}. \end{align}$$
Answer: Put $t=x-y$  then $x=y+t.$ Substitute it into the expression you get $${\frac {t+1}{1-t}}=2.$$
By solving it  you get $t=\dfrac{1}{3}.$
Answer: \begin{align} 2&=  \frac {x^2-y^2+2y-1}{y^2-x^2+2x-1} \\
 &=\frac {x^2-(y^2-2y+1)}{y^2-(x^2-2x+1)} \\
 &= \frac {x^2-(y-1)^2}{y^2-(x-1)^2} \\
 &= \frac {(x-y+1)(x+y-1)}{(y+x-1)(y-x+1)}\end{align}
$$\implies  {x-y+1}=2y-2x+2\\
3(x-y)=1 $$
Thus, $x-y=\dfrac13$

Number theory with binary quadratic


scipy curve_fit returning initial parameter estimates

Question: I am trying to use scipy curve_fit to fit a gaussian function to my data, for which there are MANY helpful examples on the web, and I have tried to get several to work, but to no avail.  I wrote a simple script using made-up data to diagnose the problem.  In short, curve_fit is not doing any fitting, the function is just returning the initial parameter values, no matter how close they are to the real numbers.  Here is the code for the simple script:
# -*- coding: utf-8 -*-
import numpy
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from scipy import optimize

##Fit
def Fit( datax, datay ):
    # define your function:
    def f(x, *p):
        p = m, b
        return m*numpy.asarray(x) + b
    m = 0.4
    b = 2.4
    p_init = [m, b]
    Initial_model = f(datax, [m, b])
    plt.plot(datax, Initial_model, label='Initial Model')
    plt.title("Initial Model")
#    plt.title('Initial Model')
#    plt.show()
   # fit! (given that data is an array with the data to fit)
    print optimize.curve_fit(f, datax, datay, p_init)
    coeff, var_matrix = optimize.curve_fit(f, datax, datay, p_init)
    global fit
    fit = f(datax, *coeff)
    plt.plot(datax, fit, 'r-')
    plt.show()
    print 'Fitted slope 1 = ', coeff[0]
    print 'Fitted intercept 1 = ', coeff[1]
    return fit

##Plot
def Plot( datax, datay, fit ):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.plot(datax, datay, 'b*')
    l = ax.plot( datax, fit, 'r-', linewidth=2)
    ax.set_xlabel('Rate')
    ax.set_ylabel('Return')
    ax.set_title("Test")
    ax.autoscale(enable=True, axis='both', tight=None)
    ax.grid(True)
    plt.show()

##data
datax = numpy.array([7.02, 20.06, 13.78, 16.92, 10.17], dtype=numpy.float64)
datay = numpy.array([5.14, 10.66, 8.44, 9.64, 6.79], dtype=numpy.float64)

##analyze
Fit( datax, datay )
Plot( datax, datay, fit )

Out:
(array([ 0.4,  2.4]), inf)
Fitted slope 1 =  0.4
Fitted intercept 1 =  2.4

Things I have tried:
-using leastsq directly: same problem
-reinstalling scipy: no change
I am using Anaconda on Windows 7.
What could be the problem?
Comment: What happend is you add noise to your data and change the initial guess so it is no longer the same as the actual parameter?
Answer: Your definition of f() is peculiar and does not do what you want.  You are assigning m and b to p thus overwriting whatever was passed in.  This is why the parameters never appear to change, because they don't change!
There is no need to define f() in a peculiar way, just define it the way that makes sense listing the parameters as you normally would.  For your simple case of fitting a line we can use
def f(x, m, b) :
    return m*x + b

The only other change needed is
Initial_model = f(datax, *p_init)

and your code will run.


What to do with negative Chow test?

Question: I have just done a Chow test on a regression in order to see whether there is a structural break. I am a bit stumped however as my Chow test returns a negative number. Now what do I do?
More specifically, this expression (from the Wikipedia entry for the Chow test):
$\frac{(S_c-(S_1+S_2))/(k)}{(S_1+S_2)/(N_1+N_2-2k)}$
turns out negative for me.
EDIT: It turns out it was a simple programming error.
Comment: Does your regression has an intercept? Omitting intercept sometimes can cause problems. Also could you post reproducible example? It is clear that you made an error, as @onestop pointed out, but with example available it may be possible to point out where the error is exactly.
Comment: Cheers! Thanks for your edit. Simple programming errors are the biggest enemy of scientific progress :)
Answer: You've made a mistake somewhere in your calculations. It's not possible for the sum of the squared residuals from a single regression using the combined data to be less than the sum of the sums of squared residuals from the regressions using the two separate sets of data.

What to do with negative Chow test?


The top bar color when app is inactive. (Cordova)

Question: I am developing a mobile App hybrid based on the cord, until now I'm doing well, but I can not change the color of the top bar when the application is inactive! Android 5.1 Cordova 5.3.3 I'm using the plugin (cordova_plugin-statusbar 1.0.1): https://www.npmjs.com/package/cordova-plugin-statusbar
Comment: http://i.stack.imgur.com/NSQPI.png
Answer: Long time this since this question was created but I just jumped into the same issue.
cordova-plugin-statusbar is not your plugin, you need cordova-plugin-headercolor to update the color in multitask view -> https://github.com/tomloprod/cordova-plugin-headercolor.


Saving object caused NullPointerException in Insert statement

Question: I have a problem when saving an object with SQLite in Android.
Below is my DAO class:
public class FundkDAO implements Dao<Training> {
    private SQLiteDatabase db;
    private SQLiteStatement insertStatement;
    private String DB_Table = "training";
    private String INSERT = "insert into " + DB_Table
        +"(" +
        "id," +
        "nameuser," +
        "kategorie," +
        "uebung," +
        "gewicht," +
        "datum" +
        ")" + " values (?,?,?,?,?,?)";
    private String SEL_ROW =
        "id," +
        "nameuser," +
        "kategorie," +
        "uebung," +
        "gewicht," +
        "datum " +
        "from "
        + DB_Table;
    private String CREATE_TABLE = "create table " + DB_Table
        + "(id INTEGER PRIMARY KEY AUTOINCREMENT, "
        + "  nameuser String, "
        + "  kategorie String, "
        + "  uebung String, "
        + "  gewicht DOUBLE, "
        + "  datum String)";

    public FundkDAO(SQLiteDatabase db) {
        this.db = db;
        try {
            insertStatement = db.compileStatement(INSERT);
            Log.d("ANDRO VEGI", "Create INSERT product");
        } catch (SQLException e) {
            Log.d("ANDRO VEGI", "NO Database, NO INSERT  TrainingsplanDao()");
        }
    }

    @Override
    public long save(Training type) {
        insertStatement.clearBindings();
        insertStatement.bindString(2, type.getNameuser());
        insertStatement.bindString(3, type.getKategorie());
        insertStatement.bindString(4, type.getUebung());
        insertStatement.bindDouble(5, type.getGewicht());
        insertStatement.bindString(6, type.getDatums());
        return insertStatement.executeInsert();
    }

    @Override
    public void update(Training type) {
        db.delete(DB_Table, "id" + " = ?", new String[] {String.valueOf(type.getId())});
        db.close();
    }

    @Override
    public void delete(Training type) {
        db.delete(DB_Table, "id" + " = ?", new String[] {String.valueOf(type.getId())});
        db.close();
    }

    @Override
    public Training get(long id) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Training get(String string) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<Training> getAll() {
        List<Training> list = new ArrayList<Training>();
        Cursor cs = db.rawQuery(SEL_ROW, new String[]{});
        if (cs.moveToFirst()) {
            do {
                list.add(buildProductFromCursor(cs));
            } while (cs.moveToNext());
        }
        return list;
    }

    public void createTable() {
        db.execSQL(CREATE_TABLE);
        try {
            insertStatement = db.compileStatement(INSERT);
            Log.d("ANDRO VEGI", "Create INSERT MAKROS");
        } catch (SQLException e) {
            Log.d("ANDRO VEGI", "NO Database, FAIL createTable(MAkrosDAO())");
        }
    }

    private Training buildProductFromCursor(Cursor cs) {
        Training makros = null;
        if (cs == null) {
            Log.e("Internal Error", "no cursor  MakrosDao()");
        } else {
            makros  = new Training(cs.getInt(0),cs.getString(1),cs.getString(2),cs.getString(3),cs.getDouble(4),cs.getString(5));
        }
        return makros;
    }
}

Here is the initalisation:
db = new OpenHelper(this).getWritableDatabase();
FundkDAO tdDao = new FundkDAO(db);

The table is created in the OpenHelper class so the problem cannot be there.
When saving an object, I get a NullPointerException in FundkDAO Save method.
Here's the LogCat output:
09-18 13:42:25.020: E/SQLiteLog(6314): (1) table training has no column named datum
09-18 13:42:25.030: E/AndroidRuntime(6314): FATAL EXCEPTION: main
09-18 13:42:25.030: E/AndroidRuntime(6314): Process: com.example.trainingslog, PID: 6314
09-18 13:42:25.030: E/AndroidRuntime(6314): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.trainingslog/com.example.trainingslog.UebungsActivity}: java.lang.NullPointerException
09-18 13:42:25.030: E/AndroidRuntime(6314):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
09-18 13:42:25.030: E/AndroidRuntime(6314):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252)
09-18 13:42:25.030: E/AndroidRuntime(6314):     at android.app.ActivityThread.access$800(ActivityThread.java:139)
09-18 13:42:25.030: E/AndroidRuntime(6314):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
09-18 13:42:25.030: E/AndroidRuntime(6314):     at android.os.Handler.dispatchMessage(Handler.java:102)
09-18 13:42:25.030: E/AndroidRuntime(6314):     at android.os.Looper.loop(Looper.java:136)
09-18 13:42:25.030: E/AndroidRuntime(6314):     at android.app.ActivityThread.main(ActivityThread.java:5103)
09-18 13:42:25.030: E/AndroidRuntime(6314):     at java.lang.reflect.Method.invokeNative(Native Method)
09-18 13:42:25.030: E/AndroidRuntime(6314):     at java.lang.reflect.Method.invoke(Method.java:515)
09-18 13:42:25.030: E/AndroidRuntime(6314):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
09-18 13:42:25.030: E/AndroidRuntime(6314):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
09-18 13:42:25.030: E/AndroidRuntime(6314):     at dalvik.system.NativeStart.main(Native Method)
09-18 13:42:25.030: E/AndroidRuntime(6314): Caused by: java.lang.NullPointerException
09-18 13:42:25.030: E/AndroidRuntime(6314):     at com.example.trainingslog.FundkDAO.save(FundkDAO.java:68)
09-18 13:42:25.030: E/AndroidRuntime(6314):     at com.example.trainingslog.UebungsActivity.onCreate(UebungsActivity.java:43)
09-18 13:42:25.030: E/AndroidRuntime(6314):     at android.app.Activity.performCreate(Activity.java:5275)
09-18 13:42:25.030: E/AndroidRuntime(6314):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-18 13:42:25.030: E/AndroidRuntime(6314):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166)

Comment: Instead of SQLiteDatabase, use ORMLiteDB which helps you easily store and fetch data.
Comment: What's line FundkDAO.java:68?
Comment: In general one would INSERT without the AUTOINCR id, which in JDBC can be retrieved from the just executed statement with `getGeneratedKeys()`.
Comment: @Dhruti it is the buildProductFromCursor(Cursor cs)  method
Comment: @JoopEggen when I remove AUTOINCREMENT
Then i get
android.database.sqlite.SQLiteException: near "id": syntax error (code 1): , while compiling: id,nameuser,kategorie,uebung,gewicht,datum from training
Comment: Sorry, I meant to remove the `id` column from the INSERT, as that will be generated.
Comment: @JoopEggen i tried it out but still not works nullpointer at save(type) in FundkDAO
Answer: Got it!
Forgot "select term in this method:
private String SEL_ROW =
    "id," +
    "nameuser," +
    "kategorie," +
    "uebung," +
    "gewicht," +
    "datum " +
    "from "
    + DB_Table;


Simple way to authenticate a human request via apache

Question: I am asking this here because, my understanding of the CGI specification is that authentication should be handled by apache rather that by the script: https://www.rfc-editor.org/rfc/rfc3875#section-3.
I put up a webpage advertising a particular birthday party. A simple html page served by apache2 on ubuntu server 12.04. I have a link on the page to a cgi script-Python-that asks the requester to submit text values that will be formatted and relayed in an email to the bithrday boy. What's a simple way to authenticate that a human being is filling out the form, so that I can avoid having the birthday boy receiving spam. Using standard CGI because I do not expect an overload of concurrent requests.
Comment: Implement something like ReCAPTCHA or SolveMEDIA?
Comment: I think you are miss-reading that specification.  "When processing the client request, it is responsible for implementing any **protocol or transport level authentication and security.**"  This is saying the web server is to be responsible for things like SSL negotiation, and certificates.  Not that it should handle all authentication from your application.  Validating that an email is valid, or a the source of a request is valid, is not a **transport level** check.
Comment: I think your correct and this goes into application level authentication. That's probably why every method I've seen suggested is at the script level.
Comment: This has been discussed extensively at our sister site [webmasters.se] where you may want to search for better answers.
Answer: The easiest and best way that I've found is to put an input form on your page that will get hidden either by javascript or by CSS. Something like:
<link href="/styles.css" rel="stylesheet" type="text/css" media="all" />
<form action="/birthday.php" method="post">

Email: <input type="text" name="email" />

Name: <input type="text" name="name" />

Phone: <input type="text" name="phone" />

</form>

In this case, we'll use phone as our secret human verification input. In your styles.css you should have:
input[name="phone"] {
  display: none;
}

In this case, the "phone" input type will be hidden by every real human's browser and won't be submitted with the form. (Most) spambots won't load and parse the external CSS file, so you can then check the existence of the "phone" input's existence in your script:
PHP code:
if (isset($_POST['phone'])) {
  // this is spam, but don't let them know
  echo 'thanks!';
  exit;
}

99% chance you won't get spam. If you did, you could go one step further and use javascript to disable the form field:
$(function() {
  $('input[name="phone"]').hide();
});

This puts the onus on the spammer to load and parse your CSS (or javascript) file and is super easy to implement.


max function c tree height

Question: is there a max function in c  so i can do something like this  to calculate tree height
:or perhaps there is a better way to calculate tree height.
int height(struct node *tree)
{
    if (tree == NULL) return 0;
    return 1 + max(height (tree->left), height (tree->right));
}

if so what includes do i need?
currently i get this error :

dict-tree.o: In function 'height':
  /home/ex10/dict-tree.c:36: undefined reference to `max'
Answer: No, there isn't one built in. Typically you'd write your own inline function, e.g.
static inline int max(int a, int b)
{
    return (a > b) ? a : b;
}

(using whichever 'inline' hint syntax your compiler prefers). In your case, though, you might as well just spell this out manually - it's simple enough:
int height(struct node *tree)
{
    int height_left, height_right;
    if (tree == NULL) return 0;

    height_left = height (tree->left);
    heigth_right = height (tree->right);

    return 1 + ((height_left > height_right) ? height_left : height_right);
}

N.B. beware of the max macro trap. It's tempting to do something like
#define MAX(a,b) (((a) > (b)) ? (a) : (b))

which you can then use for any inputs regardless of their types, but the problem here is if either of the input expressions have side effects, e.g. MAX(++i, ++j). The issue then is that the side effects will get evaluated twice for whichever of the inputs is the max. If you're going to code up max you must use an (inline) function rather than a macro. Unfortuantely since you're in C not C++ without overloading / templates this will limit you to one set of input / output types per named max function.
Answer: Probably because max is an undefined function,
try implementing max first before proceeding.
int max(int a, int b) {
    if(a > b) return a;
    else return b;
}

Answer: No there isn't. There is a family of functions to compute the maximum of floating-point values (see fmax() and friends), which you could certainly use yourself, but I think it's easier to just do it locally.
Something like:
const size_t left = height (tree->left);
const size_T right = height (tree->right);
return left > right ? left : right;

Answer: If you are willing to use C++ rather than just plain C, there is. It's in the Standard Template Library, so you will have to include the requisite file. See here for an example:
http://www.cplusplus.com/reference/algorithm/max/
Reproduced for your convenience:
// max example
#include <iostream>
#include <algorithm>
using namespace std;

int main () {
  cout << "max(1,2)==" << max(1,2) << endl;
  cout << "max(2,1)==" << max(2,1) << endl;
  cout << "max('a','z')==" << max('a','z') << endl;
  cout << "max(3.14,2.72)==" << max(3.14,2.72) << endl;
  return 0;
}

Answer: int height(struct node *tree)
{
if (tree == NULL)
{
    return 0;
}
int left = height(tree->left);
int right = height(tree->right);
return (1 + ((left >right)?left:right));
}

//if else is better than function max in this case

max function c tree height


Number of elements in orbits is a divisor of $|G|$

Question: Let $G$ a finite group acting on a set $X$. Prove that the number of elements in any of the orbits is a divisor of $|G|$.
By definition, the $G$-orbit of $x\in X$ in $X$ is the set:
$$G(x)=\{g \cdot x \in  X : g\in G\}$$
How may I prove this? I have tried to define a mapping from $G$ to $G(x)$ for arbitrary $x$ ($\phi(g)=g \cdot x$) and try to prove it is a bijection, but I can only prove that the map is surjective. So I think this approach may be wrong.
Any help or hints will be appreciated.
Answer: This is essentially the orbit-stabilizer lemma.
The following map is surjective: $$\left\{\begin{array}{ccc}G&\rightarrow&G(x)\\g&\rightarrow&g\cdot x\end{array}\right.$$
and one has: $$g\cdot x=g'\cdot x\Leftrightarrow g^{-1}g'\in\textrm{Stab}(x).$$
Hence, one has a bijective mapping from $G/\textrm{Stab}(x)$ to $G(x)$ and  they therefore have the same cardinality. To conclude, $\textrm{Stab}(x)$ is a subgroup of $G$ and using Lagrange's theorem $[G:\textrm{Stab}(x)]$ divides $|G|$.


Require with variable path in ionic

Question: I'm trying to pass the path of require function in an app done with ionic+vue.
I read different path from a json and the function should be able to load different images based on this path using the require function in the image source.

If I put the path as string it works without problems, but I need this path to change, so it has to be a variable.
Answer: did you try using backticks for string interpolation so you can change the path by setting the imagepath variable?
<img :src=`require(${imagePath})`>

Comment: I've fix it using a the require inside a function, returning the value and using the resolved path from the src.

Require with variable path in ionic


Msg 102, Level 15, State 1, Line 27 - Incorrect syntax near ')'

Question: <code>    SELECT * INTO [H_ACTIVE_STUDENTS]  FROM
/* The section below works independently fine, but generates error when used as subquery */
    (SELECT VIEW_H_ACTIVE_STUDENTS.STUD_ID,
       VIEW_H_ACTIVE_STUDENTS.STUD_LAST_NAME,
       VIEW_H_ACTIVE_STUDENTS.STUD_FIRST_NAME,
       VIEW_H_ACTIVE_STUDENTS.STUD_MIDDLE_INITIAL,
       CAST(VIEW_H_ACTIVE_STUDENTS.STUD_BIRTH AS DATE) AS STUD_BIRTH,
       VIEW_H_ACTIVE_STUDENTS.STUD_SEX,
       VIEW_H_ACTIVE_STUDENTS.STUD_MAIL_STREET_ADDRESS,
       VIEW_H_ACTIVE_STUDENTS.STUD_MAIL_CITY,
       VIEW_H_ACTIVE_STUDENTS.STUD_MAIL_ST,
       VIEW_H_ACTIVE_STUDENTS.STUD_MAIL_ZIP_CODE,
       VIEW_H_ACTIVE_STUDENTS.STUD_AREA_CD,
       VIEW_H_ACTIVE_STUDENTS.STUD_PHONE_NO,
       VIEW_H_ACTIVE_STUDENTS.STUD_PIN,
       VIEW_H_ACTIVE_STUDENTS.SEMC_YR_SEM,
       VIEW_H_ACTIVE_STUDENTS.SEMC_ACTIVE_UNITS,
       VIEW_H_ACTIVE_STUDENTS.SEMC_FINAID_ACTIVE_UNITS,
       VIEW_H_ACTIVE_STUDENTS.SEMC_ACTIVE_HOURS,
       VIEW_H_ACTIVE_STUDENTS.SEMC_FINAID_ACTIVE_HOURS,
       H_LAST_NAME_UPD  = CAST(REPLACE(REPLACE(REPLACE(REPLACE      (VIEW_H_ACTIVE_STUDENTS.STUD_LAST_NAME,' ',''),',',''),'-',''),'''','') AS CHAR(30)),
       H_FIRST_NAME_UPD = CAST(REPLACE(REPLACE(REPLACE(REPLACE(VIEW_H_ACTIVE_STUDENTS.STUD_FIRST_NAME,' ',''),',',''),'-',''),'''','') AS CHAR(15)),
       H_ADRESS_UPD = CAST(REPLACE(VIEW_H_ACTIVE_STUDENTS.STUD_MAIL_STREET_ADDRESS,',','') AS CHAR(30)), /* here is where error pointed*/
       H_STUD_ID = CAST(LEFT(REPLACE(REPLACE(REPLACE(REPLACE(VIEW_H_ACTIVE_STUDENTS.STUD_LAST_NAME,' ',''),',',''),'-',''),'''',''), 3) + LEFT(REPLACE(REPLACE(REPLACE(REPLACE(VIEW_H_ACTIVE_STUDENTS.STUD_FIRST_NAME,' ',''),',',''),'-',''),'''',''),1) + RIGHT(VIEW_H_ACTIVE_STUDENTS.STUD_ID,4) AS CHAR(8))

    FROM   [VIEW_H_ACTIVE_STUDENTS] )
</code>
Comment: I think you're missing a parentheses. Somewhere.
Comment: You most likely need an alias around the final `)`  make it `FROM   [VIEW_H_ACTIVE_STUDENTS] ) data`
Comment: @AdrianPronk You're so nice. Can you come do my job for me?
Answer: SQL Server requires aliases on all derived tables and subqueries so you need to add an alias after the last parentheses:
<code>SELECT *
INTO   [h_active_students]
FROM   (SELECT view_h_active_students.stud_id,
               view_h_active_students.stud_last_name,
               view_h_active_students.stud_first_name,
               view_h_active_students.stud_middle_initial,
               Cast(view_h_active_students.stud_birth AS DATE) AS STUD_BIRTH,
               view_h_active_students.stud_sex,
               view_h_active_students.stud_mail_street_address,
               view_h_active_students.stud_mail_city,
               view_h_active_students.stud_mail_st,
               view_h_active_students.stud_mail_zip_code,
               view_h_active_students.stud_area_cd,
               view_h_active_students.stud_phone_no,
               view_h_active_students.stud_pin,
               view_h_active_students.semc_yr_sem,
               view_h_active_students.semc_active_units,
               view_h_active_students.semc_finaid_active_units,
               view_h_active_students.semc_active_hours,
               view_h_active_students.semc_finaid_active_hours,
               H_LAST_NAME_UPD = Cast(
Replace(
Replace(Replace(Replace
(view_h_active_students.stud_last_name, ' ', ''), ',', ''), '-', ''), '''', '')
AS CHAR(30)),
H_FIRST_NAME_UPD = Cast(Replace(
Replace(
Replace(Replace(
view_h_active_students.stud_first_name, ' ', ''), ',', ''), '-', ''), '''', '')
                        AS CHAR(15)),
H_ADRESS_UPD = Cast(
Replace(view_h_active_students.stud_mail_street_address, ',', '') AS
CHAR(
               30)),
H_STUD_ID =
Cast(
LEFT(Replace(Replace(Replace(Replace(view_h_active_students.stud_last_name, ' ', ''), ',', ''), '-', ''), '''', ''), 3)
+
LEFT(Replace(Replace(Replace(Replace(view_h_active_students.stud_first_name, ' ', ''), ',', ''), '-', ''), '''', ''), 1)
+ RIGHT(view_h_active_students.stud_id, 4) AS CHAR(8))
 FROM   [view_h_active_students]) data -- add this
</code>


using javascript to determine ip works in chrome not firefox or ie

Question: I am using javascript to determine the visitors ip address. For what ever reason, it works in Chrome and not in Firefox, IE, or other browsers.
Here is my code:
function getIPAddress() {
    var xmlHttp;

    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    } else {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlHttp.open("GET", "http://api.hostip.info/get_html.php", false);
    xmlHttp.send();

    var hostipInfo = xmlHttp.responseText.split("\n");

    for (var i = 0; i < hostipInfo.length - 1; i++) {
        var ipAddress = hostipInfo[i].split(":");
        if (ipAddress[0] == "IP") return ipAddress[1];
    }

    return "unknown";
}

At the company I'm working for, I am behind a proxy. Could this be a proxy issue, or is there something wrong with this code? Thanks.
Just deployed my code to our test environment, and in IE, I receive a pop up saying 'This page is accessing information that is not under its control. This poses a security risk. Do you want to continue?' If I say, yes, it works. If I say, no, it doesn't.
Comment: Two things: if that's running in a page from a domain other than "hostip.info", it won't work due to basic browser security rules, and (2) you're not waiting for the ajax request to finish anyway.
Comment: Did you try a POST method? Maybe it is a caching issue.
Answer: for (var i = 0; i < hostipInfo.length - 1; i++) { will cause to return "unknow" if hostipInfo has only one element, change to for (var i = 0; i < hostipInfo.length; i++) {.
Answer: If you're going to use AJAX (which is what this code is), I STRONGLY suggest you use a 3rd party wrapper like jQuery. That will increase cross-browser compatibility greatly and  allows you to shrink your code down to something like this.
$.post('http://api.hostip.info/get_html.php', function(data){
    alert(data);
});

Additional Point
As Pointy mentioned, if your page is running on a different domain than hostip.info, you will need to setup a local PHP to fetch the data like this..
localGetData.php
die(file_get_contents('http://api.hostip.info/get_html.php'));

New Ajax
$.post('localGetData.php', function(data){
    alert(data);
});

Comment: just realized i could get ip from server side with Request.UserHostAddress. at moment, get address of local machine, but i think that's because my computer and server both inside the same network.
Comment: could you give an example of setting up a local fetch the data from asp.net. I'm not using PHP and don't know the equivalent.
Comment: Im not particularly familiar with ASP.NET, so I really could not off the top of my head. Maybe this link will suffice? http://wiki.asp.net/page.aspx/285/httpwebrequest/rev/4
Answer: The reason this works in Chrome is because it supports CORS which allows you to make this request cross domain.
Since the site doesnt appear to support


Rotman introduction to theory of groups exercise

Question: From Rotman "Introduction to the Theory of Groups", ex. 2:54:

Let $ G $ be a finite group, and let $H$ be a normal subgroup with $(H,[G:H])=1$.
  Prove that $H$ is the unique such subgroup in G.

That exercise was introduced here before:
link
It's easy that $HK$ is a subgroup of $G$, thus $|K| / |H\cap K|$ divides $|G|/|H|$.
But I don't see what to do in next step anyway, in spite of reading link above.
Comment: It's probably trying to get you to prove that if a Hall $\pi$-subgroup is normal then it's the only Hall $\pi$-subgroup.
Comment: Could you clarify what is meant by "such"? Clearly there might be another (normal) subgroup $K$ with $(|K|,|G:K|) = 1$.
Comment: What is $(H,[G:H])$? Thi is a pair of a subgroup with an index...
Comment: @Tobias, that's *exactly* the wording in Rotman's book...a rather poor wording, in fact. The meaning is: prove $\,H\,$ is the only normal subgroup in $\,G\,$ s.t. its order is coprime to its index.
Comment: @DonAntonio But only the trivial group has a unique such subgroup.
Comment: @Tobias, the group $\,S_3\,$ has *a unique (non-trivial) normal subgroup* which is both normal and of order coprime to its index, namely $\,A_3\,$: $$(3=|A_3|\,,\,2=|S_3/A_3|)=1$$
Comment: @DonAntonio: No, it also has the entire group and the trivial subgroup.
Comment: Ahh, I missed the non-trivial part. But still, most abelian grouups will be counter examples.
Comment: Yes, something's fishy in this. I must be misunderstanding Rotman's intention. I'll read from the book again.
Answer: As stated, the question is a bit vague, and I am having trouble interpreting it in a way that makes it correct.
Here is something that does hold and which might be what is being asked:
Let $G$ be a finite group and $H$ a normal subgroup of $G$ with $\rm{gcd}(|H|,|G/H|) =1$. Let $K$ be any subgroup of $G$ such that $|K|$ divides $|H|$. Then $K\subseteq H$ (as a special case of this, if $|K| = |H|$ then $K =H$ and I think this might be what is asked).
Proof: Since $H$ is normal, $KH$ is a subgroup of $G$ of order $\frac{|K||H|}{|K\cap H|}$. If $K$ is not contained in $H$ then $\frac{|K|}{|K\cap H|} > 1$. Let $p$ be a prime dividing $\frac{|K|}{|K\cap H|}$. Since $|K|$ divides $|H|$ we know that $p$ divides $|H|$, so since $\rm{gcd}(|H|,|G/H|) =1$ we know that $p$ does not divide $|G/H|$. But then $p|H|$ does not divide $|G|$ which contradicts the fact that it should divide $|KH|$.
Comment: Pretty impressed about the clarity and non-trivially resolution.


Drupal 7 is ready for big sites?

Question: I know to right now Drupal 7 is stable since almost a year but the truth is Drupal needs third party modules for satisfy the requirements of almost any site
Yesterday i tried jump to drupal 7 but the first thing to i see is to many of modules are betas, releases candidates and a lot  haven't a version for D7.
and many of this modules are essentials, modules like Ctools, panels,  references,  context, all of these modules are pretty useful and none of them have a stable version for drupal 7
So my question is,  Drupal 7 is  ready for a bigger site than a blog?  how many of you use drupal 7 with unstable modules for a client's sites?
How risky is use non stable modules in drupal 7?
Answer:
Q: "How risky is use non stable modules in Drupal 7?"
A: "Depends."

Without wanting to be obtuse, in late 2011 this is a question only you can answer, based on your abilities, needs and experience.
The simple answer is: Betas are usually fine, Alphas should usually be avoided, RCs are almost certainly OK.
If you're happy to hit a bug and help fix it or apply patches, you'll be mostly fine and able to really help the Drupal community. If not, the risk for you is higher and could become a show-stopper.
If you're using one of the 'biggies' with tens of thousands of users (CTools, Panels, Views etc) you can probably use alphas/betas without hitting many major issues -- or you'll be one of thousands with the same problem which means it'll get fixed quicker... But if you're using less common (but still complex) modules, or it's critical you have complete reliability in your site, then you'll need to think twice - and maybe stick with D6 for a while.
A safer approach if you're worried and don't have the expertise to get your hands dirty in code or patches is probably: use Drupal 6 but choose your modules carefully so there's always a D7 upgrade path. Upgrade when you're happy it's right for you.
Ultimately you might have to use Drupal 7 because it provides certain features you cannot get in D6.
To close I would say that, for the most part, Drupal 7 and its ecosystem of modules is ready for most people/sites/projects. But things are changing by the day, so if you don't feel comfortable now you might in do a month or two.
Do your research and if you have doubts or hit snags, Drupal 6 is generally still an excellent choice and will be for many more months.
Good luck!
Comment: Nice answer. To be mentioned is that it's the decision of the maintainer to decide what's alpha, beta, stable and so on. Meaning, an alpha module from a responsible, experienced maintainer with many users can easily be more "stable" than a new module that is declared as stable.
Answer: We have recently launched a large government site re-written using drupal 7 (> 3000 nodes, high traffic). Having gone through this development, we had to learn a few things:

due to views only recently being made stable, a lot of modules that depend on views are still unstable. Even so, the more popular ones work okay
we had to port some modules that we use a lot, that had no D7 branch. An example was Apache Solr Panels
features in D7 was shaky for a while, but now is fairly stable

All in all though, Drupal 7 has awesome new features, a whole new database abstraction layer, a wicked states API, image handling in core. As time goes on contrib will keep getting better and better for D7, whilst you will find shortly I would imagine that none wants to make new features for D6 contrib.
If you want to check the site out, visit health.govt.nz
Comment: Nice site @wiifm! Out of curiousity, how did you implement the menu under "our work"?
Comment: Custom menu theming essentially, the rendered mega-menu gets inserted and set to 'display:none', and then javascript is used to show/hide the
Answer: Absolutely, Drupal 7 is ready for big sites; even though many modules are in beta, the essential ones are stable, and you can start building with Drupal 7.
On other hand, there is no need to hurry up, since Drupal 8 will be, most probably, released between 2 years.
For your reference, read this article too.
Answer: We launched a truly huge Drupal 7 site (www.examiner.com) before Drupal 7 was launched. Then, it required a good number of people very, very familiar with core. Now? It's so ready and easy.

Drupal 7 is ready for big sites?


Proving the piecewise function is bijective

Question: Prove that the function $f: \mathbb{Z} \rightarrow \mathbb{N} \cup \{{0}\}$ defined by
$$f(x)= \left\{ \begin{array}{lcc}
             2x  & x \geq 0 \\
             \\ -2x-1& x<0 \\
             \\
             \end{array}
   \right.$$
is bijective.
I don't have any familiarity with piecewise functions when dealing with bijective proofs yet. I'm assuming I have to show the bijection for two separate cases? Like for injective assume $f(x)=f(y)$ for some and arrive at $x=y$ with both cases? Would it be possible to find an inverse which would imply its bijective also?
Comment: Both are valid proof methods, assuming that 'two separates cases' would mean proving both injectivity and surjectivity. And yes, it's possible to explicity write a bijection for $f$.
Comment: Be careful proving injectivity on both 'branches' of the function. The function $$f:\Bbb{R}\to\Bbb{R}: x\mapsto \begin{cases}x+2 & x \leq 0 \\ x & x > 0\end{cases}$$ is injective on $(-\infty,0]$ and injective on $(0,+\infty)$, but it is not injective on $\Bbb{R}$
Answer: Inverse: $g:\mathbb{N}\cup\{0\}\to\mathbb{Z}$
$$g(x)= \left\{ \begin{array}{lcc}
             \frac{x}{2}  & x \text{ is even} \\
             \\ -\frac{x+1}{2}& x\text{ is odd} \\
             \end{array}
   \right.$$


Distribution of *conditional* frequencies when frequencies follow a Dirichlet distribution

Question: Context: we have a large number of individuals characterized by two binary traits; call these $T$ with values $\{0,1\}$, and $T'$ with values $\{0',1'\}$. So there are four types of individuals: $00'$, $01'$, $10'$, $11'$, which appear in the population with unknown relative frequencies $f_{00'}$, $f_{01'}$, $f_{10'}$, $f_{11'}$ summing up to one.
Suppose that our degree of belief about these frequencies (assumed continuous) is expressed by a Dirichlet distribution with parameters $(Aa_{00'}, Aa_{01'}, Aa_{10'}, Aa_{11'})$, the $a$s summing up to one:
$$\mathrm{p}[f_{00'}, f_{01'}, f_{10'}, f_{11'} \mid
A, (a_{00'}, a_{01'}, a_{10'}, a_{11'})] \propto
\prod_{i=0}^1\prod_{j'=0'}^{1'} f_{ij'}^{A a_{ij'}-1}\;\delta\bigl({\textstyle\sum_{ij'}}f_{ij'}-1\bigr).$$
We can also consider the marginal frequencies of individuals having trait $T'$ only, for example: $f_{0'} \equiv f_{00'} + f_{10'}$ and $f_{1'} \equiv f_{01'} + f_{11'}$. Owing to the "aggregation" property of the Dirichlet distribution (Kotz & al 2000, also Basu & al 1982), these marginal frequencies also have a Dirichlet distribution with parameters $\bigl(A(a_{00'} + a_{10'}), A(a_{01'} + a_{11'})\bigr)$ (a Beta distribution).
Question: Consider now the conditional frequencies of trait $T$ given $T'$, for example
$$f_{1\mid 0'}  \equiv \frac{f_{10'}}{f_{00'}+f_{10'}}.$$
What distribution expresses our degree of belief about such a conditional frequency, given the context above?
While I sit down and calculate (or sample), I'd be grateful for any literature or calculation hints on this. Thank you!
Additional motivation: For inference about sequential data, like for example text, speech, genes, some literature express the degree of belief about conditional frequencies $f_{i\mid j}$ (of, say, one word given the previous one) with a Dirichlet distribution (e.g. MacKay & al 1995):
$$\mathrm{p}[f_{i \mid j} \mid
A, (a_{i\mid j})] \propto
\prod_{i} f_{i\mid j}^{A a_{i\mid j}-1}\;\delta\bigl({\textstyle\sum_{i}}f_{i\mid j}-1\bigr), \qquad\text{for every }j.$$
This approach is different from using a Dirichlet distribution for the joint frequencies $f_{ij}$, and I wonder how different is the distribution for the conditional frequencies that we obtain by assuming Dirichlet for the joint frequencies instead, as in my question above.
References:
– Basu, de Bragança Pereira: On the Bayesian analysis of categorical data: the problem of nonresponse (1982) https://doi.org/10.1016/0378-3758(82)90004-0, §§ 3–4.
– Kotz, Balakrishnan, Johnson: Continuous Multivariate Distributions. Vol. 1 (2nd ed. Wiley 2000), §49.1.
– MacKay, Peto: A hierarchical Dirichlet language model (1995) https://doi.org/10.1017/S1351324900000218, https://pdfs.semanticscholar.org/01fa/57bd91f731522c861404d29e4604ba6ac6d3.pdf.
Comment: I can't tell whether this is obvious to you, or a useful hint, but the answer will be given by the result of the integral $\int d \underline{f} D(\underline{f}; \underline{a})\left(\frac{f_{10}}{f_{00}+f_{10}}\right)$. This is by no means trivial to do, I'll have a think about it. In the meantime, I'm sure it will be helpful to understand how to integrate the Dirichlet Distribution and calculate its moments. I asked a question about this a while ago, you might find the answers useful: https://stats.stackexchange.com/questions/309519/how-is-the-generalised-beta-function-defined
Comment: scratch that, that will only give you the expected value of this quantity, not the full distribution. This one's a real head-scratcher, I'll think about it some more and hopefully come back with a sensible answer
Answer: Edit:
(I decided not to delete this answer, as it contains a proof of the distributive property of the Dirichlet Distribution. I have however now managed to answer the original post, which I put in a separate answer)
I generally think about these problems using the fundamental theorem of calculus. You make a new variable (let's call it a), write down an integral for the probability that $a<A$, $P(a<A)$, differentiate wrt A (this will usually use the fundamental theorem of calculus, or in more complex cases, Leibniz rule for differentiating under the integral sign, a generalisation of the former), and the result gives you the pdf for a evaluated at A, or $p(A)$. Let's see how this works, to derive an expression for $a=q_{1}+q_{2}$, or what you refer to as the associative property of the Dirichlet Distribution.
$P(a<A)=\int_{0}^{A}dq_{1}\int_{0}^{A-q_{1}}dq_{2}\int_{0}^{1-q_{1}-q_{2}}dq_{3}D(q_{1}, q_{2}, q_{3}, 1 - q_{1} - q_{2} - q_{3};\alpha)$
Writing this as $\int_{0}^{A}f(A,q_{1})dq_{1}$ and differentiating, one obtains:
$f(A,A) + \int_{0}^{A}\frac{\partial}{\partial A}f(A,q_{1})dq_{1}$
Because
$f(A,q_{1})=\int_{0}^{A-q_{1}}dq_{2}\int_{0}^{1-q_{1}-q_{2}}dq_{3}D(q_{1},q_{2},q_{3}, 1-q_{1}-q_{2}-q_{3})$
we can see that $f(A,A)=0$, so we only have to worry about
$\int_{0}^{A}dq_{1}\frac{\partial}{\partial A}\int_{0}^{A-q_{1}}dq_{2}\int_{0}^{1-q_{1}-q_{2}}dq_{3}D(q_{1},q_{2},q_{3}, 1-q_{1}-q_{2}-q_{3})$
which is a relatively simple case of the fundamental theorem of calculus, basically replace all instances of $q_{2}$ with $(A-q_{1})$
$\int_{0}^{A}dq_{1}\int_{0}^{1-q_{1}-(A-q_{1})}dq_{3}D(q_{1}, a-q_{1}, q_{3}, 1 - q_{1} - (A-q_{1})-q_{3};\alpha)$
which, explicitly now subbing in the function form of the Dirichlet Distirbution, is given by
$\frac{1}{B(\alpha)}\int_{0}^{A}dq_{1}q_{1}^{\alpha_{1}-1}(A-q_{1})^{\alpha_{2}-1}\int_{0}^{1-A}dq_{3}q_{3}^{\alpha_{3}-1}(1-A -q_{3})^{\alpha_{4}-1}$
This is now a product of integrals rather than a double integral. The first is solved with the substitution $v=\frac{q_{1}}{A}$ and the second with $u=\frac{q_{3}}{1-A}$. The first gives $A^{\alpha_{1}+\alpha_{2}-1}B(\alpha_{1}, \alpha_{2})$ and the second gives $(1-A)^{\alpha_{3}+\alpha_{4}-1}B(\alpha_{3},\alpha_{4})$
Putting these together with the original normalisation constant, you get the desired result.
However for $a=\frac{q_{1}}{q_{1}+q_{2}}$, I've hit a stumbling block which might turn out to be very hard to resolve and mean this doesn't have a closed form solution, or perhaps just that this method doesn't work. The sticking point, is that in order to define the region in 2-d space such that $0< \frac{q_{1}}{q_{1}+q_{2}}<1$, is actually quite hard. For example, if $q_{1}=1$ and $A=\frac{1}{4}$, no (permitted) $q_{2}$ can satisfy $\frac{1}{1+q_{2}}<\frac{1}{4}$.
In fact, if $A>\frac{1}{2}$, this is always possible but if $A<\frac{1}{2}$, then $q_{1}<\frac{A}{1-A}$ is needed. But the condition $q_{1}<\frac{A}{1-A}$ isn't enough, because when $A>\frac{1}{2}$, this constraint is too weak, $q_{1}$ needs to be smaller than a number which is greater than 1, so actually the constraint is $q_{1}<min(1, \frac{A}{1-A})$, and this cannot be differentiated, so I don't see how to differentiate under the integral sign.
Comment: Thank you for your efforts! The "aggregation" property is discussed by Kots & al and especially Basu & al (for the multinomial-Dirichlet distribution) in the references I added to my question. An elegant method by Jaynes to calculate Dirichlet integrals is given in this answer: . I'll try to use it for the other calculation, as you suggest!

I've also added some further reasons for my question.
Comment: I've made some substantial edits as I figured out how to do the first integral, but not the second. Let me know if you see any obvious flaws
Answer: Let $\gamma_{ij} \sim \texttt{gamma}(A a_{ij})$ independently. Recall that construction of the Dirichlet distribution as a normalization of gamma random variables. Then the Dirichlet distribution we start with is equal in distribution to
$$
\left(\frac{\gamma_{00}}{\sum \gamma_{ij}}, \ldots, \frac{\gamma_{11}}{\sum \gamma_{ij}}\right) \sim \texttt{dirichlet}(A a_{00}, \ldots, Aa_{11}).
$$
But now we have, for example,
$$
f_{1 | 0} = \frac{f_{10}}{f_{00} + f_{10}} \stackrel{d}{=} \frac{\gamma_{10}}{\gamma_{00} + \gamma_{10}}.
$$
And we can get a similar expersion for $f_{0|0} = \gamma_{00}/(\gamma_{00} + \gamma_{10})$, whence it follows that
$$
(f_{0|0}, f_{1|0}) \sim \texttt{dirichlet}(A a_{00}, A a_{10}).
$$
Easy.
To answer your question about how the conditional model varies from the joint model: if you specify Dirichlet priors on the conditionals of the first component given the second, and a very particular Dirichlet prior on the marginals of the second, then you get a Dirichlet prior for the joint. So you get a little bit more flexibility by using Dirichlet priors on the marginals and conditionals separately; the most general sort of prior you get this way is a special case of what has been called a hyper-Dirichlet, or Dirichlet-tree prior. The hyper-Dirichlet is also conjugate to multinomial sampling; in addition to the Dirichlet, it also contains all stick-breaking constructions you can get from the Beta distribution, and many other possibilities as well.
Comment: I think of this as being part of the aggregation property. You can google the Dirichlet-tree prior and get a short paper by Minka that talks about its properties. As far as what Dirichlet prior: notice that, under the construction above, $(f_{00} + f_{10}, f_{01} + f_{11}) \sim \texttt{dirichlet}(A a_{00} + A a_{10}, A a_{01} + A a_{11})$. By the gamma construction, you can also show that these marginal probabilities are independent of the conditional probabilities, so *if you choose these particular Dirichlet priors* for the marginal and conditionals independently,  you get a Dirichlet joint.
Comment: Great. And so easy, as you say. Strange that such an important property isn't mentioned in Kotz, Balakrishnan, & Johnson's book. Would you be so kind to add some references about the hyper-Dirichlet and the "very particular prior" to your answer? Cheers!
Answer: Right, I've finally solved this, and decided to add another answer rather than edit my original one as I've edited it a lot of times and it's getting messy.
From the joint distribution $P(\underline{q})=\frac{q_{1}^{\alpha_{1}-1}q_{2}^{\alpha_{2}-1}q_{3}^{\alpha_{3}-1}q_{4}^{\alpha_{4}-1}}{B(\underline{\alpha})}$
defined for $0 \leq q_{i} \leq 1 \forall i$ and $q_{1}+q_{2}+q_{3}+q_{4}=1$
and we define a new variable $a=\frac{q_{1}}{q_{1}+q_{2}}$ and wish to derive its distribution. We do this by finding an expression for $p(a<A)$ and differentiating w.r.t A. This will give us the pdf for a evaluated at A. Constructing this expression for the joint distribution is the hardest part (and the differentiation process is a little messy and requires care).
In particular, to construct $p(a<A)$, we really have to think about all of the regions in $q$-space for which $a<A$, as we have to integrate over all of this space to find $p(a<A)$. This was the part I was struggling with in my previous answers. We can solve this two ways, they equate to the same:
First
$0 \leq \frac{q_{1}}{q_{1}+q_{2}} \leq A$
We rearrange in terms of $q_{1}$ and find that $q_{1}<q_{2}\left(\frac{A}{1-A}\right)$
We also know that $q_{1}+q_{2} \leq 1$ and thus $q_{1} \leq 1 -q_{2}$. As both of these need to be true, we can write $q_{1} \leq min(1-q_{2}, q_{2}\left(\frac{A}{1-A}\right))$
Looking at this, we see that in general, when $q_{2}$ is large, $1-q_{2}$ is going to be the lesser of the two terms and vice versa when $q_{2}$ is small. The crossover occurs when $1-q_{2}=q_{2}\left(\frac{A}{1-A}\right)$ or $q_{2}=1-A$. Because $0\leq A \leq 1$, we know that this cross-over will occur for $0\leq q_{2} \leq 1$, i.e. in the allowed range, so will be important.
For $q_{2} < 1-A$, $q_{1}<q_{2}\left(\frac{A}{1-A}\right)$ and
for $q_{2}>1-A$, $q_{1}<1-q_{2}$
Thus our $(q_{1},q_{2})$ integration limits have to look like:
$\int_{0}^{1-A}dq_{2}\int _{0}^{q_{2}\left(\frac{A}{1-A}\right)}dq_{1} + \int_{1-A}^{1}dq_{2}\int _{0}^{1-q_{2}}dq_{1}$
Second
(note, these have to end up being equivalent)
We start from the same place, namely
$0 \leq \frac{q_{1}}{q_{1}+q_{2}} \leq A$
but re-arrange in terms of $q_{2}$ such that $q_{2}>\left(\frac{1-A}{A}\right)q_{1}$. Also $q_{1}+q_{2}<1$ and thus $q_{2}<1-q_{1}$, or, put together
$\left(\frac{1-A}{A}\right)q_{1}< q_{2} < 1-q_{1}$
Looking at this, we see that if $q_{1}$ becomes large enough, the upper limit for $q_{2}$ will be smaller than the lower limit, so let's check when that crossover occurs.
$1-q_{1}=\left(\frac{1-A}{A}\right)q_{1}$, which happens at $q_{1}=A$, so yes, it happens in the region we care about. Thus as well as having the above constraint on $q_{2}$, we know $q_{1}<A$. So we can write the integral limits as
$\int_{0}^{A}dq_{1}\int_{\left(\frac{1-A}{A}\right)q_{1}}^{1-q_{1}}dq_{2}$
It's not obvious to me, even when having these two forms in front of me, why they are the same. The latter one is easier to work with however, so I'm going to use the latter.
We then integrate over all $q_{3}$ values for which $q_{1}+q_{2}+q_{3}<1$ and then finally replace $q_{4}$ with $1-q_{1}-q_{2}-q_{3}$ as it's uniquely determined. Thus the term we need to differentiate is given by:
$\int_{0}^{A}dq_{1}\int_{\left(\frac{1-A}{A}\right)q_{1}}^{1-q_{1}}dq_{2}\int_{0}^{1-q_{1}-q_{2}}\frac{dq_{3}}{B(\underline{\alpha})}q_{1}^{\alpha_{1}-1}q_{2}^{\alpha_{2}-1}q_{3}^{\alpha_{3}-1}(1-q_{1}-q_{2}-q_{3})^{\alpha_{4}-1}$
We first write this as $\int_{0}^{A}f(q_{1},A)dq_{1}$, so when we differentiate w.r.t A, we get (using Leibniz rule for differentiating under the integral sign)
$\int_{0}^{A}\frac{d}{dA}f(A,q_{1})dq_{1} + f(A,A)$
because we can write
$f(A,q_{1})=\int_{\left(\frac{1-A}{A}\right)q_{1}}^{1-q_{1}}g(q_{2})dq_{2}$
it turns that that $f(A,A)$ is given by
$\int_{1-A}^{1-A}g(q_{2})dq_{2}=0$
so we get a nice simplification and only have to calculate
$\int_{0}^{A}\frac{d}{dA}f(A,q_{1})dq_{1}$
given by (essentially replace all $q_{2}$ with $q_{1}\left(\frac{1-A}{A}\right)$ and then also take the derivative of $q_{1}\left( \frac{1-A}{A}\right)$ wrt A)
$\int_{0}^{A}q_{1}\cdot -1 \cdot \frac{d}{dA}\left(\frac{1-A}{A}\right)\int_{0}^{1-q_{1}-q_{1}\left(\frac{1-A}{A}\right)}\frac{dq_{3}}{B(\underline{\alpha})}q_{1}^{\alpha_{1}-1}\left(q_{1}\left(\frac{1-A}{A}\right)\right)^{\alpha_{2}-1}q_{3}^{\alpha_{3}-1}(1-q_{1}-q_{1}\left(\frac{1-A}{A}\right)-q_{3})^{\alpha_{4}-1}$
which tidies up to
$\left(\frac{1-A}{A}\right)^{\alpha_{2}-1}\frac{1}{A^{2}}\int_{0}^{A}dq_{1}q_{1}^{\alpha_{1}+\alpha_{2}-1}\int_{0}^{1-\frac{q_{1}}{A}}\frac{dq_{3}}{B(\underline{\alpha})}q_{3}^{\alpha_{3}-1}(1-\frac{q_{1}}{A}-q_{3})^{\alpha_{4}-1}$
if you're still with me, we're now basically there. We do the $q_{3}$ integral with the substitution $u=\frac{q_{3}}{1=\frac{q_{1}}{A}}$, to get $(1-\frac{q_{1}}{A})^{\alpha_{3}+\alpha_{4}-1}B(\alpha_{3}, \alpha_{4})$
That leaves us needing to compute the integral $\int_{0}^{A}dq_{1}q_{1}^{\alpha_{1}+\alpha_{2}-1}(1-\frac{q_{1}}{A})^{\alpha_{3}+\alpha_{4}-1}$, which is done using the substitution $u=\frac{q_{1}}{A}$ to obtain $A^{\alpha_{1}+\alpha_{2}}B(\alpha_{1}+\alpha_{2}, \alpha_{3}+\alpha_{4})$
Putting this together, we have
$(1-A)^{\alpha_{2}-1}A^{\alpha_{1}-1}\frac{B(\alpha_{1}+\alpha_{2}, \alpha_{3}+\alpha_{4})B(\alpha_{3}, \alpha_{4})}{B(\underline{\alpha})}$
and I'll leave to you to verify that the beta functions do indeed cancel to give $\frac{1}{B(\alpha_{1},\alpha_{2})}$, and so the distribution we're left with, we can recognise as normalised.
And thus, somewhat remarkably, the relative prevalence the first event being 0 and 1 does not have any bearing on how likely the second event is, given the first event. In Dirichlet inference, your $\alpha$s will usually be counts of events (combined with prior constants). If you want to know the relative probabilities  of all four outcomes, you can use their respective counts and do Dirichlet inference and if you want to know the conditional probabilities, you can throw away the counts relating to first events that didn't go the right way, and then do binomial inference. The two are entirely compatible with one and other.
Now that I've done the analytics, I'd be interested/relieved to see your numerics give the same.


eWay Client Side Encryption

Question: Is this possible?
I have a ecommerce website that has a eWay Payment Gateway, so I wanted to get the encrypted card details with the use of the client side encryption key that can be seen in the code <code>$(".form").attr("data-eway-encrypt-key", "The encryption key is placed here");</code> I wonder if this is possible because I want to pass the encrypted data to another form here is the link of encrytion js https://secure.ewaypayments.com/scripts/eCrypt.js
Answer: I have done a similar thing, not exactly sure where you need help from your question but this is my code. I use "RealCardNumber" as a text field and "CardNumber" as a hidden field that gets populated with the encrypted data and sent to the server (same for card code).
<code>   $.getScript("https://secure.ewaypayments.com/scripts/eCrypt.min.js")
       .done(function (script, textStatus) {
           if (eCrypt !== undefined) {
               $('#card-details').show(); // Form details initially hidden
               $('#card-loading').hide(); // Placeholder div shown while loading the eWay script (which should happen pretty quick)
               // Setup the hooks to encrypt the card number once it is submitted
               $(".payment-info-next-step-button")[0].onclick = null; // This is the payment button in my scenario
               $(".payment-info-next-step-button").click(function () {
                   var eWayKey = "<Key goes here>"; // Get from Settings ....
                   try {
                       $('#CardNumber').val(eCrypt.encryptValue($('#RealCardNumber').val(), eWayKey));
                       $('#CardCode').val(eCrypt.encryptValue($('#RealCardCode').val(), eWayKey));
                       // Ready to go .... hook in your normal submit here
                   } catch (e) {
                       alert('Sorry there was a problem with submitting the card details securely');
                       console.log(e);
                   }
               });
           } else {
               $('#card-loading').hide();
               alert('eWay not available - please select a different payment method if available');
           }
       })
       .fail(function (jqxhr, settings, exception) {
           $('#card-loading').hide();
           alert('eWay not available - please select a different payment method if available');
       });
</code>

eWay Client Side Encryption