Cropping a photo with PHP gets stretched

Question: I'm trying to resize and crop a picture.
The picture can be landscape or portrait oriented but I want the thumbnail to be 250x250 and not stretched (crop the sides or the top/bottom but keep most of the image intact in the new size, cropped to square - kinda like wordpress's thumbnails).
This is my function, it's the right size but its stretching the pictures...
What am i doing wrong?
function make_thumb($src, $dest, $desired_width, $ext) {

    if ($ext == 'jpg' || $ext == 'jpeg') {
            $source_image = imagecreatefromjpeg($src);
    }
    if ($ext == 'png') {
            $source_image = imagecreatefrompng($src);
    }
    if ($ext == 'gif') {
            $source_image = imagecreatefromgif($src);
    }

    /* read the source image */
    $width = imagesx($source_image);
    $height = imagesy($source_image);

/* find the "desired height" of this thumbnail, relative to the desired width  */
    $desired_height = floor($height * ($desired_width / $width));
    $desired_height = 250;

    /* create a new, "virtual" image */
    $virtual_image = imagecreatetruecolor($desired_width, $desired_height);

    /* copy source image at a resized size */
    imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

    /* create the physical thumbnail image to its destination */

    if ($ext == 'jpg' || $ext == 'jpeg') {
            imagejpeg($virtual_image, $dest);
    }
    if ($ext == 'png') {
            imagepng($virtual_image, $dest);
    }
    if ($ext == 'gif') {
            imagegif($virtual_image, $dest);
    }
}

Thanks!
Comment: Maybe use `imagecopy` for cropping once you resize the image?
Comment: @Tom No, if you distort the image in your resize copying it is not likely to fix anything is it.
Comment: @RiggsFolly you're right - I was assuming the resize would be done to the correct proportions. Since `imagecopyresampled` can also be used for cropping then using `imagecopy` is a redundant step if you don't want to keep the resided image but only the cropped thumbnail. We don't know that, however.
Answer: Think about what you are saying for a second.
If you change the width of an image and do not change the height in exactly the same proportion as you have the width, the image is always going to get distorted.
You have the code to do it properly, without distortion, although I have not actually tested the calc is correct and then you override that calculation with the arbitrary height of 250. Hence you get a distortion.
Comment out this line and it will probably stop the distortion
$desired_height = 250;

So if you know you always want an image that is 250 height, change the calulation to calulate the proportionate new width rather than passing it in as a parameter.
function make_thumb($src, $dest, $desired_height = 250, $ext) {

    if ($ext == 'jpg' || $ext == 'jpeg') { $source_image = imagecreatefromjpeg($src);  }
    if ($ext == 'png') { $source_image = imagecreatefrompng($src); }
    if ($ext == 'gif') { $source_image = imagecreatefromgif($src); }

    /* read the source image */
    $width = imagesx($source_image);
    $height = imagesy($source_image);

    /* calc the new width */
    $desired_width = floor($width * ($desired_height / $height));

    /* create a new, "virtual" image */
    $virtual_image = imagecreatetruecolor($desired_width, $desired_height);

    /* copy source image at a resized size */
    imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

    /* create the physical thumbnail image to its destination */

    if ($ext == 'jpg' || $ext == 'jpeg') { imagejpeg($virtual_image, $dest); }
    if ($ext == 'png') { imagepng($virtual_image, $dest); }
    if ($ext == 'gif') { imagegif($virtual_image, $dest); }
}

Of course the width will vary a bit depending on the actual size of the original image. But you have to let that happen if you want to stop the distortion.
Comment: Isn't there a way to set it both to 250 by 250 and not compromise on one?
Comment: Only if the original picture size had the Width and Height the same eg a square 1000 x 1000, but photos dont usually come square. You could crop it from its actual size to a square and then reduce it to 250 x 250 but because PHP has no eyes you would not be sure you were getting the good bit of the picture.


How would I make this method loop if a user would input a character other than 'r' or 'c'?

Question: Say, a user would input 'e' so it would show an error dialog but how I loop it back if that would be the case?
 public static char readTypeOfConsumer(){
    Scanner kbd = new Scanner(System.in);
    char typeCode='x';
    do {
        System.out.println("Enter the type consumer< you may type r for
   residential or c for commercial>:");
        typeCode = kbd.next().charAt(0);
        if (typeCode == 'r' || typeCode == 'R') {
            System.out.println("type: Residential");
        } else if (typeCode == 'c' || typeCode == 'C') {
            System.out.println("type: Commercial");
        }
    } while (typeCode == 'r' || typeCode == 'R' || typeCode == 'c'|| typeCode == 'C');

     return typeCode;
}

doing this method has not worked for me unfortunately
Comment: what's your exact problem?
Comment: typeCode is updated in the do statement on first iteration to whatever the first char of the entered user data is.
Comment: my problem would be it not looping, I basically just need to find out how it would loop. As mentioned the do while loop has not worked for me so I need a another approach on how it would loop
Comment: Why dont you create two or statement one would be your whole statement which you have mentioned in while and another one would be not equal to r and c.
Answer: This would work:
public static char readTypeOfConsumer() {
    Scanner kbd = new Scanner(System.in);
    boolean typeCodeInvalid = true;

    char typeCode;
    do {
        typeCodeInvalid = false;
        System.out.println(
                "Enter the type consumer< you may type r for  residential or c for commercial>:");
        typeCode = kbd.next().toLowerCase().charAt(0);
        if (typeCode == 'r') {
            System.out.println("type: Residential");
        } else if (typeCode == 'c') {
            System.out.println("type: Commercial");
        } else {
            typeCodeInvalid = true;
        }

    } while (typeCodeInvalid);

    return typeCode;
}

I've added a boolean which has the value false when the input is accepted, there might be better ways to do this but I'm just going off of the code you've provided. It will just keep looping until r or c is entered.
I've also added toLowerCase() so you do not have to check if it's c or C but just c.
Answer: Please give this a try:
    public static char readTypeOfConsumer(){
   char typeCode='x';

  do {
    System.out.println("Enter the type consumer< you may type r for residential or c for commercial>:");
    Scanner kbd = new Scanner(System.in);

    typeCode = kbd.next().charAt(0);
    if (typeCode == 'r' || typeCode == 'R') {
        System.out.println("type: Residential");
    } else if (typeCode == 'c' || typeCode == 'C') {
        System.out.println("type: Commercial");
    }
} while (typeCode == 'r' || typeCode == 'R' || typeCode == 'c'|| typeCode == 'C');

 return typeCode;

}
}
Comment: How is this supposed to make it work? You've only moved the `Scanner kbd` but not adjusted the `while` loop.


Setting node.js site to auto-start when hosted in Azure Web app

Question: I have a Node.js script that I want to run in Azure on a Web app.
This script is not an express web site, rather it's a worker script which polls a database for work to perform, and when done it just polls and waits, e.g. there is not user interface for it.
I notice that after deploying it, even though it's setup with iisnode, it won't actually start until I fire up a browser and navigate to the Azure Web app host, even though it doesn't have a UI.
Only when I navigate to it does iisnode start logging and fire up my application. Then it happily polls the database and performs the required work.
Does anyone know how you can make a site just automatically start when deployed?
There seem to be autostart web.config settings available with IIS, but I don't know how to get iisnode or the Azure Web app to support it.
I could set up a Web job on the machine that just performs a GET from the site, but that seems a bit of overkill and messy.
Comment: You can get this node script run as an azure function app which is a serverless architecture approach. This can be scheduled and can be triggered based on certain events. I guess you are doing the processing in a loop. so you can schedule this app to start immediately after deployment.
Answer: You can leverage Function App to satisfy your requirement. Also, your original solution which build an Azure Web App without UI should be work.
However, please pay attention that Azure App Services will be unloaded after they have been idle. You can enable the Always on application setting to  keep the app loaded all the time. Please refer to https://azure.microsoft.com/en-us/documentation/articles/web-sites-configure/#application-settings for more details.

Any further concern, please feel free to let me know.
Comment: Thanks for that. My understanding is that there isn't as much logging and debugging support for Function Apps as there is for a full running Web App. Is this still true?
Comment: function app is a kind of Azure App Services, what you can configure in Web apps also can set in Function Apps. Also, you can custom 3rd part nodejs log modules for troubleshooting. You can refer to the update image.
Comment: Thanks very much Gary, I'll have a look at this. Great to see Function Apps  getting more features in Azure.


.NET 4.0 Framework Upgrade Requirements?

Question: What are the requirements for the upcoming .NET 4 release? Searched around for this and couldn't seem to find a definitive answer. Specifically...

Will clients have to upgrade their .NET Framework CLR (like from 1.1 to 2.0) to run 4.0-targeted applications?
Will ASP.NET require a framework upgrade or will behavior be similar to 2.0 running 3.5 apps?
Answer:
Will clients have to upgrade their .NET Framework CLR (like from 1.1 to
  2.0) to run 4.0-targeted applications?

Yes, provided you target .NET 4.0 which has a new CLR version. However, you can target pre-4.0 frameworks to avoid this and run with the previous CLR version.
Check out Scott Guthrie's blog post: Multi-Targeting Support (VS 2010 and .NET 4 Series).
In that post Scott targets the .NET 2.0 and midway through the post there's a screenshot showing ASP.NET running on 2.0 and he writes:

When we run the application using the
  built-in VS web-server, it will run
  using the ASP.NET 2.0 version (and the
  VS 2010 debugger will debug the CLR
  2.0 process)

The post ends with targeting .NET 4.0 and a similar screenshot showing ASP.NET running on 4.0.

Will ASP.NET require a framework upgrade or will behavior be similar to
  2.0 running 3.5 apps?

Scott's post above covers this. Again, it depends on what you target.
In addition, the Multi-Targeting section of the ASP.NET 4.0 whitepaper mentions the ability to use the new ASP.NET 4.0 targetFramework attribute in the Web.config compilation element: <compilation targetFramework="4.0"/>. If you omit it then the target framework is inferred. However, there are other considerations to targeting a framework, for example:

In a .NET Framework 4 application
  pool, the ASP.NET build system assumes
  the .NET Framework 4 as a target if
  the Web.config file does not include
  the targetFramework attribute or if
  the Web.config file is missing. (You
  might have to make coding changes to
  your application to make it run under
  the .NET Framework 4.)

For more considerations visit the aforementioned link.
Answer: As far as I know

Yes, They will. If you are developing with VS2010 then they will need to.
No idea :)

The system requirements can be found on Download page.
Answer: It appears that for webapps they will need to be upgraded.
http://msdn.microsoft.com/en-us/library/dd483478%28VS.100%29.aspx
There are so many changes in .NET Framework 4 that I don't see how you can write code in 3.5 and not be running into the new features.  If you are developing an application with VS2010, then doing this update just makes sense to me.
http://msdn.microsoft.com/en-us/library/dd409230%28VS.100%29.aspx


What can I do to a chain link fence to make it dog proof?

