What is a Thread-pool?

Question: What is the concept of implementing Thread-pool (in C with help from pthreads)?
how can a thread be assigned to execute from the thread pool ?
Answer: A thread-pool is a collection of a fixed number of threads which are created on application startup. The threads then sit waiting for requests to come to them, typically via a queue controlled by a semaphore. When a request is made, and there is at least one thread waiting, the thread is woken up, services the request, and goes back to waiting on the semaphore. If no threads are available, requests queue up until one is.
Thread-pools are a generally more efficient way of managing resources than simply starting a new thread for every request. However, some architectures allow new threads to be created and added to the pool as the application runs, depending on request loading.
Answer: To clarify something in previous answers:
The reason that instantiating more and more threads leads to inefficiency is context switching time.  The OS periodically switches one thread for another on the processor.  This involves saving one thread's state and loading another thread's state from memory, so it takes non-negligible time, N ms, per context switch.
For example, if you have 10 threads, the context switching takex 10*N ms.  If you have 1000 threads, it's 1000*N ms.  As the number of concurrent threads increases, eventually the context switching begins to overwhelm any efficiencies derived from multithreading.  Your application has a sweet spot in terms of the best number of threads.  Once you determine this sweet number by experimentation, you can set your thread pool max size to that number of threads, thereby obtaining maximum efficiency from multithreading.
Comment: It's unlikely that it would take even as much as 1 ms to context switch, generally these are more along the lines of us. Everything else is very nice though.
Comment: who said N was an integer and who said it was >= 1?
Comment: Using the units ms suggests that the time will be on the order of ms. I believe that most people reading your answer would not think that the context switching time was around say 1 us.
Answer: Adding to anon's answer I'd like to mention that there are Fixed thread pools which have fixed numbers of thread running in them; Cached thread pools which can dynamically grow and then shrink when no work is available; Dynamic thread pools can also be bound by maximum number of threads and/or maximum length of the work queue. I don't think there is actually a set terminology for this kind of stuff and one rarely encounters non-fixed TPs written in C but at least one should know that fixed TP is not the only kind out there.

What is a Thread-pool?


Outlets that work only part of the time

Question: In one of the bedrooms there are two outlets that work part of the time if you plug something in you might have to wiggle the plug to make it work. The bedroom next to it the closet light does the same thing it will flicker on and off if you're wiggling the plug in the other room.
Answer: This sounds like a loose connection in the junction box holding the outlet that works when wiggled. It may be a poor screw connection on the outlet, a bad wirenut connection or even a bad connection internal to the outlet itself.
The power in the bedroom is likely being fed from that bad connection.
Turn off the breaker that controls that outlet. Remove the outlet cover. Test the wires with a non-contact tester to make sure they are not live. Check all connections (screws, wirenuts). If nothing looks loose, replace the outlet itself, wiring up the same way as before. Mark each wire before removing it from the outlet so you can attach them to the new outlet in the same way. Replace cover. Turn on power.
If any of this seems daunting, you probably need help from someone with more experience.
Answer: This sounds like a bad connection or a broken wire. The outlet that works when wiggled is where the problem is. With the power turned off at the breaker remove the cover plate and then the 2 screws holding the outlet in place gently pull the outlet out. If the wires are pushed into the back stabs this is a very common failure and the side screws can be used to anchor all the wires in place. A short piece of scrap wire or a small screwdriver can usually release the wire from the back stab. If one of the wires are broken it will need to be stripped and re connected. My preference is to pig tail the blacks together using a short piece of black wire going to the outlet brass colored screw and the same with the white using a piece of white going to the silver colored screw and last the grounds but this should have already have been done.

Outlets that work only part of the time


Is there a name for a function that outputs more data than was put into it?

Question: Is there a name for a function that outputs more data than was put into it? For example: let's say I input a one byte value into the function and it returns a three byte value, is there a name for this type of function?
Comment: I think the only correct answer to this question is "no, there is no widely accepted canonical  name" (except "function that outputs more data than was put into it.") If you want us just to suggest a potential new name for this kind of thing, I recommend to try [our chat rooms](https://chat.stackexchange.com/rooms/21/the-whiteboard).
Comment: Please define what, *precisely*, you mean by "outputs more data". You have already received one answer that interprets this statement to mean that the cardinality of the set of possible inputs is strictly less than the cardinality of the set of possible outputs. However, it is not at all clear to me whether that is what you mean. Can you clarify? In particular, it is unclear whether you are talking about the codomain or the image of the function.
Comment: I don't know how to be more specific. Would I need to understand what, "cardinality", or a, "codomain", is to answer this question?
Comment: Why do you ask? As Jörg W Mittag pointed out, an answer would completely depend on the interpretation of your question. E.g, if you told a programmer that some function you have is injective - it would *never* occur to them that you mean that it takes one byte and outputs three. In most programming languages, you don't normally work with raw bytes, you work with types, so this input/output ratio is not something that comes up regularly. On the other hand, a calling it a decompressor/generator would invoke an image of something that produces an output that takes up more memory.
Comment: For illustration, consider this: a function takes a single object, and outputs an array of 5 numbers. It has more outputs than it has inputs, so the output is in some sense "bigger". But, this single input is a complex object that takes up thousands of bytes, and the output array is 20 bytes (5 numbers, 4 bytes each). Would such a function fit what you're describing or not?
Answer: Assuming that your function is a function in the mathematical sense (i.e. it is deterministic and has no side effects), then at least it is injective and not surjective, since it has 2^8 possible inputs, but the codomain has size 2^24. Wikipedia
Comment: It doesn't have to be injective. For example a function _f_ that takes a one byte value and always returns 0x000000 is not injective, because _f_ (_x1_) = _f_ (_x2_) does not imply _x1_ = _x2_.
Comment: This answer is plain wrong.
Answer: You could perhaps call it a "generator" or a "decompressor"; after all, there's no obvious upper bound on how much output from how little input there is. Even when you count the size of the function itself as "input".
There's an entire demoscene of work producing large amounts of video and sound output from four kilobyte executables.


Pub Sub using http(port 80) ( NO WCF client)

Question: I want to develop a scalable pub-sub system
it has to be on port 80
firewalls \ NAT should just work
and I cannot deploy a WCF client ( server can be WCF if needed )
any thouhts \ suggestions on how to get going
Answer: You could use MSMQ over HTTP. Check out this post
Answer: Check out the Publish-Subscribe Framework and the Publish-Subscribe Example developed by Juval Lowy at IDesign.  The framework and example can be downloaded and used for free.  You just have to provide your email address.  The download link is here.  You may have to scroll up just a little bit to see them both.


Assign cell types to groups of cells based on their gene expression profiles

Question: I have large filtered, normalized dataset of scRNA-seq data of C.Elegans species. Rows are genes (10 000), columns are cells (66 000). Let's say that I got 40 different groups of the cells based on their expression profiles, how could I now assign cell types to these groups? I would expect to get some reference dataset for C.Elegans and compare it with what I got, but I honestly have no idea of where to get such a dataset, and whether there are any R packages that do that. Any advice would be greatly appreciated.
Answer: I think the analysis will involve two steps:
1) Compile a reference list of cell types, with a list of genes expressed in each of them, based on the literature. C. elegans has only ~1000 cells, so I'm sure it's been well researched. Mark which genes are just expressed in that particular cell type, and which are uniquely expressed, this latter will be more useful markers.
Resources to do that:

http://openworm.org/science.html#other
http://www.wormatlas.org/
http://www.wormbase.org
Pubmed.
Your lab's knowledge.

This will involve mostly manual work, but maybe you can find some list.
For example, platelets express VWF. And activated platelets express SELP.
2) Use one of the single-cell RNA-seq packages (e.g. Seurat) to cluster cells and to find the "marker" (DE) genes for each cluster (vs. all other clusters).
For each cluster, look up the marker genes in the reference list and infer the cell type.
You may need to infer the cell type from the functions and descriptions of the genes.
Also see Retrieve detailed gene descriptions
Keep in mind that you will have many confusing doublets in the dataset expressing characteristics (genes) of two cells.
You may also need to re-do t-SNE and clustering on a subset of cells, e.g. blood/immune cells, in an iterative, hierarchical way.

Do you have information on which cells are from the same worm? Once you have a reference list, you can try and identify cells of just one worm.
Answer: This is an old post, but we have recently published a web-based tool called CIPR (cluster identity predictor) that enables users to upload their data along with a custom reference file for annotating unknown clusters. You can probably obtain relevant reference datasets from GEO.
You can read the manuscript in BMC Bioinformatics for more information about how the algorithm works.


Interpretation of Regression coefficient

Question: I have a five-variable regression equation, and I added any constant (fixed value, say 100) to all the observations of variable $A$, another (or same) fixed value in variable $B$, while the other three variables are unchanged, what will be the interpretation of the Betas of variable $A$ & $B$ (A & B are Independent variables).
Comment: What is the reason you want to add that constant?
Comment: If I read you correctly you are asking how the coefficients change if you add a constant value to all the observations of one of the variables in multiple regression. Is that correct?
Comment: Dear Antoni, Yes. My point is if I have independent variable (A) and I transformed A by adding constant in all its observation and new variable is A*. Now I regress  the multiple regression and use A* instead of A. How I can interpret the coefficient of A*. Remember I am interested in coefficient of A not A*. Thanks
Answer: If you transform one of the regressors by adding a constant, this shift will not influence the actual slope or estimated coefficient $\hat \beta_i$ of the regressor. Instead, it will be absorbed in the estimated intercept, which will be displaced because all the points in the data cloud will shift accordingly. As an example, here is the plot of a multiple regression with only one regressor plotted together with the OLS regression line including the intercept and the slope of the plotted regressor. After shifting the explanatory variable $20$ units up, the slope stays unchanged, but the intercept is shifted accordingly:

If instead, you transformed the variable in question by multiplying it by a scalar value, there would not be any translation of the data cloud, but the slope would change. You would be doing the equivalent of a change of units in the explanatory variable:


Are identifying chords or notes in a song on topic?

Question: The Music: Practice & Theory Stack Exchange site does not allow questions around identifying transcriptions (chords, progressions, or notes in a particular song). Is that in scope for this site?
Comment: in which way, the identifying transcriptions (chords, progressions, or notes in a particular song) is different to identify lyrics?
Answer: I would say no as there's not really a point on a music fan's site. It dives way too much into actually playing and analyzing music then listening to or consuming it.
Answer: After having had a bit more experience with both sites, I'm going to suggest that as music.stackexchange.com doesn't allow these questions, that yes, they should be allowed here.
Comment: That's really not a good reason to put them here... We're two independent sites. What Music SE allows and doesn't allow shouldn't affect us.
Comment: Note that this completely contradicts an earlier comment I made!
Comment: @Dom If someone agrees that such questions could work on SE, then the fact that no other SE site will currently accept them is a logically sound reason to *consider* accepting them here, as you'd be providing a new service that didn't previously exist.
Comment: The point of an SE is to eventually become a library of questions for a group interested in a topic along with user interactively building it and improving it. I can't see transcription working o this SE or any SE that's not completely dedicated to it with a strict scope as there will only be a few who can answer in our group, they are time consuming, and there are infinite one off questions that will be little use to others.


Does hostile juxtaposition work on my attacker?

Question: Hostile juxtaposition will let me essentially swap places with another creature when attacked, allowing the attack to damage that creature instead. If the target of my hostile juxtaposition was the one attacking me and I activated it, would the target damage itself? This should work by RAW, and Ican see this working fine with regards to a ranged attacker, but will this allow me to swap places with somebody throwing a punch at me?
Comment: @HeyICanChan: I have no solid information to back that up with and am far from an expert on Pathfinder. If Hydrothermal asks, I'll do it, but otherwise, I'll wait for an expert.
Answer: "Stop hitting yourself!"
The description of the spell hostile juxtaposition does not say that the creature that's affected by the spell and the creature doing the attacking must be different creatures:

When attacked or the subject of a spell that deals damage to you, you can spend an immediate action to cause yourself and the target creature to teleport and switch places. The target then becomes the target of the triggering attack or spell instead of you.

Thus, according to the rules, a creature can totally stab itself with its sword or be impaled by its own arrow. Even by strictly interpreting the rules for immediate actions, the spell specifically allows the immediate action to be taken upon being attacked but before damage is dealt.
(Note that in such a case the swapped-in creature's attack or spell isn't automatically successful; the creature merely becomes its own target. A swapped-in creature must, for example, still make a successful attack roll against itself or fail a saving throw against its own spell.)
The GM may, however, still say No
Despite those being the rules, having a creature teleporting into its own sword blow may be disconcerting to a GM worried about the magic system's realism. Such a DM may argue, for example, that a creature just can't make an attack roll, teleport, and stab itself: "The spell would have to teleport the parts making the attack after the parts being attacked, and that's not what the spell says it does!" Although this GM finds such a stance on magic difficult, were I player in such a campaign it would take more than that single ruling to force me to leave the table.
Comment: Maybe it can teleport the subject without teleporting his weapon?  Still doesn't work for monks and natural attackers, but I could see a guy being teleported *onto* his sword being rather miffed that the sword he swung in front of him is now sticking out of his back.
Comment: @gatherer818 Yeah, maybe it's, like, **really fast** [*Portal*](https://en.wikipedia.org/wiki/Portal_(video_game))-like hilarity? I have no idea.


How to rebuild double disk failure in IBM x3650 M3 raid 50

Question: i have a problem with IBM x3650 M3 raid 50 with 16 sas 146gb disks. Before christmas one of them started to lit yellow, but the machine wasworking (running esx). I have oredered a new one, but before i managed to replace it another one died, and the esx does not boot any more. Now i am not sure if the system will be able to rebuild the drive. The drive is divided into two spans, and both damaged disks are from the same span. Can anyone advise me what steps should i perform now before repleacing the disks?
Comment: Obligatory: RAID is not backup, it's just a way to minimize downtime. If you're using RAID 5 or any variant of it, you *must* have spares on hand unless recreating the array is nearly painless. Why do we keep seeing questions like this?
Comment: @emtezet If both failed drives are in the same span, you likely cannot rebuild any more and need to replace the drives, reinitialize the array and restore from backup.
Comment: Wow, that's a bad, because previous administrator did not bother in making backups, or having spares i started working here just before christmass... what about if i would be able to repair one of the actual disks (assuming it is a hardware issue on the elecrical board)? The virtual drive is now marked as offline. Would be possible to make it alive without loosing the data?
Comment: @emtezet: You sound like you are in way over your head. Don't mess with the actual drives. Follow @shodanshoks advice regarding `ddrescue` and **don't touch** the broken drives for anything else. The more you mess with them, the less the chance for data recovery firms to fix things if you decide to go that route in the end.
Answer: If both failed disks are from the same span you are screwed, as it means a dual failure in a RAID5 subarray.
If you don't have/can't restore from backups and the failed disks are not completely broken, the only thing you can do before contacting a data recovery firm is to order two new SAS drives and use ddrescue or testdisk to recover as much data as possible from the failed devices. If they went bad only due to some bad sectors, and you are very lucky, maybe you can revive the entire array.
If all else fails, you must contact a professional data recovery service.
Comment: Thankyou for your anwser. Considering that i would be able (and lucky) to restore the data and put on a new disk will the array try to run itself or shoud i try to restore it with the megaraid tools? In the second case what steps will lead me to most harmless solution?
Comment: After `ddrescue`, the new drivers **should** be automatically detected by the RAID controller. Anyway, after imaging the old disk, don't mess with them anymore. If you are uncomfortable with disk imaging, please stop here and contact a professional recovery service.


Can you write a 301 redirect to an anchor point?

Question: Is this valid and correct?
RewriteRule ^myOldPage.html$ /index.php#info [R]

I'm specifically interested about the #info part.
Answer: Yes. That's a  valid 301 redirect (the HTTP standard allows for any valid URI to be provided as the redirect).
Now the caveat: Not all search engines may love the redirect. Google does a fantastic job of handling anchor tags (they even have a patent on this), while others will completely ignore them. As long as that's not an issue, the redirect is technically valid.
Update: If you're having trouble with mod_rewrite, try the NE (no escape) flag to prevent the # symbol from getting encoded:
RewriteRule ^myOldPage.html$ /index.php#info [R,NE]

Comment: thanks! I was just coming back here to say about how it didn't work because of the # getting encoded...
Comment: What if we have to point to multiple anchors on the same page? For example: #info, #transformation, #coding-environment...
Answer: Although it looks correct, I have a strange feeling this won't work.
The browser needs to know about the #anchor. The server and mod_rewrite may well just ignore it.
If it doesn't work I guess you could do something like..
RewriteRule ^myOldPage.html$ /index.php?info=true [R]

and then in the php output a piece of javascript to do the anchor jump.


How to detect if a player is within a mob's line of sight, and can that be changed?

Question: Is it possible to detect if a player is within a mob's line of sight? And if so, can that line of sight be changed to only see things in 1 axis? For example, only being able to see things in front of it, but not if it's 1 or more blocks away from it.
Comment: Hi anomanous. It is extremely difficult but possible. I once tried to create an aimbot combining this mechanic and failed to do so. What I tried is to teleport the player facing the nearest mob and use a predicate ```looking_at``` to determine if the player is looking at an entity or not. If there are obstacles in between, tag the nearest mob because it cannot be seen. This way on the next tick we find the nearest mob without that tag so on and so on until we find the nearest mob without a tag. However, this method has many flaws and bugs so it is merely a concept.
Comment: Moreover, the predicate ```looking_at``` does not apply to mobs. So you might have to teleport the mobs facing you, then use raycasting to see if there are blocks between the mob and you. If there are blocks, simply stop raycasting forward. If the raycast is able to detect you it means that the mob will probably see you. You can mess around with raycasting to change the mobs  sight distance. I can provide you with a detailed answer if you ask for it.
Comment: Hello, I would very much like any answer for this question , no matter how difficult.
Comment: you can use radius eg.(@e[r=....]) but it breaks the things you wanted and it works even through blocks
Comment: You can use ^ ^ ^ it can phase through blocks though.
Answer: sorry for the late answer but I have found the ultimate trivial method to do what you want. To start off, it involves passenger entities and raycasting. The code is really short but you will still need a datapack for the raycasting function.
The only downside to this method is that the subject entities that can detect your presence must be unique and summoned manually.
First, spawn a mob with an armor stand riding it using the following command.
summon zombie ~ ~1 ~ {Passengers:[{id:"minecraft:armor_stand",Invisible:1b,Invulnerable:1b,Tags:["probe"]}]}
In this case a zombie with an invisible armor stand tagged "probe" is spawned.
Now you want to have this mcfunction in your datapack.
execute run particle flame
execute if entity @p[distance=0..0.99] run say hit!
execute if block ~ ~ ~ #permeable positioned ^ ^ ^0.2 run function namespace:raycast

