HTML5 Canvas Drawing History

Question: I'm curious to know how applications such as Adobe Photoshop implement their drawing history with the ability to go back or undo strokes on rasterized graphics without having to redraw each stroke from the beginning...
I'm wanting to implement a similar history function on an HTML5 drawing application I'm working on but duplicating the canvas after every stoke seems like it'd use too much memory to be a practical approach, especially on larger canvas'...
Any suggestions on how this might be implemented in a practical and efficient manner?
Comment: Don't try to save the entire canvas after each stroke. Save each drawing command into an array.  Then you can undo by popping the last element(s) off the end of the array, clearing the canvas and redrawing all the remaining elements (== re-executing all the remaining drawing commands).
Comment: Well I've already been using the method you suggested, and it can take a long time to redraw if there are a lot of strokes or if I'm trying to blur and do other related actions... Therefore, I'm looking for an alternate approach. :) Thanks though...
Comment: Yea, that's what I'm trying to avoid because it takes too long to redraw... I'm wondering how Photoshop and similar applications handle it, they don't redraw everything from the beginning...
Comment: Canvas is fast enough to redraw most drawings from scratch.  Although I don't have the Photoshop source, I suspect that PS actually does redraw from scratch using commands rather than saving entire raster breakpoints. I say this because the PS history lists all the commands. And PS Actions certainly work by playing commands.
Comment: @markE suggests the right direction. Re-drawing shouldn't last more than, say, 10ms, so you should benchmark your code. Notice that you can use both a canvas to store the image at a given point, and on the other hand a stack of command from this point to now. From time to time you 'cut' the stack and update the stored image to the new beginning of the command stack. This way you'll have undos and quick redraw -but limited in time-. But again, first thing i would check is why drawing takes so much time. After all, some intense video games runs ok (on desktop) with the Context2d...
Comment: (another thing : by using a Proxy on the context2D, you can build the command stack very easily (https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Proxy)).
Comment: Well, this isn't my site, but I'm basically trying to do something like: http://www.iscribble.net/gallery/drawing743636-Frozen.html (click the image to see a replay) If it goes much faster than that, especially in Firefox, it begins to lag on the redraw... I want to be able to make more of time slider, like a video, on my site. But that would mean being able to have near-instant redraws...
Answer: I may have a solution.....
<code>var ctx = document.getElementById("canvasId").getContext("2d");
var DrawnSaves = new Array();
var Undo = new Array();
var FigureNumber = 0;
var deletingTimer;
function drawLine(startX, startY, destX, destY) {
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(destX, destY);
    ctx.stroke();
    var Para = new Array();
    Para["type"] = "line";
    Para["fromX"] = startX;
    Para["fromY"] = startY;
    Para["toX"] = destX;
    Para["toY"] = destY;
    DrawnSaves.push(Para);
    FigureNumber++;
}
function undo() {
    ctx.beginPath();
    ctx.clearRect(0, 0, 500, 500);
    Undo[FigureNumber] = DrawnSaves[FigureNumber];
    DrawnSaves[FigureNumber] = "deleted";
    FigureNumber--;
    drawEverything();
    startTimeoutOfDeleting();
}
function undoTheUndo() {
    FigureNumber++;
    DrawnSaves[FigureNumber] = Undo[FigureNumber];
    drawEverything();
    clearTimeout(deletingTimer);
}
function drawEverything() {
    for (i = 0; i < DrawnSaves.length; i++) {
       if (DrawnSaves[i].type == "line") {
          ctx.beginPath();
          ctx.moveTo(DrawnSaves[i].fromX, DrawnSaves[i].fromY);
          ctx.lineTo(DrawnSaves[i].toX, DrawnSaves[i].toY);
          ctx.stroke();
       }
    }
}
function startTimeoutOfDeleting() {
   setTimeout(function() {Undo[FigureNumber] = "deleted";}, 5000);
}
</code>
This is really simple, first I draw a line when the function is called and save all his parameters in an array. Then , in the undo function I just start a timer do delete the figure drawn i 2000 miliseconds, clears the whole canvas and makes it can't be redrawn. in the undoTheUndo function, it stops the timer to delete the figure and makes that the figure can be redrawn. In the drawEverything function, it draws everything in the array based on it's type ("line here"). That's it... :-)
Here is an example working : This, after 2sec UNDOs then after 1sec UNDOTHEUNDO

HTML5 Canvas Drawing History


How does Diablo 3 local multiplayer work?

Question: I know that I can play solo but if I want to play with friends over at my place, do they need to bring a USB stick with their character over? Can I make them a separate character on my account?
Answer: They can make a separate character on your account, or bring their own and put it on another PS3 account without problem.
Source: My own experience in local multiplayer ("split-screen") of D3.
Comment: Alright, but if they brought their own character on a USB stick would I need PS+? One time I tried to load a Battlefield 3 save file on a USB stick and it wouldn't let me saying I needed PS+.
Comment: If this happen, try to create a new PS3 account (on XMB, all left), and try to charge the save on the new account. You should not need PS+
Comment: You mean same screen multiplayer


Is translucent fiberglass roof cooler or hotter than opaque roof

Question: We are building a roof over garden table: sort of like a pergola with roofing. We are using OSB panels for insulation and fiberglass roofing sheets for weather protection. We already chose translucent roofing for availability and price, but we started to wonder whether a dark opaque roofing would offer a better heat protection from the sun.
Dark opaque roofing would become way hotter than a translucent one, but would also protect the underlying OSB panels from direct sunlight. Hot air between the roofing and OSB panels is free to circulate and convey the heat away, but some heat would nevertheless be transferred to OSB panels including with heat radiation from the roofing.
Translucent roofing enables most of the sunshine to be reflected from the bright OSB panels, but I guess a greenhouse effect comes into play and traps some heat, again heating the panels.
So more out of theoretical curiosity than out of need for actual advice I ask: Which roofing would offer cooler environment under the roof: translucent or opaque?
Comment: You could even add some reflective insulation between the transparent roof and the OSB - even kitchen foil would do.
Comment: I measured the temperature under the roof (with translucent roofing) and in the nearby shade. The difference was one and a half degree (C) hotter under the roof. So I guess for practical purposes it doesn't really matter what kind of roofing we have ...
Comment: Why not a light-colored opaque roof? Get a can of white spray paint, and ...
Comment: I like Alex's idea: you can easily paint the underside of the fiberglass, or even the top of the OSB, and reduce the greenhouse effect. Seems like the OSB should be able to take it either way, if there is ventilation at the bottom and top.
Answer: Technically speaking, the coolest thing to do is to have an opaque roofing surface that's a perfect mirror.  Short of that, it should be painted somewhere in the red spectrum, reflecting the infra-red range.
Beyond that, lighter colors are better.
Personally, I'd avoid the translucent, since I don't know whether long-term exposure to UV rays will damage the OSB.
Answer: OSB is sheathing...not insulation. You need sheathing, of course, but note that it won't really be providing any insulative abilities.
If you want to increase airflow under the panels, add furring strips and attach the fiberglass to those. Be sure to put down roofing felt or ice/shield over the OSB to ensure water resistance.
A dark panel would be fine, though the lighter the color, the less it will absorb the sunlight.
Answer: Based on the same physics as a greenhouse, I would expect it to be cooler under the opaque roof because:
A translucent roof allows radiation through and when this hits a surface, a portion of the energy is re-radiated in the infra-red range, which can't get back out, thus warming the air.
But for practical solutions - the comments give some nice ideas.
Answer: It doesn't matter whether the top layer is translucent.  What matters is the overall reflectivity (albedo) of the package.
Your best bet is to scuff-sand the fiberglass then prime and paint it with a very high reflectivity snow white, on the order of 91% reflectivity.  Then keep it clean.


Ubuntu 19.10 disable grub menu

Question: Only Ubuntu 19.10 is installed on my computer. I just don't need the grub menu. I tried all the options I found for /etc/default/grub . It seems as if all my settings are being redefined elsewhere. Always a standard 30 seconds countdown. How to disable its display or adjust the countdown to the minimum value?
Answer: Try this...
sudo -H gedit /etc/default/grub
and change:
#GRUB_HIDDEN_TIMEOUT=0
GRUB_TIMEOUT=10

to:
#GRUB_HIDDEN_TIMEOUT=0
GRUB_TIMEOUT=0

sudo -H gedit /etc/grub.d/30_os-prober # find line 23
and change:
quick_boot="1"

to:
quick_boot="0"

