Using Automapper to change Collection

Question: I have two models in C# that have a one to many relation:
public class Make
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Model> Models { get; set; }
}

public class Model
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Make Make { get; set; }
    public int MakeId { get; set; }
}

and the DTO as follows:
public class MakeDto
{
    public int Id { get; set; }
    public int ModelId { get; set; }
    public ICollection<Models> Models { get; set; }
}

I'm using Automapper to map DTO in update operation, the problem is add/remove the collection are working fine but adding new items and update the existing items not working.
public AutoMapperProfile()
{

    CreateMap<MakeDto, Make>()
        .ForMember(m => m.Id, opt => opt.Ignore())
        .ForMember(m => m.Model, opt => opt.Ignore())
        .AfterMap((dt, m) =>
        {

            // Remove Model
            var removedModel = m.Model.Where(x => !dt.Model.Any(f => f.Id == x.Id)).ToList();
            foreach (var m in removedModel)
                m.Model.Remove(m);

            // Add new Model
            var addedModel = dt.Model.Where(x => !m.Model.
            Any(f => f.Id == x.Id))
            .Select(x => new Model
            {
                Id = dt.Id,
                Name = x.Name
            })
            .ToList();
            foreach (var m in addedModel)
                m.Model.Add(m);

        }).AfterMap((dt, m) =>
        {
            //Update Model
            m.Model = m.Model.Where(x => dt.Model.Any(f => f.Id == x.Id))
            .Select(x => new Model
            {
                Name = dt.Model.FirstOrDefault(x => x.Id == x.Id).Name,
            }).ToList();
        });
}

Comment: Try AutoMapper.Collection.
Comment: I couldn't fit it to m\y needs.
Comment: When mapping to an existing collection, the destination collection is cleared first. Without AutoMapper.Collection, you'd have to ignore the collection properties and map them yourself. So maybe give it another try :)
Comment: I don't know why mapper.collection remove all records from destination collection and add new ones. weird!
Comment: You're doing smth wrong. [AM.Collection](https://github.com/AutoMapper/AutoMapper.Collection) does what you need.
Answer: to answer my question and for future readers, I used Automapper.Collection as follows:
        var mapper = new MapperConfiguration(
            cfg =>
            {
                cfg.AddCollectionMappers();
                cfg.CreateMap<MakeDto, Make>()
                    .EqualityComparison((src, dst) => src.Id == dst.Id);
                cfg.CreateMap<Model, Model>()
                    .ForMember(x => x.Make, opt => opt.Ignore())
                    .EqualityComparison((src, dst) => src.Id == dst.Id);
            })
            .CreateMapper();
        mapper.Map<MakeDto, Make>(makeDto, make);
        await _unitOfWork.CompleteAsync();

also if interested, see this link

Using Automapper to change Collection


Unable to run PostgreSQL 9.2

Question: I followed an instruction on how to setup Ubuntu 10.04 with PostgresSQL
$ psql

Or this:
lucid@ubuntu:~$ sudo -u postgres psql postgres
[sudo] password for lucid:
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

Anyone knows a solution?
Comment: Take a look at postgres documentation at http://www.postgresql.org/docs/9.2/static/runtime-config.html In particular, sections 18.3.1 and 18.3.2
Answer: I believe the command should be
sudo -u postgres psql postgres

See https://help.ubuntu.com/community/PostgreSQL
If that does not work, tell us more about your configuration.
Comment: When I type this command, I get this "/var/run/postgresql/.s.PGSQL.5432"? -- same as the error in my question
Comment: See http://askubuntu.com/questions/42013/problem-installing-and-configuring-postgresql

Unable to run PostgreSQL 9.2


Network game connection lost

Question: Today I always get a network game connection lost message when I try to join to my multiplayer openttd server.
I checked local / server speed test. The only critical value is the 0.5 MBit/s on upload on the server. Do you know what is the requirement? Or can it be any other couse for this issue?
Answer: OpenTTD will automatically disconnect people if they take to long joining, how long it takes before they get disconnected is dependent on the variable max_join_time (0-65535 ticks, 30 ticks is a second, roughly 36 minutes at the highest setting).
Try changing max_join_time on the server to a higher value, the default value is 500.

Network game connection lost


Comparing Math.Log and Math.Pow

Question: I am working with annuities and have the following methods in my code:
<code>public static double NumPMTsRemaining( double CurBalance, double ContractRate, double Pmt)
{
    double rt = PeriodicRate(ContractRate);
    return -1 * Math.Log(1 - (CurBalance * (rt) / Pmt)) / Math.Log(1 + (rt));
}