It is really short and efficient and the particle command is of no practical use other than displaying to you the ray so you can delete it later. Next up, the command checks for the nearest player within a 1 block radius. Note that the detection range is set to 0.99 so that there is a minimum risk of detecting though blocks. Last command dictates that if the block it is currently in is not classified as permeable, it does not repeat itself (stops raycasting).
Now what you have to do is simple --- execeute as @e[tag=probe] at @s run function namespace:raycast. Watch as the armor stand detects you within its line of sight and say hit!. The armor stand does not detect you if there are blocks in between.
A few Tweaks you can bring to the command
You might want to consider entities obstacles as well. That is, if you are hiding behind mobs, the armor stand could not detect you. If that is the case, replace the function command in the .mcfunction with execute if block ~ ~ ~ #permeable unless entity @e[type=#exclude,distance=0..0.99,limit=1,sort=nearest] positioned ^ ^ ^0.2 run function namespace:raycast
As you have mentioned in the question, you would like the mob to have a maximum detection range. I would take it as 10 blocks for example.
The frequency of raycasting in the function is 5 times/ block, which means that if the function runs 50 times, a maximum total of 10 blocks have been covered within 1 tick. You can set up a dummy scoreboard. scoreboard objectives add count dummy. Insert this into the middle of your function scoreboard players add @s count 1. Replace the run function command with this execute as @s[scores={count=..50}] if block ~ ~ ~ #permeable positioned ^ ^ ^0.2 run function namespace:raycast
And at the end of the function you would insert this line of command.
execute as @s[scores={count=51..}] run scoreboard players set @s count 0
This way you have limited the range of raycasting. Just for you to double check, the code in raycast.mcfunction should look something like this now.
execute run particle flame
scoreboard players add @s count 1
execute if entity @p[distance=0..0.99] run say hit!
execute as @s[scores={count=0..50}] if block ~ ~ ~ #permeable positioned ^ ^ ^0.2 run function namespace:raycast
execute as @s[scores={count=51..}] run scoreboard players set @s count 0

How to integrate Probe with the mob it rides on
Until now although the probe rides the zombie, they are still literally two different entities. To eliminate this discrepancy we use a selector @e[type=zombie,limit=1,sort=nearest] to figure out the closest zombie in relation to the probe armor stand, then execute a function as that zombie.
It should look like this now.
execute run particle flame
scoreboard players add @s count 1
execute if entity @p[distance=0..0.99] run execute as @e[type=zombie,sort=nearest,limit=1] run say I see you lmao
execute as @s[scores={count=0..50}] if block ~ ~ ~ #permeable positioned ^ ^ ^0.2 run function namespace:raycast
execute as @s[scores={count=51..}] run scoreboard players set @s count 0

Replace the "I see you lmao" with a function of your own choice.

Killing the Probe
In your tick function,
execute as @e[tag=probe] at @s unless entity @e[type=zombie,distance=0..2,limit=1,sort=nearest] run kill @s
All the above code has been verified by myself and all works. There are other variations you can play with the function but I surely won't list out all of them here. Your question is certainly a great one as it is mutually beneficial.  I could use this method for my own project as well. Hope that works for you as well.
Have a good one.
Edit: the #permeable group is a predefined block type tag in the datapack.
{
    "values":[
        "air",
        "cave_air",
        "cobweb",
        "water",
        "tall_grass",
        "grass",
        "#flowers",
        "#crops",
        "#fire"
    ]
  }

Comment: For some reason the code works and all, but only if I do it manually for some reason. I put all the code in and it should be working, but it is not, does it need to be in a specific line of folders, does it need a specific name, or does it need a specific version?
Comment: If you look carefully the entire code is based on a probe entity mounted on its host. The reason is that if I rotate the zombie itself facing the player, it won't move at all.
Comment: Did you define the #permeable block type? I had put the json file content down there. If you want to save yourself from the hassle you can replace the #permeable simply with "air". But I do warn you that it might not work underground.
Comment: Also did you create objective "count"? It should be a dummy
Comment: As said above, only zombies spawned with the specific summon command would obey the datapack.
Comment: I created the objective, summoned the zombie with the specific command, but I did not define the permeable block type, do I just put the code shown in the edit at the bottom?
Comment: The code is written in .json format. You can search Google for how to define block types if you don't already know. For now you could just go for air instead of #permeable.
Comment: Also, do you have this ```execeute as @e[tag=probe] at @s run function namespace:raycast``` in your tick function? A tick function is one that runs every single tick.
Comment: I replaced #permeable with air, and I placed that within, and I changed the file that holds the code into a .json which made the code inside red and yellow, is that meant to happen? Oh and it still does not work for some reason, does it need to be on a specific version?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/133194/discussion-between-hfanatic-and-anomanous).
Answer: I just commented something about using ^^^ and I almost forgot armour stand exists.
what you can do with this is you can make the armour stand into a ray and use it for ray casting just like one of the comments said.
you can make it go forward for a few times using tp
execute at @e[type=minecraft:zombie, tag=...] if @e[r=10, type=minecraft:armour_stand, tag=...] run tp @e[type=minecraft:armour_stand, tag=...] ^ ^ ^1

then while its doing that make it check if its inside a block then make it go back to its starting point if it is.
execute as @e[type=minecraft:zombie, tag=...] at @e[type=minecraft:armour_stand, tag=...] if block ~ ~ ~ minecraft:air run tp @e[type=minecraft:armour_stand, tag=...] @s

then check if the ray is near/within the player then you can now run what ever you like if the mob is looking at you.
execute as @e[type=minecraft:zombie, tag=...] at @e[type=minecraft:armour_stand, tag=...] if entity ~ ~ ~ @a
    execute as @e[type=minecraft:zombie, tag=...] at @a unless entity ~ ~ ~ @e[r=1, type=minecraft:zombie, tag=...]

Comment: I reckon that education edition or bedrock edition commands.
Comment: Teleportation can be really inconsistent and laggy, especially when there are many armor stands. Armor stands are difficult to render for the game and adding the invisibility tag to them brings no improvement at all.
Comment: Besides, if you have ever tried in-game, teleporting entities to your position is always delayed, rendering your method pretty unreliable and inconsistent


Doctrine2 subquery

Question: I'm trying to write a subquery in doctrine2, to sort a table ordered by date column of another table.
(let's say I'm querying table A, which has an id column, and B has an a_id and a date, in the subquery b.a_id = a.id)
I'm using query builder, and the addSelect method, but since I can't use LIMIT in my query I get this error:

SQLSTATE[21000]: Cardinality violation: 1242 Subquery returns more
  than 1 row

This error is true, but how could I limit this query to 1 row, if LIMIT is not allowed in doctrine2 and when I try to do it by querybuilder (I mean the subquery) and I'm using setMaxResults, and then getDQl it is still not working.
->addSelect('(SELECT b.date FROM B b WHERE b.conversation = a.id ORDER BY b.date DESC)')

Is there any solution for my problem?
Thanks
Answer: Make the query return exactly one row. Try SELECT MAX(b.date) FROM B b WHERE b.conversation = a.id)

Doctrine2 subquery


how to connect raspberry pi with composite in crt monitor?

Question: I don't have a monitor with hdmi input so I purchased an av cable to connect my raspberry pi 2 model b with a crt tv I have. I have read that the default output of the pi is the hdmi and I tried to change by pressing SHIFT and the 1,2,3etc on my keyboard, as I have read here, but that won't do the trick. I don't know if its the keyboard that doesn't work it lights up though, I was wondering if I could change the default display output from the pc somehow. Needless to say I have downloded, extracted and copied the latest noobs on the sd card can anyone help with all these?
Thanks in advance
Comment: I edited the cmdline.txt adding Display=2 but that didn't help. I conclude that there must be something wrong with the av cable
Answer: For help with NOOBS and config.txt see https://github.com/raspberrypi/noobs
config.txt settings are shown in http://elinux.org/RPiconfig
Add one of the following settings to /boot/config.txt and reboot.
<code>Video mode options

sdtv_mode defines the TV standard for composite output (default=0)

sdtv_mode=0    Normal NTSC
sdtv_mode=1    Japanese version of NTSC – no pedestal
sdtv_mode=2    Normal PAL
sdtv_mode=3    Brazilian version of PAL – 525/60 rather than 625/50, different subcarrier

sdtv_aspect defines the aspect ratio for composite output (default=1)

sdtv_aspect=1  4:3
sdtv_aspect=2  14:9
sdtv_aspect=3  16:9
</code>
Comment: thanks for the reply, but how will I access config.txt?
Comment: @impischi Added a link at start of answer.


Odds ratio direction changes in multinomial logistic regression

Question: I am doing a multinomial logistic regression in R for an outcome variable with four categories, and 9 categorical independent variables. My dataset contains 1408 observations. When I run the model with all variables, the GVIF (1/2*df) values are good. However, when I compare the odds ratios of the multivariable model with univariable models for each predictor, the direction of the odds ratio changes for the variable gender, and for the intercept of one group. When I leave the variable gender out of the model this still happens to the intercept of that group. I am not sure how to interpret is. I also tested interactions between gender and the other predictor variables, and those are non-significant. I know that changes in odds ratios/regression signs can be a case of multicollinearity, but can there be other explanations as this does not seem to be the case here?
Answer: I would not worry about the intercept terms unless there is some reason to do so. In general, they aren't too informative or interesting as you are usually interested in  the independent variables and the dependent variable.
The fact that the sign for the parameter for sex changes when you add other variables means that, controlling for those variables, the shape of the relationship between sex and the DV changes.  This can only happen if the variables are not completely orthogonal, but it doesn't have to involve a problematic level of collinearity.
One way this can happen is if two of the IVs (sex and another) are mediators (in one direction or another). Interactions (which you looked at) are about moderation rather than mediation -- it is easy to get these two confused.
There is a tag for mediation, which might be useful to look at.


Why the work done by system not stored as potential energy?