sudo update-grub
reboot
Comment: Well ... I don't know how, but your advice helped. But I need to clarify. I'm not sure, but quick_boot setup helped. After the first reboot, I noticed that the countdown changed from 30 to 5. It turned out to be the GRUB_RECORDFAIL_TIMEOUT setting that I added in previous attempts (But it just didn't work until that moment). Trying to understand what helped, I even changed the quick_boot setting several times back, but for some reason, the GRUB_RECORDFAIL_TIMEOUT setting started working regardless of other settings. Well, that was strange.
Comment: @Dines I can't speak to other modifications that you've made. However, it sounds like my instructions achieved your goal, yes? If so, please remember to accept my answer by clicking the checkmark and up-arrow icons that appear just to the left of my answer. Thanks!
Comment: Already. And yes setting GRUB_RECORDFAIL_TIMEOUT for 0 seconds to completely disable the grub menu
Comment: @Dines Did you add GRUB_RECORDFAIL_TIMEOUT somewhere, or change an existing instance (and where)? 00_header?
Comment: I don't think that I defined GRUB_RECORDFAIL_TIMEOUT somewhere else. I also heard about the 00_header file only now only from you.
Answer: You can't set a grub timeout of 0 but you can set a timeout of 0.1 which is hardly noticeable difference from 0. First use sudo -H gedit /etc/default/grub. Then locate these lines:
#GRUB_HIDDEN_TIMEOUT_QUIET=false
#GRUB_TIMEOUT_STYLE=countdown
#GRUB_HIDDEN_TIMEOUT=0
GRUB_TIMEOUT=0.1

Placing a # at front makes them a comment. Leave the rest of the line the same in case you need it again.
The last line is the timeout. Leave that as a regular command (no #) but change the value to 0.1.
Finally run sudo update-grub to compile the configuration file into a new grub boot script.

Bug in grub 2.04
You might be effected by a bug in Grub 2.04 but I couldn't find a reference with google search. If unable to fix you can downgrade to Grub 2.02 as described in this Q&A:

How to downgrade grub from 2.04 to 2.02 on ubuntu 19.04?
Comment: No, it does not work. It seems that this bug is only in Ubuntu 19.10. Whatever I do, the countdown is always fixed for 30 seconds.
Comment: @Dines What does `grub-install --version` return?
Comment: grub-install (GRUB) 2.04-1ubuntu12.1
Comment: Per `info -f grub -n 'Simple configuration'` - 'GRUB_TIMEOUT' ... The default is '5'.  Set to '0' to boot immediately without displaying the menu, or to '-1' to wait indefinitely.
Comment: @JaradDowning Yes that is a new feature in Grub 2.04, most of the Ubuntu world is using Grub 2.02 right now.
Comment: Well ... And what do I need to do now to achieve the desired result?
Comment: @Dines It appears to be related to this: https://superuser.com/questions/124992/how-to-enable-boot-timeout-in-grub2 Can you update your question with the results from: `grub-editenv list`? If `recordfail` appears that means the timeout boot is automatically reset to 30 seconds.
Comment: @WinEunuuchs2Unix Empty output.
Comment: And although I already marked the answer @heynnema I wanted to say why maybe grub-editenv list did not return anything. https://ubuntuforums.org/showthread.php?t=2412153 (last post) I have exactly the same system (one OS, UEFI and LVM). Moreover, the answer was given back in 2007. Although I still can't understand why GRUB_RECORDFAIL_TIMEOUT had not acted before.
Comment: @heynnema has been underrated for years. I'm glad you accepted his answer and I'll upvote it too. `30-os-prober` was also on my radar but it's good he got there and saved everyone some time. Please answer his query about `00_header` though as it may help others. I was the first to upvote your question as I think it may be important for the future.
Comment: @WinEunuuchs2Unix Very kind words. Thank you.

Ubuntu 19.10 disable grub menu


How do you get down the hill on the campaign level, SOG?

Question: In Call of Duty: Black Ops, on the mission SOG (Vietnam), you come to a point where your orders are to push back the NVA down the hill. I've spent a lot of time slowly pushing down the hill but the enemies keep coming and on Veteran difficulty at some point I always end up dying. My squad mates pretty much stop at the first level down the hill providing no help.
I'm sure a portion of it is skill, but there must be something I'm missing to trigger my squad mates to continue on down and move the level forward and stop the enemy from spawning. Any ideas?
Comment: This part was incredibly annoying, I couldn't figure it out either, I never did figure out the barrels, but somehow managed to reach a checkpoint where half of the team moved on, but 2 guys including the one the game told me to follow, just stayed back there doing nothing.
Answer: You do kick the barrels.  Get close enough and an action prompt appears allowing you to pierce the barrels and kick them.  They then explode keeping the enemy at bay.  You need to do this with the 3 barrels before you will be able to move on.
Comment: Actually, Woods will kick a couple of them for you. When I played this on veteran I only had to kick the one on the far right.
Answer: Some of them will come at you regularly and some of them will not reveal themselves until you have reached a certain spot, so keep moving, but take it slowly.
Going kamikaze on veteran means certain death.
As soon as you clear all positions, they stop spawning.
You can roll barrels burning (just knife them by pressing "use" key) and use the machine gun at the side to make things easier.
Comment: I think the barrels may be what I'm looking for here. I know they mention something about napalm in barrels when you're getting to the hill, but which ones? I've seen no indication or prompt that you can kick the barrels at the very top.
Comment: They are the ones at the lower level of the descending (first) part. Must be three of them.
Comment: It's the ones that are kind of dark blue with yellow stripes running across them.  I was stuck on this bit for ages until someone told me about the barrels.  Once you knock them all down, your squad pushes down the hill themselves.
Comment: Remember, Woods will kick 2 of the barrels for you. You only actually have to kick one.
Answer: Barrels are the key. Ignore everything else. Go up to them and they will give you a prompt, or Woods will activate them. The rest of the squad then moves forward.


Interesting thing about sum of squares of prime factors of $27$ and $16$.

Question: Let
$$n=p_1×p_2×p_3×\dots×p_r$$
where $p_i$ are prime factors and
$f$  is the functions
$$f(n)=p_1^2+p_2^2+\dots+p_r^2$$
If we put $n=27,16$ and $27=3×3×3$, $16=2×2×2×2$ then
$$\begin{split}f(27)&=3^2+3^2+3^2=27\\f(16)&=2^2+2^2+2^2+2^2=16.\end{split}$$
I checked it upto $n=10000$, I did not find another number with this property $f(n)=n$.

Can we prove that other such numbers do not exist?

Some approaching values
$f(992)=981\\f(1058)=1062\\f(1922)=1926\\f(5396)=5410\\f(7198)=7206\\f(9506)=9511$
Sequence: A067666, Sum of squares of prime factors of n (counted with multiplicity).

Edit
We can show there are infinitely many $n$ s.t. $f(n)=n+4$
Proof: put $n=2\cdot p^2$ where $p$ prime number
gives $f(2\cdot p^2)=2^2+p^2+p^2=4+2\cdot p^2$.
Comment: @infinity Brute force (PARI/GP-calculation), but I will also try to find some other necessary conditions.
Comment: Just a though : assume $f(n) = n$ then $n = f(n) \ge r n^{1/r}$ so $n\ge rn^{1/r}$. Maybe this will lead to something?
Comment: Upto $10^7$ , the only solutions are $16$ and $27$
Comment: Upto $10^8$ , the only solutions are 16 and 27
Comment: This could be as hard as finding perfect numbers, but I am not sure.
Comment: What about $n=16$ ?
Comment: @Peter Yes that the answer
Comment: @Peter ok I corrected it. Thanks Peter
Comment: @Peter how did you come up with that? computer program check or some other reasoning?
Comment: If there are exactly three factors, you get a contradiction (mod 3) except for 27
Comment: @Empy2 Please formulate this as a partial answer.
Comment: Pruthviraj, see also my question on [MathOverflow](https://mathoverflow.net/questions/354266/given-m-prod-k-p-k-alpha-k-and-the-function-gm-sum-k-alpha-k)
Answer: For two factors $$f(pq)=p^2+q^2\gt pq$$ so $pq$ is not a solution.
For three factors:  If $3$ is a factor then $3^2+p^2+q^2$ is only a multiple of $3$ if $p=q=3$ as well.  If $3$ is not a factor then $p^2=q^2=r^2=1\pmod3$, so the sum is a multiple of $3$, and $pqr$ is not a solution.  So $27$ is the only solution with three factors.
For four factors, they can't all be odd as the sum would be even.  Then there must be an even number of odd factors.  So it is a multiple of $4$, and looking $\pmod4$, the factors are either all odd or all even.  So $16$ is the only solution with exactly four factors.
For five factors, I think they must all be odd; so $n=5\pmod8$.
For six factors, two of them must be 2, three must be 3, leaving $35+p^2=108p$ which has no solution.
For eight factors, all of them must be even, but $256$ doesn't work so there is no solution.
Edit:
Good news, bad news.
Good news: $$3^2+3^2+5^2+1979^2+89011^2\\=3×3×5×1979×89011$$
Bad news: $89011$ is not prime.
My idea was that the equation is a quadratic in the final prime.  The quadratic's discriminant must be a perfect square, and that is a Pellian equation in the second-last prime.  If the other primes are $3,3,5$, this Pellian has solutions $$1,44,1979,89011,...$$ with $$a_{n+1}=45a_n-a_{n-1}$$
If two consecutive terms are prime, then I think $3×3×5×a_n×a_{n+1}$ is a solution to the current problem
EDIT: Let
$$\alpha=\frac12(\sqrt{47}+\sqrt{43}),\beta=\frac12(\sqrt{47}-\sqrt{43})\\
A = \frac1{\sqrt{47}}(\alpha^{107}+\beta^{107}),B=\frac1{\sqrt{47}}(\alpha^{109}+\beta^{109})$$
$A$ and $B$ are consecutive terms from the sequence in the previous edit.  Maple confirms that $A$ and $B$ are prime, and $$3\times3\times5\times A
\times B=3^2+3^2+5^2+A^2+B^2$$
Comment: For the first edit, I looped through odd numbers, checking the sum but not primeness.  I needed five odd factors, and zero or two 3s, so start 3,3,5.  Then 3,3,5,1979 led to a quadratic with roots 44 and 89011, and playing around gave the sequence.  For the second edit, I first used Matlab to find $a_n\pmod p$ for all primes up to $10^8$.  Several $a_n$ were multiples of none of the $p$, and so were possibly primes.  I got Maple to check $A$ and $B$ because they are adjacent in the list.  The formula comes because $\alpha^2$ and $\beta^2$ are roots of the characteristic equation
Comment: Thanks,  very interesting solution A and B. How did you get it?
Answer: Just some ideas, maybe useful to obtain a proof.
Let's focus on integers of the form $p^k$, where $\,p\,$ is prime. If $p^k$ satisfies the request, then
$$f(p^k)=kp^2=p^k$$
$$k=p^{k-2}\;\;\;\;\;\;\;(1)$$
So $\,p\,$ divides $\,k\,$ and it's easy to see that the only solutions of $\,(1)\,$ are $\,(k,p)=(3,3)\,$ and $\,(k,p)=(4,2)$. More precisely (as requested by Peter), exists a certain $\,\alpha$ such that:
$$k=p^\alpha=p^{(p^\alpha -2)}$$
$$\alpha=p^\alpha -2$$
$$\alpha+2=p^\alpha\ge2^\alpha\;\;\;\;\;\;\;(2)$$
and the only solutions of $\,(2)\,$ are indeed $\,\alpha=1\,$ and $\,\alpha=2$.
Further, if $\,q\cdot p^k$ (with $\,q\,$ prime different from $\,p$) satisfies the request, then
$$f(q\cdot p^k)=f(p^k)+q^2=q\cdot p^k\;\;\;\;\;\;\;(3)$$
From $\,(3)\,$ we see that necessarily $\,q\,$ has to divide $\,f(p^k)$.
Comment: "It is easy to see" - please work this out.
Comment: Please, remove the downvote (see corrections to my post). Thanks.
Answer: Giorgos Kalogeropoulos has found 3 such numbers, each having more than 100 digits.
You can find these numbers if you follow the links in the comments of OEIS A339062 &
A338093
or here https://www.primepuzzles.net/puzzles/puzz_1019.htm
So, such numbers exist! It is an open question if there are infinitely many of them...


Fluent validation add rule with index

Question: I make a fluent validation class for this model
 public class OnlineCashierRequest
 {
    Guid InvoiceId { get; set; }
    string ClientPhoneOrEmail { get; set; }
    List<IOnlineCashierProduct> Products { get; set; }
 }

public interface IOnlineCashierProduct
{
     string Name { get; set; }
     decimal Amount { get; set; }
     int Count { get; set; }
}

I have a rule for products where Amount equals null. But how can I write in message row index like $"Amount is less zero for row {rowIndex}"
RuleForEach(t => t.Products)
    .Must(x => x.Amount < 0)
    .WithMessage(x => $"[{rowIndex}] Amount must be greater then zero\r\n");

Comment: Check this https://stackoverflow.com/questions/27213058/how-can-i-access-the-collection-item-being-validated-when-using-ruleforeach
Comment: Why do you need the row index?
Comment: @chris For log validation exception
Comment: Would it not be better to use the `Name` of the `IOnlineCashierProduct` in the log message?
Comment: @chris No, there is also may be an error with empty productName
Answer: https://docs.fluentvalidation.net/en/latest/collections.html
RuleForEach(t => t.Products)
    .Must(x => x.Amount < 0)
    .WithMessage(x => $"[{CollectionIndex}] Amount must be greater than zero\r\n");

Comment: Wouldn't it need to be `$"[{{CollectionIndex}}] Amount must be greater than zero\r\n"` because of the string interpolation?

Fluent validation add rule with index


Does SQLite write operation block database only for other processes or for threads of single process too?

Question: Does SQLite write operation block  database only for other processes or for threads of single process too? Is it possible to use SQLite in multithreading (=multisession) ASP.Net application?
Answer: You'll probably want to look at File Locking And Concurrency In SQLite Version 3.
In particular, I think you are interested in the "EXCLUSIVE" database lock:

EXCLUSIVE
An EXCLUSIVE lock is needed in order to write to the database file. Only one EXCLUSIVE lock is allowed on the file and no other locks of any kind are allowed to coexist with an EXCLUSIVE lock. In order to maximize concurrency, SQLite works to minimize the amount of time that EXCLUSIVE locks are held.

When a thread or process has an exclusive lock on a database, all other operations (read or write) are disallowed.
Regarding multisession ASP.net, I would assume that most of the time, you'll only be reading from the database:

SHARED
The database may be read but not written. Any number of processes can hold SHARED locks at the same time, hence there can be many simultaneous readers. But no other thread or process is allowed to write to the database file while one or more SHARED locks are active.

There is no problem with many concurrent reads on an SQLite database; you will only be limited by the underlying OS/filesystem.  If  you're doing a lot of reads and writes concurrently, you might be interested in Appropriate Uses for SQLite, which states:

SQLite usually will work great as the database engine for low to medium traffic websites (which is to say, 99.9% of all websites). The amount of web traffic that SQLite can handle depends, of course, on how heavily the website uses its database. Generally speaking, any site that gets fewer than 100K hits/day should work fine with SQLite. The 100K hits/day figure is a conservative estimate, not a hard upper bound. SQLite has been demonstrated to work with 10 times that amount of traffic.

Also, in response to your comment on Pascal's answer, if you check the above link, you will see that SQLite makes no distinction between processes or threads, because all locks depend on the filesystem, not any program-level locks.

The pager module effectively controls access for separate threads, or separate processes, or both. Throughout this document whenever the word "process" is written you may substitute the word "thread" without changing the truth of the statement.
Answer: This entry from the SQLite's FAQ might help you :

Can multiple applications or multiple
  instances of the same application
  access a single database file at the
  same time?
Multiple processes can have the same
  database open at the same time.
  Multiple processes can be doing a
  SELECT at the same time. But only one
  process can be making changes to the
  database at any moment in time,
  however.

So, I'd say only one process/thread/whatever can write to your DB at a given instant.
(there's more to read on the FAQ page ; you should read it : I didn't quote everything)

And, about the multithreading thing :

Is SQLite threadsafe?
SQLite is threadsafe. We make this
  concession since many users choose to
  ignore the advice given in the
  previous paragraph. But in order to be
  thread-safe, SQLite must be compiled
  with the SQLITE_THREADSAFE
  preprocessor macro set to 1. Both the
  Windows and Linux precompiled binaries
  in the distribution are compiled this
  way.

(same note)
Comment: <> - IMHO there is a difference between "process" and "thread" :)


After blowing a fuse I lost power to two rooms

Question: I blew a fuse while accidentally touching a travler wire on a three way switch to the hot wire of the switch beside it. This dual switch contains two 3 way switches.
When I turned back on the breaker I have no power to a couple different rooms. The hot wire to those rooms is no longer hot. Only one brealer was tripped so Im assuming all the rooms are on the same breaker. Could there be a loose wire in the wall after the blow out?
Comment: Could be a few different things.  The easiest to check is that connections are tight.  Quite a few people use the push in connections on outlets instead of the screws and they are known to cause problems.  Turn off the breaker/s and double check there is no power before checking.  If you find the push ins, change them to the screws.
Comment: You may have also tripped a GFI. Check them all.
Comment: First thing to do is to turn all breakers off and back on (one at a time).  Sometimes it's not obvious when a breaker is tripped.
Comment: The good news is that whatever you knocked loose, fried, melted or exploded is probably in a junction box.  So while it may be time consuming and annoying, it won't be too hard or destructive to find the problem.
Comment: you missed the other tripped breaker
Answer:
touching a travler wire on a three way switch to the hot wire of the switch beside it

I think there are some mistaken assumptions here.  Traveller wires are "hot" wires too.
So one possibility is that you touched a grounded wire or metal part at the same time.
Another possibility is that those 2 switches are on 2 different circuits and you created a line-to-line short.
Conclusion: You might have 2 circuits to check, and since you've already reset the breakers the next step is to check for loose or damaged connections on those 2 switches.
If both switches still have normal hot on one side, then you'll need to check more of the parts that have "no power".
DON'T move any wires unless the circuits are off.


Image change but cannot see it in heroku's folder

Question: I'm facing this strange behaviour. Maybe, it's normal in heroku. In my app I have an image folder located in img/uploaded. Everything is ok in my application, I do see the image. But when I connect to heroku via heroku run bash and go to the same folder my file is not there. Any idea why is this? Maybe heroku takes some time to update folders/files.
My system is in symfony2.6 if it's relevant.
Answer: The reason why your image file is missing when you inspect the file system with "heroku run bash" is that Heroku creates a separate one-off dyno when you execute that command. The file system you are inspecting is different than the one accessed by the requests coming from your browser.
If you start using more than one dyno assigned to a web worker, you'll want to use an asset store to make sure your files are accessible by all your dynos. You can also take a look at Heroku's article about the Read-only filesystem.
Comment: Ohh. I see. That makes sense. I'm probably create a AWS Amazon S3 account and set up a bucket for my assets files. As this guide says https://devcenter.heroku.com/articles/s3


How can I mount a TV to the wall so that it folds away?

Question: I currently have a projector that I connect to my Mac or to my XBox 360, and then project onto a screen that pulls down over a window.
I now want to get a PS4, but the PS4 only has an HDMI output and my projector has no HDMI input. From what I can gather online, while there are options for converting HDMI output to a VGA or component input (both of which my projector has; it also has S-Video), these are far from perfect solutions and often don't work at all, or work inconsistently.
So, if I want to use a PS4 it seems I have two options: buy a new projector, or buy a TV. It seems that new, HDMI-compatible projectors are expensive, although there are some cheap ones on Amazon. But -- and here's the first part of my question -- are these cheap Amazon projectors any good?
As for the option of buying a TV, this is made more complicated by the fact that I live in a small place and there's no room for a big TV. But is it possible to mount a TV on the ceiling, so that most of the time the screen is flush to the ceiling but when I want to watch TV I can pull the TV down 90 degrees so that is parallel to the walls/window? It would also probably be necessary to be able to adjust the height of the TV when it is pulled down.
It might also be possible to mount the TV on the wall next to the window, so that when the TV is not in use it is perpendicular to the walls/window, and then pulls out when someone wants to use the TV. Going down this route would probably require that it be possible to rotate the TV, to, to make it possible to completely hide the TV away behind a cabinet.
I've found a few TV mounts online that come close to doing what I want, but nothing that does precisely what I want. Are there any particular brands of mount I should be looking at? And should I be trying to mount the TV on the ceiling or on the wall?
Comment: What's above/below the area, could the TV go up into the ceiling or down into the floor?
Comment: https://www.evernote.com/shard/s3/sh/ebfde63e-3048-4796-878c-97cede30e7f2/25fef2456158776689200063ee7f7a59
Comment: That's what the area looks like: essentially, wherever the TV goes it will have to fold away somehow so it doesn't block the window
Answer: The question might be, where are you thinking to fold it away to? There is no room there. I would certainly try something like this first:
http://www.amazon.com/Coredy-Graphics-Multiple-Monitors-1920/dp/B0129CP6BO/ref=sr_1_1?ie=UTF8&qid=1448758981&sr=8-1&keywords=hdmi+to+vega+adapter
This would certainly be much cheaper and less hassle.
Start with the easiest cheapest solution and work you way up.
Save yourself lots of time and energy in the process.
Happy Saturday!


Rails server gives error when I load localhost:3000

Question: So, I have started learning ruby on rails, I used following command to create a ROR project:
rails new blog

next I write following command to run the rails server:
rails s

The Rails server runs, and I load localhost:3000 in a web browser; but I get 500 internal error on the web browser.
The log file has following error:
ArgumentError (wrong number of arguments (2 for 1)):
  actionpack (4.2.2) lib/action_dispatch/http/request.rb:338:in `parse_query'
  rack (1.6.3) lib/rack/request.rb:191:in `GET'
  actionpack (4.2.2) lib/action_dispatch/http/request.rb:300:in `GET'
  actionpack (4.2.2) lib/action_dispatch/http/parameters.rb:14:in `parameters'
  actionpack (4.2.2) lib/action_dispatch/http/filter_parameters.rb:37:in `filtered_parameters'
  actionpack (4.2.2) lib/action_controller/metal/instrumentation.rb:22:in `process_action'
  actionpack (4.2.2) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
  activerecord (4.2.2) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
  actionpack (4.2.2) lib/abstract_controller/base.rb:137:in `process'
  actionview (4.2.2) lib/action_view/rendering.rb:30:in `process'
  actionpack (4.2.2) lib/action_controller/metal.rb:196:in `dispatch'
  actionpack (4.2.2) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
  actionpack (4.2.2) lib/action_controller/metal.rb:237:in `block in action'
  actionpack (4.2.2) lib/action_dispatch/routing/route_set.rb:74:in `call'
  actionpack (4.2.2) lib/action_dispatch/routing/route_set.rb:74:in `dispatch'
  actionpack (4.2.2) lib/action_dispatch/routing/route_set.rb:43:in `serve'
  actionpack (4.2.2) lib/action_dispatch/journey/router.rb:43:in `block in serve'
  actionpack (4.2.2) lib/action_dispatch/journey/router.rb:30:in `each'
  actionpack (4.2.2) lib/action_dispatch/journey/router.rb:30:in `serve'
  actionpack (4.2.2) lib/action_dispatch/routing/route_set.rb:819:in `call'
  rack (1.6.3) lib/rack/etag.rb:24:in `call'
  rack (1.6.3) lib/rack/conditionalget.rb:25:in `call'
  rack (1.6.3) lib/rack/head.rb:13:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/flash.rb:260:in `call'
  rack (1.6.3) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.6.3) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/cookies.rb:560:in `call'
  activerecord (4.2.2) lib/active_record/query_cache.rb:36:in `call'
  activerecord (4.2.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:649:in `call'
  activerecord (4.2.2) lib/active_record/migration.rb:378:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.2.2) lib/active_support/callbacks.rb:88:in `call'
  activesupport (4.2.2) lib/active_support/callbacks.rb:88:in `_run_callbacks'
  activesupport (4.2.2) lib/active_support/callbacks.rb:776:in `_run_call_callbacks'
  activesupport (4.2.2) lib/active_support/callbacks.rb:81:in `run_callbacks'
  actionpack (4.2.2) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/reloader.rb:73:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  web-console (2.1.3) lib/web_console/middleware.rb:37:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.2.2) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.2.2) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.2.2) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.2.2) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.2.2) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.2.2) lib/rails/rack/logger.rb:20:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.6.3) lib/rack/methodoverride.rb:22:in `call'
  rack (1.6.3) lib/rack/runtime.rb:18:in `call'
  activesupport (4.2.2) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
  rack (1.6.3) lib/rack/lock.rb:17:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/static.rb:113:in `call'
  rack (1.6.3) lib/rack/sendfile.rb:113:in `call'
  railties (4.2.2) lib/rails/engine.rb:518:in `call'
  railties (4.2.2) lib/rails/application.rb:164:in `call'
  rack (1.6.3) lib/rack/lock.rb:17:in `call'
  rack (1.6.3) lib/rack/content_length.rb:15:in `call'
  rack (1.6.3) lib/rack/handler/webrick.rb:88:in `service'
  /home/shrakuma/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'
  /home/shrakuma/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'
  /home/shrakuma/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'

  Rendered /home/shrakuma/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (3.6ms)

Started GET "/" for 127.0.0.1 at 2015-06-18 12:59:57 -0700

ArgumentError (wrong number of arguments (2 for 1)):
  actionpack (4.2.2) lib/action_dispatch/http/request.rb:338:in `parse_query'
  rack (1.6.3) lib/rack/request.rb:191:in `GET'
  actionpack (4.2.2) lib/action_dispatch/http/request.rb:300:in `GET'
  actionpack (4.2.2) lib/action_dispatch/http/parameters.rb:14:in `parameters'
  actionpack (4.2.2) lib/action_dispatch/http/filter_parameters.rb:37:in `filtered_parameters'
  actionpack (4.2.2) lib/action_controller/metal/instrumentation.rb:22:in `process_action'
  actionpack (4.2.2) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
  activerecord (4.2.2) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
  actionpack (4.2.2) lib/abstract_controller/base.rb:137:in `process'
  actionview (4.2.2) lib/action_view/rendering.rb:30:in `process'
  actionpack (4.2.2) lib/action_controller/metal.rb:196:in `dispatch'
  actionpack (4.2.2) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
  actionpack (4.2.2) lib/action_controller/metal.rb:237:in `block in action'
  actionpack (4.2.2) lib/action_dispatch/routing/route_set.rb:74:in `call'
  actionpack (4.2.2) lib/action_dispatch/routing/route_set.rb:74:in `dispatch'
  actionpack (4.2.2) lib/action_dispatch/routing/route_set.rb:43:in `serve'
  actionpack (4.2.2) lib/action_dispatch/journey/router.rb:43:in `block in serve'
  actionpack (4.2.2) lib/action_dispatch/journey/router.rb:30:in `each'
  actionpack (4.2.2) lib/action_dispatch/journey/router.rb:30:in `serve'
  actionpack (4.2.2) lib/action_dispatch/routing/route_set.rb:819:in `call'
  rack (1.6.3) lib/rack/etag.rb:24:in `call'
  rack (1.6.3) lib/rack/conditionalget.rb:25:in `call'
  rack (1.6.3) lib/rack/head.rb:13:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/flash.rb:260:in `call'
  rack (1.6.3) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.6.3) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/cookies.rb:560:in `call'
  activerecord (4.2.2) lib/active_record/query_cache.rb:36:in `call'
  activerecord (4.2.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:649:in `call'
  activerecord (4.2.2) lib/active_record/migration.rb:378:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.2.2) lib/active_support/callbacks.rb:88:in `call'
  activesupport (4.2.2) lib/active_support/callbacks.rb:88:in `_run_callbacks'
  activesupport (4.2.2) lib/active_support/callbacks.rb:776:in `_run_call_callbacks'
  activesupport (4.2.2) lib/active_support/callbacks.rb:81:in `run_callbacks'
  actionpack (4.2.2) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/reloader.rb:73:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  web-console (2.1.3) lib/web_console/middleware.rb:37:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.2.2) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.2.2) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.2.2) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.2.2) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.2.2) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.2.2) lib/rails/rack/logger.rb:20:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.6.3) lib/rack/methodoverride.rb:22:in `call'
  rack (1.6.3) lib/rack/runtime.rb:18:in `call'
  activesupport (4.2.2) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
  rack (1.6.3) lib/rack/lock.rb:17:in `call'
  actionpack (4.2.2) lib/action_dispatch/middleware/static.rb:113:in `call'
  rack (1.6.3) lib/rack/sendfile.rb:113:in `call'
  railties (4.2.2) lib/rails/engine.rb:518:in `call'
  railties (4.2.2) lib/rails/application.rb:164:in `call'
  rack (1.6.3) lib/rack/lock.rb:17:in `call'
  rack (1.6.3) lib/rack/content_length.rb:15:in `call'
  rack (1.6.3) lib/rack/handler/webrick.rb:88:in `service'
  /home/shrakuma/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'
  /home/shrakuma/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'
  /home/shrakuma/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'

How can I resolve this error?
Comment: Looks like this issue: https://github.com/rails/rails/issues/20624
Comment: That rails issue matches my current issue as well.
Answer: There seems to be a bug in the new Rack Gem version 1.6.3.
For now, try to lock down the version of rack in the Gemfile:
gem 'rack', '1.6.2'

run bundle update rack afterwards.
Relevant issue:
https://github.com/rack/rack/issues/896
Update
Meanwhile, version 1.6.4 was released. That should do, too.
https://github.com/rack/rack/issues/896#issuecomment-113299792
Comment: Editing the rack version in gemlock file made the trick, thanks...
Answer: Our quick fix to the Gemfile:
gem 'rack', '1.6.1'

This should unblock you for now until https://github.com/rails/rails/issues/20624 is resolved.
Comment: The breaking change was added in rack 1.6.3, so 1.6.2 should be fine.
Comment: changing rack version to 1.6.1 worked thanks...


Bessel's (in)equality confusion -- always an equality?

Question: Bessel's Inequality
Let $(X, \langle\cdot,\cdot\rangle )$ be an inner product space and $(e_k)$ an orthonormal sequence in $X$. Then for every $x \in X$ : $$ \sum_{1}^{\infty} |\langle x,e_k\rangle |^2 \le ||x||^2$$
where $\| \cdot\|$ is of course the norm induced by the inner product.
Now suppose we have a sequence of scalars $a_k$ and that the series $$ \sum_{1}^{\infty} a_k e_k = x $$
converges to a $x \in X$.

Lemma 1
  We can easily show that $a_k=\langle x,e_k\rangle $
  (i'll do it fast)
Proof. Denote $s_n$  the sequence of partial sums of the above series, which of course converges to $x$. Then for every $j<n$ , $ \langle s_n, e_j\rangle  = a_j$ and by continuuity of the inner product $a_j=\langle x,e_j\rangle $
Lemma 2 We can also show that since $s_n$ converges to $x$, then $σ_n = |a_1|^2 + ... + |a_2|^2 $ converges to $\|x\|^2 $ :
Proof. $\|s_n\|^2 = \| a_1 e_1 +...+a_2 e_2\|^2 = |a_1|^2 + ... |a_n|^2  $ since $(e_k)$ are orthonormal (Pythagorean). But $||s_n||^2$ converges to $||x||^2 $ , which completes the proof.

So we showed the following $$\sum_1^{\infty} |a_k|^2= \sum_1^\infty |\langle x,e_k\rangle |^2 = ||x||^2$$
Confusion
So the equality holds for Bessel inequality, for $x$. We arbitrarily chose $a_k$, so does that mean the the equality holds for all $x \in X$ ? Obviously not, otherwise it would be Bessel's equality. What am I getting wrong?
Comment: Perhaps $x$ **isn't** of the form $\sum a_ke_k$?
Comment: @LordSharktheUnknown Why wouldn't it be, set all $a_k = 1$ and you'll get $ \sum e_k$ which is a $x \in X$
Answer: What you are missing is that the statement says orthonormal sequence and not orthonormal basis. When the sequence is a basis, you get Parseval's equality. But the inequality holds for "partial sums".
If you already have $\sum_k a_ke_k=x$, then of course you get an equality.
Comment: But then you are using $x$ for two diferent things; the theorem says "for every $x\in X$".  Let's do this: why don't you take $X=\mathbb C^3$, with the usual inner product, and take the orthonormal sequence to be $\{e_1,e_2\}$, and $x=(1,2,3)$.
Comment: I'm not familiar with Parseval's equality yet, sorry if I got it wrong: saying that $\sum a_k e_k  = x $ means that $e_k$ must be an orthonormal basis? Or I can have that $\sum a_k e_k =x \in X$ even if $e_k$ isn't a basis, but that can't happen for all $x$?
Comment: If you have an arbitrary orthonormal sequence, why would you assume that you can write $x=\sum_ka_ke_k$? Of course, if $x$ is in the closure of the span of $\{e_k\}$, then the equality will hold, as you show.
Comment: I see, well I don't see why I shouldn't assume that. $\sum a_k e_k$ is always an element of X, since X is a vector space.
Comment: I don't assume that a random $x$ can be written that way, I say that the sum is some $x$ in $X$
Comment: Ok I see, thanks for the example. The equality will hold for all $x \in span \{ e_1,e_2,... \} $ and this is not $X$ since $e_k$ isn't a basis (right? ). Thanks again :)
Comment: Yes, exactly. $ $
Answer: Bessel's inequality is equality for some $x$ iff $x$ is in the closed linear span $\overline{[\{ e_k \}]}$ of the orthonormal elements $\{ e_n \}$. You don't have to assume that $\sum_k \langle x,e_n\rangle e_n$ converges to $x$, but that is the final conclusion if $x \in \overline{[\{ e_k \}]}$. This conclusion follows because
$$\|x-\sum_{k=1}^{n}\langle x,e_n\rangle e_n\| =\inf_{\alpha_1,\cdots,\alpha_n} \|x-\sum_{k=1}^{n}\alpha_k e_k\|$$


Confusions about Galois theory and the quintic

Question: I am very confused about Galois theory, because I have never seen a rigorous presentation of it. In particular, I don't understand what the books mean by "radical expression". It is also not clear whether we are working in the real domain or the complex domain. Related to this, I do not know if the root functions are genuine functions, patial functions, or multivalued functions. And if they are multivalued functions, how can we form terms based on them? Anyway, can someone help to clarify this, or perhaps point me to a book where this is all done more rigorously.
Answer: A book recommendation would depend on your background. But the book: Galois Theory by Ian Stewart is a great book on Galois Theory and the quintic. It defines exactly what, for example, radical expression means.
The basic idea is: We are considering polynomials with real number coefficients and we want to know about real roots. For polynomials of degree less than or equal to $4$ you can find a formula that will give you the roots to such a polynomial. That is, each root can be expressed using addition, subtraction, division, multiplication, and taking $n$th roots. That's it.
Now, it is possible to find a concrete polynomial of degree $5$ that has a root that cannot be expressed in this way.
Comment: Yeh but I'd recommend the first or second edition. The third edition is entirely different. Or if you really only care about field extensions over the rationals, the third edition is fine to read in the order it's presented.
Comment: And more specifically we're considering algebraic extensions of $\mathbb{Q}$, so not any real coefficients will do, since $\mathbb R$ has transcendental elements


Deleting Row if only  exists, Delete only  if   exsist

Question: Consider below table with 2 rows.
ID_NUM      | GENERAL_DATA
0100        | <...><UpdateServices><AddServices><RemoveServices><...>
0200        | <...><UpdateServices><...>

My questions are:
How to delete the row if XML has node <UpdateServices> only (meaning <AddServices> and <RemoveServices> are not present)? and
How to delete node <UpdateServices> from the XML if <AddServices> and <RemoveServices> are present?
CREATE TABLE SAMPLE_TABLE AS
  select '0100' as id_num,
  XMLTYPE('<TRX>
  <DATA>
      <Request APIType="null">
          <SubscriberIdsInfo>
              <ExternalId>
                  <ExternalId>0100</ExternalId>
              </ExternalId>
              <SubscriberId>
                  <SubscrNumber/>
              </SubscriberId>
          </SubscriberIdsInfo>
          <UpdateServices>
              <Soc>ABC</Soc>
              <ServiceAgreementSequenceNo/>
              <DealerCode/>
              <DeployMode/>
              <EffectiveDate>2019-10-16T00:00:00</EffectiveDate>
              <ExpirationDate/>
              <OfferInstanceId/>
          </UpdateServices>
          <AddServices>
              <Soc>ABC1</Soc>
              <ServiceAgreementSequenceNo/>
              <DealerCode/>
              <DeployMode/>
              <EffectiveDate>2018-10-16T00:00:00</EffectiveDate>
              <ExpirationDate/>
              <OfferInstanceId/>
          </AddServices>
          <RemoveServices>
              <Soc>ABC2</Soc>
              <ServiceAgreementSequenceNo/>
              <DealerCode/>
              <DeployMode/>
              <EffectiveDate>2017-10-16T00:00:00</EffectiveDate>
              <ExpirationDate/>
              <OfferInstanceId/>
          </RemoveServices>
          <SubParameters>
              <Name>PoolID</Name>
              <Values>POOL0100</Values>
              <EffectiveDate>2014-10-16T14:08:37</EffectiveDate>
              <ExpirationDate/>
          </SubParameters>
          <ActivityInfo/>
      </Request>
  </DATA>
  </TRX>') general_data from dual;

 insert into SAMPLE_TABLE (id_num,general_data)
  select  '0200' as id_num,
  XMLTYPE('<TRX>
  <DATA>
      <Request APIType="null">
          <SubscriberIdsInfo>
              <ExternalId>
                  <ExternalId>0200</ExternalId>
              </ExternalId>
              <SubscriberId>
                  <SubscrNumber/>
              </SubscriberId>
          </SubscriberIdsInfo>
          <UpdateServices>
              <Soc>ABC</Soc>
              <ServiceAgreementSequenceNo/>
              <DealerCode/>
              <DeployMode/>
              <EffectiveDate>2019-10-16T00:00:00</EffectiveDate>
              <ExpirationDate/>
              <OfferInstanceId/>
          </UpdateServices>
          <SubParameters>
              <Name>PoolID</Name>
              <Values>POOL0200</Values>
              <EffectiveDate>2014-10-16T14:08:37</EffectiveDate>
              <ExpirationDate/>
          </SubParameters>
          <ActivityInfo/>
      </Request>
  </DATA>
  </TRX>') general_data from dual;

commit;

Thank you. :)
Answer: How to delete the row if XML has node <UpdateServices> only (meaning <AddServices> and <RemoveServices> are not present)?
delete from sample_table X
where xmlExists('//UpdateServices' passing X.general_data)
    and not xmlExists('//AddServices|//RemoveServices' passing X.general_data)
;

How to delete node <UpdateServices> from the XML if <AddServices> and <RemoveServices> are present?
update sample_table X
set X.general_data = deleteXml(X.general_data, '//UpdateServices')
where xmlExists('//AddServices' passing X.general_data)
    and xmlExists('//RemoveServices' passing X.general_data)
;

Note: I believe the latter can be more effectively done via XQuery, but since I (still) don't know that language, I can provide only the deleteXml() solution.


Does Ubuntu need a FQDN to get internet and email working?

Question: I want to replace Win XP on a computer with Ubuntu. Do I have to buy a domain name to get email to send/receive and get internet working? Because on my Ubuntu 14.04 at work, I had to buy a domain name to get a Mail Transfer Agent to receive and send email. I"m not sure if an email client (not the same as an MTA) has the same requirements.
(At work I got around this with a Perl program which talks directly to the SMTP server, because I only needed to send emails. On my old Win XP PC I need to run a regular email client to send and receive emails.)
Also, is it possible to use a dynamic IP with Ubuntu with an ISP like Comcast? If so, how would I set it up?
Thank you.
Answer: Standard advice for dynamic IP hosts is to use external email accounts
[e.g. free email account(s) at gmail.com].
You may configure your MTA to send messages using one of such accounts.
You may configure fetchmail to retrieve messages from external mailbox to local mailboxes.


How to teach newbie multiply of complex number

Question: I want to teach a newbie the arithmetic law of complex numbers. the law of add is acceptable psychological. but multiply is not. for example, assume $$z = a+bi, w = c+di$$
He (She) may ask me: why not $$zw = ac+bdi$$, why must we define multiply like this: $$zw = ac-bd +i(ad+bc)$$. It is hard to acceptable.
I want to explain, but I am failed. Please help me, thanks very much.

My explain:
First , define like this,then the multiply of complex number can satisfy most laws of algebra for addition, multiplication. Second, If I treat complex number as a linear operation of $\Bbb{R}^2$. then the multiplication of complex number is coincide with the multiplication of matrix in $M_2(\Bbb{R})$. this explain that this definition is reasonable.
Comment: Does the other person know about distributivity of multiplication in general? What do they think about $(a + b)(c + d)$?
Answer: The way that Complex numbers are generated is to take the Field of Real numbers, and add a point ($i=\sqrt{-1}$).
Formally, a field is a set with 2 operations defined on its elements (+,$\times$). The elements have the following properties
$$\begin{array}{rrr}
    commutative&a\times b=b\times a & a+b = b+a \\
    associative&(a\times b)\times c=a\times (b\times c) & (a+b)+c = (a+b)+c \\
    identity&1\times a = a & 0+a=a \\
    inverses&a(a^{-1}) = 1 (a\ne 0) & a+(-a)=0 \\
  \end{array}$$
and
$$distributive\:\:\:a\times(b+c) = (a\times b)+(a\times c)$$
When adding the point $i$ we need to assume that the preceding axioms hold (so long as the new field is consistent [i.e. doesn't contradict itself]).
This means that if $i$ is a number, then so is $bi$. If $bi$ is a number, then so is $a+bi$ (where $a,b \in \mathbb R$).
So now that we know that $\mathbb C$ is a Field (whose elements obey Field axioms), we can turn our attention to the problem.
$$z=a+bi,w=c+di$$
$$zw = (a+bi)(c+di)$$
$$zw = (a+bi)c + (a+bi)di$$
$$zw = (ac+bci) + (adi+bdi^2)$$
$$zw = (ac+bci) + (adi-bd)$$
$$zw = (ac-bd) + i(ad+bc)$$
Answer: I suggest drawing a parallel between $\mathbb C = \mathbb R [i]$ and, say $\mathbb Q[\sqrt 2] = \{a+b\sqrt 2| a,b \in \mathbb Q\}$. They are both sets made by extending a set by one "weird" number and in both cases the square of this element is again a "normal" number. The two sets share many properties.
However, because $\mathbb Q[\sqrt 2] \subset \mathbb R$, this set should be simpler to grasp. You can show that if we were to define $(a+b\sqrt 2) \times (c+d\sqrt 2) = ac + db \sqrt 2$, this would not be the multiplication on $\mathbb R$.
Answer: I do not know how much this could help but I faced the same problem.
Let say that we have $z = a+bi, w = c+di$ and that we want to compute the product $z \times w$. So we have $$z \times w=(a+ bi) \times (c+di)=a \times (c+di)+bi \times (c+di)$$ Now, continue expanding and later collecting the terms.
Answer: \begin{align}
(a+i*b)*(c+i*d)&=ac + i*ad + i*bc + i*b*i*d \\
& = ac + i(ad+bc) + i*i*bd \\
& = ac + i(ad+bc) + i^2*bd \\
& = ac - bd + i(ad+bc)
\end{align}
The first step is using the law of distributivity, the last step is using $i^2=-1$
Comment: Just for curiosity, and also asking for @Genju, why the down-vote? One comment and one other answer are adopting this approach.
Answer: You yourself appear to have a couple of misconceptions about the problem!
You're not defining anything. Well, except for $i^2=-1$. You're simply calculating the product:
$$(a+bi)(c+di)$$
By distributing and then gathering terms, see Genju's answer.
Your definition of addition isn't a definition either. It's just distributing and commuting.
$$a+ib+c+id=(a+c)+i(b+d)$$
(Of course, strictly speaking it's not very rigorous to construct $\mathbb C$ by just "adjoining" $i$ and saying "$i^2=-1$ but otherwise everything works as normal", but that's how $\mathbb C$ is often constructed when students are seeing complex numbers for the first time.)


Multiple folds in one pass using generic tuple function

Question: How can I write a function which takes a tuple of functions of type ai -> b -> ai and returns a function which takes a tuple of elements of type ai, one element of type b, and combines each of the elements into a new tuple of ai:
That is the signature should be like
f :: (a1 -> b -> a1, a2 -> b -> a2, ... , an -> b -> an) ->
     (a1, a2, ... , an) ->
     b ->
     (a1, a2, ... , an)

Such that:
f (min, max, (+), (*)) (1,2,3,4) 5 = (1, 5, 8, 20)

The point of this is so I can write:
foldlMult' t = foldl' (f t)

And then do something like:
foldlMult' (min, max, (+), (*)) (head x, head x, 0, 0) x

to do multiple folds in one pass. GHC extensions are okay.
Comment: I think there's a solution using Arrow's *** and &&&, using types like (f,(g,(h,i))) instead of (f,g,h,i) under the hood, but I'm a couple of hundred miles away from my laptop at the moment so can't play today.
Answer: If I understand your examples right, the types are ai -> b -> ai, not ai -> b -> a as you first wrote.  Let's rewrite the types to a -> ri -> ri, just because it helps me think.
First thing to observe is this correspondence:
(a -> r1 -> r1, ..., a -> rn -> rn) ~ a -> (r1 -> r1, ..., rn -> rn)

This allows you to write these two functions, which are inverses:
pullArg :: (a -> r1 -> r1, a -> r2 -> r2) -> a -> (r1 -> r1, r2 -> r2)
pullArg (f, g) = \a -> (f a, g a)

pushArg :: (a -> (r1 -> r1, r2 -> r2)) -> (a -> r1 -> r1, a -> r2 -> r2)
pushArg f = (\a -> fst (f a), \a -> snd (f a))

Second observation: types of the form ri -> ri are sometimes called endomorphisms, and each of these types has a monoid with composition as the associative operation and the identity function as the identity.  The Data.Monoid package has this wrapper for that:
newtype Endo a = Endo { appEndo :: a -> a }

instance Monoid (Endo a) where
    mempty = id
    mappend = (.)

This allows you to rewrite the earlier pullArg to this:
pullArg :: (a -> r1 -> r1, a -> r2 -> r2) -> a -> (Endo r1, Endo r2)
pullArg (f, g) = \a -> (Endo $ f a, Endo $ g a)

Third observation: the product of two monoids is also a monoid, as per this instance also from Data.Monoid:
instance (Monoid a, Monoid b) => Monoid (a, b) where
    mempty = (mempty, mempty)
    (a, b) `mappend` (c, d) = (a `mappend` c, b `mappend d)

Likewise for tuples of any number of arguments.
Fourth observation: What are folds made of?  Answer: folds are made of monoids!
import Data.Monoid

fold :: Monoid m => (a -> m) -> [a] -> m
fold f = mconcat . map f

This fold is just a specialization of foldMap from Data.Foldable, so in reality we don't need to define it, we can just import its more general version:
foldMap :: (Foldable t, Monoid m) => (a -> m) -> t a -> m

If you fold with Endo, that's the same as folding from the right.  To fold from the left, you want to fold with the Dual (Endo r) monoid:
myfoldl :: (a -> Dual (Endo r)) -> r -> -> [a] -> r
myfoldl f z xs = appEndo (getDual (fold f xs)) z

-- From `Data.Monoid`.  This just flips the order of `mappend`.
newtype Dual m = Dual { getDual :: m }

instance Monoid m => Monoid (Dual m) where
    mempty = Dual mempty
    Dual a `mappend` Dual b = Dual $ b `mappend` a

Remember our pullArg function?  Let's revise it a bit more, since you're folding from the left:
pullArg :: (a -> r1 -> r1, a -> r2 -> r2) -> a -> Dual (Endo r1, Endo r2)
pullArg (f, g) = \a -> Dual (Endo $ f a, Endo $ g a)

And this, I claim, is the 2-tuple version of your f, or at least isomorphic to it.  You can refactor your fold functions into the form a -> Endo ri, and then do:
let (f'1, ..., f'n) = foldMap (pullArgn f1 ... fn) xs
in (f'1 z1, ..., f'n zn)

Also worth looking at: Composable Streaming Folds, which is a further elaboration of these ideas.
Answer: For a direct approach, you can just define the equivalents of Control.Arrow's (***) and (&&&) explicitly, for each N (e.g. N == 4):
prod4 (f1,f2,f3,f4) (x1,x2,x3,x4) = (f1 x1,f2 x2,f3 x3,f4 x4)   -- cf (***)
call4 (f1,f2,f3,f4)  x            = (f1 x, f2 x, f3 x, f4 x )   -- cf (&&&)
uncurry4    f       (x1,x2,x3,x4) =  f  x1    x2    x3    x4

Then,
foldr4 :: (b -> a1 -> a1, b -> a2 -> a2,
            b -> a3 -> a3, b -> a4 -> a4)
       -> (a1, a2, a3, a4) -> [b]
       -> (a1, a2, a3, a4)                        -- (f .: g) x y = f (g x y)
foldr4 t z xs = foldr (prod4 . call4 t) z xs      -- foldr . (prod4 .: call4)
              -- f x1 (f x2 (... (f xn z) ...))   -- foldr . (($)   .: ($))

So the tuple's functions in foldr4's are flipped versions of what you wanted. Testing:

Prelude> g xs = foldr4 (min, max, (+), (*)) (head xs, head xs, 0, 1) xs
  Prelude> g [1..5]
  (1,5,15,120)

foldl4' is a tweak away. Since
foldr f z xs == foldl (\k x r-> k (f x r)) id xs z
foldl f z xs == foldr (\x k a-> k (f a x)) id xs z

we have
foldl4, foldl4' :: (t -> a -> t, t1 -> a -> t1,
                    t2 -> a -> t2, t3 -> a -> t3)
                -> (t, t1, t2, t3) -> [a]
                -> (t, t1, t2, t3)