public static double MonthlyPMT(double OrigBalance, double ContractRate, int Term)
{
    double rt = PeriodicRate(ContractRate);
    if (ContractRate > 0)
        return (OrigBalance * rt * Math.Pow(1 + rt, Term)) / (Math.Pow(1 + rt, Term) - 1);
    else return OrigBalance / Term;
}
</code>
I use the former method to determine if the payment for a loan will insure the loans pays off in its life remaining.  I use the latter method to determine if a payment is quoted for a payment period other than monthly and then replace it with a monthly payment if so.  Upon reflection I can use the latter method for both tasks.
With that in mind, I was wondering if anyone knew off the top of their head if Math.Pow is faster/more efficient than/relative to Math.Log?
I assume that Math.Pow is the better choice, but would appreciate a bit of input.
Comment: Why don't you profile each method with say 100,000 calls and see for yourself which one is faster?
Comment: Unless this is a bottleneck of your application, use the easier to read version, not the faster version.
Comment: I note that `Term` is an integer. There are generally much faster methods than Math.Pow for integer powers see for example http://mindprod.com/jgloss/power.html. Only go this route if this is a performance bottleneck.
Comment: I'd expect `log` with a fixed base to be faster than `pow`, since pow is usually implemented by calling `log` on the base followed by a fixed base exponentiation function. If you benchmark, benchmark separately for x64 and x86 since the generated floating point code on those platforms is pretty different.
Comment: Pretty well covered by [this post](http://stackoverflow.com/a/8870593/17034).  No, Math.Pow() is not faster.  Easy to find out for yourself with the Stopwatch class.
Comment: You should use `Math.Log(x, b)` instead of `Math.Log(x) / Math.Log(b)`, I guess.
Answer: I have built a benchmark as recommended by @Mangist. The code is posted below.  I was surprised by the response by @CodesInChaos.  I, of course, did some research and realized I could improve a large amount of my code.  I will post a link to a interesting StackOverflow article I found in this regard.  A number of people had worked out improvements on Math.Pow due to the aforementioned fact.
Thank you again for the suggestions and information.
<code>        int term = 72;
        double contractRate = 2.74 / 1200;
        double balance = 20203.66;
        double pmt = 304.96;
        double logarithm = 0;
        double power = 0;

        DateTime BeginLog = DateTime.UtcNow;
        for (int i = 0; i < 100000000; i++)
        {
            logarithm=(-1*Math.Log(1-(balance*contractRate/pmt))/Math.Log(1+contractRate));
        }
        DateTime EndLog = DateTime.UtcNow;
        Console.WriteLine("Elapsed time= " + (EndLog - BeginLog));
        Console.ReadLine();

        DateTime BeginPow = DateTime.UtcNow;
        for (int i = 0; i < 100000000; i++)
        {
            power = (balance * contractRate * Math.Pow(1 + contractRate, term)) / (Math.Pow(1
                      +  contractRate, term) - 1);
        }
        DateTime EndPow = DateTime.UtcNow;
        Console.WriteLine("Elapsed time= " + (EndPow - BeginPow));
        Console.ReadLine();
</code>
The results of the benchmark were
Elapsed time for the logarithm 00:00:04.9274927
Elapsed time for the power 00:00:11.6981697
I also alluded to some additional StackOverflow discussions which shed light on the comment by @CodeInChaos.
How is Math.Pow() implemented in .NET Framework?
Let me add a head to head comparison between a suggestion on the above link and the Math.Pow function.  I benchmarked Math.Pow(x,y) against Math.Exp(y*Math.Log(x)) with the following code:
<code>        DateTime PowBeginTime = DateTime.UtcNow;
        for (int i = 0; i < 250000000; i++)
        {
            Math.Pow(1 + contractRate, term);
        }
        DateTime PowEndTime = DateTime.UtcNow;
        Console.WriteLine("Elapsed time= " + (PowEndTime - PowBeginTime));
        Console.ReadLine();

        DateTime HighSchoolBeginTime = DateTime.UtcNow;
        for (int i = 0; i < 250000000; i++)
        {
            Math.Exp(term * Math.Log(1 + contractRate));
        }
        DateTime HighSchoolEndTime = DateTime.UtcNow;
        Console.WriteLine("Elapsed time= " + (HighSchoolEndTime - HighSchoolBeginTime));
        Console.ReadLine();
</code>
The results were:
Math.Pow(x,y)            00:00:19.9469945
Math.Exp(y*Math.Log(x))  00:00:18.3478346
Comment: In your paragraph "The results of the benchmark were Elapsed time for the logarithm 00:00:04.9274927 Elapsed time for the logarithm 00:00:11.6981697" you indicate twice the result for logarithm but none for power.
Comment: Thank you.  The latter should have been power.

Comparing Math.Log and Math.Pow


Javascript with multidimensional array

Question: I am having a problem with my multidimensional array. I am trying to insert an element via AJAX.
I grab the data from inside a table and send it to a PHP file which is meant to print the results but it prints incorrect data.
My HTML table:

       first
       second
       third

       fourth
       fifth
       sixth

Here is my Javascript:
for(i=0; i<=length; i++){
    for(j=0;j<width;j++){

    //inside of html table grab cell 1x1
            data = document.getElementById("mytable").rows[i].cells[j].innerHTML;

            //define the Array
            export_table[i]= new Array;
            export_table[i][j] = data;
    }
}

The PHP in my processdata.php:
print_r($_POST)

The problem I see is PHP prints:
Array
        (
            [0] => ,,first
            [1] => ,,,second
        )

But I really need it to print:
Array
        (
            [0] => Array
                              (
                                 [0] => "first"
                                 [1] => "second"
                                 [2] => "third"
                              )
            [1] =>  Array
                              (
                                 [0] => "fourth"
                                 [1] => "fifth"
                                 [2] => "sixth"
                              )
        )

Comment: where is your ajax call? you might need JSON in AJAX.
Answer: From what I can see from your Javascript it looks like you are sending your Javascript array variable to the PHP.
If this is true then the array value will not send properly because you can not pass advanced data types like Arrays and Objects into PHP $_POST and $_GET queries.
You may need to send it as a serialized string and then explode() the data inside PHP to move it back into a PHP array variable.
Alternatively you could try this:
for(i=0; i<=length; i++){
       //The first MultiDimensional Array
        export_table[i]= new Array;
        for(j=0;j<width;j++){
        //grab tables cell 1x1
                data = document.getElementById("mytable").rows[i].cells[j].innerHTML;
               //insert 'data' into 2nd dimentional array
                export_table[i][j] = data;
        }
    }

It should return values in format below:
Array
(
    [tab] => Array
        (
            [0] => first,second,third
            [1] => fourth,fifth,sixth
        )

)

Now PHP can use explode to move each array item into its own array.
Answer: This might fix it.
for(i=0; i<=length; i++){

    export_table[i]= new Array; // this line was misplaced.

    for(j=0;j<width;j++){
        data = document.getElementById("mytable").rows[i].cells[j].innerHTML;
        export_table[i][j] = data;
    }
}

But I'm confused about your workflow.  Where is this data coming from that you need to send it back to the server in table format from the client?

Javascript with multidimensional array


Best practice for entering imperial values in a construction-related software

Question: We're building a mobile app that is used in the construction industry, specifically for designing the 'flashing' of large, commercial sheds; the folded piece of steel that caps the exterior joins of the roof.
We're in Australia, and the widely adopted standard is to just have everything in millimetres (mm). Even though a flashing can be up to 1200mm, all display and input fields in our app are in whole mm values.
We want to adapt the app for the US and I'm curious to find out how imperial measurements are handled in this kind of software. We want to handle lengths from up to 1200mm (3 feet and 11.24 inches) down to, say, 15mm (0.59 inches). Ideally, we'd need accuracy to about 2mm. Concise display is also important (a lot of these values appear on a drawing).
For example, given a length of 449mm, should we go with something like:

Feet and decimal inches: 1' 5.68"
Feet and fractional inches: 1' 5 11/16"
Something else?

Even more importantly, what would users expect when entering these values, separate fields for feet, inches, and a selector for the appropriate fraction? Or would feet and inches-with-decimal be adequate?
Some other related questions:

What's the best practice for using single and double quotes to indicate feet and inches, should there be a comma or space (or nothing) between the two values (e.g. 1',5.68", 1' 5.68" or 1'5.68").
What's the best approach for a concise display of fractional values? The special Unicode character U+2044 FRACTION SLASH looks like the way to go (explained https://stackoverflow.com/questions/55033436/how-to-display-the-fraction-15-16-nicely-in-unicode)

Looking forward to some direction from those non-metric UX implementors.
Answer: When it comes to tape measures we ("imperialists") think in terms of fractional units:
1' 5 11/16"

...written without commas. However, a dash can be use to distinguish the integer inches from the fractional inches:
1' 5-11/16"

Provide two fields, one for feet, and a second for inches:
____ ft.   ________ in.

Allow either fractional or decimal inches input.

Better yet—if space allows...
Allow for fractional and decimal inputs but convert to metric.
Also allow a value to be entered in the metric field and convert it to fractional imperial IF the denominator is one of: 2, 4, 8, 16, or 32. However if the denominator is not 2, 4, 8, 16, or 32 convert it to decimal.
Here's how and why...
Start the process with imperial input, allowing the user to enter either fractional or decimal inches.
Imperial input:
Provide two fields, one for feet, and a second for inches:
____ ft.   ________ in.

But provide a metric field that gets automatically calculated:
_1_ ft.   _5_11/16_ in. ( _449_ mm )

...and be sure to accommodate if anyone enters a decimal in the inches field:
_1_ ft.   _5.68_ in. ( _449_ mm )

However...
Metric input:
If the user enters a value in the metric field, update the feet and inches field and convert to decimal:
_1_ ft.   _5.72_ in. ( _450_ mm )

—we'll have to mentally convert 5.72 to nearly 5 3/4 to determine if that works—but overall is less cognitive load because:
_1_ ft.   _5_18/25_ in. ( _450_ mm )

5 18/25 in. is practically incomprehensible.
.72 is much more easily recognized as almost .75 and that as 3/4.
Our tape measure units are: 1/2, 1/4, 1/8, 1/16, and 1/32.
Commonly known decimal/fractional associations are: .75, .5, .25, corresponding to 3/4, 1/2, and 1/4.
So, unless the numerator is 2, 4, 8, 16, or 32, it's cognitively easier for "imperialists" to round a decimal to nearest "known" decimal (.75, .5, .25), then to a tape measure unit (3/4, 1/2, and 1/4), and determine whether or not we're in the ballpark.
Comment: @MickByrne Sorry, allow me to clarify... If someone enters inches in decimal form there's no need to convert to fractional. They know what they're doing. I only recommend converting METRIC to decimal IF the fractional denominator is not one of: 2, 4, 8, 16, 32. I updated my answer—hope that helps.
Comment: Thanks @bloodyKnuckles, this is helpful. Due to screen limitations, we won't ever be displaying the metric and the imperial measurements (always one or the other). The basic gist of what you're saying though seems to be: enter imperial values in feet (whole numbers) and inches (with decimals), but display values in feet, inches and inch-fractions (closest fraction with a denominator of 2, 4, 8 or 16). Would that be right?


Placing a tkinter label on screen for a few seconds then destroying it

Question: So when you run the code below the tkinter label (and the whole window) doesn't appear at all for the few seconds then the window shows up without the label. I want to display the label for a few seconds, then for it to go away after a few seconds.
from tkinter import *
import time

root = Tk()

busted_display = Label(root, text="My Label Widget",
    font=("arial", "15"))
busted_display.place(x=0, y=0)
print("it ran")
time.sleep(3)
print("and then this ran")
busted_display.destroy()

root.mainloop()

Answer: You can't use time.sleep in an event driven program like a GUI. In tkinter, the answer to timed operations is the after() method, which runs the code you give it after a certain amount of milliseconds.
from tkinter import *

root = Tk()

busted_display = Label(root, text="My Label Widget", font=("arial", "15"))
busted_display.place(x=0, y=0)
root.after(2000, busted_display.destroy)

root.mainloop()

Comment: Ahh yes this work but you also need to use root.update_idletasks() before the 'after' method in order to get this to work
Comment: ... and for that matter you can use time.sleep() with success as long as you use the root.update_idletasks() method
Comment: @NoahCaldwell no you don't need anything else to make this work; I tested it before I posted. And if you have `update_idletasks()` anywhere in your code it's a sign that your code went wrong elsewhere. Good code would nearly never use `update_idletasks()`.


Sealing rusted spots for safety

Question: I have an old enamel wash basin that I'd like to use as a photography prop. It has some rusty spots, which actually just lend character so I don't mind them. But I want to make sure it is safe for the little ones. Is there a way to seal it off nicely?  Thank In advance for your advice!
Comment: It's not clear what you're asking. Rust is not dangerous, so ... ?
Comment: sealant may produce undesirable light reflections
Comment: Rust is a vitamin, it [makes blood red](http://scienceline.ucsb.edu/getkey.php?key=2419) and you'll die without it.
Answer: If you step on a dirty rusty nail in a barn, the problem is the puncture wound and the dirt, not the rust.  Rust is just oxidized iron and not especially dangerous on contact.
As long as it's clean with no sharp edges, burrs, etc., there is no need to seal it for safety.
Sealing it may slow the rust from spreading though.  Clear nail polish would probably work as well as anything.

Sealing rusted spots for safety


is kernel module an ideal way to access a device registers?

Question: I have a power management device (PF1550) in an I.MX6ULL embedded linux platform and its registers are configured in the uboot once.
I want to have something to pull its registers in the firmware right after boot up. Is kernel Module a good way to do this or there are simpler ways?
Thanks for your help in advance!
Comment: For device registers that are *memory mapped*, see https://stackoverflow.com/questions/12040303/how-to-access-physical-addresses-from-user-space-in-linux
Comment: There is also an existing driver for the [PF1550](https://github.com/nxp-imx/linux-imx/blob/lf-6.1.y/drivers/regulator/pf1550-regulator-rpmsg.c) in NXP's kernel tree. If you are using this most of the PMICs characteristics will be visible in [sysfs](https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-regulator).
Comment: "*pull its registers*" -- What do you mean by "*pull*"? Do you mean *read*? If reading a device register is benign, i.e. doesn't modify or self-clear the register, then you could simply read the (physical) memory location (since it's memory mapped) from userspace using the **devmem** command of Busybox. BTW "*kernel module*" is ambiguous; not every "*module*" is a driver, nor does that necessarily mean that it's *loadable*.
Comment: Sorry, I meant reading the device registers only. So you are saying that I can access (read) the registers of any device which is external to the main processor?
Comment: I am sure it is not included in my build. is there any document on how I can port it into my firmware source code ?
Answer: NXP PF1550 has an I2C interface, so I can believe it is connected to your NXP i.MX6ULL SoC. If yes, you can probe i2c-dev userspace driver, and you can read/write any PF1550's reg config via <code>/dev/i2c-X</code> adapter. I suggest to use python-periphery to test it.
By the way, it seems to me that, there was made a patch for support PF1550 via I2C in Linux kernel, but I can not find it in the mainline and in NXP's Linux kernel, maybe it is still not approved.
https://email@example.com/


Are redundant close buttons on an auto-closing popup necessary?

Question: Take a popup that closes automatically, either by losing focus, by other elements being brought into focus or clicked, or upon expiration of a set display time. Is providing a redundant close button on this popup necessary?
Compare the two examples shown side by side in the mockup below. In the first example, the popup appears when the combo box header is clicked and disappears when the combo box is clicked again or any other element on the page except for the popup is clicked. In the second example, the popup appears when a point on the map is clicked and disappears when another point on the map is clicked.

download bmml source – Wireframes created with Balsamiq Mockups
I can also provide an example where a right click opens a context menu containing the close button. But I prefer not to place a close button in a context menu. If there is also a different UX standard about this I would like to know about it.
Comment: You don't talked about audiences. It is depends on your audiences.
Comment: See also [How important is Close button in an expanded view?](http://ux.stackexchange.com/q/97889/57088)
Comment: In the second example, if the popup appears when you click on a point on the map, and disappears when you replace it with another popup by clicking elsewhere, then how do you return to the state where there is no popup? What happens when the user wants to view the map without any popup obscuring it?
Comment: *To me* (and I'm no UX expert), seeing that little `x` in your second example tells me that clicking outside of it will *not* dismiss that box (it's persistent until I click the `x`). Without the `x`, I would expect a click or interaction elsewhere would close it (it's more of a temporary thing).
Answer: A combo box has a specific interaction which has not changed for decades. Its interaction is aligned with a simple user goal - to select one or more items. Most users will expect this interaction. Note: A combo box does not have a pop-up - it is an expandable/collapsible list.
A tooltip has a completely different user goal - it is to provide additional information to a user, and it is normally displayed when someone moves the mouse cursor over an object, and disappears when you move the mouse cursor away from the object. Most users will expect this interaction.
So you should not expect the combo box and the tool tip to have the same interaction, and to compare them is wrong.
However, what you are describing is a pop-up styled to look like a tooltip which is being triggered in some way (click or tap) to persist on the page, so you should display something explicit which allows the user to close it.
Now, there is nothing wrong in closing your pop-up by clicking/tapping elsewhere in the page, but this is a hidden interaction which needs to be learned, but it does not hurt to also include an explicit close icon, so that it is abundantly clear how someone closes it. Redundancy (multiple ways to achieve the same thing) can be a good thing.
Comment: @GökhanKurt Why purposefully design a system that requires learning/training when you could design one that doesn't? The argument that if a customer is paying, they will be happier with a learning curve than someone who doesn't pay, makes no sense to me.
Comment: @GökhanKurt "...and disappears when another point on the map is clicked" Presumably opening another popup? And to close that popup, you click elsewhere on the map, opening a third popup? That would frustrate me to no end. I think the close button is needed.
Comment: @GökhanKurt: "I noticed I don't ever click that close button" -- in general that is quite a bad reason to omit a UX feature that's typically present in similar apps. "I studied many users, and few or none of them used it" is a better reason. Of course the few who do use it will hunt you down, but that's the risk you take messing with their expectations. If you turn out to be right and them wrong, and they do better without it, then they'll recover in time.
Comment: Customers pay to use the application I am working on. So they have learn to use it. Also we provide training courses to new customers. In a situation like this, it is easy for customers to learn how to close a pop-up. I personally think that the closing behaviour is also intuitive. I am an UX noob but I think UX is also about expanding the user's exprience.

Could you say it depends on the context?
Comment: @Nateowami Precisely, the pop-up disappears on mouse down on any point on the map. Also if the pop-up is open, the first click doesn't open another pop-up. I am actually using this behavior right now and it seems to work well. Google Maps also uses it but it also has a close button on the window. However, I noticed I don't ever click that close button but instead click somewhere on the map to close the pop-up.
Comment: @JBentley The application is not about just this behavior. And the training we give is not about the UX or how to use the system, but about business logic. Why design a system that requires training, that is a business decision. While watching educators, I thought customers could grab the minor UX tricks like closing a pop-up.
Comment: @GökhanKurt: It's not a business decision, but a human one. Why design a system that requires training when you can just as easily design one that doesn't? Simple: you don't.
Answer: A tooltip without a close button lacks affordance on how to close it.
Therefore, users would want to close the tooltip but may not know exactly how. It's not evident that clicking anywhere else on the page will close it. This can cause confusion and even some novice users might leave the current website/app because they might change or mess something.
That is why there should always be a visible close option for the tooltip. However, this does not concern tooltips that are closing when they lose focus.
Comment: if it does not close when the linked item looses focus, can you even call it a "tooltip"?
Comment: Yes - check [here](https://jqueryui.com/tooltip/) and [here](http://www.w3schools.com/bootstrap/bootstrap_tooltip.asp)
Answer: To add to the answers already given, let me say that if the two ComboBox mockups you show are intended to be equivalent, at least one of them is confusing/misleading.
Having a "Save" button implies that changes will not be saved unless you click it.  If the changes are saved automatically even if you click away or close the window, without clicking "Save," you shouldn't have a "Save" button at all as it is misleading.
The mockup without the "Save" button implies that changes are saved automatically.
Assuming changes are saved automatically, I would recommend no "Save" button on the ComboBox mockup.  Neither would I recommend a "Close" button as it could similarly be confused with "Canceling" the changes made.
A "Hide" button could be appropriate as it doesn't imply anything about saving or canceling changes.

For the "point on the map" popup, the small X button is a good idea for reasons discussed in the other answers.
Comment: Yes, this, exactly. I was about to post the same thing. The *save* button implies that not saving is an option. Then, if the user intends to *discard* their changes and so just clicks outside it without clicking save, they'll be surprised and possibly confused that they were saved. I'd actually expect to start seeing a few bug reports along the lines of "Changes are saved even when I discard them".
Comment: "The mockup without the "Save" button implies that changes are saved automatically."

I disagree. If I saw that mockup, I would be looking for a save button somewhere else on the page - I wouldn't assume it would be saved just because I had selected some items and closed the popup.
Comment: @Dezza, in that case I recommend you never use Apple products.  Settings in both macOS and iOS are almost universally saved without requiring you to click "save."  But, did you see what I said in the answer about a "close" button?


MVC Saving field data from a view

Question: I am using MVC and on my Index view I have placed a 'EditorFor' and a 'DropDownFor' fields on it for data entry. I would like a user to enter values and then 'Save' the record from the view. However I am having problems retrieving the data entered. I have tried creating an ActionResult and binding the data however nothing comes across. I have tried giving the fields id names and passing them in as parameters and again nothing is passed.
This is what I have in my View -

Sensitive Areas

@Html.HiddenFor(model => model.BurnSitesID, new { @id = "burnSitesID"})

    @Html.LabelFor(model => model.SensitiveTypesID, "Sensitive Area", new { @class = "control-label col-md-2" })

        @Html.DropDownList("SensitiveTypesID", string.Empty)
        @Html.ValidationMessageFor(model => model.SensitiveTypesID, "", new { @class = "text-danger" })

    @Html.LabelFor(model => model.DistSensitiveArea, new { @class = "control-label col-md-2" })

        @Html.EditorFor(model => model.DistSensitiveArea, new { @id = "distSensitiveArea" })

        @Html.ValidationMessageFor(model => model.DistSensitiveArea, "", new { @class = "text-danger" })

<input type="submit" id="CreateArea" value="Save"/>

How would you take the values entered and pass them to the controller? I have tried a button however if my button is not named the exact same thing as the view it does not do anything.
Comment: is your input elements inside a form ? What is happening when you submit the form ? How does the action method which handles the form submit looks like ?
Comment: You need to use the BeginForm helper or wrap your form with an HTML form element. In the case that you are using Ajax, you should probably show your JS code.
Comment: I added `using (Html.BeginForm())` and it still does not bring across any values. When I submit the form it acts like the fields are empty. That is using the following ActionResult - ` public ActionResult Save([Bind(Include = "SensitiveAreasID,,DistSensitiveArea,BurnSitesID,SensitiveTypesID")] BurnSiteSensitiveAreaIndexData burnSiteSensitiveAreaIndexData)`
Comment: You need to show the relevant information in your question, including the model and the controller methods. (and adding `id` attributes is pointless and has nothing to do with your issue)
Answer: Please use Html.BeginForm("ActionName","ControllerName", FormMethod.Post) .
Button should be Submit type .
If you are use textbox .
@Html.TextBoxFor("txtName", "", new { @class = "form-control", @maxlength = "50" })

<input type="submit" id="CreateArea" value="Save"/>

[HttpPost]
public ActionResult ActionName(FormCollection form)
{
 string Name=form["txtName"].ToString();
}

Where Name is a name/ID of field name .
Thanks .
Comment: Thank-you Ronak. This worked exactly like what I was looking for.

MVC Saving field data from a view


Undefined symbol in Diab linker

Question: i'm trying to run LZMA (C version) (7-zip.org/sdk.html) on an MPC5748G from NXP, by compiling a simple code to encode/decode a stream , i get the follwing WARNING from the linker:
scons: done reading SConscript files.
scons: Building targets ...
..\tools\wr\mpc5748_wr594\diab\184.108.40.206\WIN32\bin\dcc.exe -c -Xenum-is-best -Xrtti-off -Xexceptions-off -Xforce-declarations -ee1481 -tPPCVLEES:simple -Xsection-split -g3 -XO -Xsize-opt -DTGT_MPC5748_WR594 -DC_DERIVATIVE_MPC5748G -DFREESCALE_OS -DAUTOSAR_OS_USED -DOSDIABPPC -DADC_INTERRUPT_TYPE=MCAL_ISR_TYPE_NONE -DCAN_INTERRUPT_TYPE=MCAL_ISR_TYPE_NONE -DGPT_INTERRUPT_TYPE=MCAL_ISR_TYPE_NONE -DICU_INTERRUPT_TYPE=MCAL_ISR_TYPE_NONE -DLIN_INTERRUPT_TYPE=MCAL_ISR_TYPE_NONE -DPWM_INTERRUPT_TYPE=MCAL_ISR_TYPE_NONE -DSPI_INTERRUPT_TYPE=MCAL_ISR_TYPE_NONE -DTGT_DBG -DTGT_APP -DCFG_CFG -DCFG_CAN -DCFG_CSL -DCFG_MCU -DCFG_DUT -DCFG_MEM -DCFG_MOV -DCFG_GPI -DCFG_GPO -DCFG_ADC -DCFG_SED -DCFG_FRY -DCFG_LPM -DCFG_ETH -IC:\GW_MCU\tools\wr\mpc5748_wr594\diab\220.127.116.11\include -Ibsw\mcal\mcalAS\inc -I. lib\lzma\Alloc.c -o lib\lzma\Alloc.o
..\tools\wr\mpc5748_wr594\diab\126.96.36.199\WIN32\bin\dcc.exe -tPPCVLEES:simple -u__lear_calypso_memory_init -Wl,-Xremove-unused-sections -Wl,-Xunused-sections-list -lc -Wl,-m6 -Wm bsw/mcal/mcalm/linkerDescriptionVLE_App.dld -o out\app\BmwBdc2018GwmDutApp.elf out/app\objToLink.inl 1>out/app/BmwBdc2018GwmDutApp.map
dld: warning: Undefined symbol '__HEAP_END' in file 'sbrk.o(C:\GW_MCU\tools\wr\mpc5748_wr594\diab\188.8.131.52\PPCVLEE\libchar.a)'
dld: warning: Undefined symbol 'LzmaEncProps_Init' in file 'lib/lzma/LzmaLib.o'
dld: warning: Undefined symbol '__HEAP_START' in file 'sbrk.o(C:\GW_MCU\tools\wr\mpc5748_wr594\diab\126.96.36.199\PPCVLEE\libchar.a)'
dld: warning: Undefined symbol 'LzmaEncode' in file 'lib/lzma/LzmaLib.o'
dld: error: Undefined symbols found - no output written
scons: *** [out\app\test.elf] Error 1
scons: building terminated because of errors.

My question is not very clear but i want to know why i'm getting those linker erros and i'm looking for help from someone how had wworked with diab compiler since gcc does not give me this problem.
I don't know if the errors come from diabCompiler because in my laptop i got no problem
Can anybody help me please
Thansk a looot
Comment: @LPs thanks it helped me, i was including some source files that i have not compiled in the MAKEFILE, However i get now some parse error from diab compiler , i will make a new post for that
Comment: Whoa.. The ancient C compiler developed by DIAB data is still around? I've still got a DS90-10 workstation somewhere in the attic, I seem to recall the local terminal character set predating Latin-1 and using trigraphs for braces and brackets.
Comment: Maybe [THIS](http://www.linuxquestions.org/questions/programming-9/undefined-reference-to-errors-when-i-compile-lzmautil-c-943284/) could help.
Comment: If the above is an answer, then you should post as answer and mark this question answered.. :)
Answer: Try including all the source files used by the project and compile in the MAKEFILE, The error will probably disappear since you are using some functions that haven't been linked.
Comment: Did you just answer exactly the same as OPer selfanswered 5 days before?
Answer: i was including some source files that i have not compiled in the MAKEFILE, The error disappeared after including all the needed files in the makefile.
Answer: Check the read-only option for the generated file folders, also if you have added some content in the MAKEFILE then you need to check the read-write access for MAKEFILE folder.
Some times the diab compiler has this problem with the folder access for newly generated files.
As the error is .dld not found it means a perticular file format is not supported.

Undefined symbol in Diab linker


How do you paint touch-up spots on drywall?

Question: I have a few spots that need to be touched-up (after having a drywall anchor removed, being gouged while moving furniture, etc).
I filled them with putty, sanded smooth, then painted a single coat with a small foam brush, but:

The texture looks different from the rest of the wall
The color looks a bit off, though maybe this is just because of the texture.

Any tips on how to handle these spots so they don't stick out?
Comment: possible duplicate http://diy.stackexchange.com/questions/1543/problem-matching-flat-texture-finish-in-patched-drywall
Answer: A couple of things could cause this:

the original surface was primed, and you didn't use any primer on the patches.  Primer seals the surface, so changes how the surface absorbs paint.
the original surface was rolled, and you used a paintbrush.  Rollers leave a slight orange-peel texture, whereas a paintbrush -- even the brush you used -- will leave a flat to slightly rippled texture.

More coats of paint will help too, but prime it first.
Comment: You can get small rollers, which might help in matching the texture.  Can't really add much else to this answer.
Comment: I second the "mini rollers" idea from chris. I recently removed a small shelf that the previous owners had installed, left some holes that I spackled, sanded and mini rolled. Can't see any differences now that it's dried and set.
Comment: For completeness - you might also not have waited long enough. Sometimes paint takes a day or two to dry to it's final color.
Answer: The difference you are seeing (like @Niall C. mentioned) is that the area you patched is very smooth from the paint brush but the rest of the wall is speckled from a roller.  Possibly you also sanded the wall around the patch job too much and therefore removed the roller pattern that was previously there (making the smooth non-matching area larger and more apparent).  Next time when patching a small spot, put on your spackle/joint compound and then you can use a sponge sanding block to remove any high spots (but without sanding too much to remove any of the roller pattern from around the hole).  Then you can try and use a paint brush to get a match to the roller pattern by dabbing the area (instead of pulling full strokes) but you would definitely get a matching pattern by using a roller.
@Niall C. mentioned this in his answer but in my opinion priming small areas like you described is not necessary.  If this is a larger area (maybe the gouge that you describe, then priming and a roller would be required to get a match).


Anyone know the tools/process used by Starcraft 2 commentators to create the screen recordings of games?

Question: I tried FRAPS which makes great (albeit HUGE) avi files however there tends to be random times (ever 3-6 minutes or so) that the audio will skip/blup or the whole video will freeze for a second or two during playback. I was thinking about maybe going into windowed mode and using CamStudio but it only had the option to record windows sound OR mic, input not both.
The idea is to capture both voice over as well as game sound, and in the end be able to convert to a good quality YouTube video. Quality is the concern, for an example of good quality see: http://www.youtube.com/huskystarcraft.
EDIT: Yeah it could be my system causing the hiccups in FRAPS..
Thinkpad T510, i7 2.67ghz, 4GB of RAM, with this card: http://www.notebookcheck.net/NVIDIA-Quadro-NVS-3100M.24738.0.html
Comment: What are the computer specs you are using to capture your videos?  I've heard FRAPS quality depends heavily on your rig...
Comment: Is this a duplicate of http://gaming.stackexchange.com/questions/4793/best-way-to-post-a-starcraft-2-replay-to-youtube or the other way around?
Comment: not a duplicate for now, as he states FRAPS does not works, and that's the only answer on the other question, altrough we might want to merge them later.
Comment: Also note that, for voice, Husky and HD probably use studio-quality condenser mics (http://pro-audio.musiciansfriend.com/microphones)
Comment: @alexanderpas apparently FRAPS did work. Should we merge?
Answer: Actually, I'm pretty sure I remember Husky explicitly saying he was using FRAPS, though I don't recall in which video, so I can't verify it.
I think that if you encounter skips or stutters you just need to make sure that all other applications are disabled, and if that's still not good enough then maybe you should think about upgrading your system - recording high-resolution videos while playing a game is not an easy task for the computer.
You can also find FRAPS tips online; for example, recording to a different physical hard drive than the one used for the game is supposed to be great for performance.
Comment: Great point about the writing to a secondary hard drive, I'll give that shot.
Answer: Do you get the video hiccups before or after encoding the raw AVI? It matters because a lot of media players can't handle the bit rate of RAW avi @ 1080p.
Try encoding the video to mpeg4 or use real editing software to review the quality. And no, Windows Movie Maker is not real video editing software. It's really bad at pretty much everything.
You can get a trial version of Sony Vegas, it will probably handle the RAW AVI a lot better (I have no experience with vegas as when it comes to video editing I'm an apple fanboy). If you see no stuttering or issues in Sony Vegas you just have to encode your RAW AVI to some better format before uploading to youtube.
Comment: Dude that's a really good point, the AVI clips are only maybe 7 minutes long each but they are also 4gb, it makes sense that the blipping and freezing would be the player not the file itself as if it was the file it would likely not freeze on playback (meaning the play scrubber actually stops for a moment).
Comment: VirtualDub would be a great free alternative.
Answer: I use Microsoft Expression 4 recorder and it works fine for me.  I play full screen games, but in Windows.
Answer: XSplit and FFSplit are the two main programs used currently. Both allow you to stream to a site like twitch.tv or own3d.tv while also allowing you to just record videos locally if you'd prefer that.
I bought XSplit premium for myself, it's definitely one of the best pieces of software I've ever worked with and so very simple to use and configure.


Adding a duplicate of Bootstrap as a starting point for customization

Question: I've been doing research on best practices for customizing bootstrap. I get the impression that the best (css only) practice is to add a style sheet after bootstrap is called and override bootstrap classes as you customize. This being the case it seems like a reasonable starting point would be to add a duplicate of the bootstrap stylesheet and modify it's values while leaving the class names the same.
I'm hoping to get some feed back on this approach before I commit to it.
Comment: For the first step that's ok. You could also modify less/sass/scss of bootstrap (from which its css is generated). You can also take a look at fontawesome: http://fortawesome.github.io/Font-Awesome/.
Comment: If one were to modify the less/sass/scss is it still advisable to only alter the values and not the class names?
Comment: I think yes in most cases. In fact, you can check Bootstrap javascript code. It is only ~2000 lines long and if class name is used there - you probably shouldn't change it.
Comment: I think adding in a duplicate would be extra bloat you don't need.  The minimized CSS file is still 115KB, so to have two CSS files of that size would be overkill. My suggestion would be to only have the  styles you want to override in that custom style sheet.  And yes, only alter the values and not the class name.  The JS often times queues off the class name, so if you alter that you may lose some functionality in the process.
Answer: I infact do this, twitter invested 1000's of man hours into its development and it can save you time getting a project off the ground, quickly.
Most people and projects I have seen have bootstrap, then use a second stylesheet to override the default rules.
Hope that helps.
Answer: It would be a good idea only to copy over the styles you are using, as including a full stylesheet with redundant classes will effect performance. Not much but every little helps.


When should I incentivize parents to post about my kids app on social media?

Question: I have a reading app that's designed to be used by kids. However, I anticipate that the parents will have to set it up, at least initially. I want to prompt the parents to post about my app on social media. My question is, when should I prompt them?
Comment: Is the idea to have the parents all join the same discussion at the same time, to make sure that setup was successful?
Comment: Hi Montana, in what way is this about User Experience? This sounds more like a marketing question...
Comment: @Nash & StacyH: I want to include a prompt in my app for parents to share my app on their social media pages.
Answer: Look at the Users' Customers' Goals and Motivations
Initially your customer (parents) goal is to set up the application and provide to their child. Interrupting that goal is likely to cause frustration; frustration that could decrease social media posts or lead to negative social media posts.
At what point during the setup and use of the app (the customer journey) would a parent be most inclined to share the app on social media? Perhaps during one of these points:

Their child tells them they like the app
Their child has completed their first book
Their child has read every day for several days

The customer motivation for these is a sense of pride. That pride is an easy motivator to say "hey parent, share your child's proud moment with the world using social media.".
Look at the Business Goals and Motivations
This gets back to what you want. You want social media posts. Most likely, you want exposure and marketing from satisfied customers.
Is the timing of the social media sharing important? If so, you may need to find a balance between the setup process and social media post timing to ask at a least intrusive time. If not, wait to request sharing when your customer is most inclined to want to share.
The sweet spot is when your customers' goals and your business goals align.
*Note that your users are the children. They have different goals and motivations than the parents (customers) and so they are identified differently.
Comment: Should the prompt to share on social media come during the setup phase of the app, or - perhaps - in a notification?
Comment: I would recommend doing it during one of the 3 achievements from the child instead of during setup. This will provide your parent proper motivation to post and share. There are various answers to HOW to do this: one option is that the parent receives a notification or email when the child finishes their first book that congratulates the parent and asks if they would like to share the accomplishment (and share the app).
Answer: I'd suggest to put this as a final step of whatever onboarding process you have prepared there for the parent. That way you don't interrupt it with something trivial, but you can use the occasion for the parent to share that they have set up the app.


How can I pass an image from my UITableView to my detail UITableView?

Question: I'm trying to pass an image shown in my UITableView over to my detail UITableView. The images in my tableview are being pulled from a JSON end point. Any idea how I can go about this? At the moment, this is the line crashing my app:
featureImage.image = [[articleDetail objectForKey:@"Image"] objectForKey:@"filename"];
Any idea how I can do this properly? See code below.
TableViewController.m
<code>   - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    FullArticleViewController *detailViewController = [[FullArticleViewController alloc]
                                                        initWithNibName:@"FullArticleViewController" bundle:nil];
    detailViewController.title = [[Doctors objectAtIndex:indexPath.row] objectForKey:@"node_title"];
    detailViewController.articleDetail = [Doctors objectAtIndex:indexPath.row];

    [detailViewController.featureImage sd_setImageWithURL:[NSURL URLWithString:cellImageLink]];

    [self.navigationController pushViewController:detailViewController animated:YES];

}
</code>
DetailViewController.h
<code>{

    IBOutlet UIScrollView *scroller;
    IBOutlet UILabel *firstnameLabel;
    IBOutlet UILabel *descriptionLabel;
    IBOutlet UILabel *bodyLabel;
    IBOutlet UIImageView *featureImage;

}

@property (nonatomic, copy) NSDictionary *articleDetail;
@property (strong, nonatomic) UIImageView *featureImage;
@property (strong, nonatomic) NSString *cellImageLink;
</code>
DetailViewController.m
<code>- (void)viewDidLoad
{

    [scroller setScrollEnabled:YES];
    [scroller setContentSize:CGSizeMake(320, 5000)];

    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

firstnameLabel.text = [articleDetail objectForKey:@"node_title"];
descriptionLabel.text = [articleDetail objectForKey:@"Opening Paragraph"];
bodyLabel.text = [articleDetail objectForKey:@"Body"];
featureImage.image = [articleDetail sd_setImageWithURL:[NSURL URLWithString:cellImageLink]];

}
</code>
Answer: If you are using something like SDWebImage then you can just call the same code you have above:
<code>[detailViewController.featureImage setImageWithURL:[NSURL URLWithString:secondLink]];
</code>
If the image has been downloaded it will pull it from the cache, if not it will download it.
Comment: I'm totally using SDWebImage! So do I paste this line of code into my TableViewController.m during the segue? Or into the DetailViewController where my crash line is?
Comment: Personally I would pass a doctor object to your details view controller and then I would run that on viewDidLoad. You can run setImageWithURL any time you would call setImage.
Comment: Hey Patrick! See updated code above. Everything seems like it's in order, except in my DetailViewController (on the featureImage.image line), xCode throws me the error "No visible interface for 'NSDictionary' declares the selector 'sd_setImageWithURL'. Which doesn't seem to make much sense, since I've imported the appropriate SDWebImage header file. Any thoughts?


How do I trace the cabling in a "Ring Main"

Question: I have a "ring main" with many sockets on it, it is clear that it has been extended over the years.
How do I trace the cabling to.

Check that it is a single ring
That only one socket is on each spars
That there are not any other issues.

I am hoping for a testing method that I can just apply "set by set"; assume I have access to a good quality resistance meter
Is there any software I can type all the resistance readings into that will "solve" the system and will then tell me:

What additional readings it needs
Or how all the sockets are connected.

Related but a much easier problem: Are there any "easy" ways to trace a home electrical system?

Update:
The issue I have with the standard test method and all current answers is that they assume that the sockets are connect in a single ring – I don't know how they could detect for example two rings that have their ends joined just before the consumer unit.  Or a spars that is connect to anther spars rather then directly connected to the ring.
The test in the wiring standard is very good at finding common errors like a wire that is not connected, or a live that is connected to a neutral; however the test seems to assume that the wiring is basically a valid single ring to start with.   This is not a valid assumption on an old system you don't know the history off!
Comment: Are you willing to disconnect wires to do this, or are you looking for a non-intrusive solution?
Comment: I am willing to disconect some wires, but don't wish to disconnect all sockets
Answer: i don't know if this is the right way, but here's what i came up with.
THIS HAS THE POTENTIAL TO BE AN EXTREMELY DANGEROUS PROCEDURE. DO NOT ATTEMPT UNLESS YOU HAVE THE PROPER TRAINING TO UNDERSTAND WHAT IS BEING DESCRIBED HERE.
what i'm going to suggest is that you bridge the hot and neutral on one outlet in the ring. then. obviously, before you even think about attempting anything like this, you must turn off and disconnect the hot and neutral from the consumer unit. disconnecting the hot and neutral from BOTH sides of the ring is very important to the accuracy of your readings.
once you have bridged an outlet, you can take resistance readings between hot and neutral. if you have one outlet that you can be fairly certain is the first or last outlet on the ring, you can use that as your bridged outlet, then figuring out the order of the ring is as simple as sorting the list by resistance.
here's an example:

the black lines are wires. the red X's mark where the wires should be disconnected. notice the outlet on the right is bridged and a multimeter is connected to the outlet on the left. the green numbers are the resistances of the wires. obviously the numbers are not realistic, but this is just an example.
in the picture, the multimeter would be reading 58: 12 + 17 + 17 + 12 (that's the wires to outlet on the right and back).
the outlet on the bottom of the ring would read 34: 17 + 17.
since none of the outlets on the spar are bridged, they will not affect the reading above.
if you can't identify the outlets at the end of the ring, you can connect the hot/neutral on one side of the ring at the breaker, then measure the resistance of each outlet. the one with the lowest resistance is the outlet closest to that end of the ring.
the tricky part is identifying spars using this method. it might be obvious based on the resistance readings, but it might not be.
Comment: @longneck, but it is not save to have spars connect to spars due to overloading the cables
Comment: @longneck, but how do I tell the difference between a spar taht has a spar comming of it, and a socket on the ring?
Comment: you are assuming it is a single ring, also even valid spars would give invalid results with your method.
Comment: untrue. it would be difficult to identify spars properly, but a spar would not interfere with correctly ordering the outlets on a ring.
Comment: ok, sure, it's not safe. but what does that have to do with your question? you asked about mapping out your outlets to figure out how they are wired. that's what my instructions are for. once you have the map, you can pull off spar outlets and look at the gauge of the wire.
Comment: see edits above
Answer: if you can get your hands on a TDR (time domain reflectometer) you can use it to measure the distance to the end of the ring from an outlet.

turn off the power to the ring and disconnect the hot from both ends at the breaker.
using the TDR, measure the length of the hot circuit from where you just disconnected it at the breaker. that is the total circumference of the ring.
connect the TDR to the hot of an outlet. the TDR should return two "open" or "end of wire" values. this will tell you how far this outlet is from each end of the ring.
back at the consumer unit, take a short piece of wire and temporarily attach it to one of the live wires you disconnected and measured in steps 1 and 2. then remeasure the same outlet from step 3. the new measurements will tell you which "leg" of the ring goes to which wire.
repeat step 3 (and step 4 if needed) for each outlet.
Comment: yes, a good TDR can tell the difference between a screw connection and the end of a wire. the kind of TDR you need would be kinda pricey to buy, but if you could rent one, then whoever you are renting it from could suggest the correct model.
Comment: you are assuming it is a single ring, also even valid spars would give invalid results with your method.
Comment: untrue. if you TDR from the end of the ring and you only get one "open" or "end of wire" distance reading, then you know it's a ring with no spars. if you get n open readings, then you have n-1 spars. from there it's just a matter of finding the outlet with the shortest reading for a possible spar. if this doesn't make sense, i'll draw a diagram for you.
Comment: is a TDR really that good with household electric wiring that has normal screwed junctions etc? (The resistance of connections will not match the wires, so will there not be some reflections from each screwed connection?) ?  How good a TDR would I need for this, and can they be rented in the uk?
Answer: To work on complex house wiring in the UK you are required to be 'competent' and my feeling from your questions is that you are not and that you need to get a qualified electrician inspect the wiring.
I bought a decent book on house wiring with good diagrams and checked many website before attempting small jobs but still know that only a qualified electrician has the complete knowledge to test house circuits properly for faults.
Comment: All the electrician I have round to quote have basic said they would only test **their** work and could not tell me if the current ring was valid in all ways.
Comment: The issue I have is that the standard test an electrician does on a ring main, only give valid results if the ring main is wired as a single ring - all find and good if the electrician has wired the ring main, but as this is a old house all bets are off.

How do I trace the cabling in a “Ring Main”


How can I fix my window frame so that the window doesn't drop down?

Question: I'm working on a fixer-upper, and I needed to repair the screens. In order to remove the screens, I of course needed to lift the window all the way up. However, there was a bracket blocking the window's travel:

"No problem" I thought. But when I unscrewed that phillips screw, the rod just shot out of the frame. It sounded like a gunshot and took a chunk out of my hand. Same was true for the other side of the frame (though I was smart enough to wear gloves).
After the brackets came off, the rods moved freely back and forth. The window still opened and closed just fine, but it wouldn't stay up. It seems that the rods are under a lot of tension and hold the window in place when it's opened.
It seems that the rods can be screwed in. If I turn them counter-clockwise, the resistance builds up, and if I let go, they quickly spin back to their starting point. But after mucking around with them for a bit, it's not clear how to properly restore their function.
Here's what the right side of the top of the bottom window looks like where it meets the rod:

I'm definitely willing to read a manual if I can be pointed to it; I just haven't had any luck finding information about this type of window.
Answer: These are called spring balances, and have enough tension in the spring to hold the window open (sorry about your hand).  It's kind of hard to tell from the pictures you posted what type they are (other than older ones), but you should be able to find some instructions for a model similar to yours now that you know what to search for.
In general, you'll want to attach them at the bottoms first and then lift up the sash to allow re-attaching the tops.  This is a lot easier with 3 hands, so you might want to have someone hold the sash up or prop it if you can find something the right height.
Comment: Thanks, that should be the foothold I need to find out more!


Copy Sales Order Data to OrderKey

Question: Here is my test bunny sheet: https://docs.google.com/spreadsheets/d/151h1XjB98NOBnO0otNaql3ASjK84CccZZ399dX4BMBM/edit?usp=sharing
What I am trying to accomplish:

User inputs sales order on the 'salesOrder' Sheet
User submits sales order
a) sales order info is written to 'OrderKey' Sheet
b) the header info (Date, Company, Purchase Order, Sales Order,  Contact, email, phone, comments, ship via, account ) is repeated for every Product Line Item entered into the sheet into the 'OrderKey' Sheet

Having troubles figuring out how to go about doing this.
I have now created a 'kludge' sheet to formulaically copy over live information from the 'salesOrder' Sheet.
I named it kludge because It is not an elegant way of solving my problem, and not as I would be hoping to solve it.
At any rate, the 'kludge' method is not working due to appending NULL DATA... so how do I copy over only not null data?
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  // Or DocumentApp or FormApp.
  ui.createMenu('Custom Menu')
      .addItem('Submit Sales Order', 'menuItem1')
      .addToUi();
}

function menuItem1() {
    var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("kludge");
  var sourceInfo = sheet.getRange("A:N65");
  var targetInfo = ss.getSheetByName("OrderKey");
  var values = sourceInfo.getValues();
  targetInfo.appendRow(values[0]);

  sheet.getRange('B4:B5').clearContent();
  sheet.getRange('B8').clearContent();
  sheet.getRange('G6:G8').clearContent();
  sheet.getRange('F10:G10').clearContent();
  sheet.getRange('A13:B76').clearContent();
  sheet.getRange('J13:J76').clearContent();
  var cell = activeSheet.getRange("I1");
  var cellValue = cell.getValue();
  cell.setValue(cellValue + 1);
}

Answer: This is a quick solution for before(before kludge) version , not sure this is the best way,
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("salesOrder");

var val1 = sheet.getRange("G3").getValue();
var val2 = sheet.getRange("B5").getValue();
var val3 = sheet.getRange("G5:G8").getValues();
var val4 = sheet.getRange("B8").getValue();
var val5 = sheet.getRange("F10").getValue();
var val6 = sheet.getRange("G10").getValue();

var targetInfo = ss.getSheetByName("OrderKey");
targetInfo .appendRow([val1,val2,val3[0][0],val3[1][0],val3[2][0],val3[3][0],val4,val5,val6]);

sheet.getRange('B4:B5').clearContent();
sheet.getRange('B8').clearContent();
sheet.getRange('G6:G8').clearContent();
sheet.getRange('F10:G10').clearContent();
sheet.getRange('A13:B76').clearContent();
sheet.getRange('J13:J76').clearContent();
var cell = activeSheet.getRange("I1");
var cellValue = cell.getValue();
cell.setValue(cellValue + 1);

Comment: Thanks for all the help.
Comment: Thank you, I did not know about the use of .appendRow how it worked... with different ranges.  I see this would copy to 1 Row of data for only the 'Header' Order data, and leave the Product range alone.  I am still trying to figure out how to merge the Product, Qty, range with multiple rows.
Comment: Hmmm so appendRow suggests only a 1D array.  How would I loop for every product line item entered?
Comment: Welcome, you can [read more](https://developers.google.com/apps-script/reference/spreadsheet/sheet#appendrowrowcontents)!
If so you question is too broad. narrow down to small segment and ask here. People will help you.
Comment: for that, you need to configure an `onEdit` trigger. [read this](https://developers.google.com/apps-script/guides/triggers/events)
Comment: I don't see how an onEdit trigger would help.  Sounds like it would make a mess of line item data if a user changes things before submission.
Comment: yes, you have to check editing cell and if it is correct one, enter product line. or else you can add a save button. for that, Go into "Insert > Drawing...", Draw a button and add it to the spreadsheet. Then click it and click "assign Macro...", then insert the name of the function you wish to execute there.
Comment: I need to stay away from any drawings added to the sheet.  images outside of the print area mess up the export to print.  I originally had a couple of buttons set just out of the print area, but it completely messed up export to PDF, which is why I am trying to roll this into a menu item.   That being said, do you understand the problem I am trying to solve, is there anyway I can help better explain it?  I am not a seasoned programmer as you can tell, any help would be really appreciative.
Answer: Aurielle Perlmann has elegantly found a solution HERE:
https://stackoverflow.com/a/34982276/5229520
Thank you.

Copy Sales Order Data to OrderKey


prove, using induction that for natural $n$ and $0<x<1$ that $(1-x)^n<\frac{1}{1+nx}$

Question: How to prove, using induction, that for every natural $n$, and for every $0<x<1$ :$$(1-x)^n<\frac{1}{1+nx}$$
Comment: Are you familiar with [Bernoulli's inequality](https://en.wikipedia.org/wiki/Bernoulli%27s_inequality): $(1-x)^n>1+nx$?
Comment: yeah, its $(1+(-x))^n>1-nx$. But its bigger not smaller
Answer: It is just a consequence of the AM-GM inequality, since $x\in (0,1)$ grants:
$$ (1-x)^n (1+nx) \color{red}{\leq} \left(\frac{n\cdot(1-x)+(1+nx)}{n+1}\right)^{n+1}=1 $$
but equality is achieved only when $(1-x)=(1+nx)$, i.e. at $x=0$.
Answer: It is not really hard: suppose by the inductive hypothesis that, for some $n$, we have $\;(1-x)^n<\dfrac{1}{1+nx}$. As $0<1-x<1$, multiplying both sides by $1-x$, we get
$$(1-x)^{n+1}<\dfrac{1-x}{1+nx}$$
so it is enough to prove $\;\dfrac{1-x}{1+nx}\le\dfrac1{1+(n+1)x}$. As all numbers are positive, this amounts to proving
$$(1-x)\bigl(1+(n+1)x\bigr)\le 1+nx\iff 1+nx-(n+1)x^2\le1+nx. $$
Comment: The base case needs to be established as well. Also not hard - proving $1-x < \frac{1}{1+x}$ amounts to proving $(1-x)(1+x)<1$, similar to the inductive step.
Comment: Of course. I didn't claim it's a full proof, which is not in the spirit ogf this site. Note the strict inequality is true only for $n\ge 1$ natural numbers, for me, begin at $0$).
Comment: It was less a critique of your answer than a note for the OP who may forget that the base case needs to be established.


A third stacked bar in matplotlib

Question: Consider this example code from matplotlib website:
# a stacked bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, menMeans, width, color='#d62728', yerr=menStd)
p2 = plt.bar(ind, womenMeans, width,
         bottom=menMeans, yerr=womenStd)

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))

plt.show()

Suppose I had a third series and I wanted it to be stacked on top.  How to express a
bottom

parameter?  I tried to simply do
menMeans + womenMeans

but that didn't work.
Source:  https://matplotlib.org/2.0.0/examples/pylab_examples/bar_stacked.html
Answer: In principle you are correct: You need to add up the previous bar heights to obtain the bottom of the next bar.
The problem is that you cannot simply add tuples. So a good idea would be to make them numpy arrays, menMeans = np.array(menMeans).
Those numpy arrays can easily be added together, such that
p3 = plt.bar(ind, childrenMeans, width, bottom=menMeans+womenMeans)

works out nicely.
Complete code:
import numpy as np
import matplotlib.pyplot as plt

menMeans = np.array((20, 35, 30, 35, 27))
womenMeans = np.array((25, 32, 34, 20, 25))
childrenMeans = np.array((21, 30, 32, 10, 36))

ind = np.arange(5)
width = 0.35

p1 = plt.bar(ind, menMeans, width, color='#d62728', )
p2 = plt.bar(ind, womenMeans, width,  bottom=menMeans)
p3 = plt.bar(ind, childrenMeans, width,  bottom=menMeans+womenMeans)

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0], p3[0]), ('Men', 'Women', "Children"))

plt.show()

Comment: Extending the official example to 3, 4, 5, ... N stacked bars would be an excellent addition to the matplotlib documentation URL I referenced in the question.
Comment: The main point of the cited example is to show the use of the `bottom` argument. The way how to obtain the array to supply there is not really a matplotlib issue, so adding even more bars would make the example overly complicated.
Comment: Multiple stacked bars is common so I think it would be a nice addition.

A third stacked bar in matplotlib


How can I import multiple functions or components from a package using react lazy

Question: I have to replace the usage of loadable with react.lazy
This is how it was with loadable:
const loadReactIntl = () => import('react-intl');

export const intlProvider = () => Loadable({
  loader: () => loadReactIntl(),
  render(loaded, props) {
    **const { createIntl, createIntlCache, RawIntlProvider } = loaded;** // <-- this line what I'm looking for
    ... // skip rest of the code
  },
});

I'm trying to do something similar to the highlighted line but with react.lazy instead of loadable, something like this:
const ReactIntl = lazy(() => import('react-intl');

export const getLoadableIntlProvider = (localesLoaderConfig = localeConfig) => (props) => {
  const { messages } = props;
  const { createIntl, createIntlCache, RawIntlProvider } = ReactIntl;
  ... // skip the rest of the code
};

I tried doing something like this, but that did not work either it keeps giving me e.g. createIntl undefined:
const ReactIntl = lazy(() => import('react-intl').then((module) => ({ default: module.RawIntlProvider, createIntlCache: module.createIntlCache, createIntl: module.createIntl })));;

Is there a way to get around this?
Answer: This is what you probably want:
const RawIntlProvider = lazy(() => import('react-intl').then((module) => ({ default: module.RawIntlProvider })));;
const createIntlCache = lazy(() => import('react-intl').then((module) => ({ default: module.createIntlCache })));;

But I don't know if this lazy is really needed as you want to load module, not component.


Can someone read object sent with socket.io emit even though it's not printed out for user in frontend

Question: So I'm working on node.js app that pushes objects via socket to update user with latest information.
That object has user data populated with it. I'm wondering if someone can see that information somehow even though it's not printed out?
Should I remove sensitive data from object before emitting it via websocket to the frontend?
Answer:
That object has user data populated with it. I'm wondering if someone can see that information somehow even though it's not printed out?

Yes, anyone snooping around in the client with development tools can see what is sent via a webSocket.  For example, one only has to open the debugger and look at the webSocket packets that have been sent.  The same is true for any data sent to the client in any manner.

Should I remove sensitive data from object before emitting it via websocket to the frontend?

Yes, you should.
Comment: Thanks for explanation, after some googling I actually managed to see web socket data myself.
Answer: Everything you send to the client, whether using HTTP, socket connections, etc. is all accessible in the client browser. You should always only send the data that is required by your website to run for that specific client and data particular to that client.
With developer tools getting more powerful everyday, it is much more easy to snoop at such data.


generate random numbers within a range with different probabilities

Question: How can i generate a random number between A = 1 and B = 10 where each number has a different probability?
Example: number / probability
1 - 20%
2 - 20%
3 - 10%
4 - 5%
5  - 5%
...and so on.
I'm aware of some hard-coded workarounds which unfortunately are of no use with larger ranges, for example A = 1000 and B = 100000.
Assume we have a
    Rand()

method which returns a random number R, 0 < R < 1, can anyone post a code sample with a proper way of doing this ? prefferable in c# / java / actionscript.
Comment: Can you describe how you plan to specify the probabilities associated with the 99001 values in the range [1000, 100000]? Just to get an idea of what your expectations are. Also, what are your storage and time constraints?
Answer: Build an array of 100 integers and populate it with 20 1's, 20 2's, 10 3's, 5 4's, 5 5's, etc. Then just randomly pick an item from the array.
int[] numbers = new int[100];
// populate the first 20 with the value '1'
for (int i = 0; i < 20; ++i)
{
    numbers[i] = 1;
}
// populate the rest of the array as desired.

// To get an item:
// Since your Rand() function returns 0 < R < 1
int ix = (int)(Rand() * 100);
int num = numbers[ix];

This works well if the number of items is reasonably small and your precision isn't too strict. That is, if you wanted 4.375% 7's, then you'd need a much larger array.
Answer: There is an elegant algorithm attributed by Knuth to A. J. Walker (Electronics Letters 10, 8 (1974), 127-128; ACM Trans. Math Software 3 (1977), 253-256).
The idea is that if you have a total of k * n balls of n different colors, then it is possible to distribute the balls in n containers such that container no. i contains balls of color i and at most one other color. The proof is by induction on n. For the induction step pick the color with the least number of balls.
In your example n = 10. Multiply the probabilities with a suitable m such that they are all integers. So, maybe m = 100 and you have 20 balls of color 0, 20 balls of color 1, 10 balls of color 2, 5 balls of color 3, etc. So, k = 10.
Now generate a table of dimension n with each entry being a probability (the ration of balls of color i vs the other color) and the other color.
To generate a random ball, generate a random floating-point number r in the range [0, n). Let i be the integer part (floor of r) and x the excess (r – i).
if (x < table[i].probability) output i
else output table[i].other

The algorithm has the advantage that for each random ball you only make a single comparison.
Let me work out an example (same as Knuth).
Consider simulating throwing a pair of dice.
So P(2) = 1/36, P(3) = 2/36, P(4) = 3/36, P(5) = 4/36, P(6) = 5/36, P(7) = 6/36, P(8) = 5/36, P(9) = 4/36, P(10) = 3/36, P(11) = 2/36, P(12) = 1/36.
Multiply by 36 * 11 to get 393 balls, 11 of color 2, 22 of color 3, 33 of color 4, …, 11 of color 12.
We have k = 393 / 11 = 36.
Table[2] = (11/36, color 4)
Table[12] = (11/36, color 10)
Table[3] = (22/36, color 5)
Table[11] = (22/36, color 5)
Table[4] = (8/36, color 9)
Table[10] = (8/36, color 6)
Table[5] = (16/36, color 6)
Table[9] = (16/36, color 8)
Table[6] = (7/36, color 8)
Table[8] = (6/36, color 7)
Table[7] = (36/36, color 7)
Answer: Assuming that you have a function p(n) that gives you the desired probability for a random number:
r = rand()  // a random number between 0 and 1
for i in A to B do
    if r < p(i)
      return i
    r = r - p(i)
done

A faster way is to create an array of (B - A) * 100 elements and populate it with numbers from A to B such that the ratio of the number of each item occurs in the array to the size of the array is its probability. You can then generate a uniform random number to get an index to the array and directly access the array to get your random number.
Comment: You probably mean `if r > p(i)`. But this isn't correct. If 1 and 2 both appear with 20% percent probability, you'll always return just one of them and never the other.
Comment: in fact for 0.2 < r < 0.4 you will get 2.
Answer: Map your uniform random results to the required outputs according to the probabilities.
E.g., for your example:
If `0 <= Round() <= 0.2`: result = 1.
If `0.2 < Round() <= 0.4`: result = 2.
If `0.4 < Round() <= 0.5`: result = 3.
If `0.5 < Round() <= 0.55`: result = 4.
If `0.55 < Round() <= 0.65`: result = 5.
...

Answer: Here's an implementation of Knuth's Algorithm. As discussed by some of the answers it works by
1) creating a table of summed frequencies
2) generates a random integer
3) rounds it with ceiling function
4) finds the "summed" range within which the random number falls and outputs original array entity based on it
Answer: Inverse Transform
In probability speak, a cumulative distribution function F(x) returns the probability that any randomly drawn value, call it X, is <= some given value x. For instance, if I did F(4) in this case, I would get .6. because the running sum of probabilities in your example is {.2, .4, .5, .55, .6, .65, ....}. I.e. the probability of randomly getting a value less than or equal to 4 is .6.   However, what I actually want to know is the inverse of the cumulative probability function, call it F_inv.  I want to know what is the x value given the cumulative probability. I want to pass in F_inv(.6) and get back 4.  That is why this is called the inverse transform method.
So, in the inverse transform method, we are basically trying to find the interval in the cumulative distribution in which a random Uniform (0,1) number falls.  This works out to the algorithm that perreal and icepack posted.  Here is another way to state it in terms of the cumulative distribution function
Generate a random number U
for x in A .. B
   if U <= F(x) then return x
