Access a Label from one class file to another class file c# and asp.net

Question: I have created a DB Connection class file which is shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data.SqlClient;
using Asset;

namespace Asset.Modules
{
    public class Dbconn
    {

    public bool CreateDBConnection()
    {
        SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["AssetDBConnection"].ConnectionString);

        try
        {
            con.Open();
            return true;
        }
        catch (SqlException ex)
        {
            errorLabel.Text = ex.Message;
            errorLabel.Visible = true;
            return false;
        }
    }
 }

errorLabel is defined on my Default.aspx page as shown below;
<asp:Label ID="errorLabel" runat="server"></asp:Label>

The error that I am getting is: The name 'errorLabel' does not exist in the current context.
How do I get the Dbconn file to access the Label which is located on the default.aspx page?
Thanks for your help.
Comment: Managed to resolve this in the end by following this post: https://stackoverflow.com/questions/15450158/access-textbox-value-of-an-asp-net-page-from-c-sharp-class/15450218
Answer: Probably this can entail ...
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        ....accessing the database conn shared instance

        Label myLabel = this.FindControl("errorLabel") as Label;
        myLabel.Text = "my text";
    }
}

Answer: You can cast the CurrentHandler back to a Page object and use FindControl in CreateDBConnection().
Page page = HttpContext.Current.CurrentHandler as Page;
Label lbl = page.FindControl("errorLabel") as Label;
lbl.Text = "There was an error.";


Can $\pi$ and the $\pi$ in radians simplify?

Question: I saw in a proof for the limit $$\lim_{x\rightarrow 0}\frac{\sin(x)}{x}=1$$ that, in one of the steps, you had to take the area of a section of a circle, in which you had to do $\frac{\pi r^2 x}{2\pi}$, $x$ being the angle of the section. Then, they simplified the $\pi$ in the numerator with the $\pi$ in the denominator. Do these $\pi$ mean the same thing? Is this simplification correct?
Answer: Absolutely. That's the idea behind radians: $2\pi$ radians goes around a circle, and on a unit circle it moves a distance of $2\pi$ in the process.
Comment: Oh I understand. I thought the $/pi$ in the denominator meant 180 for some reason. I guess I was thinking in terms of degrees so it didn't seem natural to me. Thanks for the answer!
Comment: Yes, the measure of an angle in radians is a "pure number" (there are no units of measurement).  The angle $\pi$ is the number $\pi$.


Block code in lists - possible?