Question: Now choose a spring mass system now work done by external agent in slowly moving from equilibrium position is stored as potential energy but where is work done by spring force gone.For genralization work done on system is stored as potential energy but where is work done by system gone during the process?
Answer: For generalization work done on system is stored as potential energy but where is work done by system gone during the process?
The work done by the spring mass system takes the work done on the spring mass system and stores it as potential energy in the spring mass system. The net work done on the mass of the system is zero. The following is presented as an explanation.
When an external agent (for example you) applies a force to a mass on the end of a spring (let's assume the spring is horizontal so that gravity plays no role) it compresses the mass spring system. The force you apply to the mass is in the same direction as the displacement of the mass so you do positive work on the mass equal to $\frac{kx^2}{2}$.
At the same time the spring exerts a force on the massin a direction opposite the displacement of the mass. Therefore it does negative work taking the energy you provided to the mass and storing it as potential energy of the spring mass system. The net work done on the mass is zero, since by the work energy theorem the net work done on an object equals its change in kinetic energy. For this example, the change in kinetic energy is zero since the mass begins and ends with zero velocity.
Bottom line, the work you did winds up stored in the spring mass system as potential energy. The work you did in compressing the spring is not gone. It just becomes potential energy.
The gravity analogy is when you lift an object starting at rest on the ground and bring it to a point at rest a height $h$ from the ground you do positive work transferring energy to the object. At the same time the force of gravity, which acts opposite the direction of movement of the object does an equal amount of negative work, taking the energy you gave the object and storing it as gravitational potential energy of the object/earth system.
Hope this helps.
Comment: @HarshitRajput In this, like most spring problems, the spring is considered to be massless to simplify the analysis. A massless spring cannot possess KE. Once one includes the mass of the spring, the analysis becomes more complex, as you can see in the following link. https://physics.stackexchange.com/questions/471462/springs-with-some-finite-mass
Comment: Hello @BobD, I have a related question. If there wasn't any block attached to the spring and the force was directly applied by me on the spring, then the force applied by me does a +ve work trying to increase the KE of the spring but then there is no increase in the KE of the spring, which force is responsible for doing a -ve work in this case, which tries to remove the energy supplied by the +ve work done by me?
Answer: Well consider the definition of potential energy here:-
The change in potential energy of a system is defined as the negative of work done by the internal conservative forces of the system.
In your particular case it is the spring force which is internal and is responsible for change in potential energy of the spring.
The work done by external agent is equal to change in potential energy of the system if and only if the change in kinetic energy of the system is zero.
Again, I want to emphasize that when spring is pushed or extended slowly only then the work done by external agent is equal to change in potential energy of the spring system.
Comment: Yes again.  Yet another example of why definitions of potential energy in terms of the external force are at best confusing, and possibly faulty.  Unfortunately, many introductory texts use the faulty definition.
Comment: Why is it necessary that the process be quasi-static  (assuming an ideal spring)?  Isn't it only necessary that the kinetic energy at the start of the displacement is the same as at the end?
Answer: No energy is lost.
An external force does positive work on the spring when the spring is compressed because the external force on the spring and the displacement of that force are in the same direction.
You can also say that the spring does an equal amount of negative work when the spring is compressed because the force exerted by the spring and the displacement of that force are in opposite directions.
The work done on the spring is equal to the work done by the spring and so there is no net work done on the spring.
And yet another way of explaining what has happened is to say the the spring has gained elastic potential energy as it was compressed equal to the positive work done by the external force (or equal to the negative work done by the spring force).
Answer: After the spring is extended by x (until this, work is done on the spring, i.e. not by the spring), this spring then returns back to its natural length for which it does some work that is $\frac{1}{2}kx^2$. This also applies for the case when the spring is compressed.
Answer: To add to the previous answer. The energy stored is known as Elastic Potential Energy to the best of my knowledge. Thus, the energy is in fact stored as a form of potential energy - since the position of the mass in the mass-spring system determines the kinds of energy it possesses.


Is there a material that becomes permanently conductive after being exposed to light?

Question: There exist a material that becomes permanently conductive after being exposed to light?
Comment: I find it simply surreal, calling this question as "non-mainstream". What would be mainstream for the close voter, maybe Ohm's law?
Answer: I'd say that depends heavily on the light. Especially on the heat that is deposited in your material. The keyword here is resistive switching (for example in oxides).
With light that deposits enough energy it is for example possible to switch phase change materials between a low and high conductive state. This is how DVDs work. For DVDs the reflectivity is read out, which also changes from one state to the other. But the resistivity is switched too, as you can see in the graph below.

(I took this graph from my lecture notes: Prof. Mayer, RWTH Aachen)


My friend can't find my clan

Question: I have a friend that's trying to join my clan but when he searches for it, my clan doesn't come up.
Comment: I'm going to assume that this is actually Clash of Clans and not Castle Crashers, given that the latter has no such thing as clans. Also, what platform is your friend on, and what other information can you provide?
Comment: Use advanced search for better results. Specify frequency, location, clan points.
Comment: I really feel that this question is quite pointless, given that CoC has SOO many ways to find a clan (ex Clan ID, bookmarking, etc)
Answer: Best way to do this would be to give your friend your clan tag.  (It's a 7 character alpha-numeric code preceded by a #).
Your friend can then enter that into the search box and find your clan.
I had the same problem; where i joined a clan with several pages worth of others with the same name.  This worked perfectly for me.
Answer: When I created my first clan, I named it after my favorite show from my childhood: Naruto (a popular anime). However, when I had searched for it on a friend's device join them, many other people had the same idea, so in the end I had found it after recognizing my flag colors and member count.
Most likely many others had the same idea so I would suggest telling him how many members your clan has and what your flag looks like. If that doesn't work, I suggest making a new unique clan name only your friends would think of.
Comment: im sorry if any thing I post is not useful im try my best to help
Comment: +1 that is what I prefer, -0.5 not being able to find can actually be a bug.
Answer: If you are not able to find the clan it could also mean that he/she is ineligible to join your clan. May be you have set a higher trophy count than your friend's. If you go to the advanced search you will find a button "Show only clans that I can join". By default its set to On. By turning it off you will be able to see all the clans matching the search keyword, provided you have searched with the proper clan name.
If this was the reason why your friend could not join you need to change settings to make it eligible.
Answer: SuperCell does not stop players from creating clans with the same name. When the player searches for a clan by its name, it may be difficult to locate the desired clan through many others with the same name. There are a few solutions:
First: give your friend information like the badge of your clan, the level, the members, and total trophies to assist him in finding your clan.
Second: give your friend your Clan Tag which he can search your clan with
Third: if your are on your friend's friends list, he can tap on your name and click View Clan

My friend can't find my clan


Disabling Mac OS X Mail.app periodic SMTP server check

Question: My Mail.app is configured with three IMAP accounts and four SMTP servers.  (Each SMTP server is for a particular network connection.)  Every 10 minutes, Mail.app polls the SMTP servers to test connectivity
That by itself isn't a problem.  The issue is that these two SMTP servers require usernames and passwords.  Those credentials are stored in the account keychain, so every 10 minutes I'm prompted to unlock my account keychain.  That is six interruptions an hour, and is quite annoying.  Is there any way around this problem?
Answer: I'm not sure if it's possible but, have you tried creating a new Keychain to hold those values exclusively? If that works, then you could make that keychain only lock when you logoff.
I'm not sure ifyou can move those values to a new keychain tho'-
Try the Keychain Access app.
Comment: Good idea -- I'll try that out and hopefully have an answer in the next 10 minutes or so...
Comment: This did the trick.  I created a new keychain and dragged the SMTP authentication credentials from the display of the 'login' keychain to the new keychain.  Then I changed the keychain settings by right-clicking on the new keychain, selecting "Change Settings...", and unchecking the two "Lock..." settings.
Comment: Glad it worked Peter. No more annoying popups. ;)


How much time does it take for a Lightning node to forward an HTLC?

Question: How much time passes between the moment an intermediary node receives an HTLC and the moment it forwards if to the next hop? At least what order of magnitude is it? Is it comparable with network-latency (tens to hundreds of milliseconds)?
Answer: Short answer: Yes network Latency is should be the dominant factor here. (I have not profiled it and I am not aware of benchmarks)
If you look at bolt 02 https://github.com/lightningnetwork/lightning-rfc/blob/master/02-peer-protocol.md#adding-an-htlc-update_add_htlc you will see that update_add_htlc message including the onion and commitment-signed message will have to be sent / exchanged. (revoke_and_ack is for settling the htlcs) while decrypting the onion and producing signatures are computationally rather expensive operations (we should not forget encrypting and decrypting the lightning messages themselves according to bolt 08 and noise_xk) these operations even on a local area network should not exceed the time for network I/O.
Comment: Do you have an understanding about the order of magnitude of these delays? Like, is it in single milliseconds?
Comment: I always like the times given in this excellent article https://norvig.com/21-days.html this should hold perfectly as estimates. So depending on the location of your channel partner the network io could be a couple hundred milliseconds. Everything else should be in the order of microseconds. But again did not measure that myself. But take a local lap and pay with your phone. See how money arrived at the LAPP but your phone has not signaled a successful payment as preimage is being propagated back (which is also mainly network io)


When I choose a new ordinance, how soon does it go into effect?

Question: Does anyone know the details of the ordinance system? If I have one ordinance going, and cancel it to put a different one into effect, does the change happen immediately? The next day?
Answer: They go into effect the day following your selection/payment for the new ordinance. Note that the "day" for Animal Crossing, for most purposes, starts at 6 AM, even though the date (of course) rolls over at midnight. This is noticeable if you're playing right before 6 AM as once the clock hits 6 a short cutscene will say "it's a new day" or similar and the game will save and continue as part of the "new day" process.
I believe Isabelle even tells you this as you change the ordinance.


How to select all multipoint features from a point layer?

Question: I'm connecting to WFS layer by qgis. On some layer I've got points features and few multi-point features. Whole layer contains about 1000 features, how can I do some query just to know which features is multipoint geometry?
Comment: which version of qgis?
Comment: Do you really have a mix of Point and Multipoint features, or do you have all Multipoint features, and you want to select those that have more than one point within them?
Comment: @smithkm yes, when I was trying to export to shapefile I've got message, that geometry type is mixed, and I need to default one type of geometry..
Answer: Export the Geometries into CSV format with a WKT (well known text) field containing the types.  Load the CSV into Spatialite using QGIS's Qspatialite plugin.  Run an SQL SELECT WHERE WKT LIKE  "something%something" to search for the strings that are indicative of the data types you are looking for.
To create a WKT field, export the shapefile (other formats?) by typing
<code> GEOMETRY=AS_WKT </code>
in the OGR Layer option, of QGIS SAVE AS, then Save As CSV and QGIS.
The WKT field should have the data you build your SQL SELECT statement with.
Comment: thanks, I didnt figure it out before.I saved to geoJSON, and then I've got geometry type by default.


Mapview and Fragment

Question: I've seen some topics some months ago, about the fact that using (Google)MapView inside a Fragment was a bit tricky/impossible. I would like to know if atm (June) there is a workaround ? My application (Android 3.0) is essentially working with the Fragment system and I need to display a map in one of these fragments.
Answer: Currently I only know of one solution. I stumbled across this when I ran into the same problem. https://github.com/petedoyle/android-support-v4-googlemaps.
EDIT
Here is a newer fork based off r9 https://github.com/rfc1459/android-support-v4-googlemaps
You can build it via eclipse or download a compiled version here https://github.com/rickbarrette/android-support-v4-googlemaps/downloads
Answer: There is another question already. Basically the workaround is to create an Activity manager and a TabHost and create a single tab containing a MapActivity. In this way you can load a separate MapActivity inside a Fragment.
For more information see the sample project provided by the original answerer.
Answer: Since this question was posted, Google have now very recently (start of December '12) published the V2 Android Maps API. As well as other features, it is designed to work with Fragments and does away with the MapActivity nonsense.
https://developers.google.com/maps/documentation/android/
So it looks like we can now happily use maps in Fragments without the need for hacks.
The only slight disadvantage I've come across so far after initially playing with this new API is that older devices seem to require the user to install Google Play Services first, which may make some users whinge a bit. As they do.

Mapview and Fragment


Stage manager of music?

Question: Is there an equivalent of what in theatre is a stage manager for music? Someone that either stays at a specific venue, or travels with a band, and manages the light, sound, and other effects used in concerts?
Comment: Sometimes yes and sometimes no, it really depends. Madonna may travel with a fixed team of dozens of people. Small bands travel without any "technician/manager".
Comment: I've had the title of "stage manager" but all I did was make sure the backline was working and the band got on and off stage safely and on time. I suspect the band "manager" might be tasked with the big picture lots of the time, or "tour manager". Unlike a theatrical production, it's very rare to have someone on clearcom/telex calling cues for a concert.
Comment: In honesty, live music production is a lot like theatre production, to the extent that a lot of theatres take shows from bands, touring productions take their own technicians, directors, managers, set, lighting, costume department with them. The bigger the budget, the more alike the two are.
Answer: Touring bands with a large budget and an elaborately produced show can have an entire production crew consisting of a production manager and a stage manager and a lighting manager, a video manager a sound manager and many more.  The production manager would coordinate with the lighting manager and sound manager to be sure the "show" goes as planned.  They communicate with a private frequency communication system wearing headsets and can constantly communicate with one another during the show.
High budget touring bands are not just concerned with optimal sound, but have a light show (perhaps even pyrotechnics) and many special effects as a means of creating a unique and exciting audience experience - beyond just the music itself.
Some touring bands may hire an independent sound crew and light crew who travel with the band and set up and tear down the sound system and light system and operate under the direction of a production manager.
Some bands will hire sound and light crews locally at each venue, and leave it up to the tour manager to coordinate hiring those trades in each venue.
A band with a lower budget and less elaborate production might have a production manager of sorts who supervises the stage set up, the sound reinforcement and the lighting and helps the band manage their sets to keep the show on schedule.
Small bar bands might just have one of the musicians who takes the lead and keeps everything on track and the other musicians on the same page.
There is not a regimented standard procedure that applies to all bands.  It varies from act to act and is largely dictated by the budget.
Answer: Even if you are referring to just 'Theater' only, the range is very wide. When I worked in our small town (100 000 inh.) opera house there was a SM in the original sense of the word. Small equipment - for athmos or sound-effect playback on the fly. Light- and Sound-desk all backstage right behind the curtain. But later in the big cities I found impressive rigs. In Vienna where almost everything is aimed at Musicals and real commercial use even the old 'Raimund Theater' or 'Theater an der Wien' where they used to play Moliere and Nestroy are equipped monstrously these days. Light and sound all FOH - like a real Rock-Stage...
So I guess the same range is applicable to all different touring-scenarios... - The bigger the set the more control needed!

Stage manager of music?


Mixed effects models for a classification task on panel data

Question: I have a problem where I need to make predictions for a binary target $y$ given a set of features $X$ where $X$ is naturally nested in the form of repeated measurements. The data is meant to describe the behavior of people in a game where every line of data $X_t$ is timestamped and represent a behavior at time $t$. A toy example of my data can be the following :
ID      session      X1      X2      y
1          1         0.5     a       0
1          2         0.12    b       0
1          3         1.1     d       1
2          1         5.2     c       1
2          2         4.1     a       0

I have treated this as a typical classification problem with each sample $X_t$ being an $iid$ and an XGBoost classifier yields good enough results. However, many articles online state that this form of panel data (where we find repeated measurements per subject) is better handled with mixed effect models. This excellent blog post goes through mixed effect random forests (MERFs) for a regression problem but says that classification models are yet to be implemented (in $2017$ that is).
To this day, i know of no implementation for MERFs for classification problems. So my question is, did anyone come accross a similar classification task and solved it using mixed effect models? If yes is there any code implementation of such a model? (preferably python but I can do with R as well to test it).
Answer: I am actually looking for something similar, however, in my case I am looking for something to deal with multiclass labeled data.
In my search, I came across GPBoost, which may just satisfy your needs.
https://github.com/fabsig/GPBoost
GPBoost should be both available for Python as well as R, and if I'm correct, binary classification is yet included.


What are the advantages of making an exchange dapp on EOS?

Question: Decentralized exchanges are desirable amongst traders. What are the advantages of creating an exchange on top of the EOS blockchain?
Answer: BitShares is a good example of the advantages of decentralised Exchanges, which a similar dApp could be built upon EOS, it's also one of Dan Larimer's Blockchains.
Advantages of decentralised exchanges include
Proof of transactions
On centralised Exchanges like Binance, you rely on them as a private company to honour every transaction you make on their system. Yes you bought EOS at $15.30 but what stops them from changing it to $15.80 or deleting all evidence of that happening?
Availability
Decentralised services typically have higher availability than centralised, especially what is predicted for the EOS Main net. This means better protection against outages or government intervention.
Trust and Solvency
Centralised Exchanges assure us they are solvent but this isn't always the case, in 2013 Mt.Gox was the leading Bitcoin Exchange in the world processing 70% of all Bitcoins worldwide before 850,000 Bitcoins were lost, valued more than $450 million.
Decentralised Exchanges are able to prove their solvency and exactly where each asset is.
Freedom of market pairs
Some centralised Exchanges can charge thousands of dollars just to list a crypto asset. Decentralised Exchanges can offer this for a miniscule amount if not entirely free.
Neutrality
Decentralised Exchanges don't really care about who you are, they are neutral. They don't have to answer to a certain countries government for KYC documents, they don't create barriers to trade.
Fees
We can create decentralised Exchanges that are non profit, the only fee payable for using the service is purely technical costs. E.g. paying for RAM, bandwidth, CPU etc. Less fees mean more money for everyone!
Centralisation on a Decentralised Exchange
With all these benefits, we are more likely to achieve more people trading on fewer exchanges rather than the thousands we have today. This means less arbitrage and more liquidity!
Comment: Nice answer. Maybe another advantage is that there are no additional transaction fees which will drive more people to use it.
Comment: @TeeAttack42 cheers, I knew there was something stupid I missed.


Cropping to a desired size in LightRoom

Question: Seems a simple thing really, but is it unusual that I just can't seem to crop well in Lightroom?  I love it for organising and editing my photos, but I find that if I want to get fine grain cropping for screen or printing then I'm exporting the photo from Lightroom and then opening that up in Photoshop Elements and using the crop tool there as it's easy to set the size and aspect ratio you desire and then drag onto the image.  I'm I just not finding this functionality inside of Lightroom, or does it really not exist and you have to use another application for that?
Answer: Lightroom gives some good cropping tools, IMO. Press "R" or go to the Develop module and click the crop tool below the histogram (though it sounds like you know that part).
To set the aspect ratio, in the Crop & Straighten tool area is an "Aspect" row, and from a drop-down you can select predefined aspect ratios, create a custom aspect ratio, or just freely crop it without restriction.
You can't crop to a size in Lightroom. When exporting you can specify the size of the image. So: crop to the aspect ratio you want (or to the width/height you want), then when exporting just be sure to enter the size you want to export the image at.
Comment: Thanks, yes I did know about the crop functionality but I'd completely missed the bit that allows you to select the ratio to crop to - that's exactly what I was looking for - thanks.
Answer: There actually is a pretty easy way to crop to a specific set of pixel dimensions in Lightroom, or at least to get extremely close to the pixel dimensions that you want - I've been doing it this way for years and it works very well in preparing my photos for printing.
Using Lightroom Classic (or Lightroom 6 or previous versions), set one of your Loupe Info overlays (found in Library > View > View Options) to  include "cropped dimensions". Then in Develop module, click "i" to turn on the loupe info display (click it once or twice as needed to bring up the one that includes the cropped dimensions). Now use the crop tool to set your aspect ratio as you want, and go ahead and crop the image - you'll see the cropped dimensions change as you adjust the size of the crop or its aspect ratio. In other words you're getting a live read-out of the impact of your cropping in terms of pixel dimensions.
Sometimes it's hard to get the exact dimensions I'm after, but I can usually get within 5 or 10 pixels of my target - which is definitely close enough for pretty much anything I might want to do.
I haven't been able to find any way to see the cropped dimensions in Lightroom Mobile (cloud version) - if anyone does know a way I'd love to hear about it.

Cropping to a desired size in LightRoom


"A Better Us" or "A better We"?

Question: At the gym I use, I pass a promotional poster that shows a group of people on life cycles. The caption reads "A Better Us."  Every time I see it, I wonder, "Is this Ok?"  "us" is the object form of "we."  Is there an implied missing part that Makes "us" ok?
Answer: Provide the appropriate transitive verb of your choice with the phrase as its object:

Build a better us Behold a better usExercise makes a better us

But bear in mind that even as the complement of a copulative verb, we prefer the objective case when strict application of grammar rules requires the nominative.  Must people would say

This is a better us

and not "a better we," just as they would say when the gang comes back

It's us.

instead of "It's we.
Comment: Ok, so it's a matter of preference that is generally acceptedk.  In your first example, it's an imperative, as in "You / We" build a better us?
Comment: @michael_timofeev Yeah, as if the sweat-stained participants we're begging the trainers, "Build a better us."

"A Better Us" or "A better We"?


Several PHP packages in Ubuntu, how to only use the latest version?

Question: I suspect that my Ubuntu server contains abandon PHP files or packages which is not used. How can I do a clean install of latest PHP 5.6 in my server?
I ran this on my ubuntu server 'dpkg --get-selections | grep -v deinstall' and got this below.
php-common                                      install
php5                                            install
php5-cli                                        install
php5-common                                     install
php5-curl                                       install
php5-fpm                                        install
php5-gd                                         install
php5-intl                                       install
php5-json                                       install
php5-mcrypt                                     install
php5-mysqlnd                                    install
php5-readline                                   install
php5-tidy                                       install
php5-xmlrpc                                     install
php5-xsl                                        install
php5.6                                          install
php5.6-cli                                      install
php5.6-common                                   install
php5.6-fpm                                      install
php5.6-json                                     install
php5.6-mbstring                                 install
php5.6-mcrypt                                   install
php5.6-mysql                                    install
php5.6-opcache                                  install
php5.6-readline                                 install

It seem like there are several duplicated PHP files there.
Furthermore, on my phpmyadmin, I saw that I'm using an older PHP 5.6 version
"PHP version: 5.6.23-1+deprecated+dontuse+deb.sury.org~trusty+1"
However, when I run php -v, it shows this below:
PHP 5.6.24-1+deb.sury.org~trusty+1 (cli)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
    with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies

This seems like my server is using different PHP version on different environment.
How can I remove the unwanted PHP files and use only the latest version of PHP 5.6? I'm not able to experiment it myself because it's a production server, I can't afford to make it down for more than 10-20 minutes.
Answer: The short answer is:
apt-get purge php5-common


What is the difference between Tuple and keyvaluepair

Question: I am not understanding the difference between tuple and keyvaluepair. i was looking into this article  http://www.dotnetperls.com/tuple-keyvaluepair. it seems like tuple is better than keyvaluepair but some of the developers saying strictly do not use tuple i wonder why?
Comment: KeyValuePair was introduced in .Net 2 and contains two elements. Tuples are a family of types with varying number of elements and were introduced in .Net 4. Tuples support structural equality and comparison unlike KeyValuePairs. Another difference is that KeyValuePair is a struct, while Tuple types are all classes.
Comment: The question is: why not just make a class instead of a tuple?
Answer: The KeyValuePair<> is a struct that represents a key and a value. When you enumerate a dictionary, the items are of the type KeyValuePair<> with the same generic types as the dictionary.
The Tuple<> classes are intended to represent multiple values, but there is no specific roles for the values like key or value. There are diffent Tuple<> classes for different number of values, from 1 up to 8 values.
The Tuple<> classes have names for the items like Item1, Item2, Item3 and so on. As those names doesn't tell you anything about what the items represent, you should preferably only use tuples where the meaning is obvious, for example quarters in a year.
Answer: There are quite a few people that call themselves developers that should not. Having said that. The link that you posted goes into some detail about the differences and when you should use them. In the end it depends on the application that you're building.
Quoted from the site you linked...

I recommend avoiding KeyValuePair entirely and using Tuple or custom classes (which would be similar to Tuple in performance).

and

Tuple was faster in every test than KeyValuePair except in allocation performance. Therefore, if your program does any work beyond allocating the collections, it is a better idea to use Tuple instead of KeyValuePair.

Illustrate the point I'm trying to make.
For the big toolset that developers can use, when people tell me to never use something that's usually when I stop caring about their opinion. Nobody should tell you what to use without getting the context of the type of use it's going to get.
Answer: I think those programmers are saying not to use Tuples because on a public API, they are less effective.
Lets say you have a tuple like
Tuple<int,string,string,int>

then how will you identify that what are these values later or what they are representing. I think thats why programmers say that. Like in this case the consumer has to either guess or look up documentation to know what you mean.
The MSDN says:
A tuple is a data structure that has a specific number and sequence of elements.

Tuples are commonly used in four ways:

To represent a single set of data. For example, a tuple can represent    a database record, and its components can represent
individual fields of the record.
To provide easy access to, and manipulation of, a data set.
To return multiple values from a method without using out parameters (in C#) or ByRef parameters (in Visual Basic).
To pass multiple values to a method through a single parameter. For    example, the Thread.Start(Object) method has a single parameter that lets you supply one value to the method that the thread executes at startup time. If you supply a Tuple object as the method argument, you can supply the thread's startup routine with three items of data.
Answer: They say don't use Tuple because Tuple has properties that don't have meaningful names: Item1, Item2, etc. Under some circumstances it's perfectly ok to use them. It is certainly less work to use a Tuple than to create your own every time.
One significant difference is that KeyValuePair is a struct and Tuples are classes. KeyValuePair has no relation to Tuples, really. It existed before Tuples to store keys and values in Dictionaries.
You could argue about whether Tuples should have been implemented as value types instead. The ones you use most are the ones with few Type parameters and they would be better as value types. (You easily implement them yourself) Look here to see why they made certain decisions: http://msdn.microsoft.com/en-us/magazine/dd942829.aspx#id0400060


What information can we know by LIGO's detection of gravitational waves?

Question: LIGO's detection of gravitational waves can help estimate Hubble's constant in a new way. Another paper might be informative. Apart from that what information can we get from the observed gravitational wave?
Answer: The paper you list as another paper is the primary paper. You cant measure H, unless there is an optical observation of the event. GW tells the luminosity distance, optical counterpart tells its redshift. Use the two, get your H.
Second part of your question is too general. LIGO has tried to cover a bredth of topic since the first detections and information is listed here,
https://www.ligo.caltech.edu/page/detection-companion-papers
If you want a superficial answer before you jump into the papers for a few weeks. Here it is
1) One can test if observatons withold general theory of relativity of violate it. There are many ways to do this but LIGO has tried to follow a model independent approach
2) One can estimate the parameters of the observations and estimate the mass and spin distribution of the sources along with their rate of mergers.
3) One can talk about things like extreme-gravity after looking at signals produced by BNS>
GW astronomy is just beginning and I am sure a lot can be done.