Note that it might be more efficient to have the loop go from B to A and check if U >= F(x) if the smaller probabilities come at the beginning of the distribution
Answer: Considering, say, the random number range of 1, 2, 3 with the probabilities of 50%, 30% and 20%, I think it is the easiest to think about the problem as suggested by Jim Mischel's answer:
"Build an array of 100 integers and populate it with 50 ones, 30 twos and 20 threes. Then just randomly pick an item from the array."
... but it is probably more efficient to implement it in terms of multiple index windows (in other words, index ranges) as opposed to array allocation and initialization:
#include <assert.h>

#include <random>
#include <iostream>

// g++ algorithm.cpp -g -o algorithm

int main()
{
    // random number range: 1, 2, 3
    int lowest = 1;
    int highest = 3;

    // probabilities: 50%, 30%, 20%
    int probs[] = { 50, 30, 20 };

    /*

    "Build an array of 100 integers and populate it with 50 ones, 30 twos and 20 threes.
    Then just randomly pick an item from the array."

    */

    const int prob_count = sizeof(probs)/sizeof(probs[0]);

    // must have as many random number possibilities as there are probabilities
    assert(highest - lowest + 1 == prob_count);

    const int random_min = 0;
    const int random_max = 99;

    srand(time(NULL)); // seed
    const int continuous_index = random_min + rand() % ((random_max + 1) - random_min);

    std::cout << "continuous index: " << continuous_index << std::endl;

    int window_index = -1;

    /*

    window index 0 (50%): continuous indexes 0 - 49
    window index 1 (30%): continuous indexes 50 - 79
    window index 2 (20%): continuous indexes 80 - 99

    */

    for (int i = 0, index = 0; i < prob_count; i++)
    {
        const int prob = probs[i];
        assert(prob > 0 && prob < 100); // more likely a mistake than an intended arg

        const int continuous_index_from = index;
        const int continuous_index_to = continuous_index_from + prob - 1;

        std::cout << "window index " << i << " (" << prob << "%): continuous indexes " << continuous_index_from << " - " << continuous_index_to << std::endl;

        if (continuous_index >= continuous_index_from && continuous_index <= continuous_index_to)
        {
            window_index = i;
            // do not // break;
        }

        if (!(i + 1 < prob_count)) // the last iteration
            assert(continuous_index_to == 99); // sanity: probabilities must add up to 100

        index = continuous_index_to + 1;
    }

    assert(window_index >= 0 && window_index < prob_count);
    std::cout << "window index: " << window_index << std::endl;

    const int random = lowest + window_index;

    assert(random >= lowest && random <= highest);
    std::cout << "random number: " << random << std::endl;
}

