Wall sound proofing - hanging rows of sound proof "curtains"

Question: The building's structure is concrete, as is the floor/roof. The wall to my neighbor is brick; so a lot of noise comes through - TVs, crying babies etc.
I've seen a number of options for constructing various wooden frames with layers of sound insulation; but am wondering if just hanging "curtains" of sound isolation foam could work well. The wall in question is pictured below, and the columns on each side are concrete. Discussions of wooden frames have various approaches to decoupling the sound isolation from the wall being soundproofed - and using curtains seems like a good way to tackle this to me.
Of course; if I ever wanted to use the wall as a wall; I would need a final frame + drywall; but there is enough space to put these on the outside of the concrete pillars.
Any thoughts; comments; suggestions welcome

Thanks
Brent
Answer: Sound isolation foam doesn't work like that. It's designed to remove reverb, not block sounds. What you want are "soundproof curtains". These are designed to be heavy curtains that can actually block sound. Basically anything else with mass will have similar effects, but these are a good way to block off the entire wall. You mount them the same way you would mount regular curtains, though with more attention paid to weight. If you have a bunch of books, sticking your bookcases against that wall would also help.
Doing this correctly basically involves opening up the wall and decoupling your apartment from your neighbor's. I'll assume that isn't an option.
Comment: Thanks!
When I say sound isolation foam; I had in mind products similar to https://www.amazon.com/12-Acoustic-Panels-Studio-Wedges/dp/B00TP7C9YY/ref=bmx_1/135-9219536-4801510?_encoding=UTF8&pd_rd_i=B00TP7C9YY&pd_rd_r=16f2aee4-82c4-4164-839c-3dffbe366dbd&pd_rd_w=3USe6&pd_rd_wg=UvFfc&pf_rd_p=806524e0-5994-4c0d-9d36-11f6132400bc&pf_rd_r=ZBN2WKQB1HT03R9W94K7&psc=1&refRID=ZBN2WKQB1HT03R9W94K7 so are these unlikely to perform well at blocking sound?
Comment: Would https://www.amazon.com/dp/B008JHE1P6/ref=psdc_11975721_t4_B07FK5JYRN be good for curtains? Would attaching directly to the wall; or hanging just in front have different sound damping performances?
Comment: Acoustic panels/foam wedges are useless for soundproofing; don't bother with them. Mass loaded vinyl is actually useful, though usually mounted inside the wall. Not sure if they're suitable for wall-mounting. Acoustic curtains or soundproof curtains would look better if that's a consideration, though are more expensive.
Comment: If you have a choice, I'd mount your soundproofing material loosely, though it's more important that there aren't gaps around the outside or between sections.


In ASP.NET MVC, can I automatically model bind to a JObject from the POST body?

Question: I have a controller action that takes a JSON document as the body of a POST request. I'd love to automatically create a JObject from that, via model binding, like this:
[HttpPost]
public ActionResult Index([FromBody] JObject data)
{
  // "data" is now a populated JObject object
}

But I get errors about not creating an abstract class. I tried to extend something from JObject, but it wouldn't do that either.
I know I can just read the body of the request and call JObject.Parse on it (I'm doing this, so it does work), but my idea from above seems so much more elegant.
Is this possible?
Edit: The actual error is:
System.MissingMethodException: Cannot create an abstract class.
[MissingMethodException: Cannot create an abstract class.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
[Stack trace continues...]

The request never gets into the controller action.
Based on my research JObject isn't abstract, but just to be sure, I did this:
public class Entry : JObject

Then
public ActionResult Index([FromBody] Entry data)

Didn't work. Same error.
Comment: Is your document's json of type JObject?
Comment: `JObject` is just a generic object for holding JSON of any type. Kind of like `XmlDocument` holds XML of any type. This is from the `JSON.Net` library.
Comment: Is `FromBody` something you have created?
Comment: No. https://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
Comment: To me it seems that should work . what exactly is the error?
Comment: Updated question with error.
Comment: can you clarify whether you're using ASP.NET MVC, Web API, or ASP.NET Core MVC?
Answer: You should also put the structure of the JSON in your question. The full request would be better. Until then, try the following:
replace [FromBody] JObject data with [FromBody] dynamic data or [FromBody] object data
and see if it hits a breakpoint put on the first line of the action.
If it does, see what your dynamic actually is (type).
If it does not, maybe the POST request does not have Content-Type: application/json
Comment: The last sentence in this answer helped me solve it. See my answer.
Comment: Glad to hear this :)
Answer: There might have been two problems. I changed two things, and it works now, but I'm not 100% sure which one fixed it.
Here are both things I changed --
First, I inherited from ApiController instead of just Controller.  I'm not sure if this had anything to do with it.
Second, one of the other answers pointed out that I needed to have the correct Content-Type header of application/json. Well, it wasn't. The Content-Type header was set to some wild value specific to the software we're integrating with.
So, in Application_Start, I added this:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("[crazy ass content-type header value]"));

