Lucia is gone. Just gone

Question: Skyrim problem here. I've finally found a house mod that will support a family (as in allow them to move there). I'm excited to install it, but it says that a new save game is highly recommended unless you haven't adopted any kids yet.
I recently adopted Lucia. I have two saves in my game, a quick and a full. I know that the full save has Lucia as adopted, but I'm not sure if the quick does. If it does not, then my reasoning is that I can install the mod and load that save, rather than having to work all the way back through eighteen levels.
And here's the problem. I loaded the quick save and searched for Lucia, in an attempt to see if she was adopted or not. She is nowhere to be found. She is not sitting under the tree in the middle of Whiterun, she is not in Breezehome, and she is not in the inn.
I tried to use console commands. both the moveto and placeatme commands do not work. I used both the refid and the baseid. Neither worked. I used help Lucia, thinking maybe the wiki was wrong on her ID. it gave me a different ID, which also didn't work. Every time, the console says either that it can't find the objectbaseid, or that the id is invalid.
This has led me to the conclusion that Lucia has been entirely erased from the game's memory, and I KNOW that hasn't happened. Can someone tell me what is going on?
Additional details: I am using a Breezehome overhaul mod. When I adopted Lucia, she moved in perfectly with no trouble though, so I can't really see how that would be the problem.
Comment: I think I'm going to have to report this to Child Protective Services. Deleting your child from existence is simply unacceptable behavior.
Comment: @armadillo I have not yet installed the mod, no. I read the description page first, which is why I'm checking to see if I have a save *before* I adopted Lucia.
Comment: Yeeaaahh.... This is weird. The prid command didn't work (something about expected end of line), but the `player.moveto` one did (didn't know the xx was for load order). Lucia has decided to live with Carlotta Valentia. For some reason. Unfortunately I *have* already adopted her on that save, so is there a way to 'un-adopt' her?
Comment: Thanks armadillo. Looks like a reset of Hearthfire is on the horizon. Just to be sure, I just deactivate it and then reactivate it (in NMM), right?
Comment: Yeah, that should do it. I'd check to see if the game works OK afterwards though... like, Lucia is back, and not your child, that sort of thing. Disabling mods like that makes me nervous, but that might be the easiest way to unadopt Lucia.
Comment: But keep in mind that that will make Hearthfire houses disappear too, if you have any.
Comment: Thanks for your help. If you make an answer out of your comments, I'll mark it.
Comment: Oh, I meant, deactivate Hearthfire in NMM, start Skyrim, save your game, exit, reenable Hearthfire, start Skyrim again, and save again.
Answer: To find Lucia, or really any missing NPC:

Figure out their ref ID (not base ID). For a lot of NPCs, you can find this on their UESP Wiki page. The page for Lucia says that her ref ID is xx003F5E. Replace the "xx" with wherever your DLC is in the load order. Hearthfire is #5 in my load order, so Lucia's ref ID for me is 05003F5E. UESP has an article on finding the first two digits of the ref ID.
If neither UESP nor the Elder Scrolls Wiki have the ref ID, you could load a different saved game and click on the NPC with the console open. That will show their ref ID centered on the console window. Or you could look in the Creation Kit, if you're desperate.
If you type help Lucia in the console, that will give you her base ID, which won't do you any good unless you want to spawn another Lucia. I tried that, but adopting one of her clones didn't seem to work: she agreed to be adopted but never went to my house.
Type this in the console: player.moveto 05003F5E (or whatever the ref ID is for you). That should move you to wherever Lucia is.
If you still don't see her, type this in the console, just in case she got disabled somehow:
prid 05003F5E
enable
If the NPC is stuck/won't move (which might explain why a follower stopped following you), click on them while in the console and type moveto player. Or sprint into them a few times and try to stagger them to some other location.
If you found the NPC you're looking for but they're dead, take any important items off of their body, then click on them while in the console and type resurrect.