foldl4 t z xs = foldr (\x k a-> k (call4 (prod4 t a) x))
                      (prod4 (id,id,id,id)) xs z
foldl4' t z xs = foldr (\x k a-> k (call4 (prod4' t a) x))
                       (prod4 (id,id,id,id)) xs z
prod4' (f1,f2,f3,f4) (x1,x2,x3,x4) = (f1 $! x1,f2 $! x2,f3 $! x3,f4 $! x4)

We've even got the types as you wanted, for the tuple's functions.
A stricter version of prod4 had to be used to force the arguments early in foldl4'.


Dominance Poisson/Binomial in convex order

Question: Given two r.v. $X,Y$ (with well-defined expectations) such that $\mathbb{E}[X]=\mathbb{E}[Y]$, we say that $X$ is dominated by $Y$ in the convex order, denoted $X \leq_{\rm cx} Y$, if
$$
\mathbb{E}[f(X)] \leq \mathbb{E}[f(Y)]
$$
for every convex function $f\colon\mathbb{R}\to\mathbb{R}$, provided the expectations exist.
Given $n\geq 1$, $p\in[0,1]$, let $\lambda := np$, and $X,Y$ be distributed as $\textrm{Binomial}(n,p)$ and $\textrm{Poisson}(\lambda)$, respectively.