And then it worked.
I suspect it was the second thing that fixed it. Since the header didn't tell the model binder it was incoming JSON, the binder was trying to create a JObject object from scratch and assign properties via reflection which ran into problems with JToken being abstract. Once it knew it was dealing with JSON, it knew to just call JObject.Parse instead.
Answer: I've written a ASP.NET Core ModelBinder for JToken which you can install - https://github.com/mcintyre321/AspNetCoreJTokenModelBinder
Bind to JToken, then use .ToObject<T>() in your controller
Answer: The issue is that at some point when deserializing to type JObject, it calls to create a `JToken' and that is where the exception is thrown. Here is the exact exception:

Cannot create an abstract class. Object type
  Newtonsoft.Json.Linq.JToken


When fitting 3d cuboids into a box, how to find the order of drawing (in a 2D projection) so that the cuboids don't appear to overlap?

Question: I am working on a 3D packing algorithm (MIT-licensed). The box and the cuboids it contains are displayed as a 2D projection. The order of drawing the cuboids (now represented as polygons) is important: a cuboid placed at the back of the box must not be drawn after the cuboids in the front row. I am currently using order by(cuboid.X + cuboid.Y + cuboid.Z) and it works around 99% of the time, but not always. Some aberrations do ocurr, as depicted below. I have tried multiplying the coordinates, and order by X then by Y then by z, and other combinations. Adding the coordinates is the one that gave the best result. POV-ordering has been suggested, but it won't work, as illustrated by the second diagram.  Can someone enlighten me?
Comment: I assume that using a depth buffer is off the table, right?
Answer: Let's get our orientation straight first. When I speak of a direction, I mean the direction relative to our viewpoint. So the "front" face of a cuboid is the face nearest the camera; "back" means the face pointing away from the camera. The "left" face of a cuboid is the face pointing to the left from the camera's view.
A cuboid X is in front of cuboid Y if one of the following is true:

The back face of X is in front of the front face of Y
The left face of X is to the right of the right face of Y.

If either of these is true, then Y should be drawn before X. This is how you build your sort order. If one of the above is true, then Y should be "less than" X and thus come earlier in the sort.
Note that this algorithm assumes exact math is used to compute the faces of the cuboids for comparison purposes. If you're using floating-point math, you may encounter precision issues that cause problems.


Creating A Strut To The Center Of The Screen

Question: I have three views that are in a horizontal line. The middle view is centered horizontally while the other two are the same distance away, one to the left and one to the right.
When I rotate the screen to landscape, I want the middle view to stay centered horizontally, and I want the other two views to stay the same distance away from the center.
Is there an easy way to do this in Xcode?
Comment: are you using interface builder or are you creating your interface with code?
Comment: A little of both. I have a placeholder to make setting the frame and autoresizing mask easier, but I am adding an imageview from code. I am using interface builder for the struts right now.
Answer: This is harder to do with springs & struts and setting the frame, and is simpler to handle with Auto Layout constraints, if you can use those in your app. See this video from Justin Williams for a good overview of why.
If you need to stick with springs & struts and setting the frame in code, for some reason, you'll have to recompute the center of the super view, and then use that to set the .center of your subview.


How to know if Squid Proxy is doing the Cache correctly

Question: I wanted to test if the Clients attached to a Squid Server are actually using the Cache data instead of going directly to the internet and retrieving the data. I have configured all clients browsers to read the Server:Port from the Squid Server (Which is 10.42.0.1:3128). So how do I know if they are retrieving the information from the Cache or the Internet.
I asked since a quick "test" gave me the same speed when loading several pages that had many images on them. Same images and not ads that change on every visit.
What ways can I use to check if they are using the Cache?
I ran the following: sudo tail -f /var/log/squid3/access.log and got several lines that kept on scrolling:
1374553166.136    929 188.8.131.52 TCP_MISS/200 28198 GET http://www.amazon.de/gp/offer-listing/B000NOIW62/ref=sr_1_1_olp? - DIRECT/18.104.22.168 text/html

They had a TCP_MISS/200 and at the end had a DIRECT as the example above. This happened while I had all computers in the LAN turned off. When I tried to used one I got the following doing a sudo tail -f /var/log/squid3/access.log | grep HIT
1374553387.488      0 10.42.0.14 TCP_IMS_HIT/304 278 GET http://g-ecx.images-amazon.com/images/G/01/da/creatives/sn130.png - NONE/- image/png

So it shows as TCP_IMS_HIT/304 and at the end it shows a NONE
So what does the TCP_MISS, DIRECT, TCP_IMS_HIT and NONE mean?
Is the cache working?
Answer: in a terminal, on the server running squid, run the command
tail -f /var/log/squid3/access.log

then watch it as a user visits web pages.  If lots of lines scroll up the screen whenever they click on something then they are using the proxy server.  If the squid log file is not located there have a look in /etc/squid for the location of the log file.
To quit out of the above command press ctrl+c
To see if it is actually caching stuff and being useful there should be some lines that say it is a HIT.  To see a full description of the log file contents see the squid wiki. Note that cache HITs will not be as frequent as you'd like due to an individual user's web browser already caching stuff locally.  You will get the most hits when multiple users request the same pages before that info is dropped from the cache.
Such as when an allstaff email goes out saying "check this site out..."

TCP_MISS/200 means that the requested document was not in the cache but it could fetch it OK from the web server.  The direct at the end says that the file was fetched from the webserver.
TCP_IMS_HIT/304 means that the client asked if the file has changed, and squid checked its date/time on the webserver and found it had not changed, so it gave a copy of the file to the client out of its local cache.

So yes your squid is being used and is working as a cache.
Comment: Updated question to see if you can help further.
Comment: @Luis Alvardo updated answer to help further.


MySQL - Can you query to get last update for a table?

Question: Is there a way to query a MySQL table and get the last date when anything was done, either insert/update/delete was performed without querying the rows themselves? Or do I have to manually track that?
Comment: possible duplicate of [How can I tell when a MySQL table was last updated?](http://stackoverflow.com/questions/307438/how-can-i-tell-when-a-mysql-table-was-last-updated)
Answer: You have to manually track that. There are ways to get the query log, but is for administration.
For example, using your innodb binary log.
Comment: Not true. http://stackoverflow.com/questions/307438/how-can-i-tell-when-a-mysql-table-was-last-updated
Comment: @MattBall You're right. Didn't know that. Anyway, i'd use that inside of a webapp, becouse you would have to allow access to information_schema, and would be a huge security risk. So, rewriting my answer: "for simplicity, you have to manually track that"
Answer: that's not something native to MySQL. Your options are either the binary log which only tracks committed changes or by turning on the general log and using that as a point of audit. The general log is extremely vebose - it will log everything, selects, updates, inserts and deletes and even if they're not successful or committed changes. The binary log would be my recommendations too.


How are PE Base Relocations build up?

Question: I'm currently having trouble understanding how PE Base Relocations are build up.
I understand there can be more then one relocation, I understand also why and how this is done, but I just don't understand it programmatically:
Which of the following is true (IMAGE_BASE_RELOCATION in WinNT.h)?
// Base relocation #1
DWORD   VirtualAddress;
DWORD   SizeOfBlock; // size of current relocation
WORD    TypeOffset[1];
// Base relocation #2
DWORD   VirtualAddress;
DWORD   SizeOfBlock; // size of current relocation
WORD    TypeOffset[1];
// Base relocation #3
DWORD   VirtualAddress;
DWORD   SizeOfBlock; // size of current relocation
WORD    TypeOffset[1];

Or
DWORD   VirtualAddress;
DWORD   SizeOfBlock; // size of all relocations
WORD    TypeOffset[1]; // relocation #1
WORD    TypeOffset[1]; // relocation #2
WORD    TypeOffset[1]; // relocation #3

Or are both incorrect? How must I loop through all base relocations programmatically?
Currently I have this code, seems to be incorrect somewhere:
DWORD baseRelocationSize = imageNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
            unsigned int baseRelocationCount = baseRelocationSize / sizeof(IMAGE_BASE_RELOCATION);
            DWORD baseDelta = (DWORD_PTR)moduleBase - (DWORD_PTR)imageNtHeaders->OptionalHeader.ImageBase;

            IMAGE_BASE_RELOCATION* baseRelocation = (IMAGE_BASE_RELOCATION*)((DWORD_PTR)moduleBase + (DWORD_PTR)imageNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress);

            for(unsigned int i = 0; i != baseRelocationCount; ++i)
            {
                unsigned int entryCount = (baseRelocation->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD);

                for(unsigned int j = 0; j != entryCount; ++j)
                {
                    WORD* entry = (WORD*)((DWORD_PTR)baseRelocation + (DWORD_PTR)sizeof(IMAGE_BASE_RELOCATION));
                    if((*entry >> 12) & IMAGE_REL_BASED_HIGHLOW)
                    {
                        DWORD* pdw = (PDWORD)((DWORD_PTR)moduleBase + (DWORD_PTR)baseRelocation->VirtualAddress + ((*entry) & 0xfff));
                        (*pdw) += baseDelta;
                    }

                    entry++;
                }

                baseRelocation += baseRelocation->SizeOfBlock;
            }

Comment: Relocations are ridiculous, nobody seems to know the correct way to handle them.
Comment: It's a tricky one, right?
Comment: @JohnSmith did you figure this out?
Answer: Neither options you indicated entirely correct/true.
This excellent tutorial on How to inject code in a PE file shows that the actual IMAGE_BASE_RELOCATION structure is:
typedef struct _IMAGE_BASE_RELOCATION {
  DWORD   VirtualAddress;
  DWORD   SizeOfBlock;
} IMAGE_BASE_RELOCATION, *PIMAGE_BASE_RELOCATION;

Section 5.2 of this Microsoft Portable Executable and Common Object File Format Specification describe the structure. The SizeOfBlock-8 actually indicates how many WORD TypeOffset follow after the VirtualAddress and SizeOfBlock.
I think you would also be interested in Table 7 of the tutorial, which shows the structure of the blocks from the relocation table. I'll copy-paste the table here for quick-reference.
Comment: The number of block is not written anywhere. What I do is go block by block until the current address is equal to `imageNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress + imageNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size` at this point you know that you're at the end of the `.reloc` section
Comment: This is just perfect. One last question, how do you know how many blocks there are?
Comment: Just to be 100%, when you say `"The SizeOfBlock-8 actually indicates how many WORD TypeOffset follow after the VirtualAddress and SizeOfBlock"` you should say `"The (SizeOfBlock-8) / sizeof(WORD) actually indicates how many WORD TypeOffset follow after the VirtualAddress and SizeOfBlock"`. Correct me if I'm wrong.
Comment: I checked the link you posted. Really the best description i found on the internet. Though i have one question. If i got the asm part inside the link right, the sizeOfBlock field includes the padding 00 00 in the end of the block right? Eventhough its not really an entry. Furthermore the 00 00 part only exists to pad the array of entries to 32bit and thus does not have to exist in every block right?
Answer: from some code.. aldo check out reactos :)
BOOL FixRelocs(void *base, void *rBase, IMAGE_NT_HEADERS *ntHd, IMAGE_BASE_RELOCATION *reloc,
               unsigned int size) {
    unsigned long ImageBase = ntHd->OptionalHeader.ImageBase;
    unsigned int nBytes = 0;
    unsigned long delta = MakeDelta(unsigned long, rBase, ImageBase);
    unsigned long *locBase;
unsigned int numRelocs;
unsigned short *locData;
unsigned int i;

while(1) {
  locBase =
     (unsigned long *)GetPtrFromRVA((DWORD)(reloc->VirtualAddress), ntHd, (PBYTE)base);
  numRelocs = (reloc->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD);

  if(nBytes >= size) break;

  locData = MakePtr(unsigned short *, reloc, sizeof(IMAGE_BASE_RELOCATION));
  for(i = 0; i < numRelocs; i++) {
     if(((*locData >> 12) == IMAGE_REL_BASED_HIGHLOW))
         *MakePtr(unsigned long *, locBase, (*locData & 0x0FFF)) += delta;
     locData++;
  }

  nBytes += reloc->SizeOfBlock;
  reloc = (IMAGE_BASE_RELOCATION *)locData;
   }

   return TRUE;

}

How are PE Base Relocations build up?


How can install a new version of NPM ( 1.1.24 )?

Question: I want to install the latest stable version of node - Version 0.6.19 (stable).
http://blog.nodejs.org/ indicates to upgrade to NPM to 1.1.24
Is there a simple way to upgrade to this? I can't figure out how exactly to download and target this version.
The below gives me npm -v 1.0.106
npm upgrade npm

or
npm upgrade npm 1.1.24

Comment: It would be nice to know which OS you are using. When installing node from the source you always get the most current npm installed aside.
Answer: Update 2 (03/11/15)
Courtesy: whyleee

On Windows npm is installed together with node in "Program Files". Use npm install npm -g to install it in "%AppData%\npm" and delete 'npm', 'npm.cmd' files from "C:\Program Files\nodejs" dir (because your PATH is looking there first). After that you can use npm update npm -g in the future

According to the docs
For windows (it also worked on Mac for me)
To update npm, run the npm update npm -g command.
Also verify this
Hope this helps
Comment: On Windows npm is installed together with node in "Program Files". Use `npm install npm -g` to install it in "%AppData%\npm" and delete 'npm', 'npm.cmd' files from "C:\Program Files\nodejs" dir (because your PATH is looking there first). After that you can use `npm update npm -g` in the future.
Comment: This didn't work for me on windows. The command completed without output, but the version remains the same.
Comment: Yeah, right, probably OPs problem is `upgrade` instead of `update` and missing `-g` flag.
Comment: Refusing to delete: /usr/local/bin/npm not in /usr/local/lib/node_modules/npm
Answer: The only thing that worked for me was (from npm readme)

Fancy Windows Install
You can download a zip file from https://npmjs.org/dist/, and unpack
  it in the same folder where node.exe lives.

In my case folder is :

C:\Program Files (x86)\nodejs

Edit: It seams that newer versions of npm does not exist on address I wrote. I will copy paste instructions from npm git page

You can download a zip file from https://npmjs.org/dist/, and unpack
  it in the same folder where node.exe lives.
The latest version in a zip file is 1.4.12. To upgrade to npm 2,
  follow the Windows upgrade instructions in the npm Troubleshooting
  Guide:
https://github.com/npm/npm/wiki/Troubleshooting#upgrading-on-windows
If that's not fancy enough for you, then you can fetch the code with
  git, and mess with it directly.
Comment: Thanks, this is all that worked for me on Windows as well.  I guess I should have read the readme...
Comment: http://nodejs.org/dist/npm/ doesn't seem to have the latest version anymore. It has 1.4.12 while the nodejs-package has npm version 1.4.14. Whats up with that?
Answer: In ubuntu you can upgrade it using
sudo npm update npm -g

Answer: In windows, to install latest version of npm

npm install npm@latest -g

&
In ubuntu you can use

sudo npm install npm@latest -g

*note: the latest version till sept 12 2016 is
(The current stable version of npm is) 3.10.7
check  version by running on command prompt

npm -v
Answer: https://github.com/npm/npm/wiki/Troubleshooting#upgrading-on-windows

Option 3: navigate to C:\Program Files (x86)\nodejs with cmd.exe and then run the installation without -g:

This sovled it for me.


What happens if you choose GLaDOS' way in Portal 2?

Question: Spoiler warning!
During the first escape attempt in Portal 2 (when GLaDOS is still in charge) she opens a door for you which you can choose to go through instead of following Wheatley (the blue-eyed ball). What happens if you go there?
Comment: Related activity : When Wheatley says 'come back' to you, go back.
Comment: Here's a related question: http://gaming.stackexchange.com/questions/20434/is-there-any-way-to-escape-the-good-listener-room
Answer: GLaDOS closes the door and the wall. Then she fills the room with a deadly neurotoxin and you die.
Here's a video showing that scene:
Comment: I just wanted to see the deer
Comment: And you get an achievement, so worth it.
Comment: I did this the first time I played - I am so weak!
Comment: @Juan Manuel: It's a beautiful day out. Yesterday I saw a deer. If you come back, we can ride an elevator all the way up to the break room, and I'll tell you about the time I saw a deer again.
Comment: @TheAnnoyingPyro I didn't see the deer today, but I did see some humans. But with you here I have more test subjects than I'll ever need.
Comment: I did this on my second playthrough, not realizing it was "wrong".  After having done it "properly" on the first one.
Comment: You need to step on the button before you die.


How to properly sub class React native webview to disable the context menu on selection?

Question: I need to disable the default context menu, that pops up when some text is selected in the react-native-webView.
I forked the library and added a new MyWebView.h and MyWebView.m files to try and disable the selection action.
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    return NO;
}

Then inside RNCWebView.m file, I made the following changes:

In the implementation block of RNCWebView, I instantiated my custom webview as
  @implementation RNCWebView

  {
     MJRWebView *_webView;
     (other code here)
  }

Then inside initWithFrame, I am doing the following:

 - (instancetype)initWithFrame:(CGRect)frame
  {
     if ((self = [super initWithFrame:frame])) {
     super.backgroundColor = [UIColor clearColor];
     _webView = [[MJRWebView alloc] initWithFrame:self.bounds];
     (other props)

The selection got disabled, but other props like onMessage and injectJavascript stopped working. Is this the correct way of disabling the context menu ?
Answer: The RNCWebView is a WKUIDelegate, as below from declaration
@interface RNCWebView () <WKUIDelegate, ...

so you just need to create a subclass of RNCWebView and add the only following
- (void)webView:(WKWebView *)webView contextMenuConfigurationForElement:(WKContextMenuElementInfo *)elementInfo
   completionHandler:(void (^)(UIContextMenuConfiguration * _Nullable configuration))completionHandler
{
   completionHandler(nil);
}

and use your subclass.
Comment: @Asperi Can you please elaborate what you meant by using subclass ? What I did previously was replace code inside RNCWebview.m itself with my custom subclass of WKWebView. Did you mean all of that is not necessary ?
Comment: Thanks @Asperi.
So, there is no need of
```- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    return NO;
}```
Comment: Subclass? Hmm... `@interface MyRNCWebView: RNCWebView`. No, all of that not needed. At least to disable context menu.
Comment: Actually what I did in was MyWebView.h was `@interface MJRWebView :WKWebView` and not from `RNCWebView` as I was modifying the code within the package `react-native-webview`, which itself extends WKWebView. Then I used it inside `RNCWebView.m`. I don't know if I can use `@interface MyRNCWebView: RNCWebView` within the same package.
Comment: Ok, then just add callback from answer into `@implementation RNCWebView` of RNCWebView.m. And don't forget to remove all your previous modifications - they are not needed for this purpose.
Comment: Add
```
- (void)webView:(WKWebView *)webView contextMenuConfigurationForElement:(WKContextMenuElementInfo *)elementInfo
   completionHandler:(void (^)(UIContextMenuConfiguration * _Nullable configuration))completionHandler
   completionHandler(nil);
}
``` to the @implementation?


Blender killed outlet?

Question:
tl/dr: It seems a finicky blender killed my outlet - My blender initially turns on but then stops after a moment, and won't turn back on.  I plugged a night light into one plug and it turns on initially but then turns off once inserted fully.  The night light works fine in the other plug.  The blender doesn't work properly in either plug.  Do I just need to replace my outlet?

The incident
I had some trouble with my blender: I accidentally broke part of the lid, and it is one of those blenders that has built in "catches" to make sure it doesn't run without the lid on correctly.  I already had my food in so I attempted (with some success) to continue blending anyway.  However, the blender was finicky and kept turning off despite my efforts.  Eventually it stopped turning on altogether.  I figured the blender just didn't appreciate my efforts and switched blenders (the other one wasn't ideal for my meal, which is why I didn't try it sooner).
The Symptoms
A bit later I realized that, in fact, the whole outlet was acting wonky.  Namely, the other blender also had trouble with it.  It initially turned on, but then stopped turning on too.  I moved a few feet to the next outlet and the new blender worked fine.
I then got out a "night light" to test the wonky outlet.  In one of the plugs the light worked fine (which is the same plug the new blender was plugged into and didn't work).  In the other plug (the one the broken blender was plugged into) it only lit up if I had it partially plugged in - once it was fully plugged in it turned off.  Obviously the outlet has issues.  To recap and provide more details:

The outlet provides power, but apparently not enough for a blender
One plug worked fine for a low-power device, but the other plug stopped working when the light was plugged in all the way.
No breaker circuits are tripped
There is one GFCI outlet in the kitchen, on a different wall.  I confirmed that this outlet is not controlled by the GFCI
I'm 95% sure that this outlet isn't on a GFCI at all
There are additional outlets on this wall in the kitchen, and they all work fine (in fact I finished my lunch by using the fully-functional blender plugged into another outlet just a couple feet away).
There are no signs of physical damage to the outlet

The question(s)
I'm guessing that the blender turned on/off a little to quickly for the outlet and damaged it in some way.  My presumption is that I just need to replace the outlet, which I have done before.   However, I'm always very cautious about electrical issues and will happily get an electrician if there is any sign that there is more to this issue than it seems.  So, my questions (the first one is the only one I need answered):

Does it sound like the only issue is a faulty outlet that needs to be replaced?
Does a blender turning on/off repeatedly seem like the sort of thing that could break an outlet?  I don't think my blender actually cycled that many times, and I'm mildly concerned that there was more wrong with this outlet and my blender was just "the straw that broke the camel's back".
In particular, might this be a sign that my blender is trash?  A broken lid is a lot cheaper to replace than an entire blender.

And because a picture is worth 1000 words:
Comment: Can you turn the power off, pull the outlet out, and give us photos of it? Are there any other outlets that died alongside this one?
Comment: @ThreePhaseEel Yes, I can do that later today.  This is the only outlet that is having problems.  There is one other outlet on the counter just a couple feet away that (I assume) is on the same circuit and which operated my blender fine.
Comment: @ThreePhaseEel As promised.  In case it isn't obvious, the outlet is installed sideways on the (short) back wall of the counter.
Comment: Nothing plugged in the back (I've read enough of these to know that causes problems) - hot and neutral, are both attached via wirenuts on the side.  Looks pretty straight-forward and normal.  I've replaced this kind of outlet successfully before.
Comment: the outlet doesn't look like it had an overload problem. There could be some debris or pitting internally we can't see. Since it's a $0.50 part, just replace it and move on.
Comment: @dandavis Yeah, that's what I'm thinking I'll do.  I'm still mildly concerned that this could be a sign of a larger issue (which is the main reason I asked this), but I think the only way to find out if that is the case is by replacing it and seeing if the issue goes away permanently!  Feel free to turn that into an answer if you want
Answer: That one may be a builders grade .99 special get a spec grade for 3$ they are heavier and you won't have the problem any longer. In past positions I had to test outlets (hospital electrician) now they use hospital grade outlets crazy expensive but they last longer and have a higher withdraw force than new .99 specials, the spec grade have very similar withdraw rates as the hospital grade. I mention the 3 basic grades because they all wear out but the cheap builders grade fail much sooner than the other 2. You know the blender is good it works in another outlet, get a new quality outlet, turn the power off and replace it.
Answer: Did you check your circuit breakers to see if a circuit has tripped...?
Yes indeed, receptacles ( outlets can go bad, wiring in them can come loose and well as others things.)
First:
Check your circuit breakers, see if any are tripped.
If not...
Approach with the utmost cation if you intend to remove that outlet.. FIND ( if you can ) that outlet breaker if no breakers are tripped.. and pull out that outlet...Replace if cracked or it can no longer hold a plug.
And provide pictures please !
Comment: I'm not sure what I would provide a picture of.  The outlet looks perfectly normal.  Also no, nothing is tripped.
Comment: "Looks normal" = "I'm not seeing it" @conman
Comment: Are you convinced there's nothing wrong with your blender ? I would hope you already plugged it in to another outlet , right ?
Comment: I have two blenders - the one that gave the outlet problems and another.  In the end I made my lunch with the other blender in a different outlet, but neither blender works in this outlet.

Blender killed outlet?


Using OpenCV imread and imwrite with Python Path objects gives SystemError:  returned NULL without setting an error

Question: Passing a Python Path object to OpenCV's imread or imwrite results in an undefined error:
from pathlib import Path
import cv2

img_path = Path("test.png")
img = cv2.imread(img_path)

Results in:
Traceback (most recent call last):
  File ".\secondary_image_generation.py", line 36, in <module>
    img = cv2.imread(img_path)
SystemError: <built-in function imread> returned NULL without setting an error

Why is this and how can I avoid it?
Answer: OpenCV library sources are written in C++ and the Python bindings are primarily auto-generated and don't do much more than wrap the C++ functions. The C++ functions expect string type filenames so that is what you have to provide to the Python functions as well.
Doing the following resolves the problem by resolving the full path and converting it to a string:
img_path = Path("test.png")
img = cv2.imread(str(img_path.resolve()))

This is still an open feature request for the current version of OpenCV.


Internet doesn't be connected after suspend through VPN with WiFi on Ubuntu 16.04

Question: Wifi can resumed but it doesn't connect to Internet through OpenVPN with Ubuntu 16.04.
Comment: Wireless through VPN? That doesn't work (though the other way around would) and I'm sure we have a misunderstanding about your networking setup. Can you please [edit] your question and clarify it?
Answer: openvpn doesn't properly work after suspend. it needs restart.
<code>
sudo service openvpn restart
</code>
Actually, I wanted to leave a comment in the below question, but I don't have enough rep. So I decided to answer my question. This will help somebody having the same problem.
Wifi doesn't work after suspend after 16.04 upgrade


mySQL - Create a New Table Using Data and Columns from Three Tables

Question: I am trying to create a new table that will consist of selected data from three existing tables.
The three existing tables are set up as following, and my desired result is at the bottom:
people
id      last_name   first_name  email
1       Smith       Fred        Fred@..
2       Jones       Tom         Tom@..
3       Doe         Jane        Jane@..

taxonomy
id      taxonomy
1       age
2       gender
3       height

details
id      person_id   detail_id   content
1       1           1           36
2       1           2           M
3       1           3           5'10"
4       2           1           29
5       2           2           M
6       2           3           6'3"
7       3           1           27
8       3           2           F
9       3           3           5'8"

New Table
id      last_name   first_name  email   age
1       Smith       Fred        Fred@.. 36
2       Jones       Tom         Tom@..  29
3       Doe         Jane        Jane@.. 27

Thanks in advance for your help!
Comment: What problem are you having with it? Please post the code that you're having trouble getting to work, and we'll help you fix it.
Comment: The problem is I don't know what I'm doing. I have inherited this database as part of another project I'm working on for a non-profit, and I don't know much about mySQL except for how it works in WordPress.
Answer: You need to do a 3-way JOIN:
CREATE TABLE new_table AS
SELECT p.*, d.content AS age
FROM people AS p
JOIN details AS d ON d.person_id = p.id
JOIN taxonomy AS t ON t.id = d.detail_id
WHERE t.taxonomy = 'age'

DEMO
Or if you've already created the table, you can do:
INSERT INTO new_table (id, last_name, first_name, email, age)
SELECT p.id, p.last_name, p.first_name, p.email, d.content AS age
FROM people AS p
JOIN details AS d ON d.person_id = p.id
JOIN taxonomy AS t ON t.id = d.detail_id
WHERE t.taxonomy = 'age'

To get multiple attributes, you have to join with the details and taxonomy tables separately for each attribute:
CREATE TABLE new_table AS
SELECT p.*, d1.content AS age, d2.content AS gender, d3.content AS height
FROM people AS p
JOIN details AS d1 ON d1.person_id = p.id
JOIN taxonomy AS t1 ON t1.id = d1.detail_id
JOIN details AS d2 ON d2.person_id = p.id
JOIN taxonomy AS t2 ON t2.id = d2.detail_id
JOIN details AS d3 ON d3.person_id = p.id
JOIN taxonomy AS t3 ON t3.id = d3.detail_id
WHERE t1.taxonomy = 'age' AND t2.taxonomy = 'gender' AND t3.taxonomy = 'height'

Comment: I want to create a fourth table, sorry if that wasn't clear. So I would use INTO new_table after the SELECT?
Comment: I've updated the answer to show how to put the results into a table.
Comment: Barmar, I must be doing something wrong - when I try to run and create a new table, a bunch of duplicates are created. The id column in the new_table looks like this: 1 2 2 3 7 9 12 14 15 17 18 22  I tried creating a table and INSERT INTO with the id set as the primary key, but then I got an error because of a duplicate...
Comment: My answer copies the `id` from the `people` table into the new table, since that seemed to be what you were doing in the example in the question. If you don't want to do that, leave the `id` out of both the column list and `SELECT` clause in the `INSERT` statement. Then it will assign new IDs using `AUTO_INCREMENT` (I assume you're using this for the IDs in all the tables).
Comment: what would I add to include the other taxonomy details, i.e. gender and height.  I have tried for 4 hours to figure this out, but keep running into errors.  Here is the code that I am successfully using to create the fourth table, with a new primary key:

`CREATE TABLE new_table (id int PRIMARY KEY AUTO_INCREMENT) AS
SELECT p.last_name, p.first_name, p.email, d.content AS age
FROM people AS p
JOIN details AS d ON d.person_id = p.id
JOIN taxonomy AS t ON t.id = d.detail_id
WHERE t.taxonomy = 'age'`
Comment: Thank you very much Barmar.  You make it look so simple - I was having a really hard time with the syntax in the `WHERE` statement.
Comment: Performance would improve by changing `details` to have `PRIMARY KEY(person_id, detail_id)`.


How do I replace oven insulation that has been soiled by mice and smells bad?

Question: We've had mice work their way into the oven insulation of our standalone range and now it stinks when we turn the oven on.
Looking around on the web suggests that replacing the oven is the most common solution, but that seems extreme!  Any suggestions?
(In this case the oven is a "Viking Professional" (bottom of the line) 4 burner + oven freestanding range. I haven't yet been able to pull it out enough to check if it has removable panels or been able to find a manual online.)
I'm guessing the answer will be something like:

locate the manual for your appliance
remove access panels
remove insulation while being careful about ??
remove insulation that is "stuck" by doing ??
replace with new insulation from ??
put it all back together and test as follows
in general be careful of ??

And, perhaps this is too specific to the brand of appliance? It would be useful to know which brands are more amenable to DIY repairs of this type than others.
Comment: @DanielGriscom I ended up getting rid of it and replaced it with a cheaper stove. Very reluctantly. I couldn't find anyone who would attempt to repair it. I did get it outside and remove some panels and it was riddled with mouse droppings. Fortunately the mice did not return, perhaps because we stopped leaving the cat food out.
Comment: It is so disgusting I am going through this issue... I suggest turn the gas line off, pull all the insulation crap out, excess food, & clean it up real good... You might not be able to use the stove for a few days until you seal up hoes windows, etc in the house... It would be a bad idea to buy insulation for the stove i would wait until all the mouse or mice are out!! UGh still fighting for this!!! Good luck and were gloves!!! :(
Comment: Hi, @mm2001. Did you end up resolving this? If so, an update on what worked (or didn't) would be helpful.
Comment: Probably a good choice. The mice pee in the insulation, and then you're getting that good old "burnt pee smell" that any Boy Scout will tell you about.
Answer: I'm so sorry for your loss.  A Viking is a terrible thing to waste. Disassembling a Viking oven/range is not a job for a DIYer.  Look for a restaurant supplier in your area or a  Viking dealer to get a competent tech to do the work and bite the bullet and have it fixed right.  The insulation is not something you can buy at the local Home Depot. It uses a specialty high temp spun fabric insulation . If the job is not done properly, it will be a FIRE HAZARD!!!!  This is a  safety issue not worth saving a few bucks on. The Viking is worth saving if you can.
Comment: Thanks for the sad news :-(.  I'm guessing this is not a cheap endeavor. I have a tech coming soon to look at it and will see. Yes, I agree that it is definitely worth saving if possible. I hate seeing things wasted in this throwaway society. I'm not familiar with the Viking gear in particular, but I gather its better quality than most (it is certainly expensive, which is sometimes, but not always, a good guide!)
Comment: The only problem I have with the first answer is that a few droppings is not usually the overwhelming cause of smell.  Rodent urine can be scattered throughout the trail and the partial fix of replacing some obviously disturbed insulation may not fix your problem. Glad you decided to get a pro to look at this one.  good luck.
Comment: You can run an oven cleaning cycle to 'roast' some of the smell out.  Do this on a nice day with fans running.
Answer: Sadly enough, I had the exact same thing happen to me in the past.
If your mice were anything like mine, they are likely stockpiling food in the nest they have made inside the insulation (which, along with the droppings, is the source of the smell).  More likely than not, they have made their home in the space directly underneath the burners, on top of the oven box.
When it happened to me, this was how I went about fixing the problem:

Shut off the gas line / unplug the unit from the wall.
Remove the cooktop portion of the range, exposing the insulated oven box
Remove the affected insulation (in my case, only about a fist sized chunk was affected).
Replace the cooktop, and hook the gas/electric back up (use a new flexible gas line if applicable).

In my case, the affected area was so small that I did not replace the removed insulation.  To my knowledge, the only function of the insulation in that portion of the oven is to reduce heat loss.  Since the area was so small, I decided that the heat loss would be negligible.  If the area is relatively large, or you are paranoid about the exposed area, then you can buy some material online to patch the hole (here, for example).
The bigger issue, however, is dealing with the mice infestation in your house.  As long as the mice are there, they will come back and ruin your freshly refurbished oven (trust me, I ended up doing this twice to my oven before getting rid of all the mice for good).  Set traps, remove sources of food, and attempt to find and seal the places where the mice are entering the home.
Comment: Just a note: try and avoid moving the oven repeatedly.  Every time you move the oven out and back, it fatigues the metal in the flexible gas line, eventually resulting in a gas leak.  When I had traps set behind the oven, I attached them to a string so I could remove and replace them without pulling the oven out.
Comment: If you have snap traps, make sure that they are set perpendicular to the wall, a couple of inches away from the baseboard.  Also, get several styles of trap (electronic, traditional snap trap, multiple catch traps, etc).
Comment: Good point re the mice. I have traps set but so far nothing. The sad part is that we have a cat that likes to bring mice in for us as presents. I suspect that is the primary entry route, but cleaning out the cupboards, sweeping behind the fridge, etc is long overdue also.
Comment: many thanks. I'll go and move the trap I have sitting in the middle of the under oven space which has caught nothing despite seeing some new insulation on the floor under the oven that suggests the mice are still active.
Answer: Realizing this is very old: I'm going through this with a brand new stove that was kept in storage for a while. I've had to remove all of the insulation and clean all of the sheet metal that had urine on it. Definitely not a 1 hour task, I'm up to 2 days on and off.
The insulation I'd recommend is either the OEM (repair clinic or similar) or a ceramic 2400F insulating fireproof. The latter is not likely to be easily eaten and, should you choose to, you could wet it with 'rigidizer' making it practically impossible for the mice to get into.
When removing the OLD stove to replace, I found out mice had made a nest on top of the oven insulation- filled it with chocolate and butter scotch chip. They were all intact, never melted, despite loads of high temperature cooking.
Take your time, take photos, and keep the screws organized. Modern stoves use pretty much all the same screw both size and length to keep manufacturing costs down, and 'finish' screws are unique to their look/area.
Also consider spot-blasting the surface where the urine was; that'll clean it quickly and get rid of any rusting/rusty spots. Use an cheap spot blaster out doors, wear a mask (should be easy now), and use 70 grit (Fast cutting). Hit it with high temp primer/acid etch if you want to protect it, but it should be good.
Future Mice Removers, Rejoice!


node.js : Currency limited parallel execution with time interval (rate limiting)

Question: My goal is to send N request per time interval, and be sure that network lags won't effect on my algorithm.
I made this function:

var results=[];

function sendBatchReq(docs, fromIndex, batchSize, timeout){

    var counter=batchSize;
    console.log(new Date()+ " executing");
    for (var i = fromIndex; i < fromIndex+batchSize; i++) {

        var url=docs[i].url;

        request(url, function(err, res, data) {

            results.push(JSON.parse(data));

            counter--;

            if(counter==0 && docs.length >=fromIndex+(batchSize*2)){
                console.log(new Date()+" next batch");
                setTimeout(sendBatchReq(docs,fromIndex+batchSize,batchSize), timeout);
            }

        });

     }
}

sendBatchReq(docs, 0, 5, 10000);

This should work like this:
Execute first 5 request, when the 5th cb is been executed launch another batch of 5 request after 10s.
The problem is that the timeout seems to don't work: all the new sendBathReq are executed just after console.log print out.
Answer: You're invoking the function. You meant to pass a function, but you're passing the return value of that function because you accidentally called it inline. Did you mean:
setTimeout(function(){ sendBatchReq(docs, fromIndex + batchSize, batchSize);},
           timeout);


Contact form on mobile vs. mailto: link?

Question: I have decided to put a contact form in the footer for my portfolio site and opening the question up to include any site where the decision was to add a contact form on the desktop version...
Would it be more accessible to make the contact form responsive or to remove the contact form and add an email link for mobile users, so that they can use their devices email client?
Comment: I would recommend using hidden/encoded emails, with mailto: links generated by javascript. Unless you use firstname.lastname@example.com which is going to be spammed anyway. But I would not expose a personal email to email harvesting bots in any circumstances.
Answer: I think the mailto: link is a better option for mobile users.
The contact form gained prominence [original research] because on a desktop computer it is quite rare for users to have a mail client installed. Instead of having a link with a mailto: address that would simply fail in the majority of users' browsers, people started adding a form which would duplicate the functionality.  If Web Handlers become more widely used and supported, we may see this start to change, but the fact remains that a very large majority of users will click a mailto: link and have nothing happen.
On a mobile device, however, this is entirely the opposite: Every smartphone has a mail application pre-installed on the device, capable of handling these mailto: links with ease. This also avoids forcing the user to wrestle with their device's browser's text box controls, instead using the relatively mature controls of their e-mail application.
In short, use mailto: for mobile, because e-mail apps have better controls.
Comment: I think the rise of contact forms had as much to do with spam bots that scrape emails and the ability to collect specific information. I think these days spam filters have evolved to the point that the former is slightly less of a problem than it was. See also this [question](http://webmasters.stackexchange.com/questions/15834/why-do-websites-have-a-contact-form-isnt-an-email-address-enough) - factors also worth considering in your decision.
Comment: Awesome that's what I was hoping. I'm not a fan of using or building out forms on mobile. Plus, I think a mail app on a phone gives you more space, and the ability to use something that you are used to using. A user can also save the eMail to finish later.
Comment: Actually, *from my experience*, having an e-mail client ready is more frequent on a computer than on a mobile device. Often, on a mobile device, there is no e-mail client ready. Anyway, on mobile or not, the link "mailto:" is nice but requires an e-mail client ready, which is not always there, so it is good to propose **also** a Web contact form.
Answer: Native mailto: links have real strong advantages. They are obvious, and are summed up in the word native.
But the Web form has a strong advantage too. It is handy to use when I don't have a ready-to-use e-mail client at hand. Or when I don't want to launch it. I am on the Web, I stay on the Web. Quick. No hassle. On my mobile phone, the Web is set up, but not the e-mail. So I would happily fill in a Web form, but I would not send a native e-mail. And what if I am on a friend's iPad ?
Have both.
The good approach is the one chosen on the Contact page of Bare Bones Software, for example. A native contact e-mail link, and a contact Web form. And they tell their snail mail address too, and phone number, and fax number. This is good. And send to the user a confirmation of his/her message. So that s/he have his/her message in his/her mailbox.
Comment: I agree entirely with Nicolas. Whilst there is good argument that every smartphone now has a native mail app, who's to the say the user has it set up? If they haven't, then that's a barrier. A barrier preventing the user from reaching you. Barriers are bad. A web form on the other hand allows anyone to mail you, regardless of whether or not they've set up their native mail application. Give users the choice, **but never drop the web form.**
Comment: Agreed. I don't have my email client setup on my mobile phone because email is distracting.
Comment: The rates of mobile email opens suggests that the overwhelming majority of people do have their mail set up on their phones. It's the default behavior of phones; you have to go out of your way to disable it. While I agree that accommodating both use cases is a noble goal, if you have to prioritize (and who doesn't?), I'd go with "mailto:" given the stated use case.


well pressure tank losing pressure

Question: My well pressure tank has this symptom... Tank cycles about every 4 minutes without any water running. checked the pressure and it is where it should be. In between cycles I can see the pressure dial going down slowly until it clicks the cycle back on again. Afraid I will burn out well pump. Checked the tank by using the drain tank method and it has 28 psi pressure in it and no water comes out when checking the pressure value. Should not be waterlogged and I need help. So HELP ME DIAGNOSE BEFORE I SPEND MONEY ON A WELL REPAIR COMPANY...PLEASE!!!
Added information...Failed to mention that we have shut the water off to the house at a shut off value at the well but it still does the same thing. Have read several articles about this and from what I can tell to this point it would seem to either be the tank bladder tear or the check value that is down in the well by the pump. Could I assume this is right? And also you are saying I am losing water from the tank...could it be the AIR? – Kevin Kings Mountain
Comment: My tank is 30-50 cut in and out
Answer: If the pressure is going down, you're losing water somewhere.
If you have a main shut-off valve on your tank (usually between tank and rest of house) shut that:

If the pressure keeps going down, it's probably the check valve (submersible) or foot valve (jet pump), but could also be a leak in the pipe either going to or in the well.
If the pressure drop stops, there's a tap open or leak in your house somewhere.

Alternatives to a main shut-off valve are certain types of bypass valves on softeners, carbon or iron filters (the type with two valves to turn -- if you just turn one, it shuts off the water), or cartridge filters are often installed with shut-offs so you can service them.
Diagnosing interior leak
Unless you can isolate the problem to your well, go around your whole house and shut all valves (including toilets and outside taps) and inspect for any leaks.
The time of year is also a hint that you might have had a frozen pipe that burst, and has now melted and is now leaking, so you should definitely take a close look at areas near pipes on/near exterior walls and at any outside hose bibs.
Diagnosing leak in well
Almost certainly this will involve pulling the pump/foot valve out of the well. You'll have to turn off the pump and drain the pressure first.
Before you pull it, see if you can spot an obvious leak above the water line (eg, at the pitless adapter at the top). Pro tip: use a good spot-type flashlight or a mirror to reflect sunlight so you can see down.
Once you pull the pump out, inspect all the fittings for any signs of damage. By far the most common problem is the check valve at the top of the submersible pump sticking open (either spring or other parts corroded, or something actually lodged in it holding it open).
If you still haven't found anything, this starts pointing at a leak in the line going to the house, which is significantly harder to deal with (involves digging), and in worst case, involves digging the entire line up. In my experience, this will usually be:

Pipe was above frost line, and froze. If you know a spot the pipe isn't buried deeply, this is a good place to start.
Lightning strike. Lighting will travel across trees/fences/etc to get to the water/power lines on its way to that giant metal casing in the ground. Usually where it hits it'll burst the pipe open, and it'll following the most direct path possible.
Bad/broken fitting. There should only be one fitting undergound, which is at the pitless adapter where the pipe meets the casing. It's possible there's another at the entrance to the house, but it's best practice to just run lines inside and do the connections inside. It's also possible there's a coupler somewhere in the middle of the line if the installer was being lazy/cheap.
Comment: Failed to mention that we have shut the water off to the house at a shut off value at the well but it still does the same thing. Have read several articles about this and from what I can tell to this point it would seem to either be the tank bladder tear or the check value that is down in the well by the pump. Could I assume this is right? And also you are saying I am losing water from the tank...could it be the AIR?
Comment: If the tank bladder was torn, what you would see is rapid cycling of pump and big pressure spikes/drops as you open and close taps (since effectively, the tank is not doing anything). When you drained the tank, you'd have 0 air pressure, and it would take an enormous amount of air to refill it (since it would be filling the entire tank, not just the bladder) assuming it didn't just get out through the water line. As soon as you opened values it would go back to 0. If air was leaking, it would go down to 0 psi quickly, and then operate as I described above.
Comment: I have worked with pressure tanks that had bad bladders if there is air in the tank it can cycle normally until the tank is rusted through and the air leaks out followed by a water leak and rapid cycling as described by gregmac. I would be looking for a check valve usually close to the pump, then the foot / check valve in the pump.+

well pressure tank losing pressure


Launch Activity on AlarmManager event from broadcast receiver

Question: I have am alarm manager through which i set a time to trigger on it by providing a broadcast receiver, onReceive method of broadcast receiver calls successfully but any idea how to launch app from onReceive if app is not running in foreground?
Menifest
<receiver
    android:exported="true"
    android:name=".AlarmReceiver" />

BroadcastReceiver
  @Override
    public void onReceive(Context context, Intent intent)
    {
        Intent scheduledIntent = new Intent(context, MainActivity.class);
        scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(scheduledIntent);
    }

MainActivity
        AlarmManager alarmManager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent=new Intent(this,AlarmReceiver.class);
        PendingIntent pendingIntent=PendingIntent.getBroadcast(this,1000,intent,0);
        alarmManager.set(AlarmManager.RTC_WAKEUP,timeInMillis,pendingIntent);

Kindly help
Thanks
Comment: You cannot launch an activity from the background on modern versions of Android. Please use a high-priority `Notification` instead.
Comment: Thanks @CommonsWare for a prompt reply, what do you suggest to use if I want to play a scheduled music stream automatically?

Secondly , as you suggested to use high periority notification , will it be a local notification or a push notification and can I launch an a activity from a push notification? Thanks
Comment: "what do you suggest to use if I want to play a scheduled music stream automatically?" -- if it something akin to a ringtone, you could perhaps tie it directly to the `Notification`. If it is something longer, have a `Notification` provide the UI for a foreground `Service` that plays the stream. "will it be a local notification or a push notification" -- `Notification` on Android refers to what I suppose you mean by "local notification". "can I launch an a activity from a push notification?" -- no.
Comment: It is basically a radio music stream using exoplayer , what we need is user set a time on which he want it to play , and when that time comes stream start playing automatically . Two things in my mind either background or foreground service.
Answer:
It is basically a radio music stream using exoplayer , what we need is user set a time on which he want it to play , and when that time comes stream start playing automatically .

A background service will only run for one minute on Android 8.0+. For a music player, you will want a foreground service, where the associated Notification gives the user playback controls (e.g., pause, resume, stop).
Comment: Thanks, I would need little more help, My requirement is to show a notification on broadcast receive method and that notification can stream a music stream. Music stream method is written in main activity , but when the onReceive of broadcast receiver is called at that time no method of main activity is callable because its not in foreground. Need help, thanks
Comment: @AliAkram: "Music stream method is written in main activity" -- that will not work. You will need to move the music stream logic to some singleton that you can control from the activity (when it is around), from the foreground service (when it is around), or perhaps from broadcasts from the `Notification` (when it is around).
Answer: First, you should use workManager
Also, Brodcastreciver has limits on different android versions doc


WSS over Secure SSL connection fails only on FireFox with error 1006

Question: My website runs on https/ssl (valid CA certificate) on IIS 10.0 (iisnode 0.2.21) / node/express. I am using a websocket server on top of https server (same port)
However the websocket connection works very well for CHrome and IE11. It fails only for Firefox (version 80) with error code 1006 (error details)
in Inspector / Network console, it gives the following errorerror as shown in network under inspector console
In the web.config file, I have added the following line
<webSocket enabled="false"/>
app.js code is as below:
var cors = require('cors');
var createError = require('http-errors');
var cookieParser = require('cookie-parser');
const https = require("https");
// var app = express();
var app = require('express-ws-routes')();

.....

var wsRouter = require("./routes/wsRoute"); // route for Websocket

....
app.use('/ws', wsRouter);

....
app.listen(process.env.PORT || 443);

In my Websocket route, I use the following code
router.websocket('/', function(info, cb,  next) {

    var connid = info.req.query.connid;
    var pgid = info.req.query.pageid;

    cb(function(socket) {
        // socket is connected
        socket.send(JSON.stringify({'response_type':'WSConnActive',
                            'response':{"status":"success","details":"Welcome Message","reqOrigin":"Home","welcomeMsg":'Hello '+usr+', Welcome! you are now connected!'}}));

....
 socket.on('message', function incoming(message) {  // handle message }

socket.on("close", function socketClose(ws){
            console.log(info.req.query.usr+" closed session at "+moment().format("YYYY-MM-DD HH:mm:ss"));
            var usrClose = info.req.query.usr;
...}
});  });

At the client end I connect
var socket = new WebSocket('wss://<host>:443/ws?request_type=init&usr='+UserID+'&connid='+connectTime+'&pageid='+page_ID);
All this works as expected for Chrome and IE11 except firefox
I am not sure where the issue is.. any help is appreciated!
Answer: Finally got the WSS working on Firefox with help of the note found in iisnode githun ([https://github.com/tjanczuk/iisnode/issues/497][1]) !. Issue seemed to be with iisnode configuration, In addition t , i had create a HTTP_CONNECTION server variable and add rewrite rules as below,
                  <match url="ws/*" />
                  <serverVariables>
                      <set name="HTTP_CONNECTION" value="Upgrade" />
                  </serverVariables>
                  <action type="Rewrite" url="websocket-server.js" />
            </rule> ```

  [1]: https://github.com/tjanczuk/iisnode/issues/497