Sample output:
continuous index: 89
window index 0 (50%): continuous indexes 0 - 49
window index 1 (30%): continuous indexes 50 - 79
window index 2 (20%): continuous indexes 80 - 99
window index: 2
random number: 3


When the submit button is clicked, I want to get the value of a dropdownlist

Question: How do I get the option's value that was selected in a dropdown list when a button is clicked?
<select id="d1"><option value="1">One</option>...</select>

Answer: $('#btn').click(function () {
    var value = $('#d1').val();
})

$(element).val() returns the value of any form element.
Comment: Pretty sure I have run into this numerous times, but I'll take your word, no time to try it.
Comment: should that say "var value" not "val value"?


C with Eclipse on Ubuntu: why is an .exe and no linux executable created?

Question: I am using Neon.3 Release (4.6.3) Eclipse IDE for C/C++ Developers under Ubuntu 15.5. When I build an run my C-program the program

the program executes without any errors/warnings
delivers the expected output in the eclipse-console
and generates an .exe file in the the debug folder

For me it is very much surprising that an .exe file is generated using an Linux OS (I thought these files can only be created under Windows?). How can I configure Eclipse to generate a typical Linux-executable instead?
Many thanks!
Comment: Extensions don't matter much in Linux IIRC. You can name an executable `something.exe` and it won't change how it runs...
Comment: @c650 Thank you! I was absolutely unaware of that! By the way, with your answer (to this basic question) you have just helped me fixing a bigger bug that has annoyed me for a couple of weeks by now. Cheers!
Comment: "the program executes without any errors/warnings ..." - Apparently it "generates a typical Linux-executable" already.  So what's you problem?
Comment: @Olaf "Apparently it generates a typical Linux-executable already": what is obvious to you may not obvious to others (including me). "So what's your problem?": My problem was that, due to my lack of knowledge, that I thought a Windows-executable rather than a desired Linux-executable was generated. However, c650 noticed that there was some lack of knowledge on my side and gave me the information I needed to clear things up for me.
Comment: It is obvious to everyone reading your text. He does not even know about programming! I cited the relevant part of your text, in case you did not read it carefully yourself.
Answer: Extensions don't matter much in Linux. You can name an executable something.exe and it won't change how it runs...