Is it true that $X \leq_{\rm cx} Y$? If so, what would be a good reference or proof for this fact?

This seems to follow from Theorem 2.2 of [1], but I may be misreading -- and, in any case, this result is much more general, it would fill like overkill to use it.
[1] Negative dependence and stochastic orderings, Fraser Daly (2015). https://arxiv.org/abs/1504.06493
Answer: This follows from the fact that ${\rm Poi}(p)$ dominates ${\rm Bin}(1,p)$, and adding $n$ independent copies of these.
To see that $Y\sim{\rm Poi}(p)$ dominates $X\sim{\rm Bin}(1,p)$, note that
$$
\mathbb P(X=0)=1-p\le e^{-p}=\mathbb P(Y=0).
$$
Hence, we can couple these so that $\{X=0\}\subseteq\{Y=0\}$ is an event of probability $1-p$.
Then, $Y=0$ whenever $X=0$ so we obtain,
$$
\mathbb E[Y\vert X]=X.
$$
This holds when $X=0$ since both sides equal $0$, and hence also holds for $X=1$ since both sides have expectation $p$.
This shows that $Y$ dominates $X$ since $f(X)\le\mathbb E[f(Y)\vert X]$ for convex $f$ by Jensen's inequality.
Comment: Nice. Here, you're using the fact that the convex order is closed under convolutions in the end (just adding it here for my own (and possibly others') reference, this is, e.g., Theorem 3.A.12 of *Stochastic Orders* by Shaked and Shanthikumar).
Answer: Yes.
That is exactly the statement of Lemma 2.3 in [1].
For any convex function $f$, any integer $N \geqslant 1$ and parameter $p\in [0,1]$, we have
$$
E\left[f\left( Bin(N, p)\right) \right] \leqslant E\left[f\left( Poi(Np)\right) \right].
$$
There is also a book [2] with a million theorems of this nature.

