Header image resizing HTML/CSS

Question: I have a problem with resizing the header image so that it fits the heading size. Both the image and the heading are in the same div but I can't seem to find the solution. I had one where it looked good on the laptop, but on a smartphone, where the screen is smaller, the image was way smaller than the heading.
I tried with several height units: %, em, rem and vh, but nothing seemed to work correctly. I also tried to have a fixed div height and using object-fit with contain or size-down + max height of the image as 100%, but that also didn't work. Additionally, I am not sure about giving the div a fixed height - won't it look out of scale when viewing on various devices?
What I need is to have the home icon on the left at the same level as the heading + both having the same height, no matter what device and screen size I'm on. The heading should stay centered. Does anyone have any idea what I'm doing wrong? Below the html and css - one of many versions I checked.
Apologies if the code isn't very clean, it's only my second project.
HTML:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Photo Gallery</title>
    <link rel="stylesheet" href="gallery-styles.css" />

        <img
          id="home-icon"
          src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAhFBMVEX///8AAACampqgoKBOTk7p6ekpKSn8/Pz29va4uLhcXFzh4eH5+fkxMTEPDw/z8/NEREQ3NzcgICDl5eW/v788PDzX19dra2vHx8dJSUnt7e2oqKg1NTWEhIR9fX2xsbGRkZEVFRWKiookJCTR0dGAgICUlJR0dHRoaGhiYmJWVlYLCwtDLsDCAAAH+klEQVR4nO2d6WKyOhCGcV9QUVHc6kLlq229//s7Wm3BmSQMYQuceX+2LHkwzJaQWI26yyq7AbmLCasvJqy+mLD6YsLqq2jC4f7UbH0VecciCSd7z3pocZYedO4m1VV91wIJPxzrT/295KC9lVjuWHnbwggP29d2BTPRUf+SA1pWx1fduCDCoY0b1sSHzXUALctT3boQwuVa2DD3Gx7Y1iPcqm5eAOF115M17QisxJceYUd1+/wJL46ibc7ny7GrChK2vZjWrbuVJpwf45s3eq8w4V7VQUN5fxanYoTTuA4a6lhFQkoHDdU/VI7w3za+YS8K2rezLpUhnAYa7Tz6OlFpOYQ7vYaOdoLYzkTCS9IOmlrFEk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WopGEKYQWF2ZCJkxDOMljLU0mZEImZML/GeGVuLdbdQnh6tpMyIRMyIQ5EOaxPjETMiETMiET1o0wjw0lmLBYwjy2bjOLMI9NJcwizGPnGi3CuIZoE+ax84lgj6N4wo16G6sg4XhmKPmSA9rytPYoabRViEHCQfeoMi/UuL7ibqqddJZNqfDWbAm0ackvrKOW8mnH7PdUAzFh9cWE1RcTVl9MWH3Vn/A/ffrIdwEnvgkAAAAASUVORK5CYII="
      />

Luna's photos

CSS:
* {
  box-sizing: border-box;
}

body {
  margin: 0;
  font-family: Verdana, sans-serif;
  background: black;
}

/* for header size visibility - remove later */
#top-row {
  border: 1px solid white;
}

#home-icon {
  position: absolute;
  margin-left: 20px;
  margin-bottom: 0;
  display: block;
  max-height: 100%;
}

#header {
  background: black;
  color: white;
  display: block;
  text-align: center;
}

#gallery {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  padding: 0 4px;
}

#gallery img {
  width: 25%;
  height: 300px;
  object-fit: cover;
  margin-top: 8px;
  padding: 0 4px;
  border-radius: 10px;
}

@media (max-width: 800px) {
  #gallery img {
    width: 50%;
  }
}

a {
  color: darkgrey;
}

a:hover {
  color: black;
  background: darkgrey;
}

Answer: Can you check if this is what you are looking for.
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Photo Gallery</title>
    <link rel="stylesheet" href="gallery-styles.css" />

        <img
          id="home-icon"
          src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAhFBMVEX///8AAACampqgoKBOTk7p6ekpKSn8/Pz29va4uLhcXFzh4eH5+fkxMTEPDw/z8/NEREQ3NzcgICDl5eW/v788PDzX19dra2vHx8dJSUnt7e2oqKg1NTWEhIR9fX2xsbGRkZEVFRWKiookJCTR0dGAgICUlJR0dHRoaGhiYmJWVlYLCwtDLsDCAAAH+klEQVR4nO2d6WKyOhCGcV9QUVH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Gjpf0Ix1VM0Vq90inFk84lF3QUS3HK9C0coRbxUCuSNPwVTSLUNpLt4rpdyItTSWU7uKo3mwTq3qEbsILVY/QTnihWe0Jx+G3zkwoFhMyoUxMSJaxhJusCLvh5y41JTyHn5zVlLC7JTWGCZkwuZiQLCZ8igmzJ1wyIVVM+BQTMmFyMSFZkeyppoSRDJgJxcqLcCxb7IYJ0YWY8CEmNJgwuvBqPQmXlSPsoF1Z1TKWsCtbADjFGLBZhHPZykxJx/Gn1SOUbBQjU2S2SUUIVdNgRdpUjtBCy5IqdT3QGmMS4TYI1uv14q6BQrd/3w4L3OgUQLwWopGEKYQWF2ZCJkxDOMljLU0mZEImZML/GeGVuLdbdQnh6tpMyIRMyIQ5EOaxPjETMiETMiET1o0wjw0lmLBYwjy2bjOLMI9NJcwizGPnGi3CuIZoE+ax84lgj6N4wo16G6sg4XhmKPmSA9rytPYoabRViEHCQfeoMi/UuL7ibqqddJZNqfDWbAm0ackvrKOW8mnH7PdUAzFh9cWE1RcTVl9MWH3Vn/A/ffrIdwEnvgkAAAAASUVORK5CYII="
      />

Luna's photos

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  font-family: Verdana, sans-serif;
  background: black;
}

/* for header size visibility - remove later */
#top-row {
  border: 1px solid white;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

#home-icon {
/*   position: absolute; */
  margin-left: 20px;
  margin-bottom: 0;
  display: block;
  height: 4rem;
}

#header {
  background: black;
  color: white;
  display: block;
  text-align: center;
  font-size: 2rem;
  margin-left: 20px;
}

#gallery {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  padding: 0 4px;
}

#gallery img {
  width: 25%;
  height: 300px;
  object-fit: cover;
  margin-top: 8px;
  padding: 0 4px;
  border-radius: 10px;
}

@media (max-width: 800px) {
  #gallery img {
    width: 50%;
  }
}

a {
  color: darkgrey;
}

a:hover {
  color: black;
  background: darkgrey;
}

Comment: Thank you! It worked for the most part, only the home icon is now next to the centered title and I was thinking about having it completely on the left side of the screen if possible. I can see you commented out the position: absolute and that was the only way I managed to have it on the left side. But I can see all three solutions give the result like yours, so maybe it's not possible?
Answer: You can solve your problem with these changes:

#top-row {
  border: 1px solid white;
  display: flex;
  align-items: center;
  justify-content: center;
}

#home-icon {
  margin-left: 20px;
  margin-bottom: 0;
  display: block;
  height: 40px;
}

#header {
  background: black;
  color: white;
  display: block;
  text-align: center;
  margin-left: 20px;
}
Comment: Thank you! It worked for the most part, only the home icon is now next to the centered title and I was thinking about having it completely on the left side of the screen if possible. But I can see all three solutions give the result like yours, so maybe it's not possible?
Answer: I think JithinAji answer is a good solution.
You also asked for

icon on the left at the same level as the heading + both having the same heigh

so if you prefer you can modify his code with
#top-row {
  border: 1px solid white;
  display: flex;
  align-items: center;
  justify-content:center;
}

#home-icon {
  margin-bottom: 0;
  display: block;
  height: 2rem;
}

#header {
  background: black;
  color: white;
  display: block;
  text-align: center;
  font-size: 2rem;
  margin-left: 20px;
}

Anyway if you have problem with really narrow smartphone display you can add a @media to reduce the #home-incon height and #header font-size like
for example:
@media (max-width: 320px) {
  #home-icon {
    height: 1.5rem;
  }

  #header {
    font-size: 1.5rem;
  }
}

Comment: I'm happy that it works. About the icon on the left i tried this, I'm not shure 100%, maybe you can adjust the position.
#home-icon {
    position:fixed;
    left: 22px;
    top: 24px;
    margin-bottom: 0;
    display: block;
    height: 2rem;
  }
Comment: Thank you! It worked for the most part, only the home icon is now next to the centered title and I was thinking about having it completely on the left side of the screen if possible. But I can see all three solutions give the result like yours, so maybe it's not possible? The @media is very useful, now I understand how it works!

Header image resizing HTML/CSS


Display two column table on smartphone

Question: I've been somewhat struggling on how to display a two column table on a smartphone (iOS app specifically).
My said that they would like something other than a boring UITableView to display the data. I told them that while it maybe boring it is the most user friendly option and most practical. That being said, I decided that I would sexy up a UITableView in hopes that they would realize it's the best option.
Here is the structure of the data:

My biggest issue is trying to include the title of the columns into the view. Here is what I was thinking:
Have the view work similar to the Twitter app, where you can swipe in between tables. The first view list by the "Commonly Prescribed Medicines", the second view list sorts by "What is Treated".
"Commonly Prescribed Medicines"

"What is Treated"

As you can see at the top, the two little •• to denote that the view is horizontally scrollable.
My only issue with this is that it seems like I'm overcomplicating it. I don't see any benefit in being able to switch between the different data views. It's such a small subset of data that you can easily digest it all on a single screen.
Please shoot holes in my idea.
Comment: It does seem overcomplicated, as you say. If the aim is to sort the list by either the drug name or the symptom, it is surely easier to allow sorting on the columns rather than having two separate tables and swiping between them?
Comment: I guess we should take a step back and ask who is using this and why? Are there two very separate user groups?
Comment: I would agree, the issue that I had with that was how to display both the column names. I saw swiping between tables as a way to show one column name at a time. Thoughts?
Comment: It is primarily physicians in the age range of 35-65. The use cases from the customer is that they would be using this for quick reference so the data needs to be clearly displayed. It also needs to be uncomplicated since it's an older user group.
Answer: Instead of sticking to a 2-column layout, I would suggest going for a list based layout as shown in the mock-up below:

In this layout, the Medicine name can be the title and the condition it treats can be shown as tags under the medicine name. Furthermore, if the user wishes to search all medicines for a particular condition, he can just click on the tag to filter all medicines that are used to treat that particular sickness as shown in the second mock-up.
In addition to this, it is always good practice to provide a search box on top of any list with numerous records.
Note: Mock-up link
Comment: I like the filter aspect! Very nice, thanks for your help.

Display two column table on smartphone


Get error trying to create a share link with action.createLink with onedrive for business but can retrieve existing link if created in the portal

Question: I'm getting an Internal Server Error 500 with error message "host web isn't a personal site" when trying to create a share link with the OneDrive for Business root url - https://{tenant}-my.sharepoint.com/_api/v2.0
I can upload / create files via the above API but I cannot create a shared link. If I create the link using the Office365 OneDrive portal I can then retrieve the link with action.createLink.
using the Office 365 Developer Pack subsciption but the file that I can upload and update but not create a link for is definitely in OneDrive and not the team site.
Anyone else getting the same problem and have answers? Not sure what extra detail I can provide here.
Any help is greatly appreciated. This has stumped me for a couple of days now.
Answer: Microsoft have confirmed that this is a bug in the OneDrive api with the 'createLink' function.
Refer this: https://github.com/OneDrive/onedrive-api-docs/issues/237#issuecomment-152639588
Apparently the fix is a few days away. Hope that helps somebody.
Cheers


Where is my neutral wire for smart switch

Question: I installed 3 smart switches on one side of our entry by connecting each to the white bundle of neutral wires at the back of the box. Pretty simple and they all work fine. There are 3 more switches I want to replace, but what should be the neutral wire bundle has 2 black wires. Do I have the necessary neutral wires for the smart switches?[![enter image description here][1]][1] the 3 way on the left connects with the 3 way I just replaced in the other box.
I added a drawing to make things clearer. The 2 black wires in the white bundle lead in and out of the box and are from the cables that include the red wires bottom left and top right.
[1]: https://i.stack.imgur.com/cHEG1.jpg![enter image description here](https://i.stack.imgur.com/gpfPk.jpg)
Comment: Wow -- that box is very messed up indeed from what I can see in there (two of the white wires in the suspect junction go into cables whose black wires connect to more than one switch *and* one of the black wires tied to those white wires goes into a /3 cable whose white *and* red wires are connected to one of the switches fed by the black wires corresponding to white wires in that junction)
Comment: Neutral is the white wire not connected to any switch. And neutral is can be only one wire, make pigtails to connect few devices.
Comment: Thanks. I added a drawing to make things clearer. The only white wires not connected to a switch are in the bundle with the 2 black wires.
Answer: It's hard to believe there are no neutral wires in that box. It's possible they used black wires for neutrals but I doubt it. Most likely those are switch loops where they used white wires as hots. The best way to find out is to get a multimeter and measure that black/white bundle against ground. If you get 120v you know it's hot.
There are many smart dimmers that don't require a neutral wire. Although they are requiring it now for many devices. And the NEC now requires a neutral wire in switch boxes for this very reason.
Comment: I added a drawing to show where all of the wires go. I want to use Kasa switches so they can be grouped in the app.
Comment: Do you own a multimeter or have access to one? You can get a very inexpensive one for about $15. It's a required tool if you want to do your own electrical installation and/or maintenance.
Comment: I could not find my multimeter. I bought a new one, if I am using it right there does not seem to be any power to the neutral bundle with 2 black wires. I set the meter to 250v squiggle line and connected the black probe in the copper ground bundle of wires and the red probe to the black/white bundle. Nothing registers. There does not seem to be any power to those black wires in the white bundle.


Convert a char to upper case

Question: I have a variable which contains a single char. I want to convert this char to upper case. However, the to_uppercase function returns a rustc_unicode::char::ToUppercase struct instead of a char.
Answer: Explanation
ToUppercase is an Iterator, that may yield more than one char. This is necessary, because some Unicode characters consist of multiple "Unicode Scalar Values" (which a Rust char represents).
A nice example are the so called ligatures. Try this for example (on playground):
let fi_upper: Vec<_> = 'fi'.to_uppercase().collect();
println!("{:?}", fi_upper);   // prints: ['F', 'I']

The 'fi' ligature is a single character whose uppercase version consists of two letters/characters.

Solution
There are multiple possibilities how to deal with that:

Work on &str: if your data is actually in string form, use str::to_uppercase which returns a String which is easier to work with.
Use ASCII methods: if you are sure that your data is ASCII only and/or you don't care about unicode symbols you can use std::ascii::AsciiExt::to_ascii_uppercase which returns just a char. But it only changes the letters 'a' to 'z' and ignores all other characters!
Deal with it manually: Collect into a String or Vec like in the example above.
Answer: ToUppercase is an iterator, because the uppercase version of the character may be composed of several codepoints, as delnan pointed in the comments. You can convert that to a Vector of characters:
c.to_uppercase().collect::<Vec<_>>();

Then, you should collect those characters into a string, as ker pointed.
Comment: And then you only have to take the first char of the vector : https://play.rust-lang.org/?gist=cd2f82bd96c6ffa26ef1&version=stable  Isn't this very bloated for such a trivial thing to do ?
Comment: No, my answer is wrong. Please read the comments. That will work in some cases, but is incorrect on the general case.
Comment: @LukasKalbertodt I can't answer the question myself. I haven't deleted the answer yet because comments contain valid information. Should I delete it?
Comment: @LukasKalbertodt:  Just did. Thanks.

Convert a char to upper case


NotFoundHttpException in RouteCollection.php - Laravel

Question: I am looking some help with configurating Laravel. Managed to create new project but accessing http://localhost/website/public/index.html gives me following error (ps. http://localhost/website/public/index.php works fine):
1/1
NotFoundHttpException in RouteCollection.php line 142:
in RouteCollection.php line 142
at RouteCollection->match(object(Request)) in Router.php line 744
at Router->findRoute(object(Request)) in Router.php line 653
at Router->dispatchToRoute(object(Request)) in Router.php line 629
at Router->dispatch(object(Request)) in Kernel.php line 229
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfToken.php line 50
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 54
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 61
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 118
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 86
at Kernel->handle(object(Request)) in index.php line 54

Comment: What would you expect? You're not serving a static `index.html` page are you?
Comment: I am new to this and I don't quite know how to route this request. How can I setup my own 404 error page?
Comment: Okey, I figured it out. In resources -> views -> errors I could create my own 404 error page. In app -> exceptions -> handler.php I had to return this page.
Answer: Laravel does not by default server .html files.
You should setup apache or nginx to send traffic to index.php if no local file exists.
You then need to define routes in your routes file. You could choose to create a route called index.html but usually you would just have a / route.


How can I use aws to secure a domain with https for a non aws origin?

Question: I did a search in the aws docs and couldn't find anything that could help me to setup a cloudfront distribution for a non aws origin server to secure my domain with https. I'm using route 53 to manage my dns for the domain, I'd like to setup https for the domain but it is not hosted with aws. How can I use aws to create a secure domain with https?
Update: I've created the cloudfront distribution and set the alternative cnames to the domain (example.com and www.example.com). In Route 53 I updated the A record for the domain - example.com - to be an alias and pointed it to the cloudfront distribution, but when I try to access the site I get page not working error. The domain does now have he secure padlock, but I can't access the site. Here is the error that I get when I access the site:
Comment: Just use Certificate Manager on AWS to set it up.  You'll just verify ownership via adding a CNAME record.
Comment: @bkunzi01 I've already done that. I have generated the certificate with a wild card so that it covers subdomains. I created a cloudfront distribution and used the origin, which is not hosted with aws. but when I access the site I get a message that It cannot connect securely.
Comment: @Abdi you need to edit your question to include all those details about what you have setup and what isn't working. Are you sure you have your domain pointing to Cloudfront?
Answer: The simplest way is to use a CloudFront distribution in front of your non AWS endpoint. This endpoint would be configured as a custom origin endpoint.
You would need to generate or upload a certificate to ACM to attach to the resource. This must be done before you can use the distribution on your own domain, if you don't have it when you create the distribution you will need to edit it later.
The AWS documentation includes documentation for Creating a Distribution. If you follow this and reference your endpoint as the custom origin you will be able to create the host.
You will need to ensure you configure the Origins Origin Protocol Policy option to be HTTP Only if your host does not have a HTTPS certificate.
Be aware that as the CloudFront distribution communicates with your endpoint over the internet, any traffic between CloudFront and your endpoint will still not be encrypted.
Comment: If your domain is in Route 53, update the record to be an Alias record and reference your CloudFront distribution CNAME. This will then have your domain resolve to CloudFront, as long as you added your domain as an alternative name to CloudFront it should work
Comment: Right. I've created the distribution, do I need to do anything in Route 53? How can I use https for the domain after creating the cloudfront distribution?
Comment: So, I've created the cloudfront distribution and set the alternative cnames to the domain (example.com and www.example.com). In Route 53 I update the A record for the domain - example.com - to be a alias and pointed it to the cloudfront distribution, but when I try to access the site I get page not working error. The domain does now have he secure padlock, but I can't access the site. I'm not sure what I'm doing wrong?
Comment: What kind of error exactly are you getting, is there any HTML returned?
Comment: I've updated the OP, I put a screenshot of the error in the main question.
Comment: Do you get anymore details from the browser? You sometimes see this when caught in a redirect loop.

If you run ` curl -iv $YOUR_DOMAIN` does it return any signs of a redirect?
Comment: Yes, it's in a redirect loop: "This page isn't working ----.com redirected you too many times.Try clearing your cookies. ERR_TOO_MANY_REDIRECTS"
Comment: Presume this is also the same in incognito? Have you enabled anything on CloudFront for redirecting? Does the app do any redirecting? Can you see anything in the app logs?
Comment: Yes, it's the same in incognito mode. I haven't enabled anything in cloudfront for redirecting. I used the defaults for most settings.
Comment: If you run `curl -iv $YOURDOMAIN` does it try to redirect to itself? Are you able to see the redirect loops in your web server access logs?


New Main Panel & Sub-Panel - Hooking up Ground / Netural - Connecting to Plumbing / Ground Bar