Question: I have a chain link fence which is pretty high but my neighbors' pit bull constantly climbs the fence to get over to my yard.  I am scared of this dog and the Law Dog has been called numerous times about this.
I would really like to put something across the top of my fencing so that I no longer have to fear this dog entering my yard, as I have two Brittany Spaniels and do not want them to be harmed in any way.
I would appreciate any information you can give me to fix this problem.
Comment: I would just call Animal Control (or your local equivalent). If it keeps happening, and the owner isn't doing anything to stop it, they should take the dog away and hopefully find it a better home.
Comment: Clearly you should keep the dog. It likes you better.
Comment: This isn't your problem, if your neighbors cannot keep their dog in their own yard, then they shouldn't have a dog. And please fix your caps lock key.
Comment: Well, you could shoot the dog, once its on your property...
Comment: You are so right, this is not my problem but it has become my problem because my neighbors are ignorant to the fact...they feel they can have a pet but allow it to do whatever it wants...I do not want my girls hurt by this dog so that is why I am asking for suggestions.
Comment: Call the cops. They are rarely fans of loose pit bulls.
Comment: While shooting the dog is completely within the rights of the property owner, I would suggest a less lethal approach. Bear mace, perhaps? I bet it won't jump the fence again if it associates such an unpleasant feeling with your yard.
Comment: If you can you could consider extend the height of the fence.
Answer: Coyote rollers, won't harm children like barb wire, is effective, and can be home owner installed.

A Coyote Roller is a patented ribbed roller that mounts to the top of your fence.  When a coyote or other predator tries to jump your fence to attack your pets, it requires them to grab hold of the top of a fence.  With Coyote Rollers in place, the animals will fall right off of your fence and will not be able to jump over.
Comment: You can make a DIY version of this with PVC pipes suspended on wire run along the top of the fence.  I did this with a wooden fence by installing the wire/pipes between the tops of the wooden fence posts.  Not sure on the best way to secure it with a chain-link fence.
Comment: We had a neighbor with one of these. The coyotes figured that if they couldn't use the top of the fence, they would just jump completely over the fence. Just make sure the fence is high enough.
Answer: I'd get some Barbed Wire arms for the fence.
Since a picture is worth 1000 words,

However, the non technical answer is that it's legally your neighbour's problem.
Depending on your jurisdiction, it might be legal to shoot the dog.
Pitbulls are often great dogs.  But they can also be awful dogs if owned by idiots.
Comment: The barbed wire is probably unnecessary - if you can install the angular brackets with something solid (or even just regular wire), it will prevent the dog from being able to get over without being dangerous for kids
Comment: I like your response :) Although I am against injuring an animal I sure like the idea about the barb-wire..where could I purchase this do you know? And would I be able to do this myself? Thank you again!
Comment: Check out your big box store (Lowes/Home Depot).  They should have these in stock, or at least through order.  I've never done it, but it looks fairly simple to do.  You might need some help tensioning the wire.
Comment: @Steven  good point.
Comment: Dogs can dig too, remember.
Comment: I prefer constantina rolled barb wire!   lol.
Comment: run an electrical cattle wire across the top.  that dog will get a real surprise when he gets to that 40,000 volts!!!!!
Comment: Not that I'm saying this is a BAD pit bull, but pit bulls, in general, have an incredibly high tolerance for pain and if they are aiming to get at something, barbed wire and electric fences will likely pose little-to-no deterrent to the the pit bull. (this is a genetic thing more than anything...hopefully this dog is being raised well and is merely curious in hopping the fence)
Answer: You could put an electric fence wire at the top. They make kits that contain a single wire and are powered by a battery and possibly have a solar charger. They do not harm animals and are usually put down near the ground to stop aninals from digging under.
Answer: Use chain link fence slats.  It will prevent the dog from climbing the fence and also give you privacy.


What is a direct correlation?

Question: I have two contrary definitions of for the direct correlation between two variables $X$ and $Y$

Their correlation coefficient is close to $1$.
There is a direct causal relationship between the variables (ie. there is no $Z$ such that $Z$ causes $X$ and $Z$ causes $Y$)