[1] Barman, Fawzi, Ghoshal, Gürpinar. Tight Approximation Bounds for
Maximum Multi-Coverage, IPCO 2020 (https://arxiv.org/abs/1905.00640)
[2] M. Shaked and J.G. Shanthikumar. Stochastic Orders. (10.1007/978-0-387-34675-5)
Comment: Thank you! I have to say, I skimmed [2] and couldn't find this statement among the million theorems.


Finding the length of a train confusion

Question: Erica noted that a train to Muizenberg took $8$ minutes to pass her. A train in
the opposite direction to Cape Town took $12$ minutes to pass her. The trains
took $9 $ minutes to pass each other. Assuming each train maintained a constant
speed, and given that the train to Cape Town was $ 150$m long, what was the
length of the train to Muizenberg?
My attempt:
let $x$ be the length of the train to Muizenberg.
let $s_1$ be the speed of the train to Muizenberg.
let $s_2$ be the speed of the train to Cape Town.
let $t_1 =$ the time it takes the train to Muizenberg to pass the train to Cape Town
let $t_2 =$ the time it takes the train to Cape Town to pass the train to Muizenberg
We have $x = 8 \times s_1$
$$s_2 = \frac{150}{12} = 12.5$$
Now by the third statement, if it takes $9$ minutes for the two trains to pass each other then $$t_1 = t_2$$
$$ \frac{150}{12.5} = \frac{x}{s_1} = 9$$ (Since $Time = \frac{distance}{Speed}$.)
But clearly there is something wrong in my solution. Where did I go wrong? Can someone explain to me what is my mistake? Thank you.
Answer: You mistake is in the fact that when the two trains pass each other, the relative speed is the sum of their speed, and the length is the sum of their lengths. Letting $s_1$ (resp. $s_2$) be the speed of the first train (resp the second) relative to Erica, you get
$$
9\cdot 60 = \frac{x+150}{s_1+s_2}
$$
(the multiplication by 60 being to express the speeds in $m.s^{-1}$).

Finding the length of a train confusion


Should I reload only those areas of site where data has changed?

Question: I think the rule is: Reload only those areas of site where data has changed. Don't fetch the areas where no changes have been made.
The pros of this rule are:
1. Users will be able to examine elements of page that were not reloaded
2. It will load server less
The cons can be looked at in wikipedia but I don't see no significant issues there that can't be solved.
So should this rule be applied to all sites? And if not, what is the exact rule?
Comment: There is no 'exact rule'. It all depends on context--specifically what your site does and for who.
Answer: I always build my applications with the philosophy of progressive enhancement.
In your case, I would design your site so that the site works for users without javascript and HTML5 enabled. This will result in a full reload of the whole page everytime the user navigates, but this is fine. This represents the normal 'state-of-flow' of the web and users should be familiar with it.
If javascript or HTML5 is avaliable, then you can start looking at using AJAX or whatever you are using to reload only certain portions of the page.
You can use something like YUI History, history.js and loads of other state management scripts to maintain state across your application.
In HTML4 browsers, you would see something like http://site.com/#/page/to/whatever and in HTML5 browsers, you will see something like http://site.com/page/to/whatever, but it does not refresh the whole page.
So the conclusion:

Yes, only changing parts of the site is good and more responsive, however you should take into account users without javascript or HTML5 (screen readers, search engines, users with those features disabled, etc).
Use progressive enhancement. Provide something that will work without javascript or HTML5 (full page reloads), then use your favorite javascript frameworks or HTML5, to build ontop and update only page sections that require updating.
Answer: If you are using AJAX to update section of the page that will harm your SEO.
Here is a good read about that SEO for AJAX
Comment: What does SEO have to do with anything here?
Comment: the title says "Should I update only those areas of site that need update?" I am giving him a reason not to.. Does that make sense?


Does the Fallout 4 1.03 patch fix the glitches related to infinite building?

Question: Can someone who has installed the 1.03 patch on console (PS4/Xbox One) verify this?
Specifically, there are two glitches that are necessary for building without limits:

Unlimited resources
This is done by emptying out a workshop and having only shipments in your inventory (at least 5). Then store all junk' and quickly 'take all' before the shipments turn into their raw materials. You may or may not be asked to confirm the take all so be ready to quickly confirm.
Unlimited build size
Drop a bunch of weapons and then enter workshop mode. Simply highlight a weapon and select 'store'. Lather, rinse, repeat and your build limit will gradually go down.

Basically if I can't do these glitches anymore then I know to avoid the patch.
I have read the release notes and they don't reference these glitches at all. At the same time, it doesn't mean the issues weren't patched. I am a software developer with public facing products myself and am very aware that sometimes a company doesn't disclose everything or changes get lost in translation.
That's why I'm looking for actual proof of someone that has installed the version 1.03 and can still do the glitches. I took time to write instructions for the glitches so someone could give it a try.
Comment: Also, to the down voter,  I would like feedback on why this is not a valid question. How could you want to be a part of a community that doesn't want others to improve their questions? Without the feedback I will likely just leave this community and that can't be a good stack policy
Comment: @kraftydevil Comments are entirely **optional**.  Downvoters (and upvoters) don't have to leave comments when they vote, because the act of voting is more important than informing the poster of why they vote.  That feedback is meant for *all* readers, not just you.
Comment: you mean, aside from the developer console? (Most variables are editable through the console, hence why you can spawn people, enemies, and weapons in the heat of battle)
Comment: Sorry, when I said "console", I meant ps4 and Xbox I have clarified the question to note this and added the appropriate tags.
Comment: @Frank - I'm aware that comments are optional. I'm also aware that I have an option to request feedback and improve my question for others.
Comment: You do. But if someone would comment on why they did so, they'd already have done so. Threatening to leave because you don't get that feedback that is optional isn't going to do anything but make voters even less likely to do so. This is the system. This is how it works.
Comment: Retaining members who want to provide quality questions and answers is important. I wanted the downvoter to know that their actions were causing me to feel unwelcome. A simple number like '-1' is a very high level (low detail) feedback mechanism. If I answered a question with just a number then it would certainly be deleted. The system could be improved.
Comment: The feedback isn't for you, primarily.  If you want to take it personally, we can't stop you, but that's not what it's intended for.  That's why votes are anonymous to begin with.  It's not about *you*.  It's all about **quality**.
Comment: I don't have to be the primary reason to receive feedback for it to be an intelligent thing to ask for. Questions are editable for a reason and feedback does matter. It's definitely about quality since quality people will produce quality questions and answers. The stack sites have an opportunity to improve their community. Not leaving context specific information for the OP is irresponsible. Don't worry as I'm not taking it personally as an individual. I do think the stack community as a whole should take personally any missed opportunity at improving said community.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/35665/discussion-between-frank-and-kraftydevil).
Answer: I accidentally updated my game to 1.03 and the glitches still work. ****phew****
This video shows all 3 items required for acceptance in one continuos shot:

Proof that version 1.03 was installed: (0:00)
Proof that the unlimited resources glitch still works (0:15)
Proof that the unlimited build capacity glitch still works (0:40)
Comment: Would love to hear why this was downvoted. I actually provided proof to the OP, which was more than the speculative release notes could tell me.
Comment: This answer is linked to the meta post http://meta.gaming.stackexchange.com/questions/11283/answering-a-question-when-the-only-acceptable-answer-is-a-video?cb=1
Comment: @kraftydevil: Was this question merged or something? You're talking about the OP like it's someone other than you.
Comment: Sorry for the confusion. I meant "original post" in this context.
Comment: Please summarize the video content in text in your answer.
Comment: @ChaseSandmann - could you elaborate on what else you're looking for? There is a number bulleted list of what happens in the video. I added time markers in case you want to jump to certain part but it looks spelled out to me. Let me know if you are looking for something else.
Answer: Looking at the patch notes on the wiki, is does not look like these "features" were removed in this patch. The full list can be found here.
Below are the workshop related fixes as listed:

Fixed a bug that would cause settler counts to appear incorrectly
Fixed an issue that could prevent the player from setting up a supply line in settlements with a high population
Improvements to snapping pieces together while in Workshop mode
Fixed an issue that caused powered items to stop functioning permanently if its power source was ever removed
Player can now build workbenches in their Diamond City house
Building wires no longer uses up copper
Fixed issue with certain settlement attacks not generating properly
Fixed an issue with settlement happiness calculations
Settlers assigned to weapons stand will now stand next to it
Diamond City house now shows provided power
Repairing items will now correctly consume resources
Fixed an issue where companion would ignore commands at workshop locations
Fixed an issue with crops appearing destroyed after saving and reloading
Comment: @kraftydevil - If nobody gets around to testing it and I don't forget to, I'll try to get around to it next time I pop FO4 in. I also feel like that's a pretty "important" glitch to mention so I'd be surprised if they left something like that out (yes, as a software developer myself, I can relate). Especially considering how minor some of the others are.
Comment: Considering neither of those is really dangerous nor detrimental to gameplay I imagine they wouldn't bother patching them. Notice that all of the listed issues may appear minor but also only make things cheaper, easier, and more accurate for the player. Removing unlimited resources and building doesn't affect "normal" play and is only detrimental to players that use it.
Comment: I appreciate the response but it assumes that the release notes are entirely transparent. I did read the patch notes to make sure they didn't state they took it out. However, just because they don't state it doesn't mean it's not the case. I am a software developer myself and am very aware of things that get changed without publicly announcing them. Companies do it all the time so I am looking for actual proof. I will update my question to clarify this. Thanks for bringing this up as it is important.
Comment: @Reafexus - I agree. Although I'd probably say it's still on their "todo" list, although probably on the bottom.
Comment: @Reafexus - It depends how much you exploit the glitch. They didn't put limits on the building because of gameplay restrictions - they did it because of the limits of the PS4/Xbox One. By utilizing these 2 glitches, you can build until you crash the game. Crashing can occur for a number of reasons, but I'm sure the system is working much harder when trying to display a settlement of a very large size. For example, these settlements crash often: https://youtu.be/rES0OpFz4So and https://youtu.be/DPbUly-1ujQ
Comment: @DangerZone - turns out I found out for sure by accidentally switching the internet on with auto-update. Again, my apologies for not originally including in my OP the fact that I had read the release notes and my reasons for paranoia about software patches.
Answer: i did the unlimited resources glitch just now, and it worked the first time (however i only got it up to 450 copper) then i did it at a different settlement, 250 copper, then I've just done it at starlight drive through and was unable to get it to work....
Hmmmm
Edit: I reloaded twice, attempted it again, and was able to get it back up to 100, before it occurred again, i do believe that you can still do it, its just a matter of speed still? but i could be wrong
Answer: I've used the settlement size trick since the patch (today even). I didn't even know about the other trick and can't comment on it.