Are non-GFCI outlets that are downstream of a GFCI outlet ground fault protected if they are fed from the GFCI outlet's load side?

Question: Are non-GFCI outlets that are downstream of a GFCI outlet ground fault protected if they are fed from the GFCI outlet's load side?
If those non-GFCI downstream outlets were not fed from the GFCI outlet's load side but rather just had their hot, neutral and ground wires spliced to those feeding the GFCI outlet, would the effect be the same as if there was no GFCI outlet on the circuit at all?
Answer: Yes, that is the entire purpose of the load terminals of the GFCI.  You can imagine that the protection element of the GFCI extends both to its receptacles, and then just imagine the load pair as another "receptacle".
As to the second part, yes, if you just connect the terminals together "before" the GFCI protection is in place, the GFCI will have no effect - remember, it can only sense problems on its own receptacles and its load terminals.
Comment: Code-wise is it ok to have non-gfci outlets and gfci outlets on the same circuit?
Comment: Yes it is perfectly fine, only certain areas need gfci, and if the usage numbers for that circuit allow it, it could go other places in the house e.g., bathroom gfci to hall outlet, hall outlet doesn't need to be gfci protected.
Comment: If you mix and use downstream load outlets, its advisable to use a "GFCI protected" and a "No equipment ground" label, as appropriate (at the downstream outlets)
Answer:
Are non-GFCI outlets that are downstream of a GFCI outlet ground fault
  protected if they are fed from the GFCI outlet's load side?