Proving that this metric tensor is Riemannian

Question: Let $(M,g)$ be a Riemannian $n$-manifold, and $\varphi: M \to \Bbb R$ be a smooth map. Define another metric tensor by: $$\widetilde{g} = g - {\rm d}\varphi \otimes {\rm d}\varphi$$I know that $\widetilde{g}$ is Riemannian if $\|{\rm grad}_M\varphi\| < 1$ and Lorentzian if $\|{\rm grad}_M\varphi\| > 1$ $(\|\cdot\|$ induced by $g$, of course$)$.
To see the second case it is easy, it suffices to evaluate $\widetilde{g}$ in ${\rm grad}_M\varphi$ itself - it will be a timelike vector.
Is there an easy way to check that $\widetilde{g}$ will be positive definite? I don't quite know if there's a result about this, but I feel that computing the metric on ${\rm grad}_M\varphi$ should be enough. I'm not sure how to exactly compute $\det \widetilde{g}$ here... Thanks.
Answer: Take a vector field $v$, and compute $\bar g(v,v)$.  You need to show this is strictly positive when $v \ne 0$.  But $\bar g(v,v) = g(v,v) - (d\varphi(v))^2$.  Isn't this enough to make it work?
Comment: Oh yes, it is. Thanks, I don't know what I was thinking. $${\rm d}\varphi(v)^2 = g({\rm grad}_M\varphi, v)^2 \leq g(v,v).$$


