Multi property checking with single rule

Question: How could I make following concise, with an extension method etc.? Also could that InlineValidator consolidated into the MainPropertyValidator class?
public class PropertyDTOValidator : AbstractValidator<PropertyDTO>
{
    public PropertyDTOValidator()
    {

        RuleFor(p => p).SetValidator(new InlineValidator<PropertyDTO>
        {
            validator =>
            {
                return validator.RuleFor(p => p.MainProperty)
                    .SetValidator(new MainPropertyValidator());
            }
        }).When(p =>
        {
            var checkMainProperty = p.MainProperty.Id != -1;
            if (!checkMainProperty)
            {
                // Some actions...
            }

            return checkMainProperty;
        });
    }
    class MainPropertyValidator : AbstractValidator<PropertyDTO>
    {
        public MainPropertyValidator()
        {
            RuleFor(p => p.Id).Must(id =>
            {
                return id >= 1;
            }).WithMessage("MainProperty Id value is not valid...");

        }
    }
}

Edit
I have following extension but i want to consolidate my validator into a single class like InlineValidator. I checked the code of InlineValidator but i could not consolidate InlineValidator and MainPropertyValidator.
public static class Extensions
{
    public static IRuleBuilderOptions<T, TProperty1> SetValidator<T, TProperty1, TProperty2>(this IRuleBuilderInitial<T, TProperty1> ruleBuilder,
        Expression<Func<T, TProperty2>> exp, IValidator<TProperty2> validator)
    {
        return ruleBuilder.SetValidator(new InlineValidator<T>
        {
            v => v.RuleFor(exp).SetValidator(validator)
        } as IValidator<TProperty1>);
    }
}

RuleFor(p => p).SetValidator(p => p.MainProperty, new MainPropertyValidator()).When(p =>{});

Answer: Alternatively, following extensions could be used;
public static class Extensions
{
    public static IRuleBuilderInitial<T, TProperty> When<T, TProperty>(this IRuleBuilderInitial<T, TProperty> rule, Func<T, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators)
    {
        return rule.Configure(config =>
        {
            PropertyRule propertyRule = config;
            int num = (int)applyConditionTo;
            propertyRule.ApplyCondition(ctx => predicate((T)ctx.InstanceToValidate), (ApplyConditionTo)num);
        });
    }

    public static IRuleBuilderInitial<T, TProperty> Custom<T, TProperty, TProperty2>(this IRuleBuilder<T, TProperty> ruleBuilder, Expression<Func<TProperty, TProperty2>> expression, AbstractValidator<TProperty2> validator)
    {
        var propChain = PropertyChain.FromExpression(expression);
        var propName = propChain.ToString();
        var prop = expression.Compile();

        Func<string, string, string> joinStr = (s1, s2) => string.Join(".", new[] { s1, s2 }.Where(s => !string.IsNullOrEmpty(s)));
        return ruleBuilder.Custom((p, context) =>
        {
            var val = prop(p);
            var validationResult = validator.Validate(val);
            propName = joinStr(context.PropertyName, propName);

            foreach (var failure in validationResult.Errors)
            {
                failure.PropertyName = joinStr(propName, failure.PropertyName);
                context.AddFailure(failure);
            }
        });
    }
}

RuleFor(p => p).Custom(p => p.MainProperty, new MainPropertyValidator()).When(p =>
  {
      var checkMainProperty = p.MainProperty.Id != -1;
      if (!checkMainProperty)
      {
          // Some actions...
      }

      return checkMainProperty;
  });


JQuery adding HTML using .after possible ID conflicts

Question: I'm adding html to a page on button click.  The displayed HTML has an additional button that adds HTML on button click.  After adding the "primary HTML" twice, if I click the secondary button from the first instance of the primary HTML added, it adds HTML to the second instance of the primary HTML added.
I think it's an ID conflict.  I'm pulling my hair out over it.
Here is a jsfiddle showing the issue.
http://jsfiddle.net/JXeMS/19/
To create the issue:  Add a product, add 2-3 tiers, Add the product a second time, add 2-3 tiers.  Finally, add a new tier from the first added product, and it adds the tier to the second added product.  Doh!
JQuery code
$(document).ready(function() {

    var cainc = 1;
    var afrinc=1;
    var mfrinc=1;
    var mfralinc=1;
    var earinc=1;
    var minmcinc=1;
    var maxmcinc=1;
    var parinc=1;
    var maapinc=1;
    var eprinc=1;
    var pprinc=1;
    var minscinc=1;
    var maxscinc=1;

    $('#productbtn').on('click', function() {

        if ($('#prodselect option:selected').text() == "Commercial Attachments"){

            $('#productbtn').closest( "tr" ).after('

<input id="buttonremc" type="button" style="width: 110px; height: 22px;" value="Remove Product">Product:  Commercial Attachments

Activity Type:	<select name="caacttype'+ (cainc++) +'" style="width:87px;"><option></option><option value="send">Send</option><option value="rec">Receive</option><option value="view">View</option></select>	Monthly Commission Percentage:	<input type="text" name="mthcom" maxlength=3 size=10 value="00">

Annual Flat Rate:	<input type="text" name="afr'+ (afrinc++) +'" size=10 value="00.00" >	Monthly Flat Rate:	<input type="text" name="mfr'+ (mfrinc++) +'" size=10 value="00.00" >
Monthly Flat Rate Attachment Limit:	<input type="text" name="mfral'+ (mfralinc++) +'" size=10 >	Excess Attachment Rate:	<input type="text" name="ear'+ (earinc++) +'" size=10 value="00.00" >

Minimum Monthly Charge:	<input type="text" name="minmc'+ (minmcinc++) +'" size=10 value="00.00" >	Maximum Monthly Charge:	<input type="text" name="maxmc'+ (maxmcinc++) +'" size=10 value="00.00" >

Per Attachment Rate:	<input type="text" name="par'+ (parinc++) +'" size=10 value="00.00" >
Maximum Allowed Attachment Pages:	<input type="text" name="maap'+ (maapinc++) +'" size=10 >	Excess Page Rate:	<input type="text" name="epr'+ (eprinc++) +'" size=10 value="00.00" >

Per Page Rate:	<input type="text" name="ppr'+ (pprinc++) +'" size=10 value="00.00" >
Minimum Submission Charge:	<input type="text" name="minsc'+ (minscinc++) +'" size=10 value="00.00" >	Maximum Submission Charge:	<input type="text" name="maxsc'+ (maxscinc++) +'" size=10 value="00.00" >
<input id="addtiercom" type="button" style="width: 110px; height: 22px;" value="Add Tier">
');

            var raisetierid = 1;
            var rateplus = 1;
            var rangeplus = 1;
            var catierrate = 1;
            var rangemin = 1;
            var rangemax = 1;

            $('#addtiercom').on('click', function() {

                $('#addtiercom').closest( "tr" ).after('
<input id="addnewtier" type="button" style="width: 110px; height: 20px;" value="Add Tier" >  <input id="removetiercom" type="button" style="width: 110px; height: 20px;" value="Remove Tier" >

Tier Type	  Attachments<input type="radio" name="brackettype" value="a">   Pages<input type="radio" name="brackettype" value="p">   Offices<input type="radio" name="brackettype" value="o">
Tier '+ (rateplus++) +' Rate	<input type="text" name="catierrate'+ (catierrate++) +'" size=10 value="00.00" >	Tier '+ (rangeplus++) +' Range	Minimum <input type="text" name="rangemin'+ (rangemin++) +'" size=10 value="" > Maximum <input type="text" name="rangemax'+ (rangemax++) +'" size=10 value="" >
');
                $('#comattach9').hide();
                $('#addnewtier').on('click', function() {
                    $('#inctier'+(raisetierid-1)+'').closest( "tr" ).after('
Tier '+ (rateplus++) +' Rate	<input type="text" name="catierrate'+ (catierrate++) +'" size=10 value="00.00" >	Tier '+ (rangeplus++) +' Range	Minimum <input type="text" name="rangemin'+ (rangemin++) +'" size=10 value="" > Maximum <input type="text" name="rangemax'+ (rangemax++) +'" size=10 value="" >	');
                });
            });
        }
    });
});

Comment: Holy columns! You should consider using a templating library (Mustache, Underscore, jQuery Templates, etc.) when constructing HTML elements.
Comment: Can you confirm if all IDs are unique through DOM inspection (possibly via Firebug)? IDs have to be unique among elements. Classes, however, can be reused.
Answer: The problem occurs because you're binding event handlers within other event handlers, as well as creating multiple elements with the same IDs.
I suggest you use the this keyword more frequently, and bind delegated event handlers to the closest static parent (not nested handlers either!) and of course, switch to classes.
For example:
$('body').on('click', '.product-button', function() {
  // Your code for product buttons
  // $(this) is the button that's clicked
});
$('body').on('click', '.add-tier', function() {
  // Your code for adding a tier
});

...etc
Comment: Thank you ahren.  I don't have it worked out quite yet.  I've got some weird action going on adding the tiers below the add tier buttons, but I do already have it working independently based on your above advice.  I'll post again when I've got it figured out.
Answer: You need to change this part:
             $('.addtierbtn' + comtrinc + '').on('click', function () {
                    $('#inctier' + (comtrinc) + (raisetierid - 1) + '').closest("tr").after('
Tier ' + (rateplus++) + ' Rate	<input type="text" name="catierrate' + (catierrate++) + '" size=10 value="00.00" >	Tier ' + (rangeplus++) + ' Range	Minimum <input type="text" name="rangemin' + (rangemin++) + '" size=10 value="" > Maximum <input type="text" name="rangemax' + (rangemax++) + '" size=10 value="" >	');
                });
            }); } });
});

raisetierid++ should be raisetierid--
Answer: I believe it was an id conflict problem.  I switched to classes on the buttons and added some if, if else conditional loops to determine the variable value being appended to the tr ids.
http://jsfiddle.net/JXeMS/30/
 $


Why can't I fight Flowey at the end of a Pacifist Run

