How to reinforce a joist with plumbing running through it?

Question: After removing the sub floor in my bathroom in order to extend the sewer pipe for the toilet (it's too close to the tank-side wall), I found that the floor joists have extremely large holes cut in them to make way for the plumbing.
What are my options for reinforcing them?  I don't think I could do a sister joist both because of the plumbing running through the joist and because the joist runs quite a ways through the floor of my second story, and adding a sister joist would involve taking up a ton of the floor.
Should I brace it with steel bridging?  I'm concerned about the potential vertical load.
What options do I have?
The room is approx 74" by 105" (the 105" runs in the same direction as the joists, it appears that the joists are at least that long, but may extend beneath other rooms)
Joists are 15/8 inches wide, 71/2 inches tall.
There is a 1st floor bathroom below.  There is a tub in the 1st floor bathroom bordered by 3 walls - one of these walls runs perpendicular to the joists 4 feet away from the wall shown on the right in the first picture below.

You can see in this close-up that the furthest joist is completely missing it's bottom:
Comment: @MichaelKaras you may want to move the VtC reason back here...
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/120702/discussion-on-question-by-jordan-how-to-reinforce-a-joist-with-plumbing-running).
Answer: I had an electrician notch the top 5" of a 2x10 (9" old growth Douglas fir) in the middle of an 18' span.
I brought in a structural engineer and he said the 18' 2x10 was already over current span code limits without the 5" notch.  He specified 3/4" continuous ply gussets nailed to each side of the joist extending 18" past each side of the notch.  He allowed the gussets to only be the 4" height and fit under the notch.
In your case, you are not in the middle span, I assume this is the start of the joist?
The toilet rough in appears to have completely cut through the joist so there is no connection and it has been blocked to the side joist with a single 2x4 and a single nail.
You likely want to get a structural engineer to specify a prescriptive fix for this.  A site visit and prescription is likely to cost less than $1,000 and be well worth it.
You might be able to sister with steel that is shallow and could sit above and below the plumbing penetrations and not need to be sistered the full length of the joist.
Comment: I don't think that getting an SE on site is a "likely want". I'd suggest that it's somewhere between "highly recommended" and "critical".
Comment: This is the start of the joist, yes
Answer: I would sister 2 pieces 3/4" marine grade Plywood Braces (since it's under a toilet) on one side of the damaged joist as shown below. Use Epoxy or Urthane glue and SS deck screws to tie them to the Damaged Joist. After both Sister Braces are set and in place, add a plug (not shown) in the gap of the Brace A's (purple) opening since it'll be under compression.
Then trace the joist's opening and make a rough cut plug. Glue this in and fill in the gaps between the plug and the joist with a "filler type" resin.
Finally add 2 more Sister Braces (not shown) like on the first side.
Comment: nice drawing - how did you make it?
Comment: This answer is missing the critical specification of **how long** to extend the sisters on the main joist.  Did you calculate anything to come up with this solution?  Or is this a guess?  I think either you suggest using a listed product to repair this OR you provide the engineering calculations to prove that it's a valid solution that meets the original strength specification of the joist.  DIY structural engineering is what got OP into this situation to begin with.
Comment: This would be good if it were just 1 or 2 joists, but it sounds like this goes on for quite some distance, that's a lot of floor removal, plugging, and sistering.  Might be necessary though - but not a task I'd want to take on myself.  Time to call in some pros?
Comment: @DarrelHoffman The damage only spans the portion shown.  I looked under the subfloor and the rest of the joist appears to be intact.
Comment: While this does appear to be a "good idea", I agree with @J... that without the math and SE's stamp, this is just a "good idea". Sadly, "logical" only goes so far with inspectors, permit issues and insurance companies.
Comment: @j4nd3r53n It looks like Fusion or SolidWorks or a similar CAD program. I know I could certainly create something identical in SolidWorks.
Comment: I would make the purple and blue braces in two strips each , one  with a notch and the other continuous. this way they will both better able to resist bending. (brace A continous strip at the top, wider braces with a notch below,  brace B like that but the other way up)
Comment: All you want to be Engineers with your Calc questions are so naive. So in order to do the "calc" on this assembly you first need to have the raw numbers, like the the existing strength of the damaged joist. Then what about its moisture content, etc.?  Now be sure to use the Plywood's Manufacturer's certified Stress calculations to be sure of the length. In my 40 tears as a Design Engineer, there's always the ones in the crowd who think they know everything and shout out criticisms to prove their the smartest in the room... The OP was interested in ideas, not certified Engineer Drawings...
Comment: I used Solid Edge
Comment: @FreeMan Yep.  Even if we had calcs, it doesn't matter - no stamp, no insurance.  It's pretty cut and dry.
Comment: What J says, absolutely. Calcs, or blatant overprovision, or its meaningless
Comment: Better to make pieces A and B half the height, and install one above the other.
Answer: Also not an engineer but building my own home.
I would suggest one of four solutions, in no special order, but please check with a structural engineer if you have any doubts.
I would draw attention to the issue that the entire joist system is at risk. Just like parallel joists can reinforce each other, if all are weak, that shared strength may not be dependable. So I'd take it seriously as you are doing.
1) Sister using steel C channel:
Sistering the joist with some C shaped steel channel with an appropriate round (not rectangular! see below) hole cut through it. You'll have to break and re-make the plastic pipe to do this, but that's relativrly easy - PVC cement.
The idea is that C channel will lie with its back (the web) flat to the joist, so it can be very well secured to it, and torque (twisting) won't be a point of weakness.
The C channel wouldn't have to be very thick. It needs a stiffness more than or equal to the joist's original strength for safety and wood is very limited stiffness compared even to thin structural steel.
Theory:
In steel constriction, be it "I" beams (RSJ),  C shaped channel, or rectangular tube (RHS), the strength is provided by the flanges (the top and bottom parralel surfaces) not so much by the web (the connecting part between them).
The idea is that as the beam takes on its load, it flexes, and the flexing means that the 2 parallel surfaces have to stretch at different rates. The thicker the top and bottom flanges, and further apart they are, the stiffer the beam.
Steel takes a lot of force to stretch, so it resists the load well. But this also means that provided the hole is of a size that the channel keeps its shape (which this looks like it will do) the web is very much secondary - which is why I suspect a hole even of this size won't matter to it,provided the steel is firmly fixed to the joist along its length and top and bottom.
In fact, the web's main job isn't to resist load.  It's to keep the 2 parallel surfaces aligned and separated in their original position so they would have to stretch under load (thus resist it), and can't just move closer or twist instead.
Note as Jasen says in comments that its important to cut rounded not crude/rectangular holes, to minimise stress and weakness in the steel, which naturally arise much more at cut and sharp corners.
2) Reinforce above/below using steel angle:
You could also place steel angle along the length of the joist above and below the pipe. If that's attached really firmly to the joist so it can't pull through the wood, in theory that would work.
I honestly would have real reservations about this, because whatever you use to secure the angle to the joist, wouldn't have to pull much through the wood at all, over time, to allow the joist to sag. It doesn't have the needed overall stiffness, because the top and bottom aren't held in a fixed position against each other, unlike C channel that innately resists flexing even with a hole in the web.
This would be the simplest, but also my absolute least favourite of the 4 because of that concern.
3) Remaking the joist system to avoid the issue:
You've exposed the joists and clearly are somewhat comfortable with heavy DIY. Alljoists will need fixing anyway. So this might be one other solution, depending on the masonry and other structure of the property.
The joists in that room run "left to right" in the picture. If the property allows and has suitable load bearing walls, one could prop them all either side of the pipe/s (use timber under them so they stay aligned), cut them either side of the pipe, and put doubled or very heavy duty joists running "front to back" parallel to the pipe. Then attach the cut ends of the old joists to your new ones using ordinary joist hangers.  Essentially youd be stopping all of the the joists at one side of the pipe and starting them again 200 mm/8 inches further,on the other side of the pipe.
This would work very well, provided there is structurally sufficient bearing for the extra joists at the front and back. While that would not be in the design of the property, the load would spread down through those walls at 45 or 60 degrees, along the ground, so support may not be a huge issue.  You might need to ensure good bearing at the top.course of brickwork (engineering bricks below the new joists?) and you'd definitely need to check with an engineer for this. But if they agree, its definitely cheaper to do than steel and any builder could.do it.
4) Move the darn pipe:
Vertically in a box conduit in a corner, outside, wherever. Just reroute the pipes and then replace or sister the damaged joists.
Cheapest and probably simplest of all the 3 I'm sure would work.
Comment: The first option sounds good, but I would add that making round holes in the steel instead of rectangular or irregular shapes is important as stress is concentrated at internal corners.
Comment: @supercat Might have something to do with the fact that working with structural steel is a daunting task for the average DIYer. Ever tried cutting a typical I-beam with what you have at home (like a hobby-grade angle grinder)?
Comment: I wonder why on home-improvement channels I almost never see steel reinforcement used to allow pipes to run through joists as opposed to having to go above or below them, even in cases where the former pipe routing would be much preferable [e.g. avoid requiring bulge in the ceiling below].
Comment: @TooTea: Working with structural steel is a task for professionals, but that doesn't mean that it can't form a useful part of a DIY project.  Hiring professionals to fabricate and install part of a project may not be cheap, but it may allow the rest of the project to be accomplished more efficiently.  What's funny is that I think I've seen steel used more by amateur DIY homeowners who hired professionals to fabricate and install it, than by professionals like Mike Holmes, who would presumably have better connections.  Perhaps the pros would demand too large a sponsorship deal...
Comment: ...in order to show how economically a complicated situation could be solved with the aid of an Acme Steel Fabricators beam?
Comment: I just had the city inspector come by and he recommended exactly the same approach as #3
Comment: Well that's a thumbs up for SE :)
Comment: @TooTea -- CFS stud channel would be quite viable for this sort of reinforcement, and is no-sweat for DIYers to work with with hand tools
Comment: @Jasen - edited to note importance of rounded holes
Answer: I have dealt with this in older houses that have had water damage in a location in a bathroom.
Basically you will need two things with maybe a third:

You need metal sleeves around each of these.   You need an engineer to sign off on how big they need to be and you might need to search around because the size of your hole is quite substantial - or possibly need to be custom made.  (might try to fill cavity before the sleeves but... to do that you don't want to take out more)

You need to sister each of these with 2x lumber at the exact hole size.

You may need to strap underneath with metal which could bring down the ceiling height in the room below by an inch or so.

I would get an engineer to sign off on it and I would sue the plumber or withhold payments.   This is really insane.
I have no idea what the other answer are getting at but this is really your only option unless they make you get rid of the joists (or make joists useless by installing others.   Depending on the span it might be cheaper to throw a small I beam across there - depends what is in the way and all that good stuff.   Answer I gave you is how you have to repair this, it doesn't qualify as saying that repairing this is good enough.
To clarify #2 - sistering might include that section, up until load point (going to nearest wall and making that a load point) or the entire joist (then you might as well install a small i-beam).   I have had engineers tell me to sister to a load point to meet building code and then the city tell me that all joists must be run to "main" load point - guess they are future proofing in case of renovations.   But as mentioned in comments if you just sister this section, there are sleeves (some cup the bottom) that hold up large building structures so holding up a residential joist is not a big deal.   Now is it cost effective if each sleeve costs $300?   I don't know.
Comment: I'm unsure about these, because the sheer length of the hole, and lack of thickness above and below, means essentially there's no web to brace the flange and stiffen the steel, and the fact its in 2 parts means there's much less strength against pulling through the timber sideways under load - and a few mm is enough to sag.  It would be a solution but my least preferred of several.
Comment: @DMoore Definitely the product in the image is not suitable.  The holes in OP's joists are too large.  Most of the screws that should be hitting good wood to secure that brace would be landing in a big empty hole - missing screws = missing holding strength.  It's a good idea, but it would need to be a custom designed piece - much longer than this one so that it can get a good anchor on the existing joist.
Comment: @Stilez Yes, those braces are listed, but they have to be installed as directed, meaning the hole they guard must not exceed the size of the cutout.  This is why DMoore noted they would probably need to be designed specifically for this application, as specified by the SE.
Comment: @Stilez - These sleeves for sure will work.   Now it may cost a fortune to make and install because engineer wants 1/2" of metal but assuredly the remedy works.    It would actually the only way to keep the joists and meet building code.   Is the thin sleeve in my picture good enough... I don't know.   I don't know  the structure of his house and how much load this joist is to handle or how long it runs.
Comment: @J... - your comment is redundant as I have already hinted at that in my answer.   But there are products that look almost EXACTLY like this but thick gauge and longer that an engineer will OK.   Given neither of us know the floor layout or load standards for this house we can only guess.   This is for sure the only way to fix the joist without running a new one.   As mentioned he might need a custom sleeve which may cost a boatload of money (x3-4).
Comment: @DMoore I was directly responding to `Is the thin sleeve in my picture good enough... I don't know.`.  That one definitely is not.
Answer: It looks like you'll have to replace that toilet pipe into a
higher location, (using a street elbow at the inlet end should give you about two inches more height, using 3" pipe will give even more)
For fixing the joists it will be tricky, a beam notched half way through  has only one quarter of its original strength. you basically have four options,
Agressive sistering (but you don't need to sister the whole length
and this can possibly be done from below)
Replace the joists and do over.
Install posts or a structural wall below.
Hire an engineer
Answer: Well, it's almost a year later so I'll fill you all in about how I fixed it. The city inspector insisted that I couldn't sister the joists or repair the hole.  I ended up taking up the rest of the floor and replacing all of the joists in that room.  It ended up expanding the job into the adjacent bedroom and the landing at the top of the stairs.  I had to take out part of the ceiling in the room below the landing in order to get the joists under the wall (as seen in the photo).
It was a hell of a job, but it's safe, sturdy and to code; and I learned a lot doing it.  I finished the whole renovation about a month ago and the bathroom looks great now.
Big thanks to everyone for the advice, which was a huge help in getting me started learning about possible solutions :)
Comment: O_o Wow!!! That's a lot of work. Congrats on doing it right! So many would just bodge it some more and leave the mess for someone else to fix up.
Comment: Congrats! Way to do it right and learn properly at same time
Comment: Thank you :)  I'm very happy with how it turned out
Answer: I'm not an engineer, so take it with a pinxch of salt, but what I would suggest is, build vertical supports along each side of the pipes. And by 'build' I mean bricks and cement, reaching all the way to the same level as the top of the joists.
Since the joists are in fact standing on the concrete underfloor, I think that should be enough to make it safe. Mind, I don't know anything about US building codes.
Edit:
In light of FreeMan's comment, this won't work, since I was mistaken about the 'underfloor' - it isn't concrete, but plasterboard ('dry-wall'), which makes those holes particularly eye-watering.
I think the idea may useful still: add some strong timber parallel to the pipe on both sides, using joist hangers (randomly found with google), with maybe 20 - 30 mm clearance from the top of the joists, and add good plywood board on top of the new timbers, up to the same level as the top of the joists.
Edit:
Actually, I'm talking nonsense - don't do this. The problem here is that the joists have been weakened and are unsafe, even if there wasn't a toilet on top. Really, the pipes should be removed/relocated and the joists strengthened appropriately. Sorry about this - my brain isn't working today.
Comment: That "concrete underfloor" you see is the top of the drywall forming the ceiling for the 1st floor, below. The OP notes that this is 2nd floor construction, and the few private residences in the US that have a poured concrete 2nd floor probably won't _also_ have 2x6 joists on top of them.
Comment: Good on you for giving it a 2nd thought based on feedback. There's no shame here in deleting an answer if you feel it's not contributing.
Comment: @P2000 Thx for your kind words :-) I think it is bad manners deleting after people have spent time on commenting, really. And maybe there is some value in leaving my thought trail here - others might fall in the same trap as myself and get it wrong.
Comment: This answer contains some terrible ideas, but it also explains why those ideas are unsuitable, and that is excellent.  Showing **why** the bad ideas are wrong is just as important as presenting the right solution.  I'd suggest leaving the answer here as-is; don't delete it.  You've clearly shown the explanation for OP and future readers.


Cached Memory Takes all the memory

Question: I've switched to Ubuntu just a couple of months ago. Some days ago, I found out that the system is storing cache in memory which is occupying a lot of space and although I'm getting the benefit of cached memory, this is now making me in trouble.