provide large responses to python requests_mock

Question: I am using python requests to to access some apis, recently I learned requests_mock for mocking http responses for testing.
The responses from api that I am using are quire large
adapter.register_uri('GET', 'http://api.gateway/payment/, text='VERY LARGE TEXT')

What is the proper way of passing large response text?
Answer: There's not really a magic here, at the end of the day unless you're doing streaming requests is going to load all the data up into memory anyway.
If you're really worried about the memory (and it's python, you probably shouldn't) you could always load from a file on demand or something, but then i think it's much more about how you want to structure your tests than something requests_mock will help you with.
import requests
import requests_mock

def fileLoader(filename):
    def loader(req, context):
        with open(filename, 'r') as f:
            return f.read()

    return loader

with requests_mock.mock() as m:
    m.get('http://test.com', text=fileLoader('abc.txt'))
    resp = requests.get('http://test.com')
    assert resp.text.strip() == 'ABC'


inapp update android application installed but i'm getting the same version

Question: i decrement version build and name , so version build and version name are lower than the version on play store, i implement inapp version update of google , everything work fine, the  download has complete so i add button to tell  user restart application, and when he click it the install page is showen and application restart but when application start it's the same version like before , so the installation doesn't work :(
<code>   private fun showInAppUpdate() {

    mAppUpdateManager = AppUpdateManagerFactory.create(activity);

    mAppUpdateManager.registerListener(installStateUpdatedListener);

    // Creates instance of the manager.
    appUpdateManager = AppUpdateManagerFactory.create(activity)

    // Returns an intent object that you use to check for an update.
    val appUpdateInfoTask = appUpdateManager.appUpdateInfo

    // Checks that the platform will allow the specified type of update.
    appUpdateInfoTask.addOnSuccessListener { appUpdateInfo ->
        val a = appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
        val b = appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)

        if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
            // For a flexible update, use AppUpdateType.IMMEDIATE
            && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)
        ) {
            // To avoid crash when startUpdateFlowForResult is called two times (by accident)
            try {

                appUpdateManager.startUpdateFlowForResult(
                    // Pass the intent that is returned by 'getAppUpdateInfo()'.
                    appUpdateInfo,
                    // Or 'AppUpdateType.FLEXIBLE' for flexible updates.
                    AppUpdateType.FLEXIBLE,
                    // The current activity making the update request.
                    activity,
                    // Include a request code to later monitor this update request.
                    INAPP_UPDATE_REQUEST_CODE)

            }
            catch (e : Exception){
                e.printStackTrace()
            }

        }
        else {
            Log.e("", "checkForAppUpdateAvailability: something else");
        }
    }
  }

 val installStateUpdatedListener = object : InstallStateUpdatedListener {
    override fun onStateUpdate(state: InstallState) {
        if (state.installStatus() == InstallStatus.DOWNLOADED) {
            popupSnackbarForCompleteUpdate()
        } else if (state.installStatus() == InstallStatus.INSTALLED) {
            mAppUpdateManager?.unregisterListener(this)

        } else {
            // Download or install in progress
        }
    }
}

  /* Displays the snackbar notification and call to action. */
  fun popupSnackbarForCompleteUpdate() {
     val snackBar =  Snackbar.make(
       activity!!.findViewById(R.id.home_root),
        HtmlCompat.fromHtml(this.resources.getString(R.string.inapp_downlaod_complete),
   HtmlCompat.FROM_HTML_MODE_LEGACY),
        Snackbar.LENGTH_INDEFINITE
    )
    snackBar.setTextColor(Color.WHITE)
    snackBar
        .apply {
            setAction(activity!!.resources.getString(R.string.inapp_restart)) {
  appUpdateManager.completeUpdate() }
              setActionTextColor(Color.GREEN)
            show()
        }
}

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == INAPP_UPDATE_REQUEST_CODE) {
        if (resultCode != AppCompatActivity.RESULT_OK) {

            mAppUpdateManager?.unregisterListener(installStateUpdatedListener)
        }
    }
}
</code>
why the application does not update with the version on play store ?
Thank you for your help
Comment: If you are using debug to test and the play store to update, they are likely going to have different application id's.
Comment: If you launch the app from your code and then download from the app store, you are going to have 2 apps and 2 different app id's. The play store won't update the app that you launched from AS.
Comment: bundle id ? you talk about application id ? i already check the application id is the same
Comment: @BlackHatSamurai i will check with a exported version release, maybe the problem come from here
Comment: Yes this was the problem i thought that the same application id is enought, but i had to export and sign application to release mode to get this work
Answer: Mostly what is happening is that you are launching your first app from your code, then trying to update that app from the store. Ultimately, those are going to be 2 different apps (since the one from your code is going to be a debug version and unsigned); therefore, you won't see the update. If you want to test this, you would need to sign the app and install it on your phone rather than just launch it from the code.


