Separating file server and socket.io logic in node.js

Question: I'm fairly new to node.js and I've found its quite complicated separating a project into multiple files as the project grows in size. I had one large file before which served as both a file server and a Socket.IO server for a multiplayer HTML5 game. I ideally want to separate the file server, socket.IO logic (reading information from the network and writing it to a buffer with a timestamp, then emitting it to all other players), and game logic.
Using the first example from socket.io to demonstrate my problem, there are two files normally. app.js is the server and index.html is sent to the client.
app.js:
var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(80);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

index.html:

To separate file server and game server logic I would need the function "handler" defined in one file, I would need the anonymous function used a callback for io.sockets.on() to be in another file, and I would need yet a third file to successfully include both of these files. For now I have tried the following:
start.js:
var fileserver = require('./fileserver.js').start()
  , gameserver = require('./gameserver.js').start(fileserver);

fileserver.js:
var app = require('http').createServer(handler),
    fs = require('fs');

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

module.exports = {
    start: function() {
        app.listen(80);
        return app;
    }
}

gameserver:
var io = require('socket.io');

function handler(socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
        console.log(data);
    });
}

module.exports = {

    start: function(fileserver) {
        io.listen(fileserver).on('connection', handler);
    }

}

This seems to work (the static content is properly served and the console clearly shows a handshake with Socket.IO when the client connects) although no data is ever sent. It's as though socket.emit() and socket.on() are never actually called. I even modified handler() in gameserver.js to add console.log('User connected'); however this is never displayed.
How can I have Socket.IO in one file, a file server in another, and still expect both to operate correctly?
Comment: do you know the express js framework? http://expressjs.com/ it's great and really helps you structure your application. there are a ton of examples on github (https://github.com/visionmedia/express/tree/master/examples) maybe there's something that can help you with your problem...
Comment: @pkyeck: I'm reading up on expressjs now to try and figure out how it can benefit me, but so far it seems more complicated than what I need. All I really want is to separate my logic for the game server and the file server into two separate files then have a third file which properly starts both servers.
Comment: did you have the time to check out my "new" answer?
Comment: @pkyeck I've looked at it, although it seems like it's only masking the problem and not solving it. Not sockets.js is the ONE MASSIVE FILE instead of app.js. I'd like to have no single massive files but instead separate files for every function. More and more node.js seems like more of a hassle than a blessing.
Answer: In socket.io 0.8, you should attach events using io.sockets.on('...'), unless you're using namespaces, you seem to be missing the sockets part:
io.listen(fileserver).sockets.on('connection', handler)

It's probably better to avoid chaining it that way (you might want to use the io object later). The way I'm doing this right now:
// sockets.js
var socketio = require('socket.io')

module.exports.listen = function(app){
    io = socketio.listen(app)

    users = io.of('/users')
    users.on('connection', function(socket){
        socket.on ...
    })

    return io
}

Then after creating the server app:
// main.js
var io = require('./lib/sockets').listen(app)

Comment: If I want to trigger an emit request ? for ex., `app.get('/some/url',function(req,res){ // I want to emit here })`
Comment: We arent using 'return io' right? it's just for the var io.
Answer: i would do something like this.
app.js
var app = require('http').createServer(handler),
    sockets = require('./sockets'),
    fs = require('fs');

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

sockets.startSocketServer(app);
app.listen(80);

and sockets.js
var socketio = require('socket.io'),
        io, clients = {};

module.exports = {

        startSocketServer: function (app) {
                io = socketio.listen(app);

                // configure
                io.configure('development', function () {
                        //io.set('transports', ['websocket', 'xhr-polling']);
                        //io.enable('log');
                });

                io.configure('production', function () {
                        io.enable('browser client minification');  // send minified client
                        io.enable('browser client etag');          // apply etag caching logic based on version number
                        io.set('log level', 1);                    // reduce logging
                        io.set('transports', [                     // enable all transports (optional if you want flashsocket)
                            'websocket'
                          , 'flashsocket'
                          , 'htmlfile'
                          , 'xhr-polling'
                          , 'jsonp-polling'
                        ]);
                });
                //

                io.sockets.on('connection', function (socket) {
                        console.log("new connection: " + socket.id);

                        socket.on('disconnect', function () {
                                console.log("device disconnected");

                        });

                        socket.on('connect_device', function (data, fn) {
                                console.log("data from connected device: " + data);
                                for (var col in data) {
                                        console.log(col + " => " + data[col]);
                                }

                        });
                });
        }
};

i just copy&pasted some of my old code - don't really know what changed in the last versions of socket.io, but this is more about the structure than the actual code.
and i would only use 2 files for your purposes, not 3.
when you think about splitting it up further, maybe one other file for different routes ...
hope this helps.
Comment: Right now it's just a file server and a socket.io server, however eventually I will also have game logic to determine player positions given movement updates and I will need to have lag minimization logic which looks at the ping of each client and estimates which game state they are currently in judging from the existing data. Having some logic to fast-forward time, some logic to rewind time, some logic to move players, some logic to handle network data, and some logic to handle files meant I wanted to separate EVERYTHING into different files, ideally. Not just the socket.io stuff.
Comment: it's just the beginning - with the files you posted. you can do more than one `var xxx = require('./xxx');` and split your app into multiple files. i was at the mongodb conf yesterday and someone from 10gen showed a game based on node/mongo/websockets (https://github.com/christkv/mongoman) he's sending BSON data over the socket and decodes the data on the client - makes for a faster communication between client/server ... maybe it's interesting for you!?
Answer: I have had a crack at this as well and I am fairly happy with the result.  Check out https://github.com/hackify/hackify-server for source code.
Answer: I've another solution. You can use require.js creating a module and pass "app" as an argument. Within the module you can start socket.io and organize your sockets.
app.js:
  var requirejs = require('requirejs');

  requirejs.config({
      baseUrl: './',
      nodeRequire: require
  });

  requirejs(['sockets'], function(sockets) {

    var app = require('http').createServer()
      , fs  = require('fs')
      , io  = sockets(app);

      // do something
      // add more sockets here using "io" resource

  });

In your socket.js module you can do something like this:
  define(['socket.io'], function(socket){
    return function(app){
      var server = app.listen(3000)
        , io     = socket.listen(server);

      io.sockets.on('connection', function (socket) {
        console.log('connected to socket');

        socket.emit('news', { hello: 'world' });
        socket.on('my other event', function (data) {
          console.log(data);
        });

        // more more more

      });

      return io;
    }
  });

I hope help you with my contribution.
Comment: In case anyone reading this is wondering, no, there is no reason at all to use AMD within node.
Comment: It's just an alternative, isn't the only way to do


Specify which controllers to exclude from before_filter

Question: I'm using devise for authentication and have some before_filters in my application controller. Issue I'm seeing is that when I try to logout the before_filter intercepts that and keeps me on the view that's I've setup in the before_filter. Is there any way for me to specify which controllers should be excluded from the application controller or some other file?
Answer: In the controller where you want to skip a before filter specified in an inherited controller, you can tell rails to skip the filter
class ApplicationController
  before_filter :authenticate_user!
end

class SessionsController < ApplicationController
  skip_before_filter :authenticate_user!
end

Comment: This presents an answer to the original question in a more clear mannor, however `skip_before_filter :filter-name, :except => [:action1, :action2]` from the accepted answer is a great tip!
Comment: @Jesse Wolgamott what if the controller where I want to skip the before filter lives in a gem? Is there a way to specify on the before_filter itself something more than just actions?
Comment: @hunteros - you'd probably need to re-open the class in your code, and add the skip filter then
Comment: @JesseWolgamott I was hoping I wouldn't have to do that, but figured that would be the only solution. Are there conventions for where in the code base I should re-open the controller class?
Answer: You can qualify a filter with :only or :except.
before_filter :filter_name, :except => [:action1, :action2]

Or if the filter (as I now see is the case in your situation) is defined in ApplicationController and you want to bypass it in a subclass controller, you can use a skip_before_filter with the same qualifications in the subclass controller:
skip_before_filter :filter_name, :except => [:action1, :action2]

Answer: In config/application.rb
config.to_prepare do
  Devise::SessionsController.skip_before_filter :authenticate_user!
end

Referenced by:
How to skip a before_filter for Devise's SessionsController?
Answer: Answers above are good except:

DEPRECATION WARNING: skip_before_filter is deprecated and will be removed in Rails 5.1. Use skip_before_action instead.

So please use before_action and skip_before_action instead of *-filter.


Lambda architecture - what is origin of this name?