As you can see in this picture, Ubuntu is taking more than 50% of my RAM. Additionally, I'm using 23.3% of 11.6 GiB which basically means that my system is occupying more than 75-80% of my memory...
Now, I've searched a lot of times how I can clear my cache and I've found that sync; echo 1 > /proc/sys/vm/drop_caches command with sudo privileges can clear it, but this command only worked in the beginning like when I used this command and saw my cached my it was heavily decreased. But now, when I see my cached memory after running this it remains same.
Can anyone help me out with this trouble?
P.S. I think if I try upgrading my RAM, that won't resolve this issue...
Comment: This isn't trouble. This is by design. Why have RAM if you're not using it? When the system needs the memory for other purposes, such as applications and whatnot, the cache will be shuffled to swap or dropped from memory to accommodate the immediate requirements. Otherwise the system will do what it needs to be quick and responsive. This is one of the main benefits of Linux over another OS, like Windows.
Comment: This is not a problem, you have it wrong. The system IS NOT using any memory for cache that would otherwise be used for applications. You THINK this is a problem, when in reality it's not.
Comment: This is normal.  As an example, my 32GB RAM daily driver system's cached ram is 7.6GiB out of ~31GiB usable.  7GB of RAM is actively in use by the system.  Withj the cache, you'd think that I'm using 14.6GB of RAM, when however I'm only actually using 7GB of RAM.  The 7.6GB of RAM is released if it's needed, otherwise it's kept only to 'speed up' things on the disks, caches, etc.  Cached RAM is held until it's needed, and is immediately released when needed - it's not actually affecting your memory *usage* in any way.
Comment: @LabhamJain as has been repeatedly explained, that is wrong
Comment: If your programs make `malloc()` (memory allocation) calls and no free RAM is available then the cached ram is allocated, that part of the cache is just lost... I don't see how restrictions will help your issue, you're probably focused on the wrong issue..  (*opinion*, I don't know the code & my reading of *linux kernel workings* books was long ago)
Comment: SIGSEV is a result of programmer error. It has nothing to do with how much RAM is available or not. AVD always sucks when it's emulating arm instructions on an x86 CPU.
Comment: https://www.linuxatemyram.com/   Unused ram is wasted ram, If something needs that memory, Linux will drop what ever its using it for now. So its no real issue
Comment: Now that you mentioned SIGSEGV, this looks like an [XY problem](https://xyproblem.info).
Comment: @LabhamJain Listen to yourself. The system is *using* the memory. You want it to *not use* the memory. And your reason is that if the system uses the memory it "won't be able to use the ram". That makes no sense. You want the system to be able to use the RAM, it *is* using the RAM, proving that it *is* able to use it.
Comment: @OrangeDog It's actually a problem which happens when chrome gets out of memory access... so what i meant by cached memory is that my system occupies majority ram in cached so technically i'll be only able to use free memory e.g. 11 gb total - 6 gb in cached so i can only use 5 gigs max...
Comment: Windows also has caches, it's just a bit less aggressive about it. @matigo
Comment: @matigo Why have RAM when not using it? So it can be allocated for programs when needed instead of having the whole system hang as 2GB is suddenly put on the swap, killing the poor SSD. This is crap design. I have 8GB and I hate how freely the OS dares to allocate 3GB for cache while I know I will run out of memory soon and experience mini-hang.
Comment: Well, I don't have any problem storing cached memory, i just want that it should be in limit... Because if system is taking all the space in caching then i won't be able to use the ram... now because of the cached memory issue my chrome is showing me SIGSEV error. and AVD always sucks.
Comment: Not related to the question: since you have a lot of RAM, consider switching to ZRam instead of HDD based swap.
Comment: @matigo: Windows also uses "unused" memory to cache things, but _most_ of it's UIs hide this from the user so they dont' get confused and panic.
Comment: Note that cached memory does not always mean memory that can be discarded when more RAM is needed. For example, data in `tmpfs` will show as "cached memory". However, System Monitor will show this kind of memory as both cached and also being used (so it will be in the colored portion of the pie chart). [This has bitten me before.](https://askubuntu.com/questions/762717/high-shmem-memory-usage)
Comment: https://www.linuxatemyram.com - this is a classic ;)
Comment: @OrangeDog yes but - since a failing malloc returns null it is very common for a program to crash with SEGV if it runs out of virtual memory and does no proper return checking, so there is a strong correlation there, For example the ZIp code in the Java runtime had that problem for years.
Comment: @eckes `malloc()` on Linux essentially [never returns NULL](https://stackoverflow.com/questions/16674370), so that's moot.
Comment: I have just paid attention to it. Just hit RAM overflow, the cache still takes 2GB RAM and is forcing app memory to swap.
Comment: Please check this link https://www.linuxatemyram.com/, author explains that what you are seeing is not what you think is going on.
Answer:
if system is taking all the space in caching then i won't be able to use the ram

This is not true. Cached RAM does not determine RAM in use. You will be able to use the RAM, that's why it's called cached — it can be used and discarded as needed. In fact, it's just the opposite of your assumption. If you eliminate cached RAM, you won't be able to use what is cached.

Now, I've searched alot of times how i can clear my cache, i've found that sync; echo 1 > /proc/sys/vm/drop_caches command with sudo privileges can clear it, but this command only worked in the beginning like when i used this command and saw my cached my it was heavily decreased. But now, when i see my cached memory after running this it remains same.

You only need to manually clear the cache if you have swappiness turned off. Disabling swappiness is not recommended to increase performance as this actually reduces system performance.
Unlike Windows, Ubuntu doesn't crash under heavy RAM load because of the differences in memory management. Disabling these features will significantly reduce performance.
In summation, cached RAM is not RAM in use and does not max out your RAM or decrease system performance because cached RAM is automatically discarded as needed. Conversely, cached RAM increases performance as it is used when needed.
Comment: It's not quite fair to say Ubuntu doesn't crash on RAM overload. OOM-killing your X server is just as bad for desktop experience as locking up or kernel panicking. True, nowadays it's rare because of OOM score adjustments done by modern distros to important processes, but I did experience it often about 5 years ago.
Comment: @MooingDuck: Why do you think Linux has swap disabled by default? I think Ubuntu creates a swap partition during the default install - of course, you can insist on not having swap if you want. Also, "crash" is when the system becomes unresponsive or reboots - this is very different to what Linux does in an out-of-memory situation (deterministically stopping processes to free up ram)
Comment: Of course Linux (including Ubuntu) can crash on RAM overload. It's just harder to get to that point because of the way it manages memory, but it isn't impossible. If you actually use all of your RAM, the system will start swapping and if you fill that up as well, it will become unresponsive and eventually crash (presumably, we usually force reboot when this happens).
Comment: If you want to increase system performance, the best thing you can do is switch to a solid state drive instead of a hard disk drive.
Comment: Personally, I switched to a SSD and increased swappiness to 70 to get better performance on 5GB of RAM. Since you have 11GB, swappiness will have little effect on system performance unless the system gets bogged down. In this case, swappiness should increase performance, not decrease it.
Comment: @terdon I mean, it won't crash, there's OOM killer for that sort of situation. Depends on what you mean under "crash", of course, but kernel will be just fine. Other processes - it depends.
Comment: @terdon Yeah, I've had the system frequently lock up on a really old computer (only 1.5GB of RAM) but that was because my swap partition was too small and the HDD was super slow. After increasing the size of the swap partition (and swappiness from 10 back up to 60), the system was slow but not unresponsive.
Answer: Cached memory is in fact free memory.
It can (and will) be fed as free to any process that asks for memory, as soon as the other free memory is used up.
In the meantime, the kernel keeps track what information is cached in this otherwise free memory.
This information is not expected to be written somewhere by a time-consuming i/o. It is either already written or read and never changed in the first place. This information can be safely (and quickly) deleted from memory.
Answer: Caching does not hurt you in any way!
The RAM is not being used by cache... it is being borrowed by cache!  That means it will be returned for your use the instant you need it.
If your software requests a block of memory, the system goes "here you go" and gives the block.  If there happened to be cache sitting there, the cached elements are dropped (i.e. they are no longer in cache and would have to be fetched from disk again if needed).
Smarter systems will make smart choices about which elements to drop out of cache to give you your memory.
Comment: @LabhamJain sounds like you used up all your RAM _and_ swap. Disk cache is not your problem.
Comment: @LabhamJain cache problems don't hang your system, so I think "cache" is a red herring, and you have a completely different problem... this happens all the time here, it's called an "XY problem"...
Comment: This doesn't seems to be true, i tried running android emulator but when my ram got full with cache of 4gb it hanged my system instead of deleting that cache...
Comment: @LabhamJain I used to experience disk thrashing on an old computer and it turned out I needed to increase the size of my swap partition—the system was trying to swap out to swapspace that didn't exist. Also, I've had temporary hangs because of a slow hard drive. The solution there was to switch to SSD.
Comment: In my experience, all the answers that say that caching is not a problem are wrong. In some cases, memory is not made available fast enough to a program such as firefox and this is when the hell starts since the computer starts to swap, this causes cpu to flare up to full usage due to interrupts, rendering the computer unusable. You can try to manually envoke the kernel killer of highest ram eating programs but it will not work since your keyboard does not work since cpu is flooded by swap caused interrupts. Caching is the biggest bug in Linux kernel and as often is, it is called a feature.
Comment: my linux kernel crashes a few times a year and its always this. today it was steam verifying a very large game. I have 64 gigs of memory in my laptop. i basically have to do

watch -n 30 'echo 3 > /proc/sys/vm/drop_caches'
Answer: Open your terminal (Ctrl+Alt+T), and type the command: free -h. You will get the output like this:
              total        used        free      shared  buff/cache   available
Mem:           15Gi       2.0Gi        10Gi        33Mi       2.7Gi        13Gi
Swap:          31Gi          0B        31Gi

Here you have 15G of total RAM, 2G is used, 2,7G is cache, and 10G is shown as "free". But look at the last column: it shows 13G as "available". That means that you can use 13G of RAM (that is, sum of free+cache) despite only 10G being shown as "free". As the other answers have pointed out, the cache memory is temporary: it is assigned to applications if needed, exactly as the "free" memory; there's no difference between these two with regard to this.
Look at this this way: the system uses part of free memory on your computer to temporarily cache data read from disk to speed up disk operations. But regardless of being used as cache, this memory is still free to be used by applications, that is, it will be assigned to application (invalidating the cache) if the application needs it.
Answer: Empty RAM used as cache for your ssd is by design to speed up your computer. If you want to clear the cache every x minutes, you can set a crontab entry to clear the cache.
Comment: @LabhamJain No you don't.
Comment: That's not i want i just want to limit my caching of memory...
Answer: Welcome to GNU/Linux, friend!
In this world, our kernels don't waste ram, and we don't worry about ram being 'in use' unless it's applications fighting other applications for it.
What you describe is normal.
100% of ram will be in use ideally on a GNU/Linux system.  What ram applications don't need will be used by disk caching.  Wouldn't you rather have disk operations operate at RAM's speed than at the speed of your hard disks?  Well, you get that now, for free.  Enjoy, and don't sweat it when you see memory in use by caching.
Answer: Well, I've figured out my problem with the sync; echo 1 > /proc/sys/vm/drop_caches command, I misspelled this command somewhere, and now if I use this command properly then it cleans my cached memory, hence my problem seems to be solved, though more answers for future references and for community will be appreciated.

Cached Memory Takes all the memory


What could go wrong if I use my claw hammer as a cross peen hammer?

Question: I'm trying to sharpen a scythe blade. I'm supposed to strike the edge to flatten it. I'm supposed to strike it with a cross peen hammer. But I don't have one. Can I use my claw hammer instead with no adverse effect?
If there is a downside, what is it? Is it more likely to damage the scythe blade I'm striking or the hammer? Or will it work just about the same?
Comment: Curious question, do you have the rest of the tools you need to peen and sharpen? I just seen a video on peen sharpening a scythe and there is other things to have on hand
Answer: Well, first off, because the hammer is utterly the wrong shape, it won't work very well - and you can substitute "at all" for "very well" without being very off the mark, especially since you are evidently new to this and don't understand it much at all.
Peening a scythe properly is a process that takes some tools and some skill. With certain tools, more skill is required - with others, the tool design helps to reduce the level of skill needed. For a novice user with limited hammer skills, a special peening tool which uses a pair of caps that run on a central stake over a small anvil to do the actual peening is a common choice (yes, they do cost money, such are tools.) That reduces the skills you need to have to hitting the cap with a hammer (hard enough but not too hard) while holding the blade flat to the anvil and moving it along as you hammer.
Hammering freehand you need the cross peen hammer to concentrate the force of the blow into a small area so it will actually move metal (that's what "peening" is.) But now you not only have to hold the blade flat on the anvil (do you have one?) but you also need to place those hammer blows accurately at the correct distance from the edge (which the fixture above does for you by design.) A claw hammer's broadly rounded, mostly flat face will not hit the precise area needed (only) and it will move very little metal as the force of the blow will be spread out over the wide face.
And you will need a scythe stone and a holder to keep it wet for getting the blade truly sharp after peening, and keeping it that way as you work. I stone about every 5 minutes (takes 20-30 seconds) while working, and peen daily if working a lot, or when I feel like the scythe has done a days worth of work over several days, or when it's had a few too many run-ins with rocks or the like and/or just seems to need it.


create tsa (timestamping) certificate with openssl - add a extendedKeyUsage in a certificate

Question: I'd like to create a tsa certificate for my timestamping service.
First I create a root certificate
openssl genrsa -out tsaroot.key 4096 -config openssl.cnf
openssl req -new -x509 -days 1826 -key tsaroot.key -out tsaroot.crt -config openssl.cnf

Then I create the tsa certificate
openssl genrsa -des3 -out tsa.key 4096 -config openssl.cnf
openssl req -new -key tsa.key -out tsa.csr -config openssl.cnf
openssl x509 -req -days 730 -in tsa.csr -CA tsaroot.crt -CAkey tsaroot.key -set_serial 01 -out tsa.crt
openssl pkcs12 -export -out tsa.p12 -inkey tsa.key -in tsa.crt -chain -CAfile tsaroot.crt

In my openssl.cnf file, i add the following line :
extendedKeyUsage = critical,timeStamping

Howerver, the created certificate doesn't seem to include the extendeKeyUsage (when i try to read it with bouncy castle i got a "Certificate must have an ExtendedKeyUsage extension." exception
How can I generate a valid tsa certificate (with the correct extendedKeyUsage value included)?
Thanks
Answer: Try with the following:

Add a named section in the openssl.cnf file:
[v3_tsa]
extendedKeyUsage = critical,timeStamping

When generating the TSA certificate from the tsr, add the switch -extensions:
openssl x509 -req ... -extensions v3_tsa

Answer: The following worked :
create a file extKey.cnf with the extendedKeyUsage inside
extendedKeyUsage = critical,timeStamping

Add it when creating the request :
openssl x509 -req -days 730 -in tsa.csr -CA tsaroot.crt -CAkey tsaroot.key -set_serial 01 -out tsa.crt -extfile extKey.cnf


python tree .why it should call evaluate() method for every element

Question: I am little bit confuse why we should call evaluate method in this
program
     like this self.right.evaluate() what is the role of including evaluate()
class exprnode(object):
    def __init__(self, value=None, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

    def evaluate(self):
        if self.value == '+':
            return self.left.evaluate() + self.right.evaluate()
        elif self.value == '-':
            return self.left.evaluate() - self.right.evaluate()
        elif self.value == '*':
            return self.left.evaluate() * self.right.evaluate()
        elif self.value == '/':
            return self.left.evaluate() / self.right.evaluate()
        else:
            return self.value

Comment: Well, suppose you had (1 + (2 + 3)).  Wouldn't you want to evaluate (2 + 3) to get 5 before adding it to 1?
Comment: yes that is right ooo i understand thank you
Answer: evaluate() is returning the value of the node unless the value of the node is an operator (+,-,*,/). If the value of the node is an operator, it takes the value of the left node and adds, subtracts, multiplies, or divides it to the value of the right node. This creates
This code is a postfix calculator that you can use to put together expressions like (2 + 4) / 2 = 3.
a = exprnode(2)
b = exprnode(4)
c = exprnode("+", a, b)

d = exprnode(2)
e = exprnode("/", c, d)

print(e.evaluate())


What's the issue with vcard duplicates?

Question: No software I've seen is able to synchronize contacts between Outlook and my cell without creating duplicates. One would think that someone had synchronization in mind when they thought up the format. Is it impossible for programmers to work around this problem?
Answer: I've had the same problem using the native Nokia and Samsung software (and a free Nokia program I can't remember now), and I've found that none of them handle duplicates. To program around it, you could either copy one way, flush the source device, and copy back again, or you could copy, remove duplicates, and then copy back.

What's the issue with vcard duplicates?


How can I hide CPLEX's output in AMPL?

Question: I want to hide messages like

CPLEX 184.108.40.206: integer infeasible. 319 MIP simplex
  iterations 0 branch-and-bound nodes No basis.

I don't mind hiding successful messages or not, but I don't want unsuccessful messages.
I have tried

option cplex_options 'wantsol=8';
option cplex_options 'logfile=rubbishFile.txt';
option cplex_options 'tunedisplay=0';
option cplex_options 'incompat=0';

But don't work.
Comment: I believe that message is actually coming from AMPL. The solver returns a string to the AMPL environment and it is the AMPL environment printing it. I don't know (yet) how to disable it... but it pretty much explains why you couldn't switch it off in CPLEX.
Answer: I suspect that those lines are actually printed by the AMPL environment. Depending on what you want, please try these after suppressing all output from CPLEX:

option cplex_options 'outlev=0'; (this should quiet CPLEX) and
option solver_msg 0; or
solve >rubbishFile.txt;

Hope this helps.

How can I hide CPLEX's output in AMPL?


how to disable external pagination when data less than 10 rows in ui-grid?

Question: This is my code

var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.pagination']);

app.controller('MainCtrl', [
'$scope', '$http', 'uiGridConstants', function($scope, $http, uiGridConstants) {

  var paginationOptions = {
    pageNumber: 1,
    pageSize: 25,
    sort: null
  };

  $scope.gridOptions = {
    paginationPageSizes: [25, 50, 75],
    paginationPageSize: 25,
    useExternalPagination: true,
    useExternalSorting: true,
    columnDefs: [
      { name: 'name' },
      { name: 'gender', enableSorting: false },
      { name: 'company', enableSorting: false }
    ],
    onRegisterApi: function(gridApi) {
      $scope.gridApi = gridApi;
      $scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
        if (sortColumns.length == 0) {
          paginationOptions.sort = null;
        } else {
          paginationOptions.sort = sortColumns[0].sort.direction;
        }
        getPage();
      });
      gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
        paginationOptions.pageNumber = newPage;
        paginationOptions.pageSize = pageSize;
        getPage();
      });
    }
  };

  var getPage = function() {
    var url;
    switch(paginationOptions.sort) {
      case uiGridConstants.ASC:
        url = 'https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100_ASC.json';
        break;
      case uiGridConstants.DESC:
        url = 'https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100_DESC.json';
        break;
      default:
        url = 'https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100.json';
        break;
    }

    $http.get(url)
    .success(function (data) {
      $scope.gridOptions.totalItems = 100;
      var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
      $scope.gridOptions.data = data.slice(firstRow, firstRow + paginationOptions.pageSize);
    });
  };

  getPage();
}
]);
<!doctype html>

    <link rel="stylesheet" href="http://ui-grid.info/release/ui-grid.css" type="text/css">
    <link rel="stylesheet" href="main.css" type="text/css">

In the above code I am using external pagination in UI-grid.I want to disable pagination when data is less than 10 rows,if data more than 10 rows enable pagination.if possible display pagination outside the ui-grid.
Answer: To use a custom pagination outside the grid, set enablePaginationControls: false in gridOptions.
You can then hide your outside pagination element, when data has less than 10 items.
Here is a Plunker with live demo that uses Bootstrap pagination directive.


weblogic + eclipselink + 2 different thread = lazyloading don`t work

Question: I have two threads one of them write text field to the database, another try to read this field but it can`t.
field has following anatation:
<code>@Lob
    @Column(name = "response_soap")
    @Basic(fetch = FetchType.LAZY)
    public String getResponseSoap() {
        return responseSoap;
    }
</code>
Both thread it's part of the web application. Both running on the same weblogic server.
All transaction is commited. There is field in the database.
Every time I'm creating new Entity manager.
Comment: The problem was solved. I turned off shared cache. http://wiki.eclipse.org/EclipseLink/Examples/JPA/Caching
Answer: What error do you get?
Try using a refresh, em.refresh(object)
Are you serializing the object?  Since it is LAZY it will be null when you serialize it, unless you access before you serialize it.  Try making it EAGER.
Answer: I believe that only
Many-to_many and One-to-many are can be set to lazyload
One-to-one, Many-to-one and Basic are all Egar
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Mapping/Basic_Mappings/Lazy_Basics


How to know the name of the background image used at home screen android?

Question: How I can know the name of the image used in android home screen?
I use WallpaperInfo But it is not giving me name of wallpaper.
Comment: Have You tried anything? post the code.
Answer: As far as I know you cannot. When the wallpaper is set, the WallpaperManager is just given a Bitmap.. So it does not know anything about the original data that was used to set it.
No filename is ever transferred to the WallpaperManager, just the actual data to display..
Comment: In such a case I have to know a way for comparing bitmap.
Comment: Then you should check out the `sameAs()` function for Bitmaps [Android Reference for Bitmap.sameAs()](http://developer.android.com/reference/android/graphics/Bitmap.html#sameAs%28android.graphics.Bitmap%29)


Access Denied When using php to link to another html page

Question: I'm fairly new to php/html so bear with me.
So in the home page of my website, the login link takes the user to either

The login page
The user page if they had already logged in

Before implementing this fully, I decided to check whether or not I could get a simple php link to work and im glad i did because it does not work.
I have currently:
<a href="<?php echo 'login.html';?>">Login

This is supposed to go to login.html when clicked on but when you click on the link you get this
Corresponding error log from XAMPP's appache error.log:

[Thu Aug 09 21:51:30.257273 2018] [core:error] [pid 37376:tid 1948] (20024)The given path is misformatted or contained invalid characters: [client ::1:49721] AH00127: Cannot map GET /poll/%3C?php%20echo%20%27login.html%27;?%3E HTTP/1.1 to file, referer: http://localhost/poll/Poll_home.html

If instead of the above code I put
Login

then it works fine and links me to the login page.
Any help would be great!
edit:
Problem is fixed by creating a new php file (test.php).
Login

But when I try to make the link dynamic by changing the test.php to this:
<?php
if(session_status() == PHP_SESSION_NONE){ //if already logged on
    header("Location: login.html");
}
else{ //If not
    header("Location: sign-up.html");
}
exit;
?>

It always goes to login.html even when I am not logged on.
Comment: Your PHP hasn't been enabled yet or you are writing php code in html file.
Comment: I have a connect.php that is used to connect to a mysql database and that works fine so I don't think that's the issue? Also yes I am writing in an html file. Is that an issue? I thought it was fine if I put the <?php thing.
Comment: What you mean is that you writing php code in a file with extension `.html` ?
Comment: Yes. The only php code in the html is that echo.
Comment: On your login page... are you creating a session variable upon successful login?
Answer: if isn't working with php use this
<a href="<?='login.html';?>">login

or use this
Login

Comment: The first one doesn't work. I get the same error. As the for the second one yes that works but I need to expand this later on (I mentioned this at the beginning of the post) to make the link be either login.html or user.html which is why I nedd the php part.
Comment: How do I do that? I'm new to this so I dont know much haha.
Comment: there is no problem
do you setup **xampp** ??
Comment: Yea so it should automatically allow php to my knowledge
Answer: As per error message

Cannot map GET /poll/%3C?php%20echo%20%27login.html%27;?%3E HTTP/1.1
  to file, referer: http://localhost/poll/Poll_home.html

It says that you are writting PHP code in Poll_home.html file, which is the problem, you should write PHP code in php file (i.e. Poll_home.php). When server see url file is html it will not execute it but send it content to user browser. so rename your file and check. It should work.
Comment: But I have seen people write php in html with the  tags?
Comment: If you write php code in html file, then server treat it as normal text as part of html,  You  can verify it by seeing source code of your file, just right clicking and selected view source, you can see your php code.
Comment: So I wrote the php in a new file (test.php) and it does seem to work. Login. But I get a new problem when I try to expand it and achieve the original goal (see edited post).
Comment: If this answered your original question you should mark it as the accepted Answer. If you have a new question you should ask a new question in a new post, rather than appending it to the question that has been answered


Using a 100A main breaker in a 200A panel

Question: So I purchased a 200A Siemens panel to replace the old 100A sub panel in my house. The main panel is in the garage and is also 200A Siemens and has a branch circuit to the house of 100A.
I bought a 100A main breaker for the new 200A sub panel since the sub panel will still effectively be 100A, but I noticed on the box of the breaker it says "Do not install on 150A-225A Load Centers." Can I really not install this in the 200A panel? If so, that's kind of a bummer... I guess I'd have to return the 200A panel and downsize to a 100A or 125A panel instead. The breaker fits just fine.
Answer: Breakers protect wires.   The wire to the sub-panel can only be protected by the breaker in the main panel, and that must be correct for the wire's type and size.
Like Ed Beal says, you don't need a master breaker in a sub-panel.  The breaker in the sub-panel wouldn't protect the wire to the sub-panel. It protects the sub-panel itself, which is listed for 200A.  It can also be nice if you ever get sick of paying the tenant's electric bill and have the electric company feed a separate meter to that panel - voila, the master breaker is there already!
(I'm saying "master breaker" to avoid saying "main breaker", which might be confused with "breaker in main panel".)
If you are hoping for the sub-panel breaker to trip before the main-panel breaker, that doesn't work. Breaker trip curves are complex and unpredictable.
If the 100A breaker is not listed or labeled to work in the 200A panel, then you cannot use it, end of subject.  That's the law.
This is a situation where buying from a proper electrical supply house (and not a big-box home improvement store) will be very helpful.  You tell them what you want, they will sell you the right thing in the first place, and stand behind the combo.   On price, for the behind-the-counter stuff, I find them more than competitive with big-box. Their customers are, after all, electricians who deal in volume and drive past 3 big-box stores to buy there. (Electrical supplies do tend to wildly overprice the impulse-buy grab-candy at the front of the store, so don't go off those prices.)
Comment: I ended up returning the 200A panel and 100A main breaker to get a smaller 16/24 125A panel. I just decided the 200A was wayyyyy too big for my small house... the 125A is the perfect size and a small upgrade over the original 100A panel. I'm also going to forgo the sub panel "master" breaker for now since it's not needed. Maybe some day I will get another 100A "master" just so there is an easy shut-off in the house without having to run to the garage.
Comment: As long as you'll have enough spaces, that's the key thing.
Comment: Yep, I will. I'm changing all of my 20A outlets to 20/20s. I should have about 5 free spaces left which would be plenty if for some reason I (or someone else) make an addition to the house.
Answer: With a 100A breaker in your main panel you do not even need a main breaker. I would leave the 200A in the sub as a disconnect. Take back the new 100A and get your $ refunded. If you ever decide to upgrade the service you will need the larger breaker.


Help identifying the purpose of a central heating valve beside boiler

Question: I have a 12 year old Pottington gas combi-boiler running my radiators and water tank. I was checking the central heating loop pressure today and I discovered a twisty valve I never used before. I think this valve has been incorrectly set since I bought the house, and it appears to connect the boiler water OUT to the boiler water IN, short circuiting the radiators. It is a smaller pipe than the main one. It is located beside the boiler.

The radiators don't heat up very quickly, I had assumed it was just because the weather was extra cold
The boiler powers down every few minutes, including soon after a cold start

Please see the diagram below.

I found the valve fully open (anticlockwise) and it was stiff, not recently turned.
I measured temperatures, see diagram:

47°C
27°C
47°C

In this configuration the water seems to be going through the short circuit and so the boiler turns off soon. The radiators still work and have done for 6+ years but they could heat more quickly.
Turned the value to fully closed (clockwise), and now

measured temperatures:

47°C
33°C
33°C

boiler ran much longer even when the thermostat dial was turned down

So these are my conclusions:
This valve allows a significant amount of hot water to short-circuit into the return from the radiators, limited by the smaller diameter of the pipe. The boiler thus receives a warmer return water and cycles off quite quickly, limiting the speed at which the system can heat. Is this good for the boiler?
And my questions are this:

What is the purpose of this valve?
Should it have been fully open?
Where should it normally be placed and why?
Will it do any damage to place it fully closed?
Answer: I think you are correct that the valve helps the boiler to turn off sooner.  You typically want a delta T of 15F such that the water has lost 15F of heat after coming back from your zones before being heated again.  Heating water that is already at temperature doesn't make sense.
116F to 91F is a delta T of 25.  This means your heating your water too high.  The boiler can't choose how hot to heat the water only whether to heat.  If the water comes back hot enough the boiler turns off.  If the water comes back cold then the boiler will continue to heat.  The boilers are often over sized to account for the coldest day of the year and to avoid any call backs for heat issues.
If you open the short circuit valve then the water is coming back warmer which turns off the boiler and colder water is going to be pumped through your radiators.  The less the boiler runs the more cost efficient your bills will be.  If you want heat the quickest then pushing water at the highest temperature will get you that but that also costs the most amount of money.
Radiators in older drafty houses are also placed near windows to make those areas comfortable.
I run my radiant in floor heating at 90-95F and it returns at 80F but I have multiple zones and I am not heating up windows.  I also have a variable speed pump which adjusts speed based on the number of zones calling for heat.
Cycling the boiler quickly probably isn't great but are your measurements based on trying to heat the house from a cold state or from once the heat has been on for a while and the house has heated up to a generally acceptable temperature?  I guess what you are aiming for is that the boiler doesn't quick cycle during the majority of it's operation.  The only thing that is likely to take wear with the cycling is the gas valve but if this results in the boiler running less frequently then you'll likely save the value of the gas valve very quickly.
One other note is the general consensus is that the circulator pump should be on the cold side as it will last longer.
Let's say you close the valve and you push 47C water through your radiators.  The house reaches temperature quicker - say you have the thermostat set to 22C.
The thermostat stops calling for heat, the pump stops, the 47C water at the radiators is allowed to cool but while cooling is also still heating until is chills from 47C to 22C.  The house over heats to 25C and you overshoot your temperature - maybe ok.
The house cools to 21C and your thermostat calls for heat.  47C water goes back out through your whole loop and you overshoot again maybe by more this time as everything in the house is already warm and the heat loss is lower.
So it can depend a bit on how far you'll overshoot based on the 47C and 22C requested temp.  The closer the water temp is that you can push and still deliver heat in a reasonable amount of time the better and the lower chance of overshooting your design temperature.
Comment: 95F (35C) to 80F (26.6C) is a delta T of 15 which is the literature ideal.    35C to 26.6C is 8.4C delta T.   115F (46.11C) to 100F (37.78) is 8.33 delta T.  I am not sure what the metric boiler people use as a delta T is it 8.4C?  I work in metric temperature but in North America our components and engineered systems are mostly not metric and I've only heard/learned the delta T literature in F.  OP posted in C but had to convert to F to do the delta T work - I am not fluent in celcius delta T =)  So I've mixed the units to irritate everyone!
Comment: Don't mix your units. First part of the answer is using fahrenheit units as temperature measure and then the last four paragraphs switch to celsius, SI units are always the way to go.
Answer: It's a boiler bypass loop.  These can be installed for various reasons.  I can't tell which one(s) apply to your case:

preheat the incoming cold water a little to reduce temperature fluctuations in the heat exchanger and to reduce condensation within the boiler
provide a water circuit for the pump to keep circulating if/when all other circuits are closed by zone valves or other valves.  Various reasons for this related to the design of the overall system.

The valve is to tune the bypass. It should not be fully open or closed.  An experienced boiler installer should adjust it in order to achieve whichever of the above goals is needed.
Comment: "for reasons you can Google" shouldn't make it into an answer. Imo your answer should either only contain the name of what it's for, or the full description of what it does.
Comment: Fair enough @DaniëlvandenBerg.  "Full description", no .. that would be a two-volume set.  Hopefully now an appropriate level of summary.  And no hiding it, still a little evasion in the second bullet. :)


PHP trim row results?

Question: Hello I'm getting results in format
location1 2 4
location2 3 2
location3 0 0
location1 1 0

How can I trim results so that row returning 0 and 0 is not displayed ? thank you
.................
Here is Mysql query, I don't know how to trim it from MySQL so I thought using PHP ..
    SELECT hotelas.name, hotelas.address, hotelas.city, hotelas.country, hotelas.hotel_id
AS hotelid,
COUNT( DISTINCT apart.apartman_id ) AS number_of_free_ap,
COUNT( DISTINCT room.apartman_id ) AS num_of_free_rooms
    FROM hotel AS hotelas
    LEFT JOIN apartman AS apart ON ( apart.apartman_hotel = hotelas.hotel_id
    AND apart.occupied =0
    AND apart.what =1 )
    LEFT JOIN apartman AS room ON ( room.apartman_hotel = hotelas.hotel_id
    AND room.occupied =0
    AND room.what =0 )
    GROUP BY hotelas.hotel_id

TABLE field what, 0 - for room, 1 - apartment
So I get a few columns among which the most important ones are count columns , free rooms and free apartments. So I have a test hotel which is full 0 rooms and 0 apartments and I want is removed from this list where all other hotels have at least one room or one apartment available.
Comment: You indicated that you didnt want to touch your SQL because it was too complex. If you post your SQL query, someone here might be able to help.
Comment: Its posted above, information about hotel are stored in a hotel table, information about rooms or apartment are stored inside apartman table.
Answer: if you are querying you database to get this information and you can change the query, that would be the best place for it.
SELECT *
FROM myTable
WHERE
    firstColumn != 0
OR
    secondColumn != 0

If you are getting this in PHP from some other source (CSV or something), or you don't have control over the query, use array_filter():
// i'm assuming each line in your example is an array of values
$myArray = array_filter($myArray, 'noDoubleZeroes');

function noDoubleZeroes($line) {
    return $line[1] != 0 || $line[2] != 0;
}

Comment: No, his SQL seems correct to me. The asker wants to remove results where BOTH columns are 0, so AND is the correct choise.
Comment: your solution works when I change your function to

function noDoubleZeroes($line) {
    return $line[number_of_free_ap] != 0 || $line[num_of_free_rooms] != 0;
}

But I'm now getting empty results from column name, address, city, country
Comment: Ah, of course.  The SQL _excludes_, so it's an OR. Now I feel stupid.
Comment: @gnud - you and me both, buddy. @c0mrade, are you sure that your array's keys are what you think they are? try adding some echoes in the function to help debug: `print_r($line)` would help.
Answer: select * from table
where column1 !=0
or column2 !=0

That's how you can trim it in MySQL.
OTOH, if you have an array such as this ( you will usually get this after you query from a db)
array(array('location1', 2, 4), array('location2', 3, 2))

Then you need to loop over the array and do the manual filtering:
$newarrs=array();
foreach($arrs as $values)
{
  if($values[1]!=0 || $values[2]!=0)
    $newarrs[]=$values;
}
return $newarrs;

Comment: I have a pretty complex LEFT join query I don't know how to modify it. Its working so I should edit the results from PHP
Comment: You could post the query here. We might be able to help.
Answer: If i understood you correctly this should help
$columns = explode($resultLine, " ");
$whatYouWant =  $columns[0];

Comment: You did not understand correctly. He wants to remove the rows with two 0's.

PHP trim row results?


Can you use an Orbit Sprinkler Timer with Rainbird Valve

Question: My house has Rainbird valves and I am thinking about buying an Orbit Timer/Controller.  Can you use a Rainbird valve with the Orbit Controller.
Comment: My system has older, now discontinued, Rain-Bird solenoids that require a minimum .30 amps 24Vac. The Orbit "Easy Dial" controller that I purchased puts out .25 amps 24Vac per valve...They are not working together. The water will not turn on by itself during a cycle without me messing with the manual/purge setting on the valve. Once I get the water flowing to the heads it will then remain ON until the controller times off. I may well find the Orbit controller does not provide enough the initial "uuumpff" to pull in the plunger on the Rain Bird solenoid - only enough to 'hold in' the plunger. T
Answer: it should work. find out what kind of rainbird valves you have, then look online to see what their voltage/current requirements are. you have to match voltages between the timer, and the timer must provide at least as much current as the valve require.
Comment: They should all be interchangeable. The only caveat is that some timers and values are DC instead of the normal AC (yes, AC, but stepped down to low voltage). DC valves and controllers are used with battery-only controllers and perhaps solar controllers. DC valves are pretty unusual and you will have to go out of your way to find them.


Need help with wiring for bathroom fan

Question: I am trying to replace my bathroom fan. The old fan had a light, but I am replacing it with a basic fan with no light (Hampton Bay #BPT13-14MG).
The ceiling has two pipes that each have one white wire and one yellow wire. The new fan has two green, one white, and one black. I am not sure how to proceed at this point.
There is one switch on the wall that controlled both the fan and the light on the old unit.
Any help would be appreciated.
Comment: How many switches are there in the wall?  Was one switch controlling both the fan and light, or did separate switches control the two?  Or were there other lights controlled by the fan switch?
Comment: There is one switch that controlled both the light and the fan.
Comment: Did the new fan come with a knockout bracket? It seems that you'll have to replace the one from the old fan...
Comment: Yes, it did. It only has an opening for one pipe though.
Comment: Can you post photos of the new bracket please?
Comment: Post edited to add photo of new bracket
Answer: The old fan's bracket seems to be identical, so I'd just go ahead and continue the old one in service, rather than exchange an essentially identical piece.
The biggest problem you have is this fan is supplied with single-use stab connectors.  Once you stab, you can't un-stab.  So you need to get it right the first time, or just cut those stupid things off and use wire-nuts.
Clearly, one pipe is supply, and the other pipe is onward switched fan/light power to something else.  Since you're in conduit, the installer had more liberty to choose wire colors, and chose yellow when ordinarily someone would use black or red.  Don't worry too much about that.  But white is definitely neutral, regardless!
For now, get a plain receptacle. Pick one pipe, and attach the white to neutral and yellow to hot on the receptacle.  Plug something in there e.g. a night light.   Turn the breaker on, and see if the night light will light up.   If it does, you have identified supply.
Turn the power off and try the other pipe - same thing.  See if any switch makes that "night light" come on.  It's possible power is coming from both directions! Weird, unlikely, but we need to cross it off the list.
OK, so with the receptacle and night light lighting up off the fan/light switch, what now is broken??  I bet something that used to come on with that switch, has stopped doing so.  That is where that other pipe goes to.
Anyway, now mount the fan.  You most likely need to make a 3-way connection between the fan's white wire and the 2 white wires from the ceiling.  That stab connector won't do.  You'll need a wire-nut or a Wago lever connector.  (or stabs with more slots, but I do not like those, no I don't.)
Then, you'll (probably) need to do the same with the fan's black wire and the 2 yellow wires.  Again, use a wire-nut or a lever connector (looks like a stab connector but is locked/released by levers).
That should do it. As far as ground, the conduit is ground. When the fan is re-mounted to the bracket the conduits come in on, the steel case of the fan will be fastened to the bracket, and that will ground the fan.  You don't need to do anything with the 2 ground wires. You can leave them in their little stab connector.
Comment: I wouldn't rely on the connection of the old electrical cover plate fitting securely enough to the new fan to provide a satisfactory equipment ground. It appears to me the attachment screw on the old cover is on the top, and the new fan is on the side. If somehow the cover can be modified at very least I would run a 10-32 tap through the old cover and add a ground pigtail. (I might do even pigtail a ground wire to the new cover, not being particularly comfortable with rigid connections to vibrating equipment.
Comment: It looks to me like the 2 cover plates are identical @NoSparksPlease , and there's a notch/hook on the top, and a screw on the side.  If the old one can be un-bent, it should be able to continue in service. The screw appears to be accessible.

Need help with wiring for bathroom fan


pybind11 union fails 'is_base_of' assert

Question: I'm trying to bind a union with pybind11 and I'm getting a strange error. I'm not sure if i'm hitting a limitation of pybind11, or i'm implementing this incorrectly.
Would anyone be able to point me in the right direction? Thanks!
#include <iostream>
#include <pybind11/pybind11.h>

namespace py = pybind11;

struct object {
   object();
   union union_type {
       bool boolean;
       uint64_t u64;
       int64_t  i64;
       double   f64;
   };
   union_type via;
};

PYBIND11_MODULE(example, m) {
    pybind11::class_<object, std::shared_ptr<object>> cl(m, "object", "Object class that corresponding stuff");
    pybind11::handle cl_type = cl;
    {
        auto & enclosing_class = cl;
        py::class_<object::union_type, std::shared_ptr<object::union_type>> cl(enclosing_class, "union_type", "");
        cl.def( pybind11::init( [](object::union_type const &o){ return new object::union_type(o); } ) );
        cl.def( pybind11::init( [](){ return new object::union_type(); } ) );
        cl.def_readwrite("boolean", &object::union_type::boolean);
        cl.def_readwrite("u64", &object::union_type::u64);
        cl.def_readwrite("i64", &object::union_type::i64);
        cl.def_readwrite("f64", &object::union_type::f64);
        cl.def("assign", (union object::union_type & (object::union_type::*)(const union object::union_type &)) &object::union_type::operator=, "C++: object::union_type::operator=(const union object::union_type &) --> union object::union_type &", pybind11::return_value_policy::automatic, pybind11::arg(""));
    }
}

error:
pybind11/pybind11.h: In instantiation of 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def_readwrite(const char*, D C::*, const Extra& ...) \
[with C = object::union_type; D = bool; Extra = {}; type_ = object::union_type; options = {std::shared_ptr<object::union_type>}]':
mytest.cpp:35:59:   required from here
python3.7m/pybind11/pybind11.h:1161:9: error: static assertion failed: def_readwrite() requires a class member (or base class member
)
         static_assert(std::is_base_of<C, type>::value, "def_readwrite() requires a class member (or base class member)");
         ^~~~~~~~~~~~~

edit - i compile with:
c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` mytest.cpp -o example`python3-config --extension-suffix`

Comment: Removed my answer as it was incomplete: &object::union_type is not a class member, like error tells you, &object::via is a class member
Comment: also, mind that pointer to member of union is not the same as a pointer to class member (which type is union in this case) so this won't compile
Comment: Okay thanks! Ya I'm not sure about 100% about the other code, this is just a small example to get this 'static_assert' error which is holding me back on a much larger project.
Answer: Based on general union question with polakovicp's suggestion there , you could apply:
 typedef union _union_type {
       bool boolean;
       uint64_t u64;
       int64_t  i64;
       double   f64;
   }union_type;

py::class_<union_type>(m, "union_type")
        .def(py::init<>())
        .def_property("boolean",
            [](union_type& self) -> const bool&
            {
                return self.boolean;
            },
            [](union_type& self, const bool& value)
            {
                self.boolean = value;
            });
        .def_property("u64",
            [](union_type& self) -> const uint64_t&
            {
                return self.u64;
            },
            [](union_type& self, const uint64_t& value)
            {
                self.u64 = value;
            });
        .def_property("i64",
            [](union_type& self) -> const int64_t&
            {
                return self.i64;
            },
            [](union_type& self, const int64_t& value)
            {
                self.i64 = value;
            });
        .def_property("f64",
            [](union_type& self) -> const double&
            {
                return self.f64;
            },
            [](union_type& self, const int64_t& value)
            {
                self.f64 = value;
            });


Firebase functions/firestore not working and catch returning an empty object

Question: I would just like to access my Firestore Database from within my Firebase Functions. I have tried to follow all the documentation and other stack overflow questions but still it is not working. Here is my code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.test = functions.https.onRequest((request, response) => {
  admin
    .firestore()
    .collection('users')
    .get()
    .then(querySnapshot => {
      const arrUsers = querySnapshot.map(element => element.data());
      return response.send(arrUsers);
    }).catch((error) => {
      // It is coming in here, and this below just returns '{}'
      response.send(error);
    });
});

What am I doing wrong?
Answer: The get() method of a CollectionReference returns a QuerySnapshot which "contains zero or more DocumentSnapshot objects representing the results of a query. The documents can be accessed as an array via the docs property or enumerated using the forEach() method".
Therefore you should do as follows, calling map() on querySnapshot.docs:
exports.test = functions.https.onRequest((request, response) => {
  admin
    .firestore()
    .collection('users')
    .get()
    .then(querySnapshot => {
      const arrUsers = querySnapshot.docs.map(element => element.data());
      //return response.send(arrUsers);  //You don't need to use return for an HTTPS Cloud Function
      response.send(arrUsers);   //Just use response.send()
    }).catch(error => {
      //response.send(error);
      response.status(500).send(error)   //use status(500) here
    });
});

Note the changes to the code for returning the response and handling the error. I would suggest that you watch this official Firebase video on HTTPS Cloud Functions: https://www.youtube.com/watch?v=7IkUgCLr5oA, it's a must!
Comment: Good answer! On `querySnapshot.docs.map(...` I keep making this mistake myself, since `QuerySnapshot` *does* implement `forEach()`, but *does not* implement `map()`.
Comment: I highly recommend this documentation when working with cloud functions. Great examples: https://googleapis.dev/nodejs/firestore/latest/index.html
Comment: Thank you very much! I think the important thing I missed was the `querySnapshot.DOCS` part. Also thank you for the extra links to learn some more! Stuff like this is always useful


Rotate latitude (y) tick labels - cartopy

Question: Is there a way to rotate the latitude tick labels in a cartopy map? I know it is a very easy and usual option in GIS programs such as QGIS, but I couldn't find anything on the subject when using cartopy.
Below there's a simple example (I plot my own shapefiles, that I don't express here):
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter

mapp = plt.subplot(111, projection=ccrs.PlateCarree())
mapp.set_extent([-44.2, -45.6, -23.36, -24.35])

mapp.set_yticks([-23.5,-24], crs=ccrs.PlateCarree())
mapp.set_xticks([-44.5,-45.5], crs=ccrs.PlateCarree())

lon_formatter = LongitudeFormatter(number_format='.1f')
lat_formatter = LatitudeFormatter(number_format='.1f')
mapp.xaxis.set_major_formatter(lon_formatter)
mapp.yaxis.set_major_formatter(lat_formatter)
plt.show()

It's not the best MCVE, but anyway, it shows the latitude tick labels horizontally -- that's a standard. My question is: is there a way to rotate the latitude tick labels (or the y tick labels) in 90° so they get vertical?
Comment: Can you edit your question to include a [MCVE](https://stackoverflow.com/help/mcve)? For your question that would be something like code that creates an example longitude coordinates in the way you have them, and whatever you mean by a "map frame", with details of what you want to transform those objects to.
Comment: @JeremyMcGibbon thanks for your income. Very helpful with beginners like me. The example I put is not the best, I adapted from my code, but it may clarify what I'm trying to say.
Answer: As a cartopy axes is just a special matplotlib axes, a lot of what you can do to a matplotlib plot, you can also do to a cartopy plot.
For rotating tick labels, there is an example in the matplotlib gallery.
So, to rotate your y tick labels you just need to add the following to your code:
plt.yticks(rotation='vertical')

I also noticed that your map extents are in the wrong order. The order should be
[x_min, x_max, y_min, y_max]

So your code should look like:
mapp.set_extent([-24.35, -23.36, -45.6, -44.2])

Comment: Thanks @ldreyer! I hadn't thought that way, cartopy being dependent on matplotlib's parameters. BTW, the set_extent is right, I switched the coordinates in the set_xticks and set_yticks lines. I corrected it in the question. Thanks again!


Getting error in Python 3.x : TypeError: 'int' object is not callable

Question: I'm new to programming. I've started with Python 3.x, learning from Python Crash Course. I encountered an error when I was trying an example program in the book.
Code is:
class Car():
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self):
        car_name = str(self.year) + ' ' + self.make + ' ' + self.model + 'model.'
        return car_name.title()
    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")

my_dream_car = Car('lamborghini', 'one-off', 2017 )
print("\nMy dream car is " + my_dream_car.get_descriptive_name())
my_dream_car.odometer_reading = 23
my_dream_car.odometer_reading()

Output:
Traceback (most recent call last):

  File "C:/Users/Jai/PycharmProjects/PCC/Chapter_9-Classes/4_car_class.py", line 18, in <module>

My dream car is 2017 Lamborghini One-Off Model.

    my_dream_car.odometer_reading()

TypeError: 'int' object is not callable

Process finished with exit code 1
Answer: You are setting the value of my_dream_car.odometer_reading to an integer and then you're calling it:
my_dream_car.odometer_reading = 23
my_dream_car.odometer_reading()

This is why you're getting TypeError: 'int' object is not callable because int is not something that you can call.
You probably meant to write:
my_dream_car.odometer_reading = 23
my_dream_car.read_odometer()


TypeError: list indices must be integers or slices, not str when using dictionary

Question: I have a dictionary as listed below:
test = {'time': 1634936741449, 'ticker':
[{
 'symbol': 'T',
 'value': '1',
 },{
 'symbol': 'DT',
 'value': '2',
 },{
 'symbol': 'SDT',
 'value': '3',
 },{
 'symbol': 'USDT',
 'value': '4',
 },{
 'symbol': 'N-USDT',
 'value': '5',
 },{
 'symbol': 'NKN-USDT',
 'value': '6',
 }]}

I am trying to print only specific variable which is value.
I tried the following print statement:
print(test["ticker"]["value"])

but i got this error
TypeError: list indices must be integers or slices, not str

I know i can do this by loops would be something like: print(test["ticker"][i]['value']) i tested this and it works, but i want a way without using loop.
The final output should be as following:
1
2
3
4
5
6

Comment: Cannot be done without (implicit) loop
Comment: this is what i thought but i shared this one hoping some could help.
Comment: you can do something on the lines of `map(itemgetter("value"), test["ticker])`
Comment: what does it mean by "itemgetter"
Comment: You could do `test["ticker"][0]["value"]`, `test["ticker"][1]["value"]`, etc... but why? You could get all of the values in a list `[ticker["value"] for ticker in test["ticker"]]`. That's a good way to do it, but its a loop. This is kinda a loopy thing.
Comment: is a function that you can import from operator "from operator import itemgetter"
Comment: @DaniMesejo - that's just hiding the loop in `map`.
Comment: @tdelaney I'm aware see my first comment.
Comment: @DaniMesejo - I'm aware that you are aware. I'm just making it explicit here in the comments that `map` loops. `map` is rarely useful - list comprehensions and generators are built into the language, no need for external functions like map.
Comment: Is there some reason to avoid looping?
Answer: To have the final output as required, without using an explicit loop, you could try:
mylist = list(map(lambda d: d['value'], test['ticker']))

print(*mylist, sep='\n')

Edit:
If you really want to avoid looping, you could do this trick to move to a Pandas DataFrame:
df = pd.DataFrame(test['ticker'])
mylist = df['value'].tolist()
print(*mylist, sep='\n')


subset list of multiple dataframe based on either row or column match

Question:
library(tidyverse)
library(dplyr)

list of data frames where some have matches to the vector and some don't
lsdf <- list(
  list1 = head(mtcars),
  list2 = as.data.frame(t(head(mtcars))) %>%
    rownames_to_column(., var = "ID"),
  list3 = head(starwars)
)

the vector of names that match to some dataframe
vec <- c("mpg", "wt", "am")

If I have to manually do it step by step this would be like this.
df1 <- lsdf$list1 %>% select(vec) # column-name matches
df2 <- lsdf$list2 %>% filter(ID %in% vec) # values in ID columns matches
df3 <- lsdf$list3 # No match found

out_lsdf <- list(
  df1 = df1,
  df2 = df2,
  df3 = df3
)

Is there a better and faster way to get the output desired below ?
out_lsdf
#> $df1
#>                    mpg    wt am
#> Mazda RX4         21.0 2.620  1
#> Mazda RX4 Wag     21.0 2.875  1
#> Datsun 710        22.8 2.320  1
#> Hornet 4 Drive    21.4 3.215  0
#> Hornet Sportabout 18.7 3.440  0
#> Valiant           18.1 3.460  0
#>
#> $df2
#>    ID Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout
#> 1 mpg     21.00        21.000      22.80         21.400             18.70
#> 2  wt      2.62         2.875       2.32          3.215              3.44
#> 3  am      1.00         1.000       1.00          0.000              0.00
#>   Valiant
#> 1   18.10
#> 2    3.46
#> 3    0.00
#>
#> $df3
#> # A tibble: 6 x 13
#>   name  height  mass hair_color skin_color eye_color birth_year gender homeworld
#>   <chr>  <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr>  <chr>
#> 1 Luke~    172    77 blond      fair       blue            19   male   Tatooine
#> 2 C-3PO    167    75 <NA>       gold       yellow         112   <NA>   Tatooine
#> 3 R2-D2     96    32 <NA>       white, bl~ red             33   <NA>   Naboo
#> 4 Dart~    202   136 none       white      yellow          41.9 male   Tatooine
#> 5 Leia~    150    49 brown      light      brown           19   female Alderaan
#> 6 Owen~    178   120 brown, gr~ light      blue            52   male   Tatooine
#> # ... with 4 more variables: species <chr>, films <list>, vehicles <list>,
#> #   starships <list>

Created on 2020-02-07 by the reprex package (v0.3.0)
Comment: Is it `lsdf <- list(lis1 = head(mtcars) %>% rownames_to_column("ID"), list2 = as.data.frame(t(head(mtcars))) %>% rownames_to_column("ID"), lisst3 = head(starwars) %>% rename(ID = name))`
Comment: It is not clear to me what you are trying to do? How do you decide when to filter rows or when to select columns?
Comment: If the vector names are part of column names, I select them. If vector names are part ID column, I filter them. If none, I don't do anything.
Answer: We can do this with a condition to check
library(purrr)
library(dplyr)
map(lsdf, ~ {nm1 <- names(.x)
      if("ID" %in% nm1)  .x %>%
                   filter(ID %in% vec) else if(any(nm1 %in% vec))
       .x %>% select(intersect(nm1, vec))
 else .x
 })

We could also call the if/else conditions within select/filter
map(lsdf, ~ .x %>%
                select(if(any(names(.) %in% vec))
                   intersect(names(.), vec) else everything()) %>%
                filter(if('ID' %in% names(.)) ID %in% vec else TRUE))


echo output not getting assigned to a variable in shell script

Question: end=echo $FSDB_FILE_NAME | rev | cut -d'_' -f 2 |rev
begin=echo $FSDB_FILE_NAME | rev | cut -d'_' -f 3 |rev
echo $end
echo $begin

echo abc_11204.00_15713.00_.csv  | rev | cut -d'_' -f 2 |rev ---- This works

But echo $end is not printing anything
I even tried:
 set end=echo abc_11204.00_15713.00_.csv  | rev | cut -d'_' -f 2 |rev
 echo $end

This prints empty
Please help me with this
Sample input : abc_123.00_345.00_xyz.csv
Output : end=345.00
         begin=123.00

Comment: Good that you have shown your efforts by showing your code. Could you please simply add sample of input and expected output in your question and let us know then.
Comment: I am pretty sure once you add samples of input and expected output we could do it in a single command and could do in better approach too.
Comment: Samples added , please suggest a solution @RavinderSingh13
Answer: Could you please try following. Easy approach with awk.
start=$(echo "$input_variable" | awk  -F'_' '{print $2}')
end=$(echo "$input_variable" | awk  -F'_' '{print $3}')

When I print variable's values it will be as follows:
echo "$start"
123.00
echo "$end"
345.00


Node.js - PUT with 'request' module

Question: I am using the request module in Node.js to do a put request.  My code looks like this
var request = require('request');
var data = {foo: "bar", woo: "car"};

request({
   method: 'PUT',
   uri: myURL,
   multipart: [{
       'content-type':'application/json',
       body: JSON.stringify(data)
   }]
}, function(error, request, body){
   console.log(body);
});

When I run this I get an error:
"Unsupported content with type: application/json"
Answer: Just try it like this:
request({ url: url, method: 'PUT', json: {foo: "bar", woo: "car"}}, callback)
Comment: headers is just a nested JSON in the options JSON.
Comment: And where would I include headers?
Comment: what about a put request with a file upload?

Node.js - PUT with 'request' module


Can I have both a main account and a "smurf" account linked to my Steam account?

Question:
In League of Legends, some players make "smurf" accounts, which are typically lower-levelled or lower-ranked accounts to play on instead of a main account. Is there a good reason for creating a smurf account in DotA 2?
If so, can I have two DotA 2 accounts on one Steam account, or do I have to use a separate Steam account?
Comment: How is this to broad? Look at the answer... The questions are clearly highly linked to each other, the second one is merely the obvious follow-up to the first one, which itself does have such an obvious answer that is hard to justify as an own question.
Comment: If you have more than one question, create more than one question!
Comment: I could see the point if there was actually a multitude of reasons for creating a smurf account, but would still disagree because he's only interested in whether or not there is a reason at all. So the answer would either say "there's not" or "there is". Realistically, there can't be many reasons, so the amount of possible answers is reasonable.
Comment: I think poor wording led to massive down votes. Honestly though, this is not a bad question at all.
Answer:
You can make a smurf account to relive the MMR determination phase of a player. Afterwards, you'd probably go back to what you are in your first account. Another reason can be if you don't want your first account identity to be discovered when you want to play some particular play that are typically frowned upon.
You can only have 1 DOTA2 account per Steam account as it is tied to each other. You can make another Steam account, however, to make a smurf account for DOTA2.


How do I use the current Angular 2 version from Git (with npm)?

Question: I am currently following Angular 2 development, which means that I am using dependencies such as
"@angular/common": "2.0.0-rc.4",
"@angular/compiler": "2.0.0-rc.4",
…

in package.json. Given that there are some helpful fixes in Git already I would like to install the most recent version (or some specific commit) from Git. What is the easiest way to achieve this?
It would be preferable to avoid having to build Angular locally, but if necessary this would be acceptable, too.
Answer: You could reference angular cdn from your systemJs config.
something like:
    @angular:                   'https://npmcdn.com/angular2'
then removing the dependency from the package.json
there is an example in this plunker
//map tells the System loader where to look for things
var  map = {
  'app':                        'app',
  '@angular':                   'https://npmcdn.com/@angular', // sufficient if we didn't pin the version
};

the version is specified in a variable but maybe there is something like /latest


Eval vs web console

Question: I always hear and read "Eval is evil" if you evaluate user-generated code.
But where is the different from typing code into the web console? And what are the alternatives?
I know the web is full of questions like mine. But I wasn't able to understand what I read, I'm sorry. It would be great if you could help me. I remember I read something about scopes, so have eval() and the web console different scopes? If yes, why does that make the web console safer?
Thanks for your advice!
Darth Moon

Edit: Why is passing code through the web console / through eval dangerous at all? I though js will be executed client-side?
Comment: Typing code into the console is more evil than using `eval`. Though, if you know what you are using them for, then they are absolutely harmless.
Comment: Good point, code from the server should always get evaluated since it's mine. But what is with __user-generated__ javascript? Like if I have an online coding editor? How do I execute that code as safely as possible?
Answer: Neither are safe to execute code in; both can lead to XSS attacks.The web console is just as vulnerable in this regard as eval'd code.
However, they do indeed have different scopes.
eval() works in either the global scope or local scope depending on how it's invoked:

If you use the eval function indirectly, by invoking it via a reference other than eval, as of ECMAScript 5 it works in the global scope rather than the local scope. This means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called.

And the web console executes code in the page window scope.
What's interesting to note is that the Browser Console has a different scope to the Web Console, running under the browser's chrome window:

Similarly, you can execute JavaScript expressions using the Browser Console. But while the Web Console executes code in the page window scope, the Browser Console executes them in the scope of the browser's chrome window.
Comment: But if the web console is as evil as eval, how do I avoid people typing bad code in the console?
Comment: @DarthMoon The oly person who can type code into the console is you. The console is evil only if you type code there that you don't understand, code that c.ould be malicious.
Comment: Also the console provides more tool that are meant for debuging which makes typing code there a lot more evil than `eval`
Comment: Thanks, this absolutely answers my question. I marked it as an accepted answer. However, I would like to know how to execute user-generated code as safely as possible and how to avoid people running bad code through the web console
Comment: @ibrahimmahrir What do you mean? __I__ am able to use the web console with _any_ website I want to. I even could pass js in the google.de page scope, it wan't be a big different since js is client-side and the code gets executed on my own device
Comment: @DarthMoon Possible scenario of how the console might be evil: you found online some code that's supposed to hack any facebook account, the poster of the code instruct you to open the web console on a facebook page that you want to hack and then copy-paste the code there and press enter. You read the code but didn't understand it, yet you did as told. The code is malicious and its poster posted it so people will be hacked if they did as told. Facebook even warns you from doing that [when you open the web console](https://i.stack.imgur.com/3k6Is.png). Try opening it on a facebook page!
Comment: @DarthMoon Bottom line: if you don't know what you're typing into a web console, don't do it. If you don't know what you're passing to eval, don't do it. Also you can use `eval` to evaluate users code on the(ir) client-side. It absolutely their problem. They won't affect you in any way. If they are not carefull enough to just copy-paste code they don't understand into the web code editor on their computer, then its their problem if that code turns out to be malicious. You could add warnings and sanitize the code as much as you can, but it's their problem.
Comment: Yeah, that's a big different. So there's no way to "hack" my application with the web console if my server script (if I have one) doesn't exactly uses the javascript. I can't describe it better, so here's an example: I've got a multiplayer game. With js (and via Websockets) I told the server whenever I go and the server makes the move. That would be something like safe. But if js sent the exactly position I moved to, then every stupid nerd would be able to change his position with the web console. This means, if the server does all the important stuff, bad js won't affect me?
Comment: So I can understand that in general using eval() is not different than the console code? Any user can open the console and type whatever he/she wants... Right?

Eval vs web console


How to structure data to easily build HTML tables in Flask

Question: I am trying to create HTML tables from data stored in a table. My data is read from a table and converted into a dict of lists, e.g.:
x = {'date':[u'2012-06-28', u'2012-06-29', u'2012-06-30'], 'users': [405, 368, 119]}

My goal is to create an HTML table with the following structure for an arbitrary list length:

    Date
    Users

      2012-06-28
      405

      2012-06-29
      368

      2012-06-30
      119

I have tried doing this two incorrect ways in my Flask template:

  {% for line in x %}

      {{ x.date|tojson|safe }}
      {{ x.users }}

   {% endfor %}

Which prints the entire list into each column.
And:
{% for date in x.date %}

{{ date|tojson|safe }}

{% endfor %}

{% for users in x.users %}

{{ users }}

{% endfor %}

Which simply prints everything into the first column.
These experiments and many other dead ends lead me to believe that there is no simple way to build the table as I would like given my current data structure.
Given this, I have two questions:
1) How would I go about building the table using my current data structure?
2) What is the standard or ideal way to structure data for this use case?
Thanks in advance.
Answer: Like you said, you could either change your data structure, or change your template code. Here is one way to keep the current structure:
{% for row_index in range(x['date']|count) %}

      {{ x[row_index]['date']|tojson|safe }}
      {{ x[row_index]['users'] }}

{% endfor %}

Or you could restructure your data in python:
x = zip(x['date'], x['users'])

And then use this template:
{% for row in x %}

      {{ row[0]|tojson|safe }}
      {{ row[1] }}

{% endfor %}

You can also structure the data so that the template does not depend on the order of the cells:
from itertools import izip
x = [dict(date=d, user=u) for d, u in izip(x['date'], x['users'])]

Then you can access your data like this:
{% for row in x %}

      {{ row['date']|tojson|safe }}
      {{ row['user'] }}

{% endfor %}

Comment: Yep. Flask uses Jinja2 for its templates, so you can use anything from http://jinja.pocoo.org/docs/templates/#builtin-filters.
Comment: This is great, thank you. Before I accept, can you point me to some documentation for those pipe commands? Didn't realize there were more of them.
Answer: You might use Flask-Table or for something more complex even leverage Flask-Admin.
Answer: Yeah, you really want to use a list of dictionaries instead of a dictionary of lists, that works out better with Jinja2


Availability of PHP 7.2.21?

Question: Does anyone know when PHP 7.2.21 will be available - looking for fixes for CVE-2019-11041 and CVE-2019-11042.
Answer: PHP 7.2.21 Released

PHP 7.2.21 Release Announcement
The PHP development team announces the immediate availability of PHP
7.2.21. This is a security release which also contains several minor bug fixes.
All PHP 7.2 users are encouraged to upgrade to this version.
For source downloads of PHP 7.2.21 please visit our downloads
page.

How do I install a .tar.gz (or .tar.bz2) file?

Availability of PHP 7.2.21?