Question: Older 1960's house.
The outside panel is a FPE Stab-Lok that needs upgraded.
Will be using this panel to upgrade it, which has a 125-amp main breaker:
The current box is directly to the left of the outside meter.  The box currently has a 70-amp circuit that leads to a sub-panel (about 20 feet away), a 50-amp breaker for the oven, and two 20-amp 120v breakers.  Grounding bar is outside but it is not bonded to copper plumbing.
Questions:

Any issues there or will that panel and hook-up be OK?
The 70-amp breaker will be changed out for a 100-amp breaker (since the subpanel will be upgraded to 100 amp).  Is #4 copper good to run between these?

Next, the inside panel also needs upgraded.  It is only 70-amp and the house will get electric heat/HVAC system (has only had window units but has had forced gas air so the vents and closet are in place).  So it will be upgraded to 100-amp.
Questions:

I'm sure that box is OK for the purpose?
There is copper plumbing very close to this box.  Is it safe to also provide bonding of the separate ground bar to the copper plumbing with the outside main panel ground bar connected to the ground rod in the ground?
I'm seeing all kinds of conflicting info on this.  I understand that the neutral and ground on the sub-panel should not be bonded / connected together correct?  Some people say yes and others say no.  Seen others actually connect a wire between the two, but that makes no sense to me.
Comment: You might want to break this up in to multiple posts.  The site works best when each question only asks a single specific question.
Comment: Question #2 (the first one) is a dupe. http://diy.stackexchange.com/questions/29057/what-wire-gauge-do-i-need-for-a-100-amp-subpanel-at-the-end-of-a-60-wire-run
Comment: After further investigating, it appears #2 copper is going to be what I use.  It appears to be a bit more than needed, but I'd rather future-proof it.  And finding #3 copper is more difficult it seems.  I'm sure the panels are fine as well.  That just leaves the second set of questions 2 and 3.
Comment: Yeah you only need #4 for a 100 amp service to a dwelling unit. That is why #3 is hard to find. And do NOT bond the ground and neutral at a sub-panel that is a code violation.
Comment: ArchonOSX - table 310-16 shows 4-4-4-6 is only good for up to 85 amps at 75.  Would rather ensure to over-build than be under.
Answer: I'm fine with the idea of a main panel with only 2 things in it feeding a sub-panel with everything in it.
Question #1 - I'd rethink putting a service panel outdoors at all. Weather is rough on panels, even if they claim to be outdoor rated.  I'm a little nervous about a 100A breaker supplied from the normal bus bars, but if the manufacturer stands behind it, okay.  The 100A wires are going to be a mother to wrestle onto that 100A breaker.  Are you quite sure the power company has provisioned you 125A service?  100A is more common.
Question #1 (the second):  You're gonna want more slots than 24, since this box powers pretty much your whole house.  Nobody ever installed an addition and went "Gosh, that job was sure made harder and more expensive by having too many slots in the panel".  It's a false economy, especially since bigger boxes are often bundled with more breakers.  Your house may be ok now, but do a kitchen remodel and lookout!
Question #2 (the second):  Don't bond your grounds to random plumbing that happens to be going by.  It's not code, and someday you might have a plumbing problem and the plumber replaces a downstream chunk of it with PVC.  Whoops. Also, they've been upgrading customers to PLASTIC water meters. Double whoops.  Bond properly and to code.
Question #3 (the third): Bond ground and neutral only in the (singular) main panel. As such, you need 4 wires between main and subpanel.
Just for your edification, it's only a sub-panel if it's fed from a main panel. If it's fed directly from a transformer, it's a main panel.
Comment: Good reply.  The house already has an outside box with conduit and connections outside.  So that is why it will be replaced.  With regard to the 24-slot box, it will leave me with 8 extra slots upon based on what is in the current panel plus the new breakers for AC.  Lastly, the cold water grounding is required in Florida.  So the plan is to run a copper ground from the subpanel to the copper plumbing where it enters the house, which is in the utility room.  Any objections to this?
Comment: Actually, if you have a metal water piping system entering the house it is required to be bonded to the grounding system within 5' of its entrance to the dwelling.  Use a proper ground clamp and the proper sized bonding conductor.myounshould still have a grounding electrode and a grounding electrode conductor besides the water pipe.
Comment: In some areas, an outdoor disconnect is required (seismic, flood, etc. areas). In those places it's common to have panels outside.


CONTEXT INIT ERROR when making sparkSQL context with sparkjobserver