What are the differences between these types of small-dimension lumber?

Question: I have a project that needs smaller lumber, 1x4s, 1x3s, and 2x2s. This project is rough carpentry just a garage shelf. I have built one example of this shelf already. I did it over a year ago and I did not pay much attention when selecting materials. I have no idea what it cost or what I used! I want to be more careful this time.
When I look at the websites of the big-box stores to estimate my costs I see three types listed for this lumber and the approximate cost for an 8' length:

firring strips, $2
select grade, $10
pressure treated, $4

Why is there such a variation in price?
How can I tell which grade to get?
I assume that the select grade is straighter or has fewer defects. I expect the firring grade to be very rough and probably warped. Would the pressure treated be a compromise between cost and straightness?
Comment: Are you tied to the idea of using 1x4s for the shelving? If not, I'd price it against 3/4" plywood. Based on the diagram you're looking at $350 in select 1x4s - you can buy 6 or 7 sheets of *birch* plywood for that.
Comment: There is still another grade of material that is commonly used to do what you are looking for. One big box store calls it common 1X3, it costs about $5/pc. It is also called #2 pine or SPF. Firring strips are a lower quality version of the same material. Aside from that I have done shelves just as Comintern has suggested. and did it cheaper and better. Though for material usage you may need to adjust the depth of the shelves to minimize waste with plywood.
Comment: Just a note on the linked to plans. Drywall screws are for attaching drywall to studs, and should not be used for attaching wood to wood.  Use 1 1/2" wood screws, or 1 1/2" deck screws instead. If the shelves are in a basement or garage, I'd lean towards deck screws, but wouldn't pay a premium for them over wood screws. Since you're working with smaller lumber, I'd also drill pilot holes to avoid splitting.
Comment: [this pdf](http://forest.mtu.edu/classes/fw1035/2011/Lecture%2013%20-%20Lumber%20Grading.pdf) might be helpful. The [American Softwood Lumber Standard (PDF)](http://gsi.nist.gov/global/docs/vps/PS-20-10.pdf) might also be useful. Lowes also has a good [Lumber Buying Guide](http://www.lowes.com/cd_Lumber+Buying+Guide_896860585_) Look for the stamp, that will tell you the truth about the lumber.
Answer: There are a whole lot more types of boards than that! Even at the big box stores.
Furring strips come in limited sizes and are not meant to be structural or seen.
Pressure treated boards have a chemical applied to them under pressure that helps presserve the wood against moisture and insects. It's generally used outdoors or in direct contact with concrete otherwise it's not recommended to use pressure treated lumber. The appearance, quality and sizes match other framing lumber used for studs, juists, etc. It would be cheaper to use non-pressure treated lumber.
The better wood to use are appearance grade boards. They'll either indicate they are "appearance" grade or described as S4S (surfaced 4 sides). These will have a smooth surface on all 4 sides. They come in a variety of different sizes and species. The cheapest price is for something the box stores call "whitewood" which is whatever light colored wood they can get the cheapest at that time. Pine, spruce, fir, etc. I think Home Depot might be calling them "common boards" now.
The select grade boards are also appearance grade S4S boards but usually of better quality with fewer knots, hence the higher price. Not necessary for a garage cabinets.
That design you linked to looks like it would be expensive to build. If you want to save money and don't care about appearance you can save money by using a different design that uses 2x4's and 3/4" plywood for the shelves.
Comment: Pressure treated wood no longer contains elements of arsenic and is used and is rated to be used in pretty much any indoor situation.  Do you need to use pressure treated wood indoors?  Not most of the time but if you watch Holmes on Homes he does entire basements in PT wood.
Comment: @DMoore pressure treated wood is recommended against for indoor use depending on the situation. Even without the arsenic compounds, it still is not recommended for places where it could possibly come into contact with clothes or food, and should not be installed unless dried. It is also recommended against because the detritus from working with the wood (especially sanding) needs to be cleaned up carefully as well.
Comment: I'm very happy with the design. Built one already and its rock solid. I'm just trying to make smarter materials selection this time around.
Answer: Pressure treated are made for outdoor use and basically don't need to be painted to be protected from the elements.  Otherwise when wood gets wet, rot sets in.  Pressure treated wood is what you would see used as landscaping timbers, for example.  As far as select vs furring goes, you're generally correct, but the more important part is the strength - select is much stronger,  Furring strips typically aren't used to hold any sort of load, whereas select pieces could.
Comment: Can you quantify how much of a difference in load capacity there would be?
Comment: Furring strips are typically made from wood that is going to be hidden. In other words, it's neither structural nor designed to take a finish well.
Comment: Nobody should ever use furring strips in any sort of structural capacity, they're just meant as a surface to create points to attach other structural members.


A Problem on Isomorphism Between Compact Riemann Surfaces

Question: If M and N are compact Riemann surfaces, show that : $ f: M \to N $ biholomorphic mapping if and only if there is a finite set A, B, where $A \subset M, B\subset N$, such that
$$ g: M-A \to N-B$$
is a biholomorphic mapping.
Here I have a similar problem:
If M is a compact Riemann surface, and $ M-\{p\} \cong \mathbf{C}$, where p is a point in M, then $ M \cong \mathbf{C} \cup \{\infty\}$.
I have tried many times through definition. However, I still can't think clearly and give an isomorphic mapping.
Answer: Hint: use local holomorphic charts and Riemann's removable singularities theorem.
Edit: here are a little more details.
Let $f: M \backslash \{p\} \to \mathbb C$ be an isomorphism. Let $\phi: U \to \mathbb C$ be a local holomorphic chart of $M$ near $p$. Let $g(z)=\frac{1}{f(\phi^{-1}(z))}$, and $V:=\phi(U)$, $z_0:=\phi(p)$. Then $g: V \backslash \{z_0\} \to \mathbb C$ is an injective holomorphic map. Can you then prove:

that up to restricting $U$ if necessary, $g(V \backslash \{z_0\})$ is bounded?
that $g$ extends holomorphically to $V$?
conclude.

This is for the second part of your question, which is a special case of the first. The more general method is the same, you just need to replace the chart $z \mapsto \frac{1}{z}$ by local charts for $N$.
Comment: Is it similar method about charts with the $ \mathbf{S} \cong \mathbf{C}\cup \{{\infty}\}$? Why does it use the Riemann's removable singularities theorem?
Comment: @Tinzoe-Yui see my edit
Comment: The second step is to use the Riemann's removable singularities theorem to explain that $g$ can be extended to $V$. Here I have a question: how can I explain that $M$ can be isomorphic to $\mathbf{C}\cup\{{\infty}\}$?
Comment: Please take a look at my thought. If $g$ is unbounded on the disc $U=\{ z: \left| z-z_{0} \right| <r \}. then $\frac{1}{g}$ is bounded, by the Liouville theorem, $f(\phi(z))$ is a constant, but this contradiction. Complete the first step you mentioned.
Comment: not quite. if $g$ is unbounded, it doesn't necessarily mean that $1/g$ is bounded. however, recall that $f$ is an isomorphism, so you can just take $U \subset M$ such that $cl(f(U)) \cap \{0\} = \emptyset$
Comment: Sorry, I don't quite understand what you mean. Why consider $cl(f(U)) \cap {0}= \emptyset$ ?
Comment: because that's the condition that will ensure that $g$ is bounded on $V=\phi(U)$
Comment: thanks a lot!!!!!


Reading data from Firebase, Importing JSON file to Firebase console which is a Array Structured - Android

Question: I'm having problem to read data from Firebase by Android. I have imported one JSON file to Firebase console which is long file (List of mobile manufacturing company's name and their respective mobile phone model names). Sample is like below.
<code>[
  {
    "RetailBranding": "Google",
    "MarketingName": "Pixel",
    "Device": "sailfish",
    "Model": "Pixel"
  },
  {
    "RetailBranding": "Google",
    "MarketingName": "Pixel 2",
    "Device": "walleye",
    "Model": "Pixel 2"
  },
  {
    "RetailBranding": "Google",
    "MarketingName": "Pixel 2 XL",
    "Device": "taimen",
    "Model": "Pixel 2 XL"
  },
  {
    "RetailBranding": "Google",
    "MarketingName": "Pixel C",
    "Device": "dragon",
    "Model": "Pixel C"
  }
]
</code>
As you can see, It is a JSON file which is starting with an ARRAY. As mention here FIREBASE does not support ARRAY directly (This is mention in Firebase official document as well), How can I read these data from Firebase.
You can find out till what I have done.
Main2Activity.java
<code>    public class Main2Activity extends AppCompatActivity {

    private final String TAG = "mk";
    private DatabaseReference mDatabase;

    private EditText edt_search;
    private RecyclerView rv_brand_names;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        mDatabase = FirebaseDatabase.getInstance().getReference();

        edt_search = (EditText) findViewById(R.id.edt_search);

        RxTextView.textChanges(edt_search)
                .debounce(500, TimeUnit.MILLISECONDS)
                .subscribe(charSequence -> {
                    pullOutTagsSuggestions(charSequence.toString());
                });
    }

    public void pullOutTagsSuggestions(final String searchStr) {

        mDatabase.orderByChild("RetailBranding")
                .startAt(searchStr)
                .addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        if (dataSnapshot != null) {

                            for (DataSnapshot suggestionSnapshot : dataSnapshot.getChildren()) {
                                String suggestion = "" + suggestionSnapshot.child("RetailBranding").getValue();
                                Log.e(TAG, "suggestion -->" + suggestion);
                            }
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
    }
}
</code>
In above code I'm getting all the data not filtered data from Firebase database. Let me know If any further details required. Thanks in advance.
Comment: What is the output of `Log.e(TAG, "suggestion -->" + suggestion);`?
Comment: Getting **Google** as o/p and other manufacturer companies name after this line **"RetailBranding": "Google"**. I want to make search - filter like, if I will type **Pixel** then suggestion should come like **"Google - Pixel", "Google - Pixel 2", "Google - Pixel 2 XL"**. And If I will type **Google** then suggestion should come like **"Google - Pixel", "Google - Chromebook", "Google - Nexus 6P"**@AlexMamo
Comment: Might be this [link](https://stackoverflow.com/questions/38719402/how-can-i-load-an-autocompletetextview-from-a-list-of-firebase-data/38727876#38727876) can be helpful
Answer: you can import your JSON-File in Storage in Firebase, get the url for that json-File and read it's content using i.e. AsyncTask in your application.
that's what i did, to use JSon-File with firebase.
Comment: Was your JSON file starting with ARRAY like mine?@korchix
Comment: @MaulikDodia yes, you need just the url to your json file, then you can read it's content in your app, like every json file you can find on the internet.  (In this case you don't need the firebase methods and classes to read the json file). That's how i did it too.
Comment: @MaulikDodia and if your users should not modify your json, you don't need "realtime database" instead you can store your json in "storage"
Comment: Let me try and I will get back to you@korchix