Which one is correct?
Comment: What does $Z\to X$ mean?
Comment: I assumed that the arrow means "implies" or "causes".
Comment: @StefanHansen I wanted to say "causes" with the right arrow. Edited with plain text. Thanks for pointing out this undefined notation.
Comment: Reference for "positive correlation": [the free dictionary](http://www.thefreedictionary.com/direct+correlation). Reference for "direct cause": [Statistique : Dictionnaire encyclopédique](http://books.google.fr/books?id=PyDEP3M-T4cC&pg=PA104&dq=corr%C3%A9lation+directe&hl=en&sa=X&ei=pB9UUe_WJoeBhQejqIHgAQ&ved=0CC8Q6AEwAA#v=onepage&q=corr%C3%A9lation%20directe&f=false)
Comment: Neither of two can be  (formally, semantically) a definition of "direct correlation". At most, they could correspond to "there is a high direct correlation between X and Y". Formally. Materially, the first actually (and simply) correspond to "high correlation" (plain correlation). The second is is apt but is totally informal and matematically useless (it's rather an interpretation -and questionable-) of a probabilistic property.
Answer: I'm not a statistician (though I taught statistics about 35 years ago). But I'd say that the first definition is correct. One of the important points about correlation is that it should not be confused with causality. Remember the old joke: Smoking and cancer are correlated; does this mean that smoking causes cancer, or that cancer causes smoking. Neither one -- correlation by itself does not imply causality in either direction.
Answer: A correlation in which large values of one variable are associated with large values of the other and small with small; the correlation coefficient is between 0 and +1. Hope this helps
Comment: Is this from [the free dictionary](http://www.thefreedictionary.com/direct+correlation) or another source?

What is a direct correlation?


Why can't I summon my friend to help me?

Question: I've just started my first Dark Souls 2 experience and a friend of mine has offered to help out with some of the bosses. I'm trying to summon him for the Pursuer boss fight, but for some reason we cannot connect. I know SL aren't a problem, he's using a SL 30 character whilst I'm using a SL 26 character. The only other thing I can think of is that I'm playing the original DS2 for Xbox 360 whereas he's playing Scholar of The First Sin, also for the 360. Would that make a difference?
Comment: What do you mean with "cannot connect"? Do you not find the summon sign? Is there an error when he tries to connect?
Comment: Oh Sorry. His Summon sign just does not appear.
Comment: [Soul memory](https://darksouls2.wiki.fextralife.com/Soul+Memory) is what DS2 uses to match up players for coop, not soul level. Just fyi
Comment: Can you see other signs? It might be hard to tell if there's just no one else playing in your range but if you do see other signs at least we'll know that works.
Answer:
I'm playing the original DS2 for Xbox 360 whereas he's playing Scholar of The First Sin

Yes, that's exactly why you can't coop (or invade).
Original DS 2 and Scholar are considered two different games, even with the DLC patch for original DS 2.
I guess the non compatibility issue comes from the fact that enemy placement are different between the two games.
Edit : seems like my answer is right for the PC version but I've stumble on different answer for the consoles version. Will continue to dig.
Comment: So my answer was wrong. On old gens (Ps3 / X360) you should be able to connect to one another if the games are on the same release/update.
Answer: Are either of you a member of the Company of Champions? Summoning is not allowed in this Covenant, and the game is made much more difficult for next to no reward. It's easy to fall prey to this Covenant, as it is one of the first things you can come across in Majula. There are no messages or hints that tell you the nature of this Covenant either, so if you enter it unwittingly, you won't be able to summon your friends, and the game basically becomes NG+.
Additionally, Soul Level is important in Dark Souls 2. If you're grossly overleveled compared to your friend, you won't be able to see their summon sign. The type of soap stone they use is important too. Review and use this page to help calculate what you're doing, and to see what soul levels you can summon.
Comment: If I remember right, it's not just soul level, but also "soul memory" that impacts ability to connect. Soul memory is the total number of souls you have spent throughout the game, whether that be on levels, items, upgrades, spells, etc. This also includes souls that you lost and then failed to recover before dying again.
Comment: @MrSpudtastic Correct! Your soul level is determined by all of those factors. :)
Comment: Slight correction, matching is really done with soul memory, and soul memory is the sum of all souls you earned (except your own bloodstains), not souls spent.
Comment: Soul memory is actually sum of all souls that you came across.  If you lost souls from dying consecutively, the lost souls will count towards your soul memory, but your soul level won't go up (because you didn't spend any souls).


Can I safely add a 50A EV charge circuit breaker to a 90A panel?

Question: I have a sub panel mounted next to my main panel that is supplied with a 90amp breaker. I would like to add a 50 amp breaker to handle a 14-50 plug for an EV charger.
My question is can the sub panel handle the load without overloading? Other than the pool pump, the rest of the breakers handle outlets and switches.
There are four open slots on the right and three on the left.
I installed a 14-50 receptable using 8/3 Romex and fed it into the box. I paused when I thought I may not have enough amps in this panel.
Comment: [Highly related info on EV charging](https://diy.stackexchange.com/questions/277803/im-hearing-about-load-sheds-aka-evems-and-the-devices-differ-whats-that-abou). Also, what does your _load calculation_ say? (Search the internet on how to do a _proper_ load calc - it doesn't involve adding up the amps listed on the breaker handles...)
Answer: Instead of using a "dumb" plug-in EV charger you can upgrade to a smart EVSE which has current probes you can put on the feed of your panel. That will let the EVSE throttle down the car's current consumption when the other loads kick on. That will make sure that panel isn't getting overloaded.
Otherwise You will have to do a actual load calculation, look at all the appliances on that panel and sum up the listed power consumption in Watts of the devices likely to be on at the same time. Then divide that by 240. If it's less than 35A you are fine.
If it's more then you can very likely set the EVSE to draw less current statically.
Comment: Thank you so much for the feedback. I will definitely look into the EVSE. In the few minutes of reading on them I can see how it can benefit and potentially safeguard the vehicle and older homes with aged or revised panels over multiple owners.
Answer: There are five issues here:
8/3 Romex for a 50A Circuit
Look at an ampacity table and you will find that 8 AWG Romex (a.k.a., NM-B) is only rated for 40A. You can use it with a 14-50 receptacle, but only because a 40A receptacle can be used for both 40A and 50A circuits. But you can't use it with a 50A circuit, because 50A > 40A. And you can't use it with 40A continuous for an EV because continuous requires a derate - 40A continuous needs a 50A circuit. So if all the other issues are resolved and you still want to use a 50A circuit/40A actual (whether 14-50 or hardwired) then you need to change to either 6 AWG NM cable (good for up to 55A) or 8 AWG individual wires (e.g., THWN). Wires have to be installed in conduit, which is easy enough for a receptacle right below the panel - just connect it to the panel with a nipple.
14-50 plug for an EV charger
No. Just no.
Install a hardwired EV charger. That has a bunch of benefits:

Eliminates a common point of failure - the receptacle. Many cheaper receptacles, even though UL/ETL-listed, simply don't handle the continuous (several hours at a time) load of EV charging very well.
Removes the GFCI requirement. While not in place in all jurisdictions yet, the latest NEC requires GFCI protection for 240V receptacles. That is not required for a hardwired EV charger because that already includes built-in GFCI protection. In addition, the built-in GFCI protection includes an automatic reset feature, which is (by definition) not the case with an expensive 240V GFCI breaker.

50A (40A actual) Circuit
Most people do not need that large a circuit for EV charging. It gets complicated, but basically most people can charge daily on a 30A (24A actual) or even 20A (16A actual) 240V circuit. That lowers the impact on the panel and the utility service, which can make quite a difference.
Panel Load Calculation
You need to do an actual Load Calculation based on all the area served by the panel (i.e., the area served by general purpose receptacle and lighting circuits) and all specific loads (pool pump, HVAC, cooking equipment, etc.) served by the panel. That will give you a number. Subtract that from the feed to the panel to see how much is available to add to the panel for EV charging. It might be 50A. It might be a lot less.
Service Load Calculation
Do the same type of calculation for the main utility feed (i.e., the main panel). See how much that leaves for the subpanel. It might be 90A (and then the Load Calculation for the subpanel is what really matters) or it might be a lot less, in which case this overrides the subpanel Load Calculation.
If and only if all Load Calculations show that you can spare 50A (40A continuous) for EV charging, then you can proceed to install your 50A/40A charger (preferably hardwired). If the number is lower then you install with that lower number, or you look at load shedding options.
Comment: Thank you so much for your detailed reply. It definitely gives me a lot to think about. Right after this post, I did realize that I incorrectly stated the 8/3 vs the 6/3 actual cable. I am already looking into a hard wired EVSE charger as in the short time I have read about it, it seems to have multiple benefits versus the standard charger that comes with the vehicle. Reason I decided on a 50A was due to the specs on the back of the charger. I did look into a lower breaker, like the 40A but I did not know enough to go in that direction.
Answer: It seems like everyone who buys an EV gets handed a particular pack of misconceptions by the dealer and by people on the Internet. They almost never think about what you thought about, which is called "provisioning": Making sure the supply equipment has the capacity.
To give you some background info, the whole 14-50 RV-park plug is because early EVs were given "travel unit" EVSEs to allow them to outrange the then-quite-poor Supercharger network.  Here's CGP Grey scheming to do exactly that at 11:15 and doing it at 26:14. Tesla did it so everyone copied it. What they didn't do was provide the array of alternate plugs for 15A, 20A, 30A level 2 charging, all of which are fine for 95% of EV drivers who plug in every night.
And an important note on RV parks is they use RV-park grade sockets like the Hubbell or Bryant.  Cheaper sockets like Leviton, ELEGRP, Legrand etc. are imagined for ranges which are plugged in once every 10 years and see intermittent loads.  Experience is the cheapies tend to melt spectacularly under continuous EV loads.  The RV park quality is actually a larger diameter - 2.45" instead of 2.2" (which drives people crazy trying to find cover plates). Note in the video at 26:39 where the socket is a bit small for the hole on the commercial RV stand - cheapie :)
Your house is not a gas station.  Recharging at home is not a "transaction" like buying gas or using a DC fast charger (things you do as rarely as possible since it's a PITA), so shift out of that mentality.  Home charging is a "state of being" - if the car is home it's plugged in.  We call it ABC - Always Be Charging. (Except you set the car's console to only charge during the cheap electric rates, if you have a ToU rate plan).
Of course for that to make sense, charging is best setup to be super easy - a 2-second flick of the wrist every time you come and go.  The "travel unit" experience tends to be all about draping cords over and around things, stowing them, handling dirty or wet cords, and that gets old quick.  As such, I'm nudging you in the direction of a "wall unit" style that is mounted where most convenient for charging.  If you want to get from your current junction box to there, try Legrand Wiremold surface conduit.
Another reason I advise a wall unit is most of them the onboard DIP switches or other adjustment, which lets you make the unit fit for a 15A, 20A, 30A, 40A, 50A or 60A circuit, depending on what your panel can support.
I think the other answers cover most of the other stuff I might say.
Comment: Thank you for taking the time to write back. I really appreciate it. All the responses definitely highlights things that I need to be aware of. As someone new into the EV world, I want to make sure I learn as much as I can. So once again, thank you.


Can't take filename from Apache logs

Question: I have an owncloud seted up myself.
Need to log for the downloads files by users.
I made the bash script which greps Apache logs and pus it to the file.
Example of line in file
<code>/var/log/httpd/ssl_access_log-20200621-22.214.171.124 - - [18/Jun/2020:13:07:33 +0000] "GET /ocs/v2.php/apps/files_sharing/api/v1/shares?format=json&path=%2FHJC%2FMaster-Schedule%20Draft%20for%20SOP%20of%20HJC%20(10.10.2019).xlsx&shared_with_me=true HTTP/1.1" 200 108
</code>
How I can get file name "Master-Schedule Draft for SOP of HJC (10.10.2019).xlsx" ???
Answer: OK. Finally I found decision by using 'sed'
<code>sed 's@+@ @g;s@%@\\x@g' <my-log-file> | xargs -0 printf "%b" > <result-file>
</code>
It decoded URL, so all that remains to be done - get the 'path' value

Can't take filename from Apache logs


publishing installs, can't select "android only" audience?

Question: I am unable to select "Android only" when trying to create my audience for app installs, the radio button is disabled, see image below:

I'm using CoronaSDK for creating a game, and i publish the install when the game launches. I have all of the information setup in the App Information page (package name, class name, key hashes are all filled out).
Any idea what could be keeping me from selecting "Android only" as part of my audience?
Comment: Have you also turned on Single Sign On and Deep Linking?
Comment: No, but I don't have either of those elected for the Native iOS App either, and i can select it without an issue.
Comment: Even after enabling both of those, I'm unable to select "Android only" as an ad platform.
Comment: I had found why I can't have "Android only". There is a few things that i did to show the option for "Android only" (But I am not sure which one is the exact solutions for it but the things i did includes:
Downloading the Facebook SDK into the android application, Create Facebook login option, enable "Single Sign On" and "Deep Linking" as well as in the "Advertise on Facebook" Page, select "Android" in the App Platform drop down list and the "Android only" will show up. But I guess we could only use either iPhone or Android but not both together when creating the ads in Facebook
Answer: It sounds like your development environment is not set up correctly.  I suspect that you haven't downloaded the API Levels needed your project. You need to download that API Level via the SDK Manager too.
http://developer.android.com/tools/help/sdk-manager.html
Also note that the Android SDK requires the 32-bit version of JDK 6, which is not installed on OS X Mavericks by default, so that could be why if that is the case.


Please solve the error of type 'undefined' cannot be used as an index type

Question: Error occurred while using loginType filter.
// interface
export interface LoginTypeInterface {
  google: StaticImageData,
  kakao: StaticImageData,
  naver: StaticImageData,
  facebook: StaticImageData,
  apple: StaticImageData,
}

export interface User {
  // other data...,
  loginType?: string;
};

// images
import icon_facebook from 'image path';
import icon_google from 'image path';
import icon_kakao from 'image path';
import icon_naver from 'image path';
import icon_apple from 'image path';

// filter
export const loginTypeFilter: LoginTypeInterface = {
  'google': icon_google,
  'kakao': icon_kakao,
  'naver': icon_naver,
  'facebook': icon_facebook,
  'apple': icon_apple,
}

// init state
const [ myInfo, setMyInfo ] = useState<User>({
    // other data...,
    loginType: 'kakao'
  });

// get data
axios.get('api path')
.then(res => {
setMyInfo(res.data.data);
}).catch(err => {
// error
})

<Image src={ loginTypeFilter[myInfo.loginType] } alt="image" objectFit="cover" width={100} height={100} />

enter image description here
There is an error when using the filter in the src part of the image tag here.
How can I solve this problem?
Comment: Please do not vandalize your posts.  By posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content (under the [CC BY-SA 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/)). By SE policy, any vandalism will be reverted.
Answer: Fix
In your User interface change the loginType to keyof LoginTypeInterface instead of string.
Explanation
That's because the loginType in your User interface is a string. As far as the TS compiler is concerned, it can hold any string value. While the LoginTypeInterface  interface can only hold one of the 5 defined keys.
Changing the type of loginType "informs" the compiler that this field can only hold one of the defined keys of LoginTypeInterface, and there's no possibility that you're trying to access a key that doesn't exist.


unable to create folder on /mnt via chef recipe

Question: I am using the following chef command to create a folder on /mnt
directory '/mnt/node/deploy' do
  owner 'ubuntu'
  group 'ubuntu'
  mode '0755'
  recursive true
  action :create
end

This is a part of a recipe which is invoked via packer to create an AWS AMI. ubuntu is the user that I use to deploy my code to a provisioned machine.
When I launch an EC2 instance using the AMI, this folder is not created on the machine. What could be the problem? I see no errors when the AMI is created.
Update -1
These are the logs. I tried using root.
`amazon-ebs: * directory[/mnt/node/deploy] action create`
`amazon-ebs: - create new directory /mnt/node/deploy`
`amazon-ebs: - change mode from '' to '0755'`
`amazon-ebs: - change owner from '' to 'root'`
`amazon-ebs: - change group from '' to 'root'`

I see that EC2 is mounting ephemeral storage on /mnt.
I want to create these folders on the ephemeral storage.
I unmounted /mnt, but did not see the folders there.
Comment: The directory creation seems correct. Could you please paste the full Chef log output? Maybe something is mounting there which would make the directory disappear.
Comment: I am suspecting this has something to do with ephemeral storage. EC2 seems to mount the ephemeral storage on /mnt.
Comment: Try umounting `/mnt` and check if the directory is there.
Answer: Packer runs Chef before creating the image. So, if I understand you correctly:

Chef creates the directory on an instance ephemeral storage.
Packer creates the AMI.
You start the AMI and the directory does not exist in the ephemeral storage.

AFAIK that's an expected behavior. The directory is created in a partition that is ephemeral and this kind of partitions are not expected to endure.
Summarizing, when you create an AWS AMI image, it does not include the ephemeral storage. Only the EBS volumes. Ephemeral partitions are always empty at startup. If you want to retain that directory, it must be in a EBS partition.
If you still want to use the /mnt directory, you can avoid mounting the ephemeral storage with the ami_block_device_mappings option:
  "ami_block_device_mappings": [
    {
      "device_name": "/dev/sdb",
      "no_device": true
    }
  ],

And the same for the launch_block_device_mappings
Another solution could be to run your Chef cookbook again in the newly created instance.
Comment: /mnt is the place where ephemeral storage is loaded. The AMI creation process shuts down the instance which clears the ephemeral storage.
Answer: amazon-ebs is the name of the packer builder:

amazon-ebs - Create EBS-backed AMIs by launching a source AMI and
  re-packaging it into a new AMI after provisioning. If in doubt, use
  this builder, which is the easiest to get started with.

It runs the whole machine as EBS-backed so it can convert the EBS volume into an AMI later.
This is not related to Chef.


When passing Strings via intent only one is not null when getting the String values in the next Activity

Question: I am passing strings as intent extras, the following method is passed parameters containing the information I wish to pass via intent, I can see that the values in "mc" and "title" are as they should be in toasts:
 private void addProximityAlert(int id, Double latitude, Double longitude, String title, String mc) {

        Intent intent = new Intent(PROX_ALERT_INTENT);
        intent.putExtra("id", id);
        intent.putExtra("mc", mc);
        intent.putExtra("gl", latitude);
        intent.putExtra("title", title);

        PendingIntent proximityIntent = PendingIntent.getBroadcast(Map.this, id, intent, 0);
        lm.addProximityAlert( latitude, longitude,  POINT_RADIUS,  PROX_ALERT_EXPIRATION,  proximityIntent  );

        Toast.makeText(getApplicationContext(),"INPAMAP "+intent.getStringExtra("title")+intent.getStringExtra("mc"),Toast.LENGTH_SHORT).show();
 }

Now in my next class no matter what I try and do only ever "mc" retains its value, the other variables are always null, here is the next activity:
@Override
public void onReceive(Context context, Intent intent) {

       NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

       Intent notificationIntent = new Intent(context, Map.class);
       PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
       Notification notification = createNotification();

       //Here I can see title is null and mc is what it should be
       Toast.makeText(context,"IN PA "+intent.getStringExtra("title")+intent.getStringExtra("mc") ,Toast.LENGTH_SHORT).show();

I have tried using bundles and this did not work, I am completely clueless as to why only mc is being passed, when mc and title are both strings. I have tried passing only either mc or title and still only mc is not null. I tried to changing the order in which they are passed to the addproximityAlert method and also the order in which they are added as extras, I am out of options. I actually want to know how to debug properly in Eclipse so I can maybe figure out these problems myself before coming to SO, but I am under a lot of time pressure.
I would appreciate advice on how to figure out what my issue is, thank you.
Comment: try to pass `PendingIntent.FLAG_UPDATE_CURRENT` to `PendingIntent.getBroadcast` and `PendingIntent.getActivity`
Comment: `PendingIntent.getBroadcast(Map.this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT)` and the same thing with `PendingIntent.getActivity`
Comment: Can you maybe show an example of how to do this, I am not sure exactly what you mean Vmironov. Thank you!
Comment: Vmironov, this fixed my issue! If you create an answer explaining how adding PendingIntent.FLAG_UPDATE_CURRENT fixed my problem I can accept it as the answer! many thanks, you saved me a whole evening of frustration! :)
Answer: You need to set PendingIntent.FLAG_UPDATE_CURRENT flag in PendingIntent.getXXX methods.
PendingIntent.getBroadcast(Map.this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

The problem is that PendingIntent.getXXX caches intents and can return a previously created instance without updating it. FLAG_UPDATE_CURRENT forces it to update the intent.
You can find more detailed explanation in the official documentation.
Comment: Thank you I needed to know these strings would not all pass, it was driving me crazy, thank you!!! I will study your answer!!
Comment: Thank you! I was banging my head against the wall on this one.
Answer: If you want o figure out your problem using debugger, that's the best way to go. The way it works in eclipse is that you set up break points where you want to stop your code running and see the variables. These can be set by right clicking on the left bar beside any line number.  Now click Debug. You may do this from Project->debug. You may also right click on project and Debug -> Android Application.  Now when the app runs and reaches your break point, it shifts into debug mode. Here you can shift over break points, see variable values at each point.
In addition to this, did you try passing the whole set of values as a list? Something like:
You could pass ArrayList from one the parent activity to the called activity. Here is a sample:
ArrayList<TYPE> value = new ArrayList<TYPE>();
// populate the list
value.add(CALUE);
Intent intent = new Intent(CurrentActivity.this,TargetActivity.class);
intent.putExtra("arraylist", value);
startActivity(intent);

In the target class, you may retrieve the list as follows:
// Call in in OnCreate()
// TYPE can be String, Double etc.
ArrayList<TYPE> list=(ArrayList<TYPE>)getIntent().getSerializableExtra("arraylist");

Hope either of the two thing helps.
Comment: I usually pass as a String array. I can then get the values in any forms. For eg: I can change from
String to Int:
int value = Integer.getInteger(string);
String to Double:
double d = Double.parseDouble(theString);

// If your String value cannot be parsed to double it will throw NumberFormatException.
Comment: Thanks for your advice and your answer! The problem is I pass different types to the next class, int, double and string, I don't think I can store different types in an array? I will try and use debugger to see why the string is not passed with the key, because this is truly a mystery I cannot solve. Thank you!!!


React state is not updating and updates with old data when new one comes

Question: when I use updateCorrectAnswers with useEffect below. it is not updating my correct answers. it shows just empty array. when a new set of api call comes it shows my old data. I don't understand why. console.log image that shows old data and empty data
i revisited some of stackoverflow posts about it but it mostly about useEffect but I am trying inside of useEffect. this is whole code if anyone need https://github.com/hyklops/react-starter/tree/master/quiz-app
function App() {
  const [trivias, setTrivias] = useState(null);
  const [isFetched, setIsFetched] = useState(false);
  const [correctAnswers, setCorrectAnswers] = useState([]);

  const updateCorrectAnswers = () => {
    trivias.map((trivia) => {
      setCorrectAnswers((prev) => [...prev, trivia.correct_answer]);
    });
  };

  async function dataFetch() {
    const res = await fetch(
      "https://opentdb.com/api.php?amount=5&type=multiple"
    );
    const data = await res.json();
    return setTrivias(data.results);
  }

  const shuffle = (trivia, index) => {
    const answers = [...trivia.incorrect_answers, trivia.correct_answer];
    const shuffledAnswers = getRandomAnswers(answers);

    // const shuffleArray = (answer) => [...array].sort(() => Math.random() - 0.5);
    return shuffledAnswers;
  };

  const getRandomAnswers = (answers) => {
    const newAnswers = [];

    while (newAnswers.length !== 4) {
      const getRandomIndex = Math.floor(Math.random() * 4);

      const condition = newAnswers.some(
        (item) => item === answers[getRandomIndex]
      );

      if (!condition) {
        newAnswers.push(answers[getRandomIndex]);
      }
    }

    return newAnswers;
  };

  const getTrivias = () => {
    return trivias.map((trivia, index) => {
      return <Trivia question={trivia.question} answers={shuffle(trivia)} />;
    });
  };

  useEffect(() => {
    dataFetch();
  }, []);

  useEffect(() => {
    if (!!trivias) {
      setIsFetched(true);
      updateCorrectAnswers();
      console.log({ correctAnswers });
    }
  }, [trivias]);

  if (!isFetched) {
    return
loading
;
  }

  return (

{getTrivias()}

        <button>Check Answers</button>

  );
}

export default App;

I tried useEffect and it did'nt worked.
Comment: If you think its not updating just because the log shows an empty array, `setState` is async and the `console.log` statement is called before `setCorrectAnswers` finishes
Answer: This is because you're calling console.log in the same function as you're calling the function to set correct answers. When you're updating state, it doesn't happen synchronously in the same render, so when you're logging correctAnswers right after updateCorrectAnswers, the state is still []. But when you're changing state, a rerender is triggered, in which the state is now the updated state.
To be able to see it, you can just pop a console.log somewhere inside your App like so:
function App() {
  const [trivias, setTrivias] = useState(null);
  const [isFetched, setIsFetched] = useState(false);
  const [correctAnswers, setCorrectAnswers] = useState([]);

  console.log({ correctAnswers });

  const updateCorrectAnswers = () => {
    trivias.map((trivia) => {
      setCorrectAnswers((prev) => [...prev, trivia.correct_answer]);
    });
  };

Or just render it on the screen:
return (

{getTrivias()}

{correctAnswers}

        <button>Check Answers</button>

  );

This article in the doc can help understand this better.
Comment: my problem was `setValue(newValue)` didn't work. now I do this: `setValue(value => newValue)`. thanks man
Answer: When you call 'updateCorrectAnswers();', the correctAnswers are only updated on the next render. Your console log runs in the same render, with the old results.
Answer: The issue you are accessing the value of the same state variable correctAnswers at the level when you are updating. The updated value will be available in the next render only.
You can use a useEffect instead like below.

useEffect(() => {
    if (isFetched) {
      console.log({ correctAnswers });
    }
  }, [isFetched]);


Moto G not listed by Qt Creator / adb after upgrading to 15.10

Question: I developed happily with my Moto G on Ubuntu 15.04 a while ago. I upgraded to 15.10 and now that I tested it again Qt Creator (official 5.5 SDK) doesn't see the device anymore.
Developer mode and USB debugging is enabled just like before.
When I plug in the device I get:
<code>[ 2490.115388] usb 1-3: New USB device found, idVendor=22b8, idProduct=2e76
[ 2490.115402] usb 1-3: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[ 2490.115405] usb 1-3: Product: MotoG3
[ 2490.115407] usb 1-3: Manufacturer: motorola
[ 2490.115409] usb 1-3: SerialNumber: ZY2223HN83
</code>
But:
<code>$ adb devices
List of devices attached

$
</code>
If I kill the server and start it again I can see the device for a while:
<code>$ sudo adb kill-server
$ sudo adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
$ adb devices
List of devices attached
ZY2223HN83  device
</code>
After trying to deploy from Qt Creator (that still doesn't see it) the server goes "out of date":
<code>$ adb devices
adb server is out of date.  killing...
* daemon started successfully *
</code>
Qt Creator shows two(!) ghost devices "ABI is incompatible, device supports ABIs:." in the deploy dialog.
What might cause this? My Qt installation is not changed, either.
Answer: I solved this by removing Ubuntu's android-tools-adb and restarting adb server from the Android SDK installation directory.


Android SDK command line not working on mac

Question: I have my ADT folder at /Users/username/Development/adt-bundle-mac-x86_64-20140702/ and I am trying to set the bash_profile file to work with it because whenever I type "android" or "adb" into the terminal, it returns "-bash: android: command not found".  Right now, my .bash_profile (which is stored at /Users/username/) looks like:
export PATH=$PATH:~/bin
export ANDROID_HOME=/Developer/adt-bundle-mac-x86_64-20140702/
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

After each time I update the file to try something else, I save it and then type "source .bash_profile" into the terminal to refresh the file.  Is it possible that I should be using a command?
I have gone through numerous tutorials on Stack Overflow and other sites, but none of them are working.
Thanks in advance for the help
Comment: What do you see if you type `echo $PATH` ?  Can you invoke those tools if you specify the full pathname of the executable, or might there be a permission issue or path typo as well?
Comment: @ChrisStratton Here's the output:`nicks-mbp:~ nick$ echo $PATH
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/Users/nick/bin:/Developer/adt-bundle-mac-x86_64-20140702//tools:/Developer/adt-bundle-mac-x86_64-20140702//platform-tools`
Answer: Your variable ANDROID_HOME doesn't match the path that you say your ADT folder is located at.  Try changing it to:
export PATH=$PATH:~/bin
export ANDROID_HOME=/Users/username/Development/adt-bundle-mac-x86_64-20140702/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Comment: Usually the way the adt-bundle is laid out there is a sdk/ folder that contains the commands you're looking for, try adding /sdk to the end of the `ANDROID_HOME` variable
Comment: Yes, find the tools and test them with full paths from the command line, *then* update your path.
Comment: Oh, right.  Duh.  I changed ANDROID_HOME, but it still doesn't solve the problem.  Here's the output when I echo the $PATH: `nicks-mbp:~ nick$ echo $PATH
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/Users/nick/bin:/Users/nickstigsell/Development/adt-bundle-mac-x86_64-20140702//tools:/Users/nickstigsell/Development/adt-bundle-mac-x86_64-20140702//platform-tools`
Comment: Take out the backslash at the end of the `ANDROID_HOME` variable, and see if that does it. I've edited my answer
Comment: I removed the trailing slash on line 2: but that doesn't work either. Here's the echo $PATH: `nicks-mbp:~ nick$ echo $PATH
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/Users/nick/bin:/Users/nickstigsell/Development/adt-bundle-mac-x86_64-20140702/tools:/Users/nickstigsell/Development/adt-bundle-mac-x86_64-20140702/platform-tools`
Comment: I notice that your username seems to be different at different points in the path: `/Users/nick/bin` and `/Users/nickstigsell ...`. Which one is your home directory located at?
Comment: It's located at "nick".  I mistakenly typed "nickstigsell" because that's the directory name on my other computers.  I've updated the ANDROID_HOME link but it still doesn't work. `nicks-mbp:~ nick$ echo $PATH
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/Users/nick/bin:/Users/nick/Development/adt-bundle-mac-x86_64-20140702/tools:/Users/nick/Development/adt-bundle-mac-x86_64-20140702/platform-tools`
Comment: What is the output of `ls -l /Users/nick/Development/adt-bundle-mac-x86_64-20140702/platform-tools/adb` (or substitute whatever you put in your $PATH most recently)
Comment: The output was that the file doesn't exist.  I looked at the file path in Finder and then I realized that I was missing the /sdk directory.  Therefore, this is the correct .bash_profile: `export PATH=$PATH:~/bin
export ANDROID_HOME=/Users/nick/Development/adt-bundle-mac-x86_64-20140702/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools`
Comment: Is everything working now then? If so accept the answer so that people know the problem has been solved.
Answer: Have you checked the shell you are using is ksh or bash? I had same problem but after changing from ksh to bash,it worked every time! refer this answer


Find the matrix representative of a linear transformation $T∈L(\mathbb R,\mathbb R^2).$

Question: Let $f(x) =(x^2, \sin x)$. Find the matrix representative of a linear transformation $T∈L(\mathbb R,\mathbb R^2)$ which satisfies $\lim_{h→0}\frac{||f(x+h)−f(x)−T(h)||}{h}= 0.$
The norm part of this problem is throwing me off. I believe I have the right answer for the problem, its just the matrix of the derivatives of $f(x).$ I just don't know how to explain why.
Answer: Start from scratch and calculate:
$f(x+h)-f(x)=((x+h)^2-x^2, \sin (x+h)-\sin x)\Rightarrow $
$f(x+h)-f(x)-T(x)h=((x+h)^2-x^2-T_1(x)h, \sin (x+h)-\sin x-T_2(x)h)\Rightarrow $
$\frac{1}{h}\left(f(x+h)-f(x)-T(x)h\right)=\left(\frac{(x+h)^2-x^2-T_1(x)}{h}, \frac{\sin (x+h)-\sin x-T_2(x)}{h}\right).$
Now, if we choose $T_1(x)=2x$ and $T_2(x)=\cos x$, the limit in your question is zero, as required. And of course, $T_1(x)$ and $T_2(x)$ are the derivatives of $f_1(x)=x^2$ and $f_2(x)=\sin x$.
The matrix representation of $T(x)$ is then $\begin{pmatrix}
2x\\
\cos x
\end{pmatrix}$ and it operates on the "vector" $t\in \mathbb R$ by $\begin{pmatrix}
2x\\
\cos x
\end{pmatrix}t= \begin{pmatrix}
2xt\\
(\cos x)t
\end{pmatrix}.$
Since the domain vector space is just $\mathbb R,$ we can take $t=1$ to recover the definition of the derivative usually seen in elementary calculus courses.
Comment: Thank you or your reply. If I could follow up, I was wondering how does the limit go to zero with those choices of T(x)? I might just not be seeing it.
Comment: Your $\sin x$ should be $\cos x$.
Comment: @MartinArgerami Yes thanks.
Comment: @JohnBeaver: Notice you have the definition of the derivative in each component. Now use the fact that the limit exists iff the limit of each component exists,individually. This latter item is easy to prove using the norm on $\mathbb R^2-$
Answer: Since $T\in L(\mathbb R,\mathbb R^2)$, it is of the form
$$
T_x(y)=(a_xy,c_xy).
$$
for certain $a_x,c_x\in\mathbb R$.
So, for some fixed $x$, we want
$$
\lim_{h\to0}\frac{\Big\|\big((x+h)^2-x^2-a_xh,\sin(x+h)-\sin x-c_xh\big)\Big\|}{h}=0.
$$
The quotient expands to (using the MVT)
$$
\frac{\sqrt{\big((2r_h-a_x)h+h^2\big)^2+\big(h\,(-c_x+\cos s_h)\big)^2}}{h},
$$
where $r_h,s_h$ are between $x$ and $x+h$. Considering the case $h>0$ (the case $h<0$ is similar) the square quotient (which has to go to zero) can be written as
$$
\Big((2r_h-a_x)+h\Big)^2+\Big(-c_x+\cos s_h\Big)^2.
$$
When $h\to0$ it becomes
$$
(2x-a_x)^2+(-c_x+\cos x)^2.
$$
So, to be $0$, we need $a_x=2x$, $c_x=\cos x$. Then
$$
T_xh=(2xh,(\cos x) h).
$$


Lawn mower dies when blades are engaged

Question: I have a 1993 model Craftsman (917.257560) mower. I was having problems with it last weekend when I was trying to get it out. Charged the battery, checked the carb and checked the starter. Everything looked fine. I bypassed the seat safety cause I thought that was the culprit. Put everything back together and it started and purred like a kitten. It was too late to start mowing so I put her up.
Yesterday I was going to mow so I started it up and went to engage the blades and it died. I think there is a safety switch of some sort at the end of the engage/disengage lever under the dash. That is a whole other problem cause I can't figure out how to take the dash off... please advise.
Comment: Cross posting to [other sites](http://mechanics.stackexchange.com/q/28917/511) is not good form here. If you want your question moved to a different stack, please flag it for moderator attention, and they can migrate it.
Comment: Are the blades bound up? Are all the pulleys aligned and free of debris?  Does the belt have a clear path?
Comment: The blades are not bound. Pulleys are fine and belts are fine. I can move the blades by hand.
Comment: This [YouTube video](https://www.youtube.com/watch?v=PaN6F5FDoY0) might be helpful, as it shows you how to access the interlock switch. Though I would replace the switch, rather than bypassing it.
Comment: I don't necessarily want to bypass it. I just want tips right now on how to get to it, if that is what we think the problem is. My mower is definitely not that easy to access.
Answer: Rather than bypassing the various safety systems, either replace it (23 years is not an unreasonable retirement age for a mower) or have it properly repaired (since your "repair" methods don't appear to be oriented that way, take it to somone who is oriented that way.) Rendering the safety systems inoperable is a good way to find out why they were installed in the first place. Perhaps you'll have a child mowing the lawn someday with your customized mower...
Comment: While I understand your concern, I'm not going to pour money into a 23 year old tractor. Which happens to be the reason I'm on the DIY forum...
Comment: Ecnerwal, there's nothing wrong with temporarily bypassing a safety interlock for diagnostic purposes.  Atticus, parts are readily available cheap on Amazon of all places.  If you're going to use it, maintain it.  23 years old says nothing about its remaining service life.

Lawn mower dies when blades are engaged


Limit problem in book: $\lim_{n\to\infty}\frac{1+\sqrt{2}+...+\sqrt{n}}{n^{3/2}}$

Question: My book states that the
$$
\lim_{n\to\infty}\frac{1+\sqrt{2}+...+\sqrt{n}}{n^{3/2}}=
\lim_{n\to\infty}\frac{1}{n}\left[\frac{1+\sqrt{2}+...+\sqrt{n}}{n^{1/2}}\right]=\frac{2}{3}.
$$
But I just don't see it. I was thinking that if the $$\lim_{n\to\infty}\frac{1}{n}=0$$ then the whole thing would equal 0 but I don't see how to get $\frac{2}{3}$. Thanks
Comment: Interpret it as a Riemann or Darboux sum for $\sqrt{x}$ over $[0,1]$.
Comment: yes that is what it is but how do they get that the limit is $\frac{2}{3}$? I know how to get it by calculating the integral of $\sqrt{x}$ from $[0,1]$.
Comment: The limit of the Riemann sums, if it exists, i.e., if the function is Riemann integrable, is just the value of the integral.
Comment: So basically just calculate the integral? I was trying to find the limit value just just like that if I did not know if it was the riemann sum of $\sqrt{X}$ on  $[0,1]$.
Answer: Draw the graph of $y=\sqrt{x}$. In red, draw the rectangle with base $[0,1]$ and height $\sqrt{1}$, the rectangle with base $[1,2]$ and height $\sqrt{2}$, and so on up to the rectangle with base $[n-1,n]$ and height $\sqrt{n}$.
In blue, draw the rectangle with base $[1,2]$ and height $\sqrt{1}$, the rectangle with base $[2,3]$ and height $\sqrt{2}$, and so on up to the rectangle with base $[n,n+1]$ and height $\sqrt{n}$.
Then $\sqrt{1}+\sqrt{2}+\cdots +\sqrt{n}$ is the sum of the areas of the red rectangles, and it is also the sum of the areas of the blue rectangles. Call this sum $S_n$.
Then $S_n$ is greater than the area under $y=\sqrt{x}$ from $x=0$ to $x=n$, and less than the area under $y=\sqrt{x}$ from $x=1$ to $x=n$. Thus
$$\int_0^n \sqrt{x}\,dx\lt S_n\lt \int_1^{n+1} \sqrt{x}\,dx.$$
Calculate. We get
$$\frac{2}{3}n^{3/2} \lt S_n\lt \frac{2}{3} ((n+1)^{3/2}-1).$$
Divide through by $n^{3/2}$. We get
$$\frac{2}{3}\lt \frac{S_n}{n^{3/2}}\lt \frac{2}{3}\frac{(n+1)^{3/2}-1}{n^{3/2}}.$$
Now let $n\to\infty$. The expression $\frac{(n+1)^{3/2}-1}{n^{3/2}}$ has limit $1$, so by Squeezing we get $\lim_{n\to\infty} \frac{S_n}{n^{3/2}}=\frac{2}{3}$.
Answer: As
 $\displaystyle\lim_{n \to \infty} \frac1n\sum_{r=1}^n f\left(\frac rn\right)=\int_0^1f(x)dx$
$$\lim_{n\to\infty}\frac1n\sum_{1\le r\le n}\sqrt{\frac rn}=\int_0^1\sqrt xdx$$
Answer: Another variant is to use the theorem of Cesaro-Stolz. There
\begin{align}
\lim_{n\to\infty}\frac{1+\sqrt2+...+\sqrt n}{n^{3/2}}
&=\lim_{n\to\infty}\frac{\sqrt{n}}{n^{3/2}-(n-1)^{3/2}}
\\
&=\lim_{n\to\infty}\frac{\sqrt{n}(n^{3/2}+(n-1)^{3/2})}{n^3-(n-1)^3}
\\
&=\lim_{n\to\infty}\frac{n^2(1+(1-\tfrac1n)^{3/2})}{3n^2-3n+1}=\frac23
\end{align}


Uniformly continuous homeomorphism from open set to $\mathbb{R}^n$.

Question: Let $U \subset \mathbb{R}^n$ be an open set. Suppose that the map $h:U \to \mathbb{R}^n$ is a homeomorphism from $U$ onto $\mathbb{R}^n$, which is uniformly continuous. Prove $U = \mathbb{R}^n$.
My first attempt guided by intuition was to look at covering $\mathbb{R}^{n}$ by balls of radius $=\frac{1}{n}$ and conclude something forwarding to contradiction by looking at inverse-image of such covering, but I cannot see it for now.
Answer: Here's a sketch of another argument along the line of Daniel Fischer's.
By the connectedness of $\mathbb{R}^n$, it suffices to show $U$ is closed.
 So suppose $x_n \in U$ and $x_n \to x$.  Then $\{x_n\}$ is Cauchy, and it follows from the uniform continuity that $\{f(x_n)\}$ is Cauchy as well.  $\mathbb{R}^n$ is complete, so $f(x_n)$ converges to some $y \in \mathbb{R}^n$.  By the continuity of $f^{-1}$, we have $x_n = f^{-1}(f(x_n)) \to f^{-1}(y)$ so $x = f^{-1}(y)$.  In particular, $x \in U$.
This would work just as well if we replaced $\mathbb{R}^n$ by another connected complete metric space.
Comment: @Silent: Theorem: If $X$ is a connected topological space and $U \subset X$ is both open and closed, then either $U = X$ or $U = \emptyset$.  Proof: If not, then $U$ and $U^c$ are two disjoint nonempty open sets, and we have $X = U \cup U^c$, contradicting the assumption that $X$ was connected.
Comment: Sir, I can't understand why it suffices to show that $U$ closed, given that we know $\Bbb R^n$ connected.
Comment: What if $U$ is the empty set?
Comment: @user439126: There is no homeomorphism from the empty set onto $\mathbb{R}^n$.
Answer: $\mathbb{R}^n$ is a complete metric space. A uniformly continuous map from a metric space $X$ to a complete metric space can be extended to a uniformly continuous map from the completion of $X$ to $Y$.
If $U \neq \mathbb{R}^n$, the extension $\overline{h} \colon \overline{U} \to \mathbb{R}^n$ could not be injective, and that would contradict the assumption that $h\colon U \to \mathbb{R}^n$ is a homeomorphism.
Comment: Hi Daniel. Would you be able to clarify why this would contradict $h$ being a homeomorphism?
Comment: @user124910 For $y \in \overline{U}\setminus U$, there is an $x\in U$ with $\overline{h}(y) = h(x)$. Pick disjoint neighbourhoods (in $\mathbb{R}^n$) $V$ of $y$ and $W$ of $x$. Since $h$ is assumed to be a homeomorphism, $h(W)$ is a neighbourhood of $h(x)$. By continuity of $\overline{h}$, we however have $\varnothing \neq h(V \cap U) \cap h(W)$ - if we chose $V$ small enough, $h(V\cap U) \subset h(W)$ - and thus $h$ can't have been injective.
Answer: Suppose $(p_n) \to p$ for $p_n \in U$. We have by uniform continuity that $\forall \epsilon > 0$, $\exists\delta>0$ $$|x-y|<\delta \implies |hx-hy|<\epsilon$$ Thus, given $\epsilon>0$, we have for sufficiently large $n,m$ that $|p_n-p_m|<\delta$ (since $(p_n)$ is Cauchy) and thus $|hp_n-hp_m|<\epsilon$. So $(hp_n)$ is Cauchy and thus converges in $\mathbb{R}^m$ say $(hp_n) \to q$. Since $h^{-1}$ is continuous, we have $(h^{-1}(hp_n))=(p_n) \to h^{-1}q$ which shows $p=h^{-1}q \in U$. Thus, $U$ is clopen and since $U \ne \emptyset$, $U=\mathbb{R}^m$ by connectedness of $\mathbb{R}^m$.
Note the necessity of uniform continuity since regular continuity does not give a globally applicable $\delta$ to show Cauchyness of $(hp_n)$.


Trigonometric system is complete proof-Lebesgue Integration by parts

Question: Page 8, Chapter 1 in R. Young's "Introduction to non-harmonic analysis". I cannot follow the step: "Integration by parts shows that..."
Theorem 2.
The trigonometric system is complete in $L^2[-\pi,\pi]$.
Proof:
Suppose that
$
\begin{align*}
\int_{-\pi}^{\pi}f(t)e^{-int}dt=0
\end{align*}
$
for some integrable function $f(t)$ defined on $[-\pi,\pi]$ and $n=0,\pm1,\pm2,\dots$
We need to show $f=0$ a.e. Set
$
\begin{align*}
g(t)=\int_{-\pi}^{t}f(u)du
\end{align*}
$
for $t\in[-\pi,\pi]$. Integration by parts shows that:(*)
$
\begin{align*}
\int_{-\pi}^{\pi}\big(g(t)-c\big)e^{-int}dt=0
\end{align*}
$
for every constant $c$ and $n=\pm1,\pm2,\pm3$. Choose $c$ so this holds and for $n=0$ also, and put $F(t)=g(t)-c$. Then $F$ is continuous on $[-\pi,\pi]$ and $F(\pi)=F(-\pi)$. Then by Weierstrass's approximation theorem.. (rest of proof is straight forward)
(*)This is where I am stuck. My attempt:
$
\begin{align*}
g(t)=\int_{-\pi}^{t}f(u)du \implies g'(t)=f(t) \quad a.e,
\end{align*}
$
There are details here, but I think that this is just the generalisation of the Fund. theoerm of calculus to Lebesgue integral. I am not sure about applying this to Lebesgue integrable/differentiable functions. Also, I think continuity of $g(t)$ is required at $t$ to write $ g'(t)=f(t) \quad a.e$, and so doesn't this exclude lots of functions in $L^2$?
Anyway, assuming I can do the above I get:
$
\begin{align*}
\int_{-\pi}^{\pi}f(t)e^{-int}dt=0 &\implies
\int_{-\pi}^{\pi}g'(t)e^{-int}dt=0 \\
&\implies \int_{-\pi}^{\pi}g'(t)e^{-int}dt=g(t)e^{-int}\Big|_{-\pi}^{\pi}+in\int_{-\pi}^{\pi}g(t)e^{-int}dt=0 \\
&\implies g(\pi)e^{-in\pi}-g(-\pi)e^{in\pi}
+in\int_{-\pi}^{\pi}g(t)e^{-int}dt=0 \\
&\implies \frac{g(\pi)e^{-in\pi}}{in}
+\int_{-\pi}^{\pi}g(t)e^{-int}dt=0
\end{align*}
$
Also,
$
\begin{align*}
\int_{-\pi}^{\pi}c \: e^{-int}dt=c \: e^{-int}\Big|_{-\pi}^{\pi}
=c\big((-1)^n-(-1)^n\big)=0
\end{align*}
$
So I guess that I choose
$
\begin{align*}
\frac{g(\pi)e^{-in\pi}}{in}
=\frac{\int_{-\pi}^{\pi}f(u)du\:e^{-in\pi}}{in}=-c \: e^{-int}
\end{align*}
$
Then I get
$
\begin{align*}
-c \: e^{-int}+\int_{-\pi}^{\pi}g(t)e^{-int}dt=0
\end{align*}
$
But I really need:
$
\begin{align*}
\int_{-\pi}^{\pi}(-c \: e^{-int})dt+\int_{-\pi}^{\pi}g(t)e^{-int}dt=0
\end{align*}
$
Any help appreciated.
Comment: If $f$ is Lebesgue integrable on $[a,b]$, then $F(x)=\int_{a}^{x}f(t)dt$ is absolutely continuous on $[a,b]$ with a derivative that exists a.e., and that derivative equals $f$ a.e.. So $F$ is the intergral of its derivative.
Comment: I appreciate the comment, but it only clears up that $g(t)$ is ok. I still don't see how he gets $(*)$.
Comment: Wherever $g$ is differentiable, which is a.e., the Fourier series for $g$ converges to $g(x)$. But you know that the Fourier coefficients for $g$ are all $0$, except possibly the coefficient of $1$. Therefore $g$ is constant a.e., which gives $g'=f=0$ a.e..
Answer:
Also, I think continuity of $g(t)$ is required at $t$

$g$ is the integral of an integrable function, and as such it is continuous everywhere. One can show that with the dominated convergence theorem for example.
In your integration by parts, you overlooked that
$$g(\pi) = g(\pi) - g(-\pi) = \int_{-\pi}^{\pi} f(t)\,dt = \int_{-\pi}^{\pi} f(t) e^{- i\cdot 0\cdot t}\,dt = 0$$
by the assumption on $f$ (using the case $n = 0$), thus you get
$$\int_{-\pi}^{\pi} f(t) e^{-int}\,dt = \int_{-\pi}^{\pi} g'(t) e^{-int}\,dt = g(t)e^{-int}\biggr\rvert_{-\pi}^{\pi} + in \int_{-\pi}^{\pi} g(t)e^{-int}\,dt = in\int_{-\pi}^{\pi} g(t)e^{-int}\,dt.$$
For $n \in \mathbb{Z}\setminus \{0\}$, the assumption on $f$ therefore implies
$$\int_{-\pi}^{\pi} g(t)e^{-int}\,dt = 0.$$
Since also
$$\int_{-\pi}^{\pi} c\cdot e^{-int}\,dt = c\frac{ie^{-int}}{n}\biggr\rvert_{-\pi}^{\pi} = \frac{ci}{n}\bigl(e^{-in\pi} - e^{in\pi}\bigr) = 0$$
for $n\in \mathbb{Z}\setminus \{0\}$ and arbitrary constant $c$, the assertion $(\ast)$ follows. Choosing
$$c = \frac{1}{2\pi}\int_{-\pi}^{\pi} g(t)\,dt$$
then yields
$$\int_{-\pi}^{\pi} \bigl(g(t)- c\bigr)e^{-int}\,dt = 0$$
for all $n\in \mathbb{Z}$.
Comment: Very nice answer, thank you very much for the clarification.


Areas between intersecting chords

Question: In the circle below let the two chords be called $C_1$ and $C_2$, and their intersection be some point that is not the center. The chord power theorem tell us that $a \cdot b = c \cdot d$. I am interested in knowing if there is some similar result for the area of the divided up parts of the circle as well. That is, is there some sort of meaningful relationship between the colored areas? For example, what is the ratio of the total red area to the total area of the circle? What is the ratio of the large red area to the small red area? What information is needed to calculate these/how could I calculate them if I had all the required information?
I have not done any geometry for many years, and I am unsure on how to approach these questions. I was trying to find the ratio between the two red areas, and my idea was to divide the red areas up so that each one consists of a segment and a triangle. Then the two triangles are similar to each other, but I was not sure how to find the area of the segmented areas that remain.
Answer: The area of the upper red portion is
$$A_1=\frac{r^2}{2}\left(2\sin^{-1}\left(\frac{\sqrt{b^2+c^2-2bc\cos\phi}}{2r}\right) -\sin\left(2\sin^{-1}\left(\frac{\sqrt{b^2+c^2-2bc\cos\phi}}{2r}\right)\right)\right)+\frac{bc\sin\phi}{2}$$
This is due to the sum of the area of the triangle and segment bound by $b,c$ and the arc. The last term is the triangle and the first (larger) term is the segment based only on $r,b,c,\phi$ where $\phi$ is the angle between segments $b$ and $c$. Likewise, the are of the lower red portion is
$$A_2=\frac{r^2}{2}\left(2\sin^{-1}\left(\frac{\sqrt{a^2+d^2-2ad\cos\phi}}{2r}\right) -\sin\left(2\sin^{-1}\left(\frac{\sqrt{a^2+d^2-2ad\cos\phi}}{2r}\right)\right)\right)+\frac{ad\sin\phi}{2}$$
Same $\phi$ for both because of they are vertical angles. I'm sure that in conjunction with the identity $ab=cd$ that you started with, some kind of relationship between the two can be made.

Areas between intersecting chords


Terraform Custom Provider - Data Source

Question: I am currently working on a custom Terraform Provider for Jumpcloud and am experiencing some challenges with configuring a custom data source. I see that the Resource schema requires Create, Read, Update, and delete.
I am just wanting to run an API query in Terraform so that I can return a list of users and use those users in a for loop.
Below is the API call that I have tagged as a schema.Resource
func userquery() *schema.Resource {
    apiKey := ""
    userGroupID := ""

    contentType := "application/json"
    accept := "application/json"

    // Instantiate the API client
    client := jcapiv2.NewAPIClient(jcapiv2.NewConfiguration())

    // Set up the API key via context
    auth := context.WithValue(context.TODO(), jcapiv2.ContextAPIKey, jcapiv2.APIKey{
        Key: apiKey,
    })

    // Make an API call to retrieve a specific user group by ID
    userGroup, res, err := client.UserGroupsApi.GroupsUserGet(auth, userGroupID, contentType, accept, nil)
    if err != nil {
        fmt.Printf("Error retrieving user group %s: %s - response = %+v\n", userGroupID, err, res)
    } else {
        fmt.Printf("Details for User group %s: %+v\n", userGroupID, userGroup)
    }

    return nil

}

This is the mapping
ResourcesMap: map[string]*schema.Resource{
            "jumpcloud_user":                  resourceUser(),
            "jumpcloud_user_group":            resourceUserGroup(),
            "jumpcloud_user_group_membership": resourceUserGroupMembership(),
            "jumpcloud_user_query":            userquery(),

        },

And this is the error that I am receiving. What is interesting is that this is returning the name correctly from the API call however, there is still an error...
Comment: This looks like you added an extra function and argument to a resource, and not created a new data source.
Comment: yes, I am unsure how to add an actual data source in the provider
Answer: I don't have much experience working with Terraform but forwarded this thread to a coworker who does and this is what they sent me
"The user is trying to build a custom datasource for his custom JC provider instead of a resource.  I've had minimal experience with this, however, his error seems like there's an issue with how he's building his plugin but there is no information on what version of terraform or golang he is using so I'm would be unable to help there. I would suggest referencing the custom JC provider (https://github.com/sagewave/terraform-provider-jumpcloud) since they have some custom data sources built but there aren't any custom data sources that are jumpcloud specific. Hope that helps."
Have you checked out this JC terraform provider to see if it will fit your use case?
https://github.com/sagewave/terraform-provider-jumpcloud
Cheers
Comment: you should probably accept this answer or post your own answer to this question
Comment: I have not and this is the exact example that I need. Thank you for your help!

Terraform Custom Provider - Data Source


Emptying a PHP array

Question: I want to clear all elements from an array object (which can be a standard PHP array, an ArrayObject or basically any other object that implements the basic array interfaces such as Itertable, ArrayAccess, Countable etc.). However, I do not want to reinstate the object, so I somehow have to unset all the individual elements, instead of creating a new object of the same type. Is there an easy way to do this?
Comment: Why don't you want to reinstate an object/array?
Comment: Because the object is a function parameter, and I do not necessarily have knowledge of where it comes from or how to instantiate it.
Answer: foreach ($array as $key => $element) {
    unset($array[$key]);
}

This requires both Traversable and ArrayAccess, Countable is not required. Or obviously just a normal array.
Comment: Using that gives me the following error: ArrayIterator::next(): Array was modified outside object and internal position is no longer valid
Comment: @mrjames: Hm, seems like arrayiterator is pretty strict. On arrayobject I would simply call `exchangeArray`, but arrayiterator doesn't have something like this.
Answer: I'm not entirely sure why you need to do it this way, but in answer to your question, you should be able to simply use the array_splice function to remove all of the objects from your array;
$my_array = array('A', 'B', 'C');
array_splice($my_array, 0);

I've never used array_splice to remove all objects from an array, but I assume it works in the same manner.
Comment: @nikic Ahh, my bad. Upvote given to your answer as it better matches the question criteria!
Answer: I am having trouble deciphering what the question is really asking for. Replacing the array/iterator with an empty iterator (an EmptyIterator, or another iterator with no values?) might suffice.
$array = new EmptyIterator;

Answer: Try
$my_array = array('A', 'B', 'C');
unset($my_array);

Answer: What about a simple unset?
unset($array);
Answer: In case you remove the last record from array than the next foreach loop can fail (internaly calling $this->next() )
So it helped me to test the validy and break in this case the next loop.
deleteOffset = true;

foreach ($iterator as $key => $value)
    {
            if ($deleteOffset && $iterator->offsetExists($key) )
            {
                 $iterator->offsetUnset($key);
            }

        //if remove last record than the foreach ( $this->next() ) fails so
        //we have to break in this case the next ->next call

        if (!$iterator->valid()) break;

    }

Answer: The best place PHP Manual
http://php.net/manual/en/function.unset.php

Emptying a PHP array


If the order of 3 modulo $p$ is $q$, why are $1, 3, 3^2, ..., 3^{q-1}$ all distinct (mod $p$)?

Question: Really confused on going about proving this. I know $1,3,3^2,...3^{q-1}$ can't be congruent to $1$ mod $p$, as that would imply the order isn't $q$. But I'm not sure how to go about showing these numbers are distinct mod $p$.
Answer: Because if $3^i \equiv 3^j$ where $1<i<j<q$, then $3^{j-i} \equiv 1$ would contradict the fact that $q$ is the smallest positive integer with $3^q \equiv 1$.


Do manufactories and Customs Houses sacrifice the Strategic or luxury resources on those tiles?

Question: I cannot figure out if using my GE or GM to build a manufactory or customs house on a tile with a strategic or luxury resource in it sacrifices that resource.
I'm also wondering if there is any benefit to building those improvements on tiles with resources.
The Customs house description says it will connect a resource to the trade network but how does that help nix the city it's worked by is already connected via trade route?
Answer: "A resource is connected to the trade network" means an appropriate building was constructed on that resource and it may now be used or traded to other civilizations.  Trade routes are about connecting your cities to the capital by roads and harbors and then generating gold automatically from the connection.  Trade network and trade routes don't have anything to do with each other.
A great person's improvement can connect strategic resources but not luxury resources.  The type of the improvement does not matter - a manufactory, a landmark and a custom house provide the same amount of iron when built on an iron resource.
The reason great person improvements are allowed to connect strategic resources, is that strategic resource aren't revealed on the map until the cooresponding technology is researched.  It would be a disaster to require someone to tear down their landmark just to get to the Aluminum that appeared underneath it.
Luxury resources are shown at the start of the game and so this grace in the rules does not apply to them.
Comment: This is the right answer but the definition of trade route is obsolete given the new expansion. What was formerly called a trade route is now called a city connection, and a new mechanic exists for international trade routes
Answer: Yes you do get strategic resources linked into your network.  They do not get luxury resources.
From the 126.96.36.1992 patch notes

All great person tile improvements now connect all strategic
  resources.

You do not however get the bonus to production or income that you would normally get from building the corresponding improvement.
The benefit of building a great person building on a resource tile is that the resource improves the output of that tile, so you can collect the tile output and the bonus from the great person's building with a single citizen.  It also allows you to use Citadels to help defend important resources.
Answer: All the great people improvement (Citadel, Manufactory, Customs House, Academy and Landmark) connect strategic resources, but do not connect luxury resources.
Regarding trade routes - I think you might be confused: trade routes have no relation to strategic or luxury resources. Once you improve a luxury or strategic resource, you get the benefit from it, no matter where that improvement is (might be a far-away, isolated city) and no matter if there's a citizen working the tile or not.


Hive failed with java.io.IOException(Max block location exceeded for split .... splitsize: 45 maxsize: 10)

Question: The hive does need to process 45 files. Each size is about 1GB. After the mapper execution finished 100%, hive Failed with the error message above.
<code>Driver returned: 1.  Errors: OK
Hive history file=/tmp/hue/hive_job_log_hue_201308221004_1738621649.txt
Total MapReduce jobs = 3
Launching Job 1 out of 3
Number of reduce tasks is set to 0 since there's no reduce operator
Starting Job = job_1376898282169_0441, Tracking URL = http://SH02SVR2882.hadoop.sh2.ctripcorp.com:8088/proxy/application_1376898282169_0441/
Kill Command = //usr/lib/hadoop/bin/hadoop job  -kill job_1376898282169_0441
Hadoop job information for Stage-1: number of mappers: 236; number of reducers: 0
2013-08-22 10:04:40,205 Stage-1 map = 0%,  reduce = 0%
2013-08-22 10:05:07,486 Stage-1 map = 1%,  reduce = 0%, Cumulative CPU 121.28 sec
.......................
2013-08-22 10:09:18,625 Stage-1 map = 100%,  reduce = 0%, Cumulative CPU 7707.18 sec
MapReduce Total cumulative CPU time: 0 days 2 hours 8 minutes 27 seconds 180 msec
Ended Job = job_1376898282169_0441
Ended Job = -541447549, job is filtered out (removed at runtime).
Ended Job = -1652692814, job is filtered out (removed at runtime).
Launching Job 3 out of 3
Number of reduce tasks is set to 0 since there's no reduce operator
Job Submission failed with exception
'java.io.IOException(Max block location exceeded for split: Paths:/tmp/hive-beeswax-logging/hive_2013-08-22_10-04-32_755_6427103839442439579/-ext-10001/000009_0:0+28909,....,/tmp/hive-beeswax-logging/hive_2013-08-22_10-04-32_755_6427103839442439579/-ext-10001/000218_0:0+45856
Locations:10.8.75.17:...:10.8.75.20:; InputFormatClass: org.apache.hadoop.mapred.TextInputFormat
 splitsize: 45 maxsize: 10)'
FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.MapRedTask
MapReduce Jobs Launched:
Job 0: Map: 236   Cumulative CPU: 7707.18 sec   HDFS Read: 63319449229 HDFS Write: 8603165 SUCCESS
Total MapReduce CPU Time Spent: 0 days 2 hours 8 minutes 27 seconds 180 msec
</code>
But I didn't set the maxsize. Executed many times but got the same error. I tried to add mapreduce.jobtracker.split.metainfo.maxsize property for hive. But in this case, hive failed without any map work.
Comment: What's the query you're running?
Comment: The hql is just a select * from table. Nothing special.
Answer: set mapreduce.job.max.split.locations > 45
In our situation it solved problem.
Comment: Would really appreciate an explanation / background of the "split.locations" configuration means in Hive - please?
Comment: Yes this solve the proble but > is not working there.

query should be :
set mapreduce.job.max.split.locations = 45 (or any value above than 45)


Create a raycast in spritekit

Question: I am building a game using Spritekit and am trying to build a raycast that will connect the player with the point where the player tapped. It will be like a rope that connects the player to the point where he or she tapped. For example if a player taps at the point x: 0, y: 0 then it will become a rope that connects both things with each other. With the time the rope will become shorter and the player will be dragged against it. The player does have a physicsbody. When the player releases the finger the rope will be remove and the player are not going to be dragged to that point anymore.
I want to archive the same thing as if you search raycast in unity but with spritekit.
I know how to implement the touch function as well as when he or she releases a touch. So the question is how do I make a raycast as described. I would also like to have some sort of visual effect which means a skshapenode or something that indicates where the player is going.
Have tried using SkPhysicsJoints but I'm not successful.
Any help would be appreciated!
Comment: Why do you need a ray cast?  Sounds like a simple line segment to me
Comment: The point is that the player will be connect by a rope to where he or she taps. For every one second or so the rope will become shorter and the player will be dragged with physics against that point. If you are able to do that with line segment than it's absolutly okey. Could you possible show code about how to implement it? Thanks!
Comment: Huh?  That is not a ray cast nor a line segment.  You need to rework this question to better explain what you are trying to do.
Comment: Have updated the question. Thanks for your effort!
Answer: Raycast is supported by physicsWorld object on your scene, with the method
func enumerateBodies(alongRayStart start: CGPoint, end: CGPoint, using block: @escaping (SKPhysicsBody, CGPoint, CGVector, UnsafeMutablePointer<ObjCBool>) -> Void)

You can use like this:
self.physicsWorld.enumerateBodies(alongRayStart: playerPosition, end: clickPosition) { body, point, vector, object in
    if let node = body.node as? SKSpriteNode {
        node.color = SKColor.red.withAlphaComponent(0.2)
        let pointNode = SKSpriteNode(color: .cyan, size: CGSize(width: 5, height: 5))
        pointNode.position = point
        let path = CGMutablePath()
        path.move(to: playerPosition)
        path.addLine(to: clickPosition)
        path.closeSubpath()
        let line = SKShapeNode(path: path)
        line.strokeColor = .green
        line.fillColor = .green
        self.addChild(line)
        self.addChild(pointNode)
    }
}

And get this result on each click:

The complete example it's here: https://github.com/Maetschl/SpriteKitExamples/blob/master/Raycast2dLinesVsObjects/Raycast2dLinesVsObjects/GameScene.swift

Create a raycast in spritekit


Can I get `cabal install` to use multiple cores?

Question: Does anyone know how to get cabal install to exploit parallelism?  I'm compiling with GHC, and while I don't know if GHC itself can do parallel builds, surely cabal install could run multiple compilations in parallel, no?  At least for distinct, independent packages?
Does anyone know if it is possible and how to do it?
Comment: @amindfv: for me, the bottleneck is compiling dozens of haskell source files.   And about dependencies, like parallel make, parallel `cabal install` would have to respect them.  But there is still parallelism available to be had.
Comment: What's the motivation for this? Isn't the main bottleneck for cabal the network transfers? Also, couldn't build errors bump into each other, if there are shared dependencies?
Comment: there's also an open [stack issue](https://github.com/commercialhaskell/stack/issues/644)... (if you're using stack instead of cabal-install)
Answer: I'm the one who was working on this Summer of Code project. The patches have been sent to Duncan, but he hasn't reviewed them yet. Note that my code works at the package granularity, so you won't get any speedup when building a single package. I'm currently working on a parallel wrapper around ghc --make, which will solve this problem (I hope to get it merged into the mainline cabal-install eventually).
Update (Feb. 2012): Duncan has reviewed my patches, I need to incorporate his feedback and resubmit them. I hope to get this done before the end of this month.
Update (Apr. 2012): I've updated my patches in response to Duncan's comments. The new code is a bit slower, but requires much less changes to the Cabal library.
Update (Jun. 2012): Duncan Coutts just merged the parallel branch into Cabal HEAD. Parallel install will be available in the next cabal-install release.
Update (Oct. 2012): cabal-install1.16.0 has just been released. This is the first official release that includes my parallel patches.
Comment: @nh2 Maybe I should write a blog post about the current status of parallel install. For now, you can follow the discussion [here](https://github.com/haskell/cabal/issues/976). Short answer: add a line 'jobs: n' (where n is a positive integer) to your `~/.cabal/config`; this makes `cabal install` use n threads. This is only package-level parallelism; modules and components are not built in parallel.
Comment: @nh2 The next Haskell Platform (2012.4.0.0) will use cabal-install 0.14 and GHC 7.4.2. I expect the 2013.2.0.0 release to ship with cabal-install 1.16 and a more recent GHC.
Comment: That is fantastic! Can you give us a short summary about what the final patch can do? Are normal/profiling compilations parallel? Do single packages now use multiple cores? Thank you.
Comment: And what is the state of `ghc-parmake`?
Comment: @nh2 Regarding `ghc-parmake`, it works in some cases, but there are known bugs (can't build libs for profiling, can't build large projects such as uhc, etc). I'm working on another Cabal-related project (sandboxes), so I don't have time to spend on `ghc-parmake` or parallel `cabal build` right now. Maybe after the end of this GSoC.
Comment: I tried the cabal HEAD today (with GHC 7.4.1, and there was a type error, which I solved by deleting code, hehe), and it works pretty well! Will this be in the next Haskell platform?
Comment: If the next Haskell Platform will ship with cabal-install 0.16, then yes.
Comment: Great, looking forward to that!
Comment: With my recent `cabal update`, I got `Note: there is a new version of cabal-install available`, so a `cabal install cabal-install` now gave me 0.16, even on the Haskell Platform 2012.
Answer: Completing Mikhail Glushenkov's answer to document the usage a bit:
As of cabal 1.16.0, you can now use
cabal install -j [pkgs…]

This defaults to one job per core.  It also gives much cleaner output.
You can make parallel installs the default with:
echo "jobs: $(getconf _NPROCESSORS_ONLN)" >> ~/.cabal/config

Or (cabal-install 1.18+):
echo 'jobs: $ncpus' >> ~/.cabal/config

Get the latest cabal-install with:
cabal update
cabal install cabal-install --bindir ~/bin --upgrade-dependencies

Comment: As of [Cabal 1.18](https://github.com/haskell/cabal/commit/99264248db78835b308232943038e6cbce4e72a4) you can set `jobs` setting to `$ncpus` or a number of jobs to run.
Answer: There was a Google Summer of Code project this summer to parallelize cabal-install. While it hasn't been merged into the mainline yet, the linked article provides instructions for grabbing the source and building it yourself.
Comment: @donatello: See the update in Mikhail's answer below. I'll see if I can get the link fixed.


Does the Steam Deck preorder page tell you when your reservation is ready for purchase?

Question: This question is primarily aimed at people who were already able to purchase the Steam Deck they placed a reservation for, or just anyone who has seen or knows the exact process.
As far as I understand, Valve sends emails to everyone who reserved a Steam Deck, in the order that those reservations were made, in weekly batches, the first of which was sent yesterday at the time of writing. Those emails are said to contain a link where you have 72 hours to make the actual purchase.
Is that email the only way to actually purchase the Steam Deck, or can you also tell that it's your turn and proceed with the purchase inside Steam itself? Specifically, I'm talking about the official store page, which (for me) currently displays the date the reservation was made, the expected quarter of the year it will be available to order, and a "Cancel Reservation" button. Will that button be replaced by the option to purchase when it becomes possible, or do you just have to pay close attention to your emails?
Answer: Yes.
Once your Steam Deck reservation is ready to be purchased, the part of the store page that would previously show the expected order availability changes to this:

Additionally, the following notification appears in the top right of the desktop Steam client (next to where your profile links and account balance are):

Clicking on this opens a popup which also lets you know that you can now order the Steam Deck, and should do so within the next few days unless you want your deposit to be refunded instead.


What are X apps in ubuntu

Question: I was monitoring my system using Netdata today, and noticed that, some kind of X apps are using more CPU than other applications.

Look clearly in the image, X is taking a larger CPU% time than others.
Not only CPU, but everything like Disk, Swap, Net, Memory and Processes.
I searched for it on the web, but I couldn't get a clear view.
Please explain.
Thank you.
Answer: X is your display server that shows all the graphics on your screen. See more on Wikipedia about Xorg.
Comment: It has a number of features, but primarily its used to simply show everything on your screen. The spikes in your graph are probably when you open a new web page, load a video or app, etc.
Comment: Also note the CPU percentage usage. CPU usage of 100%+ maybe okay. It depends on how many cores you have on your CPU. Keeping it simple, you have 100% of each core to use, so if you have 4 cores on your system, you have 400% to play with. So it is only concerned if you see stuff using up to 400%. X using 100% here and there means it is only using one core for a short period of time, which is normal. I would need to know more about your hardware though to help you. Usually in Linux we use system load as a better way of determining how utilized a system is.
Comment: only graphics or system processes also ?
Comment: thanks for this extra info, it was explanatory to many things

What are X apps in ubuntu


NHibernate check for same join in QueryOver

Question: Using QueryOver I am creating a query like this
BulkActionItem bulkActionItemAlias1 = null;
BulkActionItem bulkActionItemAlias2 = null;

var query = GetSession().QueryOver<Student>(() => studentAlias)
        .JoinAlias(() => studentAlias.BulkNotifications, () => bulkActionItemAlias1, NHibernate.SqlCommand.JoinType.LeftOuterJoin);

if (query.UnderlyingCriteria.GetCriteriaByAlias("bulkActionItemAlias2") == null
    query = query.JoinAlias(() => studentAlias.BulkNotifications, () => bulkActionItemAlias2, NHibernate.SqlCommand.JoinType.LeftOuterJoin);

This will crash because I have the same join twice with different aliases. Is it possible to check if a join already exists on a query, even with a different alias?
Comment: You're always joining to `BulkNotifications`, so why join again inside the `if` statement?
Comment: This is just a snippet. In the complete complete code there are good reasons, ie the joins are added by extension methods depending on the required criteria.
Answer: I haven't found a built-in way to accomplish this. Typically I use an out parameter with extension methods to keep track of what tables are part of the query. For example:
bool joinedOnBulkNotifications;

BulkNotification notificationAlias = null;

Expression<Func<object>> aliasExpr = () => notificationAlias;

var query = GetSession().QueryOver<Student>(() => studentAlias)
    .FilterByBulkNotificationStatus(
        someCondition, aliasExpr, out joinedOnBulkNotifications);

public static class QueryExtensions
{
    public static IQueryOver<Student, Student> FilterByBulkNotificationStatus(
        this IQueryOver<Student, Student> query,
        bool someCondition,
        Expression<Func<object>> aliasExpr,
        out bool joinedOnBulkNotifications)
    {
        joinedOnBulkNotifications = false;

        if (someCondition)
        {
            joinedOnBulkNotifications = true;
            query.JoinAlias(s => s.BulkNotifications, aliasExpr);
        }

        return query;
    }
}

The issue is that you might need to reuse the alias you created later. You might be tempted to pass in a BulkNotification and use that, but this only works if the parameter name matches the name of the variable you pass to the extension method. NHibernate uses the name of the variable to create an alias name, so if these two do not match, you'll get an error. Because of this, you need to wrap the alias in an Expression and use that instead.
This isn't a very clean option, so I hope someone has a better solution.


How to reinforce a flimsy settee?

Question: we have a Settee that does not feel very sturdy. It is rated at 250 lbs and there is a slight wobble. What can I do to make it steadier and more load bearing? (e.g. 400lb)
Here is the settee: http://www.wayfair.com/Skyline-Furniture-Velvet-Settee-Loveseat-I-6006-SKY1440.html
Here are the instructions: https://i.stack.imgur.com/loc5Q.jpg
Structually, it's essentially two solid wood sides and a bench held together by four 5/16th bolts.
Am I right in thinking that the legs are the weak point?
Comment: Note that couch weight limits are typically listed on a **per-seat** basis.  Your settee should safely hold **two** people who are each up to 250lbs.  If your family is bigger than this you generally need to shop for furniture specially designed for larger people.  Augmenting the structure would, of course, be possible, but it's altogether easier and cheaper to just buy the right thing to start.
Comment: Adding another pair of legs in the centre would probably be the easiest, but it's likely even the [internal bracing](https://designbigger.com/what-is-the-weight-capacity-of-an-average-couch/) would need to be augmented. (link for an example of how these things can fail internally when overloaded).
Answer: According to the instructions, it appears that there are six washers and nuts holding it together. If you only used four, that might be a problem. ;)
I would go back over the piece, checking the tightness of the nuts. Side-to-side motion is likely a problem with the nuts, not the legs.
Comment: Not any suggestions that don't involve getting into upholstery. You could conceivably get into the settee and add internal bracing, but then you'd have to fix the appearance of those repairs, etc. (If you're actually interested in that kind of thing, I can highly recommend the 'Furniture Guys' book on repair.
Comment: Haha yes, I did use all 6 washers and nuts. I will check the tightness again. Any suggestions for the fact that it is rated to be only 250 lbs weigh limited?
Comment: Time to go to the library!

How to reinforce a flimsy settee?


What is the difference between these healing perks?

Question: I am unsure what the differences are between these sets 2-piece healing bonus perks on artefact sets. They looks identical to me, just with different wording.

Character Healing Effectiveness +15%

Healing Bonus +15%

What are different bonuses doing?
Comment: Don't know anything about the game, but *healing effectiveness* sounds like out going health (like healing an ally) while *healing bonus* sounds like your personal healing only.
Answer: Should be exactly the same.
If you look at the artifact summary screen (don't mind the actual number, this is just a random screen I found on Google)

you should notice that in both cases the "Healing Bonus" parameter is increased by 15%. So this is just inconsistent wording.
Note that this is different from the 2p bonus on Traveling Doctor, which only increases the effect of received healing.