Yes.

If those non-GFCI downstream outlets were not fed from the GFCI
  outlet's load side but rather just had their hot, neutral and ground
  wires spliced to those feeding the GFCI outlet, would the effect be
  the same as if there was no GFCI outlet on the circuit at all?

Yes. The GFCI outlet will only protect its own outlets and any outlets that are connected via it's 'Load' connections. Anything spliced before the GFCI will behave as if there is no GFCI.
The most important thing is to make sure you connect the GFCI to power from the panel via the 'Line' connections. If you connect to the Load connections, the GFCI functions just like a cheap $1 non-protected outlet, and provides no extra protection.
Comment: << Anything spliced before the GFCI will behave as if there is no GFCI. >>  Is that a kosher config to have? That is, a GFCI outlet and non-GFCI outlets on the same circuit?
Comment: Yes, it's fine code-wise (as far as I can tell), but I would generally run a separate circuit for the GFCI outlets vs, the non-protected stuff, just to be neat about it. That way you know that one circuit breaker, for instance, controls the kitchen outlets, or garage, bathroom, etc.
Comment: @geerlingguy: I think it would also be appropriate to have e.g. a kitchen with several independent GFCI-protected outlets if e.g. the one which was more likely to have a ground-faulted load plugged in was further from the supply, but would be more convenient to reset.  BTW, I wonder why the convention is simply to label downstream outlets "GFCI protected" without any indication of where the protecting GFCI is located?
Comment: @supercat I always add the GFCI sticker, plus a tiny circuit number sticker next to it, on all protected circuits. It makes life easy down the road!
Answer: Yes to the first question.  No to the second.  The GFCI protects everything downstream of its load side only.
Comment: I think you mean yes to both, though the second question was worded in a way that makes it hard to answer in the affirmative... the important thing is to make sure you don't put the line into the GFCI's load side—power goes into the GFCI on the line connections only, not the load :)