Question: when I run curl -d "" 'localhost:8090/contexts/test-context?num-cpu-cores=4&memory-per-node=512m' it makes sparkContext with no problem but when I want to make a sparkSQL context I get an error I used this line to make it curl -d "" '127.0.0.1:8090/contexts/sql-context?context-factory=spark.jobserver.context.SQLContextFactory'  here is the response it gives
{
  "status": "CONTEXT INIT ERROR",
  "result": {
    "message": "",
    "errorClass": "java.lang.ClassNotFoundException",
    "stack": ["java.net.URLClassLoader$1.run(URLClassLoader.java:366)", "java.net.URLClassLoader$1.run(URLClassLoader.java:355)", "java.security.AccessController.doPrivileged(Native Method)", "java.net.URLClassLoader.findClass(URLClassLoader.java:354)", "java.lang.ClassLoader.loadClass(ClassLoader.java:425)", "java.lang.ClassLoader.loadClass(ClassLoader.java:358)", "spark.jobserver.JobManagerActor.createContextFromConfig(JobManagerActor.scala:265)", "spark.jobserver.JobManagerActor$$anonfun$wrappedReceive$1.applyOrElse(JobManagerActor.scala:106)", "scala.runtime.AbstractPartialFunction$mcVL$sp.apply$mcVL$sp(AbstractPartialFunction.scala:33)", "scala.runtime.AbstractPartialFunction$mcVL$sp.apply(AbstractPartialFunction.scala:33)", "scala.runtime.AbstractPartialFunction$mcVL$sp.apply(AbstractPartialFunction.scala:25)", "ooyala.common.akka.ActorStack$$anonfun$receive$1.applyOrElse(ActorStack.scala:33)", "scala.runtime.AbstractPartialFunction$mcVL$sp.apply$mcVL$sp(AbstractPartialFunction.scala:33)", "scala.runtime.AbstractPartialFunction$mcVL$sp.apply(AbstractPartialFunction.scala:33)", "scala.runtime.AbstractPartialFunction$mcVL$sp.apply(AbstractPartialFunction.scala:25)", "ooyala.common.akka.Slf4jLogging$$anonfun$receive$1$$anonfun$applyOrElse$1.apply$mcV$sp(Slf4jLogging.scala:26)", "ooyala.common.akka.Slf4jLogging$class.ooyala$common$akka$Slf4jLogging$$withAkkaSourceLogging(Slf4jLogging.scala:35)", "ooyala.common.akka.Slf4jLogging$$anonfun$receive$1.applyOrElse(Slf4jLogging.scala:25)", "scala.runtime.AbstractPartialFunction$mcVL$sp.apply$mcVL$sp(AbstractPartialFunction.scala:33)", "scala.runtime.AbstractPartialFunction$mcVL$sp.apply(AbstractPartialFunction.scala:33)", "scala.runtime.AbstractPartialFunction$mcVL$sp.apply(AbstractPartialFunction.scala:25)", "ooyala.common.akka.ActorMetrics$$anonfun$receive$1.applyOrElse(ActorMetrics.scala:24)", "akka.actor.Actor$class.aroundReceive(Actor.scala:465)", "ooyala.common.akka.InstrumentedActor.aroundReceive(InstrumentedActor.scala:8)", "akka.actor.ActorCell.receiveMessage(ActorCell.scala:516)", "akka.actor.ActorCell.invoke(ActorCell.scala:487)", "akka.dispatch.Mailbox.processMailbox(Mailbox.scala:238)", "akka.dispatch.Mailbox.run(Mailbox.scala:220)", "akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:393)", "scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)", "scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)", "scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)", "scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)"]
  }

the same thing happens if I use HiveContextFactory too , this error comes even if my curl is like this curl -d "" '127.0.0.1:8090/contexts/sql-context?context-factory'
Comment: لا مصب اون واتس اپ رو و داشتی بالاخره
Answer: You should build your spark-jobserver with spark-jobserver-extras. You can do this with SBT:
$ sbt
> project job-server-extras
> assembly

So you should take jar from target directory of job-server-extras project and you will can use spark.jobserver.context.SQLContextFactory and HiveContextFactory.


jQuery - back and next between multi select questionnaire

Question: I have to build a multi select questionnaire which the user can  go back to previous question and change the answer.
I want to ensure the following (for example):
The user in question number 2 and he clicks on the button "back"- how can I display the selected answer from question 1 as checked?
This is the code for creating the checkbox:
 $.each(multiQ[questionIndex].answers, function(key, val) {
            $('#answers').append('<input type="checkbox" class="radio" name="fooby[1][]" value="'+val+'"  onchange="test(this)" >' + val + '');

Comment: Are you questions on the same page? Is it a single page application where you are using tabbed divs for question pages? There's not enough information to answer your question.
Comment: All the questions are in the same page and I change them dynamically. The data is taken from JSON file.
Answer: Well, what I will recommend you to use is HTML5 Web Storage. You can use this to save the answer for each question, then you can get the previous/next question's answer by giving a key/value on the button..
Here is an example how to use LocalStorage:
// Check browser support
if (typeof(Storage) != "undefined") {
    // Store
    localStorage.setItem("lastname", "Smith");
    // Retrieve
    document.getElementById("result").innerHTML = localStorage.getItem("lastname");
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}

Answer: Create an object called questions, and store questions and questions answers in it.
It's structure will look like this:
{
    0: {
            text: "Who is the president of USA",
            options: ['Obama','Obama','Obama','Obama'],
            correctOption: 3,
            userAnswer: 2
    },
    1: {
            text: "Who is the president of USA",
            options: ['Obama','Obama','Obama','Obama'],
            correctOption: 3,
            userAnswer: 2
    },

}

And store current question number in another variable (for example, called 'step' ). When a user clicks next button increase the step variable and render question which you take from questions object (do the same when user clicks back button).When a user select an answer write it to questions object in order to store it. In this way, you can display the question and users answer easily.
Edit:
I have made an example for you:
http://jsfiddle.net/oxzp88ub/3/
It's very simple example to show the basics of displaying question.
Comment: How am I supposed to update the userAnswer and display the answer as checked?
Comment: I have updated the example, it is much better now :) http://jsfiddle.net/oxzp88ub/3/


Determine intent filters associated with a service

Question: We removed an SDK from our Android app (all class and method references) and pushed it to the play store, but forgot to remove the declaration for it from the manifest:
    <service android:name="com.radiumone.emitter.location.LocationService"/>

Today we have one crash through Crittercism that didn't happen in regression testing in which an attempt is made to load this service.  My research suggests the only way this could happen is if the service is exported by default, and that can only happen if the service contains intent-filters.  Is this true, and if so, how do I find the intent-filters associated with a service?  I can't find any contained in my AndroidManifest.xml; where else should I look?
Answer:
Is this true

In an unmodified application, yes.

how do I find the intent-filters associated with a service?

They would be child elements of the <service> element in your manifest. If your element is as it is shown in the question, you have no <intent-filter> elements, and your service is not exported.

I can't find any contained in my AndroidManifest.xml; where else should I look?

There is no place else to look.

Today we have one crash through Crittercism that didn't happen in regression testing in which an attempt is made to load this service.

You may wish to ask a separate Stack Overflow question where you provide more details about the crash, to try to get our help in confirming your belief that somebody else is attempting to start or bind to your service. Perhaps you are misinterpreting the results.


Example of a disconnected manifold where the tangent space is not the dimension of the manifold?

Question: Wikipedia says that the tangent spaces of a connected manifold all have the same dimension, equal to that of the manifold.
Well, is there an example of a simple disconnected manifold that doesn't have this property?
All I can think of is taking $[0,1]$ and $[2,3]$ as a subspace of $\mathbb{R}$. Well, first of all, does the tangent space even exist at $0,1,2,3$? I can see that the set of "virtual velocities" are only in one direction at these points. Hence, this does not constitute a linear space. Is it a tangent space then?
If it is a tangent space, its dimension would still be 1, as the closed half-line of $\mathbb{R}$, so I am failing to find a good counterexample.
Comment: Some people require manifolds to be of pure dimension even if disconnected. Others allow the different components to have different dimension. In the latter case, the dimension of the tangent space depends on the point.
Comment: Take the disjoint union of a line and plane.
Comment: You're talking about manifolds *with boundary* with $[0,1]$, etc., and there is still a $1$-dimensional tangent space at the boundary points. But that's a different kettle of fish.
Comment: See the appropriate section from Lee's *Intro. to Smooth Manifolds*: https://books.google.at/books?id=w4bhBwAAQBAJ&pg=PA73&lpg=PA73&dq=tangent+space+manifold+with+boundary&source=bl&ots=FnnGjQSMMz&sig=EixS_2XXGnqGgsX6lFwRpK4ZmJ0&hl=en&sa=X&ved=0ahUKEwjx-qfb_afMAhXFjSwKHcHIAEcQ6AEIKTAC#v=onepage&q=tangent%20space%20manifold%20with%20boundary&f=false
Answer: Just to close the question: You can take a disjoint union of two manifolds of different dimensions. Some people see this space as a manifold.


How to Create charts like this in android?

Question: some app has very nice charts an UI,  i want to know how they create such a UIand chart like this one.
i know there is some Psd file for that but how to use them?
Answer: There are many libraries in android to create charts some of which are:

achartengine
androidplot

Also for greater details on the matter you can look at a question on StackOverflow
Comment: the ones I've mentioned are free. also on the answer I referenced you can find free and paid solutions
Comment: thanks, and that one on the picture, with them can i draw like that? i want a pie chart with percentag in center or a photo in center
Answer: AChartEngine is probably to most commonly used Android chart library. I have used it on several occasions
with good results.

I have also heard some good things about AndroidPlot, but never tried it myself


Renewing/Refreshing Express Session

Question: In my app I restrict some access to some actions and pages if a user is not logged in. I have:
var restrict = function(req, res, next) {
    if (!req.user) {
      console.log("USER isn't logged in.")
      return res.status(403).send('Access or action denied, please log in');
    }
    next();
}

app.get('/stocks', restrict, MainHandler.findAllStocksFromUser);
app.get('/stocks/:id', MainHandler.findStockByIdAndDates);
app.put('/stocks/:id/stockActions', restrict, MainHandler.handleStockAction);

I'm essentially trying to refresh a session everytime the client makes a request to the server so that the server doesn't logout the user/destroy the session when it shouldn't. For testing, I want the session to expire/the user to be logged out if 20 seconds go by without the user making an requests to the server. I have:
    app.use(session({secret: 'secret', saveUninitialized: true, resave: true, expires: new Date(Date.now() + (20000))}));

Then I try to use middleware to refresh the expiration date every time the use makes a request:
// Session-persisted message middleware
app.use(function(req, res, next){
  req.session.cookie.expires = new Date(Date.now() + 20000);
  next();
});

But if I log in from the client, and click around, causing requests to the server, I still get the log-in error on the client after 20 seconds, despite trying to "refresh" the session in the middleware. I have also tried using maxAge using the same strategy with the middleware. Any ideas? Thanks!
Comment: You could try to use https://github.com/expressjs/session#sessionregenerate
Answer: You can try define your session as follows
app.use (
   session ({
      secret: "secret",
      saveUninitialized: true,
      resave: true,
      cookie: {
         expires: 20 * 1000
      }
   })
);

and then refresh the session using
req.session.touch()

or you could define your session as
app.use (
   session ({
      secret: "secret",
      saveUninitialized: false,
      resave: true,
      rolling: true,
      cookie: {
         expires: 20 * 1000
      }
   })
);

and it will renew the session automatically and it will only expire when it has been idle for the value in the expires variable
Answer: express-session supports a duration-based maxAge setting, which will work better than setting a fixed date for all sessions. So your middleware usage should instead look like:
app.use(session({
  secret: 'secret',
  saveUninitialized: true,
  resave: true,
  maxAge: 20000
}));

Next, to update the expiration of the session, you can just call req.session.touch(); if that is all you're doing to the session and its contents.
The documentation has a lot of other good information on controlling session expiration and related topics.
Comment: I think you have to use req.session.cookie.maxAge
Comment: This isn't working for me. If i print req.session.maxAge to the console on each request I get 'undefined'. So I tried doing app.use(session({secret: 'secret', saveUninitialized: true, resave: true, cookie: {maxAge: 20000}})); instead and req.session.touch() isn't seeming to work because the session still stops after 20 seconds regardless of how many requests I make
Comment: @gcc Did you get any solutions to this??

Renewing/Refreshing Express Session


Change Item Limit on Specific Category Page OpenCart

Question: I have a custom Category tpl page in OpenCart. Just recently I was about to wrap the products loop with this code:
<code><?php
$ids=array(444,443,145,97,459,460,454,451,450,449,445,446,447,448,457,456,387,385); // array of product id's
?>

<?php
foreach ($products as $product){
  if(in_array($product['product_id'],$ids)) {
     //Display item
  }
}
?>
</code>
This code lets me choose specific products that I want to be displayed on this page. It works great! My problem now is that I have more than 16 products to display, and in my opencart setting my item limit is set to 16. I cannot change the settings because it would change all the other pages on my store.
Is there a way I can do this on the template page? Or, if I have to, the category controller? I would love to be able to add code to the loop. But Im up for any solution. Thanks!
Comment: Is this the limit used for pagination or some other one?
Comment: And what is wrong with the pagination? Just copy the pagination from default template back to this custom one. Once You paginate the same functionality will be preserved... But sir, please, check my answer to Your other question - this solution is really awful and all You need is to just unlink the products from that category that You do not want to be displayed...
Comment: have you created a separate category.tpl file or you just edited the original to add your code ? if you created a tpl file how do you instruct controller file to use that tpl file instead of default file, by how i mean what condition ? are all these products in same category ?
Comment: I have created a new category tpl. Basically what I'm trying to do is change the item limit number on specific pages. Right now all the pages have the same product limit that you set in the store settings.
Comment: @JCBiggar you are still avoiding the most important questions. i know what you want to do. but i want on what condition you are loading your new tpl file and how ? are all these products in same category ? don't be choosy on providing the info
Answer: I just edited the Controller file:
<code>        if ($category_info['category_id'] == '132'){
            $limit=1000;
        }
</code>
Now if my category has the id of 132, it will display all the products on that particular page.
Comment: exactly this is the reason why i was asking those question
Comment: sorry, I'm new to opencart so alot of things are hard to explain. Thanks though!


My SQL insert statement, string variable has apostrophe

Question: I'm trying to insert data into a MySQL database with an INSERT statement in java. However one of the variables I am using contains an apostrophe and I'm not sure how to account for it in the statement.
public static void addAlbum(Album album) throws Exception {

        try{
            Connection conn = getDBConnection();
            PreparedStatement posted = conn.prepareStatement(
                    "INSERT INTO album(title, year, singer, company) VALUES ('" + album.getName() +"', '"+ album.getYear() +"', '"+ album.getSinger() +"', '"+ album.getCompany() +"')"
            );
            posted.executeUpdate();
        }
        catch(Exception e) {
            System.out.println(e);
        }
        finally{System.out.println("Insert completed");}
    }

It's the album.getName() that retrieving a String that is "I'm Back", what could I do so that this value could properly be inserted rather than the apostrophe cutting the String and invalidating the statement?
Answer: Assumming, all the values are of String type, you should do it as follows:
String sql = "INSERT INTO album(title, year, singer, company) VALUES (?, ?, ?, ?)";
PreparedStatement posted = conn.prepareStatement(sql);
posted.setString(1, album.getName());
posted.setString(2, album.getYear());
posted.setString(3, album.getSinger());
posted.setString(4, album.getCompany());

This will also protect your database from SQL injection.
Note: If year is an integer, you shoukd do posted.setInt(2, album.getYear());


I want my search bar to look for nested value but I have troubles with my WHERE LIKE

Question: I have two tables, Phones and Records, they are related to each other by the phone.ID.
I have a search bar for each index. On each, I've implemented a search bar where user can searching for their phone by their IMEI.
Recently, I've added a ref_number column in the Phones table.
So into the views/phones/index, it does works well.
However, in the views/records/index, it doesn't work because of the phone relation. What I meant by that is that I could access it in my phone.rb like this :
def self.search(term)
  if term
    where('imei LIKE :term OR ref_number LIKE :term', term: "%#{term}%")
  else
    order('id DESC')
  end
end

But I can not in my record.rb using this :
def self.search(term)
  if term
    where('imei LIKE :term OR phone.ref_number LIKE :term', term: "%#{term}%")
  else
    order('id DESC')
  end
end

Here's my records_controller, my phones_controller looks clearly the same :
def index
  if user_signed_in?
    @records = Record.search(params[:term]).paginate(:page => params[:page], :per_page => 20)
  else
    redirect_to root_path
  end
end

Does any of you knows how I could access the value phone.ref_number in something like this ?
Thanks,
Raphaël.
Comment: How are those 2 related?
Comment: Yup, they are related.
Comment: @Nermin 1) You said "this date", what do you mean by this? 2) You said "it doesn't work because of the phone relation", what do you mean by this? 3) It would help us if you could show code of your `Phone` and `Record` models, and also `PhonesController#index` and `RecordsController#index` 4) Also, it would also help if you could update your post to add something like "I expect something something..., but currently it's not working because something something", and be specific about them. This would also help us. ty.
Comment: Thanks for you comment. I've updated my question, do not hesitate if you need something more.
Answer: If you're using normal Rails conventions then the table for the Phone model will be phones.ref_number, even if the association within Rails is just phone, because you're writing raw SQL at this point.
You may need to also use joins(:phone).where(.. ), as I'm not sure that ActiveRecord will do it for you when you're writing raw SQL like that.