Question: I've read Manning's Big Data Lambda Architecture (http://www.manning.com/marz/BD_meap_ch01.pdf) and still not able to get why it's named 'Lambda'. Is it kinda code-name or name of system this architecture is based on?
Answer: In my opinion two of the core principals of Lambada Architecture are

Embrace data immutability
All queries can be formulated as pure
functions(without side effects) on your entire data set

These properties of immutability and pure functions are the core tenets of functional programming which in turn has its origins in Alonzo Church's Lambda Calculus. Because of this Nathan Marz must have named this architecture Lambda Architecture.
Comment: So... they took a fundamental mathematical concept, and applied it to an architecture, thus overloading an already established, highly specific term with something completely different and well, fluffy?
Comment: Lambda. You could pretty much call it "Functional Architecture" - perhaps that term could give insight into how bizarre and mildly insulting the term "Lambda Architecture" could be. _I'm not strong on Lambda calculus, and am not offended by "Lambda Architecture" - just the title seems to indicate it's something I'd not like too much. That said, I think it's got a reasonable chance of being a good architecture._
Comment: That was also my guess, but nobody knows for sure except Mr. Marz?
Answer: It was chosen by the American mathematician Alonzo Church, who needed a Greek letter to denote the operator for functional abstraction when he was developing the theory of computation in the 1930s.  Different people asked him why he chose that particular letter, and he gave them different answers (but the bottom line is, he didn't really care very much).  For a little more detail and some links, see http://www.lambdafaq.org/why-are-lambda-expressions-so-called/
Comment: but what does it have to do with the lambda arhcitecture?
Comment: @MK The question was about origin of word 'Lambda' in term 'Lambda architecture'. But still check parth.patil answer, he points to a logical link between 'Lambda calculus formal system' to 'Lambda architecture'.
Answer: I think its just the letter 'Lambda'. It looks like the data is divided into two streams.


Touchpad from HP laptop not working on OpenBSD

Question: I have installed OpenBSD 6.8 on a HP laptop. I have also installed xfce4.
My problem is that the touchpad of the laptop does not work.
Running the following command:  dmesg | grep Touchpad the system prints pms0: Elantech Touchpad, version 4, firmware 0x5d4f01.
Is there a way to configure the system in order to have the touchpad working properly?
Thanks
Answer: You can try doas wsconsctl mouse.tp.tapping=1


Pin Application to Specific Screen

Question: Is there anyway to pin windows that an application launches to a specific screen? As an example zoom launches two windows when starting a meeting one that for video and one with meeting information. It used to keep launching them in the same screens but lately I have noticed that each window will open on a different screen each time. The pattern seems random as sometimes they will just swap places but other times they will go to a different screen where it is not normally on to begin with.
Answer: Apps will launch to a given Space, if set - right click the app in the Dock > Options , *.
They will only launch to a given physical display if you don't have "Displays have separate Spaces" on in System prefs > Mission Control.
Apps do not like being spread across multiple Spaces.
*Apple use the terms Desktop and Space interchangeably, unfortunately. Display, however, always means 'physical screen'.
Comment: Have you checked if you have "Displays have separate Spaces"  on or off? This will only work if it's off.
Comment: This isn't from the app itself launching but from something happening after the app itself is already running. In my case I keep zoom running as I will use it for meetings throughout the day. My first meeting could launch the windows in the correct order on screens 1 and 2 but the second meeting could swap them or change one of them to screen 3. Zoom my default will always launch the video and meeting stats on different windows.
Comment: It is currently on and I will have to look into that option more.
Comment: It's quite a paradigm shift, but at the moment you are trying to force an app to use three different Spaces - it's not going to like doing that.
Comment: I am not trying to force the application to do anything other than open the same window every time. Zoom (the application in question) opens multiple windows in different spaces whenever you start or join a meeting, in fact it opens them up in full screen mode. All I am looking to do is to determine if I can get them to open up in the same spaces every time so I don't have to rearrange windows so I can get them to the correct places so I can work properly.
Comment: fullscreen windows each generate their own, un-numbered Space, so I doubt you're going to get any control over them. [Yet one more reason I absolutely never use fullscreen; one of the worst thought-out 'improvements' Apple ever made, imnsho] Fullscreen basically is designed for single-screen laptops. It's a mess on anything more sophisticated.

Pin Application to Specific Screen


What does "scoop on" means?

Question: I got an email telling me the following " The Scoop on can't-miss sessions at Reinvent event" I guess it means that I can not miss the reinvent event, however I am not sure why do they use scoop on here ?
Answer: Was this the subject-line of the e-mail? If so, I think they meant, "this e-mail will give you the scoop on can't-miss ...." Where "the scoop" means "the information" (Newspaper reporters supposedly use the expression "the scoop" when they are talking about some exciting information that they have just exclusively learned, and are planning to write a great newspaper article about.)
"Can't-miss" is an adjective describing something you don't want to miss, but it sounds like you already understand that part.
Comment: the subject line is trending news, one of the news in bullet point is this
Answer:
scoop (n):  informal A piece of news published by a newspaper or broadcast by a television or radio station in advance of its rivals.

In this case your teaser headline is trying to tell you that the linked news article contains information that you can't find in any other news source.  As usual, "You shouldn't believe everything you read".

What does “scoop on” means?


Why won't my Yongnuo YN-560-TX trigger power on correctly?

Question: When I turn on my Yongnuo YN-560-TX flash trigger it gets stuck on the power-on loading screen. Can someone please help me?
Comment: Did you try different batteries?
Answer: It's Yongnuo.
In other words, it's a disposable piece of... gear.
Sometimes Yongnuo devices last for many years. Usually they fail within a year of two.
I've got a single YN685 that still works seven years since I bought it, though it has gotten fairly light use over the past 3-4 years as I've moved to Godox/Flashpoint (I use a Godox X1-R on the hot foot of the flash to control it with a Godox transmitter when I need a third flash).
Two YN-622 transceivers were still working after about three years of moderate use when I moved to Godox/Flashpoint, but they've been sitting on a shelf for several years now. I have no idea if they still would work.
I've also got a small pile of other YN flashes, mostly YN-568EX II, that barely lasted a year each.
I've got a YN35mm f/2 lens for EF mount that lasted three day-long shooting sessions using it maybe 10% of the time at each before it no longer will stop down. Since it's hopelessly soft wide open, it's now useless. It's not even heavy enough to be a paperweight.


Proof a Weyl Algebra isn't isomorphic to a matrix ring over a division ring

Question: Can anyone prove that a Weyl Algebra is not isomorphic to a matrix ring over a division ring?
Answer: Notation: The Weyl algebra is
$$k[x_1, x_2, \ldots, x_n, \partial_1, \partial_2, \ldots, \partial_n]$$
with the obvious relations.
The Weyl algebra doesn't contain any division rings larger than $k$, and it is infinite dimensional over $k$. So, assuming you don't allow infinite matrices, that's a proof.
How to see that it doesn't contain any division ring larger than $k$? I just need to show that any nonconstant differential operator is not invertible. One way to see this is to notice that multiplying differential operators multiplies symbols, and the symbol of a nonconstant differential operator is a nonconstant polynomial.
Comment: I guess you could also use the fact (which follows easily by looking at highest order terms) that the Weyl algebra is a domain and not a division ring.  So it can't be a matrix ring over a division ring.
Comment: Whats the base field?
Comment: The field of constants. I have edited the answer; see if that is clearer.
Answer: A different proof would be to show that a Weyl algebra is not semisimple, that is, that it is not a direct sum of simple submodules as a left module over itself.  However, note that there is an infinite descending chain of left submodules of a Weyl algebra given by
$A_n\supseteq A_nd\supseteq A_nd^2\supseteq A_nd^3\supseteq...$
where $d$ is any non-invertible element.  A direct sum of a finite number of simple modules can't have an infinite descending chain of submodules.  Then, by the converse of Artin-Wedderburn, $A_n$ is not a direct sum of matrix algebras over a divsion ring.
Of course, showing this sequence of submodules never stabilizes can be done by looking at the associated graded algebra, and noting that the $\overline{A_nd^n}$ are always distinct there.  However, then this answer starts getting closer to David's answer, so maybe this wasn't a truly different proof.
Comment: What does the bar mean?
Comment: Image in the associated graded ring.
Comment: Makes sense now
Answer: I would only like to add a simple proof that the Weyl algebra doesn't even HAVE any (non-trivial) finite-dimensional representations.  Already in the case n=1, consider the relations
$$[\partial_x,x]=1.$$
Now suppose you had a finite dimensional representation, and take the trace of both sides of the above.
It implies that the identity acts as 0 so the whole representation does.
Comment: The question is about matrix rings over division rings, not over fields.  Unless you're just stating a weaker result?
Comment: ...and, moreover, the division rings in questions need not be finite dimensional algebras over the basefield of $A_n$.
Comment: I was going to say this, but I wasn't sure if it still works when the underlying ring is noncommutative.
Comment: Which ring are you calling underlying?  The base field?  This is part of the standard proof that W_n is simple.  In fact not only can it not have finite dimensional representations, but it's smallest representations have so-called Gelfand Kirillov dimension n, meaning that they are infinite-dimensional, and graded, and the dimension of the kth piece is on the order of k^{n-1}.  These are called holonomic modules.  The prototype example is C[x_1,...x_n] with its natural action.  The dimension of the kth graded part is \choose{k+n-1}{n-1}, which is approximately k^{n-1} as k-->\infty.
Answer: This is not an answer to the original question. However, it is related and I think that it is worth mentioning.
Assuming that ring morphisms take identity elements to identity elements, we can show the following for the $n$:th Weyl algebra, with very basic methods.
Choose an arbitrary positive integer $n$ and put $A_n := \mathbb{C}\langle x_1,\ldots,x_n,y_1,\ldots,y_n \rangle / I$ where $I$ is the ideal generated by the elements $y_1x_1-x_1y_1-1,\ldots,y_nx_n-x_ny_n-1$ and $x_i x_j-x_jx_i, y_i y_j - y_j y_i$ for $i,j \in 1,\ldots,n$.
Claim:
There does not exist a positive integer $m$ and an associative, commutative and unital ring $R$ such that there is a ring morphism
$$ \phi : A_n \to M_m(R).$$
Proof:
Seeking for a contradiction, suppose that there is some $m$ and some associative, commutative and unital ring $R$ such that $\phi$ exists. Denote the images in $M_m(R)$ of $x_1$ respectively $y_1$, under $\phi$, by $A:=\phi(x_1)$ respectively $B:=\phi(y_1)$. The image of $1$ will be the identity matrix $I$.
Consider the element $y_1x_1-x_1y_1=1$, the image of which, under $\phi$, is equal to
$$
BA-AB=\phi(y_1x_1-x_1y_1)=\phi(1)=I.
$$
Hence the matrices $A$ and $B$ have to satisfy $BA-AB=I$.
Taking the trace of the left hand side of this equality yields
$$
tr(BA-AB)=tr(BA)-tr(AB)=tr(AB)-tr(AB)=0
$$
whereas the trace of the right hand side is equal to $tr(I)=m$. This is a contradiction.

Corollary of the above proof:
The same claim holds if we replace $M_m(R)$ by any unital Banach algebra.
This is easily seen by using the following well-known fact:
The identity element of a unital Banach algebra can not be a commutator,
i.e. $ab-ba\neq 1$ for any elements $a,b$ of the Banach algebra.
This applies to the case $M_m(R)$ with $R=\mathbb{C}$, because $M_m(\mathbb{C})$ is a unital C*-algebra and in particular a unital Banach algebra. So in this particular case, this gives us an alternative way of making the desired conclusion without using the trace.
Comment: I think by "unital ring" you mean "unital commutative (associative) ring".  Otherwise, there are obviously ring homomorphisms.  Similarly tr(AB) = tr(BA) requires commutativity (it has counterexamples in every non-commutative ring).  Unfortunately, the original question specifically allows matrix rings over non-commutative rings, so this doesn't answer the question.
Comment: Jack, you are of course right. Thanks for pointing this out. I have tried to make my "answer" a bit more clear now.
Answer: A matrix ring contains zero-divisors.


mmenu opens/shows blank page

Question: I am struggling to resolve an issue I have with jquery mmenu
I am currently testing on Android and have configured the setup as per the demo using
open menu

setup with $('menu').mmenu();
I have also tried (as suggested)
$("#menu").trigger( "open" );

(using a different href on the link.
Can anyone suggest how to debug or a solution.
Thanks.
Answer: I have fixed my issue - it appears that having
// DON'T copy, this is the problem not solution //

overflow:scroll !important;
height: auto !important;

on the body tag of the page (required to override issues being caused elsewhere) caused the page to shrink to 0px in height and force the page to appear blank.
Hope this helps anyone else.

mmenu opens/shows blank page


What are the laws regarding eviction of adult children from residence in the UK?

Question: What is the process in the UK for parents to evict an adult child that is living at home with them if he refuses to leave willingly?
Comment: Change the locks?  (This is not an entirely facetious question; I would hope any answer would address why simply locking the person out of the home would out would not be an advisable or legal course of action.)
Comment: You run the risk of a oxymoron when you talk of adult children.
Answer: The Protection from Eviction Act 1977 defines an excluded tenancy as, amongst other things, a tenancy that is granted for other than money or money's worth ((7)(a)).
This means that someone who shares accommodation with the landlord does not have the protection from eviction that an ordinary tenant would have, as per Part 5.
You should seek advice from a legal professional before taking action to evict, however, there is nothing in the Protection from Eviction Act that protects an excluded tenancy. It would probably still be advised that you give reasonable notice.
Comment: Ah. This is where I will refer you to legal counsel. The Act appears to be silent on the matter.
Comment: See also [this guide to eviction under excluded tenancies](http://england.shelter.org.uk/get_advice/eviction/eviction_of_private_tenants/eviction_of_excluded_occupiers).
Comment: What if the lodger doesn't pay rent? How quick would the landlords be able to evict them?
Comment: [This blog](https://www.samuels-solicitors.co.uk/news/parents-evict-son) suggests 2 months warning, and claims the child can be treated as a squatter in the absence of a tenancy agreement.
Answer: Property owners have the right, in general, to ask anyone to leave their property, and to use reasonable force if they fail to comply (note that in England and Wales there is no concept of 'criminal trespass').
If you have a tenancy agreement, there are clear laws regarding eviction, depending on the type of tenancy. If a tenant is paying (and continues to pay) rent but has no tenancy agreement, the rules are less clear but will generally be interpreted in favour of the tenant. If you are not paying rent, you are not a tenant (almost certainly, though see 'Formalities' in Wikipedia's article on Leases).
Minors also have some rights to remain at home, though this is complicated by the fact that parents have the legal right to make decisions for a child. However, if you are over 18 (the age of majority in England and Wales), you have the right to make your own decisions. The flip side of this is that you also have the responsibility for your own life, including earning your own living and providing shelter for yourself.
Comment: Actually, in terms of where you live, you get to make that decision at 16 not 18.  I *think* parents can evict their 16 yo children.
Comment: Minors do not have a right to remain at the home. Any parent can relinquish parental rights and make a problem child the responsibility of the state.
Answer:
Ask them to leave
Try mediation
Use the Law

If you reach step 3 then the steps you take will depend on the status of the party being asked to leave (A) and they party staying (B):

If A is a co-owner - tough, they have a right to be there.
If A is a co-tenant of the same third party - tough.
If A is a tenant of B then they can be evicted under the applicable law.
If A is a boarder of B then they can be evicted under that applicable law.
If A is or threatens violence to B then the police can intervene and a restraining order may suffice to keep A out.
If A has no legal right to be there then if B asks them to leave and the do not then they are trespassing and the police can arrest them.
If B is a tenant, they could relinquish their interest in the property by ending the lease (if a tenant); A then becomes the owner's problem.
If B is an owner they can sell the property but if A has a legal right to possession (e.g. they are legally a tenant) then that would have to be transferred to the new owner.

See https://www.gov.uk/browse/housing-local-services
Comment: @dale It's not obvious how/if the link you added supports the answer that you gave. Can you include some quotes to improve your answer?
Comment: 6.  The police are very unlikely to arrest them.  Trespass is broadly a civil, not criminal matter.  Trespass in E&W *can* be criminal - but even then it's not likely to serious enough to justify an arrest.  B will have to use reasonable force to evict A in this case.
Comment: I think number 4 is relevant to my question. What would be the applicable law in this case then?
Comment: Sorry, you'll have to do your own research on that, I'm based in Australia.
Comment: Sorry to say, but [citation needed] for #6. I think that trespass in the U.K. Is civil, and barring breaches of criminal law act 1977 how  could one be arrested?


applyEdits fails in ArcGIS JSAPI

Question: I am using a feature layer in JSAPI, where I edit a feature by the standard selection, change attributes, applyEdits process. It seems that there is a bug in JSAPI both 3.12 and 3.14 which makes the apply edits fail on certain features. The callback just errors out without any clue.
The interesting observations:

Failure only happens on certain features and all cases belong to a particular layer (other features in that layer are just fine).
Changing from 3.12 to 3.14 the features that cause the error are changed but did not go away.

Here is a quick snippet of the code:
<code>sq = buildSelectionQuery();
if (sq) {
    all(assetsFeatureLayers.map(function (l) { return l.selectFeatures(sq, esri.layers.FeatureLayer.SELECTION_NEW).promise;})
    ).then(function (fls) {
        console.log('sel res', fls);
        all(fls.map(function (r, i) {
            var fs = r[0]; // the first is an array of selected features
            var l = assetsFeatureLayers[i];
            console.log(fs);
            if (fs.length > 0) {
                console.log("Switching phases to: ", tph);
                fs.forEach(function (f) {
                    f.attributes['phasecode'] = tph;
                });
                console.log("Saving switched phases for layer: ", l.name);
                return l.applyEdits(null, fs, null); //.promise;
            } else {
                return null;
            }
        })).then(function (l) {
            console.log("Phase switching finished successfully!", l);
            clearAllSelections();
        }, function (e) {
            console.log("Error switching phases!", e);
            clearAllSelections();
        });
    });
}
</code>
Answer: OK, I found the root cause. We are using ESRI's PHP proxy, and it was a bug in that. Upgrading to the latest 1.1 beta solved the issue. Here is the link to their repo: https://github.com/Esri/resource-proxy

applyEdits fails in ArcGIS JSAPI


Why are xcodebuild and Xcode 4.2 so slow?

Question: I am using Xcode 4.2 on a relatively large project (a few ten thousand lines of code) and it is horribly slow. Editing is ok, but whenever I try to compile the project (in Xcode, or with xcodebuild on the command line), my machine (quad core i7 MacBook Pro, 4 GB RAM) crawls to a halt. I have noticed that directly after starting xcodebuild, it spawns more than 8 clang processes, without the "real" compile processes starting. No xcodebuild output is so far seen on stout. I've tried reducing the number of parallel build processes, but still lots of clang processes are launched at the beginning. The project uses 6 or 7 direct dependent external projects and has maybe 120 source files. Under Xcode 3.2 the project used to be compiled very quickly. What's happening? And how can I make Xcode fast again?
Comment: fwiw, this is not new in 4.2. the last major hardware plateau was Xc4.0.
Answer: Most of us have three primary options:

Revert to Xcode 3 for daily development.
Throw more hardware at it.
Change your projects' structures and apply large scale development tricks (even though 20-30 KSLOC is not large).

The easiest solution is revert to Xc3. Yes, Xc4 requires a lot more than Xc3; memory, CPU, and disk space and I/O. You will have to determine where your biggest problems are to reduce the amount it affects you.
I recently bought a new MBP with twice the physical cores and twice the physical memory, upgraded to Lion and upgraded Xc4 at the same time. The compilation times did improve, but much of the rest is actually slower, and far more resource hungry. That's not at all what one would expect from an IDE which also disallows multiple open projects and also uses a unified workspace view.
The move to Lion + Xc4 more than doubled my hardware demands in all of the following categories:
Memory
4GB is now too little for most nontrivial projects using Xc4 and Lion. You can still reduce this. I have 8GB and 10GB on my main 2 machines, Xc4 consumes it all quite easily (but my projects are more complex than yours, unless you write reeaeaaaally long lines). Anyways, You can reduce this problem by:

Buying more memory.
Disable indexing if you are building out huge projects in Xcode. This can halve Xcode's memory consumption.
Running Xcode in 32 bit. This is not an option for everyone, because it will exceed 4 GB in larger projects.
Reduce the number of build processes (again).
Restarting Xcode often (It doesn't do a very good job cleaning up after itself).
Use clang as your compiler. Clang instances in general use less memory than Apple's GCC 4.2.
Offload dependent targets which do not change often. Example: You will not need to rebuild third party libraries daily in most cases.

CPU
Xcode 4 uses a new (more accurate) completion parser.

Pare down your include dependency graphs, and dependencies. This is quite easy to with Obj-C, since every Obj-C instance is a pointer. Example: remove loosely dependent framework includes from your headers.
Separate your dependencies and modules properly. Develop libraries, but try to make them fairly small and be aware of the dependencies they will add. Example: I lead a project where a dev added a small feature (less than 1% of the app), but due to the number of dependencies it required (e.g. Three20 and then a few more), the binary size of the final executable doubled (and the build times went up, and the parser had a lot more work to do). Most of this was not needed for the feature - they just could not be stripped because they were objc symbols.
Reduce translation counts, if possible.
Optimize how you use prefix headers. You can share them, and you can create them for no good reason. This benefits the compiler more than the IDE.
Minimize memory usage. GC work (including all NSObject allocs) consumes over 1/3 of the CPU usage in larger projects, but it still spends a lot of time collecting when its heap is huge.
Use external text editors and VC clients. Pretty obvious because Xc4 displays the SBBOD rather often in large projects.
Minimize language complexity. In order of complexity: C, ObjC, C++, ObjC++. The more complex the translations, the longer it will take to parse and compile your sources, especially when your dependencies are high. If you can easily set up language barriers in your dependencies, do so.
You can disable code sense indexing via defaults (also reduces memory demands).

Hard Disk
This can be a speed/size balance.

Buy a faster one (e.g. SSD).
Cleanup and minimize your header dependencies.
Use a RAM Disk, such as Make RAM Disk.
Buy more memory. With the amount Xc4 consumes, it ends up swapping out to disk often in large projects.
Optimize your builds to use pch files appropriately. This is not always the obvious direction: I have not used them for several years in large projects.
Clear out the temp files Xcode and Instruments leave behind, they can be huge. In some cases, you can save them in customized locations. If they do consume tens of GB and your build dir is the same as your boot dir, then you will make your disk work a lot less by cleaning them up regularly.

Builds

In Xc4, xcodebuild parallel to Xcode now doubles the work (separate build dirs by default). In Xc3, the default was to build to the same destination. Verify your settings - Xcode will do a ton of redundant building, if you allow it (e.g. one target per workspace/config, rather than Xc3's flat build model).
Or just fill a drawer with quad core MacMinis and use that as a dedicated or distributed builder.

File Bugs
(self explanatory)
Comment: Thanks. Good collection of solution possibilities.
Comment: @Arne Since writing this, I realized disabling indexing can halve Xcode's memory consumption in huuuge projects.
Comment: @justin: Nice answer! I've noticed imports do have a dramatic effect on autocompletion speed.
Comment: Another comment: I upgraded my machines to 8 and 12 GB RAM respectively. This also helped a lot to speed things up. I guess Xcode 4 is just very, very RAM hungry.
Answer: One more possible solution that in some cases might help speed up Xcode 4: In my case, the main problem seems to have been that accidentally four files from my build/ folder had been checked in with my git repository. During compilation Xcode notices that the build folder changed, and triggers git. Since the build folder contains thousands of files in my case, the performance went down. Removing the build/ folder completely from git (shouldn't have been checked in anyway) reduced the compilation times and system load massively. Performance is still slower than with Xcode 3, but much better than before.
Answer: You can switch on Distributed Building in XCode Preferences, and find some friendly person who will help you build your app by forming compilation machines cluster with you.
The funny thing is that even he is off, your compiler still uses different algorithm/mechanism to build you app in a blazing speed if compared to the problems before ;)
So, that means that they at Apple have forgotten about lonely programmers who don't work in teams and therefore lonely compilation scenario is purely tested in versions 4.0 - 4.2
Answer: Quick Note Regarding 'Throw more hardware at it' approach..
SUMMARY: I experienced a SMALL speed increase from making a SIGNIFICANT hardware upgrade
Test: Build/Run the exact same project on cloned macbooks (where the only difference should be their hardware)
Old Macbook Air (1.86GHZ Core 2 Duo ONLY 2GB RAM)
vs
Brand New Macbook Pro (2.3GHZ Core i7 8GB RAM)
BUILDING ON IPHONE 3GS
Macbook Air 1:00 - 1:15
Macbook Pro ~1:00
=> 0 to 0:15 of speed increase
BUILDING ON IPHONE 4S
Macbook Pro ~0:35
Macbook Air ~0:50
=> ~15 seconds of speed increase
**Partially tested: There DOES apear to a significant difference between build times for the SIMULATOR between the 2 machines
Comment: The SSD in the MBA might help a lot in making the performance gap so small. I noticed a huge gain in performance by throwing more RAM at my Macs, which all have traditional hard disks.
Answer: Another culprit for slowness is plugins. The Subversions plugin was absolutely killing my Xcode performance. I followed the instructions in this SO post to disable it. WHEW!


On Windows XP - Change monitor resolution based on which user is logged in?

Question: In Windows XP Professional, each of our family members are listed as icons at startup.  Is there a way to have the system change the monitor resolution based on the family member?  For example, if 'Dad' is clicked have it render 1028 x 768, if 'Mom' logs in have the monitor resolution set to 800 x 600.  If 'Boy' logs in have the resolution set to 1280×1024 etc...
Comment: Your user profiles are called "Mom", "Dad", and "Boy"?
Answer: I found this program : "XP Keep per User Display Settings". I quote:

The program is launched for each and
  every user -- don't worry, it's rather
  small -- and monitors the following
  events:

switching among active users
users logging off

Each time such an event occurs the
  current user's display settings are
  saved in that user's part of the
  registry.
  Conversely, each time a user logs in
  or becomes active, his/her saved
  settings are restored.
Comment: I just installed this (after scanning it for viruses).  It is working well (and free) which is a big plus over the UltraMon suggestion.
Comment: Doesn't work for dual monitor setups :(
Comment: Added a free suggestion for multi-monitor setups.
Answer: Use UltraMon's display profiles:

Display profiles make it easy to
  switch between different desktop
  configurations. A profile stores the
  display mode, position and state
  (enabled/disabled) of each monitor, as
  well as which monitor is primary
  (changing the primary is only
  supported on Windows 2000/XP and
  later).
If your computer is used by more than
  one person, you can use display
  profiles to set up custom display
  configurations for each user. Whenever
  a user logs in, his or her display
  settings will be applied. Windows XP
  Fast User Switching is supported.
Answer: Multi-monitor resolution change can be achieved for free by using MultiRes (115K when installed!) from a batch file called from user logon scripts.
For example, place the following in a batch file (adding users as necessary and call it something like MultiRes.bat):

if /I %USERNAME% == USER1 "c:\program files\MultiRes\multires.exe" /1:1280,1024,32,60 /2:1280,1024,32,60 /exit
if /I %USERNAME% == USER2 "c:\program files\MultiRes\multires.exe" /1:1024,768,32,60 /2:1024,768,32,60 /exit

Place this batch file in an accessible directory, such as:

C:\Documents and Settings\All Users\MultiRes.bat

Add this as a user logon script:

Open the Group Policy Editor (Start -> Run, enter gpedit.msc)
In the left-hand tree of the Group Policy window, open User Configuration
Open Windows Settings
Click Scripts (Logon/Logoff)
In the right-hand pane, double-click Logon
In the Logon Properties window, click Add...
Click Browse... and select your MultiRes.bat file
Click OK and then OK again and close the Group Policy window

Please Note: MultiRes is free for personal use only. See above URL for further details.


Include central function that applies for all my Wordpress themes

Question: I have a Wordpress network with a big amount of different themes and even more pages using those themes.
Now, I have a PHP function (for some tracking) that I want to run every time a page from my network is accessed. I don't want to edit all my themes, so I am looking for a central file where I can have this new function.
First thing in my mind was the index.php in the root folder of the WP installation. This would probalby work but does not seem the finest solution.
All my themes are using the wp_head function maybe this can help somehow?
Is there any other place where I can add my tracking code and make sure that it is run on every page access?
Comment: I'd suggest implementing Billy J answer as a Must Use plugin as pointed by doublesharp.
Answer: The two options I can think of would be to use a plugin that loads "custom functions" for the sites that it is included on - much like functions.php in your theme, but independent of each theme. I wrote a plugin that does this which you can find here: http://justinsilver.com/technology/wordpress/wordpress-plugins/wordpress-plugin-custom-functions-php/
The other option would be to put a PHP file with your code into the wp-content/mu-plugins (Must-Use Plugins) that will be loaded before all other plugins on every site in your network. A bit more straightforward than the first option, but you can't selectively disable it should you not want on it on one of your network sites.
Answer: You should create a plugin to do this. In that plugin you will have that function and add the action to the wp_head hook. This will keep it working with all of your themes and easy to change without having to go into all your themes.
The code will look something like this
/**
* Plugin Name: Tracking Function
* Description: Lets me track my code
*/

function tracking_function(){
//enter code here
}

add_action("wp_head","tracking_function");

Then, because you have a network of sites, you will have to go into the Network Plugin manager, and activate the plugin for all networks and then you can activate or deactivate it for each specific site in your network.


How do I sense that the serial monitor is started?

Question: When starting the serial monitor in IDE I want to save important data to EEPROM before the Arduino Uno restarts. I do not have physical access to the Arduino so a "press button" solution does not work here.
Answer: You can't. There is no way of detecting if the serial monitor is open or not.
However, you can disable the automatic reset and provide some functionality in your code for saving data to EEPROM when prompted through a command entered on the serial monitor (if you now need to even save the data).
Comment: you did it again.  That is a very cool trick.  Thank you for teaching me that one.  I don't understand how the 120 Ohm value was figured out, but this is something I will put in my mental toolbox for sure.  Kudos.  Upvote.
Answer: What you really want to do is to store the data before the computer shuts down.
Here is what I did.
 I am running a Mega in a car and using it for a lot of things.  The Mega receives its power from the ignition switch.  When the ignition switch it turned on, the Mega boots up.  In the "setup" section of the program, I set a digital output HIGH.  The digital output is tied to the coil of a relay.  One side of the relay is tied directly to the battery.  Once the relay is energized, the relay supplies power to the Mega.  I have a digital input tied to the power coming from the ignition switch through a resistor and a zener diode to clamp the voltage at 5 volts.  In the main program I monitor the input power digital input.  When I see the power go down,(ignition switch is turned off), I run a Shutdown program that stores all of the data I need stored to the EEProm.  Once that is done, I set the digital output LOW.  This de-energizes the relay and removes the power from the Mega.  If you push the reset button, that is a hardware reset and you lose your data.  If I want to reset the computer, I simply run the "Shutdown" routine. I can do that using a remote switch that drives a digital input.


Eval is evil... So what should I use instead?

Question: An ajax request returns me a standard JSON array filled with my user's inputs. The input has been sanitized, and using the eval() function, I can easily create my javascript object and update my page...
So here's the problem. No matter how hard I try to sanitize the inputs, I'd rather not use the eval() function. I've checked google for ways to use "JSON in AJAX without eval" and have ran accross a bunch of different methods...
Which one should I use? Is there a standard, proven-secure way of doing this?
Comment: Have a look at: http://stackoverflow.com/questions/86513/why-is-using-javascript-eval-function-a-bad-idea
Comment: I thinks eval in this case isn't evil... Maybe you should take a look at that question: [When is JavaScript's eval() not evil?](http://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil)
Answer: json.org has a nice javascript library
simple usage:
JSON.parse('[{"some":"json"}]');
JSON.stringify([{some:'json'}]);

Edit: As pointed out in comments, this uses eval if you look through its source (although it looks to be sanitized first)
to avoid it completely, look at json_parse or json-sans-eval
json2.js is insecure, json_parse.js is slow, json-sans-eval.js is non-validating
Comment: It uses eval only as fallback for browsers that doesn't natively support the JSON object, and if this does not have the "parse" function.
Comment: _json2.js is insecure_ **from where is that ? it has 1mb of regex which syntisize the string before uses eval**
Answer:
Is there a standard, proven-secure way of doing this?

There is a proposed standard way of doing this, in the forthcoming ECMAScript 3.1 version of JavaScript: JSON.parse.
It will be supported in IE8, Firefox 3.1/3.5 and most likely the other popular browsers in the future. In the meantime, you can fall back to, or use exclusively, eval(). Evil it may or may not be; certainly it will be slower than JSON.parse. But that's the usual way to parse JSON today.
If an attacker is able to inject malcious JavaScript into content you are spitting out via JSON, you have bigger problems to worry about than eval-is-evil.
Comment: hmm https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Answer: I would say, once the input is sanitized, eval is the best way to go. If your server gets compromised, people will be able to send whatever scripts they want to the client anyway. So putting an eval is not a big security risk. If you are worried about people manipulating the packets before they reach the client then, again, the scripts themselves can be modified.
Don't worry about eval. But make sure to wrap it in a try...catch block so your users don't get JS errors if your JSON gets mangled.
:)
Answer: To safely convert JSON to a JS object you should use a JSON parser such as the JSON.parse() function provided by this library.
Answer: Compare to the command design pattern: http://en.wikipedia.org/wiki/Command_pattern. Given this, you can precisely define the operations a client can execute and your application will be as safe as the underlying interpretation.
Answer: Depends on what you're trying to accomplish with the sanitation. I've had great success w/the prototype framework's support for JSON and safe evaluation.
Answer: If you're certain there's no injection risk, and you're not eval()ing in a loop, then use eval(). It will compare favorably to other options which will certainly be slower, might break, and will require the client to download additional code.
Answer: "stolen" from jQuery
// Try to use the native JSON parser first
return window.JSON && window.JSON.parse ?
    window.JSON.parse( data ) :
    (new Function("return " + data))();

Answer: Issue:
The problem eval poses is that it executes in the global scope
eval.call(document, "console.log(this)")
eval.call(navigator, "console.log(this)")
eval.call(window, "console.log(this)")
(function(){eval.call(document, "console.log(this)")})()
>Window

Scenario:
Assume you are using individual attributes in the markup code of various document-elements such as an attribute onvisible

You would like to get all elements with this attribute, turn the onvisible-content-string into a closure and put it into an EventHandler queue. This is where the JS Function constructor comes into play.
Function === 0..constructor.constructor
>true

Function('return [this, arguments]').call(window, 1,2,3)
>Window, Arguments[3]]
Function('return [this, arguments]').call(document, 1,2,3)
>Document, Arguments[3]]
Function('return [this, arguments]').call(navigator, 1,2,3)
>Navigator, Arguments[3]]

Putting it all together:
var eventQueue = [];
var els = document.querySelectorAll('[onvisible]');

for (var el in els) {
    var jscode = els[el].getAttribute('onvisible');
    eventQueue.push( {el:els[el], cb:Function(jscode)} )
}

//eventQueue[0].cb.call(scope, args);


In a closed loop system, when obtaining a bode plot why is the open loop transfer function used?

Question: In a typical closed loop system, with G(s) as the forward function, and H(s) as the feedback function, why is the transfer function used to calculate the bode plot G(s)H(s) instead of G(s) / 1+G(s)H(s)?
Comment: Short answer is you can use the CLTF. But, if the objective is to design a controller, it's often convenient to base the design on the phase margin and/or gain margin which are readily derived from the OLTF. Furthermore, if the closed loop happens to be unstable then the frequency response (Bode plot) can't be measured practically, whereas the open loop may well be stable and hence measurable.
Answer: Let me try to give you a short insight of why that is done. \$G(s)H(s)\$ is called the loop gain. You don't need to find the whole system transfer function (i.e closed loop) to have a 'feel' for what the stability looks like.
Now, with the loop gain you can analyze the relative stability of the system. Think about it, when the magintude of \$G(s)H(s)\$ is -1, the denominator in the closed loop transfer function becomes zero and the transfer function gives you and unbounded result.
So by plotting the bode plot of \$G(s)H(s)\$, you can see how close to instability the system is (how close you are to 1 or 0dB when the phase is -180 degrees or how close to -180 when the gain is 0 dB; this means -1 in the denominator). Those two tests done with the loop gain are the phase and gain margin tests.


Loose socket plugs will not stay secure

Question: I ordered snug plugs from Amazon to keep plugs in place but they don't work all the time.  Can you explain how to use the double-sided tape how and where on the socket do you apply it.
Comment: Does this answer your question? [How to prevent plugs from falling out of a wall socket?](https://lifehacks.stackexchange.com/questions/20394/how-to-prevent-plugs-from-falling-out-of-a-wall-socket)
Comment: Please post a picture (or more) to understand the problem.
Comment: If the snug-plug doesn't work, try flipping it over so the right hand 'flap' goes into the left slot and vise-versa. Look closely and you'll see that one flap of the snug-plug is slightly wider than the other - it's easy to miss. Put the wide flap into the wide slot of the outlet receptacle.
Answer: Maybe this isn't hacky enough, but I would replace the old loose receptacle with a newer, better quality one. You could also replace the plug/cord with a grounded 3 prong plug. I've never heard of the foam product, but I've avoided sticking things into power outlets ever since junior high school...
Answer: Just replace the outlet! You paid more for them snug plugs, than it cost to buy a new outlet and cover.
Comment: Not true where I come from.  Plugs cost pence, a new socket is a few pounds.
Answer: Welcome to Lifehacks.
The moderator Chenmunka offered the double-sided tape hack to hold an electrical plug securely in an electrical socket without explaining how to do it.
Here's how:

Cut a small piece of the double-sided (foam) tape that will fit between the prongs of the plug.

Put one side of the sticky tape on the plug.

That done, peel off the back of the double-sided tape so that the exposed sticky back side will stick to the electrical socket wall plate.

Push the plug far enough (all the way) into the socket so that the double-sided tape is between the plug and the socket so that the plug becomes stuck onto the plate.

I hope that's helpful.
Good luck.
Comment: New contributor Billy Goode noted that any use of tape to hold an electrical plug into a wall socket, must only be used when the appliance being plugged in isn't a large current drawing appliance such as a space heater or a power tool. The reason the plug falls out is because the socket itself is worn out. The surfaces could potentially produce a weak/or intermittent contact, increased electrical resistance, heat, and risk of electrical fire. So be careful, Better, call a professional, or at least consult a do-it-yourself electrical book.

Loose socket plugs will not stay secure


Buying salvage cars and doing the body work myself

Question: I'm not that great when it comes to working on cars but I did wreck two of my doors to my truck a year ago and then repaired them quite easily and quickly by going to a salvage yard and picking used ones up. I was thinking of seeing if I can find myself a low mileage car or truck that has minimal damage to the Frame or broken doors that can be replaced and then buy it for cheap and do the necessary body work to it myself. I found this 2020 Jeep gladiator for sale near me. It seems like I could put new door on it and it'll be fixed. Has anyone tried this or does anyone have any input before I go ahead and put a bid on this truck ?
Comment: Before you do this, I suggest you watch these two videos: [RDX Aspec history](https://youtu.be/60J0EL84PWw) and [What happened to it](https://youtu.be/Z3QUnDDqEb4) ... it should give you an idea of what really goes on at the auto auctions if you don't know what to look for and how to bid. You can find great deals, but you can also get taken to the cleaners.
Comment: I would have thought that the best ones to repair would have already been picked out before they reach the salvage yard by the people who know what they are doing.
Comment: @HandyHowie - These cars aren't from the salvage yard. The cars he's talking about are from auto auctions, which can be hit or miss. Look up [Copart.com](https://www.copart.com/) and you can see the format of what's going on as well as the types of cars which are available. I don't know if anything like this is available in your part of the world, but it has become common here in the States.
Comment: @Pᴀᴜʟsᴛᴇʀ2 My mistake. I realise that vehicle beakers in the UK buy most of their cars from auctions selling insurance write-offs.  I did miss his comment about putting a bid in, however.  I do think that the ones that appear to be really good value may be the ones that were left by the people who know what they are doing, because they would not be worth repairing.
Comment: @HandyHowie - I think there is merit to your reasoning, which should make one warry about purchasing a vehicle this way. The thing to remember is, a large portion of the vehicles which come through the auctions are straight from the insurance companies. If they are from insurance, there is no "picking over". Insurance sells them as they get them. The auto auctions specify if they are from insurance or if they are from a seller. If from a seller, you need to pay closer attention to them (IMHO).
Answer: Buying a salvage car and doing the body work yourself can be a great way to save money, but it's important to be aware of the pros and cons before making a decision.
Some of the pros of buying a salvage car include:

Low Prices: The biggest perk of buying a salvage vehicle is the remarkable savings you stand to receive
Possible High Value: There is a fair possibility that you may find a rare model or get your hands on a vehicle that needs little to no repairs.
Rare Parts: You may be able to find rare parts for your vehicle

However, there are also some cons to consider:

The possibility of hidden damage: One of the biggest dangers of buying a car with a salvage title is that there could be hidden damage that's not immediately apparent. This could cost you more in repairs than you would've spent if you'd bought a different car

Difficulty getting insurance coverage: It may be difficult to get insurance coverage for a salvage car

Challenges selling the car later on: You may face challenges when trying to sell the car later on
It's important to thoroughly inspect any salvage-titled vehicle before making a purchase. You should also check the car's history and see when the salvage title was issued. If you decide to buy a car with a salvage title, make sure to have it
Once the DMV issues a salvage title, the owner has a few options as to how to sell the vehicle:
The most common way to sell a salvage vehicle is to list it online for private buyers to make an offer
Certain dealers who specialize in "as is" vehicles may also be interested because they may have the means to rebuild the car and get it re-titled
It's important to be transparent with potential buyers about the car's history and the repairs that have been made

A salvage title is issued when a vehicle is damaged and considered a total loss by the insurance company. In most states, it is illegal to drive a salvage car on public roads. However, if you successfully refurbish the damaged automobile, you can apply for a rebuilt title. This way, the vehicle will be eligible for insurance and you'll be able to properly register, drive, and even sell it.
The main difference between a salvage title and a rebuilt title is that a salvage title refers to a vehicle once claimed by an insurance company as a total loss. On the other hand, a rebuilt title indicates that the owner fixed the vehicle, and it's currently drivable, but it does show history that it was involved in major problems. A rebuilt title has considerable advantages over a salvage title. When you buy a used car with a rebuilt title, it's ready to register, insure, and drive right away without much of a headache. That typically isn't the case with a salvage title.
In terms of selling restrictions for rebuilt title cars, there are no legal restrictions on selling them. However, some buyers may be hesitant to purchase a vehicle that has been in an accident or has had significant damage. It's important to be transparent with potential buyers about the car's history and the repairs that have been made. Providing documentation such as repair receipts and photos of the damage before it was repaired can help build trust with potential buyers. Additionally, having the car inspected by a mechanic and providing a report of the inspection can also help reassure buyers that the car is in good condition.
Lastly it important  to study in  your locality how easy it is to  get an inspection done that will  change the salvage to rebuilt title. Maybe take a trip at the DMV and ask folks over there bout what kind of approach is being cultivated - whether this is easy or inspectors make a  real fuss  doing this and if there are conflicts of interest involved. As long as the title is salvaged you will not be able to reap in the full value of the car. More people you talk to in this regard a better consensus you will have. Also understanding conflicts of interest , you might want to take information coming to you with a pinch of salt from various parties.
References :
Salvage Titles 1
Salvage Vs Rebuilt Titles
Salvage Titles 2


What is DOM (document object model) testing?

Question: I have read it from a Google blog that Google guys have used DOM concept to test Google Instant. But I did not understand it completely. Is it possible to use DOM concept anywhere while testing a web application if yes can I see some code for it.
Comment: Can you link the blog? So we can understand your context.
Comment: @NielsvanReijmersdal http://googletesting.blogspot.in/2011/07/how-we-tested-google-instant-pages.html I did not find any difficulties to understand this blog but I am looking for some practical example.
Comment: @Priyanshu Shekhar, Google wrote n automated test to compare the DOMs of a Google Instant page to a 'regular' version of the page. The comments indicate that they might open source that project in the future.
Answer: The blog post is about determining whether Instant Pages renders web pages correctly.  Or to be more precise, it is about determining whether Instant Pages renders a web page the same way that Chrome would ordinarily render a page.
If Chrome renders the page the same way in both cases, but renders the page the wrong way, their test will not detect the problem.  This is a pretty typical strategy for tests in which the requirements are fuzzy and/or there are too many test cases to test exhaustively.
The gist of the method described in the blog post is this:

We automatically scan each page, pixel by pixel, but look at what element is visible at the point on the page, not the color/RGB values. We then do a simple measure of how closely these pixel measurements match.

They can map a pixel to an element because they know the spacial extent of every element, and they know about every element because Chrome has that information in the DOM.
Of course, it is always possible that the two instances of the page will have structural differences.  Less of that will happen if you sample those pages at around the same time, e.g. if you run the tests in parallel.  Of course, you may still find cases where the page structures differ.  The blog post describes how they deal with that:

Where the pages where different we built a web page that showed the
  differences between the two pages by rendering both images and
  highlighting the difference. It was quick and easy for the developers
  to visually verify that the differences were only due to content or
  other non-structural differences in the rendering. Anytime test
  automation scales, is repeatable, quantified, and developers can
  validate the results without us is a good thing!

Software testing always requires coping with change.  The job is easier if you can find automatic ways to distinguish between the changed parts and the static parts.  The mechanism described in the blog post does that.
Finally, the OP asked whether you could use this technique to test web applications.  You could imagine capturing a web applications requirements as pair of DOMs, where each pair consists of a DOM before and after performing an action.  I personally think this would be a terrible way to test a web application because you would spend an inordinate amount of time maintaining your test cases.
Answer: From what I understand they compare the DOM of different build versions. If you expect the DOM to be same this could be a very fast way to verify you didn't change anything. Also see this page that explains the DOM, since there is some confusion about what it actually is.
You can use dom-compare to compare the DOM's, they also show some examples. It seems there is no easy way to get the actual DOM of a rendered page, I couldn't find one after some searches. I think you will need to hack some browser (good thing they are open-source) to get the run-time DOM. Save it and compare it to a previous save.
Comment: yeah, it seems so.But what if developers added a new web element on page then comparing DOM of two different versions of same page does not make any sense here. There must be something interesting in it. Google people must be doing something intelligent.


What to do when you don't want to award your bounty?

Question: I started a bounty on Infinite Scroll not working in own theme and found out the answer myself. I do not consider the answer of Otto worth the bounty. What should I do? What happens when I do not select one for the bounty?
Answer:
If you do not award the bounty within 24 hours of the bounty period ending, half the bounty value will be automatically awarded to the top voted answer posted after the bounty start, provided it has a score of at least 2. If no new answer matches this requirement, no reputation will be awarded at all, and the reputation used on the bounty will be lost forever.
privileges > set bounties
Answer: See How does the bounty system work?

If after the end of the bounty period a question has no answers, no bounty will be awarded and the question will no longer be featured.
Bounties are best understood as exchanging reputation for higher question visibility and increased answerer motivation. A bounty does not guarantee a response and is not refunded if none are received.

You cannot award the bounty to your own answer, so the bounty is lost.
Answer:
I do not consider the answer of Otto worth the bounty. What should I do?

Nothing. If you don't want to award a bounty, let it disappear.


Are protons bigger than electrons?

Question: In every text/ physics book that I've read, Protons are mentioned as particles that are bigger, way bigger 2000 times to be precise, than electrons...I believed that until a few minutes ago when I googled "what is the radius of an electron" and then I read somewhere that it was 2.5 times bigger than the radius of a PROTON...the radius of an ELECTRON is bigger than that of a PROTON. Which goes completely against every physics text book that I've read...Any help towards explaining why protons are 2000 times bigger while its radius is 2.5 times smaller than that of an electron will be valued...thanx in advance
Comment: you have to give a link to the claim. The context is important particularly in controversial statements.
Comment: Electrons, like all fundamental (i.e. non-composite) particles, are point particles in the Standard Model. They aren't little spheres with a radius.
Comment: Couldn't it be that you read something about the radius of electron's orbit instead?
Comment: Protons have that much more _mass_, not _volume_. The two are very different properties - in fact, for small particles like protons and electrons, bigger mass means occupying less space (or more accurately, less uncertainty in their position - neither electrons nor protons are little balls).
Comment: Does this answer your question? [Do electrons have shape?](https://physics.stackexchange.com/questions/119732/do-electrons-have-shape)
Comment: I suspect that this question is not based upon a very large corpus of physics books.  A quick review of some physics textbooks reveals "more massive", "mass is … larger", "mass is … bigger", "heavier", "weighs … times more", and so forth.  I only found two books that did this: _Radiography in the Digital Age_ talked about "size" and "bigger".  It immediately then contradicted itself by talking about electric charge and mass.  The other was a discussion of atomic theory aimed at helicopter pilots.
Comment: I've alway seen it very specifically phrased that protons are more "massive" than electrons. Never that they are bigger. I've never given volume much though to be honest.
Comment: The quote from **NJATC DC Theory 3rd edition (2009)** that landed me here: "_The electron and proton have two characteristics in addition to charge: size and mass (heavy or light). The electron is about three times larger than the proton but is much lighter. Even though it is only one-third the size of the electron, the proton has a mass that is more than 1,836 times greater._"
Answer: Quantum mechanical particles have well-defined masses, but they do not have well-defined sizes (radius, volume, etc) in the classical sense.  There are multiple ways you could assign a length scale to a particle, but if you think of them as little balls with a well-defined size and shape, then you're making a mistake.
de Broglie Wavelength: Particles which pass through small openings exhibit wavelike behavior, with a characteristic wavelength given by
$$\lambda_{dB} = \frac{h}{mv}$$
where $h$ is Planck's constant, $m$ is the particle's mass, and $v$ is the particle's velocity.  This sets the length scale at which quantum effects like diffraction and interference become important.  It also turns out that if the average spacing between particles in an ideal gas is on the order of $\lambda_{dB}$ or smaller, classical statistical mechanics breaks down (e.g. the entropy diverges to $-\infty$).
Compton Wavelength: One way to measure the position of a particle is to shine a laser on the region where you think the particle will be.  If a photon scatters off of the particle, you can detect the photon and trace it's trajectory back to determine where the particle was.  The resolution of a measurement like this is limited to the wavelength of the photon used, so smaller wavelength photons yield more precise measurements.
However, at a certain point the photon's energy would be equal to the mass energy of the particle.  The wavelength of such a photon is given by
$$\lambda_c = \frac{hc}{mc^2} = \frac{h}{mc}$$
Beyond this scale, position measurement stops being more precise because the photon-particle collisions start to produce particle-antiparticle pairs.
"Classical" Radius: If you want to compress a total amount of electric charge $q$ into a sphere of radius $r$, it takes energy roughly equal to $U = \frac{q^2}{4\pi\epsilon_0 r}$ (this is off by a factor of 3/5, but nevermind - we're just looking at orders of magnitude).  If we set that equal to the rest energy $mc^2$ of a (charged) particle, we find
$$r_0 = \frac{q^2}{4\pi\epsilon_0 mc^2}$$
This is sometimes called the classical radius of a particle with charge $q$ and mass $m$.  It turns out that this is of the same order of magnitude as the Thompson scattering cross section, and so this length scale is relevant when considering the scattering of low-energy electromagnetic waves off of particles.
Charge Radius: If you model a particle as a spherical "cloud" of electric charge, then you can perform very high precision scattering experiments (among other things) to determine what effective size this charge cloud has.  The result is called the charge radius of the particle, and is a very relevant length scale to consider if you are thinking about the fine details of how the particle interacts electromagnetically.  Fundamentally, the charge radius arises in composite particles because their charged constituents occupy a non-zero region of space.  The charge radius of the proton is due to the quarks of which it is comprised, and has been measured to be approximately $0.8$ femtometers; on the other hand, the electron is not known to be a composite particle, so its charge radius would be zero (which is consistent with measurements).
Excitation Energy: Yet another length scale is given by the wavelength of the photon whose energy is sufficient to excite the internal constituents of the particle into a higher energy state (e.g. of vibration or rotation).  The electron is (as far as we know) elementary, meaning that it doesn't have any constituents to excite; as a result, the electron size is zero by this measure as well.  On the other hand, the proton can be excited into a Delta baryon by a photon with energy $E\approx 300$ MeV, corresponding to a size
$$\lambda = \frac{hc}{E} \approx 4\text{ femtometers}$$

In the first three examples, note that the mass of the particle appears in the denominator; this implies that, all other things being equal, more massive particles will correspond to smaller length scales (at least by these measures).  The mass of a proton is unambiguously larger than that of an electron by a factor of approximately 1,836.  As a result, the de Broglie wavelength, Compton wavelength, and classical radius of the proton are smaller than those of the electron by the same factor.  This raises the question of where the meager 2.5x claim came from.
A quick google search shows that this claim appears on the site AlternativePhysics.org.  The point being made is that the classical electron radius mentioned above is 2.5 times the "measured" proton radius - by which they mean the measured proton charge radius.  This is true, but not particularly meaningful - being quantum mechanical objects, neither the electron nor the proton have a radius in the sense that a classical marble does.  Comparing two particles by using two completely different measures of size is comparing apples to oranges.

As a final note, I would caution you from taking any of the claims you find on AlternativePhysics.org too seriously.  To borrow a saying from the medical community, there's a name for the subset of "alternative physics" which actually makes sense.  It's called physics.
Comment: @my2cts The proton doesn't have a radius because it isn't a tiny sphere. You're referring to the charge radius - yet another way to assign a size to a quantum object. It's the most relevant measure for many experiments, but certainly not the only possible one.
Comment: @my2cts this is an odd argument. Of course people working on the proton charge radius talk about the proton charge radius and not any other measure of proton size, and because that's a relatively famous problem it's what google defaults to. It doesn't mean that other measures of proton size are "incorrect". I work in the lab where one of those measurements was done, by the way (though on a different experiment).
Comment: @my2cts Consider this: Earth's atmosphere also doesn't have a definite boundary, it just fizzles out into space. In fact, its outermost part possibly reaches *beyond the Moon*. So, how do you define its thickness? If you take the cutoff to be at 99% of the mass, it's about 31 km thick. If you choose the 99.9% mark, it's 42 km. If you take 99.99997%, it's 100 km, the beginning of space by international *convention*. But there's still atmosphere beyond that. If you imagine that it has uniform density,so that it has a definite boundary, it's only about 8.5 km. Similar kind of thing with particles
Comment: @my2cts - you are being skeptical about the wrong things. The Wikipedia article you linked to actually says that it's talking about charge radius (implying that there are other kinds of radii you can talk about). And in fact, there's a link, right there, to the Wikipedia article on Charge Radius, that clearly states "neither atoms nor their nuclei have definite boundaries" (note that this includes the nucleus of hydrogen - which is just a proton). Which means that you *have to define* what you'll take the radius to be. There's nothing controversial about any of this.
Comment: @my2cts I'm sure some experts are working in an area where the charge radius is useful... and other ones are working in an area where the Compton wavelength is useful.
Comment: @VladimirKalitvianski I was referring specifically to an internal excitation, not simply a state with more kinetic energy, but I will edit to make this point more clear.
Comment: you might be thinking of cross-section which paradoxically does not translate directly to a measure of size
Comment: Electron can be (and always is) exited into the state "electron + emitted photons".
Comment: Atomic ionization is not an internal excitation, but it shows that the atom is not point-like. There are elastic and inelastic scattering processes, and there is an inclusive picture; each gives different "sizes".
Comment: The proton radius can be determined from experiment. The three definitions of particle size given above are all incorrect. The best is the Compton wavelength (1.5 fm) which is almost twice the experimental value.
Comment: @J.Murray I am using the terminology of the experts in the field. They are working on the proton radius puzzle, where charge is implied. You are correct that energy and charge distribution can be different.
Comment: @user253751 Google gives as a first result for "proton radius" : https://en.wikipedia.org/wiki/Proton_radius_puzzle. There is no mention of a Compton radius there. You can also consult https://www.nature.com/articles/d41586-019-03364-z. No mention of a connection to the Compton wavelength there either. Please come forward with a reference if you think such a connection is relevant.
Comment: @Ilama I am not making an argument against another definition. You are the one who is making an argument for it. I am just interested to see a reference of main stream research to back this up.
Comment: Thinking about quantum particles as "as little balls with a well-defined size and shape" *is* very misleading, *but* the Newton-Wigner position operator has eigenstates localised on the scale of the Compton length. Note that the eigenstate $|x\rangle$ of the canonical position operator isn't normalisable, so unphysical. While the interactions in the standard model are point-like, fully localised states do not exist (Heisenberg doesn't allow it). Cf. the extensive literature on the Foldy-Wouthuysen transformation.
Comment: Only one of these has any claim at all to be called the size of a proton, and that's the charge radius. You should lead off with that one. The others have units of length but by no stretch of the imagination are they the *size* of a proton, unless you also think the radius of the earth is something entirely different from 6400 km. Incidentally, in that category of lengths that aren't sizes, you left out the Schwarzschild radius.
Comment: @benrg Thank you, but I am satisfied with my answer in its current form. The point I intended to make is that *"how big is a proton?"* is an ill-defined question unless you specify what you mean by *big*, and that there are a number of different quantities with dimensions of length which could, in the proper context, be interpreted as a measure of the size of a quantum mechanical particle. You are more than welcome to write an answer detailing how you find this one to be misguided, of course.
Answer: Reading the good last answer by Roger, it is also important to also note that an atom does not have a well-defined volume.
Treating the electron and proton as perfect spheres with even mass-density is not correct. Having said that, note
that while classical measurements may put the electron at about 2.5 times the diameter of a proton as you have stated (and a citation to that would be nice too - are you referring to the classical electron radius?),
the mass of a proton is 2000 times that of an electron.
The mass of an
electron is $\approx 9.1 \times 10^{-31} kg$ while that of the proton is $\approx 1.67 \times 10^{-27} kg$. "Size" and mass are not the same.
Comment: Atoms do have a well defined volume, but it depends on the chemistry. For example, a sodium atom in the metal under room conditions has a volume of ~0.4 nm$^3$.
Comment: @my2cts Is that how it's generally viewed? To me it seems a bit like saying a car in parking garage has a size of 45m3, because a 3m high 750m2 parking space has space for 50 cars. I'm no expert though, perhaps it makes sense for atoms.
Comment: @my2cts is all this pedantry and contrariness really necessary? What is the point that you're trying to make?
Comment: @my2cts Atoms do not have a well-defined volume. By quantum physics the orbitals that contribute to the "shape" and "size" of an atom have no sharp boundary. By chemistry the "volume" computer for an atom depends on the atom it bonded with.
Comment: @my2cts A car tyre has a very well defined volume. All classical objects have well defined shape/boundary/edges etc. Your logic would imply that, say a beach-ball, does not have a well defined volume because I could let air out of it. No. It's volume is $4/3 \pi r^3$.
Comment: @Foo Bar It is sometimes useful to define atomic or ionic volumes. The statement that an atom has no well defined volume is not always useful. I argue against overly confident statements because I can. No dogmas. Btw you are breaking forum rules with your last comment.
Comment: @Mark There is also the packing fraction to consider, I give you that. Note that in your car example the packing fraction is far too low to be ignored, even for a rough estimate. In crystals it is much closer to unity. See https://en.wikipedia.org/wiki/Atomic_packing_factor.
Comment: @electronpusher Your car tyre does not have a well defined volume either. It depends on pressure, temperature, load, atmospheric condition and roughness. Nothing has a well defined volume if you are critical enough. Atomic volume is well enough defined to be useful.
Comment: @jh You can squeeze a beach ball, much easier than an atom.
Answer: A proton is a composite particle with a radius of about 0.8-0.9 femtometers. This value is obtained from scattering and spectroscopic data that are sensitive to the details of the coulomb potential at very small scale.
For all we know an electron is a point particle. No internal degrees of freedom besides spin were found and scattering data are consistent with an upper limit for the radius of $10^{-18}$ m (from wikipedia but with a broken link as reference). The unsolved issue is that the EM self energy diverges for a point particle. For a radius of 2.8 femtometers this self energy is already equal to the electron mass, which is why this value is known as the (Thomson) radius of the electron. It is this number that caused your confusion.
Answer: The fact behind this claim is that the masses of protons and neutrons are about 2000 times greater than those of electrons. The mass is more objective and permanent characteristic of a particle than its size (which is often defined as the extent of its wave function and can vary significantly in various circumstances).
Comment: @alienare4422 *volume which is also directly proportunal to the radius* No, it isn't.
Comment: @alienare4422 The mass of a particle is proportional to its volume, only if you are assuming that particles have constant densities, that these densities are the same for all particles, and that the density of particle is the same under all circumstances. None of these is true, especially in the quantum world.
Comment: thanx for the answer...but think about it this way- the mass of a particle is directly proportuanal to its volume which is also directly proportunal to the radius...So I don't see how, under any circumstances, the radius of an electron can be bigger than that of a proton
Answer: Let me give you the crazy idea that the radius of an electron and a proton is fixed but complex, where the real part is the mean and the imaginary part is the standard deviation. Then the classical radius of an electron and a proton determines the mean value, and the root-mean-square value is variable in its meaning. The electron radius is pointwise at high energies, when relativistic corrections are applied, and the scattering cross section is proportional to the square off classical electron radius.
The formula for the scattering cross section of a photon by an electron does not need to be regularized and determines the scattering cross section
$$Re\sigma=\sigma(0)-\sigma(\infty)=\frac{8}{3}\pi r_e^2;\sigma(x)=\sigma(\frac{\hbar \omega}{mc^2})$$
In this case, the radius in complex form is
$$R_e=r_e(1\pm\sqrt{(Re\sigma-\pi r_e^2)/\pi}i)=r_e(1\pm 1.29i)$$
its modulus determines the scattering cross section
$$|R_e|=r_e|1\pm1.29i|=1.63r_e=\sqrt{\frac{8}{3}}r_e$$
The formulas for the cross section of the scattering of an electron by an electron and the annihilation of an electron and a positron with the formation of two photons require regularization. The regularization parameter must be chosen so that the size of the electron coincides with the size of the electron when a photon is scattered by an electron. It turns out that the three formulas equally determine the size of the electron.
There is no unambiguous value for the size of elementary particles. Elementary particles do not have a finite size and it is impossible to determine an unambiguous final size by their charge. For an electron, there are scattering cross-sections of various reactions, and with their help I was able to determine the complex size of an electron. The complex size of an electron is determined up to the imaginary part. For a proton, this cannot be done, since there are no formulas describing the cross-sectional area of reactions. Nuclear forces are not described by the perturbation theory, therefore only measurements are made and there are no theoretical formulas. The classical radius of the electron is greater than the classical radius of the proton. But this does not mean anything, the size of the proton is unknown.

Are protons bigger than electrons?