Display current year starting on August 1 - PHP

Question: I need a PHP function that displays the previous year until August 1, at which point it should display the current year.
For example:

today is May 12, 2011, so this should echo "2010"
when it's August 1, 2011 this should echo "2011"
...continue to echo "2011" until August 1, 2012
on August 1, 2012, it should echo "2012"
etc.

Please let me know if you have any questions. Thanks in advance!
Comment: Question... what have you tried so far?
Comment: Agree with @Mark Baker. This is a relatively easy question to answer with just a little bit of research.
Comment: So basically show a fiscal year with August 1 as its starting date?
Answer: Here ya go:
<code>$year = date('Y') - 1;
$month = date('n');

if($month >= 8) $year++;

echo $year;
</code>
Demo: http://codepad.org/qOx1TO95
Comment: I think you are one off in your if condition.
Answer: <code>$august = strtotime('1 August');
if(time() < $august) {
  echo date('Y') - 1;
}else{
  echo date('Y');
}
</code>
Comment: @Emil...   does this mean august of every year? this doesnt look right
Comment: It does. strtotime should default to the current year. But I agree more with your solution - didn't think straight when I chose strtotime over date :-)
Answer: <code>function year($timestamp) {
    if(date('m', $timestamp) < 8) {
        return (date('Y', $timestamp) - 1);
    }
    return (date('Y', $timestamp));
}
</code>