Do mechanical stresses propagate in time as EM waves do?

Question: If someone may, I expect a mathematical comparison of the governing equations "Maxwell Equations" for wave propagation and "Conservation of momenta & equilibrium equations" for stress and deformation. I am confused if a stress wave exists? If yes, how similar it is to EM waves?
Comment: I think the typical equations are https://physics.stackexchange.com/questions/525659/what-are-the-partial-differential-equations-for-solid-stress-analysis but i dont know about stress waves
Answer: I am reaching way back in my memory, but I recall that in seismology there are at least two distinct types of mechanical wave propagation. Both are wave phenomena (and are thus modeled as solutions of wave equations), but one is more similar to electromagnetic waves than the other is.

Shear waves or S-waves are transverse waves, in that the displacement occurs perpendicular to the direction of propagation, as in electromagnetic waves.

EDIT February 2021: But there is a crucial difference between S-waves and electromagnetic waves: electromagnetic waves involve two distinct fields (yes, I know that E and B fields are part of a unified field, but the propagation really depends on their interaction). Further, S-waves require a physical medium to carry them. Electromagnetic waves require no aether.
P-waves, on the other hand, are pressure waves, and the compression and dilation occur along the direction of propagation.
Answer: The displacements field equations can be derived for a cubic small element $\Delta x \Delta y \Delta z$ of a body, by taking the components of the net force on it:
$$F_{x+\Delta x} - F_x = ma_x$$
$$F_{y+\Delta y} - F_y = ma_y$$
$$F_{z+\Delta z} - F_z = ma_z$$
$$(\sigma_{xx(x + \Delta x)} - \sigma_{xx(x)})\Delta y \Delta z + (\sigma_{yx(y + \Delta y)} - \sigma_{yx(y)})\Delta x \Delta y + (\sigma_{zx(z + \Delta z)} - \sigma_{zx(z)})\Delta x \Delta z = ma_x$$
Dividing by $\Delta x \Delta y \Delta z$ and taking the limit when deltas go to zero:
$$\frac{\partial \sigma_{xx}}{\partial x} + \frac{\partial \sigma_{yx}}{\partial y}  + \frac{\partial \sigma_{zx}}{\partial z} = \rho a_x = \rho \frac{\partial^2 u_x}{\partial t^2}$$ where $\rho$ is the density and $u_x(x,y,z)$ is the displacement at the point to the $x$ direction. The same  for the $y$ and $z$.
For the element doesn't rotate, $\sigma_{ij} = \sigma_{ji}$. Considering the material linear elastic, there are linear relations between stresses and deformations:
$$\sigma_{ij} = E_{ijkl}\epsilon_{kl}$$
where E is the elasticity matrix.
As $$\epsilon_{kl} = \frac{1}{2}\left(\frac {\partial u_k}{\partial x_l} + \frac {\partial u_l}{\partial x_k}\right)$$
We end up with three differential equations of second order, to find the 3 components of the displacement field $u(x,y,z)$. In the left side there are second derivatives with respect to x, y and z. At the right side second derivatives with respect to time. There is some similarty with the wave equation for EM, but more parameters and variables. The solutions depends on boundary conditions.