Question: I recently bought Undertale, and I've had a lot of fun with it. I'm currently going for pacifist.
I got all the way up to the Asgore fight and mercy'd him. In the judgement hall, Sans told me that I did a pacifist run, and my stats and the game files both said that I was level 1 and had 0 exp. Whenever I beat Asgore, I mercy him and then Flowey steals his soul. After the screen flashes, and I'm in a room where Flowey once stood. Nothing there except a door to the next room. The credits go on, I get the phone call, then it sends me back to the menu.
Any Suggestions?
Comment: Possible duplicate of [Undertale Pacifist Ending](http://gaming.stackexchange.com/questions/253175/undertale-pacifist-ending)
Comment: Not a duplicate - this focuses on the endgame stuff, while that focuses on post game stuff.
Comment: If you find yourself in a fight with Asgore and said fight isn't interrupted at the very start, then you missed something for a Pacifist run.
Answer: I'm guessing that, if you really saw Flowey after he stole Asgore's soul,

 the game crashed, you fought Flowey in his glitched world and then saw the credits.

which is a neutral ending.
After you boot once again the game, Flowey will tell you what you did wrong or what you are missing. Follow his tips.
You might have killed a single mob / boss that you think might be "un-merciable", which sounds like you didn't from the 0 exp, or you might not have completed all of the side quests most likely.
Just listen that little flower ;) he's nothing to be afraid of ;)
Comment: But he didn't ever say anything. He just absorbs the souls, and I get the phone call.
Answer: It might be that you've already defeated Flowey in a previous run. The flower remembers, and thus gives up without you having to go through Your Best Nightmare.
But if this is your first run, then it might be a glitch caused by a certain scientist.
Comment: So I have to true restart?
Comment: Yes, you'll have to True Restart in order to see the Flowey fight again.
Answer: To get the pacifist ending, you have to do the Papyrus date, the Undyne date, the Alphys date and the true lab (in that order). Maintaining LV1 alone won't give you the pacifist ending. It will only give you the speech from Sans.
Here is how:

Return to Snowdin after sparring Papyrus. Ask him to let you in to his house, go into his room, then talk to him.
Spare Undyne, give her the water, go to her house (which is to the left of Nastabloc's house), and speak to Papyrus.
Walk between the Core and MTT Resort after sparring Metaton. You should get a call from Undyne. Meet her in Snowdin, and she will ask you to deliver a letter. Do so, and the Alphys date will start.
So long as you have not killed any monsters, you will now be able to access a hidden area in the lab.
Answer: If you have already defeated Flowey in a previous run without a True Reset, then Flowey will decide it's not worth it. Don't worry, your still on True Pacifist, so just go do whatever is needed to get the ending.


Shading bars conditionally in ggplot for multiple series bar charts

Question: I'm making bar charts that show the difference between groups over separate periods, however I also want to shade out certain bars that don't meet certain criteria (i.e CV > 20 or Sample_size < 30).
Can someone please help me to do this? I've attached a picture as an example of what I'm looking for my output to look like (mocked up in excel), and some example data below.
Thanks a million!!
Example data:
    structure(list(Group = c("A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J"),
    Perc = c(38, 38, 46, 27, 18, 39, 43, 27, 38, 40, 39, 39,
    50, 32, 33, 41, 52, 32, 43, 43), Lower_CI = c(36, 36, 36,
    15, 8, 31, 30, 14, 18, 23, 38, 37, 40, 21, 15, 31, 40, 17,
    24, 27), Upper_CI = c(39, 40, 57, 39, 27, 47, 55, 40, 58,
    56, 41, 41, 60, 44, 51, 51, 64, 47, 63, 60), CV = c(2, 2,
    11, 12, 28, 11, 15, 6, 18, 13, 2, 2, 10, 19, 5, 13, 12, 23,
    14, 20), Sample_size = c(30, 15, 140, 40, 69, 75, 56, 256,
    45, 536, 4852, 785, 36, 48, 315, 120, 83, 15, 123, 45), Period = c(1,
    1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)), row.names = c(NA,
-20L), class = c("tbl_df", "tbl", "data.frame"))

Answer: You can try a dplyr and ggplot2 pipeline. You can integrate a new value for Period using mutate(). After that you can also keep the same order for Group formating it as a factor. The plot you want is a dodged bar plot. Using ggplot2 functions you can reach that. Finally, move the axis using coord_flip(). The additional level created can be dropped using breaks inside scale_fill_manual(). Here the code:
library(ggplot2)
library(dplyr)
#Code
df %>%
  mutate(Period=ifelse(CV>20 | Sample_size<30,3,Period),
         Group=factor(Group,levels = rev(unique(Group)),ordered = T))%>%
  ggplot(aes(x=Group,y=Perc,fill=factor(Period)))+
  geom_bar(stat = 'identity',position = position_dodge(0.9))+
  geom_errorbar(aes(x=Group,ymin=Lower_CI,ymax=Upper_CI,group=Period),
                position = position_dodge(0.9))+
  scale_fill_manual(values=c('cornflowerblue','orange','gray'),
                    breaks=c('1','2'))+
  labs(fill='Period')+
  theme_bw()+
  coord_flip()

Output:

Some data used:
#Data
df <- structure(list(Group = c("A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J"),
    Perc = c(38, 38, 46, 27, 18, 39, 43, 27, 38, 40, 39, 39,
    50, 32, 33, 41, 52, 32, 43, 43), Lower_CI = c(36, 36, 36,
    15, 8, 31, 30, 14, 18, 23, 38, 37, 40, 21, 15, 31, 40, 17,
    24, 27), Upper_CI = c(39, 40, 57, 39, 27, 47, 55, 40, 58,
    56, 41, 41, 60, 44, 51, 51, 64, 47, 63, 60), `(-)` = c(2,
    2, 10, 12, 10, 8, 13, 13, 20, 17, 1, 2, 10, 11, 18, 10, 12,
    15, 19, 16), `(+)` = c(1, 2, 11, 12, 9, 8, 12, 13, 20, 16,
    2, 2, 10, 12, 18, 10, 12, 15, 20, 17), CV = c(2, 2, 11, 12,
    28, 11, 15, 6, 18, 13, 2, 2, 10, 19, 5, 13, 12, 23, 14, 20
    ), Sample_size = c(30, 15, 140, 40, 69, 75, 56, 256, 45,
    536, 4852, 785, 36, 48, 315, 120, 83, 15, 123, 45), Period = c(1,
    1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)), row.names = c(NA,
-20L), class = c("tbl_df", "tbl", "data.frame"))

Comment: Thank you so much, that's exactly what I wanted :D
Comment: @barnesybee Always a pleasure!
Answer: You could do something like this:
library(ggplot2)

#create variable for color/fill
df$col <- df$Period
df$col[df$Sample_size < 30 | df$CV > 20] = 3
df$col <- as.factor(df$col)

#plot
ggplot(data = df, aes(x = Group, y = Perc, group = Period,
                      color = col, fill = col)) +
  geom_bar(stat = "identity", position = position_dodge()) +
  geom_errorbar(aes(ymin = Lower_CI, ymax = Upper_CI),
                position = position_dodge())+
  scale_color_manual(values = c("blue", "orange", "grey"),
                     breaks = c("1", "2"),) +
  scale_fill_manual(values = c("blue", "orange", "grey"),
                    breaks = c("1", "2")) +
  coord_flip()+
  theme_bw() + theme(legend.title = element_blank())


Simplifying trigonometric identity: $(\cos^4x-\sin^4x) = 2\sin^2x-1$

Question:
Simplify $$ \left(\cos^4x-\sin^4x\right) = 2\sin^2x-1 $$

But how can anyone show why this is true?
I ended with $ \sin^2x-\cos^2x $.
Comment: Maybe it is the same thing ?...
Answer: The given equation is merely conditionally true, but becomes an identity once a negative sign inserted in front:
\begin{align}&-\left(\cos^4x-\sin^4x\right)
\\\equiv&\sin^4x-(1-\sin^2x)^2
\\\equiv&2\sin^2x-1\end{align}
Comment: Thanks I don't understand why that's true now I knew it thanks ryang
Comment: @Blueemerald For future reference, verify that the given equation is true for all $x$ by [checking that the graph of LHS minus RHS identically equals $0$](https://www.desmos.com/calculator/8xbhvj7oat).
Answer: Hint:
Factor $\cos^4 x - \sin^4 x$ into two similar terms, i.e. $$(\cos^2 x + \sin^2 x)(\cos^2 x - \sin^2 x)$$  What do you notice with this factorization?  And how can you resolve it?
Comment: I've updated my post and removed the "identity" language.
Comment: The identity is false, as you can see by substituting $0$ for $x$.
Answer: This statement is false.
$$
\begin{aligned}
\cos ^{4} x-\sin ^{4} x &=\left(\cos ^{2} x+\sin ^{2} x\right)\left(\cos ^{2} x-\sin ^{2} x\right) \\
&=\cos ^{2} x-\sin ^{2} x \\
&=1-\sin ^{2} x-\sin ^{2} x \\
&=1-2 \sin ^{2} x
\end{aligned}
$$


Problems with the placement new operator

Question: I understand the placement new operator allows to construct object at a particular/specific memory location. So i tried this;
#include <iostream>
#include <new>

using namespace std;

struct Any {
    int x;
    string y;
};

int main() {

    string mem1[1];
    int mem2[5];

    Any *p1 = new (mem1) Any;
    Any *p2 = new (mem2) Any;

    p1->y = "Hello";
    //p2->x = 20;

    cout << p1->y << endl;
    //cout << p2->x;

    return 0;
}

What I realized is, I can set a string to a location that I've set aside to hold exactly 1 string but i can't do same for an integer like so;
int mem2[1];
Any *p2 = new (mem2) Any;
p2->x = 20;

I get a buffer overflow error even though it manages to show me the value I placed in that location which is 20;

Why?
Also, with my full code shown above, I have set aside 2 different memory locations to hold the 2 objects which makes p1->y print without any problems. But when i reduce this location
int mem2[5]; to any number below 5 which i think has nothing to do with the location where I placed the string and try to print the string, I get a segmentation fault error. Why >= 5? Does it have to do with memory available?
Is there a way to check if using the placement new operator to place an object at a specific memory location was successful?
Comment: You have to make sure that an `Any` object fits in the space you try to put it in. `mem1` is definitely too small. Another problem is that the destructor for a string is called at the end of its scope, so you will have to restore `mem1` before the end of `main`.
Comment: Looks like you'll have some serious memory alignment issues when placement new'ing a `Any` into an array of `string` or `int`
Comment: Also, most compilers are smart enough to transform `x = 20; cout << x;` into just `cout << 20;`, and not bother to write anything to `x`. So that is not a very good test for if it is working.
Comment: Placement new is *guaranteed* to be successful, unless the constructor throws an exception or you provoke undefined behavior. If the constructor throws you can just `catch` it, and undefined behavior can't be detected kind of by definition.
Comment: @BoPersson I don't get any error that says `Any` object didn't fit into `mem1` so it runs fine. It's when i reduce 'mem2` to any number below `5` that i get errors trying to print what's in `mem1`. That's why I'm confused!
Comment: @NanaOsaberima there is no guarantee at all that if you override memory you would notice it, so you need to understand how it works rather than guess.
Answer: You have sets of Undefined Behavior in your code.
First of all, there's no guarantee that the declaration string mem[1]; sets aside enough memory to contain an abject of type Any....
Secondly, even if the first had adequate memory to hold such object, the destructor of the array string mem[1]; will still run at the end of main, but you've overwritten that array with something else, hence your program should at best case, crash.
You may want to use a POD type, like char mem1[sizeof(Any)] to store the object, that way you are sure of mem1 being capable enough to store Any, and you'll have no issues with destructor of mem1 being called at the end of main()
Again, you may want to explore a standard facility for this kind of thing, std::aligned_storage
Comment: Placement new is guaranteed to succeed if and only if: the constructor being called doesn't throw an exception **and** you have all rights to the **entire** memory required to store such object
Comment: That is why i asked if there's a way to check if **placement new** was successful
Comment: @NanaOsaberima, the primary job of placement new is to call the constructor... And it's the only way to make the C++ runtime create an object in a specific location. Your question is like asking how to know if an object's constructor was successfully called when declared on the stack.


Android Studio - ListView updates in weird way

Question: My ListView is connected to a database online. I click on a button from the main activity that starts the activity that has the ListView. When I create a item in another activity and add it to the database the ListView still has the old items.
So for example, I click on a button in the main activity that leads me to the create item activity when I add a item into the database online. Then I go back to the main activity and I click on the button that leads to the activity with the ListViewand then it shows all the items EXCEPT the one i just added. However, when I press the back button to back to the main activity that has the button and press the button again, the ListView is updated with the item that were created. I have to do this every time I want the ListView to show the updated items I just created.
How can this happen? Given the same onCreate() method is called when I press the button. Why does going and coming back update the ListView?
ANSWER: I was populating the ListView before I got a response from the server, hence, the ListView has incorrect information. The response was received by the time I went back and started the activity again. That's why now the correct information was there. To solve this I populated the the ListView after I got a response from the server.
Comment: Do you go back using a android back button or something else?
Comment: because you load listView @onCreate >> after creating new item (data) reload listView at that point OR @onResume()
Comment: I went back using a button that takes you to main activity not the android back icon.
Answer: Your Activity with ListView is resumed it was not destroyed so it wont start afresh you have two alternatives

Override onResume method and load your data there probably using network connection again in your ListViewActivity.
The easy one,  Override onBackPressed in your add item activity and start the activity with listView like this:
@Override
public void onBackPressed() {

    Intent intent=new Intent(this, YourActivityWithListView.class);
    startActivity(intent);
}

Comment: The onCreate method AND the onResume is called every time I start the listView activity. I checked this putting a toast message in both methods and starting the listView activity and both appear.
Comment: Okay then check your logic somewhere else, butc `onCreate` cannot be called when resuming an activity.


How can I predict now the heat sinks that will appear in winter?

Question: I've just moved into a house where I'm concerned that an energy audit might find problems.  The clue is that the windows appear to be old single-pane windows.  Once it's cold out I can borrow an infrared camera and go around checking to see how bad things are and exactly where the greatest heat losses are.  But it's hard to install new windows in winter.  What can I do now to anticipate where the problems will be?
Comment: It's called "window inserts". You could probably google that... or, here's a good site that explains that method of retrofit:  https://www.treehugger.com/sustainable-product-design/amp/save-your-windows-and-your-money-indow-window-inserts.html
Comment: If in the winter you would determine that you have an unacceptably  large heat loss through your windows, then you would not be under any obligation to immediately install new windows, right? Wait until you get the results of this energy audit.
Comment: @JimStewart - I get depressed when I am living in a drafty house. Where I live it's a long winter and workmen will not, in my experience, replace a window in winter.
Comment: Generally, the best energy retrofit (from best to least) is: 1) fixing air leaks, 2) adding attic / ceiling insulation up to 16" - 20" thick, depending on your location, 3) adding wall insulation, 4) adding floor insulation, 5) adding retrofit single pane glass to existing single pane windows, 6) replace single pane windows with double pane windows.
Comment: @LeeSam - Thank you.  If I ask a separate question, how to add single pane glass to existing single pane windows, will you post an answer?  Maybe you have a link to a good how-to?
Answer: The general principle to use is that actual air leaks are a lot worse than just having poor insulation.
Look around your doors, windows, plumbing, attic/basement/crawlspace access hatches, fireplace, and anywhere else where there's a hole in the wall. Anywhere you feel air movement is an issue. Anywhere you can see daylight (that's not glass) is an issue.
Comment: Yeah, (well-maintained) single planed glass isn't as bad as people think, to the point where upgrading to double-paned windows doesn't have a great return. It's not as good as double-paned, it's just not worth upgrading in most cases.
Comment: @user3757614 I agree. We have priced the cost of replacing single pane windows with double pane and the payback is 40-50 years.
Comment: So, you're saying that single pane glass is not a deal breaker for keeping warm if I sit on an arm chair or sofa that's placed near the window (as long as there are no gaps around the frame)?
Comment: As a side note, really old houses were built assuming people would be wearing sweaters indoors, have heavy curtains, and keep the heat low during winter. Modern construction techniques assume people want to be comfortable in a T-shirt in the dead of winter. While bringing your home up to modern standards would be nice, adjusting your expectations would be cheaper.
Comment: That is a very good point about thick curtains.  I think that is something I neglected to do where I was living last year, which I did do in my previous house.
Answer: My answer is old school but it has worked for me many times. Get a roll of that semi clear plastic and tape a piece to the entire inside window frame, basically sealing it. Any air leaking will either bow or suck in the plastic. you can then work on fixing any leaks and will know when you've succeeded because the plastic will quit moving.
here is a link to the type of plastic I used.
https://www.amazon.com/Premier-Clear-Plastic-Cloth
I also used the blue painters tape so i wouldn't damage the walls or frame.
Comment: I used the blue painter's tape.
Comment: Somehow I missed this.  This would also be worthy of a green checkmark.  Thank you very much.
Comment: Do this to all the windows. It will definitely stop the drafts. I did it in a house I lived in in Grand Rapids, cut the heating bill in half.
Comment: The plastic taping procedure you're recommending -- is it a diagnostic, or is it a remediation, or both?  Can you post a link to the type of plastic and the type of tape?  Also, do I tape it to the window frame (not the edge of the wall)?
Comment: It ended up being both because we were renting and the owner had no intention of installing new windows. I did add some weathering stripping around the doors because we didn't want to keep the plastic up there. You can tape the frame or wall, whichever give you a better seal. If you suspect a leak between the frame and wall, then tape the wall.
Comment: You didn't want to keep the plastic up -- was that to prevent moisture getting trapped between window and plastic?  They sell kits and I have tried them, but the plastic is so thin it ended up not making a big difference.  I felt cold whenever I sat near a window.  When you have a chance, would you post a link to the type of plastic and the type of tape?
Comment: I had updated my answer to include that. We didn't want to keep the plastic up around the door for easy access in and out. I know the kits you're talking about and the stuff I used was much heavier... actual drop clothes for painting.
Comment: How many mil?  In the sixties my family put very heavy plastic on the outside of each window, stapled to the frame.  It helped a lot.
Comment: I've used 1.5 to 3 mil.
Comment: Thank you.  What sort of tape?  I recently saw that electrical tape can easily remove veneer off furniture if one isn't careful.
Answer: One way is to heat the whole house so it is above the outside ambient temperature, say 24 degrees C, then use a thermal camera to take pictures of the outside walls and roof surfaces of the house.
Those walls, windows etc that are loosing heat faster than other surfaces or parts of surfaces show up. If the camera is calibrated then it will provide a scale showing the relative temperatures.


Ubuntu 20.04 Network Manager Wireguard DNS Leak

Question: I added my Peer-Config from Wireguard to Network Manager manually:
[Interface]
Address = 10.13.13.5
PrivateKey = key
ListenPort = 51820
DNS = 10.13.13.1, lan

[Peer]
PublicKey = key
Endpoint = domainname:51820
AllowedIPs = 0.0.0.0/0

I  get a successfull connection from wireguard. But I found out, that the DNS from Wireguard is not used. I get a DNS-Leak.
When I check the status from wg0. I get:
Link 14 (wg0)
      Current Scopes: DNS
DefaultRoute setting: yes
       LLMNR setting: yes
MulticastDNS setting: no
  DNSOverTLS setting: no
      DNSSEC setting: no
    DNSSEC supported: no
  Current DNS Server: 10.13.13.1
         DNS Servers: 10.13.13.1
          DNS Domain: lan

Wlan has:
Link 2 (wlp59s0)
      Current Scopes: DNS
DefaultRoute setting: yes
       LLMNR setting: yes
MulticastDNS setting: no
  DNSOverTLS setting: no
      DNSSEC setting: no
    DNSSEC supported: no
  Current DNS Server: 172.20.10.1
         DNS Servers: 172.20.10.1
          DNS Domain: ~.

And when I check my DNS requests via dnsleaktest.com I see that my Ubuntu uses the DNS from WLan and not from the wireguard. I read about to change the DNS Domain from Wireguard to "~."
When I make the change then I get a result that my ubuntu uses both DNS requests from Wlan and Wireguard. But I could not find any solutions to use only the DNS over Wireguard.
I read from a post from 2019 that this was a bug in Network Manager from Ubuntu. We are now in 2022 and is this bug still there?
One more info:
When I use the same config over my Phone I have no DNS-Leaks.
Comment: I see a Winegaurd question here with nothing to do with Ubuntu. Maybe ask them?
Comment: I found that this Issue is discussed directly in the gitlab from NetworkManager. The Issue is not yet done. The Issue comes from NetworkManager and not from Wireguard

Source: https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/issues/921
Comment: issue 921 was a bug in a recent version of NetworkManager. It is already fixed, it's not likely that you are using the version (although you don't specify).
Comment: My NetworkManager is in Version 1.22.10.
Answer: check ipv4.dns-priority and ipv6.dns-priority. Those need to be set to a negative value (e.g. -50), if you want to avoid DNS leaks. Read man nm-settings.
You can see the setting with nmcli connection show "$PROFILE". You get the $PROFILE name from nmcli connection. You can change the DNS priority with nmcli connection modify "$PROFILE" ipv4.dns-priority -50 ipv6.dns-priority -50.
As always, when you modify a profile that is currently active, then the changes only take effect after (re)activating the profile the next time (or doing nmcli device reapply). That means, do an nmcli connection up "$PROFILE" afterwards.
Comment: Hi thaller, thanks for your answer! I tried it and have still the DNS-Leak. And when I write the last step 'nmcli connection up $PROFILE, then the priority goes back to 0. and with priority of -50 I have still the DNS-Leak :(


How to remove all items in the end dimension without chunks being loaded?

Question: Me and my friend were playing on a minecraft server. We dedicided to build this sand/gravel duper:

 by Rays Works. Unfortunately we ran this overnight and when we went in the end to pick up the stuff the server crashed because of how many items there were. When we started up the server again, it crashed again. Any ideas to fix this? We would prefer a command soulution. We have also tried /execute as @e[type=item] at @s in minecraft:the_end run kill @s.
Comment: I wonder what could be done short of resetting the End dimension or at least the regions around the central island. You've definitely found yourself in a bind - to affect items in a chunk by any means, you must first load that chunk, and items in it.
Answer: There is no way to alter a chunk without loading it first. At least not "from within minecraft".
What you could try to do, if the end dimension as it currently is is super important to you and there is no way you just delete and regenerate it entirely would be to manually edit the chunk data with an NBT (=the format of the save files) editor like this one. (Or just search Google for "minecraft nbt editor", there are multiple different programs available.)
The format in which the data is stored is explained in detail in this article from the Minecraft Wiki.
But this looks to me like a HUGE pain in the butt, so I would only recommend it, if you absolutely need to restore the end dimension.
Also, it's a bit of a stupid question by myself, but don't you have any backups? If you run a Bukkit / Spigot server, it's pretty easy to set up your own little backup script that just copies the world saves to a different location in a regular interval. You'd just have to start the backup script when you start the server itself.
I'd generally recommend for the future, that you back up your world so you can revert things that went wrong, or recover your world after a crash.
Answer: It's quite easy: you go to NBTExplorer, find your world in appdata or wherever. Go to DIM1, which is the end folder, and find the chunk that is lagging your world. Now seeing the video I used this design so the spawn platform from my personal world(s) will always spawns at r.0.0.mca chunk 6, 0; this is where the platform will be and where the entities will be located, so all you have to do in this chunk is delete all the entities.
Note that in this chunk any entity will be deleted: item frames, minecarts, armor stands, etc. Anything that is entity based will be deleted. So assuming you don't have anything like that deleting the items is probably your best bet. Just go to entities and delete the entire archive so every entry of items. Now, depending on how many items there are, this could lag NBTExplorer, so be careful of that. As long as the items are not exceeding probably 1-10 million items, it should be okay - it will be incredibly slow but it should eventually get there.
Anyway, delete all the entities and hit Save once that is done: that chunk you deleted all the entities in should be fixed.
Note though, that if you get the wrong folder for the Overworld or the Nether then those entities will be gone potentially causing corruption, so I highly recommend a backup and then trying this. It's unlikely it will cause chunk errors but it's a possibility to take into consideration so just use at your own risk. Anyway, this should fix the end and remove the crashing.


GFCI outlet reads hot and neutral reversed regardless of correct wiring and successful test and reset?

Question: UPDATE - tested all the wires with a multimeter, WHITE - Neutral to GROUND - no reading, BLACK - Hot- to GROUND no reading, BLACK - Hot to WHITE Neutral no reading. When using a no contact voltage tester the  WHITE - Neutral is beeping and giving me a warning, the BLACK - Hot isn't and so is the GROUND. I traced all the junctions and they are all wired correctly and tests correctly.
I just installed a GFCI outlet to an outdated backyard outlet that was just conventional outlet without any protection. Upon testing with an outlet tester, it reads 1-RED 2-Yellow 3-off hot and neutral reversed. I tested the outlet TEST and tripped successfully, and then RESET properly. Then I tested it again with the outlet tester and still reads the same 1-RED 2-Yellow 3-off hot and neutral reversed. Should I be concerned? What is causing this?
Some context, this is a 3 wire (hot, neutral and ground), when I turned off the breaker circuit for this line, its associated with the garage lights, half bath lights, and the backyard lights. I connected the wires to the LINE connections of the outlet.
Comment: Did you check the voltage of the wires with a multi meter to verify which is hot and neutral?  You can't go by insulation color.
Comment: No reading (based on everything else) on White (presumed hot) to Ground and Black to White makes no sense. Are you sure you are using the multimeter correctly (correct mode, correct connections if the meter has more than 2)? Test it against another receptacle. But non-contact lighting up only on White matches the hot/neutral reverse because that means White is hot.
Comment: Yes, tested it on a different receptacle and is working, self tested it as well. It's on AC, V with ~ on top, probes were double checked and inserted firmly. I couldn't believe it either. The no contact tester reading the Neutral wire presumed hot may be indeed the issue here. I came to the conclusion this is beyond me now. It is not as easy as replacing a receptacle anymore. I am hiring a professional. Thanks for troubleshooting with me.
Answer: The three light testers are what Harper likes to call the Magic 8-ball. They give messages that are sometimes true, sometimes meaningless or even misleading. In this case, the message may actually be correct. What the message/lights you describe normally means is:

(Note that the sequence and colors will vary by model of tester.)

Left red light = Voltage between neutral and ground (not good)
Middle yellow light = Voltage between hot and neutral (good)
Right yellow light = Voltage between hot and ground (good)

So when you have Red/Yellow/off, that means:

Voltage between neutral and ground, so one of those is connected to hot (Hot/Neutral Reverse or Hot/Ground Reverse)
Voltage between hot and neutral
No voltage between hot and ground (Hot/Neutral Reverse or Hot disconnected)

The only possibility in common is Hot/Neutral Reverse, so that's what the key displays.
The first question is: What did the tester show with the old receptacle? My guess is that it had no ground hole so you couldn't (super easily, though not that hard really) test it with the same tester, or maybe it had ground and you just didn't think of it. I bet it would have shown Hot/Neutral Reverse but we don't know that for sure.
Since a GFCI normally only looks at Hot and Neutral and ignores ground, a GFCI will still work (including TEST and RESET) with a Hot/Neutral Reverse.
So the most likely scenario is that you actually have Hot and Neutral Reversed! To test this, use a multimeter to check voltage between each pair of holes in the receptacle.

If you get:

Hot to Neutral ~ 120V
Hot to Ground ~ 0V
Neutral to Ground ~ 120V

then you indeed have Hot/Neutral Reverse.
If you get something else, update your question and we'll figure it out.
If you have White to Line Hot and Black to Line Neutral on the GFCI then swap them. If you have Black to Line Hot and White to Line Neutral then the problem is at a previous receptacle or junction in the same circuit. I have found these reversals multiple places in my home from work done previously, presumably by the previous homeowner and not an electrician because that is Electrical Wiring 101.
Comment: Clarifying question: I am testing with a multimeter and say a ground to neutral (white wire) is reading 120v, and ground to hot (black wire) is 0v, then what you're suggesting is that a previous receptacle in this same circuit was reversed. Now instead of me trailing it all the way back is it safe to just swap them?
Comment: The old receptacle is indeed a three prong with ground except it is outdoors and not gfci which prompted me to change it since I plan to use that outlet for string lights and/or inflatable tub.

I followed the same wiring diagram from the previously installed outlet. Hot/Black wire to Line Hot, and Neutral/White wire to Line Neutral. Bare copper wire to green/ground.

The Old receptacle did show the same, Hot and Neutral Reversed Red/Yellow/Off. I did test everything before disassembly and replacement.

I should test it with a multimeter and get back to you guys. Thank you.
Comment: It is **not** safe to swap them because at least one prior receptacle has an actual problem. That problem may be on the incoming wires to that receptacle (what in a GFCI is called *line*) in which case that receptacle is *also* reversed, or it may be on the outgoing wires (what in a GFCI is called *load*) in which case it only affects this receptacle. But swapping when there is at least one reverse elsewhere is *wrong*. Or as they say, *two wrongs don't make a right* (but two Wrights make an airplane).
Answer: If the wires are actually reversed, then it is probable that they are interchanged at a junction point along the way.
It is probably not one continuous cable from the breaker panel to the outdoor receptacle. So follow it back and open each junction box to find the problem.


Url is not being read from appsettings.json

Question: Apologies in advance if I ask anything silly as this is all very new to me, but i essentially need to store a couple of hardcoded URLs that are living in the cs files into a json file.
This is not a web project, this project runs a series of selenium automation tests through NUNit its a .NETCore app
so My appsettings.json looks like:
{
  "Development": {
    "urlName": "https://dev.website.com"
  }
}

My Program.cs file looks like
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

namespace Automation
{
    class Program
    {
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddEnvironmentVariables();
                config.AddCommandLine(args);
            });

    }
}

Im basically creating a constructor in my startup "BaseTest" class, this is the class that gets run first before the test itself is executed the constructor is as follows:
  protected IConfiguration _config;

        public BaseTest()
        {
             _config = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();
            baseUrl = _config["urlName"];
        }

the idea is that once this line in the BaseTest class is ran, it pulls the URL from the json file
driver.Navigate().GoToUrl(baseUrl);

but its coming back as null, I know im missing something but idk what, or if im even in the right direction please help.
the appsettings.json file is also set to copy always
Answer: urlName is in a property/section named Development
var baseUrl = _config.GetSection("Development")["urlName"]

 Note : There are many other ways to do this in a typed manner, plumb it into .net core, integrate it more succinctly with DI and optionally using IOptions, however this is inline with what you had

If you had Microsoft.Extensions.Configuration.Binder nuget installed you could also conceivably do something like this
public class Development
{
   public Uri UrlName { get; set; }
}

...

var myConfig = _config.GetSection(nameof(Development)).Get<Development>();

If you wanted to use the options pattern one of many ways, add the Microsoft.Extensions.Options.ConfigurationExtensions nuget and do the following
services.Configure<Development>(_config.GetSection(nameof(Development)));


Print stacktrace with Log4j2 in JSON with JSONLayout in a single line

Question: I'm tryting to configure JsonLayaout with Log4j2. I would like to have the stacktrace in just one message in the JSON. I understand that I have to use the attribute "complete".
The example class that I have created is:
public class MyApp {

private static final Logger logger = LogManager.getLogger(MyApp.class);

    public static void main(final String... args) {
        logger.debug("Entering application.");

        try{
            int i = 0;
            int a = 5 / i;
        }catch(Exception e){
            //StringWriter sw = new StringWriter();
            //e.printStackTrace(new PrintWriter(sw));
            //String exceptionAsString = sw.toString();
            logger.error(exceptionAsString);
        }
    }
}

The the log4j2.properties is:
name=PropertiesConfig
property.filename = logs
appenders = file, console
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = JSONLayout
appender.console.layout.complete="false"
#appender.console.layout.compact = true
#appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=/var/tmp/propertieslogs.log
appender.file.layout.type=JSONLayout
appender.file.layout.complete="true"
#appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

rootLogger.level = debug
rootLogger.appenderRefs = stdout, logfile
rootLogger.appenderRef.stdout.ref = STDOUT
rootLogger.appenderRef.logfile.ref = LOGFILE

The output I'd like it:
[
  {
    "logger":"com.foo.Bar",
    "timestamp":"1376681196470",
    "level":"INFO",
    "threadId":1,
    "thread":"main",
    "threadPriority":1,
    "message":"Message flushed with immediate flush=true"
  },
  {
    "logger":"com.foo.Bar",
    "timestamp":"1376681196471",
    "level":"ERROR",
    "threadId":1,
    "thread":"main",
    "threadPriority":1,
    "message":"Message flushed with immediate flush=true",
    "throwable":"java.lang.IllegalArgumentException: badarg\\n\\tat org.apache.logging.log4j.core.appender.JSONCompleteFileAppenderTest.testFlushAtEndOfBatch(JSONCompleteFileAppenderTest.java:54)\\n\\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\\n\\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\\n\\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\\n\\tat java.lang.reflect.Method.invoke(Method.java:606)\\n\\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)\\n\\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\\n\\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)\\n\\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\\n\\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)\\n\\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)\\n\\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)\\n\\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)\\n\\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)\\n\\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)\\n\\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)\\n\\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)\\n\\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)\\n\\tat org.junit.runners.ParentRunner.run(ParentRunner.java:309)\\n\\tat org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)\\n\\tat org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)\\n\\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)\\n\\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)\\n\\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)\\n\\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)\\n"
  }
]

But I get:
{
  "timeMillis" : 1474362834903,
  "thread" : "main",
  "level" : "ERROR",
  "loggerName" : "test.MyApp",
  "message" : "Exception:",
  "thrown" : {
    "commonElementCount" : 0,
    "localizedMessage" : "/ by zero",
    "message" : "/ by zero",
    "name" : "java.lang.ArithmeticException",
    "extendedStackTrace" : [ {
      "class" : "test.MyApp",
      "method" : "main",
      "file" : "MyApp.java",
      "line" : 24,
      "exact" : true,
      "location" : "classes/",
      "version" : "?"
    }, {
      "class" : "sun.reflect.NativeMethodAccessorImpl",
      "method" : "invoke0",
      "file" : "NativeMethodAccessorImpl.java",
      "line" : -2,
      "exact" : false,
      "location" : "?",
      "version" : "1.8.0_91"
    }, {
      "class" : "sun.reflect.NativeMethodAccessorImpl",
      "method" : "invoke",
      "file" : "NativeMethodAccessorImpl.java",
      "line" : 62,
      "exact" : false,
      "location" : "?",
      "version" : "1.8.0_91"
    }, {
      "class" : "sun.reflect.DelegatingMethodAccessorImpl",
      "method" : "invoke",
      "file" : "DelegatingMethodAccessorImpl.java",
      "line" : 43,
      "exact" : false,
      "location" : "?",
      "version" : "1.8.0_91"
    }, {
      "class" : "java.lang.reflect.Method",
      "method" : "invoke",
      "file" : "Method.java",
      "line" : 498,
      "exact" : false,
      "location" : "?",
      "version" : "1.8.0_91"
    }, {
      "class" : "com.intellij.rt.execution.application.AppMain",
      "method" : "main",
      "file" : "AppMain.java",
      "line" : 147,
      "exact" : true,
      "location" : "idea_rt.jar",
      "version" : "?"
    } ]
  },
  "endOfBatch" : false,
  "loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
  "threadId" : 1,
  "threadPriority" : 5
}

Should I build an String to the message as I do in the code or how could I complete the throwable attribute in the log with all the stacktrace?
If I use this code:
   public static void main(final String... args) {

        // Set up a simple configuration that logs on the console.
        logger.debug("Entering application.");

        try{
            int i = 0;
            int a = 5 / i;
        }catch(Exception e){
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String exceptionAsString = sw.toString();

            logger.error(exceptionAsString);
        }
    }
}

I get almost which I want to:
{
  "timeMillis" : 1474542115319,
  "thread" : "main",
  "level" : "DEBUG",
  "loggerName" : "MyApp",
  "message" : "Entering application.",
  "endOfBatch" : false,
  "loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
  "contextMap" : [ ]
}{
  "timeMillis" : 1474542115573,
  "thread" : "main",
  "level" : "ERROR",
  "loggerName" : "MyApp",
  "message" : "java.lang.ArithmeticException: / by zero\n\tat MyApp.main(MyApp.java:23)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:498)\n\tat com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)\n",
  "endOfBatch" : false,
  "loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
  "contextMap" : [ ]
}

But, I guess that I could do it automatically without parse the stacktrace to String.
Answer: <JsonLayout compact="true" eventEol="true" stacktraceAsString="true" >

This will help.
Comment: It didn't. I am not seeing stack traces with this :<
Comment: Hi , using log4j 2.9.0 version and above will show stacktrace as a single line . suspect there was a bug on stacktraceAsString flag , on 2.5 version indeed setting stacktraceAsString=true not works .
Answer: I solved this using a custom Log4j layout:
@Plugin(name = "FlatJsonLayout", category = "Core", elementType = "layout", printObject = true)
public class FlatJsonLayout extends AbstractStringLayout {
    private final ObjectMapper objectMapper;

    FlatJsonLayout(Charset charset) {
        super(charset);
        SimpleModule module = new SimpleModule();
        module.addSerializer(LogEvent.class, new LogEventSerializer());
        module.addSerializer(Throwable.class, new ThrowableSerializer());
        module.addSerializer(ReadOnlyStringMap.class, new ContextDataSerializer() {
        });
        objectMapper = new ObjectMapper();
        objectMapper.registerModule(module);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    }

    @Override
    public String toSerializable(LogEvent logEvent) {
        try {
            return objectMapper.writeValueAsString(logEvent);
        } catch (JsonProcessingException e) {
            throw new IllegalStateException(e);
        }
    }

    private static class LogEventSerializer extends StdSerializer<LogEvent> {
        LogEventSerializer() {
            super(LogEvent.class);
        }

        @Override
        public void serialize(LogEvent value, JsonGenerator gen, SerializerProvider provider) throws IOException {
            gen.writeStartObject();
            gen.writeNumberField("timeMillis", value.getTimeMillis());
            gen.writeStringField("threadName", value.getThreadName());
            gen.writeStringField("level", value.getLevel().name());
            gen.writeStringField("loggerName", value.getLoggerName());
            gen.writeObjectField("marker", value.getMarker());
            gen.writeObjectField("message", value.getMessage().getFormattedMessage());
            gen.writeObjectField("thrown", value.getThrown());
            gen.writeObjectField("ContextMap", value.getContextData());
            gen.writeObjectField("ContextStack", value.getContextStack());
            gen.writeStringField("loggerFQCN", value.getLoggerFqcn());
            gen.writeObjectField("Source", value.getSource());
            gen.writeBooleanField("endOfBatch", value.isEndOfBatch());
            gen.writeEndObject();
        }
    }

    private static class ThrowableSerializer extends StdSerializer<Throwable> {
        ThrowableSerializer() {
            super(Throwable.class);
        }

        @Override
        public void serialize(Throwable value, JsonGenerator gen, SerializerProvider provider) throws IOException {
            try (StringWriter stringWriter = new StringWriter()) {
                try (PrintWriter printWriter = new PrintWriter(stringWriter)) {
                    value.printStackTrace(printWriter);
                    gen.writeString(stringWriter.toString());
                }
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
        }
    }

    @PluginBuilderFactory
    public static <B extends Builder> B newBuilder() {
        return new Builder().asBuilder();
    }

    public static class Builder<B extends Builder> extends org.apache.logging.log4j.core.layout.AbstractStringLayout.Builder implements org.apache.logging.log4j.core.util.Builder<FlatJsonLayout> {
        Builder() {
            this.setCharset(StandardCharsets.UTF_8);
        }

        public FlatJsonLayout build() {
            return new FlatJsonLayout(this.getCharset());
        }
    }
}

The class has to be on the classpath of the application. It can then be configured in the log4j2.xml like this:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <FlatJsonLayout/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

Comment: can you share which log4j version is in used  ?
Comment: We are using version 2.13.3, but I believe this should work with any version >= 2.0.0
Answer: set compact="true" and eventEol="true" works for me
 <JsonLayout complete="false" compact="true" eventEol="true">

Answer: On properties files appender.console.layout.complete is boolean not string so change:
appender.console.layout.complete="false"

to:
appender.console.layout.complete = false

Answer: using today - log4j version 2.9.0 or above will print stacktrace as single line when setting stacktraceAsString="true"


Is my doorknob handleset installed correctly?

Question: I recently had a new front door installed and the installer also installed a new doorknob handleset (it's a Schlage F60 V CAM 619 ACC).
The new door is weather and impact resistant so it opens out and has some weather stripping to seal it firmly.
Detailed steps to reproduce my problem:

Stand outside with door properly closed and the deadbolt locked
Depress the thumb piece fully

At this point, the door jumps as if it's about to swing open toward you, makes a thud, and is only stopped by the deadbolt being contained within its strike plate. The latchbolt is no longer contained within its strike plate.
It seems to me that a storm/impact should not be prone to movements like this. I'm thinking that debris could hit the thumb piece during a storm and compromise the seal (you never know).
We've all probably seen and used doors like this. My question is whether this is correct or proper? Should I have the installer fix this? Should it simply be a matter of moving back the deadbolt's strike plate (towards the interior) to prevent the wiggle room after the thumb piece is depressed?
Comment: If you would move the deadbolt's strike plate back, you might have trouble with the deadbolt operation. To avoid the jolt when unlocking, just unlock the deadbolt first.
Comment: Over time the door seal will probably reduce in thickness and resistance to compression, and this should reduce the jump. If the jump does not decrease with time, then that would implicate the hinges. But maybe some modern weatherstripping seals well, but is soft. Is it possible to easily remove the weather sealing? If so, you could remove it temporarily and see if the springiness remains.
Comment: @cfx Did you figure it out ?
Answer: There is always a little difference where the strike catches and the deadbolt hits the edge of the keeper. If there wasn't, the deadbolt would be difficult to latch. The weatherstripping needs to be compressed when the latch sets into the strike allowing the room needed to let the deadbolt engage easily. When the latch is depressed, and the door releases the little bit that it does, the weatherstripping should still be compressed enough to do its job.
FWIW, the odds of a limb hitting the thumb latch and creating a problem by doing so is very improbable, in my opinion.
Comment: And if the OP is still concerned about the improbable press of the thumb piece they could determine to replace the door knob with one that requires a hand turn !!!
Answer: While I would consider Jacks answer a pretty good answer for the most part - the part of your post that speaks to me is :
"the door jumps as if it's about to swing open toward you, makes a thud"
I am thinking the door framing is not properly done - so the hinges have force behind them like a spring - I have experienced this with one door in particular before. The Framing is probably angled ever so slightly on one end. I am guessing that originally your previous door was probably opening inward and so the installer had some trouble when they placed the new frame.
I am not sure where you are in the world that you are concerned with wind and impacts that you desire the outward opening door - maybe South Florida or Tornado Alley.
Pro's and Con's Outward opening door.
Comment: I installed some expensive solid oak doors with 3/4" or 7/8" thick oak jambs. These jambs were so stiff that they could not develop waves and twists in them even though the 2x4 framing of the rough opening (bedroom doors) was crooked, out of plumb, and twisted. A competent carpenter might have done some surgery on that framing, but I didn't know how to do that. Later I got some less expensive oak veneer doors with soft wood jambs. Trying to install these in the same type of rough openings was a nightmare for me. I had one door that was springy; I finally got it to just barely tolerable.
Comment: Was this a prehung door? Presumably even if the framing is a little off plumb the installer would shim the jamb so that the door and jamb are plumb, square and straight?
Comment: @JimStewart - you would think square and straight would be done. I did make the assumption the door framing was replaced - because he said the new door opens out (change of direction). So I conferred from that statement it was a new frame too - might be a bad assumption on my part. Either way though - it is possible the door is not square and so he has that 'spring' action. I have had one prehung do this exact same thing .


Cross compiling libcurl and openssl for A9331

Question:
I am using a dragino product that is basically an arduino Yun running openwrt Linino for an IoT related project. I get data from the arduino part and send json to a firebase DB using libcurl (and HTTPS) in a C program on the openwrt part.
I have managed to setup the cross-compiling toolchain for AR9331 and I can compile simple programs relying on libc. However I need to cross compile libcurl with ssl support in order to send data to firebase with HTTPS. This means that I need to crosscompile openssl. However, i am not sure which option I have to pass to the Configure script in order to set it correctly. Can I compile a static library from openssl and curl so that my program doest have any dependency ? Or is it a bad practice to do so ?
In my last attempt to compile openssl with:
<code>./Configure  --prefix=$(realpath $LIBPATH)/openssl  linux-mips32
</code>
where $LIBPATH is the location of my lib in the toolchain.
makes returns the following :
<code>apps/speed.o: In function `speed_main':
speed.c:(.text+0x4424): undefined reference to `AES_set_encrypt_key'
speed.c:(.text+0x443c): undefined reference to `AES_set_encrypt_key'
speed.c:(.text+0x4454): undefined reference to `AES_set_encrypt_key'
speed.c:(.text+0x7530): undefined reference to `AES_encrypt'
speed.c:(.text+0x7544): undefined reference to `AES_encrypt'
./libcrypto.so: undefined reference to `AES_set_decrypt_key'
./libcrypto.so: undefined reference to `getcontext'
./libcrypto.so: undefined reference to `setcontext'
./libcrypto.so: undefined reference to `makecontext'
./libcrypto.so: undefined reference to `AES_decrypt'
collect2: error: ld returned 1 exit status
Makefile.shared:180: recipe for target 'link_app.gnu' failed
</code>
How can I compile openssl for the AR9331 ? If i try to add the host flag my architecture is not recognised.
EDIT: Maybe the best method to avoid dependencies problem is to create an ipkg package (openwrt package manager)
I will try it and inform you if this works.
Comment: @FilipKočica if you edit something, do it carefully please. The `` tags don't hurt in normal text, but they become visible in a code block. Also, use `` if a code block isn't actual code.
Answer: Those packages should be present in Openwrt by default.
Have you tried downloading them with opkg? maybe you have to check you the repos you are pulling from.
As a last resort you can download OpenWrt source code and build this two packages and then get the .ipkg to your device, OpenWrt build system takes care of getting the toolchain and building everything for you.


What is the full list of git diff options

Question: On another question I found a mention of this command:
git diff --merge

However, upon looking at the diff man page or the --help documentation, I can't find any explanation of the --merge option.
Some commands can use options from other subcommands, like git show that states in the --help page:

The command takes options applicable to the git diff-tree command to control how the changes the commit introduces are shown.

Does git diff uses options from other git commands like git show does? If it does, is it stated somewhere in the docs? Or its an oversight?
Answer: git diff uses all the same options as git rev-list (in fact, many git commands do this, either by running git rev-list directly—many are shell scripts—or by calling it from their source code)..  So --merge here is this one, from git-rev-list:

   --merge
       After a failed merge, show refs that touch files having a conflict
       and don't exist on all heads to merge.

Comment: I haven't found it documented properly.  (I think the git documentation leaves something to be desired, in general. :-) )  I tried running `git diff --merge` and got an error message (not being in the middle of a merge) and traced it back from there in the source, just to confirm.
Comment: Nice! Do you know if it is stated somewhere, or is it just general knowledge?
Answer:
Does git diff uses options from other git commands like git show does?
If it does, is it stated somewhere in the docs? Or its an oversight?

Git 2.43 (Q4 2023), clarifies, regarding git diff vs. git show:
See commit 4fbe83f (20 Sep 2023) by Han Young (eseedo).
(Merged by Junio C Hamano -- gitster -- in commit e076f3a, 29 Sep 2023)

show doc: redirect user to git log manual instead of git diff-tree
Signed-off-by: Han Young

While git show(man) accepts options that apply to the git diff-tree(man) command, some options do not make sense in the context of git show.
The options of git show are handled using the machinery of git log.
The git log(man) manual page is a better place to look into than git diff-tree for options that are not in the git show manual page.

So git show --help now changes its man page:

Some options that 'git log' command understands can be used to control how the changes the commit introduces are shown.

It no longer references git diff-tree as in the OP.


Anchors for concrete - what to use on a concrete ceiling?

Question: When it comes to concrete, besides metal anchors like lag shield we have the plastic ones being: wall plug, plastic anchor and ribbed anchor. Is there any other (non-metal) anchor that can be used on concrete?
Plastic anchors are by far the most popular. You get them when buying stuff to hang on the wall.
However in my research it seems that wall plugs (below) are better rated (higher weight support).

Source: https://www.rolliers.com/blog/post/helpful-tip--choose-the-fastener-right-for-the-job
While wall plugs are not as or even more popular than plastic anchors if they are better rated? I've never received them in products purchased, it has always been plastic anchors.
Personally, it seems to me they would just slip (especially from the ceiling) as they seem to be smooth outside.
I have a project to hang a wood panel to the (concrete) ceiling. I was checking about non-metal anchors because metal anchors wouldn't allow multiple replacements of this panel and also usually requires big holes/damages. I know Tapcon would be the most recommended, but I wouldn't be able to reuse the hole when replacing the panel so it's a no for me. I found these three types listed above, and also read about one with/made of "lead" (if not mistaken).
So, I'm curious as to why one would use plastic anchors when ribbed anchors look to be better, and why use ribbed anchors when wall plugs are rated for heavier stuff.
Like everything, I know there are specific situations. However I could not find when one would not use a wall plug and instead go with a plastic (non-ribbed) anchor.
For hanging stuff on the ceiling, which non-metallic anchor would be the best?
I appreciate any insight on that!
Comment: You might want to talk to a local building official about your plans and see what they say.  You don't seem to be receptive to the feedback you're receiving about your plans for this ceiling; but a building official isn't just feedback, it's what they'll allow.  I think you should be looking at attaching furring strips with tapcon-like fasteners, or doing something more substantial like threaded rod (requiring some tricky concrete work in a ceiling.)  I understand why you want to avoid that, but seriously, it's a ceiling.  If it falls the consequences will be serious.
Comment: Many of the anchors in your picture are for drywall and/or hollow walls and won't work on solid concrete.
Comment: If you'll take a wander down the "screw aisle" of your local big-box store, you'll not see any of those (except, perhaps, the lag shield) in the section dedicated to anchoring things into concrete. Pick from among _those_ fasteners. I don't think any of these would do to hang more than streamers from a drywall ceiling.
Comment: Notice that in your linked post, _only_ the toggle bolt is listed for ceiling application. Of course, that only works if you have a hollow behind the surface for the toggle to expand into. I don't believe any of these anchors will work for you. You can go ahead and use them, but it's above _your_ head, not mine.
Comment: @JeffWheeler your recommendation sounds very much like the answer I gave to his other question.
Comment: @Mattman944 I edited the picture to show only the ones I wrote about. Thanks!
Comment: Just because you delted some does not mean they will work or be safe for your intended purpose. You don't mention a load.
Comment: do you own the concrete ceiling?
Answer: It is risky ,no matter what you use. A concrete floor/road is basically in compression. The bottom of your ceiling is in tension and concrete is generally considered to have no or poor tensile strength. There should be steel rebar in the ceiling , I would verify the presence and amount of rebar before putting holes in the concrete. Each of those anchors works by putting compressive force on the concrete in the concrete ; this compressive ( expansion ) adds to the tensile stress. I would check with local contractors and find out what they do.
Answer: I believe you will find that the toggler alligator AF6 or larger are suitable for insertion in concrete and have a rating for both shear and pullout.
They can also be reused.
https://www.amazon.com/gp/product/B0051IAWM2/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1
Comment: This is very interesting! It looks like a good product, and they even state concrete ceiling as an application. I wonder why everybody else says I should go with stronger hold using metal anchors though.
Comment: I've used only them for years. They work in drywall, brick, and concrete. And they can be removed and patched.
Answer: To address the anchors shown in your picture, basically they're ordered from "cheap and useless" up to "pricey but actually holds". The basic wall plug, in my experience, pulls out so easily that even when they come included with things you're going to attach to a standard drywall wall, you're better off throwing them away and using a better anchor. (Personally I like the "Wall Driller" style of zinc screw-in anchors for those jobs.) The plastic anchor is a tiny step up, but basically still not worth using even on a wall. The ribbed anchor has a bit more grip, but is still only "meh". The lag shield and the expanding lead anchor can, when used right, hold a lot of weight, but they require a really big hole and are nearly impossible to remove.
As for your specific scenario, there are some unanswered questions. Is "non-metallic" actually a requirement, or is it just that that metal anchor is inappropriate for the reasons given. Also, do you plan to hang additional weight from this wood panel when it's in place, or is it just the panel itself? Different anchors for concrete can have wildly different load ratings.
If non-metallic is not strictly a requirement, an anchor that has tremendous load rating and makes it easy to swap out your wood panel would be the expanding wedge anchor. The cons are that they require a biggish hole and are kind of a pain in the ass to get installed nice and flush. They're not easy to remove once they're in, but nowhere near as bad as lead anchors. On the other hand, they can take ridiculous amounts of weight, and once installed each anchor leaves you with a threaded rod sticking out of the ceiling so you can use flat washers and plain old nuts to attach your panel. To my mind, that's hard to beat for ease of replacing the panel with another identical one in the exact same spot every once in a while.
Keep in mind that any setup where you have hollow plastic anchors in the ceiling and then you drive screws directly into the anchors is going to be weakened every time you remove and replace the panel, because the screws bite into the plastic and sort of "shred" it a little bit more every time. This holds true no matter what the initial load rating of the anchor is.
Depending on the overall scenario, building a low-profile frame that has bolts or clips or whatever to hold the wood panel in place, and then attaching that frame to the ceiling with Tapcon screws, might be worth considering.
Comment: Thank you! So you'd say that Tapcon screw (your last paragraph) would be a better overall option than expanding wedge anchor? I believe the expanding anchor still holds more than Tapcon, right? However you think that Tapcon is easier overall? Thank you!
Comment: If you prioritize long-term convenience and minimum damage to the concrete, yes. Build a frame, mount the frame permanently using Tapcons, and use clips or wood screws or window latches or whatever to attach the panel to the frame, so that it's easy to swap the panel out without disturbing the concrete anchors at all. Wedge anchors can hold *way* more load than Tapcon screws, it's true, but that only matters if you need this rig to support many hundreds of pounds. If `Tapcon rating × number of Tapcons > the load you need it to hold`, wedge anchors are overkill.
Comment: But if you really want to avoid building a frame, and/or you need to support a huge amount of weight, wedge anchors provide maximum strength while still giving pretty good convenience for swapping out the panel in the future with minimal risk of messing up the anchors... but at the expense of bigger holes in the concrete. So it really depends what your priorities are. Without more information about the overall project, I'd be shooting in the dark if I told you "just use this method". (BTW, if my answer solves your problem, don't forget to hit the "Accept" checkmark. Thanks!)


.NET Configuration Class save problem

Question: When I change some config property and call Save() method to configuration object, and then change some config property and call Save() again I get exception because config was changed.
Text of exception: "The configuration file has been changed by another program."
So if user in run time changes something and do save and than changes something again and do save my app will throw exception. Am I right?
Shouldn't I be able to save config multiple times?
EDIT: Provided code sample.
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            map.LocalUserConfigFilename = UserConfig;
            map.RoamingUserConfigFilename = RoamingConfig;
            map.ExeConfigFilename = AppConfig;

            System.Configuration.Configuration combinedConfigFile = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoamingAndLocal);

            AddinConfiguration combinedConfig = (AddinConfiguration)combinedConfigFile.GetSection(sectionName);
            combinedConfig.Config = combinedConfigFile;
            return combinedConfig;