Question: Sometimes it makes sense to write answer in points, and include couple lines of code in one point. However, indenting with 4 spaces does not work for lists, and breaking list with no-list text causes list numbering to reset. Using apostrophes ` makes all lines of code to display as one line (or separate code blocks).
Is there a good way to do it?
Example:

a
b
first code
d

list break
second code

e
third code line 1
third code line 2
Answer: Inside lists, indent the code by (N + 1) * 4 spaces, where N is the indentation level for the list item containing the code.

First point
Second point
Third point
// This code is indented by 4 spaces; the item containing it is indented by 1 level.
$account = user_load($uid);

Fourth point

Another point
Yet another one
 // This code is indented by 8 spaces; the item containing it is indented by 2 levels.
 $account = user_load($uid);

Block code in lists - possible?


P5.js : manually calculate additive blendmode with pixels[]

Question: I'm currently coding a P5.js program in which I draw some random generated patterns like this :
function setup() {
     colorMode(RGB, 255, 255, 255, 255);
     blendMode(ADD);
}

function draw() {
    for(var i = 0; i < 20000; i++)
    {
      x = generateCoordinatesX();
      y = generateCoordinateY();

      var pointColor = generateColor(); //rgba

      stroke(pointColor);
      point(x, y);
     }
}

When two ore more points get supperposed, they are displayed with additive BlendMode.
As the number of point is quite big, it slows down the simulation a lot. I tried to adapt this code with the pixels method like bellow to speed up things :
function draw() {
    loadPixels();
    for(var i = 0; i < 20000; i++)
    {
      x = generateCoordinatesX();
      y = generateCoordinateY();
      var index = (x + y * width)*4;

      pixels[index+0] += ???;
      pixels[index+1] += ???;
      pixels[index+2] += ???;
      pixels[index+3] += ???;
     }
     updatePixels();
}

The issue is that i dont know how to generate the R,G,B,A value so that it behave with additive Blending like my first version.
Is there a way to manually calculate this ? I tried with formulas i found but after some tests, the results are different.
Thanks in advance
Answer: There's a bunch of very helpful methods that will fill in this information for you. They are respectively named red, green, blue and alpha, and you can use them to extract the relevant information from a known color.
Here's a code snippet to demonstrate:
function setup() {
  createCanvas(400, 400);

 background(color(0, 255, 0));
}

function draw() {
}

function mouseClicked() {
  let blendColor = color(128,0,0);
  let density = pixelDensity();

  loadPixels();
  for (var i=0; i<width*height*density*4; i+=4)
  {
    pixels[i] += red(blendColor);
    pixels[i+1] += green(blendColor);
    pixels[i+2] += blue(blendColor);
    pixels[i+3] += alpha(blendColor);
  }
  updatePixels();
}

Once you click on the canvas, it'll update the background color by adding the blendColor to the pixel array. I deliberately choose a color that you can blend more than once to demonstrate that there won't be any stack overflow if you try to blend two colors which should go over 8-bit (255) in intensity, so you can click more than once without fearing a crash.
Hope it helps. Have fun!


How to disable horizontal scrolling when the mobile navigation is pulled out?

Question: I want to have the drag-out navigation like there is on touch.facebook.com and my (simplified) markup is showcased on this fiddle here.
When the navigation is shown, the browsers can scroll to the end of the content on the right side, as witnessed by the horizontal scrollbar that appears. Not a problem on the desktops really, but on mobile devices you might accidentally drag it to the right and it looks really clumsy.
The only working solution I know of for this situation is to give the document a overflow-x:hidden;. But for some reason, if I do that, vertical scrolling no longer fires jQuery's scroll event. So I have to find another CSS solution to achieve the desired behavior.
Answer: Actually, it turns out the problem was giving the html element height:100%. Once that was removed, and overflow-x:hidden; was applied to body again, both situations were successfully resolved.
Answer: Have you tried applying the overflow-x: hidden to the body tag instead of html?
Comment: Kinda, sorta, but i actually figured out something else that was causing the problem, will post the answer (i don't have enough reputation to give you a vote up for a useful suggestion)
Comment: Haha no worries, glad you figured it out!


Does the initial polynomial of a Sturm sequence need to be normalized?

Question: I've written an algorithm that generates a Sturm sequence and uses that sequence to determine the number of real roots over an interval.
My algorithm is working, but I made no precaution to normalize my polynomial i.e. to ensure that the leading coefficient is 1.
I've looked around for information on whether it needs to be normalized or not but without anything concrete - although all examples I see make use of a normalized polynomial.
Does the initial polynomial need to be normalized or not? If so, why is my algorithm still working?
Answer: Nope, you can multiply a polynomial by a constant factor (even negative) without influencing the roots. All derived polynomials will be multiplied accordingly.
Comment: Thanks! Makes sense


How do I unlock new workout environments?

Question: In My Fitness Coach, you start out with a few different workout locations, and the rest are locked.
How do I unlock them? Is it number of workouts? Do those workouts have to be on the days that I have "planned" them?
Answer: According to the game manual, you have to work out a certain amount of times on consecutive scheduled days:

3 days -> Bronze level -> Desert Spring Resort -> Dance music
5 days -> Silver level -> Alpine Retreat -> Techno music
7 days -> Gold level -> Island Paradise -> House music
9 days -> Platinum level -> Forest Glade
11 days -> Diamond level -> Rooftop Vista

For example, if you want to reach Silver level, you have to stick to the calendar during 8 days, three from Bronze level plus five to achieve Silver level.


Advice on a better way to extend C++ STL container with user-defined methods

Question: I inherited from C++ STL container and add my own methods to it. The rationale was such that to the clients, it will look act a regular list, yet has application-specific methods they can readily be called.
This works fine, but I have read numerous posts about not inheriting from STL. Can someone provide a concrete advice of how I might write the code below in a better way?
class Item
{
  int a;
  int b;
  int c;

  int SpecialB()
  {
    return a * b + c;
  }
};

class ItemList : public std::vector<Item>
{
  int MaxA()
  {
    if( this->empty() )
      throw;

    int maxA = (*this)[0].a;

    for( int idx = 1; idx < this->size(); idx++ )
    {
      if( (*this)[idx].a > maxA )
      {
        maxA = (*this)[idx].a;
      }
    }
    return maxA;
  }

  int SpecialB()
  {
    if( this->empty() )
      throw;

    int specialB = (*this)[0].SpecialB();

    for( int idx = 1; idx < this->size(); idx++ )
    {
      if( (*this)[idx].SpecialB() < specialB )
      {
        specialB -= (*this)[idx].c;
      }
    }
    return specialB;
  }

  int AvgC()
  {
    if( this->empty() )
      throw;

    int cSum = 0;
    for( int idx = 0; idx < this->size(); idx++ )
    {
      cSum += (*this)[idx].c;
    }

    return cSum / this->size(); // average
  }
};

EDIT: Thanks for a bunch of thoughtful answers. I will create helper functions instead and from now on will never inherit from STL containers.
Answer: This is a bad idea.
There are a lot of reasons you shouldn't derive from STL classes, foremost of which is that they're not designed for it.  Vector doesn't have a virtual destructor, so if you extend it, the superclass's destructor may not be called properly and you'll get memory leaks.
For more on this, see this answer on why not to derive from std::string.  Many of the same points apply:
Constructor doesn't work for class inherited from std::string

No virtual destructor
No protected functions (so you gain nothing by inheriting)
Polymorphism won't work, and you'll get object slicing.  std::vector is assignable, but if you add your own fields they won't get copied on assignment if you assign from a vector pointer or vector reference.  This is because vector's operator= does not know about your fields.

For all of these reasons, you're better off making utility functions than extending when it comes to STL.
Comment: You mentioned destructor; if I have a bunch of objects inside a std::list, will they be destroyed once the std::list is destroyed? Or do I have to empty the list manually by myself before cleaning.
Answer: why you need extend vector in this way?
use standard <algorithm> with your functors.
e.g.
std::min_element, std::max_element
int max_a = std::max_element
        (
            v.begin(),
            v.end(),
            boost::bind(
                std::less< int >(),
                bind( &Item::a, _1 ),
                bind( &Item::a, _2 )
            )
        )->a;

std::accumulate - for calculate avarage
const double avg_c = std::accumulate( v.begin(), v.end(), double( 0 ), boost::bind( Item::c, _1 ) ) / v.size(); // ofcourse check size before divide

your ItemList::SpecialB() could be rewrited as:
int accumulate_func( int start_from, int result, const Item& item )
{
   if ( item.SpecialB() < start_from )
   {
       result -= item.SpecialB();
   }
   return result;
}

if ( v.empty() )
{
    throw sometghing( "empty vector" );
}
const int result = std::accumulate( v.begin(), v.end(), v.front(), boost::bind( &accumulate_func, v.front(), _1, _2 ) );

BTW: if you don't need access to members, you don't need inheritance.
Comment: But doesnt the  work on an item at a time? My particular case needs to work on the data members. i.e. ::a, ::b, or ::c...?
Comment: @ShaChris23: most of algorithms could accept functors which will get your members
Comment: @ShaChris23: fixed avg sample
Comment: I'm not familiar boost::bind...could you please describe what _1 and _2 are or mean?

reference: boost::bind( &accumulate_func, v.front(), _1, _2 ) );
Comment: boost::bind - function which creates functor object from another function or functor. Binder allow you define parameters for function from which new functor will created  _1, _2 - input parameters in newfunctor.
Comment: http://www.boost.org/doc/libs/1_38_0/libs/bind/bind.html - standard boost::bind documentation, if my explanation a little complicated.
Answer: Since you can only "extend" the vector by using its public interface, it is far more useful to write functions which operate on a vector instead of being part of a vector.
Heck, if you plan it well, make it work with iterators instead of indexes and it'll work with more than just std::vector (see <algorithm> for some very good examples).
For example, you could use a functor for the MaxA like this:
struct CmpA {
    bool operator()(const Item &item1, const Item &item2) { return item1.a < item2.a; }
}

const int result = std::max_element(v.begin(), v.end(), CmpA()).a;

your specialB could be just as simple with a functor and std::accumulate
EDIT: or for c++11 and later, it can be as simple as:
const int result = std::max_element(v.begin(), v.end(), [](const Item &item1, const Item &item2) {
    return item1.a < item2.a;
}).a;

EDIT: you've asked why it is better to do it this way:
if you use algorithms, templates and iterators, it'll work even if you decide to put the items in a std::list<Item> or whatever. It is simply more versitile and helps code reuseablity.
Plus the functions in <algorithm> do much of this for you so you can just use little 3 line adapter functors.
EDIT: In addition to this, tgamblin listed some very compelling reasons to not inherit from std::vector (and most other std containers, including std::string).
Comment: Indeed: writing functions for iterators is a _way_ more powerful concept  than inheriting a bag of member functions. +1 you!
Answer: I prefer to use stl containers as an implementation detail rather than as part of my solution's interface. This way I can change containers (vector for deque or list) if the need arises without any of the calling code being affected. You may have to write a few call through functions but the encapsulation is worth the extra typing.
Answer: Warnings about not inheriting from STL containers appear because methods of STL containers are not virtual. So if you don't override methods and don't need polymorphic behaviour, but just extend the class — it's OK to inherit STL containers.
Comment: sure, it's "ok". But there is no point since you can only rely on the public interface of std::vector anyway. So you may as well just operate on that without the hassle of inheritance.
Answer: If the standard algorithms don't have what you need, just write free functions, preferably templated.
Answer: I can't see why you need to extend vector with those methods. You could just write them as standalone functions, eg:
int MaxA(const std::vector<Item>& vec) {
    if(vec.empty()) {
        throw;
    }

    int maxA = vec[0].a;
    for(std::vector<Item>::const_iterator i = vec.begin(); i != vec.end(); ++i) {
        if(i->a > maxA) {
            maxA = i->a;
        }
    }
    return maxA;
}

Or there's std::max_element which would do much the same... minus the throwing of course.
Comment: I agree with what you are saying. However, dont you think it would be nice if the MaxA() function is part of your container class? I mean..the MaxA is expected to work with vector container afterall.
Comment: It would be nice, yes, but it's a bad idea b/c STL isn't designed for inheritance.  See my answer.
Answer: You're correct that you should not inherit from STL containers. Virtual functions would make them meaningfully larger -- the base size of vectors would jump from 12 to 16 bytes (in the implementation I'm using). Besides that, virtual functions are difficult to inline, which can slow down the code. If you find yourself making an array of a million mostly-empty vectors, the difference adds up pretty fast.
You can still get the effect you want by declaring the vector as a member variable in your ItemList and then thunking through any methods that you wish to expose.
class ItemList {
private:
  std::vector< Item > mItems;
public:
  typedef std::vector< Item >::size_type size_type;
  int MaxA();
  int SpecialB();
  Item &operator[]( size_type offset ) { return mItems[offset]; }
  size_type size() const { return mItems.size(); }
};

... and so forth. This is a fair amount of grunt work, but it will give you the effect you asked for.
Answer: Just write a class that has a vector as a private member and write public interface functions that act on that vector.
edit:
I saw that AHelps already gave the same answer so bump...
Comment: Then, please remove/delete your duplicate answer


Refrigerator is warm but freezer stays cool

Question: I have a Frigidaire top freezer refrigerator. The freezer is fine, however it freezes up and blocks the vent, preventing cool air from circulating into the refrigerator section: Pic attached is freezer interior:
Problems:

Ice builds up on back panel of the freezer.
Air vent into fridge gets blocked by this ice.
Fridge doesn't cool down.

A few things I have tried:

Defrost heater is reading 35 ohms.
I have noticed the fridge enter its defrost cycle throughout the day.
Manually turning the mechanical defrost timer does send the unit into defrost.
When I trigger the defrost, the heater does warm up and glows red.
Ventilation fan is working.

What could be the problem here, or what should I check for?
The thermostat should be okay, since it turns on the heater once the defrost cycle is on. There is no problem with the defrost heater. The only other thing that could be the problem is the defrost timer. However it does activate the defrost cycle throughout the day that I've noticed. Could it still be faulty?
Answer: three main points come to mind (in this order):

Door seal(s): even though you may think the door is closed all the way, a weak magnet or bad seal will cause this problem EVERYTIME. Try the "dollar bill" trick: place a dollar bill in the area around the door seal and do a full series of tests the full perimeter of the door. The dollar bill should be held in place by the door seal when closed and should require effort to pull it out. If it is "easy" anywhere, then the seal is poor and moisture is getting in greatly accelerating frost buildup
Air fan: While you identify the fan is working, is it working properly? The motor itself can be marginal, running poorly, or not at all, check contacts and wiring, and also confirm the bearings are firm but the blades spin freely. Also (and this is critical), ensure the supply and return ducts are not blocked. Make sure they are fully defrosted, and clean. Any food, mold, plastic bags, etc are removed and do not store products in front of or blocking the ducts
Refrigerant cycling: if there is a flow issue (pinched lines etc) or too low refrigerant, the unit can be cycling on and off or never off, either way allowing the ice buildup, but this is usually only found in old or damaged units. Try setting the freezer to its warmest acceptable level, and make sure it is cycling off vs. running 24/7

As noted in the other answer, but amplifying it a bit further, make sure that if the unit has a defrost tray that it has water in it - it is possible the ductwork is bloxked by plastic debris or mold/food. Make sure all tubing is free and clear
Comment: Try cleaning the drain with a turkey baster filled with hot water. Caution be sure you know where the water goes, on some units it is in a small pan thing where the compressor heat evaporates it and it can overflow if you are not careful.
Answer: I had similar problem. The fix for me was to unplug the drain so the water that is gathering under the radiator has a chance to escape from the fridge.


How to rebind the mob light level indicator toggle key?

Question: I'm using the NotEnoughItems (NEI) mod and I know if I press F7 there should be a grid where monsters will spawn. But when I press it, nothing happens, it was working before I don't know what happened.
Is there a way to rebind the key? I've looked in all the places I thought it would be but I cant find it.
Comment: Do you have any way to check that the key is working outside the game?
Comment: Check the config file.
Comment: Yes, my key is working outside of the game. I don't know why it isn't working in-game.
Comment: Got any other mods? It could be button conflicts causing this.
Answer: You can rebind the key in NEI.cfg by going to the 55th line (at least in my version), and change world.moboverlay=65 to whatever number that matches the key code of the button you want to toggle it.
You can find a reference for the LWJGL key codes on the Minecraft Wiki,
or directly from the Javadocs...

Keyboard mapping taken from the wiki page (for archival purposes):
Answer: There is one thing that I know works. Go to options in the Escape menu, then click controls. It should be somewhere in there. If it is red, then that means something else is also using the F7 key.


What's the difference between Model.id and Model.pk in django?

Question: I saw the django documents use both sometimes? Are they identical? What's the difference and where is the reference? I only see documentation of pk.
BTW, does django reference cover all the methods of its classes?
Comment: DUPLICATE : http://stackoverflow.com/questions/2165865/django-queries-id-vs-pk
Comment: @PriyankPatel I saw that question too, I don't think they are duplicate.
Comment: I'm working through the tutorials now and was confused by this too. For now I'm just going to ignore it and worry about the difference when there is a practical reason to. This comment is just to help me remember not to forget to look into it down the road. They say taking an active part in your learning makes it more effective.
Comment: @dspjm Why are they not duplicate? I think they are.
Answer: pk is the attribute that contains the value of the primary key for the model. id is the name of the field created as a primary key by default if none is explicitly specified.


Bigquery API: Running query with destinationTable does not save results

Question: I'm trying to use Google Apps Script to automate a daily aggregation process. The idea is to run on a few tables from one dataset, and save their results to a table on a second dataset. My user has permissions on both relevant datasets.
My request looks as follows
        var request = {
        "maxResults": 10000,
        "useQueryCache": false,
        "destinationTable": {
              "projectId": "project_name_obfuscated",
              "datasetId": "project_114151_shared",
              "tableId": "test123"
            },
        "writeDisposition": "WRITE_TRUNCATE",
        "createDisposition": "CREATE_IF_NEEDED",
        "allowLargeResults": true,
        "query": "query syntax here"
      };

  var queryResults = BigQuery.Jobs.query(request, "project_name_obfuscated");

(I've obfuscated the name of the projects and the query itself for confidentiality reasons).
The query actually runs fine, however, it's not being saved into the designated project/dataset/table which I've defined.
In the BQ UI I'm seeing something like:
Job ID: project_name_obfuscated:job_NhkQpi110p3i5yoOO7nzXp3tTKY
Start Time: 5:47pm, 20 Oct 2014
End Time: 5:47pm, 20 Oct 2014
Bytes Processed: 0 B
Destination Table: project_name_obfuscated:_138c3340e691065e8db0b55781b5a41c6b4bcd49.anonev_SOiiRC10lfetj000kcj4rmXNc5E

Any ideas what I'm doing wrong?
Answer: You're using arguments which are only available via the Jobs.insert in the Jobs.query method. Jobs.query is intended for quick, synchronous queries, and doesn't support the full range of options available in Jobs.insert, which is the asynchronous version.
Try something like:
var configuration = {
  "query": {
    "useQueryCache": false,
    "destinationTable": {
          "projectId": "project_name_obfuscated",
          "datasetId": "project_114151_shared",
          "tableId": "test123"
        },
    "writeDisposition": "WRITE_TRUNCATE",
    "createDisposition": "CREATE_IF_NEEDED",
    "allowLargeResults": true,
    "query": "query syntax here"
  }
};
var job = {
    "configuration": configuration
};

var jobResult = BigQuery.Jobs.insert(job, "project_name_obfuscated");

var jobId = jobResult.jobReference.jobId;

// The job might not actually be done; wait until it is marked
// complete.
var sleepTimeMs = 500;
while (true) {
    Utilities.sleep(sleepTimeMs);
    sleepTimeMs *= 2;
    queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId, {
      "maxResults": 10000);
    if (!queryResults.jobComplete) {
      break;
    }
}

Comment: Needs a small correction in order to mark as solved - the entire content of the configuration needs to be behind another "query" parameter (e.g. configuration->query->). Otherwise, you get errors from the API.
   var configuration = {
    "query": {
        "useQueryCache": false,
Comment: Thanks. Fixed (looks like your proposed updates were rejected by SO moderators for some reason, but I've applied then anyway).
Comment: I got the following error with the code you wrote:GoogleJsonResponseException: API call to bigquery.jobs.getQueryResults failed with error: Encountered "  ").* "" at line 0, column 0.
Was expecting:
    ")" ...
[Try using standard SQL (https://cloud.google.com/bigquery/docs/reference/standard-sql/enabling-standard-sql)]


How should a GFCI be installed according to the NEC?

Question: I am taking a National Electric Code safety class as part of an electrical maintenance certificate course. On one of my quizzes, it asks me to explain how a GFCI is to be installed and tested. I've carefully searched the NEC and have been unable to find anything about how GFCIs are to be installed. It explains where they are to be installed, but not how. This seems like a dumb question since GFCIs can be used in many applications such as circuit breakers and receptacles. Does anyone know what this is asking or if the NEC has any specifications on how GFCIs are to be installed?
Comment: Any Nation in articular?
Comment: @BrianDrummond: Isn't the NEC US-specific?
Comment: Mostly. It's used in a few places outside the U.S.
Comment: @BrianDrummond United States
Comment: NEC is not US law, it's a "model law" written by a nonprofit organization *with the hopes* that jurisdictions worldwide will adopt it as law.  It has become Code-of-default anywhere 120/240-ish split-phase is used - writing an alternate Code is *expensive* (Chicago, Canada).  Even in 230V-land it is respected, and if a Thailand agency questions your wiring, "I installed to NEC" is a pretty good defense.
Answer: The NEC isn't the right place to look for this stuff
The reason you couldn't find anything that answered this question in the NEC is stated right up front in NEC 90.1(A) (quoting from the 2014 edition, italics mine, italicized text new in 2014):

90.1 Purpose.
(A) Practical Safeguarding. The purpose of this Code is
the practical safeguarding of persons and property from
hazards arising from the use of electricity. This Code is not
intended as a design specification or an instruction manual
for untrained persons.

Instead, you want to look at the installation instructions that the manufacturer provides for a given GFCI device.  This is enshrined in NEC 110.3(B):

(B) Installation and Use. Listed or labeled equipment
shall be installed and used in accordance with any instructions included in the listing or labeling.

However, I'm not sure if that's a sufficient answer for your quiz.  If it's not, most receptacle and deadfront devices do install similarly -- your input conductors terminate on to the LINE-side screws (black/brass is hot and silver is neutral, as usual), while loads downstream of the box can either be fed from the LOAD terminals if they need protection or from pigtails off the LINE terminals if they don't.  Grounding and pigtailing is the same as a standard receptacle otherwise.  Breaker-type GFCIs install like a breaker, but have a pigtail or clip that attaches to the neutral bar, and then an extra lug for the load neutral to land on (if you try to wire the load neutral to the neutral bar, the GFCI won't ever reset as it won't be able to "see" the current returning back from the load).
As to testing? There's one correct answer, and that's to use the TEST button on the device.  This creates a path from load-hot to line-neutral (or vice versa) through a current-limiting resistor that is a "controlled leak" for the GFCI to sense and trip on.
Comment: The quiz does specifically regard the National Electric Code, so in light of your post, the correct answer would probably be "according to the manufacturer's specifications."
Comment: @DanielWolfe -- yeah, that's one possible answer, but I'm not sure what the quiz writer was intending.  Either way, it's not exactly a good quiz question in the context of the quiz in question!
Answer: This is addressed in NEC 110.3:

110.3(B). Listed or labeled equipment shall be installed and used in  accordance with any instructions included with the listing or labeling.

Simply put, you must install a GFCI the way the manufacturer tells you to.


Is Black Hole a Knockback?

Question: Is the spell Black Hole counted as knockback? It would be insane with Strongarm Bracers.
I've googled it and some people say it does, while others say it doesn't, does anyone have an offical statement about that or tested this on his own?
Comment: If you compare the videos for any skills with knockback (e.g. Seismic Slam) and Black Hole, it looks like BH does not have knockback. Enemies are not knocked back.
Comment: At first enemies struck in BH are pulled towards the center of the hole, and after it ends they are 'knocked' out of the black hole, which made me wonder about that.
Answer: According to the majority of the posts of the D3 forums, it DOES count.
This is the best explanation I found: Knockback tends to refer to any effect that moves the target, usually making them airborne. The direction of the movement tends to be irrelevant for it to count as "knockback".
A very good thread about Black Hole and knockback can be found here: http://us.battle.net/d3/en/forum/topic/12373517571
Comment: Addition: per [this thread](http://us.battle.net/d3/en/forum/topic/11913192267), Cyclone Strike *is* a knockback. Since Cyclone Strike pulls monsters in like Black Hole, this also supports Black Hole being a knockback.
Comment: Wow. I need to find those bracers. That plus the Spellsteal black hole...
Comment: Interesting... this has fun implications for the Monk ability [Cyclone Strike](http://us.battle.net/d3/en/class/monk/active/cyclone-strike) as well!
Comment: that opens some awesome build options then (:
Comment: Indeed it does...good luck and happy farming.
Comment: @Werdli Oh yes, the strongarms bracers are awesome for just about every class.  Also they synergize super well with a monk's deadly reach's knockup which also procs it.

Is Black Hole a Knockback?


Assignment expression that sets a dynamically-created enum value

Question: I have the following enumeration:
[Flags]
public enum MyEnum
{
    None = 0,
    Value1 = 1,
    Value2 = 2,
}

This enumeration has been dynamically created using the TypeBuilder so there is no compile-time reference to it as a strongly-typed enumeration.
// The variable enumBuilder is fully created and ready for use.
var code = Expression.Variable(enumBuilder, "code");

I now need to assign MyEnum.Value2 to the variable code.
// The following line is supposed to do this: code = MyEnum.Value2;
var assign = Expression.Assign(code, ?????);

How do I create the right side of the expression that would evaluate to MyEnum.Value2?
Answer: Type enumType = enumBuilder.CreateType();
var assign = Expression.Assign(code, Expression.Constant(2, enumType));


How to simulate polyhedral dice in Minecraft?

Question: A dispenser can simulate dice of up to nine sides by random choice, and there are redstone circuits for simulating six-sided dice. But how do you simulate, say, ten-sided, twelve-sided or twenty-sided dice in Minecraft?
Comment: Hehe, playing Dungeons & Dragons via Minecraft?
Answer: You need to create a counter that resets after n ticks, where n is the number of sides on your dice. You can see an overview of creating a counter on Wikipedia. All you need to do is add extra logic so that when the output matches n, it resets the counter to 0.
Hook up your counter to a fast clock with a switch to stop the clock to simulate rolling the dice. The number rolled will be displayed in binary.
Comment: You could use pigs jumping on plates for some actual randomness, rather than timing.


Firebase: Why is my set (with merge : true) operation removes all other fields in my document?

Question: Assume a document on Firebase Firestore representing a house
{
  id: "1234",
  owner: "John",
  address: "123 Something Ave.",
  residents: [],
}

I have a cloud function that is supposed to add residents to the house.
Also note: the residents field isn't always there from the start. Idea is to add it when the first resident is added.
This is my operation, which is part of a cloud function:
db.collection("houses")
      .doc(house_id)
      .set(
        {
          residents: admin.firestore.FieldValue.arrayUnion({
            uid: context.auth.uid,
            first_name: driverData.first_name,
            last_name: driverData.last_name,
          }),
        },
        { merge: true }
      );

But instead of creating this field with the array an leaving all the other data in the document, the function completely removes all the other data and I am only left with the residents array field.
Why is that?
Comment: That seems unlikely. Are you sure you don't have any other code also modifying the document?
Comment: @FrankvanPuffelen I'm not sure what I've changed as I tried it like 5 times, but it is working now. Will delete this question in a few minutes. Thank you.
Answer: The way I understood the difference:

set with merge will update fields in the document or create it if it doesn't exists

update will update fields but will fail if the document doesn't exist
To update just the residents field, you can use the update() method instead of set() method.
db.collection("houses")
  .doc(house_id)
  .update({
    residents: admin.firestore.FieldValue.arrayUnion({
      uid: context.auth.uid,
      first_name: driverData.first_name,
      last_name: driverData.last_name,
    }),
  });


Construction of locus of agreement of schemes

Question: I'm trying to understand the construction of the locus of agreement of schemes. Multiple references use a certain commutative diagram but I fail to see why it's commutative.
Let $ f,g:X\rightarrow Y$ be two $ S $-scheme morphisms. The locus of agreement of $ f $ and $ g $ is defined to be $V$, the pullback of the diagram $$\require{AMScd}\begin{CD}V@>>>Y\\@VVV@V\Delta VV\\X@>f \times g>>Y\times_SY\end{CD}$$
Let $h:Z\rightarrow X$ be an $ S $-morphism so that $ f\circ h=g\circ h$. Then $ h $ factors uniquely through $ V $.
Why does $ Z $ form a commutative diagram with $ \Delta $ [the diagonal] and $ h $ [unique factorization through the pullback]?
Thanks
Comment: I think you have an error in your diagram: the lower right corner is currently $X\times_S Y$, but should be $Y\times_S Y$.
Comment: @KReiser Right. I corrected that.
Answer: If $h: Z\to X$ is an $S$-morphism so that $f\circ h = g\circ h$, then $f\circ h$ and $g\circ h$ are identical maps from $Z\to Y$. In addition, we have that $(f\times g)\circ h$ and $\Delta \circ (f\circ h) =  \Delta \circ (g\circ h)$ are equal in $Y\times_S Y$. So $h:Z\to X$ and $f\circ h=g\circ h : Z\to Y$ are maps from $Z$ to $X,Y$ such that the composites agree in $Y\times_S Y$. So by the universal property of pullbacks, we have a unique morphism $Z\to V$.


How do I configure Jetty to allow larger forms when used with Spark Framework

Question: How do I configure Jetty options via Spark framework ?
Im getting the problem below when i submit a large form. The solution for Jetty is documented at Form too Large Exception
But Jetty is hidden from me using Spark Framework, how would I configure to resolve this.
    org.eclipse.jetty.http.BadMessageException: 400: Unable to parse form content
        at org.eclipse.jetty.server.Request.getParameters(Request.java:373)
        at org.eclipse.jetty.server.Request.getParameter(Request.java:1016)
        at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:194)
        at spark.Request.queryParams(Request.java:283)
        at spark.http.matching.RequestWrapper.queryParams(RequestWrapper.java:141)
        at com.jthink.songkong.server.callback.ServerEditSongs.startTask(ServerEditSongs.java:45)
        at com.jthink.songkong.server.CmdRemote.lambda$null$62(CmdRemote.java:171)
        at spark.RouteImpl$1.handle(RouteImpl.java:72)
        at spark.http.matching.Routes.execute(Routes.java:61)
        at spark.http.matching.MatcherFilter.doFilter(MatcherFilter.java:130)
        at spark.embeddedserver.jetty.JettyHandler.doHandle(JettyHandler.java:50)
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1568)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
        at org.eclipse.jetty.server.Server.handle(Server.java:564)
        at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:317)
        at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
        at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279)
        at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:110)
        at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124)
        at org.eclipse.jetty.util.thread.Invocable.invokePreferred(Invocable.java:128)
        at org.eclipse.jetty.util.thread.Invocable$InvocableExecutor.invoke(Invocable.java:222)
        at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:294)
        at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:199)
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:673)
        at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:59
1)
        at java.lang.Thread.run(Thread.java:745)
    Caused by: java.lang.IllegalStateException: Form too large: 273433 > 200000
        at org.eclipse.jetty.server.Request.extractFormParameters(Request.java:516)
        at org.eclipse.jetty.server.Request.extractContentParameters(Request.java:454)
        at org.eclipse.jetty.server.Request.getParameters(Request.java:369)
        ... 26 more

Answer: A bit of history:

I looked up a little on the git repo of spark and found that this issue was raised on 3 Aug 2015, here issue 314
Perwendel (the guy maintaining Spark) added the Much wanted label on 11 Oct 2016
Then started working on it on 3 Nov 2016
He merged the Pull Request PR #813 to opens up possibility for any Jetty setting in Spark embedded.

I looked into the modifications added in this PR and I think you might be able to configure something by implementing the JettyServerFactory, if you overwrite the public Server create(...) method, you can return your custom Server:
public class Main {

  public static void main(String ...args) {
    CustomJettyServerFactory customJettyServerFactory = new CustomJettyServerFactory();
    EmbeddedServers.add(
        EmbeddedServers.Identifiers.JETTY,
        new EmbeddedJettyFactory(customJettyServerFactory));
  }
}

class CustomJettyServerFactory implements JettyServerFactory {
  @Override
  public Server create(int maxThreads, int minThreads, int threadTimeoutMillis) {
    Server server = new Server();
    server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", 1000000);
    return server;
  }

  @Override
  public Server create(ThreadPool threadPool) {
    return null;
  }
}

Please have a try and see if you can make this work, I don't have anything setup to try it, but I think this is the correct path to configure your Jetty server.
Comment: Glad it works! :) This allows real deep customisation.
Comment: Thankyou, yes it worked if you use the  server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", 1000000) (Note also extra zero, default is 200,000) (Although getting a different issue now - java.lang.IllegalStateException: Form with too many keys [1001 > 1000]
 at org.eclipse.jetty.util.UrlEncoded.decodeUtf8To(UrlEncoded.java:502)
 )
Comment: FWIW, 2nd problem fixed by adding server.setAttribute("org.eclipse.jetty.server.Request.maxFormKeys", 10000); :)
Answer: That is controlled via a org.eclipse.jetty.server.Server attribute ..
org.eclipse.jetty.server.Request.maxFormContentSize=<int> for max form size in bytes
org.eclipse.jetty.server.Request.maxFormKeys=<int> for max form keys (limit here exists to combat hash key collision DoS techniques).
Use a Server.setAttribute(String name, Object value) call.
Comment: But do I have access to these Jetty classes from Spark Framework ?
Comment: Apparently this was a known issue https://github.com/perwendel/spark/issues/314 and fixed in Spark Framework 2.6, but I cannot find any instruction on how to do it.
Comment: I mean the ability to fully configure Jetty from Spark was added in 2.6
Comment: @PaulTaylor and what version do you have?
Comment: @Bentaye I'm on 2.7.1 but there are no instructions  on how to configure Jetty form Spark


MSVC /FA GCC equivalent

Question: I'm using GCC to compiler and I want to print the full path of the file using __FILE__, but GCC shows only the name of the file. In MSVC is the same, but you can use an argument /FC (Full Path of Source Code File in Diagnostics) and it works. Is there any equivalent to GCC?
int main(int argc, char ** argv)
{
    std::cout << __FILE__ << std::endl;
    return 0;
}

Answer: I couldn't find any equivalent, but I realized that __FILE__ macro expands to the name of the current input file via the path used by the preprocessor to open the file. So it will depend on what is passed to the compiler.
I solved it using CMake as build system. When CMake creates the MakeFile it uses the full path in the variable CMAKE_SOURCE_DIR, this way __FILE__ will print exactly what we expect.

MSVC /FA GCC equivalent


Rails 4.2 Custom Error Page for Sidekiq When Missing ENV

Question: In our app, we have Sidekiq and have modified the sidekiq.rb file to have it require authentication to view the page.
sidekiq.rb
Sidekiq::Web.use(Rack::Auth::Basic) do |user, password|
  [user, password] == [ENV['SIDEKIQ_USER'], ENV['SIDEKIQ_PASSWORD']]
end

We want to have an error page set up for whenever the ENVs above are missing it will let us know specifically that the missing ENVs are the issue.
Answer: Solution 1: check the Sidekiq web code, open its base controller class and write a before action to render an error page when error happens.
Solution 2: write a conditional route, show the error page when error happens
Solution 3: throw errors in sidekiq.rb, so your server wont startup successfully, you will not need an error page anymore. I think the last one is the best, because this is just internal page to be viewed by few people, and probably only you, its better to find the problem as soon as possible.


Jersey 2.14: how to receive and parse multipart mime using custom MessageBodyReader

Question: I am not generally used to programming in Java, and this is my first post so I ask for a bit of patience.  I am having trouble putting the pieces together for a standalone client that will request via GET and then receive, multipart messages from a server.  I should note that I have no way of changing the format of these messages.
The received protocol header looks something like this:
HTTP/1.1 200 OK
Content-type: multipart/custom; boundary=custom-17940605525230162027
X-Custom-Domain-Name: my-custom-domain
Server: Myserver
Content-Length: 71576
Connection: Keep-Alive
Keep-Alive: timeout=5

The received body has the custom boundary element indicated above and is formatted as follows (content mostly elided):
--custom-17940605525230162027
X-Custom-Designation: ack
Content-Type: application/xml
Content-Length: 291

<cust:ack>
A bunch of xml...
</cust:ack>

--custom-17940605525230162027
X-Custom-Designation: update
Content-Type: application/xml
Content-Length: 1101

<cust:update>
A bunch more xml...
</cust:update>

--custom-17940605525230162027
X-Custom-Designation: document
Content-Type: application/xml
Content-Length: 6259

<?xml version="1.0" encoding="UTF-8"?>
Lots more xml...

--custom-17940605525230162027
...

The following code will correctly grab the above content from the server (please ignore extraneous libraries for the moment):
package com.mycompany.multipart.test;

import java.io.IOException;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.glassfish.jersey.media.multipart.MultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;

public class ClientMultipartTest {

    public static void main(String[] args) {

        Client client = ClientBuilder.newClient();
        HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("user1", "password1");
        WebTarget webTarget = client.target("http://theserver:80/test.xqy")
                .queryParam("domain", "12345")
                .queryParam("target", "67890");
        webTarget.register(feature);
        Invocation.Builder invocationBuilder = webTarget.request("multipart/mixed");
        Response response = invocationBuilder.get();
        System.out.println(response.getStatus());
        System.out.println(response.readEntity(String.class));
    }
}

But I can't quite figure out how to actually pull out the entity as a multipart object.  When I try the following code (starting right after webTarget.register()):
MultiPart response = webTarget.request("multipart/mixed").get(MultiPart.class);

I get the following exception:
Dec 22, 2014 10:56:15 PM org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor aroundReadFrom
SEVERE: MessageBodyReader not found for media type=multipart/custom; boundary=custom-17940605525230162027, type=class org.glassfish.jersey.media.multipart.MultiPart, genericType=class org.glassfish.jersey.media.multipart.MultiPart.
Exception in thread "main" org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=multipart/custom; boundary=custom-17940605525230162027, type=class org.glassfish.jersey.media.multipart.MultiPart, genericType=class org.glassfish.jersey.media.multipart.MultiPart.
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:225)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:149)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1124)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:851)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:783)
    at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:326)
    at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:761)
    at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:90)
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:671)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:424)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:667)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:396)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:296)
    at com.mycompany.multipart.test.ClientMultipartTest.main(ClientMultipartTest.java:29)

I think I understand that I need to create and "register" a class that implements a custom MessageBodyReader interface (as seen here).  That example is confusing to me however.
Would someone be able to guide me so that I can get to the point of having a MultiPart object whose body parts can be parsed?  I also ultimately need to be able to construct a multipart response consisting of only the <cust:ack> elements and post it back to the server.
Many thanks in advance for any help that can be rendered!
Comment: @peeskillet I did not do that in the code above, and I'm pretty sure I will need to once I get past this exception.  But I'm also pretty sure that it's not the cause of this exception.
Comment: I have registered the MultiPartFeature and still get the same exception.  I have even tried to implement my own MessageBodyReader class that @consumes multipart/custom and still get the same exception.  I'm completely stumped.
Answer: Better late than ever. What you're looking for is this:
MultiPart content = response.readEntity(MultiPart.class);

This will cause the Jersey framework to parse out the content and give you a MultiPart object through which you can iterate over the parts.


Error with Ajax-Enabled WCF Service (JSON) when consuming from jquery .ajax()

Question: Unfortunately it only hits the error condition when calling .ajax() and textStatus (2nd param) only says "error".  I've read through several examples and other questions on stackoverflow but must be missing something.  Thanks in advance for any help.
WCF Service:
[ServiceContract(Namespace = "http://localhost/")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Items
{
    [OperationContract]
    [WebGet]
    public string HelloWorld()
    {
        return "Hello World.";
    }
}

WCF Web.config
Pertinent parts only...
Services:
<services>
  <service name="OService.ReadServices.Items">
    <endpoint address="soap" binding="basicHttpBinding" contract="OService.ReadServices.Items"/>
    <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="OService.ReadServices.Items"/>
  </service>
</services>

Behaviors:
<endpointBehaviors>
    <behavior name="jsonBehavior">
      <enableWebScript />
    </behavior>
  </endpointBehaviors>

Jquery
$(document).ready(function () {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "http://localhost/OService/ReadServices/Items.svc/json/HelloWorld",
        data: "{}",
        dataType: "json",
        success: function (msg) {
            alert("success: " + msg.d);
        },
        error: function (xhr, textStatus, errorThrown) {
            alert("error: " + textStatus + " - " + errorThrown + " - " + xhr);
        }
    });
});

Comment: Check response in FireBug (Firefox addmin)
Answer: This reply is kind of late, but you defined your web method as a [WebGet] but call it as a POST request in your Jquery Ajax method. Replace the [WebGet] with something like:
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json)].
Comment: First, +1 for replying after so long... unfortunately, I am no longer using this type of code as I've moved on to using WebApi, so I can't test the original issue, but I agree with your reply it seems as though that would fix it - I don't think I even realized I had POST in the javascript call at the time.


Easiest to read fonts

Question: Has there been studies to determine what fonts make it easiest to read? I'm interested in the font type, but also size and color. For example, is dark gray better than pitch black?
Also of interest is eye strain. Which fonts are the softest to our eyes?
Comment: Arial is actually quite useful on screen. It typically renders better in a browser at text sizes than Helvetica does.
Comment: @BartGijssens Yes, it's true. Windows is designed to align glyph strokes to the pixel grid (even if it means slightly manipulating the design). Mac OS X by default tries to retain the letterforms the font designer produced (only mapping to the pixel grid if the designer added bitmaps or explicit screen hinting), although [Panther did improve things a little](http://daringfireball.net/2003/11/panther_text_rendering). [Here's an explanation of the difference](http://www.joelonsoftware.com/items/2007/06/12.html). If this stuff interests you check out [Raster Tragedy](http://www.rastertragedy.com)
Comment: Not an answer at all but I must say it: don't ever use Arial.
Comment: @BartGijssens Could you elaborate? Especially considering the (well-designed) website you're posting this comment on uses Arial :)
Comment: Note that the anti-aliasing engine used to display the font (eg. ClearType) can affect readability considerably at certain sizes, so keep that in mind when creating UIs that are used in cross-platform situations like websites.
Comment: @Rahul: Is that true? If I'm using Google Chrome on Mac, am I seeing Arial on my screen? In many cases Arial makes some words hard to read. Thing like "Illegal" or "determine" are hard to read. I never use Arial on windows applciation's UI, always give priority to Tahoma, or Calibri.
Comment: Read about Guy Kawasaki's 10/20/30 rule.
Answer: For size and colour, the other answers have covered them well.
For font choice, I can't recall where the research was from, but I read a study that showed reading large blocks of text was faster with serif fonts.  But there was no real difference between serif and sans serif fonts for shorter pieces of text (like labels or headlines).
This explains why almost all novels and newspapers are printed with a serif font.
For a specific font, my vote would be for Palatino for serif and Helvetica for sans serif (purely personal opinion though).
Comment: Could it have been [Typography for lawyers](http://www.typographyforlawyers.com/?p=587) Quote: "Sans serif fonts look less traditional than serif fonts and most people — me included — find them tiring to read in long documents. (That's why so few books, newspapers and magazines use sans serif fonts for body text.)" - or maybe it was [Alex Poole](http://alexpoole.info/which-are-more-legible-serif-or-sans-serif-typefaces) discussing serif vs sans-serif
Comment: I remember reading that for printed text as well. Would you happen to know whether there is any difference in "easyness to read" when the text is on a different medium such as a CRT and nowadays LCD screens?
Comment: @MarjanVenema: I've read a different study on that, and excluding poor CRT's with flicker which are obviously bad, it was more the contrast that made the difference.  Too high or too low caused eye strain.
Comment: As I recorded in [this UX.SE answer on the topic](http://ux.stackexchange.com/a/23083/11687), there hasn't really been any **reliable** evidence that serif text is more readable in any form. It is, most definitely, the conventional wisdom, however, which means more serif typefaces are likely to be designed with body copy in mind than sans serif.
Answer: Regarding font size: 9 point to 14 point are preferred sizes - according to this research / this table:
http://webstyleguide.com/wsg3/8-typography/4a-type-size-legibility.html
Answer: There's a fair amount of research. All of it less than scientifically sound and highly contradictory and completely dependent on so many factors that it's usually out of context.
That said, there are basic rules of good typography that help lead you to a more readable decision:

low resolution screens and smaller type can benefit from a larger x-height.
careful consideration of line lengths and leading can have an impact on making it more readable
contrast is good. But too much may not be. (ie, on screen, gray text on white is better than pure black on white...on paper, black ink on off-white paper is better than black ink on pure white)
Answer: Getting the contrast correct between font and background is important. Too little contrast and obviously you cant read the text. But also too much contrast can strain the eyes. I believe dyslexic people in particular can struggle with black text on a white background.
WCAG provide min Colour contrast guidelines, but I remember HP "used" to provide a similar tool for checking max colour contrast (Although I can't find it anymore so this may be old news)
Regarding font types: It depends on the the scenario. For web fonts sans serif fonts are generally better. I think fonts such as Verdana were developed especially for the web. As to studies regarding which font is the "best" I'm not so sure.
Good resource on WebAim: http://webaim.org/techniques/fonts/
And I just article comparing fonts for web: http://www.design-by-izo.com/2011/10/18/what-should-i-look-for-in-a-ui-typeface/
Answer: It depends on:

media (screen, paper)
contrast (font/background color/texture)
font size (a font can be too large or too small for a purpose)
eyes of the reader (no font size will make it easier for blind people to read - braille does)
text length (some fonts need more space, so the text gets longer)
available paragraph width (can cause bad word wrap with lots of ugly gaps)
target audience (Arial is the wrong choice for writing programs; programmers need to be able to distinguish between O and 0 and between I, l and 1. Test word for programmers: O01Illegal - Oh, zero, one, capital i, lowercase L).
Answer: Adobe have been conducting research in this field, here's a recent update: https://blog.adobe.com/en/publish/2022/05/10/the-need-to-personalize-fonts-for-each-individual-reader

Easiest to read fonts


How to display details of whats going on inside of a Windows Form with C#

Question: OK,
So i've looked at alof of posts to try and figure out how to do this but i haven't got it.
all i want to do is display details of whats happening inside of a form. for instance, you know how when you install a program and it says:
copying blah blah blah.dll..
copying blah blah blah2.dll..
copying blah blah blah3.dll..
copying blah blah blah4.dll..
copying blah blah blah5.dll..
etc etc.
I want to display results of a query that i'm doing
Am i making any sense?
Comment: Are you trying to update the contents of a form, while something is occuring, and you're not seeing the changes?
Comment: not really, please give more details... show some source code... what have you tried ? what is not working ? any errors ?
Comment: add a textbox and then any event you want to display is happening add a line textbox.text += "another event" or some such..
Comment: SOrry for taking so long to get back. Anyway, i think Prescott knows what i'm trying to do. whenever i have some code be executed i want thre result of the query to display inside the same window MUCH LIKE how a list of files being copied during an installation is shown.
Comment: I'd like to mark your comment as the answer @Prescott but it won't seem to let me. thats what i was looking for
Answer: add a textbox and then any event you want to display is happening add a line textbox.text += "another event" or some such..


Installed Tesla gen 3 home charger with 60amp breaker and car pulling 48 amps. The conduit from charger to power panel is approx 4 ft

Question: The conduit gets so hot you can't keep touching it.  The certified electrician used #6 THHN.  should #4 wire be used?
Comment: Type of conduit, metal or plastic?   #6 should be okay for 48 amps, but if conduit is that hot wondering if something else is the problem.  Bad connection or bad insulation.  The certified electrician should be called back to fix it.
Comment: @crip659 asked the type of conduit, which does matter. But also the **size** of the conduit. And is this #6 copper or aluminum? It should be copper because (a) for aluminum it needs to be #4 and (b) because AFAIK, Tesla chargers can't connect to aluminum. But sounds like bad connection.
Comment: Conduit heats up only during charging
Comment: @Ruskes What information did I state that is "bad" on Tesla charger? If it is about aluminum: From the [installation manual](https://www.tesla.com/support/charging/wall-connector/installing): "COPPER WIRE TERMINATIONS ONLY for landing in Wall Connector wirebox terminals. Conductors can be stranded or solid."
Comment: @Ruskes I fail to see what your complaint is about my statement. I said "must use copper to Tesla wall charger" - Harper's answer confirms that. I also said "aluminum needs to be #4" - Harper's answer confirms that. And to use #4 aluminum + polaris connectors to switch to copper for all of 4 feet - that makes no sense whatsoever (and in any case, that can't possibly be the case here because OP stated #6, just didn't say copper or aluminum". So please **explain** what my "bad" actually is.
Comment: There's at least one other DIY.SE question about current flowing through ground from their Tesla charger.  At a skim, I do not yet see a solution mentioned on that post: https://diy.stackexchange.com/questions/274254/
Comment: Conduit is metal and wire is copper.  Electrician pulled new #6THHN copper thru conduit and still heats up.  I am thinking the ambient temp in garage is contributing to heat.
Answer: EV charging is the most demanding electrical load in your home.  It is running the hardware at its  absolute thermal red-line limit for a continuous load.  The 6 AWG THHN is making full use of its 75°C (167°F) thermal limit in this application.
That is to say, the 60°C-rated "Romex" NM cable is not legal for 60A (at 6 AWG) because its insulation is not rated for a rise above 60°C (140°F or just into scalding).   (Implied: this wire running around 60°C is to be expected). Did the electrician do anything WRONG? Well no, there's a gold-standard for right and wrong, NEC, and I see no defect here unless the wire is not actually 6 AWG copper.
In fact, NEC is alright with with that same conduit accommodating three such charging circuits: see 310.15(B)(3)(a).
The only exception I would see is if you have high ambient temperature conditions - the standard derates assume ambient temperature of 30°C.  Phoenix attic, sunny side of dark painted house, etc. might warrant further thermal derates.
If you really, really, really want to "fix" it, then run 1/0 aluminum to a 60A breakered disconnect (reducing heating by 60% along that run) then then 4 AWG copper the last 2 feet to the Wall Connector (only 40% heat reduction, but only 2 feet).  I spec #4 because it's the largest that will fit on a Tesla Wall Connector v3.  I spec 1/0 aluminum because it's the largest that will fit on standard large-frame breakers, and you may have to use a 100A breaker to get there (hence the 60A disconnect).
Not your grandfather's golf cart charger
When they designed this generation of EVs, SAE and Tesla recognized that "needing to get an electrical service upgrade to charge at home" would be a huge barrier for adoption of EVs. So into the charging standard they designed tech to make service upgrades unnecessary: the car can draw any amount of current based on a capacity signal from the wall unit (which is a GFCI switch, not a charger).
The wall unit can be set to transmit one ampacity always, or vary it "on the fly" as other appliances turn on.
Home charging is rife with misconceptions. Like the "1982 golf cart" logic that if it's rated for 48A charging, it must be provisioned 48A (ignoring the abovementioned tech).  Others greedily want the Fastest Charge Possible (tm).
The charging speed you need
Thermal heating is the square of amps.  Double amps, quadruple heat and losses.
Technology Connections has a fantastic video on home EV charging, and let me cue it up to the "level 2 charging speed" conversation.  Feel free to roll back for more stuff.
You only need to replace the miles you drove that day, + a 50% margin for recovery from unusual days.
Home charging can be like Uncle Ralph who owns a gas station, every night bringing over a 7 gallon can of gas and pouring as much as will fit into your tank. You leave full most days except after travel.  And after travel, you'd be tempted to "game it" by arriving home empty and letting Ralph catch you back up over the next few days, wouldn't you?
But like the video says, "The fastest charger is expensive, and may come with more headaches than you bargained for". And here you are with one of the more minor headaches we see.
Cool your jets
Here we can borrow from Elon Musk via Wintergatan and their Magical Marble Machine (yes that thing works, not well) in less than 2 minutes of this video.
So I think the 48A was called out by a brilliant person, yet, I'm betting it's wild overkill for your home charging needs.  So I would propose to simply turn it down to 24A (half).  And then see where that puts you.   That's still charging over 200 miles a night on a Tesla.
My rule of thumb is: if a reduced charge rate actually, in the real world, forces you to seek public charging during ordinary in-town activities (can't count travel) then the charge rate is too low.  But if it does not, it is not too low.
That'll take care of the heating problem, and also, that heating isn't free, so you're saving some coin too.
And honestly for the vast majority of people, 16A would satisfy their needs.  On the more efficient Teslas, possibly even 12A.
Now, how do you turn it down?  Since your installation is actually safe and legal to 60A, you do not need to use the Wall Connector commissioning procedure to make this adjustment. You can simply use the Tesla's console inside the car.
(the setting in the Commissioning procedure is for when the cable has been downsized, e.g. #12 Romex for a 16A installation, and the EVSE must not exceed 16A.  UL requires that setting be inaccessible to the end user.)
Comment: Reducing the power draw from the EVSE just sounds like it is papering over the issue.  The conduit should not be getting hot because any wiring should be properly sized and free from damage to not cause heating.  There's almost certainly an issue with the install or there's been some kind of damage.  Given that this is a 60 amp circuit then this is might be outside of DIY territory and an electrician needs to be called.  I'm pretty comfortable with anything up to 30 or 40 amps but past experience with 50 amps tells me I should consider an electrician with anything that big.
Comment: @MacGuffin If OP's claim of 6 AWG is correct, there's no code problem here - so it's an aesthetic problem that rates an aesthetic solution. "The conduit should not be getting hot because any wiring should be properly sized and free from damage to **not cause heating**." I'm gonna need a Code citation on that one. Look at 310.14 et.seq. (Or 310.15 in the pre-2020 NEC) and there's a great deal about thermal ampacity ratings.  Crunch the numbers but it looks right to me, in fact it appears 2 more similar circuits could share the same pipe per 310.15(C)(1) former 310.15(B)(3)(a).
Comment: I'm not claiming there's a code violation.  I'm pointing out that if there's a concern on the wires getting too hot then there could have been some damage to the wires.  Perhaps there was damage during the install, or in the shipping of parts to the electrician.  If the heat coming off the conduit is normal then an electrician can verify that.  If this is not normal then the electrician that did the install should take on some responsibility for repairing the problem as there was damage not seen by the electrician in final inspection before calling it done.
Comment: @MacGuffin But a) in my experience I've never heard of any kind of wire damage which would cause that (other than the "Made in China" kind)... and b) heat over 60C is *within spec*, so there is no evidence of a problem NEC cares about.  Remember heat is proportional to amps **squared**. OP wants to run the wires within 7.7% of thermal limit, they're gonna get heat within 14.8% of thermal limit.  If they didn't, that would be alarming because it would mean the laws of physics have been suspended!!!
Comment: I don't know if there is evidence of a problem, only that the original concern is that the conduit is hotter than expected.  To know if this is in spec or not would require some measurement.  An electrician would have the tools to take that measurement, the homeowner might not.  If the homeowner has the right equipment and knowledge to do a proper DIY inspection then that's great.  If not then the professionals need to be called.  If there is a problem then the pros might still need to be called since the EVSE setup, or some other issue, is outside of DIY territory.
Answer: If I saw that then I'd suspect a ground fault issue.
The current flow on the wires from the breaker box to the EVSE should be balanced, and that means the net magnetic field around the wires is cancelled out.  If there's a significant imbalance on the current flowing on the wires, as could happen if there's current flowing to ground somewhere outside the conduit, then there could be a magnetic field inducing a current on the steel conduit.  Steel isn't a great conductor, it's good but not great, so it is more prone to heating with current flowing through it.  This is steel, correct?  Some kind of metal?
The ground fault may be simpler than some induced voltage, the ground fault is flowing back to the breaker box through the steel conduit and heating it up.  Since this is heat that you feel and not an electrical shock then the voltage is close enough to ground potential that you feel only the heat.
If not a ground fault, and not undersized wiring (which a certified electrician is unlikely to do), then perhaps it is damaged wiring.  An incomplete break in some wire could produce heat that is conducted (thermal conduction, not electrical) to the steel would be felt on the outside surface.  This heating should be fairly local to that break, as in one spot on the conduit is hot but the rest is relatively cool.  That is likely a sign of a bigger failure later.  The wire could have been damaged as it was pulled through the conduit and left undetected in any testing done afterward.
One last thing in my "stream of consciousness" answer (I'm typing in possible problems as they pop in my head) is a very benign one.  The sun is heating up the conduit.  Is the conduit exposed to sunlight?
Whatever the cause I'd avoid touching it again until checked out.  Do you have any kind of heat sensor that doesn't require touching it?  My brother has an infrared thermometer that can check body temperature and such by just aiming it at the spot, it has a laser pointer or something to indicate where it is looking.  The point of light isn't exactly where it is looking as the light would influence the result so account for that if using such a device to monitor the conduit heating.  The electrician likely has one and will use it if there's a repeat visit to check on this.
I'd avoid touching the conduit again.  Whether this is a safety hazard that requires turning off the circuit at the breaker is something of a judgement call in my opinion.  And my opinion is worth precisely what you paid for it.  That's the thoughts from a sometimes electrical engineer and amateur electrician.
Comment: The EVSE itself is a GFCI, and will not permit an imbalance load to go into the car. Since the hardwired EVSE is a GFCI (receptacle) there is no need for a GFCI breaker.
Comment: I didn't down vote but it's not a ground fault. Code requires a GFI breaker which would trip in that event. EV chargers don't always play nice with GFI breakers because they can have their own ground detection system which will cause the GFI breaker to trip so people do swap them out for a non-GFI breaker. It really sounds like undersized wiring. Most likely aluminium instead of copper.
Comment: Could someone explain their reasons for the down votes?  I'd like to know how I could improve my answer.
Comment: @JD74 I'm not an expert on electrical code but I recall another answer on DIY.SE that pointed out EVSE do not require a GFCI breaker, and the answer spelled out how this meets code.  Also, it is possible the GFCI protection failed.  Even if the GFCI works properly that doesn't mean there isn't a ground fault that is somehow not detected by the breaker, could be some error in installation that prevents the protection from working.  I agree that a ground fault is unlikely but it is also the most probable explanation.  Undersized wire to the point of heating the conduit seems unlikely.
Comment: A *properly functioning* GFCI will not permit an unbalanced load into the car.  Given the description there's a high probability that something is broken somewhere.  Maybe the heat coming off is normal, it's just in the head that this is "too hot".  The electrician should have some measure of liability here and want to make it right, give them a call and see what they say.


How to add an user element to users collection

Question: I have users and venues.
in table user_venue I store multiple connections (manyToMany)
$rUsers = \DB::table('user_venue')->where('venue_id',$user->id)->get();

$resUsers = collect();

foreach ($rUsers as $key => $i) {
    $id = $i->user_id;
    $u = User::findOrFail($id);
    $resUsers->push($u);
}

As you can see I want to store user model into collection $resUser but its return me error page and don't load view...
WHy?
Comment: Can you post the fully code and error.
Answer: When you are $u->push($resUsers) you are attempting to push into a single User record/instance. I believe you would like to do the following instead:
$resUsers->push($u);

This will push the single User record into the $resUsers collection.
Comment: yes, thanks. Just then I got an error - don't show my view.
Answer: If you have a many-to-many relationship and want to load the Users linked with a given Venue, why don't you use a relationship? This is more efficient because you are hitting the database just once as opposed as your actual strategy.
# Venue.php

public function users()
{
    return $this->belongsToMany(User::class);
}

Then in your controller:
# VenueController.php

public function myFunction(Request $request)
{
    $venue = Venue::find('your-venue-id'); // getting a venue
    $users = $venue->users; // <-----

    return view('users')->with('users', $users);
}

In the above code the $users variable is an instance of Collection, this hold a collection of User models that match the query that, as far as I know, is your desired output.


Ionic how to fire a function just before app is closed?

Question: I'm using ionic and I would like to run a function to  clear my localstorage once a user triggers an event to close the app.
Does ionic have a built in on app close function? Something like
<code>$ionicPlatform.close(function() {
   // code to clear localstorage
})
</code>
Answer: Can you just clear on suspend of the app and reload on resume?


Getting cpu name eg. QJZG, SR2HG etc. using linux terminal

Question: How to get the name of CPU using linux terminal, but not the name of a style i3-6100, but the name of a style SR2HG etc.? I mean the name that is typed on a cpu case and has capital letters and numbers.
EDIT
I tried lshw command but not succeed
Comment: I'd suggest looking at the information that's available to the OS level at all -- look through `lshw` and similar. Once you know the information's available, if you hit a narrow, specific problem with bash itself or another programming-specific language or tool while trying to extract it, come back here and ask about that problem.
Comment: (Stack Overflow is specifically focused on narrow, specific problems with programming languages and tools; if your problem is "I don't know if any UNIX tool can access this specific information", you might want our sister site [unix.se] instead; they permit questions about non-programming-specific tools, which when our rules are strictly interpreted we don't).
Comment: @CharlesDuffy There are actually such questions on SO, but about ordinary cpu name, so u may be wrong.
Comment: Rules change over time (and, to be sure, are inconsistently enforced); in general, they're considerable more strict today than they were, say, a decade ago. If you want to know what the rules are right now, the canonical sources are [meta] and the Help Center, _not_ other knowledge base contents.
Comment: ...if we allowed precedent to control, it would be a swift race to the bottom: anything that was ever allowed (even by mistake, or because a questionable question got an excellent answer -- which is likely to save you here, since moderation guidelines cut against doing anything that removes good content, all else being equal) would be allowed forever.
Answer: First some terminology:

QJZG, SR2HG and the like are called "Sample Specification Numbers" or "S-Spec numbers" or simply "SSpecs".

i3-6100 and the like are "model numbers"

A0, B1 and the like are "stepping" codes

The reason that lshw won't give you S-Spec numbers is that they are not readable electronically from the CPU chip.  What is actually readable are numeric codes that correspond to the model number and stepping.  In addition, the chip reports a "product" string that describes the chip ... as show in your lshw screen capture.
There is another Linux utility called lscpu that will also display the numeric codes for the model number and stepping, and other information.  For example:
$ lscpu
Architecture:        x86_64
CPU op-mode(s):      32-bit, 64-bit
Byte Order:          Little Endian
CPU(s):              4
On-line CPU(s) list: 0-3
Thread(s) per core:  2
Core(s) per socket:  2
Socket(s):           1
NUMA node(s):        1
Vendor ID:           GenuineIntel
CPU family:          6
Model:               142
Model name:          Intel(R) Core(TM) i3-8145U CPU @ 2.10GHz
Stepping:            11
CPU MHz:             800.034
CPU max MHz:         3900.0000
CPU min MHz:         400.0000
BogoMIPS:            4599.93
Virtualisation:      VT-x
L1d cache:           32K
L1i cache:           32K
L2 cache:            256K
L3 cache:            4096K
NUMA node0 CPU(s):   0-3
Flags:               fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca
                     cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht
                     tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art
                     arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc
                     cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx
                     est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2
                     x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c
                     rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb
                     invpcid_single ssbd ibrs ibpb stibp tpr_shadow vnmi
                     flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1
                     avx2 smep bmi2 erms invpcid mpx rdseed adx smap
                     clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm
                     ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp
                     md_clear flush_l1d arch_capabilities

However, neither lshw or lscpu or (AFAIK) any other standard Linux utility is able to map the model and stepping numeric codes to their conventional textual forms.
And it is generally impossible to map a model and stepping to an S-Spec number.
Why?
Because the mapping is not unique.  There are usually at least two S-Spec numbers for any model + stepping.  One for pre-production samples and another for the production chips.
Even the Intel Support Site says that the only reliable way to determine the S-Spec of a chip is to look at what is printed on the chip itself.


How do I go back to playing the main game after having started the Epilogue/Origin?

Question: There's a couple of Angelics that I left for later but now I can't go back to try to perfect them.
Answer: The "Origin" is the main game. The "Epilogue" is additional levels beyond the 'normal' levels--beyond the credits rolling. You can switch between Origin and Epilogue by tapping/clicking the word Origin or Epilogue as shown below.
Epilogue with a 'link' to Origin

Origin with a 'link' to Epilogue


AWS Lambda: Unable to access SQS Queue from a Lambda function with VPC access

Question: I have a Lambda function that needs to read messages from an SQS queue using it's URL. Then it needs to insert that data to Cassandra running on a server inside a VPC.
I am able to access the Cassandra server from my Lambda function, using it's private IP and configuring the security groups correctly.
However, I am not able to read messages from the SQS Queue. When I change the configuration of Lambda function to No VPC, then I am able to read the messages from the SQS Queue. However, with VPC settings, it just times out.
How can I overcome this ? I have checked the security group of my Lambda function has full outbound access to all IP addresses.
Answer: At the end of 2018, AWS announced support for SQS endpoints which provide

connectivity to Amazon SQS without requiring an internet gateway, network address translation (NAT) instance, or VPN connection.

There is a tutorial for Sending a Message to an Amazon SQS Queue from Amazon Virtual Private Cloud
See also the SQS VPC Endpoints Documentation for more information.
Its important to note that if you want to access SQS within the Lambda VPC there are a couple other things you need to do:

Make sure to specify the SQS region in your code.  For example, I had to set my endpoint_url to "https://sqs.us-west-2.amazonaws.com"
Make sure that you have attached a "wide open" security group to the SQS VPC Interface, otherwise SQS will not work.
Make sure that your subnets in your Lambda VPC match what you have set up for your SQS VPC Interface.
Comment: Can this be leveraged to have SQS trigger a Lambda function residing inside a VPC as well?
Comment: Would love to know if anybody got this working from inside a nodejs handler (meaning using the SQS JS SDK sendMessage method). I can't find anywhere that documents support for the endpoint-url parameter that is described in the CLI example in the tutorial here. In fact the SQS API doesn't even describe it.

https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-sending-messages-from-vpc.html#sqs-vpc-tutorial-publish
Comment: `Make sure that you have attached a "wide open" security group to the SQS VPC Interface, otherwise SQS will not work.`
If you attach a wide open outbound security group policy, then you dont need a VPC end point with SQS service. You Lambda can directly invoke publicly available SQS endpoint directly.
Comment: @RajeevAtmakuri, yes. I used it for that and it worked as expected. Make sure to follow the setup guide and add endpoints for any other services you may be using in the function.
Comment: Never mind. Apparently you don't need that param at all from the JS. It "just works". :)
Comment: Thank you, worked Step 4 for me....Step 4: Create an Amazon VPC endpoint for Amazon SQS - https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-sending-messages-from-vpc.html
Answer: Some services (e.g. S3) are offering VPC endpoints to solve this particular problem but SQS is not one of them.  I think the only real solution to this problem is to run a NAT inside your VPC so the network traffic from the Lambda function can be routed to the outside world.
Comment: Am I the only one that reads this kind of "just create a NAT and edit your routing tables and setup your VPC endpoints and ..." and thinks it's too much? I'm pretty sure if AWS offered peanut butter and jelly sandwiches, it would require setting a permission policy on the peanut butter jar and creating special separate subnets for each slice of bread to reside in.
Comment: This answer is no longer correct.  AWS offers VPC endpoints for SQS.
Comment: I tried adding an entry to the route table for destination `0.0.0.0/0` with the target as the id of the newly created NAT gateway. However, there was already an entry for Internet gateway with the same destination. Is it safe to replace that ?
Comment: Ok I think it does not work that way. Once I replaced the entry, I could no longer SSH to my instance. How to go about that ?
Comment: @Jwan622 no. You can add services like Lambda, EC2 and RDS into your own VPC, but not SQS nor S3. Usually SQS and S3 would require your EC2 or Lambda to have internet access so you can reach them, which can be tricky. A VPC Endpoint allows AWS Services (EC2, Lambda) in a VPC to access other AWS Services like SQS without leaving AWS Network, thus not requiring internet access.
Comment: I have no clue how to do that. could you point me in the right direction ?
Comment: It has gotten easier.  AWS now has a managed NAT service.  Here's a blog post describing it: https://aws.amazon.com/blogs/aws/new-managed-nat-network-address-translation-gateway-for-aws/
Comment: What is a VPC endpoint for SQS? What is the heart of the problem here... is SQS not in the VPC?
Answer: I ran into the same kind of problem when I was running lambda function with access to elasticache on the VPC. While the function was configured to run in the VPC, I wasnt able to talk to any other service (specifically codedeploy for me).
As @garnaat pointed out NAT seems to be the only way to go about solving this problem for services without VPC endpoints.
And like you pointed out, I also ran into the same trouble where I could'nt SSH into the machine(s) once I replaced the entry with the IGW in the route table. Seems like detaching the IGW starves the VPC of either the incoming traffic (mostly) or the outgoing traffic from or to the internet respectively. So here's what I did and it worked for me:
Create a new Subnet within the VPC
Now, when lambda runs, make sure lambda operates from this subnet.
You can do this by using aws-cli like so:

 aws lambda update-function-configuration --function-name your-function-name --vpc-config SubnetIds="subnet-id-of-created-subnet",SecurityGroupIds="sg-1","sg-2"

Make sure you add all the security groups whose inbound and outbound traffic rules apply for your lambda function.
Next, go to Route Tables in the VPC console and create a new route table.

Here is where you add the NAT gateway to the target.
finally go to the Subnet Associations tab in the new route table and add the newly created subnet there.
Thats all this should get it working . Mind you, please treat this as only a workaround. I haven't done much digging and I have a very limited idea on how things get resolved internally while doing this. This might not be an ideal solution.
The ideal solution seems to be to design the VPC before hand. Use subnets to isolate resources/instances that need internet access and that dont(private and public subnets) and place appropriate gateways where needed.( so that you may not have to create a seperate subnet for this purpose later). Thanks
Answer: I was unable to get either of the other two answers to this question to work. Perhaps this is due to one or more mistakes on my part. Regardless, I did find a workaround that I wanted to share, in case I'm not alone with this problem.
Solution: I created two Lambda functions. The first Lambda function runs inside my VPC and performs the desired work (in mandeep_m91's case, that's a data insertion to Cassandra; in my case is was accessing an RDS instance). The second Lambda function lives outside the VPC, so I could hook it up to the SQS queue. I then had the second Lambda function call the first, using the information found this this StackOverflow Q&A answer. Note, the linked question has both node.js and Python examples in the answers.
This will effectively double the cost of making a function call, since each call results in two function executions. However, for my situation, the volume is so low it won't make a real difference.
Answer: To clarify a point above about a "wide open" security group, the group set on the endpoint needs to allow inbound access to SQS from your lambda function.
I created a security group for my endpoint that only opened 443 to my lambda's security group.


Path-connectedness of $\mathbb{C}\setminus \lbrace z_1, ..., z_n \rbrace$

Question: Today I was thinking about the fact that $\mathbb{C} \setminus \lbrace z_1, ..., z_n \rbrace$ is path-connected. I know how to prove that, just constructing a path joining two points, but I was wondering : is there a way to prove this using the fact that the image of a path-connected space by a continuous function is path-connected ?
More precisely, it is possible prove that $\mathbb{C} \setminus \lbrace z_1, ..., z_n \rbrace$ is path-connected by defining explicitely a surjective continuous function $f : X \rightarrow  \mathbb{C} \setminus \lbrace z_1, ..., z_n \rbrace$, where $X$ is a path-connected topological space ?
For the case $n=1$, using $\exp : \mathbb{C} \rightarrow \mathbb{C}^*$ works, but I was not able to generalize that in the case you remove more than one point.
Thanks for your help !
Comment: @PaulFrost OP is looking for a non-circular proof that $\mathbb{C} \setminus \{z_1, \dots, z_n\}$ is path-connected, so the identity map would not be a good answer. I agree that the question is really "is there an easily-explicitly-describable continuous surjection $X \to \mathbb{C} \setminus \{z_1, \dots, z_n\}$ where $X$ is easily seen to be path connected?" Of course this is subjective, but I think it's a perfectly reasonable question to ask.
Comment: You may note it's not my question :) But imo OP did make this reasonably clear. How would someone read the question, as currently written, and think OP is looking for a circular argument?
Comment: One thing to note is that there cannot exist a surjective holomorphic function $\mathbb{C} \to \mathbb{C}\setminus \{z_1, \dots, z_n\}$ for $n > 1$. This is called [Picard's Little Theorem](https://en.wikipedia.org/wiki/Picard_theorem).
Comment: Honestly, I don't. I'm sure there is a reasonable proof along these lines (my guess is that the domain of the function should be a compact surface of genus $n-1$ with a point removed), but I don't quite see how to do it.
Comment: @PaulFrost Thanks for the comment. If you read carefully, my question is not "is it possible to define a function...", but "is it possible to prove that $\mathbb{C} \setminus \lbrace z_1, ..., z_n \rbrace$ is path-connected by defining...". So I guess the formulation matches the expectation here.
Comment: @diracdeltafunk Thank you for the comment. Indeed, this gives a reason why I couldn't find a function given by a "nice" formula ! But what I am looking for just requires the function to be continuous, do you know a way I could proceed ?
Comment: Your question "Is it possible to define explicitly a surjective continuous function $f : X \rightarrow  \mathbb{C} \setminus \lbrace z_1, ..., z_n \rbrace$, where $X$ is a path-connected topological space?" does not make much sense. We can take the identity on $\mathbb{C} \setminus \lbrace z_1, ..., z_n \rbrace$. I guess you ask whether we can take $X = \mathbb C$ or something like that.
Comment: @diracdeltafunk Then OP should edit his question to make precise (or at least *somewhat more* precise) what he/you expect.
Comment: @diracdeltafunk I am aware what OP expects. But do you think that expectation and formulation agree?
Answer: First of all, the explanation "just constructing a path joining two points" proves absolutely nothing. I suggest, you write a careful proof of path-connectedness of $Z^c$ which is the complement to a given finite subset $Z\subset {\mathbb C}$ and compare complexity of the proof to the complexity of your proof that ${\mathbb C}^*$ is path-connected (it hinges upon proving continuity and surjectivity of the complex exponential function $\exp: {\mathbb C}\to  {\mathbb C}^*$: Proving this from scratch is a nontrivial challenge).
No, let's prove path-connectivity of $Z^c= {\mathbb C}\setminus Z$ along the lines of your request.

First, consider a finite subset $W\subset  {\mathbb R} \subset {\mathbb C}$. Then $W^c$ is the union of two subsets $U^+, U^-$, where
$$
U^+=\{z: Im(z)\ge 0\}\setminus W$$
and
$$
U^-=\{z: Im(z)\le 0\}\setminus W.$$
In fact, both sets are homeomorphic via the complex conjugation map. I claim that $U^+$ is path-connected. Indeed, it is star-like with respect to the point $i$: For each $z\in U^+$ the line segment $[i, z]$ between $i$ and $z$ is contained in $U^+$. I will leave it for you to verify that each star-like subset of  ${\mathbb C}$ is path-connected. (Concatenate two segments $[p, i], [i,q]$ to connect points $p, q\in U^+$.) It follows that $U^-$ is path-connected as well. Observe that $U^+\cap U^-\ne \emptyset$, which implies path-connectivity of  the union $U^+\cup U^-=W^c$.

Second, I will use the fact that if $W, Z$ are two subsets of the same cardinality in ${\mathbb C}$ then there exists a homeomorphism $h: {\mathbb C}\to {\mathbb C}$ sending $W$ bijectively to $Z$, see for instance here for an explicit construction.

Thus, given aby finite subset $Z\subset {\mathbb C}$, I find a finite subset $W\subset
 {\mathbb R} \subset {\mathbb C}$ of the same cardinality and, hence, a homeomorphism
$$
f: X:= W^c\to Z^c
$$
obtained by restricting the homeomorphism $h$. This is the continuous surjective function from a connected space $X$ to $Z^c$ you asked for.
Needless to say, this is much more complex than the standard direct proof of path-connectivity of $Z^c$.
Comment: Thanks a lot for your answer. Obviously, I know that what I am looking for is not the most direct way to prove this classical fact (and don't worry, I know how to make a rigorous proof of it, and I also know how to prove quickly that $\exp$ is continuous and surjective). My question was rather a curiosity question... Anyway, I understand your answer, but to be a little bit annoying, it does not really answer my question : indeed, your answer relies mostly on the fact that $W^c$ is path-connected, but you prove it by constructing paths, which is precisely what I hoped to avoid.
Comment: But thanks again for your answer and your time, I appreciate !
Comment: @Henry: Your proof that ${\mathbb C}^*$ is path-connected is also by constructing paths: When you prove that ${\mathbb C}$ is path-connected. It is unavoidable that at some point you have to construct paths in some space if you want to prove that a space is path-connected.
Comment: I understand your point, and I kind of agree with you. However, the fact that $\mathbb{C}$ is path-connected is really more elementary than the fact that $Z^c$ is path-connected, whereas, in my opinion, the fact that $W^c$ is path-connected is not so much easier than for $Z^c$. Again, my question was not about a formal rigorous proof, but rather a curiosity : can we explicit a continuous surjective map $f : X \rightarrow Z^c$, where $X$ is "obviously" path-connected. I admit that mathematically speaking, it might seem stupid and useless, but I am curious about that.
Comment: @Henry: "obviously" (applied to path-connected or anything else) is a subjective term that varies from person to person: What you find obvious somebody else might not and vice versa. I suggest you edit your question to make it objectively answerable. In the current form, it is not. For instance, you may require $X$ to be a convex subset in a finite-dimensional vector space: Would you find this "obviously" path-connected? No other space? If so, make this requirement a part of the  question.


How do I replace a busted garage door hinge #0?

Question: My home's garage door has several #0 hinges in the interior (see picture below). Ten years ago or so I noticed a few of them were broken, so I bought replacements online and installed them without issue.
Tonight I noticed another hinge was broken so I jumped online to order a replacement, but it appears now that #0 hinges are no longer sold? The websites I found state that garage door hinges start at #1. I did find a seller on eBay selling #0 hinges, but he's asking $95 per hinge!
I presume #0 hinges have been phased out. Can I use a #1 hinge, instead, and just replace the broken one? Or do I need to replace all #0 hinges with #1 hinges? Or can I not use #1 hinges as replacements at all?
Thanks
Answer: The number of the hinge simply specifies "how tall they are" - i.e. the distance between the plane of the door and the hinge shaft.   That decides the distance between the (actually slightly slanted) garage door track, and the outer seal of the door.
Using too tall a hinge will cause the door to jam against the frame/seal.  It won't drop all the way, will bind badly, and after you adjust the garage door track to stop the binding, it will leak air badly.
Comment: Therefore, in order to use a #1 where a #0 used to go, either the hinge pivot point needs to be modified or the track's distance from the wall needs to be adjusted to make the whole thing fit. Correct?
Comment: @FreeMan modifying the hinge pivot point is what the size change does. Yes, you would need to change the track's distance from the wall if you didn't want it to bind at the bottom.