React state is not updating object

Question: Here first I have a static object which has three values and I have created a form where I am taking input from user and then I wanna merge that new input with already created static object but it is not working although if I console to check whether values are merged are not then in console results are according to my exception but while rendering its not working on output screen I am just getting three static values here is my code:
import React, {useState} from "react";

import Expenses from './components/Expenses/Expenses.js';
import NewExpense from './components/NewExpense/NewExpense.js';

  let my_expenses = [
    {
      title : "Scholarship Fee",
      date : new Date(2021, 11, 24),
      amount : '$1000'
    },
    {
      title : "Sports Fee",
      date : new Date(2021, 1, 14),
      amount : '$200'
    },
    {
      title : "Extra",
      date : new Date(2021, 10, 8),
      amount : '$100'
    }
  ];

const App = () =>{
  const [expenses, setExpenses] = useState(my_expenses);

  const newExpenseData = (data) => {
    const updatedExpenses = [data, ...expenses];
    setExpenses(updatedExpenses);
  }
  return (

      <NewExpense newExpenseData = {newExpenseData}/>
      <Expenses item={my_expenses}/>

  );
}

export default App;

Comment: the issue doesn't seem to be in the provided code… please add more relevant information like the print and what triggers the change
Comment: you are not callig newExpenseData method, just declaring it,  what it acutally doing, can you plase more clear
Answer: [Using spread operator while merging]