How to make listbox placed in a large canvas in wpf more performant?

Question: I have a custom UserControl looks like this:

The brown boxes are ListBoxItems in a ListBox control and there are many such items. Each item again contains a lot of other controls, like images, text blocks among others. They and a Rectangle control are fixed positioned relative to a very big canvas, wrapped in a ScrollViewer. The rectangle takes up almost the entire height of the canvas. Currently, all the boxes are rendered at once, as can be confirmed in the visual tree (in the visual tree, there are 30k+ elements with about 40 elements per ListBoxItem), because the ListBox has a height of almost the canvas' height. However, the user can only see a small portion of all the boxes (and the rectangle) at one time. The user can scroll down to bring the boxes into view and the corresponding part of the rectangle. Since all the boxes are rendered at once, the UserControl behaves very poorly in terms of performance when a view containing this UserControl is being navigated to.
Apparently, the ListBox is not virtualized in this setup. I tried to limit the height of the ListBox to the containing ScrollViewer, and then virtualizing seems to be turned on. However now the ListBox itself has an implicit ScrollViewer in it. When the user scrolls the viewport down, the boxes corresponding to the certain part of the rectangle will not be shown.
The code I use to simulate this:
Window x:Class="ListBoxVirtualizationExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Width="800"
        Height="450">
    <ScrollViewer HorizontalScrollBarVisibility="Auto"
                  VerticalScrollBarVisibility="Auto">
        <Canvas Width="2000"
                Height="2000">
            <Rectangle x:Name="Rect1"
                       Canvas.Left="0"
                       Canvas.Top="0"
                       Width="100"
                       Height="100"
                       Fill="Red" />
            <Rectangle x:Name="Rect2"
                       Canvas.Left="0"
                       Canvas.Top="600"
                       Width="100"
                       Height="100"
                       Fill="Green" />

            <ListBox Canvas.Left="150"
                     Width="200"
                     Height="{Binding Path=ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollViewer}}}"
                     ItemsSource="{Binding YourDataSource}"
                     VirtualizingStackPanel.IsVirtualizing="True"
                     VirtualizingStackPanel.VirtualizationMode="Standard">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Canvas>
                            <TextBlock Canvas.Left="{Binding RectangleLeft}"
                                       Canvas.Top="{Binding RectangleTop}"
                                       FontSize="20"
                                       Text="{Binding Text}" />
                        </Canvas>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Canvas>
    </ScrollViewer>
</Window>

code-behind:
using System.Collections.ObjectModel;
using System.Windows;

namespace ListBoxVirtualizationExample
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            YourDataSource = new ObservableCollection<DataItem>();

            for (var i = 0; i < 200; i++)
            {
                YourDataSource.Add(new DataItem {Text = $"Item {i}", RectangleLeft = 0, RectangleTop = 20 * i});
            }

            DataContext = this;
        }

        public ObservableCollection<DataItem> YourDataSource { get; set; }
    }

    public class DataItem
    {
        public string Text { get; set; }
        public double RectangleLeft { get; set; }
        public double RectangleTop { get; set; }
    }
}

This gives me results like this when scrolled down:

But ideally, it should look something similar to this (this picture is taken when the ListBox takes the entire height of the canvas, so basically no virtualization is on) :

That is, items 25-28 should always be in the green square no matter how the user changes the viewport and scrolls up and down.
The question is: how can I improve the performance of the UserControl? Is the ListBox control the right way to do this? Are there any other ways to achieve the same effect?
Comment: Try using Virtualized Canvas: https://learn.microsoft.com/en-us/archive/blogs/jgoldb/virtualized-wpf-canvas
Comment: What is your goal, why do you want to position the TextBlock elements on a Canvas?
Answer: The virtualization is working. Because you wrap each item into a Canvas and apply the content position absolute, you are effectively moving the TextBlock elements out of the item container: each TextBlock is rendered on the screen relative to the Canvas (the one inside the DataTemplate).
Because you assigning them a Canvas.Top of a multiple of 20 the items are stacked by force and not by the VirtualizingStackPanel that the ListBox uses as panel.
If your idea was to add a top margin of 20 to each item, you must do this from the ListBox.ItemContainerStyle:
<ListBox>
  <ListBox.ItemContainerStyle>

  <ListBox.ItemContainerStyle>
<ListBox>

If your idea is to place the TextBlock elements on a Canvas to position them by the location provided by the data item (and by stacking them inside the item panel), then instead of wrapping each item's content into a Canvas you must replace the panel of the ListBox with a Canvas and set Canvas.Top and Canvas.Left on the ListBoxItem (from the ItemContainerStyle). But unless you have acustom Canvas panel that supports virtualization you lose this performance feature.
The second issue is that your ListBox is obviously the wrong size. You give it the size of the ScrollViewer which is basically the size of the viewport.
If the ListBox is supposed to stretch across the Canvas you must bind it accordingly. Bind ListBox.Height to Canvas.Height.
The following code has removed the Canvas from the DataTemplate and fixed the binding set on the ListBox.Height property to make it behave as expected.
<ScrollViewer HorizontalScrollBarVisibility="Visible"
              VerticalScrollBarVisibility="Visible">
  <Canvas Width="2000"
          Height="2000">
    <Rectangle x:Name="Rect1"
               Canvas.Left="0"
               Canvas.Top="0"
               Width="100"
               Height="100"
               Fill="Red" />
    <Rectangle x:Name="Rect2"
               Canvas.Left="0"
               Canvas.Top="600"
               Width="100"
               Height="100"
               Fill="Green" />

    <ListBox Canvas.Left="150"
             Width="200"
             Height="{Binding Path=Height, RelativeSource={RelativeSource AncestorType={x:Type Canvas}}}"
             ItemsSource="{Binding YourDataSource}">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <TextBlock FontSize="20"
                     Text="{Binding Text}" />
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>
  </Canvas>
</ScrollViewer>