Why is the installer downloading the whole game again when I have already downloaded during my pre-order?

Question: I'd pre-ordered Diablo III quite some time back and downloaded and ran the installer which then proceeded to download the full game.
However, today when I try to install Diablo III, it's redownloading the entire 8gb set of files. I've also downloaded the new installer, yet it proceeds to download the entire game.
What can I do to make the installer recognize that I've already downloaded the game?
Answer: Blizzard had posted this post which mentions that the initial installers had a bug. The post mentions:

Obtain the new Diablo III digital downloader using the links below

EU English Installer - Windows
EU English Installer - Mac
German Installer - Windows
German Installer - Mac

Point the download save at the same directory as before. The folder in question is your main game data folder. If you have the game
  downloaded to D:\Games\Diablo-III-8370-enGB-Installer, please point
  the download to D:\Games\.
Do not use the automatically generated folder containing the
  installation files (i.e. do not use the directory
  D:\Games\Diablo-III-8370-enGB-Installer as this is the one created by
  the downloader).
  If you chose the correct directory only 50MB will need to be downloaded to fix your install, otherwise you'll re-download the
  entire ~7.6GB

Also, it's absolutely imperative that you download the same language & region client that you used to download the game after pre-ordering.
In my case, I had downloaded the En-GB version of installer & game after pre-ordering. However, today while downloading the new installer, Blizzard offered me the US version of the installer & because of this mismatch, it was downloading the whole game again.
After grabbing the En-GB(aka EU) install client, it was able to detect my previous download.


`a,b,c` are both type `Eigen::ArrayXd`. What's the shape of `{a,b,c}`?

Question: from others' codes in the codebase, there is an assignment like z = {a,b,c} where z has type Eigen::Matrix<Eigen::ArrayXd, 3, 1>, but I have no idea how it forms this, and how to access a member of a such as a[1] for example in this Matrix.
I have to say it is much easier to understand with numpy.vstack in Python.
the docs of Eigen https://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html says it should be a scalar type in template Matrix<typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime>
so how is Eigen::Matrix<Eigen::ArrayXd,3,1> even possible since Eigen::ArrayXd is not a scalar type?
Comment: Can you define what is `{a, b, c}`? If you ask about how to concatenate the matrices, [here is the answer](https://stackoverflow.com/questions/21496157/eigen-how-to-concatenate-matrix-along-a-specific-dimension). Otherwise, if you want to know if it's possible to have a "matrix of eigen matrices" - yes it is, but you need to follow the guidelines for [using custom scalars](https://eigen.tuxfamily.org/dox/TopicCustomizing_CustomScalar.html#user_defined_scalars) (not sure if it makes sense, though).
Comment: Where are those "other's codes" that gave you this idea?
Comment: @pptaszni I'm reading others' codes in my company's codebase, it is an assignment where it's like `arr = {a,b,c}` and `arr` is `Eigen::Matrix` type
Answer: The shape of Eigen::Matrix<Eigen::ArrayXd, 3, 1> is 3 rows x 1 column. Each element contains an array (not a matrix or vector, from math POV) of size N (dynamic).
That's it, all the operations will be defined like usual. In particular, given:
Eigen::Matrix<Eigen::ArrayXd, 3, 1> m = {a, b, c};

the transposition of this matrix will have a shape (1,3), and the matrix multiplication result
auto prod = m * m.transpose();

will be 3x3 matrix with elements
aa ab ac
ba bb bc
ca cb cc

And since your elements are of type Eigen::ArrayXd, they will be multiplied element-wise.
Small demo
Comment: Not in C++ in general, but Eigen library defines it like that. See [the documentation](https://eigen.tuxfamily.org/dox/group__TutorialArrayClass.html) with some examples.
Comment: thank you! Is the multiplication of arrays element-wise by default in C++?
Comment: thank you, but I still dont quite get the assignment, like `{a,b,c}` is assumed to be shape {3,1}?
Comment: Yes, the shape is determined by the Matrix type you are assigning to. So in your case it's 3 rows x 1 column with element type being Array of dynamic size (elements a, b, c don't even need to have the same size). Don't think about it from the mathematical point of view (well, unless your colleagues have some special interpretation for these types), treat it like a container with fancy operations.