let p = {x: 12, y: 34}
let q = {z: 56}

let mergedObj = {...p, ...q} // works as union
console.log(mergedObj) // { x: 12, y: 34, z: 56 }

hope it will help you to understand further step

React state is not updating object


Mapbox GL JS refresh layer

Question: I'm using Chroma.js to style a Mapbox choropleth map. I do this by storing in a variable dataStyleProp a single property of the source -- in this case the data are population and the properties are "free", "slave", "white", and "total"). Then I use dataStyleProp to build the Chroma.js color scale. What I would like to do is:

Select the value for dataStyleProp from a radio button on the HTML page,
Pass that value to the Chroma script,
Then refresh the map to show the new choropleth.

I've managed to do 1. and 2. but can't get 3. to work. I've tried map.update and map.resize to try to force the refresh but neither works. I also looked at map.getSource(source).setData(data) but the data passed must be a geojson and my dataStyleProp is a string.
I considered creating a new layer for each dataStyleProp value, but that would mean creating hundreds of extra layers (each source has at least 4 different dataStyleProp values) and I'd like to avoid creating all those extra layers if possible.
How can I refresh the map to show the new dataStyleProp color scale?
HTML:

<button id="update">Update</button>

JS:
mapboxgl.accessToken = "myaccesstoken";
var map = new mapboxgl.Map({
    container: "map",
    style: "mapbox://styles/mystyle",
    center: [-100.04, 38.907],
    minZoom: 3
    });