Answer: The first thing to try is give each item in that listbox a specific size.
Your listbox isn't virtualising because it doesn't have a size for each of it's items. They are all as big as they like because each item is going in a virtualising stackpanel and has nothing sets or constrains it's size.
If you give each item a size then the virtualising stackpanel can decide how many of them should fit and which will not.
That will of course virtualise those that do not fit.
You could do that with the canvas.
The height here is just arbritrary. You should pick whatever suits size of your rectangles. Maybe that's 50 * 1900. It's the height that matters, obviously.
            <ListBox.ItemTemplate>
                <DataTemplate>
              **    <Canvas Height="22" Width="200">  **
                        <TextBlock Canvas.Left="{Binding RectangleLeft}"
                                   Canvas.Top="{Binding RectangleTop}"
                                   FontSize="20"
                                   Text="{Binding Text}" />
                    </Canvas>
                </DataTemplate>
            </ListBox.ItemTemplate>

I don't really follow why you have a canvas in each of the items though. It doesn't make much sense without an explanation. But maybe that doesn't matter so much.
If you can get the ui items down to around 10,000 then I think you'll likely find your problems greatly reduced.
If not then you could consider simplifying the controls in each item somehow. Difficult to say exactly what would be best without knowing more about the intent of this design.  A drawingvisual encapsulating everything in an item into one thing might be something to consider.
I don't really follow why the whole thing is not one listbox with a canvas as itemspaneltemplate and everything rendered from that. You would just have the one scrollviewer to deal with.
With this scenario the 2000 x 2000 canvas would be the panel in the listbox and everything would be rendered in that.
It would virtualise ( if you tell it how big things are ).


RandomForestClassifier import

Question: I've installed Anaconda Python distribution with scikit-learn.
While importing RandomForestClassifier:
from sklearn.ensemble import RandomForestClassifier
I have the following error:
File "C:\Anaconda\lib\site-packages\sklearn\tree\tree.py", line 36, in <module>
    from . import _tree
ImportError: cannot import name _tree
What the problem can be there?
Comment: try this: run `python -m site` and make sure there is no other python environment active other than  Anaconda.
Answer: In sklearn version '0.18.1'
from sklearn.ensemble.forest import RandomForestClassifier

Answer: The problem was that I had the 64bit version of Anaconda and the 32bit sklearn.
Comment: how did you figure this? and how exactly did you fix it? i can't seem to figure my version and or how to update it..
Answer: I solved it by:
pip install -U scikit-learn

RandomForestClassifier import


Any ideas on how to make 'the' treated as one, example the appears in position 1 and 3

Question: I'm supposed to write a program to report the position of each word in a sentence.  Here is my code:
User_input = input('Enter your phone number separated by space >>>')

newlist = (str.split(User_input))

print (newlist)
print ('Length of list',len(newlist))

newset = set(newlist)
print (newset)

shortlist = list(newset)
print (shortlist)

def findit(item,newlist):
    for i in range (len(newlist)):
        if item == newlist[i]:
            print ((newlist[i]),'appears',"in position ",i,"in the list")

for i in range (len(shortlist)):
        findit(shortlist[i],newlist)

Output desired:

What is your sentence?the boy the girl
['boy', 'girl', 'the']
boy appears in pos 2
girl appears in pos 4
the appears in pos 1
the appears in pos 3

The problem is that I get "the" reported in positions 0 and 2.  How can I get the correct position numbers?
Comment: Why is this tagged iOS? Please tag this properly.
Comment: Welcome to StackOverflow.  Please read and follow the posting guidelines in the help documentation.  [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here.  We cannot effectively help you until you post your code and accurately describe the problem.
Comment: Also, please note that your input prompt is for a phone number.  You need to change that.
Answer: Sure.  You're printing out the index of the word, rather than the position you want.  In many computer languages, including Python, array / list indices begin at 0.  Look at your actual output (which you didn't bother to provide): each of the positions is 1 lower than you want.
Simply add 1 to the subscript:
print ((newlist[i]), "appears in position ", i+1, "in the list")


error in building a simple user interface in Android using XML (The markup in the document following the root element must be well-formed)

Question: I'm learning how to develop applications using Android.
This is the first lesson of building a simple user interface and facing the error
The markup in the document following the root element must be well-formed.
here is the code
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientatio="horizonatal"

    <EditText android:id="@+id/edit_message"
        android:layout_widthe="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message">

        <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send">
        />
</LinearLayout>

the lesson is on http://developer.android.com/training/basics/firstapp/building-ui.html
Answer: Looks as though the LinearLayout element is missing its closing angle bracket. There also appear to be a couple of typos in the final attribute name and value.
Try:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

You've also forgotten to close your EditText element and there's a typo in 'width'. Try:
<EditText android:id="@+id/edit_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/edit_message" />


Lagrange Multipliers and Unfeasible Constraints

Question: Given a point $\mathbf{a} \in \mathbb{R}^{3}$ and a unit vector $\boldsymbol{n} \in \mathbb{R}^{3}$. A unique plan $P$ goes through $\mathbf{a}$ and possesses a normal $\boldsymbol{n}$.
A surface $S$ is parametrized by a function $\boldsymbol{f}(x,y,z):\mathbb{R}^{3}\rightarrow\mathbb{R}^{3}$.
Statement of the problem
I would like to find the point of the surface $S$ that is the closest from $\mathbf{a}$ and that is in the plane $P$.
To solve for this, the objective function to minimize is:
\begin{equation}
\boldsymbol{g}(x,y,z,\lambda)=\left\Vert \boldsymbol{a}-\boldsymbol{f}\right\Vert -\lambda\boldsymbol{c}
\end{equation}
with $\boldsymbol{c}(x,y,z)=(\boldsymbol{a}-\boldsymbol{f})^{T}\boldsymbol{n}$ the constraint that forces the point of the surface $S$ to be in the plane $P$.
I solve this optimization problem numerically using in general a Newton-Raphsson scheme.
If there is an intersection between the plane $P$ and the surface $S$, I can converge to an extremum of the $\left\Vert \boldsymbol{a}-\boldsymbol{f}\right\Vert $ as long as my first guess is sufficiently good.
However, if there is no intersection, the scheme diverges because the constraint in $\boldsymbol{c}$ cannot be satisfied.
Is there any alternative procedure apart from the use of Newton-Raphsson with Lagrange Multipliers that would allow me to know that the solution I am looking for cannot exist because there are no point where the constraint is respected ?
Put more simply, what is the method of choice to employ when one is not sure that a solution of the optimization problem respecting the constraints exists ?
Answer: As a side note, I think what you meant to write is that the surface $S$ is defined as the zero set of a function $f:\mathbb{R}^3\to\mathbb{R}$ (i.e. the set of points $(x,y,z)$ such that $f(x,y,z)=0$). Similarly, you can write the plane $P$ as the zero set of some function: $g(x,y,z)=0$. In fact, you even know that $g$ will be of the form $g(x,y,z) = \vec{n}\cdot (x,y,z)- \vec{n}\cdot \vec{a}$.
Now, in words, what you are trying to do is minimize the distance to the point $\vec{a}\in \mathbb{R}^3$, subject to the constraint of being on the surface $S$ and on the plane $P$. Can you think of an objective function that sends $(x,y,z)$ to the distance from $(x,y,z)$ to $\vec{a}$? Hint: it might be easier to minimize the square of this function, which is perfectly fine since the map $\mathbb{R}_{\geq0}\to\mathbb{R}$, $x\mapsto x^2$ is monotone.
As I mentioned above, the constraints are that you would like your point to be on the surface $S$ and on the plane $P$. Thus, your constraint equations should be $f(x,y,z)=0$ and $g(x,y,z)=0$. Now you're all set to use Lagrange multipliers!
Comment: As an alternative, you might consider solving the equation of the plane $P$ for one of the variables, say $z=\frac{1}{n_3}(\vec{n}\cdot\vec{a} - n_1x-n_2y)$ (assuming $n_3\neq 0$) and substituting this into the equation $f(x,y,z)=0$ to obtain a constraint in two variables. Geometrically, what you are doing here is finding an equation for the curve given by intersecting $S$ with $P$. The resulting Lagrange multipliers problem will be easier to solve, as you will only have one constraint.


Not receiving string messages from SQS

Question: I am working with SQS. I am sending messages from a java code and receiving it from a python script. I am sending json object in string form using JSONObject.toString(). Sometimes python script receive the proper string but sometimes it get the message in following format:
���'��eq��z��߭��N��n6�N��~��~��m=���v+���Myӟ=���e�M�ߟv׎�۽y�����8��w��;�M��N�۞�㾹뾷�n���7�}7�o=��4۽����߾v��6��<�}7�}4�ν��=���߾{��}�n6���߭��^������~���|�]��N��~��κ�����y�������^��}��M��θ��:�^�����_|߮6��5�^�q��z�ږǫiخ�����n�Wږǭʗ�9�������F���8�����4�N�u��q�������_o�<���o�Zo�<�n�뗷
Answer: You Can manually check by visiting your aws console, whether your message are in proper format. Verify that.
Comment: yes messages are in proper format in the queue I have checked that manually.

Not receiving string messages from SQS


Using local variable within case statement

Question: I am trying to determine if any columns in @pi_included_columns is a LOB. The query below will work if I do not use the local variable (@included_columns). However if I just use a
PRINT @included_columns

and plug the same results into where the @included_columns variable is in the case statement, it will work. Why would the variable not be accepted in the WHERE clause?
I think it may work with Dynamic SQL but I've never used Dynamic and not sure where to start.
DECLARE           @offline_flag CHAR(1),-- = 'N',
                  @pi_table_name varchar(128) = 'ngkbm_default_values_',
                  @pi_included_columns varchar(1000) = ' table_name, field_name, set_value , sql_count, sql_insert, sql_update',
                  @included_columns varchar(1000),
                  @new_variable varchar(1000)

SET @included_columns = replace(@pi_included_columns,',',', ')
SET @included_columns = replace(@included_columns,'  ',' ');

SELECT @new_variable = '(''' + REPLACE(REPLACE(@included_columns , ' ' , ''), ',' , ''',''') + ''')'

SELECT @offline_flag =
       CASE
          WHEN EXISTS (
             SELECT 1 FROM information_schema.columns
                           WHERE (TABLE_NAME = @pi_table_name
                                   AND COLUMN_NAME IN (@new_variable)
                                   AND (data_type IN ('TEXT','NTEXT','IMAGE' ,'XML', 'VARBINARY')
                                   OR (data_type = 'VARCHAR' AND character_maximum_length = -1)
                                   OR (data_type = 'NVARCHAR' AND character_maximum_length = -1))
          ))
          THEN 'Y'
          ELSE 'N'
       END
print @new_variable
Print @offline_flag

Comment: If you want to do it in this way, yes you may well need dynamic SQL. Which DB engine are you using - is it SQL Server? Please add the tag for it so we can give the most appropriate answer
Answer: You can't use a comma separated string with an in expression to match the values inside the string.
You could create a dynamic query to use the string in that, but that means that you have to put the entire query in a string. Instead you can separate the items in the string into a set, for example a table variable:
declare @pos int
declare @new_variable table(name varchar(100))

set @pos = charindex(',', @pi_included_columns)
while @pos <> 0 begin
  insert into @new_variable values (ltrim(rtrim(substring(@pi_included_columns, 1, @pos - 1))))
  set @pi_included_columns = substring(@pi_included_columns, @pos + 1, len(@pi_included_columns) - @pos)
  set @pos = charindex(',', @pi_included_columns)
end
insert into @new_variable values (ltrim(rtrim(@pi_included_columns)))

Now you can use @new_variable with the in operator like this:
and COLUMN_NAME in (select name from @new_variable)