Running jar files from terminal using absolute path

Question: So I have a jar file timeline.jar which when executed (using java -jar timeline.jar from its directory) saves a few JSON files in its directory.
However I need to execute timeline.jar from Crontab using:
5 * * * * java -jar /path/to/timeline.jar
and since I'm using the absolute path, the files are not saved in the jar file's directory.
Right now the only solution is to specify the exact path where to save the JSON files through the java code, but I would rather not hard code it like that.
Surely there must be a way to specify the "current directory" from the Crontab command?
Apologies if the question has been asked before, none of the answers I read seemed to answer mine.  Thanks
Comment: isn't the same as http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file
Comment: Isn't there a way to specify the "path" or "working directory" through the terminal command itself without amending the jar file?
Comment: Not a Java or terminal problem at all
Answer:
Surely there must be a way to specify the "current directory" from the Crontab command?

The way to specify the working directory for a cron job is to use the cd command within the job to change to the correct working directory:
5 * * * * cd /path/to && java -jar timeline.jar

Cron jobs are run using the shell, so you can use shell syntax within the job. The job here is a sequence of two commands, the cd command and the java command. The '&&' means that the second command (java) runs only if the first command (cd) succeeds.
In the general case, depending on the command being run you may need to set environment variables, change the working directory, or redirect standard output and standard error within the cron job. You can do all these things in shell one-liners. But personally, I try to avoid having complicated shell commands in the crontab file. If I need to do something complex in a crontab, I'll write a shell script and have cron run the script:
#!/bin/bash
cd /path/to && java -jar timeline.jar

...
5 * * * * /home/jdoe/bin/launch-timeline-jar.sh

This is admittedly a little overkill for the case at hand. But suppose you needed to set the command PATH, and you want to capture the program's error messages in a log file, and you want to add a timestamp to the log file so you can know which run produced which errors. It's much easier to express all of these things within a shell script than directly within the crontab file:
#!/bin/bash

PATH=/some/path/bin:${PATH}      # Set our PATH
cd /path/to || exit 1            # Set the working directory
exec >> timeline.log 2>&1        # Direct output to a logfile
date                             # Write a timestamp to the log
exec java -jar timeline.jar      # Launch the command we came here for

Comment: Hmm I didn't know you can enter multiple commands like that.  Thanks! this works well for my purpose


Outlets for gas range

Question: I am building a bay for a new 30" gas range.
Q1: I was wondering if there are specifications, or code requirements, for the position of the gas and electrical outlets, most specifically, is there a height at which they should be installed because I know that stoves normally have an opening at the bottom to which the height of outlets should roughly correspond but I am not sure if it is standard or varies by model.
Q2: I am planning to install this gas outlet.

Does the vertical direction matter? In the case of my pipe, it would be easier to install it upside down (if this picture is right side up) because the pipe is coming from above down? Or do I need to install it the way it is in the picture?
Comment: Where the actual connection is, is what matters since the valve itself is in the wall. I would consider setting the valve such that when the gas line is connected it is angled out of the wall to help ease the bend it will need to take to coil up the excess behind the unit.
Comment: Please ask about these two things in separate questions. Outlet height and gas piping rules are not closely related.
Comment: The electrical code says you have to follow the installations instructions submitted to the NRTL (UL) for listing. Take a look at the installation instructions for the actual appliance you will be using, here is a sample, look at fig 4a. http://pdf.lowes.com/installationguides/012505502415_install.pdf
Answer: Typically the gas comes through the floor, so what you are planning may make a difference.
There may be some general tendencies for gas line location, most I see are close to the floor, usually within 6" or less. Whether it is on the left, right or center is usually defined by the maker of the appliance.
To insure the hook ups are in the right place, do your reasearch, check the reviews for the range you wish to use and download the install guide for that particular unit, and set up everything (gas and electric) for that unit. You can't go wrong.

Outlets for gas range


set Timer is not working in void loop() arduino

Question:
I have the following piece of code which I was able to test and verify that it works properly.
In essence, the call myThread.setInterval(5000); makes the led start blinking after 5 seconds.
#include <Thread.h>

Thread myThread = Thread();
char powerValue;
int ledPin1 = 2;
boolean flag = false;

void myThreadCallback() {
    digitalWrite(ledPin1, HIGH);
}

void setup() {
    pinMode(ledPin1, OUTPUT);
    digitalWrite(ledPin1, LOW);
    Serial.begin(9600);

    myThread.onRun(myThreadCallback);
    flag =  true;
    myThread.setInterval(5000);
}

void loop() {
    if (Serial.available()) {
        powerValue = Serial.read();
        Serial.println(powerValue);
    }

    if (powerValue == 'A' ) {

    } else if (powerValue == 'a' ) {
        digitalWrite(ledPin1, LOW);
    }

    if (myThread.shouldRun() && flag == true)
        myThread.run();

    powerValue = 'Z';
}

I wrote a slight variation of this code which pushes that call into the loop() code, which is shown below.
However, for some reasons that are unknown to me, with this code the led lights up right from the start instead of waiting 5 seconds.
#include <Thread.h>

Thread myThread = Thread();
char powerValue;
int ledPin1 = 2;
boolean flag = false;

void myThreadCallback() {
    digitalWrite(ledPin1, HIGH);
}

void setup() {
    pinMode(ledPin1, OUTPUT);
    digitalWrite(ledPin1, LOW);
    Serial.begin(9600);

    myThread.onRun(myThreadCallback);
}

void loop() {
    if (Serial.available()) {
        powerValue = Serial.read();
        Serial.println(powerValue);
    }

    if (powerValue == 'A' ) {
        flag =  true;
        myThread.setInterval(5000);
        // checks if thread should run
    } else if (powerValue == 'a' ) {
        digitalWrite(ledPin1, LOW);
    }

    if (myThread.shouldRun() && flag == true)
        myThread.run();

    powerValue = 'Z';
}

Question. Could anyone help me understand why the behaviour is different among the two sources?
Answer: In your modified code, in the loop, the if condition is not satisfied initially, so the setInterval is not called and it runs immediately.


Android Listview with sqlite and CursorAdapter

Question: After about 12 hours of work, I managed to write a working cursoradapter class with  the super fast code of the famous Google video , this class fill the listview from the database, with a text and a picture per row.
But I have the feeling that I ruined google efforts for performance with the code that I added at the end of the class, to fill the text and the picture, and I can't tell the performance when ill use the real/final database... (c is also the cursor made in the activity class)
Here are the 2 subclasses:
    public class CursorLi extends CursorAdapter {
    LayoutInflater minflater;
    int imd;

        public CursorLi(Context context, Cursor c, boolean autoRequery) {
            super(context, c, autoRequery);
            minflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent){
            ViewHolder holder;
            if (convertView == null){
                convertView = minflater.inflate(R.layout.lvitem, parent, false);
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.litext);
                holder.icon = (ImageView) convertView.findViewById(R.id.fiig);
                convertView.setTag(holder);
            } else{
                holder = (ViewHolder) convertView.getTag();
            }
            c.moveToPosition(position);
            imd = getResources().getIdentifier(c.getString(6), "drawable", "com.example.myapp");
            dr = getResources().getDrawable(imd);
            holder.text.setText(c.getString(4));
            holder.icon.setImageDrawable(dr);
            return convertView;
        }
        @Override
        public void bindView(View view, Context context, Cursor cursor) {}
        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) { return null;    }
    }

public static class ViewHolder {
    TextView text;
    ImageView icon;
    }

Can you guys help me optimize the code please ?
In particular:

Why I had to add "c.moveToPosition(position);" ? I thought that
cursoradapter manages the position...
Is there a faster way to apply the picture to the row's imageview ? I used 3 lines of code
(the db contain the pic file name).
getString is the best way ?
Was it better a separate class or a subclass ? When the class was a
separate class I didn't know how to get the cursor data for the
getView() funciton, so now its a sub class of the activity and the
cursor is globally declared.