Capacitor Testing

Question: I have some old ceramic capacitors and I wanted to test it to see whether it meets the specification in the datasheet or not. I know how to test the capacitance of it but I do not know how to test the voltage and compare it with the datasheet. Datasheet shows 50V for the rated voltage and the capacitance is 22 uF.
Comment: Voltage rating testing is usually destructive.
Comment: I believe a test of ESR is a better indication of the ageing of an old capacitor.
Comment: What do you suggest to see if there is any aging on them without destroying it ?
Answer: The voltage rating is generally a parameter for the maximum voltage which the component can withstand. This maximum voltage could be

the absolute maximum
the the typical maximum, or what the component manufacturers' tests found over repeated tests
a conservative figure well below a threshold expressed in the previous
By testing for the voltage in a given component, you stand to destroy the component when testing. This is certainly not recommended, especially if you have a limited number of components.
If you need to test the components, maybe consider placing the components in an area of the circuit well below the specified threshold and test the component instead for the typical and maximum operating values.

Capacitor Testing


Can netbeans auto-generate correct hashCode() and equals() methods for a mapping?

Question: I am creating a many-to-many mapping of two object classes. Do I need to write hashCode() and equals() methods; if so, does the netbeans automatically generated code help?
Comment: you will need `equals` and `hashCode` only when you're performing comparing two objects.
Comment: "Does it need hashcode and equals method" If you mean "do *I* have to implement them", well, it depends on what you're trying to do; see [Why do I need to override the equals and hashCode methods in Java?](http://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java).
Comment: Since you're using `ManyToMany` mapping, you're one of the parameter will be `Collection` of objects, so technically you will need equals and hashcode method. And hence you will need to decide the implementation of `equals` method and perhaps you can use generated `hashCode` method.
Comment: Re-worded for grammar.  This question could still do with some sample code to help illustrate what you're doing (for example, in which class you implement the methods).
Answer: Yes it can!
Simply right click within the class where the objects have been created and choose insert code. A small menu titled "Generate" will pop up with various options, among them is equals() and hashCode(), select it and presto, NetBeans generates the code override for you. Test out the equals method and it will work this time.
NB. When you select "equals() and hashCode()" a Dialogue box appears, just check the boxes on both sides for all the variables you want dealt with. See the image below:
Answer: Yes, you can use the IDE generated hashcode for comparing two instances. It will suffice your case what matters more is the equals method, pay attention to the parameters that are compared for equality. The auto generated code will compare all the parameters but you may need only few parameters for identifying it uniquely.
Let's say if you need to see if the record read from DB is of the same entity just compare the primary key in equals method. Choosing an equality criteria is totally you discretion.
Answer: In NetBeans 8.2, the name of the right click menu option is "Insert Code", after you right click on the class or hit Alt-Insert choose "equals and hashCode..."