function loadAll() {
  function getStates() {
    return fetch("data/1790_state_race.json").then(function(response) {
        return response.json();
        });
    }

  getStates().then(function(response) {
    states1790race = response;
    console.log(states1790race);
    });

all = $.when(states1790race);

all.done(function() {

    var vtMatchProp = "GISJOIN";
    var dataMatchProp = "GISJOIN";

    map.on("load", function () {
      map.addSource("states1790", {
            type: "vector",
            url: "mapbox://statessource"
            });

      map.addSource("1790", {
            "type": "vector",
            "url": "mapbox://countiessource"
            });

      if (document.getElementsByName("dataInput").value === undefined) {
        var dataStyleProp = "TOTAL";
        }
    var dataInput = document.getElementsByName("dataInput");
            $("#update").on("click", function() {
                    for (var i = 0; i < dataInput.length; i++) {
                            if (dataInput[i].checked) {
                                dataStyleProp = dataInput[i].value;
                                break;
                                }
                            }
                    console.log(dataStyleProp);

                    //refresh map layer here???

                    });

    var stops = [["0", "rgba(227,227,227,0)"]];
    var numbers1790 = states1790race.map(function(val) {
            return Number(val[dataStyleProp])
            });
    //chroma quantile scale
    var limits1790 = chroma.limits(numbers1790, 'q', 9);

    //chroma color scale
    var colorScale = chroma.scale(["#ffe8c6", "#915c0e"]).mode("lch").colors(10);

    var newData1790 = states1790race.map(function(state) {
        var color = "#e3e3e3";
        for (var i = 0; i < limits1790.length; i++) {
            if (state[dataStyleProp] <= limits1790[i]) {
              color = colorScale[i];
              break;
              }
            }
        var id = state[dataMatchProp];
        return [id, color]
    });

map.addLayer({
        "id": "1790states",
        "source": "states1790",
        "source-layer": "USA-states-1790",
        "type": "fill",
        "layout": { "visibility": "visible" },
            "paint": {
                "fill-color": {
                    "property": vtMatchProp,
                    "type": "categorical",
                    "stops": newData1790
                    },
                "fill-outline-color": "white",
                "fill-opacity": 1
                }
            });

});

map.on("click", function(e) {

        var features = map.queryRenderedFeatures(e.point, { layers: ["1790states", "1790counties" ] });
        map.getCanvas().style.cursor = (features.length) ? "pointer": "";

        var feature = features[0];

        if (feature.properties.COUNTY == undefined) {
            for (var i = 0; i < states1790race.length; i++) {
                if (feature.properties.GISJOIN == states1790race[i].GISJOIN) {
                    total = states1790race[i].TOTAL;
                    free = states1790race[i].FREE;
                    slave = states1790race[i].SLAVE;
                    white = states1790race[i].WHITE;
                    year = states1790race[i].YEAR;
                    document.getElementById("data1").innerHTML = "<input type='radio' checked name='dataInput' value='TOTAL'> Total State Population: " + addCommas(total);
                    document.getElementById("place").innerHTML = feature.properties.STATENAM;
                    }
                }

            } else if

             (feature.properties.COUNTY != undefined) {
            for (var j = 0; j < counties1790race.length; j++) {
                if (feature.properties.GISJOIN == counties1790race[j].GISJOIN) {
                    total = counties1790race[j].TOTAL;
                    free = counties1790race[j].FREE;
                    slave = counties1790race[j].SLAVE;
                    white = counties1790race[j].WHITE;
                    year = counties1790race[j].YEAR;
                    document.getElementById("data1").innerHTML = "<input type='radio' checked name='dataInput' value='TOTAL'> Total County Population: " + addCommas(total);
                    document.getElementById("place").innerHTML = feature.properties.NHGISNAM + " County, " + feature.properties.STATENAM;
                    }
                }
            }

        if (feature.properties.STATENAM != undefined) {
            var buildings = map.querySourceFeatures(e.point);
            document.getElementById("data2").innerHTML = "<input type='radio' name='dataInput' value='FREE'> Free: " + addCommas(free);
            document.getElementById("data3").innerHTML = "<input type='radio' name='dataInput' value='SLAVE'> Slave: " + addCommas(slave);
            document.getElementById("data4").innerHTML = "<input type='radio' name='dataInput' value='WHITE'> White: " + addCommas(white);
            document.getElementById("timeline").innerHTML = "Population in " + year;
            }

    });

  });

}

Answer: I'm a bit confused about what you're trying to do (I don't know what Chroma is), but it looks like you are trying to somehow dynamically update properties of a vector tile source hosted on Mapbox. You can't do this.
You basically have two options for a dynamic data visualisation:

Generate a GeoJSON in the browser, and call map.setData() to display it.
Keep the map data static, but generate a huge data-driven property to visualise it: "If state name = X, draw it pale pink. If state name = Y, draw it pale blue" etc.

If you already have all the data and all the geographies in the tileset, then I'm not clear on what your problem is, or why you have trouble "refreshing" it. Just call setPaintProperty or even setStyle to update the visualisation.
Comment: Yes, I'm trying to dynamically update the color scale and stops (using Chroma.js). Basically, I'd like the user to be able to click on a button to change the map's color scale without me having to create a separate layer for each potential color scale. Option #1 isn't possible because the color scale is a string, not a geojson. Option #2 is what Chroma.js does to style the choropleth. I can't update paintProperty directly because it's  a variable generated by a function (see code). You're right though that what I'm trying to do isn't possible with Mapbox right now. Hope that changes soon.
Comment: I don't understand what you mean by "change the map's color scale"? What is a "color scale"?
Comment: A color scale (https://gka.github.io/chroma.js/#color-scales) maps values to colors for the choropleth.

Mapbox GL JS refresh layer


Google search is not working in Ubuntu 18.04

Question: I have a very peculiar problem. Sometimes Google search is not working. But if you type the website directly it works. Now to check whether it is a problem with my network, I connected the LAN to my laptop working on windows 10 and its working fine.
Comment: What browser are you using? Have you installed any browser addons?
Comment: And ... what error are you seeing?
Comment: Iam using google cgrome. The problem is there in mozilla and brave browsers.
Comment: when i type ping google.com in terminal the error message is:connect: Network is unreachable
In all the other browsers the problem is www.google.com's server IP address could not be found.
Comment: But if  I type directly facebook.com.. its loading
Comment: I have added a screenshot of the browser
Comment: Welcome to AskUbuntu! Please [edit] your question to include the output of `dig google.com` Thank you for helping us help you!
Answer: You probably solved it, but I will write it anyway:
Go to the IP network settings and check what is there in DNS settings.
Add to them the google DNS (184.108.40.206).
I had similar issues when I was only using 220.127.116.11 and 22.214.171.124
It seems that google doesn't want to leave you unattended...
Comment: Can you breafly explain the process


How many Channel Points would I need to complete the game just by skipping?

Question: I've been attempting to complete the game OLDTV just by using the in-game skip mechanic, though I have not been able to reach the end by doing so. The cost to skip constantly increases every few channels and every time I have attempted to do so I've always been left with too little CP to reach past Africa.
Is there an exact number of CP I'd need to complete the whole game just by skipping?
Comment: Huh. I didn't think Stack Exchange allowed single-character tags.
Answer: You will have to farm around 3000CP in order to skip from the beginning all the way to the end. The exact number, in fact, has been found to be 2912.
Source: This Steam guide.


Will a dragon head drop if you kill the dragon with a charged creeper?

Question: If I get a charged creeper to the End, and kill the ender dragon with it, will a dragon head drop, or will I have to find an end ship?
Comment: This is most creative idea ever read
Answer: From Minecraft Gamepedia:

Skeleton, wither skeleton, zombie, and creeper heads are also dropped by the respective mob if it dies due to a charged creeper's explosion. Player heads and dragon heads cannot be obtained as drops.

Hence, you can't use the charged creeper method. Dragon heads are only obtainable in an End city ship, so you have to go to an End city ship to get any Dragon heads.


Camera Pitch/Yaw to Direction Vector

Question: What I'm trying to do is cast a ray from my camera. I know the camera's x, y and z coordinates, as well as its pitch and yaw. I need to calculate its direction vector so I can pass it to my raytracing algorithm.
The camera's up vector is (0, 1, 0). "Pitch", from the perspective of the camera, is looking up and down.
(I would prefer to not use matrices, but I will if I have to)
Comment: Why the objection to matrices? That seems like the most logical way to do it for me. Too confusing, too expensive? If you don't do matrices you'll just have to devise it using a lot of trigonometry, which will end up pretty much doing the same thing.
Answer: Assuming that your coordinate system is set up such that the following conditions are met:
<code>(pitch, yaw)  -> (x, y, z)
(0,     0)    -> (1, 0, 0)
(pi/2,  0)    -> (0, 1, 0)
(0,    -pi/2) -> (0, 0, 1)
</code>
This will calculate (x, y, z):
<code>xzLen = cos(pitch)
x = xzLen * cos(yaw)
y = sin(pitch)
z = xzLen * sin(-yaw)
</code>
Comment: Awesome, this helped me out a lot :D
Comment: @Neil Forrester, what dose xzlen mean ? where can I find math derivation of the formula ?
Comment: `xzLen` is the length of the unit vector in the desired direction after projecting it into the plane containing the x and z axes. The formula follows directly from the definitions of sin() and cos().

Camera Pitch/Yaw to Direction Vector