If you want to ask me why I didn't use simplecursoradapter, because I wanted to use the google code, for performance, since the list may have 300 rows...
Thanks
Answer:
For CursorAdapters, you can override only newView and bindView instead of getView. The default implementation of getView in CursorAdapter does cursor.moveToPosition for you.
I don't know what you mean.
getString is fine.
Read 1. For managing cursors, I recommend using CursorLoader. (See: https://developer.android.com/training/load-data-background/setup-loader.html)

Your adapter should look like this.
public class CursorLi extends CursorAdapter {

    private LayoutInflater minflater;
    private int imd;

    public CursorLi(Context context, Cursor c, boolean autoRequery) {
        super(context, c, autoRequery);
        minflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view = minflater.inflate(R.layout.lvitem, parent, false);
        ViewHolder holder = new ViewHolder();
        holder.text = (TextView) view.findViewById(R.id.litext);
        holder.icon = (ImageView) view.findViewById(R.id.fiig);
        view.setTag(holder);
        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        imd = getResources().getIdentifier(c.getString(6), "drawable", "com.example.myapp");
        dr = getResources().getDrawable(imd);
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.text.setText(c.getString(4));
        holder.icon.setImageDrawable(dr);
    }

    public static class ViewHolder {
        TextView text;
        ImageView icon;
    }

}

Comment: Thanks. So why without "c.moveToPosition(position);" , getString doesn't work ?
Comment: The default implementation of `getView` in `CursorAdapter` does that for you (https://github.com/android/platform_frameworks_support/blob/master/v4/java/android/support/v4/widget/CursorAdapter.java#L247). If you (mistakenly) override `getView`, you need to do it yourself.
Answer: what i do is the following :
1st - create a Bean class that holds the values of the database like the following :
public class MyData {
    private String text ;
    private String imageName ;

    // with its getter and setter methods

}

2nd - when i query the database i will get a cursor , i will loop through the cursor and set the values in MyData objects
in an ArrayList like the following :
Cursor cursor = database.query(....);
ArrayList<MyData> list = new ArrayList<MyData>();
MyData data = null;
while(cursor.moveToNext()){

data = new MyData()

data.setText(c.getString(4));
data.setImageName(c.getString(6));

list.add(data);

}

   cursor.close() ;

return list ;

3rd- i would use a BaseAdapter instead of CursorAdapter like the following :
public class MyAdapter extends BaseAdapter {

    private ArrayList<Mydata> list ;
    private Activty activty ;

    public MyAdapter (Activity activty ,ArrayList<MyData> l ){
        this.activty =activty ;
        this.list = l ;

    }

}

4th - in your getView method you get the items from the list like the following :
public View getView(int position, View convertView, ViewGroup parent) {

        //.... just like you did with your PlaceHolder to initialize the views

        String text = list.get(position) .getText();
        String imageName = list.get(position).getImageName();

        // here you your image inside a new thread

        Thread trd = new Thread(new Runnable(){
             @Override
              public void run(){

                   try{
            final int drawableResource = activty .getApplicationContext().getResources().getIdentifier(imageName , "drawable", "com.example.myapp");

                     activty .runOnUiThread(new Runnable() {

                    public void run() {
                        imageView.setImageDrawable(drawableResource );

                    }
                });
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
        });
        trd.run();

}

and please give me some feedback , i wrote this on notepad :P
Hope that helps .


Open Set Under Integer Set

Question: I have a confusion regarding open set. This answer  https://math.stackexchange.com/q/1158238 states that -> i) S⊂R  is open iff for all s ∈ S, there exists an interval of the form (a,b) such that s ∈ (a,b) ⊂ S. ii) If C is a closed set, then R∖C is open (and Vice-Versa) and iii) union of open sets is open.
Now, if I take an set Z (Integer set) instead of R, is the subset {1} open or closed?  According to the first definition if I take S = (0,2) I can say that {1} is open.
But I can write {1} as -: Z - (−∞,1) U (1,∞) ((ii) + (iii) combined) which should make it a closed set.
What am I missing here? Can I not define an open or closed set in Integer set? Or there's something wrong I am presuming ?
Comment: Sets are not doors. They can be open, closed, both or neither
Comment: Thanks. Will Remember that.
Answer: If you are looking at $\mathbb{Z}$ as a subset of $\mathbb{R}$ equipped with the induced topology, then you obtain nothing other than the discrete topology on $\mathbb{Z}$, ie every singleton $\{n\}$ is open and closed in $\mathbb{Z}$. Indeed, $$\{n\}=\mathbb{Z} \cap (n-1/2,n+1/2)=\mathbb{Z}\cap [n-1/2,n+1/2]$$
This shows that $\{n\}$ can be written as the intersection of $\mathbb{Z}$ with an open subset of $\mathbb{R}$, as well as with a closed subset of $\mathbb{R}$. This topology is not really interesting, because every subset of $\mathbb{Z}$ is now open and closed.
If you want another example of a topology on $\mathbb{Z}$, you may want to consider the topology having finite subset as closed subsets, for instance.
Comment: Any topology where every set is open and closed is called a discrete topology. Though it's not very interesting in it's own, it's a good example of a totally disconnected space. Totally disconnected spaces are pretty interesting :-)

Open Set Under Integer Set


Laravel Validator only works for fails

Question: I'm trying to validate the upload file in laravel.
The file only accepts xlsx,xls and csv
I have this working code from my controller
  public function project_import_excel(Request $request){
    $validator = Validator::make($request->all(), [
        'file' => 'required|max:5000|mimes:xlsx,xls,csv'
    ]);

    $modal = "active";

    if($validator->passes()){
        return redirect()
        ->back()
        ->with(['success'=>'File uploaded successfully!'])
        ->with('modal',$modal);
    }else{
        return redirect()
        ->back()
        ->with(['errors'=>$validator->errors()->all()])
        ->with('modal',$modal);
    }
}

and I have this sessions for errors and success in my blade file
 @if(session('errors'))

        @foreach($errors as $error)

{{$error}}

        @endforeach

 @elseif(session('success'))

       {{ session('success') }}

 @endif

If I try to upload .jpeg or any other file that is not xlsx, xls, or csv
This will give me a message like

But if I upload  a file like`

The success message doesn't want to show up. Is there anything wrong with my if else?
The problem is, it always end up to session('errors')
UPDATE
I tried to remove this mimes:xlsx,xls,csv and the session('success') works fine. But how can I validate which files are acceptable or not?
My HTML code for form

Upload Projects List

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      ×
      </button>

        @include('main.projectlistRedirectBack')

            Note upload:
            You are trying to upload multiple project records that containas multiple task records. This record will be useful to any transaction

            *format : xlsx,xls,csv

            <form action="{{ url('/projectlist/project_import_excel') }}" method="POST" enctype="multipart/form-data">

            {{ csrf_field() }}

                    Choose file
                    <input type="file" name="file" id="file">

    <button type="button" class="btn btn-outline-success" data-dismiss="modal">Close</button>
    <button type="submit" name="submitImport" class="btn btn-success waves-effect" id="upBulkSubmit">Upload</button>
        </form>

tried this one dd($validator);
Comment: Try with status: `redirect()->back()->with('status', 'File uploaded successfully!')->with('modal',$modal);` . Then in blade `@if (session('status'))  {{ session('status') }}  @endif`
Comment: I also tried to change the variable `success` to `status` but still getting the same
Comment: did you have  enctype="multipart/form-data" on your form?
Comment: Yes, I have this attribute on my form `enctype="multipart/form-data"`
Comment: can you dd the `request` or `$validator` to see if file is there when you upload excel file?
Comment: pls check the updated question to see the `dd();`
Comment: what is inside array data? (data: array: 3)
Answer: Link given by @porloscerros
Laravel validator and excel files error
This answer, solved my problem!
   $validator = Validator::make(
    [
        'file'      => $request->file,
        'extension' => strtolower($request->file->getClientOriginalExtension()),
    ],
    [
        'file'          => 'required|max:5000',
        'extension'      => 'required|in:,csv,xlsx,xls',
    ]
    );

Answer: Try the followings:
@elseif(Session::has('success'))

  {{ Session::get('success')}}

@endif

or
 @else(session('success'))

       {{ $success }}

 @endif

Comment: Tried your options but still getting the same error.
Answer: Try this
if ($validator->fails()) {
return redirect()->back()
    ->withErrors($validator)
    ->with([
        'modal' => $modal
    ]);
} else {
return redirect()->back()
    ->with([
        'success'=>'File uploaded successfully!'
        'modal' => $modal
    ]);
}

and
@if ($errors->any())

    @foreach ($errors->all() as $error)

{{$error}}

    @endforeach

@else

   {{ session('success') }}

@endif

Hope it will works
Comment: Still the same.
Answer: You can try to show success and errors message to separate condition:
if($validator->passes()){
    return redirect()
    ->back()
    ->with('success', 'File uploaded successfully!')
    ->with('modal',$modal);
}else{
    return redirect()
    ->back()
    ->with(['errors'=>$validator->errors()->all()])
    ->with('modal',$modal);
}

And then view file:
@if(Session::has('success'))

         {{ Session::get('success') }}

@endif

@if(session('errors'))

       @foreach($errors as $error)

{{$error}}

       @endforeach

@endif

Laravel Validator only works for fails


Trouble with basic JavaScript loop

Question: I'm a newbie in JavaScript programming. At our university we were just beginning to learn about JavaScript loops. So here's a code using for loop:
var i;
var x = new Array();
var y = new Array(1, 1, 0, 3, 5);
for (i = 0; i < y.length; i++) {
    x[y[i]] = y[i];
}

I know that such code produces variable x to be an array with values
0, 1, undefined, 3, undefined, 5

I do not understand the logic behind it. Can somebody please help me?
Comment: What do you not understand exactly?
Comment: `i=0->x[1]=1, i=1->x[1]=1, i=2->x[0]=0, i=3->x[3]=3, i=4->x[5]=5` so x[2] and x[4] is never set
Comment: @mplungjan Waw, if the OP was having trouble deciphering the code he was looking at, this will be even more perplexing! :)
Comment: Nah. He is a university student
Answer: Let's first simplify this a bit and expand to make it more legible:
var x = new Array();
var y = new Array(1, 1, 0, 3, 5);
for(let i = 0; i < y.length; i++){
    let key = y[i];
    x[ key ] = y[i];
}

On first evaluation, i === 0, so key === y[0] or 1. Now that we have the key, we will assign the key as a value to the x array at the index that was the number stored in your y array at index i. So x[y[0]] = y[0], therefor x[1] === 1.
Wrince, repeat.
Comment: Tried your code and after some mental effort I understood. Thank you!
Answer: You have to realize that the positions where data is put in Array X are taken from Array Y.
As Array Y only have the following numbers (it means, positions): 0, 1, 3, 5, the positions 2 and 4 will be undefined in the Array X

var i;
var x = new Array();
var y = new Array(1, 1, 0, 3, 5);
for (i = 0; i < y.length; i++) {
    console.log("Index taken from ARRAY Y where number will be put in ARRAY X: " + y[i]);
    x[y[i]] = y[i];
}
Comment: Informative! Took me awhile to get it, but it's crystal clear now. Thank you!
Answer: Okay let's loop through that one by one:
i=0
x[1] = 1 //because y[0] = 1
i=1
x[1] = 1 //because y[1] = 1
i=2
x[0] = 0 //because y[2] = 0
i=3
x[3] = 3 //because y[3] = 3
i = 4
x[5] = 5 //because y[4] = 5
So you've set values in x for indices 0, 1, 3 and 5, but not 2 and 4, that's why those values are undefined
Comment: Thank you so much for this explanation!
Answer: Because you are not incrementing it by the index. You are setting the index based on the value of the index of the y array.
So what you are doing in your loop is
x[1] = 1  // i = 0;
x[1] = 1  // i = 1;
x[0] = 0  // i = 2;
x[3] = 3  // i = 3;
x[5] = 5  // i = 4;

There is no value of 2 or 4, so those indexes were never defined, so it it is undefined.
What you want is
for (i = 0; i < y.length; i++) {
    x[i] = y[i];
}

Comment: I read post by Thomas and then returned to yours. Thank you so much!
Answer: Try to write down each iteration and see how x changes in successive steps.
START           //                 []
x[y[0]] = y[0]; // x[1] = 1;       [undefined, 1]
x[y[1]] = y[1]; // x[1] = 1;       [undefined, 1]
x[y[2]] = y[2]; // x[0] = 0;       [0, 1]
x[y[3]] = y[3]; // x[3] = 3;       [0, 1, undefined, 3]
x[y[4]] = y[4]; // x[5] = 5;       [0, 1, undefined, 3, undefined, 5]

Trouble with basic JavaScript loop


A property of $k$-stable theories.

Question: Following the study of Tao's notes about model theory, i found a theorem about $\kappa$-stable theory and order property. It says that if a theory is $\kappa$-stable (with $\kappa\ge\aleph_0$), then this theory doesn't admit the order property. I'll include the proof and something that can be useful.

The question is: why do we need of elementary extension $N$ (and so we don't work only in $M$)?
Here there are the order property and $\kappa$-stable theory definitions.

(Order property) A theory is said to have the order property if there is an $L$-formula $\varphi$ and $M\models T$, with $X\subseteq M$, such that $\varphi$ defines a linear order on $X$.

($\kappa$-stable) We say a theory $T$ $\kappa$-stable, for a $\kappa$-infinite cardinal, if whenever $M\models T$, $A\subseteq M$, and $|A|\leq \kappa$, then $|S_n^M(A)|\leq \kappa$ for all natural $n$. (Note that, $S_n^M(A)$ consists in the set of $n$-type complete in $M$ over $A$.)

(Lemma 1.7.) For any $\kappa\geq \aleph_0$, there is a dense linear order $(A,<)$ with $B\subset A$ such that $B$ is dense in $A$ and $|B|\leq \kappa< |A|$.
Comment: By '*linear order*' do they specifically mean the linear order of order type $(\Bbb N,<)$? Or *any* linear order?
Comment: An order as that of Lemma 1.7 may not exist in $M$. By compactness it exists in some $N\equiv M$. You are right that $M\preceq N$ is more than what is needed. (I guess.)
Comment: @Berci Yeah, i suppose that is the first one.
Answer: To contradict $\kappa$-stability, you need to find a set $A\subseteq M$ with $|A|\leq \kappa$ and $|S_n^M(A)|>\kappa$.
So here's a stupid answer: What if $M$ is small relative to $\kappa$? Say $2^{|M|} \leq \kappa$. Then for any infinite $A\subseteq M$, $|S_n^M(A)|\leq 2^{|A|}\leq 2^{|M|} \leq \kappa$ so there is no hope of contradicting $\kappa$-stability while working in the model $M$.
In fact, it's not just enough to work in a large enough model and find a large enough set $A$: The strategy of the proof is to find a set $A$ which is linearly ordered in a specific order type (the kind described in Lemma 1.7). Now suppose we have some infinite set $X$ linearly ordered by a formula $\varphi$. [Correction: in your definition of "order property", you should include the condition that $X$ is infinite, otherwise every theory has the order property, by definably ordering a finite set.] Then we can use the compactness theorem to find a set which is linearly ordered by $\varphi$ in whatever order type we want. But the key thing is that the compactness theorem produces a model for us, which is in general different from the model we started with. The exception is if the model $M$ we started with is sufficiently saturated - then you can use compactness to show that a certain type is consistent, and realize it in $M$ using saturation.
Moral: If you want to apply the compactness theorem to realize some type, you have to be willing to move to a new model (which can be arranged to be an elementary extension) or work in a sufficiently saturated model to begin with.

In the comments, you ask for more explanation on the application of the compactness theorem. Here's how it works:
By Lemma 1.7, there is a dense linear order $(A,<)$ with $B\subseteq A$ such that $B$ is dense in $A$ and $|B|\leq \kappa < |A|$. For each $a\in A$, let $\bar{c}_a$ be a tuple of new constant symbols of the same length as the tuples $\bar{v}$ and $\bar{w}$. Now write down the following theory: $$\text{EDiag}(M)\cup \{\varphi(\bar{c}_a,\bar{c}_b)\mid a<b\text{ in }A\} \cup \{\lnot \varphi(\bar{c}_a,\bar{c}_b)\mid b\leq a\text{ in }A\}.$$
Here $\text{EDiag}(M)$ is the elementary diagram of $M$. A model of this theory is an elementary extension of $M$, which contains a family of tuples which are linearly ordered by $\varphi$ in order type $A$.
To find such a model, we apply the compactness theorem. We need to show that any finite subset of this theory is satisfiable. Any finite subset of this theory is contained in $\text{EDiag}(M)$, together with sentences asserting that finitely many of the tuples of new constant symbols, say $\bar{c}_{a_1},\dots,\bar{c}_{a_n}$, are linearly ordered by $\varphi$. Such a finite subset is satisfiable in $M$ by interpreting the tuples of constant symbols $\bar{c}_{a_1},\dots,\bar{c}_{a_n}$ as $n$ of the tuples from $X$.
I've only given a sketch of the argument, and Tao summarizes the argument even more, just writing "using the compactness
theorem...". This is quite common in model theory: Once you get used to applications of the compactness theorem like this, they become quite mechanical, and authors often write "by compactness" and leaave the details to the reader. But until applying the compactness theorem becomes second-nature to you, you might be better served by working through a textbook on model theory (Marker's Model Theory: An Introduction or Hodges's A Shorter Model Theory are good choices) before moving on to terse lecture notes like Tao's.
Comment: @Silvie I've added to my answer. I hope this helps.
Comment: Thank you so much. Now it's really clear! I'll study also on the other textbook which you showed me.

A property of $k$-stable theories.


Taking a Switch on vacation from EU to USA. What region eshop will I be able to access?

Question: If I take an EU Switch (with EU account) to the USA for the holidays, will I be able to access the EU eshop?
If I do switch to the USA eshop, will those games still be available for download after I switch back to the EU shop? Will they even start when in the EU?
Answer: It doesn't matter where your Switch came from. They're all the same, and region-free. The only thing that matters, is which region your account belongs to.
If you have a Japanese account, it will only be able to access the Japanese eShop, no matter where you are in the world.
If you have a German account, it will only be able to access the German eShop, no matter where you are in the world.
etc.
In order to access another eShop, you will either need another account from that country, or you'll need to change your account's country setting. Note that you'll have to use up any and all funds remaining on your account to do so:

Your Nintendo eShop account balance does not carry over when you change your Nintendo Account country. You will need to use the remaining funds before you can change your country.

If you intend to change regions often (or temporarily), I recommend using multiple accounts. You can easily download games on one account, and play them on another. Just make sure both accounts are on the same Switch, and that the Switch is registered as the "primary console" for the secondary account.
The only downside to having multiple accounts from different regions, is that the News channel will display the same news from different regions. You'll also have to select an account whenever you want to launch a game or the eShop (as opposed to simply defining a default account).


Is safety of Object as dictonary really really guaranteed by standard?

Question: var x = Object.create(null);
x["hello"] = "world";

But can I allow unverified user input as keys? I want to use it as player name -> player object map. Player names will only be constrained by length of 32. I'm worried if there are special property keys that would allow players to gain control of the server.
EDIT: I'm not making web server. JavaScript will be ran server-side via SpiderMonkey embedded into the game server. If someone hijacks the JavaScript running there, they could ruin the game.
Answer: Property keys are always strings. You'll never encounter a problem with any property name, except for maybe:

Object.prototype.hasOwnProperty. For example in:
var obj = {hasOwnProperty:'fail'};
for (var i in obj) {
    if (obj.hasOwnProperty(i)) ; // ...
}

which can be solved by using Object.keys(obj).forEach( ... ) or:
for (var i in obj) {
    if (Object.hasOwnProperty.call(obj, i)) ; // ...
}

The only hazard is caused by how you deal with the object. The previous example is not an uncommon usage of hasOwnProperty, but it can be used to break your script, because you don't expect the key name hasOwnProperty. The same can apply to .toString, or any other property of the object which can be overriden by setting a new name.
Comment: Won't Object.create(null) create an object that doesn't even have hasOwnProperty?
Comment: @lamefun Yes, that's correct. Your code is safe, because you do *not expect* any pre-defined properties/methods. That, and "property keys are always strings" should be sufficient to sleep well ;)
Comment: Amazingly, I ran into a bug today caused by this in some old code. Properties were being added to an object based on user input, and there was a situation that could result in a `hasOwnProperty` property being added. And your suggestion is just what I did too, so +1!
Answer: In one word: no, just remember the Google Docs __proto__ fail
You should use a Hash-like class, or at least access these keys prefixed:
var hash = {}, key = "something-evil", value = Math.PI;
hash["$" + key] = value;
console.log( hash["$" + key] == value );

Comment: `__proto__` comes from Object.prototype, at least on my Firefox. If I create an object with `null` prototype, it doesn't have `__proto__`.
Comment: Yes, but it is supported in webkit & opera too, and if you create objects with `Object.create(null)`, the `__proto__` setter still works, because its not comes from `Object.prototype`, instead it reflects the inner [[Prototype]] property - in Chrome and Opera.

You're right, FF is an exception here.
Answer: No, an object is basically a blank slate, there are no special keys. On top of that, even if somebody hacks your Javascript it is very unlikely that they will gain control of your server unless you are using very lax security policies (like putting the root password in your Javascript or something silly like that).
Comment: I want to use JavaScript server-side via embedding a JavaScript engine into the game server. Although I won't expose system functions to it, it's still undesirable that someone will ruin the game.
Comment: Ah, in that case it depends on what you are exposing to the embedded engine, and what software you're using for the embedded engine.
Answer: You cannot control what will be sent to your web server. At all. Ever.
So, you need to put restrictions on what you server will do, in response to anything sent to it. Part of this is validating all user input, even if it's JSON representing a JavaScript object that was created by your code.


Searching with mandatory filters

Question: I'm having trouble designing a search box with two mandatory filters/categories before the user hit the "go" button.
So far, the best solution I could come up with was this one:

I've presented the following solution to my client, but they insist it's not ideal once the user would have to open up the split button and change the axis of their cursor and all of that, but I don't really see how this can be a heavy impact on the navigation. If it was all up to me, I would go along with this one, but they insist it's not the format they want, so forget about it.

Well... any ideas?
Comment: Using the same search term, how will the results differ with each of these options?  I cannot quite figure out if users are searching _for_ documents or _within_ documents
Comment: Are these the only two categories users would search?
Comment: yes, there are only these two filters available
Answer: If the filter is mandatory, choose the most frequent search as the default.
You can try a scoped search dropdown before the search input field. This way the search button is Active from the beginning.
Lead with what your metrics show that the majority of users will want to search by, and don't make them pause to choose a filter.

The tradeoff
If you have some metrics that make the case for the most likely search, users who don't see the filter, and just search will be rewarded.
Those who would search 'Fragments' (let's say it's the lesser of the searches), might not see the dropdown, and search immediately.
Comment: this is a very good solution, even Amazon use this logic and I don't see a good reason for not using it.

I may suggest the client that they leave the user search for whatever they want, and then when the results come in, they can filter it by tabs just above the results list. That could be more effective. I don't know.
Comment: @feelerino I could see the argument that that leads to a significantly increased search time, both in terms of processing and in terms of user decision.  It's worth bringing up, just figure out what the average time increase is if the person gets irrelevant results and has to filter them out after the search so you know what you're dealing with.
Answer: I remember GitHub had something like what Mike M suggested for their search. I just noticed that it's changed, and what they do now is make the selection a part of their autocomplete-like menu:

I imagine the default selection at the top is what they believe to be the most common, which makes sense to search in the current repo by default. An advantage I note in this is that it let's you switch without hassle. If I wanted to search "rails" in "All GitHub" (which makes more sense), all I need to do is press ↓ before hitting Enter. This means that switching the filter is just a single additional keypress.
Comparing this with other solutions:

dropdown input at the left means I have to Shift+Tab and hit ↓ either once or twice (I get the feeling that some dropdowns don't change the selection on the first hit and only open the menu with the selection unchanged, which gives me uncertainty about dropdowns in general).
2 buttons at the right with the default on the left means I have to hit Tab twice.
2 buttons at the right with the default on the right means I only have to hit Tab once to switch, but it might not be intuitive that the default is not what's closest to the input.
radio input is like dropdown but at least I can be sure that hitting the arrow key will cause a change in selection.

All these other solutions also suffer in that they have more visual noise, when the input is not in use. An advantage they do all have, however, is that they don't require javascript (if we're talking websites here), which is nice both for the developer and users.
Comment: hey JoL, unfortunatelly only now I saw your reply :( this is a very convenient solution. Thank you anyway, that was a great insight.
Comment: @feelerino I see you haven't accepted any answer, yet. You probably should, even if it's not mine. You accept an answer by clicking on the checkmark below the voting buttons.
Answer: Since this is a mandatory tasks before interacting with search, consider search like the Call to action like save or submit. Before you can accomplish these actions you must fill out a form.
In this case your form is a radial group and a text input field.
Comment: I've offered this option too, but client argued the filters "are too important" to go out of the reading flux. I mean, the thing is right by the search field, right?
Comment: Perhaps since you have disabled interaction with the call to action this will be better received and you also provided inline instruction. I do like DarrylGoddan option where you just use two call to actions. This is not scalable solution but you can iterate later.
Answer: If these are the only two options and are likely to remain so, I would go with something like this:

download bmml source – Wireframes created with Balsamiq Mockups
Comment: this is actually a good option, but the problem is that apparently the user would search for very long terms, like this is a page that's gonna be used by engineers and people looking for some very particular content about energy, power plants and the likes. The client himself commented about this solution, even saying they used it in a previous project, but that it wouldn't really work for this current one.
Comment: I would very interested in a usability test to see what criteria your users will search. The norm for search is to be vague and use keywords. I find it curious that you would have users search for long phrases. In the event that users do search with key words and or questions this would circumvent your clients concern, making this a viable solution.
Comment: This is a valid option only if the 2 options are equal in terms of importance and expected usage frequency. Otherwise - you force the user to make unnecessary choices every single time he uses the search..
Answer: Did you consider an auto-suggest search for both categories?
That way you provide the user with immediate value before forcing him to make a further choice..
Answer: Probably not an ideal design decision — I mean I certainly wouldn't do this, but since the client seems to be a bit of a stickler, I'm just throwing it out there as an idea.
Two search bars, one for each category, when the user focuses on one, disable the other.
Like I said, not a good idea, but I don't see anything wrong with the other solutions you've already presented to the client, so it seems to me like the client doesn't really want some that makes sense. Instead, they just want what they want, and they want you to just figure out what that is.
Maybe they want something stupid like this...?!
Answer: One good alternative: Search for both every time (if performance considerations allow), and present the results in two tabs "documentos" and "fragmentos". Foreground the tab that is known to be about the more frequent search (can be globally set, or a per-user setting). If performance is a problem here, execute the search filling the background tab only if it is actually clicked.
Answer: You could ask yourself how mandatory choosing really is and just search in both categories by default. You can then offer filters on the result page to refine the search.
If, as you say, the search terms are long anyway, the results might already be unique enough to yield what the users are searching for.
If you still want to give all options from the beginning, hide the filters under an advanced search drawer or something similar.

Searching with mandatory filters


Determine $x$ coefficient of $f(x)=( (x+1/x)^a+(x-1/x)^a)^b$

Question: I'm trying to find the coefficients of $x$ from $f(x)=( (x+1/x)^a+(x-1/x)^a)^b$ where $a,b\in\mathbb{Z}^+$.  I tried reading through some of Wilf's Generatingfunctionology, but I think I am still having trouble.
$$\begin{align}
[x^n]f(x)&=[x^n]\bigg( \big(x+\frac{1}{x}\big)^a   +   \big(x-\frac{1}{x}\big)^a   \bigg)^b \\
&=[x^n]\sum_{i=0}^b \binom{b}{i} \bigg(x+\frac{1}{x}\bigg)^{a(b-i)} \bigg(x-\frac{1}{x}\bigg)^{a i}  \\
&=[x^n]\sum_{i=0}^b \binom{b}{i} \bigg[\sum_{j=0}^{a(b-i)} \binom{a(b-i)}{j} x^{a(b-i)-2j }\bigg]
\bigg[\sum_{k=0}^{ai} \binom{ai}{k} x^{ai-2k }\bigg]  \\
\end{align}$$
So now I feel like the trick is just to figure out the coefficients for the two pieces in square brackets, since that means I could use the following
$$\begin{align}
[x^n]f(x)&=[x^n] \bigg(g(x)\cdot h(x) \bigg)\\
&=\sum_{p} \bigg([x^{n-p}] g(x) \bigg)\cdot \bigg([x^p] h(x) \bigg)\\
\end{align}$$
However, at this point I'm getting a little unsure of how exactly to pull the coefficients out of $g(x)$ and $h(x)$ above without messing up indices or the $n-p$ relationship.  Is it just
$$\begin{align}
[x^n]f(x)&=[x^n]\sum_{i=0}^b \binom{b}{i} \bigg[\sum_{j=0}^{a(b-i)} \binom{a(b-i)}{j} x^{a(b-i)-2j }\bigg] \bigg[\sum_{k=0}^{ai} \binom{ai}{k} x^{ai-2k }\bigg]  \\
&=\sum_{i=0}^b \binom{b}{i} \sum_p\bigg[[x^{n-p}]\sum_{j=0}^{a(b-i)} \binom{a(b-i)}{j} x^{a(b-i)-2j }\bigg] \bigg[[x^p]\sum_{k=0}^{ai} \binom{ai}{k} x^{ai-2k }\bigg]  \\
&=\sum_{i=0}^b \binom{b}{i} \sum_p\bigg[\binom{a(b-i)}{j}\binom{ai}{k} \bigg]  \\
\end{align}$$
with $(n-p)=(ab-ai-2j)$ and $p=(ai-2k)$.  Which simplifies further by $k=(ai-p)/2$ and $j=(ab-ai-n+p)/2$ giving
$$\begin{align}
[x^n]f(x)&=\sum_{i=0}^b \binom{b}{i} \sum_p\bigg[\binom{ab-ai}{(\frac{ab-ai-n+p}{2})}\binom{ai}{(\frac{ai-p}{2})} \bigg]  \\
\end{align}$$
I'm not sure which steps I'm doing wrong, but plugging the last equation into Mathematica and punching in some $a,b,n$ values is giving me some numbers often with a $1/\pi$ term which I know is incorrect since $a,b\in\mathbb{Z}^+$ should be giving me integer coefficients for all $[x^n]$.  Any hints, tips, or references?
Answer: OK, first of all I would advise that you bring out a factor of $x$ from each of your inner brackets, to get $$\left(\left(x+\frac{1}{x}\right)^{a}+\left(x-\frac{1}{x}\right)^{a}\right)^{b}=\left(x^{a}\left(1+\frac{1}{x^{2}}\right)^{a}+x^{a}\left(1-\frac{1}{x^{2}}\right)^{a}\right)^{b}=x^{ab}\left(\left(1+\frac{1}{x^{2}}\right)^{a}+\left(1-\frac{1}{x^{2}}\right)^{a}\right)^{b} $$
Now, we can certainly expand the inner brackets easily, as: $$2^{b}x^{ab}\left(1+\binom{a}{2}x^{-2}+\binom{a}{4}x^{-4}+\ldots\right)^{b}$$
Now count all the ways we can make $n$ by choosing $b$ even numbers less than $a$ to subtract from $ab$.
Comment: Okay, those expansions do help simplify things inside the $(...)^b$ and with the "choose b numbers less than a" hint I think I could figure out a "find $[x^8]$"-type problem by working it out by hand, but what would be the best way to find the coefficient for general n? I thought about trying a multinomial expansion now, but it seems like that would be a huge mess of $a$-many binomial coefficients.  Is there some better way of counting "$b$ even numbers less than $a$"?  Thanks
Comment: If you redistribute the $x^{ab}$ inside the bracket, then all your exponents are positive. Beyond that, I can't see a clever trick that's better than the multinomial formula.