Hopefully, by now you're standing next to the NPC and they're alive.
The answers to this question are also relevant for finding NPCs: How do I find my follower if and when they leave me?
You mentioned that you wanted to unadopt Lucia, so check the answers to this question for how to do that: How do I unadopt my children? (preferably without killing them)
Comment: Thanks. I did eventually manage to teleport to Lucia with `player.moveto`. Found her in the Valentia house for some reason. Carlotta acted like I lived there and everything (wonder if her playing with Mila caused that somehow...). Lucia still acted like she was adopted and I even had the option to send her home. I'm going to get everything out of Lakeview Manor, uninstall Hearthfire, and see where I'm at. Thanks for your help!
Comment: Everything appears to be working. I got Lucia home, emptied Lakeview, deactivated Hearthfire and the mods that depended on it, saved, re-activated hearthfire and the other mods, saved, downloaded the mod that started this whole thing, and everything appears to be working. Thanks for your time and help! I have an uneasy feeling about Uthgerd's absence from the inn as she was my steward (forgot to 'un-steward' her before uninstalling)... but I can live with that.
Comment: @ThomasMyron Cool, glad it worked. You could try to find Uthgerd with the steps above, or even try to spawn a new one if she is completely gone. To get a new Uthgerd, I think this will work (haven't tested it): `placeatme 918E2`, then click on her and type `setrelationshiprank 7 1` to make her like you, if she doesn't already. I'm not sure if you can get an Uthgerd clone to be your steward, but you could try... I'm also not sure whether the clone will un-spawn, but that would be sort of awkward if your steward disappeared after spawning her...
Comment: I don't really need her since I won't be using the Hearthfire houses (stewards only work for hearthfire houses), but if I don't come across her, I'll try out the codes. Thanks!
Answer: Using player.moveto and then her ref id didnt do anything.
However...for fun i was just messing around and did player.moveto 02003f5e which brought me to a cave...then i did player.moveto 03003f5e and it placed me in the breezehome at which point she started talking to me.
Hopefully this can help anyone else out with the issue in the future.
But i have a feeling it was completely random for just my game.

Lucia is gone. Just gone


Classic ASP Error Page Not Working IIS 7.5

Question: I use Classic ASP on IIS7.5 at Windows Server 2008 R2. I have a problem. I have a custom 404 page. And redirect all 404 errors to default.asp. That is work on the web but it's not working on local ! My web.config's setting under the document. Can you help me please about this situation.
<code><customErrors mode="On">
   <error statusCode="404" redirect="/default.asp" />
</customErrors>

    <httpErrors errorMode="DetailedLocalOnly">
        <remove statusCode="404" subStatusCode="-1" />
        <error statusCode="404" prefixLanguageFilePath="" path="/Default.asp" responseMode="ExecuteURL" />
        <error statusCode="500" subStatusCode="100" path="/e/Default.asp" responseMode="ExecuteURL" />
    </httpErrors>
</code>
Comment: You wish to redirect all 404s and 500s to a custom page, right? What occurs instead of the expected behaviour when you attempt to test this?
Comment: I test this this is work real but it isn't local iis
Answer: httpErrors errorMode is DetailedLocalOnly So That is work at web bu not work local. I set errorMode = custom and it's work
http://www.iis.net/configreference/system.webserver/httperrors


"The LinkedList node does not belong to current LinkedList"

Question: I've run into a wall while trying to understand how to insert hashtables into LinkedLists. I lost count of different things that I tried. I know I could use ArrayList or something else, but I wanted to make this work with LinkedLists so that I could benchmark it...
This is what I've come up with:
#BEGIN SAMPLE SCRIPT
#------------------------
$list = New-Object Collections.Generic.LinkedList[Hashtable]

For($i=1; $i -lt 10; $i++){
   $list.AddLast(@{ID=$i; X=100+$i;Y=100+$i})
}

ForEach($item In $list){
   If($Item.x -eq 105){
       $list.AddAfter($item, @{ID=128;X=128;Y=128})
       Break
   }
}

ForEach($item In $list){
   write-host "ID:"$item.ID", X:"$item.x", Y:"$item.y", TYPE:" $item.GetType()
}
#-----------------------------------
#END SAMPLE SCRIPT

Expected output:
ID: 1 , X: 101 , Y: 101 , TYPE: System.Collections.Hashtable
ID: 2 , X: 102 , Y: 102 , TYPE: System.Collections.Hashtable
ID: 3 , X: 103 , Y: 103 , TYPE: System.Collections.Hashtable
ID: 4 , X: 104 , Y: 104 , TYPE: System.Collections.Hashtable
ID: 5 , X: 105 , Y: 105 , TYPE: System.Collections.Hashtable
ID: 128 , X: 128 , Y: 128 , TYPE: System.Collections.Hashtable
ID: 6 , X: 106 , Y: 106 , TYPE: System.Collections.Hashtable
ID: 7 , X: 107 , Y: 107 , TYPE: System.Collections.Hashtable
ID: 8 , X: 108 , Y: 108 , TYPE: System.Collections.Hashtable
ID: 9 , X: 109 , Y: 109 , TYPE: System.Collections.Hashtable

Error that I get:
Exception calling "AddAfter" with "2" argument(s):
"The LinkedList node does not belong to current LinkedList."

Line that triggers the error message:
$list.AddAfter($item, @{ID=128;X=128;Y=128})

Answer: Basically, using foreach, you iterate over the values (hashtable), and not the LinkedListNode, which is what is expected input for AddAfter method. I recommend iterating over the list as follows -
#BEGIN SAMPLE SCRIPT
#------------------------
$list = New-Object Collections.Generic.LinkedList[Hashtable]

For($i=1; $i -lt 10; $i++){
   $list.AddLast(@{ID=$i; X=100+$i;Y=100+$i})
}

$current = $list.First

while(-not ($current -eq $null))
{
   If($current.Value.X -eq 105)
   {
       $list.AddAfter($current, @{ID=128;X=128;Y=128})
       Break
   }

   $current = $current.Next
}

ForEach($item In $list){
   write-host "ID:"$item.ID", X:"$item.x", Y:"$item.y", TYPE:" $item.GetType()
}
#-----------------------------------
#END SAMPLE SCRIPT

Comment: Perfect way to iterate though the list.
Comment: Thank you for explaining that; no wonder none of the declarations and castings helped - I was handling the wrong object.
Answer: Just to get the mind going I had a look at this. The issue is what the error is suggesting. $item is a hashtable and not a linkedlist object. In order to find the correct position in the list I performed a Find on the $item. Once that was done I got the desired output. Makes me think that there is a better way to crawl through the list.....
$list.AddAfter($list.Find($item), @{ID=128;X=128;Y=128})

Having a look at the data types of the objects:
$item.GetType().FullName
System.Collections.Hashtable

($list.Find($item)).GetType().Fullname
System.Collections.Generic.LinkedListNode`1[[System.Collections.Hashtable, mscorlib, Version=126.96.36.199, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

It would seem that the position in the LinkedList is not preserved when using ForEach hence the need to locate the position with a Find
For anyone not familiar with LinkedLists I found this to be a useful resource.


Best practice for logo height in admin sites?

Question: If you visit any admin/franchise/clients sites, these sites always have logo on the left top corner.
What is the golden rule for admin site logo height? as i have build a logo with 50px height but its looking quite tall, because there is some old printed images which increase the height of logo and i can not change these images height.
i need your suggestion about admin site header and logo.
Answer: There is no golden rule. Marketing wants it twice as large. The UI designer wants it twice as small. So just go somewhere in between.
Comment: That would be twice the same then?
Answer: Hard to visualize the problem you have. Not sure there's a golden rule to logo height - but 40 to 70px sounds about right, probably including padding, but it depends on the rest of the content and whether it's wasting space right along the top. Look at this very page for example.
[Edit] Added some examples below. If you are forced to have a 15px padding top and bottom, then a 30px logo looks too small, between 40 and 50 looks better. Depends on your colour scheme, aspect ratio of the logo, and what else you have in the same horizontal panel as the logo...?
Comment: padding top and padding bottom is 15 pixel so header height is increase to 80 pixel, but i can not decrease the above 15 and the below 15, as i have to show some content there.
Comment: 30px ltd is looking good in admin sites.
Answer: 50px does not seem unreasonable at all. Any size that is at least legible but not obtrusive should work.
Comment: Yes I can see that, but I still think that 50px is not unreasonable, as Roger concurs.
Comment: I guess you answered your own question then, make the logo smaller :)
Comment: if you look at the top outer header of ux.stackexchange.com, it has 18 px height.
Comment: padding top and padding bottom is 15 pixel so header height is quite tall then 80 pixel.
Comment: yes but padding can not be decreased, as i have to place some contents,
Comment: I am looking for some research on admin site logo and header, some references.


expectation maximization algorithm matlab out of memory error

Question: I am implementing Expectation Maximization algorithm in matlab. Algorithm is operating on 214096 x 2 data matrix and While computing probabilities, there is multiplication of ( 214096 x 2 ) * (2 x 2) * ( 2 x 214096 ) matrices, which is resulting in error of out of memory in matlab. Is there a way to fix this problem?
Equation
Matlab Code:
          enter image description here  D = size(X,2); % dimension
            N = size(X,1); % number of samples
            K = 4; % number of Gaussian Mixture components ( Also number of clusters )

            % Initialization
            p = [0.2, 0.3, 0.2, 0.3]; % arbitrary pi, probabilities of clusters, apriori probability of cluster
            [idx,mu] = kmeans(X,K); % initial means of the components, theta is mu and variance

            % compute the covariance of the components
            sigma = zeros(D,D,K);
            for k = 1:K
                tempmat = X(idx==k,:);
                sigma(:,:,k) = cov(tempmat);  % Sigma j
                sigma_det(k) = det(sigma(:,:,k));
            end

            % calculate x-mu
            for k=1: K
                            check=length( X(idx == k,1))
                            for  lidx = 1: length( X(idx == k,1))

                                cidx = find( idx == k) ;
                                Xmu(cidx(lidx),:) = X(cidx(lidx),:) - mu(k,:); %( x-mu ) calculation on cluster level
                            end
            end

            % compute P(Cj|x; theta(t)), and take log to simplified calculation

            %Eq 14.14 denominator
            denom = 0;
            for k=1:K
                calc_sigma_1_2 = sigma_det(k)^(-1/2);
                calc_x_mu = Xmu(idx == k,:);
                calc_sigma_inv = inv(sigma(:,:,k));
                calc_x_mu_tran = calc_x_mu.';
                factor = calc_sigma_1_2 * exp (-1/2 * calc_x_mu * calc_sigma_inv * calc_x_mu_tran  ) * p(k);

                denom = denom + factor;
            end

            for k =1:K
                calc_sigma_1_2 = sigma_det(k)^(-1/2);
                calc_x_mu = Xmu(idx == k,:);
                calc_sigma_inv = inv(sigma(:,:,k));
                calc_x_mu_tran = calc_x_mu.';
                factor = calc_sigma_1_2 * exp (-1/2 * calc_x_mu_tran * calc_sigma_inv * calc_x_mu ) * p(k);

                pdf(k) = factor/denom;
            end

            %%%% Equation 14.14 ends

Comment: is 214096 number of dimensions/features?
Comment: 214096 is number of observations in each of 2 dimensions
Comment: When in EM algorithm you get a matrix of N^2 elements? it does not seem correct. Why would you need a Gramian?
Comment: I might have wrong understanding of algorithm then, i am using P(Cj | x : theta(t) ) = det(sigma)^-1/2 * exp ( -1/2 (x - mu).' * Inv(sigma) * (x-mu) / ( xxxx)  to compute conditional probabilities in Expectation step. sigma is covariance matrix of (214096 x 2) data, mu is first iteration clusters mean and x is data sample. x-mu in my case is resulting in same 214096 x 2 matrix. Is this correct?
Comment: isn't this point wise? this does not look like a valid equation for x being a matrix, it looks like a valid one for per-vector only (thus x has to be 1x2), otherwise as a result of this operation you would get matrix N x N, which does not represent any reasonable probabilistic object, you want to get a number
Answer: It seems that you tried to apply vector based equation by simply substituting vector for matrix, this is not how it works
(x - mu).' * Inv(sigma) * (x-mu)

is supposed to be mahalanobis norm of (x-mu), and you want to obtain this value per each row of matrix X, thus
(X - mu).' * Inv(sigma) =: A <- this is ok, this results in N x d matrix

and now you have to do point-wise multiplication of A with (X - mu), not a dot product, and finally sum over second axis (columns), this way you end up with N element vector, each containing a mahalanobis norm of corresponding row from X.
Comment: Thanks a lot @lejlot, i m fixing this


Random number - Choose seed

Question: because of one project I have to make use of pseudo random numbers with normal distribution.
To this respect, I'm generally putting this down:
nn_u = complex((normrnd(0,1.0,size(H_u))),(normrnd(0,1.0,size(H_u))));
nn_v = complex((normrnd(0,1.0,size(H_u))),(normrnd(0,1.0,size(H_u))));
nn_w = complex((normrnd(0,1.0,size(H_u))),(normrnd(0,1.0,size(H_u))));
size(H_u) = [4096,1];

This way I don't have any real access to the seed number. What I expect is that, using the above mentioned form, there will be 6 seeds, that means one different seed for any of the six times called normrnd function.
What I'd like to do at the moment is to generate six independent representations, just as happens above, with only one seed point, which I can pick out of the range [1,999].
To achieve this I was thinking to proceed this way:
n = 4096;
nn_tmp = normrnd(0,1,[n*6,1]);
nn_u = complex(nn_tmp(1:n,1),nn_tmp(n+1:2*n,1));
nn_v = complex(nn_tmp(2*n+1:3*n,1),nn_tmp(3*n+1:4*n,1));
nn_w = complex(nn_tmp(4*n+1:5*n,1),nn_tmp(5*n+1:6*n,1));

But this way, I don't have any direct access to the seed; I don't even know if the kind of operation I'd do has any strong theoretical validation.
Any support would be welcome.
Comment: Have you seen http://stackoverflow.com/questions/4682080/how-to-set-custom-seed-for-pseudo-random-number-generator ?
Comment: A comparison of `RandStream` vs `rng` for interests sake: http://blogs.mathworks.com/loren/2011/07/07/simpler-control-of-random-number-generation-in-matlab/ but I think both will work for you
Answer: I think you can use rng to seed and then use randn instead of normrnd for your problem
So something like
SEED = 120; %for example
rng(SEED, 'twister');
nn_u = complex(randn(size(H_u)),randn(size(H_u)));
nn_v = complex(randn(size(H_u)),randn(size(H_u)));
nn_w = complex(randn(size(H_u)),randn(size(H_u)));

Random number - Choose seed


Why the mountain pass point cannot be a relative minimizer?

Question: The finite-dimensional mountain pass theorem (MPT), by Courant, states that if $F \in C^1(\mathbf R^n, \mathbf R)$ has two distinct strict relative minima $x_1$ and $x_2$, then $F$ has a third critical point $x_3$ distinct from $x_1$ and $x_2$, characterized by
$$F(x_3) =  \inf_{\Sigma \in \Gamma} \max_{x \in \Sigma} F(x)$$
where $\Gamma$ is the set of `curves' connecting $x_1$ and $x_2$.
Why the fact that $x_3$ is different from $x_1$ and $x_2$ is quite clear, I wonder why $x_3$ cannot be a relative minimizer.
I have checked proofs from several references and it seems that these proofs of this part are not clear enough. In fact, how to rule out the following scenario: $F$ is flat everywhere in part of the minimizing curve containing/around $x_3$, namely $x_3$ is not isolated.
Answer: Since $x_1$ and $x_2$ are relative minima, neighboring points must be higher than each.  Thus there exists a curve $\Gamma$ that is increasing for nearby points to $x_1$ and increasing for nearby points to $x_2$.  For a joining curve, then, there MUST be a "top of the curve" point, where $\Gamma$ goes from increasing from $x_1$ and decreasing to $x_2$.  Thus there exists a point (which we label $x_3$) at the top.
QED.
True, there may be local minima along $\Gamma$, but the theorem just concerns the existence of the "peak" at $x_3$.
Clear?
Comment: Think about it:  What is the *maximum* of all points on $\Gamma$?  Whatever it is, let's call it $x_3$.
Comment: What I understood is that you just show that $F(x_3)>\max\{F(x_1), F(x_2)\}$. (In fact, $F$ reaches its maximum value along the curve $\Gamma$ at the point $x_3$, as you pointed out.) But I still have trouble understanding why $x_3$ cannot be a relative minimum. The picture I have in mind is sort of a trapezoid. After increasing a bit, the function $F$ goes horizontally, then decreases toward $x_2$. So any point in that horizontal part can be $x_3$?
Comment: I think now I got the point.

The theorem only says that there is some point $x_3$ which is not a relative minima although along the minimizing curve $\Sigma$, there could be infinite many critical points that could not be a relative minima. For example, in the picture of a trapezoid, we could think that $x_3$ is one of the top two vertices. (I was thinking in the following direction: any point $x_3$ characterized by $F(x_3) =  \inf_{\Sigma \in \Gamma} \max_{x \in \Sigma} F(x)$.., which is not quite correct because there is some, not any.)

Anyway, thanks for helping me.


How often do mysterious wanderers give loot back?

Question: Sometimes, a mysterious wanderer arrives and asks for wood or fur. They say if you give them (100 or 500), they will come back with more. How often is that statement true? The builder isn't sure that they can be trusted.
Answer: Taken from the wiki:
The Mysterious Wanderer: Wood
A mysterious wanderer arrives with a cart. He asks for wood and promises to come back with more.
The player can choose to ignore them, give 100 wood for a 50% chance of receiving 300 wood in 1 minute, or give 500 wood for a 30% chance of receiving 1500 wood in 1 minute.
The Mysterious Wanderer: Fur
A mysterious wanderer arrives with a cart. She asks for fur and promises to come back with more. The player can choose to ignore them, give 100 fur for a 50% chance of receiving 300 fur in 1 minute, or give 500 fur for a 30% chance of receiving 1500 fur in 1 minute.
Excerpt from the code on github:
Room Events code:
We can see from the code that

giving 100 wood/fur has 50% chance to return 300.

giving 500 wood/fur has 30% chance to return 1500.

Here is relevant code:
<code>{ /* Mysterious Wanderer  --  wood gambling */
    title: _('The Mysterious Wanderer'),
    isAvailable: function() {
        return Engine.activeModule == Room && $SM.get('stores.wood');
    },
    scenes: {
        start: {
            text: [
                _('a wanderer arrives with an empty cart. says if he leaves with wood, he\'ll be back with more.'),
                _("builder's not sure he's to be trusted.")
            ],
            notification: _('a mysterious wanderer arrives'),
            blink: true,
            buttons: {
                '100wood': {
                    text: _('give 100'),
                    cost: {wood: 100},
                    nextScene: { 1: '100wood'}
                },
                '500wood': {
                    text: _('give 500'),
                    cost: {wood: 500},
                    nextScene: { 1: '500wood' }
                },
                'deny': {
                    text: _('turn him away'),
                    nextScene: 'end'
                }
            }
        },
        '100wood': {
            text: [
                _('the wanderer leaves, cart loaded with wood')
            ],
            onLoad: function() {
                if(Math.random() < 0.5) {
                    Engine.setTimeout(function() {
                        $SM.add('stores.wood', 300);
                        Notifications.notify(Room, _('the mysterious wanderer returns, cart piled high with wood.'));
                    }, 60 * 1000);
                }
            },
            buttons: {
                'leave': {
                    text: _('say goodbye'),
                    nextScene: 'end'
                }
            }
        },
        '500wood': {
            text: [
                _('the wanderer leaves, cart loaded with wood')
            ],
            onLoad: function() {
                if(Math.random() < 0.3) {
                    Engine.setTimeout(function() {
                        $SM.add('stores.wood', 1500);
                        Notifications.notify(Room, _('the mysterious wanderer returns, cart piled high with wood.'));
                    }, 60 * 1000);
                }
            },
            buttons: {
                'leave': {
                    text: _('say goodbye'),
                    nextScene: 'end'
                }
            }
        }
    }
},

{ /* Mysterious Wanderer  --  fur gambling */
    title: _('The Mysterious Wanderer'),
    isAvailable: function() {
        return Engine.activeModule == Room && $SM.get('stores.fur');
    },
    scenes: {
        start: {
            text: [
                _('a wanderer arrives with an empty cart. says if she leaves with furs, she\'ll be back with more.'),
                _("builder's not sure she's to be trusted.")
            ],
            notification: _('a mysterious wanderer arrives'),
            blink: true,
            buttons: {
                '100fur': {
                    text: _('give 100'),
                    cost: {fur: 100},
                    nextScene: { 1: '100fur'}
                },
                '500fur': {
                    text: _('give 500'),
                    cost: {fur: 500},
                    nextScene: { 1: '500fur' }
                },
                'deny': {
                    text: _('turn her away'),
                    nextScene: 'end'
                }
            }
        },
        '100fur': {
            text: [
                _('the wanderer leaves, cart loaded with furs')
            ],
            onLoad: function() {
                if(Math.random() < 0.5) {
                    Engine.setTimeout(function() {
                        $SM.add('stores.fur', 300);
                        Notifications.notify(Room, _('the mysterious wanderer returns, cart piled high with furs.'));
                    }, 60 * 1000);
                }
            },
            buttons: {
                'leave': {
                    text: _('say goodbye'),
                    nextScene: 'end'
                }
            }
        },
        '500fur': {
            text: [
                _('the wanderer leaves, cart loaded with furs')
            ],
            onLoad: function() {
                if(Math.random() < 0.3) {
                    Engine.setTimeout(function() {
                        $SM.add('stores.fur', 1500);
                        Notifications.notify(Room, _('the mysterious wanderer returns, cart piled high with furs.'));
                    }, 60 * 1000);
                }
            },
            buttons: {
                'leave': {
                    text: _('say goodbye'),
                    nextScene: 'end'
                }
            }
        }
    }
},
</code>
Comment: @Caleb: no, he is right because you always lose the original "investment". With 100, there is a 50% chance of gaining 200 and a 50% chance of losing 100, for a total average gain of 100. With 500, you have a 70% chance of losing 500 and a 30% chance of gaining 1000, which is an average *loss* of 50.
Comment: So giving more has a bigger chance of a larger amount.
Comment: ...how much larger?! At 30% for 100, that better be more than 333, and 50% for 500, it better be more than 1000, or that's a negative sum game, completely not worth the expense.
Comment: @SF - I have updated my answer with data from the source code.  (For the browser version of the game)
Comment: That would mean giving 100 fur/wood is a positive sum game (50% chance for 300% gain), 500 is negative sum (30% for 150% gain).
Comment: @SF, your math is a bit off.  The gain for both is %200 (You are making 3x back on your investment).  In any case, statistically the lower investment is still better.
Comment: @Michael Borgwardt, I said I agreed with him that the lower investment is better.  Just pointing out that the "% gain"  he stated was incorrect.


Is it still possible to start and finish a quest from Chapter 1 after starting Chapter 2?

Question: Baldur's Gate: Enhanced Edition is divided by chapter. When I start Chapter 2, will I still be able to activate quests from Chapter 1? In my journal, all previous chapter quests disappeared after starting Chapter 2.
Answer: Starting a new Chapter does not prevent you completing quests you started previously.
In this specific case however, you won't be able to re-enter Candlekeep to do the quests.
Comment: IIRC the Candlekeep part is labeled as Prologue and is more of a tutorial than a real chapter, but it is separate from the next chapters.


JSF backing bean structure (best practices)

Question: I hope that in this post, I can get people's opinions on best practices for the interface between JSF pages and backing beans.
One thing that I never can settle on is the structure of my backing beans. Furthermore, I have never found a good article on the subject.
What properties belong on which backing beans? When is it appropriate to add more properties to a given bean as opposed to creating a new bean and adding the properties onto it? For simple applications, does it make sense to just have a single backing bean for the whole page, considering the complexity involved with injecting one bean into another? Should the backing bean contain any actual business logic, or should it strictly contain data?
Feel free to answer these questions and any others that may come up.

As for reducing coupling between the JSF page and the backing bean, I never allow the JSF page to access any backing bean property's properties. For example, I never allow something such as:
<h:outputText value="#{myBean.anObject.anObjectProperty}" />

I always require something like:
<h:outputText value="#{myBean.theObjectProperty}" />

with a backing bean value of:
public String getTheObjectProperty()
{
    return anObject.getAnObjectProperty();
}

When I loop over a collection, I use a wrapper class to avoid drilling down into an object in a data table, for instance.
In general, this approach feels "right" to me. It avoids any coupling between the view and the data. Please correct me if I'm wrong.
Comment: For more information, see BalusC's answer at http://stackoverflow.com/questions/7223055/making-distinctions-between-different-kinds-of-jsf-managed-beans/7223910#7223910
Comment: Can you given an example for: When I loop over a collection, I use a wrapper class to avoid drilling down into an object in a data table, for instance.
Answer: You might want to check this out: making distinctions between different kinds of JSF managed beans.
Here is a description of the different bean types, as defined in the above article by Neil Griffin:

Model Managed-Bean: Normally session scope.  This type of managed-bean participates in the "Model" concern of the MVC design pattern. When you see the word "model" -- think DATA. A JSF model-bean should be a POJO that follows the JavaBean design pattern with getters/setters encapsulating properties. The most common use case for a model bean is to be a database entity, or to simply represent a set of rows from the result set of a database query.
Backing Managed-Bean: Normally request scope. This type of managed-bean participates in the "View" concern of the MVC design pattern. The purpose of a backing-bean is to support UI logic, and has a 1::1 relationship with a JSF view, or a JSF form in a Facelet composition. Although it typically has JavaBean-style properties with associated getters/setters, these are properties of the View -- not of the underlying application data model. JSF backing-beans may also have JSF actionListener and valueChangeListener methods.
Controller Managed-Bean: Normally request scope.  This type of managed-bean participates in the "Controller" concern of the MVC design pattern. The purpose of a controller bean is to execute some kind of business logic and return a navigation outcome to the JSF navigation-handler. JSF controller-beans typically have JSF action methods (and not actionListener methods).
Support Managed-Bean: Normally session or application scope.  This type of bean "supports" one or more views in the "View" concern of the MVC design pattern. The typical use case is supplying an ArrayList to JSF h:selectOneMenu drop-down lists that appear in more than one JSF view. If the data in the dropdown lists is particular to the user, then the bean would be kept in session scope. However, if the data applies to all users (such as a dropdown lists of provinces), then the bean would be kept in application scope, so that it can be cached for all users.
Utility Managed-Bean:  Normally application scope.  This type of bean provides some type of "utility" function to one or more JSF views. A good example of this might be a FileUpload bean that can be reused in multiple web applications.
Comment: Still, I can't get to it that this answer is currently at 71 upvotes. Whoever implemented their JSF application according those rules must undoubtedly afterwards be ranting on JSF being a terribly opaque framework and their JSF applications being a big code mess and they all blame JSF itself instead of their own bad approach based on the wrong lessons and so-called "best practices" learnt.
Comment: This is a great article. I have never seen it before and am definitely glad that you posted it. Whoever voted this down is crazy. It's not iceFaces specific.
Comment: Link to actual article appears to be gone.
Comment: A copy can be found [here](http://java.dzone.com/articles/making-distinctions-between)
Comment: is any of these beans' logic executed in the browser instead of in the server?
Comment: @BalusC care to explain what the correct approach to JSF should be like then?
Comment: @Ghos3t: see link which OP itself posted in question's comments.
Answer: Great question. I suffered a lot with the same dilemma when I moved to JSF. It really depends on your application. I'm from the Java EE world so I would recommend to have as little business logic in your backing beans as possible. If the logic is purely related to the presentation of your page, then it is fine to have it in the backing bean.
I believe one of the (many) strengths of JSF is actually the fact that you can expose domain objects directly on the managed beans. I would therefore strongly recommend the <:outputText value="#{myBean.anObject.anObjectProperty}" /> approach, otherwise you end up making too much work for yourself in manually exposing each property. Furthermore it would be a bit of a mess when inserting or updating data if you encapsulated all the properties. There are situations where a single domain object may not be sufficient. In those cases I prepare a ValueObject before exposing it on the bean.
EDIT: Actually, if you are going to encapsulate every object property that you want to expose, I would recommend that you instead bind UI components to the backing bean and then inject the content directly into the value of the component.
In terms of bean structure the turning point for me was when I forcefully ignored all the stuff I knew about building web applications and started treating it as a GUI application instead. JSF mimics Swing a lot and therefore the best practices for developing Swing applications would mostly also apply to building JSF applications.
Comment: Thanks for your insight. I never really did much in the way of swing applications (other than academic projects a long time ago). What are some good principles of swing applications?

Also, why is it a mess when inserting and updating values? seems the same to me?
Answer: I think the most important thing with your backing beans is to seperate their logics. If you have a front page for a CMS system I would see it as bad practice to put every piece of code into one bean because:

The bean would turn very large eventually
Its easier for other people to find what their looking for if they are troubleshooting the login page, if they then can easily just look up the loginBean.java file.
Sometimes you have small pieces of functionality that is clearly distinct from the rest of your code, by separating this I would imagine you would make it easier on yourself to redevelop/expand this code into something bigger, when you already have a nice bean with good structure.
Having 1 big bean, to do it all, will make it more memory dependant if/when you have to do declarations like this MyBigBean bigBean = new MyBigBean(); instead of using the funksjonality you actually needed by doing LoginBean loginBean = new LoginBean(); (Correct me if Im wrong here???)
In my opinion, separating your beans is like separating your methods. You dont want 1 big method which runs over 100's of lines, but rather split it up with new methods that handles their specific task.
Remember, most likely someone other than you will have to work on your JSF projects aswell.

As for the coupling, I dont see it as a troublesome issue to allow your JSF pages access too the properties in objects in your backingbean. This is support which is built into JSF, and really just makes it easier to read and build imo. Your allready separating the MVC logic strictly. By doing this your saving yourself tons of lines with getters and setters in your backingbean. For example I have a really huge object given to me by the web services, where I need to use some properties in my presentation. If I were to make a getter/setter for each property my bean would expand with atleast 100 more lines of variables and methods for getting the propeties. By using the built in JSF functionality my time and precious code lines are spared.
Just my 2 cents regarding this even with the question already marked as answered.
Comment: however, if you have a huge object that's sitting in your bean, and you have -- say -- 15 EL functions digging into that object from the JSF page, you are now tied not only to the bean, but to that object. Therefore it will be difficult to remove that object without breaking the UI.
Comment: But wont your backing bean be tied to that object aswell? And your UI tied to the backing bean? When you then have to modify it, you will have to change all your getters/setters in both UI and bean.
Answer: I might not answer your every question, because few seems quite dependent on case to case.

This is fine to have a business logic in your backing bean. It depends where are you coming from. If you are practicing domain driven design, you will be tempted to include the business logic in to backing bean or may be persistence logic as well. They argue that why so dumb object. Object should carry not just state but behavior too. On the other hand if you consider traditional Java EE way of doing things, you might be feeling like having data in your backing bean, which also can be your entity bean, and other business and persistence logic in some session bean or something. That is fine too.
Its perfectly fine to have single backing bean for the whole page. I don't see any problem with this alone. This might not look right, but that depends on the case.
Your other question is far more dependent on case you are having in hand. I would prefer to go domain driven here, it might be appropriate to add properties to the existing or otherwise create a new bean for that. Which ever suits better. I don't think there is any silver bullet for this.
Which properties belongs to which backing bean. Well, is it not depend on the domain object? Or may be the question is not that clear.

Moreover, in your given code example, I am not seeing any huge benefit.
Comment: if--for example--we were to change from using home-brewed POJOs created with JDBC queries, to Hibernate entities that had slightly different field names, we would have to not only change the backing bean. We would have to change the JSF page also. Not so with my code example. Just change the bean.
Comment: In that case you can make your backing beans, entities. then you just need to change the JSF pages. Or it depends why would you change the name of the properties anyway? that would only make sense when you rename the field to match your database column name. But thats a different case, altogether.
Answer: I would not necessary keep only one backing bean per page. It depends on functionality but most of the time I had one bean per page as mostly one page handle one functionality. For example on a page I have a register link (I will link with RegisterBean) and a shopping basket link (ShoopingBasketBean).
I do use this <:outputText value="#{myBean.anObject.anObjectProperty}" /> as I normally keep backing beans as action beans which holds data object. I don't want to write a wrapper in my backing bean to access the properties of my data objects.
Answer: I like to test business code without View's, so I consider BackingBeans as interfaces from View to Model code. I never put any rule or process in a BackingBean. That code goes into Services or Helpers, allowing reuse.
If you use validators, put them out of your BackingBean and reference them from your validation method.
If you access DAOs for filling Selects, Radios, Checkboxes, do that always out of a BackingBean.
Believe me!. You can inject a JavaBean into a BackingBean, but try to inject a BackingBean into another one. You will be soon in a nigntmare of maintenance and understanding code.


Is it possible to flip two curves at the end of an animation caused by an if iteration?

Question: I try to get used to, building Background animations within a VB.net Forms paint Event. To improve my search i still Need some help. With the present Information i use a VB.net Windows Form-Application. The Form has the size 300 x 300, and one timer Event.
Public Class Form1

Dim z As Integer = 0
Dim simpleZero As Integer = 0

Dim X As Integer = 150
Dim Y As Integer = 100
Dim rightX As Integer = 250
Dim rightY As Integer = 100

Dim sunset As Integer = 50
Dim sundawn As Integer = 100
Dim leftX As Integer = 101
Dim leftY As Integer = 100

Private Sub CurveBall(g As Graphics)
    With g
        Dim canon() As Point = {New Point(simpleZero + 150, 100), _
        New Point(simpleZero + 150, 85), _
        New Point(simpleZero + 160, 65), _
        New Point(simpleZero + 180, 50)}
        .DrawCurve(New Pen(Color.Black, 3), canon)
    End With
End Sub

Private Sub DrawBall(g As Graphics)
    With g
        Dim CurvePoints() As Point = {New Point(z + 100, 100), _
        New Point(z + 130, 75), _
        New Point(z + 155, 60), _
        New Point(z + 180, 50)}
        .DrawCurve(New Pen(Color.Black, 3), CurvePoints)
    End With
End Sub

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    Timer1.Start()
    DoubleBuffered = True
    CenterToScreen()
End Sub

Dim stepStone As Integer = 1

Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
    If X < 150 Then
        stepStone = 1
    ElseIf X > 200 Then
        stepStone = -1
    End If
    If leftX < 100 Then
        stepStone = 1
    ElseIf leftX > 200 Then
        stepStone = -1
    End If
    If leftX < 200 Then
        z += stepStone
    End If
    If leftX < 200 Then
        simpleZero += stepStone
    End If
    X += stepStone
    leftX += stepStone
    Invalidate()
End Sub

Private Sub Form1_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
    e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
    e.Graphics.DrawLine(New Pen(Color.Black, 3), X, Y, rightX, rightY)
    e.Graphics.DrawLine(New Pen(Color.Black, 3), sunset, sundawn, leftX, leftY)
    CurveBall(e.Graphics)
    DrawBall(e.Graphics)
End Sub
End Class

The Solution are two lines with a gap in the center, moving from a left side to a right side and back again. The center is not empty. A spike or shark flapper is in between the two lines. I want achieve that the flapper truns it`s direction at each turn the if Iteration reaches a side.
To flip the flapper i tried some matrix and Rotation Solutions, but had no success.
Answer: An If Statement in a For Loop brought light to darkness. I can not explain the iterations. Copy and Paste the solution Code is the only way i can offer within my way. Also i have not mirrored the curve Points with a command, the Points are calculated, each seperate. It is still an original Visual Basic 2010 Form 300 x 300 with an additional timer. No other changes.
Public Class Form1

Dim z As Integer = 0
Dim simpleZero As Integer = 0

Dim X As Integer = 150
Dim Y As Integer = 100
Dim rightX As Integer = 250
Dim rightY As Integer = 100

Dim sunset As Integer = 50
Dim sundawn As Integer = 100
Dim leftX As Integer = 100
Dim leftY As Integer = 100

Private Sub CurveBall(ByVal e As PaintEventArgs)
    For aNewword As Integer = 0 To -stepStone
        If X < 200 Then
            With e.Graphics
                Dim canon() As Point = {New Point(simpleZero + 150, 100), _
                New Point(simpleZero + 150, 85), _
                New Point(simpleZero + 160, 65), _
                New Point(simpleZero + 180, 50)}
                .DrawCurve(New Pen(Color.Black, 3), canon)
            End With
        End If
    Next
End Sub

Private Sub DrawBall(ByVal e As PaintEventArgs)
    For aNewword As Integer = 0 To -stepStone
        If X < 200 Then
            With e.Graphics
                Dim CurvePoints() As Point = {New Point(z + 100, 100), _
                New Point(z + 130, 75), _
                New Point(z + 155, 60), _
                New Point(z + 180, 50)}
                .DrawCurve(New Pen(Color.Black, 3), CurvePoints)
            End With
        End If
    Next
End Sub

Private Sub stelar(ByVal e As PaintEventArgs)
    For aNewword As Integer = 0 To stepStone
        If leftX > 100 Then
            With e.Graphics
                Dim CurvePoints() As Point = {New Point(simpleZero + 150, 100), _
                New Point(simpleZero + 114, 75), _
                New Point(simpleZero + 87, 60), _
                New Point(simpleZero + 68, 50)}
                .DrawCurve(New Pen(Color.Black, 3), CurvePoints)
            End With
        End If
    Next
End Sub

Private Sub vektor(ByVal e As PaintEventArgs)
    For aNewword As Integer = 0 To stepStone
        If leftX > 100 Then
            With e.Graphics
                Dim CurvePoints() As Point = {New Point(z + 100, 100), _
                New Point(z + 98, 85), _
                New Point(z + 84, 65), _
                New Point(z + 68, 50)}
                .DrawCurve(New Pen(Color.Black, 3), CurvePoints)
            End With
        End If
    Next
End Sub

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    CenterToScreen()
    Timer1.Start()
    DoubleBuffered = True
End Sub

Dim stepStone As Integer = 1

Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
    If X < 150 Then
        stepStone = +1
    ElseIf X > 200 Then
        stepStone = -1
    End If
    If leftX < 100 Then
        stepStone = 1
    ElseIf leftX > 200 Then
        stepStone = -1
    End If
    If leftX < 200 Then
        z += stepStone
    End If
    If leftX < 200 Then
        simpleZero += stepStone
    End If
    X += stepStone
    leftX += stepStone
    Refresh()
End Sub

Private Sub Form1_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
    e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
    e.Graphics.DrawLine(New Pen(Color.Black, 3), X, Y, rightX, rightY)
    e.Graphics.DrawLine(New Pen(Color.Black, 3), sunset, sundawn, leftX, leftY)
    CurveBall(e)
    DrawBall(e)
    stelar(e)
    vektor(e)
End Sub
End Class

My Answer is not a bridge it is only a possible answer. But there are more Solutions that could be written. Shorter, but until no one provides easy Cookies i am glad to have a solution.


Deserialize XML with multiple types

Question: I'm trying to deserialize XML where some same name tags have different xsi types:
<user-defined-data-row>
  <field name="entity">
    <field-value xsi:type="field-text-valueType">
      <value>Test</value>
    </field-value>
  </field>
  <field name="expiry_date">
    <field-value xsi:type="field-date-valueType">
      <value>2001-10-07</value>
    </field-value>
  </field>
</user-defined-data-row>

This is easily achieved by deserializing the xml into this model:
[XmlRoot(ElementName = "field-value", Namespace = "http://www.crsoftwareinc.com/xml/ns/titanium/common/v1_0")]
[XmlType("field-text-valueType")]
public class Fieldvalue
{
    [XmlElement(ElementName = "value", Namespace = "http://www.crsoftwareinc.com/xml/ns/titanium/common/v1_0")]
    public string Value { get; set; }
}

The only thing that differs are the types in the XML:
field-text-valueType
field-date-valueType
How can I make the C# class interpret both types using something like
[XmlType("field-text-valueType")]

EDIT: deserializing not serializing
Comment: Do you mean **de**serializing?
Comment: The type attribute indicates the class inherits a base class where field-value is the base class name and field-text-valueType is the sub class.
Answer: The xsi:type attributes you are seeing in your XML are standard W3C XML Schema attributes that allow an element to explicitly specify its type; for details see here.  As explained in Xsi:type Attribute Binding Support, XmlSerializer supports this mechanism for deserialization of polymorphic types, specifically by use of XmlIncludeAttribute.
First, define an abstract base class FieldValue as follows:
public static class XmlNamespaces
{
    public const string Crsoftwareinc = "http://www.crsoftwareinc.com/xml/ns/titanium/common/v1_0";
}

[XmlRoot("field-value", Namespace = XmlNamespaces.Crsoftwareinc)]
[XmlType("field-value", Namespace = XmlNamespaces.Crsoftwareinc)]
[XmlInclude(typeof(TextFieldValue)),
XmlInclude(typeof(DateFieldValue))]
public abstract partial class FieldValue
{
    // It's not necessary to have this in the base class but I usually find it convenient.
    public abstract object GetValue();
}

Next, for each possible xsi:type="XXX" value, define a derived type of FieldValue whose XmlTypeAttribute.TypeName matches the xsi:type value.  Decorate the base class with [XmlInclude(typeof(TDerivedFieldValue))] attributes for each (already shown above):
[XmlRoot("field-text-valueType", Namespace = XmlNamespaces.Crsoftwareinc)]
[XmlType("field-text-valueType", Namespace = XmlNamespaces.Crsoftwareinc)]
public class TextFieldValue : FieldValue
{
    [XmlElement("value")]
    public string Value { get; set; }

    public override object GetValue() { return Value; }
}

[XmlRoot("field-date-valueType", Namespace = XmlNamespaces.Crsoftwareinc)]
[XmlType("field-date-valueType", Namespace = XmlNamespaces.Crsoftwareinc)]
public class DateFieldValue : FieldValue
{
    [XmlElement("value", DataType = "date")]
    public DateTime Value { get; set; }

    public override object GetValue() { return Value; }
}

Then define the containing type corresponding to <field> and other, higher elements as follows:
[XmlRoot("field", Namespace = XmlNamespaces.Crsoftwareinc)]
[XmlType("field", Namespace = XmlNamespaces.Crsoftwareinc)]
public class Field
{
    [XmlAttribute("name")]
    public string Name { get; set; }

    [XmlElement("field-value")]
    public FieldValue FieldValue { get; set; }
}

[XmlRoot("user-defined-data-row", Namespace = XmlNamespaces.Crsoftwareinc)]
[XmlType("user-defined-data-row", Namespace = XmlNamespaces.Crsoftwareinc)]
public class UserDefinedDataRow
{
    [XmlElement("field")]
    public List<Field> Fields { get; set; }
}

// The XML for the root object is not shown so this is just a stub
[XmlRoot("root", Namespace = XmlNamespaces.Crsoftwareinc)]
[XmlType("root", Namespace = XmlNamespaces.Crsoftwareinc)]
public class RootObject
{
    [XmlElement("user-defined-data-row")]
    public List<UserDefinedDataRow> Rows { get; set; }
}

Notes:

If the base class FieldValue has a namespace specified in via XmlTypeAttribute.Namespace, then the derived classes must also, or else an error will get thrown by XmlSerializer.
Once an [XmlType] namespace is defined, it automatically applies to all serialized properties, so it isn't necessary to specify the same namespace via [XmlElement(Namespace = "http://www.crsoftwareinc.com/xml/ns/titanium/common/v1_0")] attributes.
I got tired of repeatedly typing the namespace "http://www.crsoftwareinc.com/xml/ns/titanium/common/v1_0" and so I extracted it into a constant.
Other derived types of FieldType can be added easily, e.g.:
[XmlRoot("field-decimal-valueType", Namespace = XmlNamespaces.Crsoftwareinc)]
[XmlType("field-decimal-valueType", Namespace = XmlNamespaces.Crsoftwareinc)]
public class DecimalFieldValue : FieldValue
{
    [XmlElement("value")]
    public decimal Value { get; set; }

    public override object GetValue() { return Value; }
}

[XmlInclude(typeof(DecimalFieldValue))]
public abstract partial class FieldValue { }

Don't forget to add [XmlInclude(typeof(DecimalFieldValue))] when doing so.
If you have been given an XSD for the XML you are trying to deserialize that specifies the possible types of <field-value> via e.g. an <xsd:extension> element as shown in Generating XML Documents from XML Schemas: Abstract Types, then xsd.exe will generate classes that include an appropriate type hierarchy.  But if you only have the XML, then xsd.exe and Paste XML as Classes will not generate a correct type hierarchy using whatever xsi:type attributes are present.
For more about this limitation see xsi:type attribute messing up C# XML deserialization.
Your XML is not well-formed because it omits a declaration for the xsi: namespace.  Also, a default namespace xmlns="http://www.crsoftwareinc.com/xml/ns/titanium/common/v1_0" is not defined so none of the elements are actually in this namespace.  Thus I assume your XML is a fragment of some larger document that is valid, e.g.
<root
 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://www.crsoftwareinc.com/xml/ns/titanium/common/v1_0">
  <user-defined-data-row>

  </user-defined-data-row>
</root>

Sample working .Net fiddle here.

Deserialize XML with multiple types


How to get internal storage size of a windows phone 8 device programmatically

Question: I'm creating a windows phone 8 app and I need to get internal storage size of the device. I'm using C# in building my app.
Comment: What would you do with the answer?  Your app cannot determine whether user is running some other app which is competing for available memory.  Or if your app starts first and hogs most of avail memory, then user decides to start some other app, it might yield laggy performance in either app, or both.
Comment: i need yo calculate the device internal storage !
Answer: From here:
How much storage do I have access to on WP7?
You can test for available space with IsolatedStorageFile.AvailableFreeSpace.
You should be careful about using all available space as it will impact other apps and general device performance. Hopefully the OS will stop anything horrible happening if you did use all free space but best to try and avoid being the cause of this.
There are some limits on the number of fies and directories you can have but you're very unlikely to hit these. Details at http://dotnetcatch.wordpress.com/2010/09/08/wp7-how-many-files-does-it-take-to-crash-isolatedstorage-more-than-you-think/
Comment: i'm just want to get phone internal storage and total available storage
EX:
a method return
Total Storage : 14.2 GB
Free Space : 1.3 GB


NumPy: calculate cumulative median

Question: I have sample with size = n.
I want to calculate for each i: 1 <= i <= n  median for sample[:i] in numpy.
For example, I counted mean for each i:
cummean = np.cumsum(sample) / np.arange(1, n + 1)
Can I do something similar for the median without cycles and comprehension?
Answer: Knowing that Python has a heapq module that lets you keep a running 'minimum' for an iterable, I did a search on heapq and median, and found various items for steaming medium.  This one:
http://www.ardendertat.com/2011/11/03/programming-interview-questions-13-median-of-integer-stream/
has a class streamMedian that maintains two heapq, one with the bottom half of the values, the other with top half.  The median is either the 'top' of one or the mean of values from both.  The class has an insert method and a getMedian method.  Most of the work is in the insert.
I copied that into an Ipython session, and defined:
def cummedian_stream(b):
    S=streamMedian()
    ret = []
    for item in b:
        S.insert(item)
        ret.append(S.getMedian())
    return np.array(ret)

Testing:
In [155]: a = np.random.randint(0,100,(5000))
In [156]: amed = cummedian_stream(a)
In [157]: np.allclose(cummedian_sorted(a), amed)
Out[157]: True
In [158]: timeit cummedian_sorted(a)
1 loop, best of 3: 781 ms per loop
In [159]: timeit cummedian_stream(a)
10 loops, best of 3: 39.6 ms per loop

The heapq stream approach is way faster.

The list comprehension that @Uriel gave is relatively slow.  But if I substitute np.median for statistics.median it is faster than @Divakar's sorted solution:
def fastloop(a):
    return np.array([np.median(a[:i+1]) for i in range(len(a))])

In [161]: timeit fastloop(a)
1 loop, best of 3: 360 ms per loop

And @Paul Panzer's partition approach is also good, but still slow compared to the streaming class.
In [165]: timeit cummedian_partition(a)
1 loop, best of 3: 391 ms per loop

(I could copy the streamMedian class to this answer if needed).
Comment: Yep, not even `numpy` can make an `O(n^2)` (or worse) algorithm faster than an -- what is it -- `O(n log n)` one or even better?
Answer: Here's an approach that replicates elements along rows to give us a 2D array. Then, we would fill the upper triangular region with a big number so that later on when we sort the array along each row, would basically sort all elements till the diagonal elements and that simulates the cumulative windows. Then, following the definition of median that chooses the middle one or the mean of two middle ones (for even no. of elements), we would get the elements at the first position : (0,0), then for the second row : mean of (1,0) & (1,1), for the third row : (2,1), for the fourth row : mean of (3,1) & (3,2) and so on. So, we will extract out those elements from the sorted array and thus have our median values.
Thus, the implementation would be -
def cummedian_sorted(a):
    n = a.size
    maxn = a.max()+1
    a_tiled_sorted = np.tile(a,n).reshape(-1,n)
    mask = np.triu(np.ones((n,n),dtype=bool),1)

    a_tiled_sorted[mask] = maxn
    a_tiled_sorted.sort(1)

    all_rows = a_tiled_sorted[np.arange(n), np.arange(n)//2].astype(float)
    idx = np.arange(1,n,2)
    even_rows = a_tiled_sorted[idx, np.arange(1,1+(n//2))]
    all_rows[idx] += even_rows
    all_rows[1::2] /= 2.0
    return all_rows

Runtime test
Approaches -
# Loopy solution from @Uriel's soln
def cummedian_loopy(arr):
    return [median(a[:i]) for i in range(1,len(a)+1)]

# Nan-fill based solution from @Nickil Maveli's soln
def cummedian_nanfill(arr):
    a = np.tril(arr).astype(float)
    a[np.triu_indices(a.shape[0], k=1)] = np.nan
    return np.nanmedian(a, axis=1)

Timings -
Set #1 :
In [43]: a = np.random.randint(0,100,(100))

In [44]: print np.allclose(cummedian_loopy(a), cummedian_sorted(a))
    ...: print np.allclose(cummedian_loopy(a), cummedian_nanfill(a))
    ...:
True
True

In [45]: %timeit cummedian_loopy(a)
    ...: %timeit cummedian_nanfill(a)
    ...: %timeit cummedian_sorted(a)
    ...:
1000 loops, best of 3: 856 µs per loop
1000 loops, best of 3: 778 µs per loop
10000 loops, best of 3: 200 µs per loop

Set #2 :
In [46]: a = np.random.randint(0,100,(1000))

In [47]: print np.allclose(cummedian_loopy(a), cummedian_sorted(a))
    ...: print np.allclose(cummedian_loopy(a), cummedian_nanfill(a))
    ...:
True
True

In [48]: %timeit cummedian_loopy(a)
    ...: %timeit cummedian_nanfill(a)
    ...: %timeit cummedian_sorted(a)
    ...:
10 loops, best of 3: 118 ms per loop
10 loops, best of 3: 47.6 ms per loop
100 loops, best of 3: 18.8 ms per loop

Set #3 :
In [49]: a = np.random.randint(0,100,(5000))

In [50]: print np.allclose(cummedian_loopy(a), cummedian_sorted(a))
    ...: print np.allclose(cummedian_loopy(a), cummedian_nanfill(a))

True
True

In [54]: %timeit cummedian_loopy(a)
    ...: %timeit cummedian_nanfill(a)
    ...: %timeit cummedian_sorted(a)
    ...:
1 loops, best of 3: 3.36 s per loop
1 loops, best of 3: 583 ms per loop
1 loops, best of 3: 521 ms per loop

Comment: I got faster times for `loopy`, but I was using `np.median`, not the stats one.
Answer: Use statistics.median and cummulative list comprehension (note that odd indices contains medians of even-length lists - where the median is the average of the two median elements, so it usually results with a decimal and not an integer):
>>> from statistics import median
>>> arr = [1, 3, 4, 2, 5, 3, 6]
>>> cum_median = [median(arr[:i+1]) for i in range(len(arr)-1)]
>>> cum_median
[1, 2.0, 3, 2.5, 3, 3.0]

Comment: without open cycles and comprehension
Comment: `np.median` is much faster in this role than `statistics.median`.
Answer: Is there room for a late entry?
def cummedian_partition(a):
    n = len(a)
    assert n%4 == 0 # for simplicity
    mn = a.min() - 1
    mx = a.max() + 1
    h = n//2
    N = n + h//2
    work = np.empty((h, N), a.dtype)
    work[:, :n] = a
    work[:, n] = 2*mn - a[0]
    i, j = np.tril_indices(h, -1)
    work[i, n-1-j] = (2*mn - a[1:h+1])[j]
    k, l = np.ogrid[:h, :h//2 - 1]
    work[:, n+1:] = np.where(k > 2*l+1, mx, 2 * mn - mx)
    out = np.partition(work, (N-n//2-1, N-n//2, h//2-1, h//2), axis=-1)
    out = np.r_[2*mn-out[:, h//2: h//2-2:-1], out[::-1, N-n//2-1:N-n//2+1]]
    out[::2, 0] = out[::2, 1]
    return np.mean(out, axis=-1)

The algorithm uses partition which has linear complexity. Some gymnastics are required because np.partition does not support per-line split points. Combined complexity and memory required are quadratic.
Timings compared to current best:
for j in (100, 1000, 5000):
    a = np.random.randint(0, 100, (j,))
    print('size', j)
    print('correct', np.allclose(cummedian_partition(a), cummedian_sorted(a)))
    print('Divakar', timeit(lambda: cummedian_sorted(a), number=10))
    print('PP', timeit(lambda: cummedian_partition(a), number=10))

#  size 100
#  correct True
#  Divakar 0.0022412699763663113
#  PP 0.002393342030700296
#  size 1000
#  correct True
#  Divakar 0.20881508802995086
#  PP 0.10222102201078087
#  size 5000
#  correct True
#  Divakar 6.158387024013791
#  PP 3.437395485001616

Answer: There is an approximated solution. if you treat the list arr of values as probability mass function. you can use the np.cumsum(arr) to get the cumulative distribution function. By definition, median is only for half of the probability.
which give you an approximated solution
arr[np.searchsorted(np.cumsum(arr), np.cumsum(arr)/2)]

Comment: I think this assumes that `arr` is already sorted, in which case you can simply look at index `i//2` for each `i`.

NumPy: calculate cumulative median


What does the stack of this function look like?

Question: I have to following question.
Given is the function:
show(int a, int b)
{
    int v1;
    int v2;
}

a and b are parameters. v1 en v2 are local variables. Draw a stack in which its is clear where a, b, v1 , v2, the old frame pointer en the return adress are. Also show where the high and low stack addresses are.
I hope i have been clear enough.
Edit:
What i have now is:
v2      <-- SP
v1
prevLV  <-- LV
Ra
a
b

Comment: What i have now from bottom to top. b - a - rA - prevLV - v1 - v2. With LV --> prevLV and SP--> v2
Comment: What architecture is this?  x86?  MIPS?  SPARC?
Answer: Drawing a definitive picture is hard as it depends on the implementation of the JVM, but what you have now is VERY unlikely to be correct.
Because Java doesn't distinguish args from temps (see the iload, etc.. bytecodes), they're going to need to appear side by side in memory, or someone's going to have to copy them from the caller pending stack to the callee at frame construction time (which tends to be expensive).


Unhandled exceptions in field initializations

Question: Does Java have any syntax for managing exceptions that might be thrown when declaring and initializing a class's member variable?
public class MyClass
{
  // Doesn't compile because constructor can throw IOException
  private static MyFileWriter x = new MyFileWriter("foo.txt");
  ...
}

Or do such initializations always have to be moved into a method where we can declare throws IOException or wrap the initialization in a try-catch block?
Comment: akf's answer is correct, but if you hate declaring new methods, you can also use static blocks to initialise your static variables; you can have try/catches within static blocks.
Comment: Lest others misread my last comment as an endorsement of the static-block approach: I prefer creating new methods. I just suggested an alternative for those who don't. :-)
Comment: Sorry, I forgot to mark the field as static. Does the recommendation still apply?
Comment: Or you can use non-static (i.e. instance) init blocks to initialise non-static fields. Try/catches work just as well. (Some consider this a "hidden feature", http://stackoverflow.com/questions/15496/hidden-features-of-java/47493#47493)
Answer: Use a static initialization block
public class MyClass
{
  private static MyFileWriter x;

  static {
    try {
      x = new MyFileWriter("foo.txt");
    } catch (Exception e) {
      logging_and _stuff_you_might_want_to_terminate_the_app_here_blah();
    } // end try-catch
  } // end static init block
  ...
}

Comment: you also have the option to throw a RuntimeException if you want to propagate after you do your handling.
Comment: If the MyFileWriter has to be initialized for the class to function properly, then a RuntimeException should be thrown which will prevent the class from being loaded.  This would effectively render any code trying to use this class doomed to fail, which is probably the desired behaviour if it is crucial to the running of your application.  Logging without doing this will potentially make every call to MyClass methods fail instead.
Comment: Isn't this a problem if you have more than one class witha MyFileWriter member? You would have to rewrite your static block in every class.
Comment: Since it's a class member, doesn't that just come with the territory?
Answer: it is best practice to move those sorts of initializations to methods that can property handle exceptions.
Comment: agreed. I implemented a Factory method in my answer.
Answer: This construction is illegal, as you have discovered. Members whose constructors throw checked exceptions cannot be constructed except when in a context that allows exception handling, such as a constructor, an instance initializer, or (for a static member) a static initializer.
So this would be a legal way to do it:
public class MyClass {
    MyFileWriter x;
    {
        try {
            x = new MyFileWriter("foo.txt");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    ...
}

Legal, but rather ugly. I would prefer either initializing it in the constructor and declaring the exception there, or else making the user call a method to explicitly initialize it. But if the user must initialize it, you must then account in any dependent methods for the possibility of the object's being invalid.
If you are writing MyClass as a wrapper for MyFileWriter, I would say to do the initialization in the constructor. Otherwise, I would first question whether it is necessary to have a writer open during the object's entire lifetime. It may be possible to refactor this away.
Edit: When I was writing this, the "static" hadn't been added to the field. This changes things quite a bit: I now would like to know why on earth you want to have a writer open for the classloader's entire lifetime. How could it ever be closed?
Is this a home-grown logging system of some sort? If so, I'd encourage you to have a look at java.util.logging or any of the many fine third-party logging frameworks around.
Answer: An exception thrown from a static intialiser may indicate a design problem. Really you shouldn't be attempting to load files into statics. Also static should not, in general,  be mutable.
For instance, working back with JUnit 3.8.1 you could almost use it from an applet/WebStart, but it failed due to one static initialiser doing file access. The rest of the class involved was fitted the context fine, it's just this bit of static which did not fit the context and blew the whole framework away.
There are, some legitimate cases where an exception is thrown. If it's a case that the environment doesn't have a particular feature, say, because it's an old JDK, then you might want to substitute implementations, and there is nothing out of the ordinary. If the class really is borked, throw an unchecked exception rather than allowing a broken class to exist.
Depending on your preference and the problem at hand, there's two common ways to go around it: an explicit static initialiser and a static method. (I, and I think most people, prefer the former; I believe Josh Bloch prefers the latter.)
private static final Thing thing;

static {
    try {
        thing = new Thing();
    } catch (CheckedThingException exc) {
        throw new Error(exc);
    }
}

Or
private static final Thing thing = newThing();

private static Thing newThing() {
    try {
        return new Thing();
    } catch (CheckedThingException exc) {
        throw new Error(exc);
    }
}

Note: statics should be final (and generally immutable). Being final, correct single assignment is checked by your friendly compiler. Definite assignment means that it may catch broken exception handling - wrap and throw, do not print/log. Strangely, you can't user the class name to qualify the initialisation with the class name in the static initialiser (I'm sure there is a good reason for this).
Instance initialisers are similar, although you can make the constructor throw or you can put the initialiser within the constructor.
Answer: If the class has only one constructor, I usually move such initializers into that constructor.
If the class has more than one constructor, I use an initialization block:
public class MyClass {
   private static MyFileWriter x;

   // initialization block start here
   {
       try {
          x = new MyFileWriter("..");
       } catch(Exception e) {
         // exception handling goes here
       }
   }

   public MyClass() {
    // ctor #1
   }

   public MyClass(int n) {
     // ctor #2
   }
}

The nice thing about an init. block is that it is "injected" into the beginning of every constructor. Thus, you don't need to duplicate the initializers.
Answer: I suggest a factory method:
  public class MyClass{
      private static MyFileWriter fileWriter = MyFileWriter.getFileWriter("foo.txt");

  }

  public class MyFileWriter {
     /*
      * Factory method. Opens files, etc etc
      * @throws IOException.
      */
     public static MyFileWriter getFileWriter(String path) throws IOException{

        MyFileWriter writer  = new FileWriter();

       //stuff that can throw IOException here.

       return writer;
     }

   /*protected constructor*/
    protected MyFileWriter(){

     //build object here.

    }
  }

Comment: This doesn't fix the problem, you have no exception handling in the call to the getFileWriter(), and to add it you will need to put in a static block.
Answer: There is another way to handle exception in field initializations. Let consider your case, where MyFileWriter constructor throws an exception. Consider this sample code for references.
import java.io.IOException;
public class MyFileWriter {
    public MyFileWriter(String file) throws IOException{
         throw new IOException("welcome to [java-latte.blogpspot.in][1]");
    }
}

If we try to initialize file like this.....
public class ExceptionFields{
    MyFileWriter f = new MyFileWriter("Hello");

}

Compiler won't allow us to initialize this. Instead of doing initialization in the static block, you can do like this
Declare a default constructor that throws IOException
import java.io.IOException;
public class ExceptionFields{
    MyFileWriter f = new MyFileWriter("Hello");
    public ExceptionFields() throws IOException{

    }
}

This will initialize your MyFileWriter object.


Canvas won't draw

Question: I don't get it, I have other custom views in which I can draw to canvas perfectly fine. But now the new views I'm creating don't draw to canvas at all! I can't find any discernible difference between what I was doing then and now, it's still the same "canvas.drawLine()" calls afterall.
Here's an example view that will not draw regardless of what I try to do with it (note that the background is black, so the white color should show up)
public class TestView extends View {

    public TestView(Context context)
    {
        super(context);
    }

    public TestView (Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public void onDraw(Canvas canvas){
        Paint paint = new Paint();
        paint.setColor(0xFFFFFF);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(4);

        canvas.drawLine(0,0, 500, 500, paint);
        canvas.drawCircle(0,0, 40, paint);
        Logy.Print("Drew top:" + getTop() + " left:" + getLeft() + " right:" + getRight() + " bottom:" + getBottom());
    }

}

I've looked at other similar questions, and this issue I'm having is definitely not like the others. I didn't mispell onDraw, onDraw IS being called (I can tell via Logy, which is just a simpler facade to Debug.log()). Please consider this before marking this as duplicate of something else.
The dimensions of the view when onDraw is called is 0,0,800,800 (left, top, right, bottom). onDraw is called at least once when the activity starts.
canvas.drawRGB() will flood the view with color.
This view is the only view in the activity, and when I put another "working" custom view in it's place that draws just fine. But now any new custom views I try to get drawing DON'T DRAW.
Comment: What is the height and width of the textview and what color is its background
Comment: Your color has an alpha value of 0, or completely transparent. If you want solid white, change it to `0xFFFFFFFF`, or just use `Color.WHITE`.
Answer: The colour you are drawing with has an alpha value of 0 (aka transparent), and colour of white. Try drawing with use paint.setColor(0xFFFF3432); or something similarly likely to contrast with your background -- see if you see a red line, you know it is working.
Then choose the colour you wish. If it is white you are going for make sure to use 0xFFFFFFFF not 0xFFFFFF
Colour Format:
0xAARRGGBB
where A = Alpha/Transparency, R = Red, G = Green, B = Blue.
Comment: Ah yeah, it's white on a black background so that part isn't so bad.
Answer: You are not overriding the onDraw method.
Try this
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    //your stuff here
}

Comment: You can skip `super.onDraw(canvas);` if you are drawing your custom stuff. It's not mandatory to call.
Comment: It was the transparency value that was getting me. You don't need to override onDraw.
Answer: By assuming that you have provided correct width and height to your view, it seems like your drawing is working right. However there might be a possibility that your activity background is white and the line you are drawing is also white/transparent - causing delusion.
Try changing the paint color to something like:
paint.setColor(Color.Red);

Canvas won't draw


Selecting a Lyapunov function for a SEI model

Question: Consider the system:
$$\frac{dS}{dt} =\nu N -\frac{\beta S I}{N} -\nu S$$
$$\frac{dE}{dt} =\frac{\beta S I}{N} -(\sigma+\nu)E $$
$$\frac{dI}{dt} = \sigma E -\nu I$$
where $N=S+E+I$.
Removing degeneracy we have the following reduced system:
$$\frac{dS}{dt} = -\beta S I +\nu -\nu S$$
$$\frac{dI}{dt} = \sigma  -\sigma S -(\sigma+\nu) I$$
where $\mathcal{R}_0 = \frac{\beta \sigma}{\nu(\nu+\sigma)}$.
The equilibrium point:
\begin{align*}
e_2 : \left( S_2^*, E_2^*, I_2^*\right)&= \left(\frac{\nu\left(\sigma + \nu\right)}{\beta \sigma},\frac{\nu^2 \left( \sigma + \nu \right) \left( \frac{\beta \sigma}{\nu\left(\sigma+\nu\right)} -1 \right) }{\beta\sigma\left(\sigma +\nu \right)} , \frac{\nu\sigma \left( \sigma + \nu \right) \left( \frac{\beta \sigma}{\nu\left(\sigma+\nu\right)} -1 \right) }{\beta\sigma\left(\sigma +\nu \right)}\right)\\[1ex]
\end{align*}
I've been looking for a (global) Lyapunov function to prove global stability for the equilibrium point $e_2$ but I haven't found one that works with this specific system, Any ideas?
A similar question was asked here: Searching for a Lyapunov function for a SIRS model
Comment: I am looking for a canonical answer.
Comment: I don't know exactly what you mean by canonical, but please see  my answer below. I only saw your post recently. There a few minor details to fix, but the time is running short. I hope this helps.
Answer: I believe there is no Lyapunov functional for this ODE system.
Nevertheless, one can prove the global stability of this fixed point by using
information one gathers from  nullclines of this system, which are the curves
where $\dot S=0$ and $\dot I=0$.
From the reduced system, we have the $\frac{dS}{dt}=0$ nullcline given by
$$
-\beta S I +\nu -\nu S=0,
$$
this corresponds to the curve
$$
I=\frac{\nu}{\beta}\left(\frac1S-1\right).
$$
Above it $\frac{dS}{dt}<0$ while below it $\frac{dS}{dt}>0$.
The  nullcline with $\frac{dI}{dt}=0$ is given by
$$
\sigma  -\sigma S -(\sigma+\nu) I=0.
$$
The straight line is
$$
S+\left(1+\frac\nu\sigma\right)I=1.
$$
Below it: $\frac{dI}{dt}>0$, while above it: $\frac{dI}{dt}<0$.
Due to the normalization $S+E+I=1$, hence, all states start in the region
$\Omega$ (greenish shaded area), which we define as below the line $S+I=1$ and in the first quadrant.
Defining the velocity of the flow given in the reduced system as
$$\vec v=(-\beta S I +\nu -\nu S, \sigma  -\sigma S -(\sigma+\nu) I),$$
On the boundary $I=0$ and $0\leq S\leq1$, one finds that $\frac{dS}{dt}=\nu(1-S)\geq 0$ and
$\frac{dI}{dt}=\sigma(1-S)\geq0$, hence the trajectories cannot leave the region
$\Omega$ there.
On the boundary $S=0$ and $0\leq I\leq1$, one finds that $\vec
v\cdot(1,0)=\nu\geq0$, hence the trajectories cannot leave the region
$\Omega$ there either.
Finally, on the boundary $S+I=1$, whose normal vector is
$\hat n=(\frac1{\sqrt{2}}, \frac1{\sqrt{2}})$, $\vec v\cdot \hat
n=-\frac1{\sqrt{2}}\beta SI\leq0$.
Hence, again no trajectories can leave region $\Omega$ across this boundary.
Therefore, we  conclude that $\Omega$ is an invariant region under the flow
defined by the reduced ODE system.
One can show that the shaded blue area between the nullclines is an attractor.
We call it attractor $A$.
Furthermore, there are no other fixed points in $A$ besides the unstable
fixed point $e_1=(1,0)$ and the stable fixed point
$e_2=\left(\frac{\nu\left(\sigma + \nu\right)}{\beta \sigma},
\frac\sigma{\sigma+\nu} -\frac\nu\beta \right)$.
Also, since the trajectories cannot leave region $A$ since on the nullcline 1 (lower boundary of $A$) the flow points upwards and on
nullcline 2 (upper boundary of $A$) the flow points leftwards.
In addition, in region $A$
$\frac{dS}{dt}\leq0$ and $\frac{dI}{dt}\geq0$ for all time, then periodic
solutions (limit cycles) are ruled out.
Furthermore, due to the Poincaré-Bendixon theorem (PBT), all trajectories in that region
with converge to $e_2$.
We don't even need to use the PBT inside region $A$, if we notice that in each vertical cut of it, the flow points from left to right towards fixed-point 2. Take a cut at $S=S_0$ for example, then we obtain $\vec v\cdot (-1,0)=\beta S_0 I -\nu +\nu S_0\geq0$. See the trajectories in Fig. 2, starting at one such cut, illustrating this
point.
Below nullclines 1 and 2, we have $\frac{dS}{dt}>0$ and $\frac{dI}{dt}>0$, hence
no fixed-points and no limit cycles exist there.
In region $\Omega$, below nullcline 1 and above nullcline 2, we have
$\frac{dS}{dt}>0$ and $\frac{dI}{dt}<0$, hence, there are no fixed-points nor
limit cycles therein.
Finally, in region $\Omega$ above both nullclines, we have $\frac{dS}{dt}<0$ and
$\frac{dI}{dt}<0$, hence there are no fixed points nor any periodic orbits
there.
Comment: Firstly, thank you for your answer! How do you know there is no Lyapunov function(s) for this system? Also, if you don't mind, can you post your code for the figure? I am also stuck proving global stability for another but similar model, maybe you can have a look when I post it?
Comment: I can't prove there isn't a LF. I suspect there isn't one. But if your main objective is to prove global stability, then you don't need it. At least, for the present case. Also, one can still improve on my answer. For example, you can take vertical cuts in the region A (between the nullclines) and you can easily find that all trajectories crossing the cut flow from right to left. Then, inside the region A, you wouldn't even need the Poincaré-Bendixon theorem.
Comment: Before I post the code, let me know if the answer I provided is acceptable or not to you.
Comment: As long as it proves global stability, which it does(I need to do a deeper read tomorrow) then, yes it is acceptable. I will respond back to your response tomorrow.
Comment: I just added a few comments and a new figure displaying trajectories to better illustrate my point. Notice also, that with this construction of nullclines, when $R_0\rightarrow1$, $e_2\rightarrow e_1$ and you have a bifurcation.
Comment: You can make similar arguments to this cut-argument in the other regions too.
Comment: Can you explain why you did $\vec v \cdot (1,0)$,  $\vec v\cdot \hat
n  $ and $\vec v \cdot (-1,0)$? Also can you explain the argumentation regarding $dS/dt >0$ ,$dS/dt <0$, $dI/dt >0$, $dI/dt <0$ throughout the answer.
Comment: Also, can you provide the code for the figures?
Comment: I'll add more details explaining the arguments. Yes, sure. Send me your email, if possible, I'll mail you the code.
Comment: my email is: firstname.lastname@example.com


Can't get OpenID auth working with Onelogin and Azure web apps

Question: Microsoft supports Openid as an auth provider for web apps.
https://learn.microsoft.com/en-us/azure/app-service/configure-authentication-provider-openid-connect
This works fine with auth0 but with onelogin, after signing in I receive an error via the browser "The page cannot be displayed because an internal server error has occurred."
Here is my config

{
  "platform": {
    "enabled": true
  },
  "globalValidation": {
    "requireAuthentication": true,
    "unauthenticatedClientAction": "RedirectToLoginPage",
    "redirectToProvider": "onelogin",
    "excludedPaths": []
  },
  "identityProviders": {
    "openIdConnectProviders": {
      "onelogin": {
        "enabled": true,
        "registration": {
          "clientId": "2a55cc10-ec26-0139-d4f3-063fe3b18f59195700",
          "clientCredential": {
            "secretSettingName": "onelogin"
          },
          "openIdConnectConfiguration": {
            "wellKnownOpenIdConfiguration": "https://snapcomms-dev.onelogin.com/oidc/2/.well-known/openid-configuration"
          }
        },
        "login": {
          "nameClaimType": "name",
          "scope": ["openid", "profile", "email"]
        }
      }
    },
    "login": {
      "tokenStore": {
        "enabled": true
           },
      "preserveUrlFragmentsForLogins": true
    },
    "httpSettings": {
      "requireHttps": true
    }
  }
}

and the error from the logstream

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<title>IIS Detailed Error - 500.74 - Internal Server Error</title>

HTTP Error 500.74 - Internal Server Error

The page cannot be displayed because an internal server error has occurred.

<fieldset>
Most likely causes:

IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred.

IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly.

IIS was not able to process configuration for the Web site or application.

The authenticated user does not have permission to use this DLL.

The request is mapped to a managed handler but the .NET Extensibility Feature is not installed.

</fieldset>

<fieldset>
Things you can try:

Ensure that the NTFS permissions for the web.config file are correct and allow access to the Web server's machine account.

Check the event logs to see if any additional information was logged.

Verify the permissions for the DLL.

Install the .NET Extensibility feature if the request is mapped to a managed handler.

Create a tracing rule to track failed requests for this HTTP status code. For more information about creating a tracing rule for failed requests, click here.

</fieldset>

<fieldset>
Detailed Error Information:

Module	   EasyAuthModule_32bit

Notification	   BeginRequest

Handler	   ExtensionlessUrlHandler-Integrated-4.0

Error Code	   0x80004005

Requested URL	   https://snapinf-admntlluke-test-use-as2:80/.auth/login/onelogin/callback?code=4ZZnAKFixx4BFYqh0CLBWkOsgZj&state=%2F

Physical Path	   C:\home\site\wwwroot\.auth\login\onelogin\callback

Logon Method	   Not yet determined

Logon User	   Not yet determined

</fieldset>

<fieldset>
More Information:
This error means that there was a problem while processing the request. The request was received by the Web server, but during processing a fatal error occurred, causing the 500 error.
View more information »

Microsoft Knowledge Base Articles:

</fieldset>

This is the output of the chrome dev tools network tab https://drive.google.com/file/d/1HCWsQH0Npasr4hxvxX-ooeg6QJQbCVzm/view?usp=sharing
Is there some onelogin settings I need to set to get this working?
Answer: Looking at your browser trace I see you're using the Authorization Code Grant and successfully obtaining the auth code, so I would guess that you may be running into an issue in the second part of the grant where your server attempts to exchange the auth code for the tokens. First thing to check on the OneLogin app config is the token endpoint authentication method found on the SSO tab of the app connector. The way that your app/server is performing that code exchange will impact what setting should be used for the token endpoint auth method. More info can be found here: https://developers.onelogin.com/openid-connect/api/authorization-code-grant
Comment: I changed it from basic to post and now it's working! :-)


odoo 10, setup company_parameter,commission, then assign it to a specific model, sale_order

Question: Odoo 10, How to create a commission field (Float) from configuration menu of sale (used for all sale order for a certain period of time) then assign it to a field, namely, sale_order_commission to calculate the commission for a sale_order ( based on amount_total of the sale_order form). Thanks
<code>_inherit = "res.company"
commission_pct =  fields.Float( )
.....
_inherit = "sale.order"
commission_total = fields.Monetary(string="Commissions",
    compute="_compute_commission_total_",        store=True)
....
_compute_commission_total_(self)
    commission_total = amount_total* "commission_pct from res.com"
</code>
However I failed to transfer the "commission_pct" to current self.env"
Answer: you can setup as below: after struggling a while
<code>class YourCompany(models.Model):
    _inherit = "res.company"

    company_commission =  fields.Float( default =15.00)
    commission_ids = fields.One2many( 'sale.order', 'company_id',
        string="Commission_ids")

class SaleOrder(models.Model):
    _inherit = "sale.order"
    company_id = fields.Many2one('res.company', string='company_id',
         required=True)
    company_commission =
             fields.Float(related='company_id.company_commission',
          string="Comm", store = True)
</code>
the "company_commission" field of model "sale.order" always automatically contains the value of  "company_commission" field  of model "res.company".
Have a good day.


tor browser loading but Nothing to see on ubuntu 20.04 ... please help

Question: I can run tor services for my other apps (telegram for example but the tor browser app doesn't work and I don't know what to do ...I have tried to use the tor launcher app but nothing ... my system is updated and downloaded the last version of tor browser on the tor project website
clicking on the .desktop app (the previous version of tor browser has .deb instead...however...) but loading but nothing appears...
Comment: Hey apm! [Right click on `start-tor-browser.desktop`, open Properties or Preferences and change the permission to allow executing file as program.](https://tb-manual.torproject.org/installation/) Now try to open the `.desktop` file. Is it working? BTW, I suggest you to go through the [tour] page.
Answer:
Open Files (GNOME Files/Nautilus).
Click on the hamburger button and click on Preferences.
Go to the Behavior tab and under Executable Text Files select Run them or Ask what to do. If you choose the latter click on Run after launching the start-tor-browser.desktop file.


Flutter - Expandable - How to keep the panel expanded when changing the state

Question: I am using the expandable package (https://pub.dev/packages/expandable), and when I call the setState () method when taping on a checkbox the expandable panel closes during the widget tree reconstruction.
When I call setState () I tell the controller to keep the panel expanded expController.expanded = true, but that doesn't work.
I researched and it seems to me that the solution would be to use a key, but my tests did not work.
Can someone help me? I need to change the state of the checkbox, but keep the panel expanded.
Here is an sample from my code:
class ExpandableCard extends StatefulWidget {
  ExpandableCard({Key key}) : super(key: key);

  @override
  _ExpandableCardState createState() => _ExpandableCardState();
}

class _ExpandableCardState extends State<ExpandableCard> {
  var _value = false;

  @override
  Widget build(BuildContext context) {
    ExpandableController expController =
        new ExpandableController(initialExpanded: false);

    return ExpandableNotifier(
        controller: expController,
        child: Padding(
          padding: const EdgeInsets.all(2),
          child: Card(
            clipBehavior: Clip.antiAlias,
            child: Column(
              children: <Widget>[
                ScrollOnExpand(
                  scrollOnExpand: true,
                  scrollOnCollapse: false,
                  child: ExpandablePanel(
                    theme: const ExpandableThemeData(
                      headerAlignment: ExpandablePanelHeaderAlignment.center,
                      tapBodyToCollapse: false,
                      tapHeaderToExpand: true,
                      tapBodyToExpand: true,
                      hasIcon: true,
                    ),
                    header: Padding(
                      padding: EdgeInsets.all(10),
                      child: Text('HEADER'),
                    ),
                    collapsed: Padding(
                      padding: EdgeInsets.only(left: 4),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('collapsed'),
                        ],
                      ),
                    ),
                    expanded: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        for (var _ in Iterable.generate(3))
                          Padding(
                            padding: EdgeInsets.only(left: 2, bottom: 2),
                            child: Row(
                              children: [
                                Checkbox(
                                  value: _value,
                                  onChanged: (bool value) {
                                    setState(() {
                                      this._value = value;
                                      expController.expanded = true;
                                    });
                                  },
                                ),
                                Text('Checkbox'),
                              ],
                            ),
                          ),
                      ],
                    ),
                    builder: (_, collapsed, expanded) {
                      return Padding(
                        padding:
                            EdgeInsets.only(left: 10, right: 10, bottom: 10),
                        child: Expandable(
                          collapsed: collapsed,
                          expanded: expanded,
                          theme: const ExpandableThemeData(crossFadePoint: 0),
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ));
  }
}

Answer: Sorry it is very late but as i was using expandable in my app then i came to know that:
You can do this by first making an ExpandableController, then assiging its initialExpanded a static bool isOpened (It needs to be static because the bool that we are assigning to initialExpanded should be present before the construction of this ExpandableController). Then in initState(), you have to add an addListener to it that will change the value of isOpened. So now whenever you will tap on the expandable, the listener will listen and will change the value of isOpened and now when the tree widget will reconstruct this isOpened variable will have the current state of the Expandable.
static bool isOpened=false;

ExpandableController additionalInfoController=ExpandableController(
    initialExpanded: isOpened,
  );

// do this in initState

additionalInfoController.addListener(()
     {
       isOpened=!isOpened;
     });

//Then assign this controller to the controller of ExpandablePanel like this

ExpandablePanel(
       controller: additionalInfoController,
);


How do you create and run an html page directly from LocalStorage?

Question: With JavaScript, HTML and CSS and maybe PhoneGap (optional), how do you create and run a simple html page directly from LocalStorage? I basically want a custom HTML page that I can view online through my ipod the first time, and when I go offline with my touch, I can still access the same source and interact with the page as though I still have internet.  I can't find any guides on how to build this project.
Thanks for any pointers or direction to sources that teach this!
Answer: localStorage is very limited, especially in size, and isn't dedicated to this.
To make your site available offline, you need to use the new HTML5 application cache.
Here's a very good tutorial : http://www.html5rocks.com/en/tutorials/appcache/beginner/
An excerpt from the introduction :

It's becoming increasingly important for web-based applications to be
  accessible offline. Yes, all browsers have caching mechanisms, but
  they're unreliable and don't always work as you might expect. HTML5
  addresses some of the annoyances of being offline with the
  ApplicationCache interface.
Comment: @CMKanode +1 diveintohtml5 is a pleasant and very  recommendable read, at least for an introduction.
Comment: Awesome so far, but What if I don't have permission to modify an Apache server to add AddType text/cache-manifest .manifest, is there away to do that indirectly via javascript???  I'm basically in a SharePoint Designer environment.
Comment: A well managed server should already have this type. If not, you can always add it in a `.htaccess` file in the directory of your site.
Comment: Regarding your question about SharePoint : all http servers handle the parameterization of mime types, [even SharePoint](http://www.hosting.com/support/dedicated/IIS/newmime/), so this isn't a problem.
Comment: Thank you - This is where I will begin my journey!
Answer: You may actually be looking for ApplicationCache.  AppCache allows you to specify to the OS what files it should hold on to in memory.  Think of localStorage and sessionStorage as offline variables of sorts, while AppCache is the director that tells the device what resources to hold in local memory for later offline browsing.
Comment: Yes, an ApplicationCache is what I want, but I can't add an add AddType text/cache-manifest .manifest. I'm in a SharePoint environment, not an Apache/PHP location.


chanaging an IF and Weekday formula into a vba

Question: I need help to change the following function into VBA code. This will be part of a larger code.
IF((WEEKDAY($B12)=7),$I12,"")

Answer: There are probably more than 5 ways to do what you want, depending on what exactly do you need. One of these ways is to build a simple custom formula like this:
Public Function changingIfAndWeekday() As Variant

    Application.Volatile

    If Weekday(Range("B12")) = 7 Then
        changingIfAndWeekday = Range("I12")
    Else
        changingIfAndWeekday = ""
    End If

End Function

Answer: You could also do it like so (if you want the result on cell C12):
Sheet1.range("C12").value = "=IF(Weekday(Sheet1.range("B12").value = 7),Sheet1.range("I12").value,"")

You could also do it like so (if you want the result on a variable):
Variable = "=IF(Weekday(Sheet1.range("B12").value = 7),Sheet1.range("I12").value,"")