What may be the causes of the error 0x80010108 (The object invoked has disconnected from its clients)?

Question: In C++ program the call to method of coclass returns the error 0x80010108 (The object invoked has disconnected from its clients). What may be the causes of that?
Answer: It is an RPC error, you'll see it when you use out-of-process COM.  It tells you that the server .exe stopped running.  It probably bombed.  Or decided to exit even though there were still active interface references.  That could be a reference count problem.  Or improper use of CAtlModule::Lock().  Etcetera, I can only guess.  Debug the server with Tools + Attach to Process and find out why it decided to quit.
Answer: This error is raised from a COM generated proxy object, so your server object (the one being called) is living in another apartment, ether out-of-proc or on another thread in the current process. Something very bad has happened to this apartment so it was terminated and now the COM stub living there cannot be reached by the proxy (via RPC or message pump).


Measuring position and momentum at the same time?

Question: In a non-relativistic quantum mechanical system in an infinite potential well. I try to measure the energy and the position of the system simultaneously. Since, the respective operators do commute according to Heisenberg's uncertainty relation I should be able to measure them both with infinite precision. Now, since I know that there is no potential energy in the well I can use $ E=\frac{p^2}{2m} $ since the potential energy is 0 and determine it's momentum provided I know it's mass. But I shouldn't be able know the momentum and position simultaneously with infinite precision! So where am I going wrong?
Comment: What do you mean "There is no energy in the well"?! That the well has it's base at an arbitrary $V_0$ does not mean that the particle in it has to have that $V_0$ as its energy!
Comment: By no energy in the well I mean the potential energy is V=0 ... Yes the particle can have kinetic energy T and T=V.
Comment: The notion of "measure A and B simutaneously" where A and B do not commute, is ill defined.
Comment: As clarified in the comments to an answer, the question is based from the wrong understanding that the Energy operator is $E=i\frac{\partial}{\partial t}$, which is not even an operator on the Hilbert space of the particle.
Answer: If you are considering a system of a single particle in a potential well with infinitely high walls and with finite width, the energy operator is
$ H = \frac{p^2}{2m} + V(x) $
where $ V(x) $ is the potential energy operator, vanishing inside the well and infinite outside it. Being that $ \frac{p^2}{2m} $ does not commute with $ x $, how are you saying that the energy and position operators commute?
Besides, if that were true than we could place a particle in any point inside the well and the particle would stay there forever.
Comment: That's not the energy operator, it's not even an operator on the Hilbert space.
Comment: $ E = i \hbar \frac{d}{dt} $ and $ p = -i \hbar \frac{d}{dx} $
where these are partial derivatives hence they do commute
Comment: Nevermind I understood where I was going wrong u were right ... Thanks
Answer:
I try to measure the energy and the position of the system
  simultaneously

The states with definite energy are not states with definite position so there is no particle state of both definite energy and definite position.
Answer: At the first look the question seemed very interesting, but later I found the mistake. You said you are measuring the position of the particle precisely. But how? You can tell that the particle is inside the well but you can not know the exact position of the particle. For more info read http://physicspages.com/2012/07/10/infinite-square-well-uncertainty-principle/


How do I skip minibuffer completion in `completing-read`?