I have injected property Config into my section so I can use it to save configuration like this.
mySection.Config.Save();

Comment: Really strange error. I already made some app settings editor and I never runned into this error. Did you wrote the configuration sections you are trying to save or is it sections from the framework or is it sections designed through a code generator? Also are you opening the file as a current application configuration or as a mapped application configuration? A code sample could help too.
Comment: @Ucodia, I'm opening file as a mapped application configuration. I have written my own configuration section classes. I'll provide code sample in question above.
Answer: The documentation states: "If the configuration file has changed since this Configuration object was created, a run-time error occurs." So after Save(), you need to destroy the configuration object and recreate it for multiple save operations to work normally.
Comment: No not at all. It is also ill advised to use singleton instances with config since it makes unit testing quite difficult.
Comment: Yes, I read that too, but it seems strange to me. So I cannot have singleton config object in my application?

.NET Configuration Class save problem


Insert empty value using Bindparam without error Incorrect Integer value

Question: I want to insert some data into my MySql table using PDO. If it's not empty it will have Integer datatype so i use PDO::PARAM_INT, but the problem is this data is not required so sometimes it's empty.
It make me have an error:

PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value.

So is it anyway I can pass this empty value variable into my database without having error when it have empty value? here's my code snippet:
<code>$stmt = $db->prepare("INSERT INTO table (column) VALUES (:column)");
$stmt->bindParam(':column',$_POST['value'], PDO::PARAM_INT);
$stmt->execute();
</code>
Answer: An empty string is incorrect integer value all the same. Although been permissive in the past, nowadays MySQL tends to be more strict with types, enforcing the STRICT MODE by default, hence not accepting an empty string for the integer field anymore.
Besides, PDO::PARAM_INT doesn't cast your values.
Therefore, you have to cast them manually
In case you want to retain a possible NULL value, convert your input like this
<code>$value = is_null($_POST['value']) ? null : (int)$_POST['value'];
</code>
If you want to just convert to integer unconditionally, then just make it
<code>$value = (int)$_POST['value'];
</code>
Both snippets will convert an empty string to 0 which will be gladly accepted by MySQL
Comment: so it's not possible to use Bindparam in this case?
Comment: nice, but may i know why bindparam is ugly and useless? is it batter to sanitizing than using bindparam or there is any saver way than this?
Comment: there is no difference between NULL and null, so I dont see how it would be solved that way
Comment: also casting a null to int , will store 0 in the db, it will not set the field to NULL
Answer: In My Case I use like this:
<code>if(empty($_POST['value'])){ $value = NULL; } else { $value = $_POST['value']; }
$stmt->bindParam(':column', $value);
</code>
It works Best for me, try from your side :-)