Question: In a function X that calls completing-read, I'd like to be able to call X and pass in a constant input without invoking the minibuffer. From the emacs manual, it seems I'm supposed to flet completing-read-function, but I'm not sure the correct way to do this.
Answer: Assuming that you want the constant input to be optional, you can declare the function as taking an optional argument and then check if the argument is actually passed: if it is, go ahead and use it; if it isn't, then call completing-read.
Something like this:
(defun X (&optional foo)
  (message (or foo (completing-read "Enter foo value: " nil)))

where I assume that the value of foo is a string.
If you call it with M-: (X), then foo will be nil and you will get the prompt. If you call it with M-: (X "bar") then no prompt will be issued and the value of foo will be the string bar.
Comment: (Nit:) `(when (null foo))` = `(unless foo)`.
Comment: Hi @NickD, the function X in question is `counsel-org-goto`, which isn't my function. I'd like to refrain from changing it, and instead, when it calls `completing-read`, have a user-supplied constant value automatically fed in.
Comment: You should have specified that in your question. I do not have time to check (and I know nothing about counsel), so I'm afraid I can't help. Maybe somebody else will provide an answer.


Is it possible to add new vocabulary to BERT's tokenizer when fine-tuning?

Question: I want to fine-tune BERT by training it on a domain dataset of my own. The domain is specific and includes many terms that probably weren't included in the original dataset BERT was trained on. I know I have to use BERT's tokenizer as the model was originally trained on its embeddings.
To my understanding words unknown to the tokenizer will be masked with [UNKNOWN]. What if some of these words are common in my dataset? Does it make sense to add new IDs for them? is it possible without interferring with the network's parameters and the existing embeddings? If so, how is it done?
Comment: Please, consider marking one of the answers as correct (with the tick mark) or, alternatively, let us know what clarifications are needed.
Answer:
To my understanding words unknown to the tokenizer will be masked with [UNKNOWN].

Your understanding is not correct.
BERT's vocabulary is defined not at word level, but at subword level. This means that words may be represented as multiple subwords. The way subword vocabularies work mostly avoids having out-of-vocabulary words, because words can be divided up to the character level, and characters from the training data are assured to be present in the subword vocabulary. Therefore, as long as the alphabet used in your fine-tuning data is the same as the training data, there should be no out-of-vocabulary words: your out-of-domain terms will simply be divided into smaller subwords. So you should not need to include new entries for them in the embedding table.
There are some answers in this site that may give you more examples, like this and this.


What is a charge, apart from fundamental property?

Question: What really a charge is apart from saying its a fundamental quantity. I mean IF in case of gravity, its curvature of spacetime due to mass so just like that can anyone explain how charge like properties come in place
Comment: If you're asking whether we can interpret the EM forces in a geometrical was, as we can for gravity, then see [Can all fundamental forces be fictitious forces?](https://physics.stackexchange.com/questions/148028/can-all-fundamental-forces-be-fictitious-forces).
Comment: As far as I know, we don't really know what charge is besides an intrinsic property of objects. We mostly just talk about charged bodies. You can compare it to mass. We never exactly talk about what mass is. We just discuss properties related to it.
Comment: ok, if what you are saying is true then, there is a lot more to discover about these properties.
Comment: Related: https://physics.stackexchange.com/q/21753/109928
Answer:
in case of gravity, its curvature of spacetime due to mass

technically to the stress-energy tensor so energy density, energy flux, pressure, shear stress, momentum density, and momentum flux. But yes, for a stationary object with no internal stored / binding energy, it's just the mass. And we could also ask -- what is mass exactly? Elementary particles with same sizes have vastly different masses, so, like charge, it must be something "instrinsic" (... or at least its coupling to the Higgs field).
A charge (not electrical) is the generator of continuous symmetry. As per Noether's theorem, a continuous symmetry implies the existence of a conserved current (not necessarily electrical).
In the specific case of electrical charge, it is the generator of the U(1) symmetry associated with electromagnetism (QED). The conserved current is electrical current.
Comment: "Color charge" is not the Noether charge corresponding to SU(3) (no such charge exists for there is no continuous global symmetry associated with the string force) - see e.g. https://physics.stackexchange.com/q/430935 (and same spiel for SU(2))
Comment: @NiharKarve You are right, removed the strong force bit.
Comment: 'the generator of continuous symmetry' This is a mathematical definition. I think the OP asks for a physical one.


Initiate email to admin/Group when user account is created in Marketing cloud

Question: I would like to know if there is way in Marketing cloud through code/clicks to send an email to a specific user(s)[Admins] when user is created in Marketing cloud .
Answer: As far as I know, there is no UI way of doing it. It might be a quite complex implementation, that is why there will not be everything prepared for you but here is the idea of what you can do:

Create an Automation, which would run every day/hour (depends on how frequent you want to check for new users);

Add Script activity that would perform SOAP API call via SSJS. You can check this example;
2.1 API call would do a Retrieve method on AccountUser object with some filters on CreatedDate property. You would probably need to set a variable date rather than a hardcoded one. Example of SOAP API call and filtering;
2.2 In the response body, you would receive all users that have been created based on your filtering date. Parse the response body to get all the needed info about newly created users;
2.3 This step could be done differently, for example, you can put parsed info into Data Extension with Overwrite data action;

And add Email activity to the automation, which would have AMPscript to lookup into the Data Extension and pull all the data and finally send it to your admins.

Not saying this is the perfect suggestion, there is definitely room for improvement, since you can actually do everything within one Script activity but that is going to be up to you.
Hopefully, it helps.
Comment: Thanks Niko for the idea .. will try and let you know how it went through
Comment: Hi @Niko , I used wsproxy to call SOAP API functionality and the response is JSON and easy to parse  .
Comment: Hello @Sancool, yep it is also a solid way to go. Glad it worked out for you!


Question on the integer size

Question: Is there any kind of boolean division with bitcoin?  There has to be something before the decimal number.  Kind of say it seems like end to end and it always should be the number that is largest.
Comment: What do you mean by boolean division?
Answer:
Question on the integer size

Bitcoin uses many sizes of integer from 8-bit integers up to at least 256-bit integers. It also has variable-size integers. It uses a mix of signed and unsigned integers.

Is there any kind of boolean division with bitcoin?

There is no kind of division at all in Bitcoin scripting language since OP_DIV and OP_2DIV were disabled.
I imagine fairly normal division is involved in calculating network difficulty and in calculating network time for checking block timestamps.

There has to be something before the decimal number.

The Bitcoin network probably doesn't have significant use for decimal numbers.
Units of money are integer Satoshi. There are 100,000,000 Satoshi per Bitcoin. The user interface of software sometimes converts money in integer Satoshis to some decimal unit such as Bitcoin or millibitcoin for user-interface purposes only. Internally it is all integers.
Hashes and signatures are mainly working with large integers so far as I know.
The compressed "bits" representation of network difficulty bears some superficial resemblance to floating point number representation but nothing else decimal-like occurs to me.

Question on the integer size


Can parameters other than $n$ be always ignored in big $O$ notation?

Question: The Bentley–Ottmann algorithm, for example, has time complexity of $O((n + k) \log n)$. Is the statement $O((n + k) \log n) = O(n \log n)$ true? I know that $k$ is there because it has big enough of an impact on the overall time complexity that it's relevant to include it. But can it be ignored, so that the previously stated equivalence holds, and hence we can without any reservations say that the algorithm has time complexity of $O(n \log n)$?
Answer: In general you cannot erase things. A bivariate function $f$ is $O((n+k)\log n)$ if there exists a constant $C>0$ such that for all legal settings of the parameters $n,k$, we have $f(n,k) \leq C(n+k)\log n$. Here a setting of parameters is legal if it can actually happen – for example, if $V,E$ are the number of vertices and edges in a simple graph, then we always have $E \leq V(V-1)/2$, any other setting being illegal. If in some context you know that $k \leq Bn$, then in that context (which restricts the set of legal settings of parameters) $f = O(n\log n)$. In any other context, you cannot drop the $k$.
In your particular case, the Bentley–Ottmann algorithm, it is generally not the case that $k = O(n)$, and so $k$ cannot be dropped.
Comment: Unless in your case you are guaranteed that $k = O(n)$.
Comment: Just to be clear: if I'm looking for a $O(n \log n)$ algorithm, Bentley–Ottmann (as is, without domain specific modifications) would definitely fall out of the question?
Comment: Could you answer this related question? https://cs.stackexchange.com/questions/77458/from-order-1-to-order-2-voronoi-diagram


How can I switch users from within XFCE?

Question: I am using xubuntu 11.10. I'd like to be able to switch users, and I'd like to be able to do this within the xfce user interface. I read somewhere that there might be an applet I can install, but I cannot seem to find it. Can someone help?
Answer:
In a terminal:
sudo apt-get install xfswitch-plugin

During installation it will ask you to switch window manager - do not choose GDM, but stick with lightdm. N.B. since its a text screen press TAB to navigate to "OK" and press ENTER
Right-click and add a new panel item - User Switching
Comment: CAREFUL WITH THAT AXE, EUGENE! This will bring in the entire heavyweight Gnome... That's a bad choice if you run XFCE.
Comment: Great! Now if only there was a way to add that to the Logout/Suspend/Hibernate menu instead of having it a separate entry...
Answer: If you don't want to bring in the whole of gdm and dependencies, you can just create a launcher that achieves the same thing. Put this
#!/bin/sh
zenity --question --text "Switch user?" --title "New login" &&
gdmflexiserver --new

into a file called fast-user-switch, then do
chmod +x fast-user-switch
sudo mv fast-user-switch /usr/local/bin/

Then add a Launcher plugin to your panel, edit the menu and click the button with a white paper with a plus on it, there you can just type in fast-user-switch (it should auto-complete while you type if you did the past steps correctly), and select a nice icon (search for switch for a fitting one …)
Note: The next version of XFCE, 4.10, will include a Switch User button in the Actions plugin, and deprecate the session menu.
Note to the note: if you have kdm instead of gdm/lightdm (kdm+xfce may be an odd combination, but it happens), the 4.10 Switch User button doesn't work. However, the following bash script works, and additionally lets you either log in as a currently logged in user, or start a new login:
#!/bin/bash

set -f              # no globbing, so we can safely use *

# other_local[joe]=:0, other_local[bob]=:1 etc. for all active local
# users other than us:
unset other_local; declare -A other_local;
while read -rd $'\t'; do
    IFS=$',\n' r=($REPLY)
    [[ "${#r[@]}" -ge 4 && "${r[4]}" != '*' && "${r[2]}" != '' && "${r[0]}" != '' ]] && other_local[${r[2]}]=${r[0]}
done < <(kdmctl list alllocal)
IFS=$',\n' r=($REPLY)
[[ "${#r[@]}" -ge 4 && "${r[4]}" != '*' && "${r[2]}" != '' && "${r[0]}" != '' ]] && other_local[${r[2]}]=${r[0]}

user_choice=$( printf "%s\n" "${!other_local[@]}" "New login" |\
    zenity --list --column User --text 'Switch to an active user, or start a new login:' --title 'Switch user?' ) || exit 1

case $user_choice in
    "New login" ) kdmctl reserve ;;
    * ) kdmctl activate "${other_local[$user_choice]}" ;;
esac

Comment: Very nice! No need to install gdm this way...
Comment: Awesome. The 2-line script worked like a charm on default installation of Ubuntu 12.04 LTS.
Answer: You can click your user name in the top panel and then select "Lock Screen." From the locked screen select "New Login" and it will take you back to the LightDM screen where you can click a different user name and enter the password. The first user is still logged in and you can switch back and forth this way.
Comment: Switching back to my own session does require typing my password twice, though... (LightDM requires a password to get into my session, and xscreensaver does too).
Answer: Lock screen, and when prompted to login, click "New login".
(Works on 12.04, but it probably works on 11.10 too)
Answer: gdmflexiserver did not work for me coz it was not there on my system.
I used dm-tool instead:
https://bugs.launchpad.net/ubuntu/+source/xfswitch-plugin/+bug/1320560
Answer: Invoking dm-tool, with either the 'lock', or 'switch-to-greeter' option, will leave an xfce4 session vulnerable to a login without a password, as per the following bug report: https://bugs.launchpad.net/lightdm/+bug/904006.
Rather than chase the bug, the devs seem to be directing people to use light-locker, which is simple to use, and set up with secure defaults.
The following fix ensures that the 'switch user' option in the xfce4 panel invokes light-locker. There is no need to create a launcher plugin, or install additional gnomeware.
(1) Install light-locker (in my case from the Debian 8/Jessie stable repository).
(2) Replace /usr/local/bin/gdmflexiserver with:
#!/bin/bash
light-locker-command -l
# [End]

(3) reboot (full shutdown and restart, needed once only, to get the panel to activate the 'switch user' option - you may have smarter ways to get this done).
Each time I hit the 'switch user' menu option, there is a slight pause on a black screen before the login appears, which is not there when I use dm-tool, but it's good to know my session is fully locked.
Thanks to pomidorabelisima at https://bugs.launchpad.net/ubuntu/+source/xfswitch-plugin/+bug/1320560 (duplicate bug report) for the heads-up.