Ubuntu one music showing 'unknown artist' and 'unknown album' for most songs

Question: I successfully uploaded 23GB of music from my hard drive (after lots of waiting) to Ubuntu One except that only ~20 artists/albums are showing up correctly and the rest are 'unknown'.  They are (almost) all mp3 files and the correct info shows up when loaded into a media player, including Rhythmbox and Banshee.
Thus, this is not a problem with the files themselves (info also shows up correctly under properties->audio in Nautilus) but rather a problem with U1.  There seems to be other threads with this issue but no answers, except for the excuse: "Ubuntu One does not currently support m4a files" which is clearly not the issue.  This is of particular concern for streaming to my iPhone since all the music is disorganized, which really defeats the whole purpose of the app.
I should note that most song titles are correct (except may contain a song number in front of them) which from what I understand is due to the fact that generally the file name is the song name.  Any help with this is greatly appreciated.
Comment: Exactly the same here, 10 of 262 albums are recognized correctly. Upload finished a few hours ago. I will let you know whether the problem persists or not.
Comment: I'm having the problem as well.  Is there any work-around?
Answer: The part of our system that scans the track data in music files is delayed as we have lots of files to scan. This may take some time. Please let us know if you still have this problem.
Answer: Over the holidays there was a problem with the scanning server. It has been fixed, and you should get the proper tags for yours songs within the next 24hs.
Sorry for the problems it caused you :(
Comment: There still only seems to be only proper tags for the same 20 artists.  Is there something I need to do to update the tags?  I'd rather not have to re-upload all of my music if possible.


Facebook (web) dialog started immediately dismissing on iOS6/SDK3.1|3.2

Question: I had some code to post to a friend's facebook wall that upon the deprecation of this via Open Graph I changed to use the deprecated headers and Facebook dialog to include the user in the posting. That has been working for weeks, but seems to have stopped working (worked fine Tuesday, failed Wednesday) in production application (i.e. no code change or re-build.)
I've spent hours trying all sort of things (running on main thread, asserting sessions are live, re-writting to SDK 3.2, uninstalling app/re-installing, completely changing the dialog type and post contents) to restore the ability but whatever I do the dialog immediately dismisses. [Note: There are no developer alerts on our app, and I believe that none of the app settings have changed.]
Here is the code. The facebookManager "performConnectedAction" is from the Facebook sample to ensure an active session (and I assert it w/o problem.) :
NSMutableDictionary *wallPost = [NSMutableDictionary dictionary];

  // Content populating not show (and I've tried various simplifications)

// Who to...
[wallPost setObject:_selectedUser.id forKey:kFB_FIELD_TO];

[facebookManager performConnectedAction:^{
    FBSession *facebookSession = facebookManager.facebookSession;
    Assert( facebookSession.isOpen, @"Need an open Facebook session.");

    [FBWebDialogs presentFeedDialogModallyWithSession:facebookSession parameters:wallPost handler:^(FBWebDialogResult result, NSURL *resultURL,NSError *error) {
        if ( !!error ) {
            [self logEventWithFormat:@"Failed to invite on Facebook [%@]", error];
        }
    }];
}];

Basically ... not only does the dialog flash up/down, but no callback is given (no error or result provided.) All other parts of the Facebook application continue to operate (our graph calls, our Facebook Friends dialog, and so on.)
I'd appreciate any thoughts on ways to investigate this further. I have filed a bug report:
http://developers.facebook.com/bugs/165456656937602?browse=search_5130e2d7663dd6543665811
Comment: I tried to find why it does not work. You can read what I found there: [Bug > Facebook dialog stopped appearing (and no error callback invoked)](https://developers.facebook.com/bugs/165456656937602?browse=search_5130e2d7663dd6543665811)
Answer: I had the same issue and fixed it by delaying the method call like this. My method is fbWallPost
[self performSelector:@selector(fbWallPost) withObject:nil afterDelay:0.5];

Comment: Looking promising, thank you! Will do more testing and mark as correct (holding my nose to whatever Facebook SDK issues causes this to fail) once I've tested on a few more devices. Thanks for posting.


Changing a light switch with 9 wires , just a normal 1way

Question: I am trying to change a light switch from a dimmable to a normal 1 way light switch. There are 3 red 3 black and 3 earth's. One red black and earth are producing current the others are not. Can someone tell me where the wires should go?
Comment: They go in the same labelled terminals as the switch you just removed. Hope you took pictures... [otherwise you have to start testing where each cable goes]
Comment: Has any other light fixture or outlet stopped working? I'm betting at least one set is a continuation of the "hot" feed.  But at this point you need to call in a licensed electrician.
Comment: I stupidly didn't take photos
Comment: The second picture makes me considerably more wary of saying anything about the first picture. What country is this?
Comment: I am in the uk does it look different from what you would expect
Comment: I wouldn't expect that second photo at all, but then I'm not a qualified sparky, so I'll leave potential explanations for wiring it like that to those who are.
Comment: Hey thanks everyone yeah just the other bedroom has stopped. I will call in an electrician not the simple swap light switch I'm use to
Answer: It looks like lighting wiring, but the variety where the power and onward lines come into the switch, with only a spur to the lamp.
All the earths always go together, to each other and also to anything else in the box that has an earth terminal, including switches, receptacles or the box itself.  "That was easy", push them into the back of the box and forget them.
Black is "old school colors" neutral, and since we don't have a switch leg we can be confident all black wires are actually neutral.
The cable that has power: is certainly the line coming in from the supply. (i.e. either straight from the consumer unit/service panel, or another switch or lamp).  That will be "always-live".
Another cable carries "always-live" power onward to serve other switches or lamps in a similar way.
The third cable goes to the lamp.  Its neutral must be always connected.  Its live (red) wire is connected to "live" when you want the lamp to be lit.  That is the role of the switch, at the risk of stating the obvious.
So the two "always-live" red wires (supply, and onward to other switches/lamps) need to go together.  (i.e. in the same lug of the switch, if the switch is rated/approved for 2 wires per lug).  "Lamp" goes on the other switch lug.
Should you experiement? Generally no, as many combinations will seem to work but set the stage to kill you later.  But in this situation, once earths and neutrals are properly connected, experimenting with arrangements of "live" on a switch is harmless. Well, assuming you turn the circuit breaker off before touching or arranging wires!
The final arrangement will be with supply and "onward" connected to one switch lug, and lamp to the other switch lug.
Comment: Hi again , can I ask once you find where the red wires go. Light red wire into L1 , and supply and outward red into common. How.do you connect the 3 black neutral wires.  I know these were connected previously with a wire strip but I read two wires shouldn't go into the same whole.of a wire stripe so what's the best thing to use to connect two wires together I.e. the neutral supply and neutral light wire , then the supply out wire or can all 3 go together
Comment: USA has a "1 neutral per hole" rule for panels (consumer units), but it does not apply to the UK.  Depends on the wire strip, you have to check the labeling and instructions for them. I believe in this setup, all neutral wires need to end up connected to each other.


How to get count_id and rating_evarate from table?

Question: How to get count_id and rating_evarate from table?
I want to count the id and get rating evarate from the table bellow .
how can I do it in mysql .
SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `rating`
-- ----------------------------
DROP TABLE IF EXISTS `rating`;
CREATE TABLE `rating` (
  `id` int(11) NOT NULL,
  `rating` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of rating
-- ----------------------------
INSERT INTO `rating` VALUES ('1', '5');
INSERT INTO `rating` VALUES ('2', '0');
INSERT INTO `rating` VALUES ('3', '0');
INSERT INTO `rating` VALUES ('4', '0');
INSERT INTO `rating` VALUES ('2', '0');
INSERT INTO `rating` VALUES ('1', '0');

Comment: Is the last image your expected output? If yes then it is wrong for the given data.
Answer: you can try this query:
SELECT id, count_id, AVG(rating_average) FROM rating GROUP BY count_id;

Comment: now i get that i think i did not understand, Take a look at hims answer.
Answer: You can try this:
SELECT ID
     , COUNT(ID) Count_ID
     , AVG(Rating) AS rating_average
FROM rating
GROUP BY ID;

See this SQLFiddle
Comment: @mingfish_004 - What's your expected result for the given data?


How do I fix a 404 (Not Found) error in a CRUD application?

Question: I'm trying to add an update function to my MERN CRUD app, and I can't get the Update to work properly. I can't figure out how to build either the function to handle the update or the API to carry the command between the app and the database. Whenever I hit submit, I get a 404 error.
Here is my function to handle the update from the page:
  onSubmit = e => {
    e.preventDefault();
    const updatedObj = {
      bucketListItem_name: this.state.bucketListItem_name,
      bucketListItem_comment: this.state.bucketListItem_comment,
      bucketListItem_completed: this.state.bucketListItem_completed
    };

    API.submitItemEdits(this.props.match.params.id, updatedObj)
      .then(res => console.log(res.data))
      .catch(err => console.log(err));

      this.props.history.push("/");
  };

Here is my API:
  submitItemEdits: function(id, updatedObj) {
    return axios.post("/api/bucketList/" + id, updatedObj);
  }

And in case they're needed, here is the controller:
  update: function(req, res) {
    db.bucketListItem
      .findOneAndUpdate({ _id: req.params.id }, req.body, {upsert: true})
      .then(dbModel => res.json(dbModel))
      .catch(err => res.status(422).json(err));
  }

And here is my route:
router
  .route("/:id")
  .get(listController.findById)
  .put(listController.update)
  .delete(listController.remove);

I've been able to console.log the info for the updatedObj, so I'm pretty sure the info from the form is making it as far as the API. And I'm pretty sure it's something small that I'm overlooking.
Many thanks in advance for you help.
Answer: In your router ,you don't define post method,
In submitItemEdits funtion, axios should use "put" instead of "post" method
Answer: axios.post will send data to the router.post('/api/bucketList/:id' , ()=>{}) route.
So it won't send to the correct router. To update, you need to send data to the router.put("/api/bucketList/:id", ()=>{}).
To do this you need to use axios.put() instead of axios.post()


-Wall: command not found

Question: im trying to compile two files on my bash : Main.c , DB.c
this is how i compiled them and they gave me no errors : gcc -c Main.c  DB.c`
so they should have created Main.o and DB.o .
now im trying to compile Main.o and DB.o :  -Wall Main.o DB.o
but when im trying to compile these the bash gives me that -Wall: command not found
anyone encountered this issue ?
Answer: -Wall isn't a command1, it's an option (show all warnings) to the gcc command. From man gcc
   -Wall
       This enables all the warnings about constructions that some users
       consider questionable, and that are easy to avoid (or modify to
       prevent the warning), even in conjunction with macros.  This also
       enables some language-specific warnings described in C++ Dialect
       Options and Objective-C and Objective-C++ Dialect Options.

To link your object files to produce an executable a.out , you need
gcc Main.o DB.o

or (to give an alternative executable name myprog)
gcc -o myprog  Main.o DB.o

Alternatively, compile and link in a single command (with warnings)
gcc -Wall -o myprog Main.c DB.c

[1]. wall is - but that's something completely unrelated
Comment: thanks a lot for the answer and the information , it really worked :)
Answer: Try to build and compile like this:
gcc filename.c -o outputFile_name
./outputFile_name
And do this for the two files separately. The following file should compile with the name "outputFile_name" after it has been followed by -o
Comment: thank you for helping me , it was really helpful taking me to the solution :)

-Wall: command not found


How do I keep the users selected option showing on the screen after a page refresh or reload?

Question: I have made a select drop down with 3 options.  Currently, when the user picks one of the options then refreshes the page, his selection disappears.  I need the user to be able to refresh the page and still see the option he chose before the page refresh.  Is there an AngularJS directive that does this?  If not, how can I keep the users selection from disappearing after a refresh?  There are no questions on stack overflow that address this specific issue.
Here is the html with the select tag:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

5+5={{4+6}} (this is a check to make sure angular is working)

Choices: {{greetings}} (this is a check to make sure greetings is connected)

<select class="" name="">
  <option value="one">Stack Overflow, You're the Best!</option>
  <option value="two" ng-repeat="greeting in greetings">{{greeting}}</option>
</select>

Here is the angular controller in the app.js file:
angular
  .module("findTheBug", [])
  .controller("bugCTRL", bugCTRL);

  function bugCTRL($scope){
  $scope.greetings = ["good morning", "good evening", "good night"];
}

I have not been able to find an angular directive that addresses this issue, but here is an example of a select drop-down that doesn't hide the users option on a page refresh.  A working example of a sort, posted below for reference purposes only...
<select  class="form-control from-to-controls" ng-model="pair.from._id"  ng-change="selectEndpoint(pair.from,'{{pair.from._id}}')" ng-disabled="autoTest && testRunning || disableAll">
    <option value="NEW">New</option>
    <option ng-repeat="endpoint in endpoints" value="{{endpoint._id}}" ng-selected="endpoint.name==pair.from.name">{{endpoint.name}}</option>
</select>

<select class="form-control from-to-controls" ng-model="pair.to._id"   ng-change="selectEndpoint(pair.to,'{{pair.to._id}}')" ng-disabled="autoTest && testRunning || disableAll">
    <option value="NEW">New</option>
    <option ng-repeat="endpoint in endpoints" value="{{endpoint._id}}" ng-selected="endpoint.name==pair.to.name">{{endpoint.name}}</option>
</select>

I have googled, and tried adding ng-change, ng-selected, and ng-disabled to my code to attempt to replicate this code snippet above, but have not been successful.  I don't believe one of these 3 directives is related to the refresh issue I'm having, but I could be wrong.
(I spent a considerable amount of time asking this question the correct way according to stack overflow.)
Comment: COOKIES!!!!!!!!! So, make a cookie to store the user selection. Then call the cookie on ``. Simple!
Comment: You can either use cookies as mentioned or local storage, which in my opinion is the better solution because these values are not sent to the server with every request. This is supported on every major browser. Documentation and examples can be found here: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API
Comment: Why you need to reload the webpage? Angular is a SPA so reload is not necessary. But if you must, i recommend you use Localstorage.
Comment: I am working on a project and my bosses said the users may reload the page and still need to see their selected option.  I tried to recreate the situation in this little project.  I believe they want the code to look similar to the working example above and was wondering if any angular directives can accomplish this, otherwise I will look into cookies and local storage.
Comment: @AraYaghsizian did you checked my answer ?
Answer: You can use HTML5 localStroage to store the previously selected data.
DEMO

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope) {
    $scope.greetings = ["good morning", "good evening", "good night"];
    var selectedVal = localStorage.getItem('greeting');
    if(selectedVal) {
      $scope.greet = selectedVal;
    }
    $scope.selectedOption = function(greet) {
      localStorage.setItem('greeting', greet);
    };
});

<select name="selectData" ng-model="greet" ng-change="selectedOption(greet)">
  <option ng-selected="true" value="">Stack Overflow, You're the Best!</option>
  <option ng-repeat="greeting in greetings">{{greeting}}</option>
</select>