Anchoring sail shade to roof rafters

Question: I'm trying to figure out the best mounting layout for installing 20x16 sail shade over my patio. My plan is to anchor 2 corners to roof rafters, and 2 other to trees. I'm worried about load from winds, and how would all of this hold up to that. Mostly my concern is that trees would be flexing in the wind. I'm planning to anchor at ~10' off the ground to a 10-15" diameter tree. I don't like to use posts (that would not have this problem) since they would end up in the middle of the grass. The trees are ~35' from the corner of the shade. To install post by the tree, I'd need to bury it 5' deep (for 10' above grade), which would be quite a fit.
So 3 questions I'm trying to address:

How should I go about calculating loads I should be expecting, and what kind of load can my roof take before damage occurs?
As an idea to solving roof damage, would you recommend using some sort of fail-safe mechanism that would break and drop the shade in case winds are too strong before doing damage to a roof? If so, what would that mechanism be, and how to properly size it?
Is there a way to estimate tree trunk flex in strong winds, other than observing when such an event occurs?
Comment: I couldn't add a comment to the "cable pulling line swivels" answer. You don't need to use the commercial products for power lines. The consumer products are called "turnbuckles" and you can get these from your local home improvement store.
Answer: It's not really clear what you're asking, but 3/8" stainless eye bolts into your rafters and springs inline with your tree lines should do. The springs should be stout enough that they don't stretch except in severe weather and act as a safety measure for extreme tree movement.
Comment: Thanks for the answer! I restructured the question to hopefully be more clear. The spring suggestion - how would one size it? If the spring just flexes, then sail might flap, and produce stronger dynamic loads (according to other sources I looked at). Is there a standard mechanism that releases when loaded over certain threshold (and is re-settable)?
Comment: I agree, springs would help lower the jerk, but not the overall forces here, and In fact, you might be creating more lift as the fabric gets more camber  due to stretch.
Comment: You can use shear bolts, but they're not exactly "resettable".  They snap when their shear force is exceeded and need to be replaced.  Think of them as "fuses" for mechanical loads instead of electrical.
Comment: @ChrisM. this is exactly the direction I was thinking. But looks like bolt will not work with more or less standard mounting. Are there any other "fuse-like" solutions? Like a carabiner or a ring that will break after a certain threshold.
Comment: @Serge  I can't figure out what they're called, but at work we use what amounts to a double-shear clevis pin rope coupling (fork on one end, loop on the other, joined by a pin through the middle) that uses a shear pin (same idea as a shear bolt).  Essentially, once the tension in the line exceeds a certain amount the pin snaps and releases all tension.
Comment: I'd be inclined to use what Chris is describing with a fallback spring of lighter tension. This would prevent total collapse of the canopy if the pin was to give out.
Answer: I found what I mentioned in the comments on isherwood's answer.  They're called "cable pulling line swivels", used for power lines and other cables to prevent over-tensioning the line when pulling.  The two halves of the swivel are joined by a shear pin held in place by a retaining ring.  When the line tension exceeds the shear pin's rated load, it breaks, preventing the line from being overstretched.
They do seem to be kind of expensive, though.  I imagine they're not really intended for purchase by consumers.
More information on one of the brands available here.  You'll need to find a distributor near you for pricing, though.
Comment: Good stuff, but at $200 a pop is out of the budget :D
Answer: You could probably calculate the loads starting with some ideal lift calculations [1]. I would bet that these numbers would be surprisingly high and that your design is driven by how much force you are willing to let the rafer see.
The direction is also important to, but something flapping in the wind will likely be pulling in a wide range of direction.
Here's a few things I'm thinking:

Add a system where you can easily drop/furl the sail shade. This can be as simple as, on any corner you cannot reach easily, add a block instead of a hard point and send the corner line thru that block and into a cleat. When it's not in use, you can take it down easily.
If you want to design in a weak point, perhaps it could be done with rope, making the corner which is tied to the roof rafter, a small diameter with a breaking strength just under whatever you determine is correct. [2]
Maybe another way to add a weak point would be to use a rectangular ring that has a split in the center.

Have you considered what material you have on the shade fabric? Something mesh would still shade you but not become a wing/sail.
Another benefit of having an easy way of taking the shade down is cleaning!
[1] https://en.wikipedia.org/wiki/Forces_on_sails
[2] http://www.neropes.com/new-england-ropes/sail-making-products/braided-luffline.html#
Comment: Using a rope as a fail safe was one of my options. Taking it down after each use would be cumbersome, but worthy of a plan B. I'll work in this direction, and see what first trial really shows.

Anchoring sail shade to roof rafters


Group and concatenate List of tuples

Question: I have a list of pairs (key, val) with both key and value being strings. I want to aggregate the tuples with duplicate keys.
For (key1, val1), (key2, val2), (key3, val3), (key1, val4), (key2, val5)

I want output
(key1, val1+val4), (key2, val2+val5)

This is my current query
var duplicates = Contents.Records.SelectMany(x => x.Users).Select(x => new { Name = x.Name, ID= x.ID}).GroupBy(x => x.ID).Select(x => new { x.Key, Names = x.Select(p=>p.Name).Aggregate((a,b) => a +","+b)}).ToArray();

But at the end for each entry in duplicates the member Names is empty.
The data is as follows each Records has a List Users. Each user has a Name and an ID.
What am I doing wrong?
Comment: I do not see an obvious flaw in your grouping and selection, and can indeed run that against a sample set of data and get what I believe to be your desired results. Have you checked the inputs to verify that the data you expect is loaded? For example, split the query and perform a `ToList()` after `.SelectMany(...).Select(...)`. Does your data look as you expect it to be?
Answer: Aggregate looks like it should do the job. But I've never liked Aggregate. The syntax is not intuitive (in my mind). Usually other ways look more lucid. Take this one:
Tuple<string,string>[] tuples = {
                                    Tuple.Create("key1", "val1"),
                                    Tuple.Create("key2", "val2"),
                                    Tuple.Create("key3", "val3"),
                                    Tuple.Create("key1", "val4"),
                                    Tuple.Create("key2", "val5")
                                };
tuples.GroupBy(t => t.Item1, t => t.Item2)
      .Select(g => Tuple.Create(g.Key, string.Join("+", g)))
      .Dump(); // Linqpad output command

result:
key1    val1+val4
key2    val2+val5
key3    val3

Group and concatenate List of tuples


Can't figure out why this output formatting loop is going infinite

Question: My program is supposed to take in a number from user input, determine whether or not it is prime, and then if it is not, output the factors of the entered number, 5 to a line. The 5 to the line part is where everything goes haywire, the loop i wrote should work fine as far as i can tell, however no matter how much i change it around, it does one of two things, 1) goes infinite with either new lines or the first factor, or 2) outputs a line with 5 of each factor. Here's the code:
 else
      {
          cout << "\nNumber is not prime, it's factors are:\n";
           for (int x = 2; x < num; x++)
          {

              factor=num%x;
              if (factor==0)
               {
                  int t=0;
                   cout << x << "\t";
                   t++;

                  for (int t; t <= 5; t++) // THE TROUBLE LOOP
                      {
                          if(t>=5)
                         {
                        t=0;
                        cout << endl;
                         }
                      }
               }

          }
      }

Comment: Please don't abuse apostrophes:  The proper grammar is "its factors are:"
Answer: Replace the declaration of t in the loop since you've declared t prior to the loop:
for(; t <= 5; t++)

With int t in the loop declaration you are overriding t as an uninitialized variable that will have a garbage value.
Outside of this problem your loop is infinite since you will be resetting t to 0 whenever it equals 5.
Comment: Still goes infinite after building and compiling.
Comment: @user3525452: As I mentioned at the end of my answer there is something wrong with your logic in that loop as it will always be infinite.  If you could elaborate on what it is supposed to do I may be able to help more.
Comment: what the first loop does is goes through and tests the input number as prime or not, and then puts out factors if the number is non prime, the loop that is going infinite is simply supposed to go to a new line after 5 factors are output.
Comment: @user3525452: You shouldn't need a loop to do that.  You should have some kind of a counter and check to see if that is `5`, if so, print a new line and reset the counter.
Answer: In the for loop change the
int t

to
t=0

it is the
for(int t,t<=5,t++)

the int t part in particular that is causing the issue.
Comment: You are repeating the answer given by GWW.  I don't see any additional content.
Comment: Yea, The answer wasn't posted as I was typing
Answer: @GGW
Or this:
    int t = 0;
    //some code
    for(t; t <= 5; t++)
    //more code

Comment: Still goes infinite after building and compiling.
Comment: Even if you put the "int t = 0;" out of the loop? like:                  else
{
    int t = 0;
    //Code
    for(t; t <= 5; t++)
    //Code


How do I count correctly processes created by fork?

Question: I am having problems with C code about processes that are created with fork given by our professor to figure out the number of processes that it creates.
pid1 = fork();

if (pid1 != 0) {
   pid2 = fork();
   pid3 = fork();
}
else {
   pid4 = fork();
}

Comment: What problem? What have you tried to solve it?
Comment: And how did that go? Did you get stuck at some particular point? If so, please include your thought process in your question. We need to see your attempt at solving your problem.
Comment: I have tried to run the code with some printf at the end of every fork, to try to figure out how to create the processes tree that we were asked for.
Comment: Instead of a bunch of variables consider using an array.
Answer: Running the code is only somewhat helpful (and can't be done during the exam!)--better to draw a process tree. The rules are that every child process starts execution after the fork call that spawned it, parents have nonzero pid and children have a pid of zero.
         main
       /   |   \
    pid1 pid2 pid3
     /     |
  pid4   pid3

We can see main spawns three children, pid1, pid2 and pid3 (pid1 is trivial and the other two are spawned in the true if block). pid1 goes on to the else portion of the conditional and spawns pid4 before finishing. pid2 is the only trick: it spawns again at pid3 because that's where its execution starts.
Answer:

 6 processes in total are created (main and 5 children)
Comment: Your count is right, but your tree is wrong.  You appear to have gotten the sense of the condition backward.  `pid1 != 0` is true in the parent, not the child.
Comment: That is very helpful, I was having a similar confusion about the two fork () inside the if. But, now I think I got a clearer view abou it especially pid3. Thank you


WPF ContextMenu Submenu Style

Question: How does one set the style of a sub-menu under a ContextMenu?
Here is the code for ContextMenu:
<ListView.ContextMenu>
  <fw:AcrylicContextMenu Style="{StaticResource NowPlayingContextMenuStyle}" ItemContainerStyle="{StaticResource NowPlayingContextMenuItemStyle}">

    <MenuItem>
      <MenuItem.Header>
        <TextBlock Text="Play" Style="{StaticResource NowPlayingContextMenuItemHeader}" />
      </MenuItem.Header>
      <MenuItem.Icon>
        <materialDesign:PackIcon Kind="Play" />
      </MenuItem.Icon>
    </MenuItem>

    <MenuItem>
      <MenuItem.Header>
        <TextBlock Text="Sort" Style="{StaticResource NowPlayingContextMenuItemHeader}" />
      </MenuItem.Header>
      <MenuItem.Icon>
        <materialDesign:PackIcon Kind="Sort" />
      </MenuItem.Icon>

        <MenuItem>
          <MenuItem.Header>
            <TextBlock Text="Ascending" Style="{StaticResource NowPlayingContextMenuItemHeader}" />
          </MenuItem.Header>
          <MenuItem.Icon>
            <materialDesign:PackIcon Kind="SortAscending" />
          </MenuItem.Icon>
        </MenuItem>

        <MenuItem>
          <MenuItem.Header>
            <TextBlock Text="Descending" Style="{StaticResource NowPlayingContextMenuItemHeader}" />
          </MenuItem.Header>
          <MenuItem.Icon>
            <materialDesign:PackIcon Kind="SortDescending" />
          </MenuItem.Icon>
        </MenuItem>

    </MenuItem>

  </fw:AcrylicContextMenu>
</ListView.ContextMenu>

The styles have been defined in this way:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:V_Player.Resources.Styles"
                    xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes">

</ResourceDictionary>

And results are not quite right... For sub menus of course.
Menu background is Acrylic and transparent, but sub menu no, it is gray and has material design style.

What can i do for fix it?
Comment: Does this answer your question? [WPF Submenu styling](https://stackoverflow.com/questions/3391742/wpf-submenu-styling)
Comment: This is not it. because there was described how to create a style for the main menu, not for the popup menu.

Additionaly, there is changed template. What causes combined with the MaterialDesign and fw:AcrylicContextMenu styles: deletion of the animations (mouser hover, click) and Acrylic theme.
Answer: This style work for me:

        </Style>

        <ControlTemplate x:Key="{x:Static MenuItem.SubmenuItemTemplateKey}" TargetType="{x:Type MenuItem}">
            <Border Name="Border">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" SharedSizeGroup="Icon" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="Auto" SharedSizeGroup="Shortcut" />
                        <ColumnDefinition Width="13" />
                    </Grid.ColumnDefinitions>
                    <ContentPresenter
                        Name="Icon"
                        Margin="6,0,6,0"
                        VerticalAlignment="Center"
                        ContentSource="Icon" />
                    <Border
                        Name="Check"
                        Width="13"
                        Height="13"
                        Margin="6,0,6,0"
                        Background="{StaticResource ToolBarBackground}"
                        BorderBrush="#5082a4"
                        BorderThickness="1"
                        Visibility="Collapsed">
                        <Path
                            Name="CheckMark"
                            Width="7"
                            Height="7"
                            Data="M 0 0 L 7 7 M 0 7 L 7 0"
                            SnapsToDevicePixels="False"
                            Stroke="#5082a4"
                            StrokeThickness="2"
                            Visibility="Hidden" />
                    </Border>
                    <ContentPresenter
                        Name="HeaderHost"
                        Grid.Column="1"
                        ContentSource="Header"
                        RecognizesAccessKey="True" />
                    <TextBlock
                        x:Name="InputGestureText"
                        Grid.Column="2"
                        Margin="5,2,0,2"
                        DockPanel.Dock="Right"
                        Text="{TemplateBinding InputGestureText}" />
                </Grid>
            </Border>
            <ControlTemplate.Triggers>
                <Trigger Property="Icon" Value="{x:Null}">
                    <Setter TargetName="Icon" Property="Visibility" Value="Hidden" />
                </Trigger>
                <Trigger Property="IsChecked" Value="true">
                    <Setter TargetName="CheckMark" Property="Visibility" Value="Visible" />
                </Trigger>
                <Trigger Property="IsCheckable" Value="true">
                    <Setter TargetName="Check" Property="Visibility" Value="Visible" />
                    <Setter TargetName="Icon" Property="Visibility" Value="Hidden" />
                </Trigger>
                <Trigger Property="IsHighlighted" Value="true">
                    <Setter TargetName="Border" Property="Background" Value="#5082a4" />
                </Trigger>
                <Trigger Property="IsEnabled" Value="false">
                    <Setter Property="Foreground" Value="#0f3c5a" />
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>

        <ControlTemplate x:Key="{x:Static MenuItem.SubmenuHeaderTemplateKey}" TargetType="{x:Type MenuItem}">
            <Border Name="Border">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" SharedSizeGroup="Icon" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="Auto" SharedSizeGroup="Shortcut" />
                        <ColumnDefinition Width="13" />
                    </Grid.ColumnDefinitions>
                    <ContentPresenter
                        Name="Icon"
                        Margin="6,0,6,0"
                        VerticalAlignment="Center"
                        ContentSource="Icon" />
                    <ContentPresenter
                        Name="HeaderHost"
                        Grid.Column="1"
                        ContentSource="Header"
                        RecognizesAccessKey="True" />
                    <TextBlock
                        x:Name="InputGestureText"
                        Grid.Column="2"
                        Margin="5,2,2,2"
                        DockPanel.Dock="Right"
                        Text="{TemplateBinding InputGestureText}" />
                    <Path
                        Grid.Column="3"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        Data="M 0 0 L 0 7 L 4 3.5 Z"
                        Fill="#0f3c5a" />
                    <Popup
                        Name="Popup"
                        AllowsTransparency="True"
                        Focusable="False"
                        HorizontalOffset="-4"
                        IsOpen="{TemplateBinding IsSubmenuOpen}"
                        Placement="Right"
                        PopupAnimation="Fade">
                        <Border
                            Name="SubmenuBorder"
                            Background="{StaticResource ToolBarBackground}"
                            BorderBrush="{StaticResource ToolBarBackground}"
                            BorderThickness="1"
                            SnapsToDevicePixels="True">
                            <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Cycle" />
                        </Border>
                    </Popup>
                </Grid>
            </Border>

            <ControlTemplate.Triggers>
                <Trigger Property="Icon" Value="{x:Null}">
                    <Setter TargetName="Icon" Property="Visibility" Value="Collapsed" />
                </Trigger>
                <Trigger Property="IsHighlighted" Value="true">
                    <Setter TargetName="Border" Property="Background" Value="#5082a4" />
                </Trigger>
                <Trigger SourceName="Popup" Property="Popup.AllowsTransparency" Value="True">
                    <Setter TargetName="SubmenuBorder" Property="CornerRadius" Value="4" />
                    <Setter TargetName="SubmenuBorder" Property="Padding" Value="0,3,0,3" />
                </Trigger>
                <Trigger Property="IsEnabled" Value="false">
                    <Setter Property="Foreground" Value="#0f3c5a" />
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>

WPF ContextMenu Submenu Style


What causes enemies to reset?

Question: I've been playing an Engineer recently, and although it can be fun to kite enemies instead of going toe-to-toe with them, I sometimes have a problem with enemies resetting before I have a chance to kill them. When this occurs, the enemy stops chasing you, returns to where they were when you first engaged them, and regenerates back to full health.
What causes an enemy to reset? How can I stay out of an enemy's range without resetting them?
Answer: Based on my own experience and programming skills, I would say that each monster probably has a Pathing Algorithm that tells him how to move, where to move for, what to avoid and the maximum range from its Home Zone it is allowed to move away, if it leaves its Home Zone, the mob will return to its zone and reset.
Also, what takes place here is time without receiving damage. If you run in front of a mob, it will follow you, but if it receives no damage in a matter of, i would say 8-9 seconds, it will stop chasing you.
There are two Triggers for the mob to stop attacking you and run back to its original coordinates : Time without receiving damage and Maximum walk range reached.
Numbers still needs testing but the Triggersare those, for sure, not taking in account the Underwater Environment which is sort of bugged causing monsters that are in battle with you face to face and in close range to sometimes, leave combat and regen full or half of its health for no good reason.
Comment: Thanks for the response! I've definitely had problems with underwater combat as well.

What causes enemies to reset?


Rails: s3_direct_upload - How do I save/use the data response?

Question: I've searched all over SO for an answer, so I'm sure this hasn't been asked before. Please help me, o savior!
I'm trying to use the s3_direct_upload gem to handle uploading files directly to S3, but I just don't know how to see/use/save the data that apparently is given back from the S3 server. I've read the README for s3_direct_upload a dozen times, and it gives some example snippets of JS code but doesn't tell me where that code should go.
I have worked through the first part of the README and set up AWS config and the simple jQuery
jQuery ->
  $("#s3-uploader").S3Uploader()

In my CoffeeScript (which is included in the asset pipeline correctly).
I have this in my view:
<%= s3_uploader_form callback_url: work_path, callback_param: "work[url]", class: "s3-uploader" do %>
    <%= file_field_tag :file, multiple: false %>
<% end %>

<%= form_for(@work) do |f| %>

    <%= f.label :name, "Title" %>
    <%= f.text_field :name %>
    <%= f.label :category, "Category" %>
    <%= f.text_field :category %>

    <%= f.submit "Upload", id: "btn-upload-work", class: "btn btn-large btn-warning btn-upload" %>

<% end %>

I want the user to upload a work and fill in some fields. When the user clicks the "Upload" button, a new work should be created with attribute :url equal to the url of the file uploaded, as well as the :name and :category attributes equal to the text inputted by the user. Then the page should redirect to the show page of the submitted work. The README gives this example:
$('#myS3Uploader').bind "s3_upload_complete", (e, content) ->
  $('#someHiddenField').val(content.url)

But I have no idea where to put this bit of code.
This is my controller: (I know the create action needs changes, but I don't know exactly what. I've experimented for several hours with respond_to to no avail.)
def show
    @work = Work.find(params[:id])
end

def new
    @work = Work.new
end

def create
    @work = current_user.works.new(work_params)
    if @work.save
        flash[:success] = "Work successfully submitted!"
        redirect_to @work
    else
        render 'new'
    end
end

private

    def work_params
        params.require(:work).permit(:name, :category, :url)
    end

Even after reading the README a dozen times, I still don't understand what callback_url really is, what callback_param is, and how to work with them. Even worse, loading this view gives an error - Rails doesn't like the callback_url: work_path portion. I had to change that to work_path(@work) to have it load, but I'm not sure if that's right (since I don't understand callback_url).
From the questions everyone else has asked about s3_direct_upload, it seems that they already know how to use it (the questions are just smaller details). So I'm lost because I can't even get it to work in the first place. I'm a bit new to web frontends, so please bear with me and explain this to me. Thanks so much!
Answer:
I still don't understand what callback_url really is,

callback_url is the path that it would post to via AJAX after the gem finishes uploading the file to s3. So work_path(@work) should be ok.

$('#myS3Uploader').bind "s3_upload_complete", (e, content) ->
$('#someHiddenField').val(content.url)
But I have no idea where to put this bit of code.

You can place the above code in the same coffeescript file where you put $("#s3-uploader").S3Uploader().  Replace $('#someHiddenField').val(content.url) with alert(content.url). This way if the upload is successful you will get an alert message.
Also paste the following code in the same coffeescript file
$('#myS3Uploader').bind "s3_upload_failed", (e, content) ->
  alert("#{content.filename} failed to upload : #{content.error_thrown}")

The above code would show an alert if there was an error.
If you do not see any of the two after submitting the file, then there is some other issue. I highly recommend using firebug. It is really helpful in debugging client side javascript functions. In firebug net panel you can see if the gem is making a call to the s3 server or not. It will also show any javascript errors in the console panel.
Comment: Thanks for the quick response. I see that the file isn't being uploaded at all after I put in a file. What might be stopping the file from being uploaded?
Comment: do you get any alerts after putting in the above codes? If not look at the firebug console for errors.
Comment: I realized that the form code should have "s3-uploader" as the id instead of class. The file now uploads fine, but I don't get any alerts. This is very weird. (Where would I see the alerts?)
Comment: one step done, now look at your rails server console and see if it gets request after the upload is done.
Comment: It gets the request. Parameters: {"url"=> ..., "filepath"=> ..., ..., "work"=>{"url"=>"..."}}.  A `work` is created and inserted into `ActiveRecord` with only the `:url` attribute, but that's not what I want. I just want the be able to access all the parameters so I save a `work` along with the other text fields. (I still don't see any alerts.)
Comment: you will need to write some js to do that, serach for `additional_data:` in the gem read me, that gives an option to pass additional params but you need to write js to fetch those from the form into js. Try it and if it does not work ask another question with your attempted code and errors if any
Comment: It turned out to be that the .coffee file wasn't indented properly; I have the general idea of what I want working now. I deleted the callback_url and callback_param because I didn't want the work to be saved immediately. I used s3_upload_complete event to insert the URL into a hidden field on the form. Thanks a ton for your help!


What type of silicone should I use for caulking the shower corner and the transition from wall tiles to shower base?

Question: What type of silicone should I use for caulking the shower corner and the transition from wall tiles to shower base?
I know recommending a product is out of scope here but I am asking about the characteristics of the product that I need
Comment: Something rated for use in showers such at 100% silicone waterproof bathroom
Comment: And flexible. But reading the product info should tell you that...
Answer: You want 100% waterproof silicone for "Bath and Shower". Formulated to prevent mold/mildew, but no special provisions needed for exterior use (sun light, UV, radiant heat).
Silicone cures with the help of moisture in the air, but do not add water.
Some silicone caulking for bath & shower costs more because it is fast drying. This is mostly for contractors that want to install & quickly demonstrate the shower to the customer and get paid. It is not necessary for DIY, unless you have a line-up of teens & inlaws waiting to use the shower.
You also do not need paintable or "30 minute" paint ready properties, nor exterior "30 minute" rain ready.


log4net wrapper doesn't log (during MSTest UTs)

Question: I have a wrapper class for log4net to log across multiple classes and assemblies within a group of dll-libraries. (This may be poor design, but.. don't ask)
The code basically looks like this:
<code>public static class Logger
{
    private static ILog log;

    static Logger()
    {
        log = LogManager.GetLogger("abcd");
        XmlConfigurator.Configure(new FileInfo("LoggerConfig.log4net"));
        log.Info("=== NEW SESSION ===");
    }

    public static void Log(string message)
    {
        log.Debug(message);
    }
}
</code>
Now.. if the static constructor was the static main routine of a simple executable, this works perfectly fine (I quickly made a console app to test it). But here it does not.
Since I deal with standalone assemblies, not executables, the only way I can easily test the logger is through MSTest. This may be a cause for this problem. I am not 100% sure if  it maybe simply can't find the config file. It is copied at compilation and lies in the same folder as the assembly containing the logger class, so i think that should work.
bleh.. stuck since three hours. :T any suggestions?
Answer: My psychic debugger says that your LoggerConfig.log4net is not in the right directory. It is not deployed to your test directory and not found when running the test. That is why there is no log output. Deploy the file in the test directory and you will have you logging output.
EDIT: More precisely, you need to add it as a deployment file under Test->Edit Test Settings->>Deployment (as described here: How can I get "Copy to Output Directory" to work with Unit Tests? )
Comment: mmm.. you're right, I was wondering about those 'Out' folders in the TestResults subfolders - there the file is not present. My concern however is that I want it to 'belong' to the assembly/project in which the logger is, since in the end, i want to deploy the library without the unit test assemblies. Is there a way to tell MSTest to copy this file?
Comment: I'm not sure, but I think you can add the file to deployment files. But in the case of unit test your config file has to come out of the unit test project (otherwise if you change your logging settings your unit tests will fail). I would try to add the file and mark is for deployment.
Comment: Ah, one can add it as a deployment file under Test->Edit Test Settings->>Deployment (as described here: http://stackoverflow.com/questions/227545/how-can-i-get-copy-to-output-directory-to-work-with-unit-tests )
Answer: Have you tried to reference the config file by an absolute path? Maybe the root directory for MSTests is different to the Console App root dir?
Answer: MsTest shadow copies things all over the place and as peer and Hinek say the location of the file is probably the issue. I find including files within the test assembly is one way to get around this.
Check out a previous answer here for details.
Comment: I guess this will work.. but I don't want to do that, since the library user shall be able to pick the logging location and level after deployment. (see comment above)
Answer: Log4net uses configs in App.config? Try to put them also in the testlibrary?
I know the problem by Application with many libraries and there de config must only be in the Main-Application.


Ant Sql Target Cannot Create Postgresql Function

Question: I have the following in a file called function.sql:
CREATE FUNCTION increment(i integer) RETURNS integer AS $$
        BEGIN
                RETURN i + 1;
        END;
$$ LANGUAGE plpgsql;

And I'm trying to execute it against a local Postgres (9.3.4) database with Ant:
<target name = "create" >
    <sql driver="org.postgresql.Driver" url="${db.url}" userid="${db.username}" password="${db.password}">

        <transaction  src="create/functions.sql"/>

        <classpath>
            <pathelement location="lib/postgresql-9.3-1101.jdbc41.jar"/>
        </classpath>
    </sql>
</target>

(I've created an example project on github here.)
When I execute ant, I get the error:
BUILD FAILED
/home/paul/jobhop-workspace/AntSqlPostgresFunctions/build.xml:17: org.postgresql.util.PSQLException: ERROR: syntax error at or near "$"
  Position: 58

However if I execute the file directly:
psql -d <mydb> functions.sql

it creates the function just fine. I've tried the solutions suggested here and here, which sound like the same problem, but they didn't work for me.
Answer: The error message is because Ant's property expansion behaviour sees the $$ and replaces it with a single $ before it gets to PostgreSQL (see http://ant.apache.org/manual/properties.html, section $$ Expansion)
We can get around that in a few ways. Doubling up the dollar characters as recommended in the Ant manual works, but at the expense of making the file no longer work when passed to the psql client. I've had more success using $BODY$ or ($whatever-you-fancy$) instead of $$ to delimit the function body, or by setting the SQL task's expandproperties argument to false in the build.xml.
Once that's done we hit a second problem: the Ant task parses your file
to find statements which it feeds to JDBC. However, it's not very smart: it just
splits on ';' characters, even when they're in the middle of the body
of your function definition (see http://svn.apache.org/viewvc/ant/core/trunk/src/main/org/apache/tools/ant/taskdefs/SQLExec.java?view=markup#l724), so then we'll see an error about an unterminated string (i.e. the first half of the function body).
We can get round that by using a different delimiter and telling the SQL task about it via the delimiter and delimitertype arguments. The following patch to your project
gets it working for me:
diff --git a/build.xml b/build.xml
index 7d8a990..5dbbdc5 100644
--- a/build.xml
+++ b/build.xml
@@ -14,7 +14,7 @@
    </target>

    <target name = "create" >
-               <sql driver="org.postgresql.Driver" url="${db.url}"
userid="${db.username}" password="${db.password}">
+               <sql driver="org.postgresql.Driver" url="${db.url}"
userid="${db.username}" password="${db.password}" delimiter="/* END_STATEMENT */" delimitertype="row" >

                    <transaction  src="create/functions.sql"/>
diff --git a/create/functions.sql b/create/functions.sql
index 3238d3e..1a8518f 100644
--- a/create/functions.sql
+++ b/create/functions.sql
@@ -1,9 +1,9 @@
-CREATE FUNCTION increment(i integer) RETURNS integer AS $$
+CREATE FUNCTION increment(i integer) RETURNS integer AS $BODY$
     BEGIN
             RETURN i + 1;
     END;
-$$ LANGUAGE plpgsql;
-
+$BODY$ LANGUAGE plpgsql;
+/* END_STATEMENT */

I initially put the statement delimiter in a comment of the form -- END_STATEMENT. That only gives the illusion of working, since, when parsing the SQL, the Ant task discards those comments before it goes looking for delimiters. Finding no delimiter it just passes the entire contents of the file to PostgreSQL as a single statement, which works in your simple case but won't be ideal as the list of functions gets longer.
Instead, I used C-style comments which are recognized by PostgreSQL, but not (currently) by the Ant task's parser. Of course, this could stop working if the Ant task's parser is changed.
If the functions.sql file doesn't need to work from psql then you can consider using anything you like as delimiter. It doesn't even have to be valid SQL syntax since the Ant task removes it before passing on the statements to PostgreSQL.
Comment: This worked for me! The amalgamation of the other two solutions I found.


How to add contact in the list using sendgrid?

Question: I'm trying to add contact in the list so i'm using this link below to Add a Single Recipient to a List :
click here
I have Advanced 100k plan and using full access api key but still getting forbidden error.
Please help me out in this.
My code
<code>string data = @"[
  {
    'age': 25,
    'email': 'firstname.lastname@example.com',
    'first_name': '',
    'last_name': 'User'
  },
  {
    'age': 25,
    'email': 'firstname.lastname@example.com',
    'first_name': 'Example',
    'last_name': 'User'
  }
]";
        var client = new SendGridClient("#################");
        var json = JsonConvert.DeserializeObject<Object>(data);
        data = json.ToString();
        var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "contactdb/recipients", requestBody: data);
        Console.WriteLine(response.StatusCode);
        Console.WriteLine(response.Body.ReadAsStringAsync().Result);
        Console.WriteLine(response.Headers.ToString());
        Console.ReadLine();
        return response;
</code>
Answer: You can resolve this by editing your API Keys settings in Send Grid and enabling the permissions for the features you need access to for that API Key.
API Keys settings


Draw multiple feeds simultaneously from the Google Feed API

Question: Using the Google Feed API it's possible to request multiple feed objects like so:
<code>var feed1 = new google.feeds.Feed(url1),
    feed2 = new google.feeds.Feed(url2),
    feed3 = new google.feeds.Feed(url3);

feed1.load(callback);
feed2.load(callback);
feed3.load(callback);
</code>
This can create a large number of simultaneous requests that can take a long time to resolve and load.
Is there a way to get multiple feeds from the API and retrieve them with a single request?
Comment: Another way would then be to use different services or even services with different subdomains because the conucurrency limits in browsers is domain/subdomains based. You could "cheat" when using a service like [Superfeedr](https://superfeedr.com) by proxying calls to its api thru different domains on your end.
Comment: To my knowledge it is not possible, however, that should not be a problem because jabascript is async, so you cn certainly make multiple requests in parallel, and, based on the number of conurrent connections allowed by your browser, you'll get responses simultaneously!
Comment: You are correct, but I was hoping to avoid this behavior as requesting more simultaneous feeds than the browser has concurrent connections is the source of the slow loading I was trying to avoid.
Answer: The API developer guide doesn't seem to have an option to allow that, so I'd guess you need to do it the way you are using it currently, although IMO it may be a better idea to request them one after another to not overload the server.


Highlight .tpl syntax in Eclipse

Question: I've been googling and can't find a solution for this.  I'm trying to setup .tpl files to use either HTML syntax highlighting or PHP syntax highlighting.  Has anyone does this, or do you know how?
Thanks
Answer:
Go to Window -> Preferences-
Then General -> Editors -> File Associations-
Add the PHP Editor to the *.tpl file type. You may have to create the *.tpl type if it doesn't already exist.

You may also have to set the content type for your tpl files in Content Types also under the General settings. Scroll down to PHP Source File and make sure *.tpl exists there as well.
Then you need to restart eclipse to make it work.
Comment: And you have to close and open Eclipse to make the changes happen!
Answer:
Go to Window -> Preferences -> General -> Content Types
Select Text -> CSS, click Add, write *.tpl and save.
Do the step two for Text -> HTML, Javascript and PHP.
Answer: I took that from this link. You can get that form there or I give their content below if the anyhow that link doesn't work. It works for me nicely.
steps how to install SmartyPDT 0.9.1
Be sure that the .TPL files are not associated with any content type (file type). In Eclipse,

Be sure that the .TPL files are not associated with any content type (file type). In Eclipse,
Go to Help-> Install New Software

At the Work With section click on the Add... button. Give the new "Site" a name and set the location with http://smartypdt.googlecode.com/svn/trunk/org.eclipse.php.smarty.updatesite/ , then click OK. Go back to the Install New Software window and select the newly added "site". If the "Group items by category" check-box is checked, uncheck it. Now you should be able to see 1 item in the software list named "Smarty Feature"

Select the Smarty Feature, click Next> and from here afterwards it shouldn't be a problem.

If you are prompted that this is an unsigned package, just ignore the warning and install it anyway.

After the installation completes, restart Eclipse and it should be working.
Define a default PHP executable of type 'Zend Debugger' (only if you install vanilla Eclipse PDT):

In Eclipse go to Window->Preferences->PHP->PHP Executables Click on the Add button. Enter a name for that executable definition, for example "PHP localhost", complete the 2 fields which ask you for the PHP executable path (the PHP binary CLI executable) and php.ini path. Be sure that the PHP debugger is the Zend Debugger.
Comment: Thanks for the eclipse/smarty install software URL.
Comment: Broken link. If possible update the link, if not put an advice to let users know the issue. I would suggest [this one](http://p2-dev.pdt-extensions.org/).
Answer: Installing smarty on eclipse kepler fails
(see Install SmartyPDT 0.0.9.1 in Eclipse Kepler).
The recommendation there is to use the PHP Development Tools (PDT) from former eclipse juno version. But in contrary to the recommendation I did not DELETE the mentioned features folder  but I just uninstalled the plugins from eclipse itself (Help/About/InstallationDetails):

Uninstall all PDT packages
Restart eclipse
Then follow the instructions in above answer to install the PDT packages from Juno version and then the smarty package.

All these Installations worked without error.
But unfortunatly the *.tpl files are still not syntax highlighted. What to do more?
Answer: Our *.tpl file extension  is not associated with the HTML editor in Eclipse by default.

Open Eclipse's preferences.
Expand General from the tree on the left and select Content Types.
Expand Text on the right and select HTML. Click the Add... button below, enter *.tpl and click the OK button.
General -> Editors -> File Associations
Click Add..., enter *.tpl, and click OK.
Select HTML Editor from the Associated editors: section below and click the Default button to the right.

Highlight .tpl syntax in Eclipse


/folder/ does not point to .aspx page

Question: A quick question. Pointing to admin panel in my website on IIS 5.1 (XP Pro) like this
<code>localhost\testsite\admin\
</code>
automatically picks default.aspx on my machine but it does not on server2003 which uses IIS 6.0. Do I need to change something for that to work, may be permissions?
Is it a good practice to point to admin/default.aspx or just /admin/. I prefer the later.
Thanks
Answer: On your server2003 IIS, have you verified that

Default documents are enabled
Default.aspx is on the list of Default docs

Right-click your website, Properties->Documents
Comment: they are enabled but default.aspx was not the list. Default.asp was. Thanks
Comment: Please mark this answer as correct if it helped, and consider reviewing answers to your past questions and marking those that helped you.
Answer: Follow the instructions on this page and ensure that default.aspx is configured as a default document:
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/dc6eb1b4-9028-4308-9935-52b64edfad36.mspx?mfr=true

/folder/ does not point to .aspx page


How to use 'return' statement?

Question: I'll trying to classify text given a bunch of words in a dictionary, the dictionary contains stemmed groups with different words correlated. And another aspect is that I have a dataframe in which each represen and article.
The main goal is that if at least of 50% of the words in the group were found it, will be assign 1 otherwise 0.
stemmed_search = {Group_1:['solicit', 'requier', 'día'], Group_2:['infraestruc', 'construccion', 'gas', 'nigrogen']}
test = ['solicit', 'requier', 'día', 'infraestruc', 'construccion', 'gas', 'nigrogen']
word_list = [['solicit', 'requier', 'día'], ['infraestruc', 'construccion', 'gas', 'nigrogen']]
def compar(test):
    for item in stemmed_search.values():
        filt = []
        for i in item:
            if i in test:
                filt.append(True)
            else:
                filt.append(False)
        #print(filt)
        umbral = len(filt) * 0.5
        Trues = filt.count(True)

    return[1 if Trues > umbral else 0 for i in range(0, len(words_list))]

text['Class'] = text.Stem.apply(compar)

I tried using this statement, but it doesn't work:
return[1 if Trues > umbral else 0 for i in range(0,len(filt))]

Then I have this: [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0].
Later suppouse that the problem was in the range of the list, so I changed and I had a similar output that was I expected:
return[1 if Trues > umbral else 0 for i in range(0, len(words_list))]

But when I executed that line the output is very similar that I want: [1, 1],[1, 1],[0, 0],[0, 0].
I think that the problem is here, because when I only execute the comprar function without apply it works.
I expect an output like that in the text['Class'] column: [0, 1],[0, 1],[0, 0],[0, 0]
Comment: I think you first need to decide if you want to print things, or you want to create a column in a `pandas` dataframe, because it doesn't make sense to call a function by `pandas.apply()`, when all it does is to print numbers and "END ROW".
Comment: Could you provide an example of  input and expected output? Thanks!
Comment: Both inputs ...dictionary of the dataset? or which one?
Comment: at least 'stemmed_search', 'test' and 'filt', if you can do the rest better
Comment: Is that better?
Comment: Of course yes, I know it. This is only for debugging
Comment: compar(test) return [1,1]. Is it the output you expect?
Comment: No, It would be [0,1], [0,1], [0,0],[0,0]
Answer: If I understood your problem correctly, given the following input:
stemmed_search = {'Group_1':['solicit', 'requier', 'día'], 'Group_2':['infraestruc', 'construccion', 'gas', 'nigrogen']}
test = ['solicit', 'requier', 'día', 'infraestruc', 'construccion', 'gas', 'nigrogen']
test2 = ['solicit', 'lol', 'lol', 'infraestruc', 'construccion', 'gas', 'nigrogen']

df = pd.DataFrame([[test,test2]], ['Stem']).T
                                                Stem
0  [solicit, requier, día, infraestruc, construcc...
1  [solicit, lol, lol, infraestruc, construccion,...

This code is for you:
def compar2(test):
    test = set(test)
    return [1 if len(set(group) - test) < len(group) * 0.5 else 0 for _,group in stemmed_search.items()]

df['Text'] = df.Stem.apply(lambda x: compar2(x))

And gives:
                                            Stem      Text
0  [solicit, requier, día, infraestruc, construcc...  [1, 1]
1  [solicit, lol, lol, infraestruc, construccion,...  [0, 1]

EDIT: Other example:
def category_name(test):
    return [k for k,group in stemmed_search.items() if len(set(group) - set(test)) < len(group) * 0.5]

stemmed_search = {'Food': ['pizza', 'chips', 'cheese', 'tomato', 'apple'],
                  'Animal': ['horse', 'snake', 'dog', 'cat'],
                  'School': ['book', 'pen', 'vocabolary', 'homework', 'student']
                 }
stemmed_articles = [['macheroni', 'car', 'pizza', 'free', 'dog', 'apple', 'chips'],
                    ['dog', 'hungry', 'cat', 'kill', 'snake', 'gas', 'apple'],
                    ['student', 'train', 'car', 'pen', 'homework', 'table', 'book']
                   ]

df = pd.DataFrame([stemmed_articles], ['stemmed_articles']).T
df['categories'] = df.stemmed_articles.apply(lambda x: compar2(x))
df['categories_name'] = df.stemmed_articles.apply(lambda x: category_name(x))

And gives:
                                    stemmed_articles categories  categories_name
0   [macheroni, car, pizza, free, dog, apple, chips]  [1, 0, 0]  [Food]
1        [dog, hungry, cat, kill, snake, gas, apple]  [0, 1, 0]  [Animal]
2  [student, train, car, pen, homework, table, book]  [0, 0, 1]  [School]

Comment: @ChachoFuva `group` is the value of the dict `stemmed_search`. For example for the key `'Animal'` `group` is `['horse', 'snake', 'dog', 'cat']`
Comment: The problem is: I have dataframe with a column a 'n' numbers of rows, each row represent an article. In the other hand I have a dictionary with differrent topics. So, I have to check whichs aricles match in at least of the 50%...if is True obtain `1` otherwise `'0`. For every key in the dictionary.
Comment: that's exactly what this code does :) tag article1 in topic1 and topic2, tag article2 in topic2 @ChachoFuva
Comment: @ChachoFuva is it clear or do you want me to give you another example?
Comment: @ChachoFuva I added another example, I hope I have clarified your doubts
Comment: Thanks. Could you explain me what does group?

How to use 'return' statement?


Where is the project wizard in VS 2017?

Question: I want to create a static library which I want to use in other projects in VS2017 Community but I can't find the right way.
I tried to follow the instructions from here which is for VS2015 but when I want to create a new project I can just provide the name, solution name, location of solution and whether I want to create a directory for the solution or not and with git repository or not.
I remember a project wizard where I could deselect precompiled headers and set the output to a static library.
Did something change or am I missing a component?
Answer: Updated answer:
Create new project and under Visual C++ -> Windows Desktop there is a project template called Windows Desktop Wizard which will open the project wizard.
From VS 2017 15.3 Release notes (credits to user VTT from another question)

The Windows Console and Desktop Application templates now create the projects without displaying a wizard. There's a new Windows Desktop Wizard under the same category that displays the same options as before.

Where is the project wizard in VS 2017?


Backtesting stock returns for Moving Average rule in r

Question: I am trying to backtest stock returns given a 10 month moving average rule. The rule being, if the price is above the 10mnth average - buy, if it is below the 10mnth average - hold the value constant.
I know how to do this in excel very easily, but I am having trouble in R.
Below is my approach in R:
#Downloand financial data
library(Quandl)

SPY <- Quandl("YAHOO/INDEX_GSPC", type = "xts", collapse = "monthly")
head(SPY)

#Calculate log returns
SPY$log_ret <- diff(log(SPY$Close))

#Calculate moving average for Closing price
SPY$MA.10 <- rollapply(SPY$Close, width = 10, FUN = mean)

#Create binary rule to determine when to buy and when to hold
#1 = Buy
SPY$Action <- ifelse(SPY$MA.10 < SPY$Close, 1, 0)

#Create default value in a new column to backtest returns
SPY$Hit <- 100

#Calculate cumulative returns
SPY$Hit <-ifelse(SPY$Action == 1, SPY[2:n, "Hit"] *
                (1 + SPY$log_ret), lag.xts(SPY$Hit, k=1))

Returns do get calculated correctly for an Action of 1, but when the Action is not 1, I find that SPY$Hit only lags 1 time, then defaults to the 100 value, while I would like it to hold the value from the last Action == 1 time.
This formula works very well in MS Excel and is very easy to implement, but it seems that the issue in R is that I cannot keep the value constant from the last Action == 1, how can I do this so that I can see how well this simple trading strategy would work?
Please let me know if I can clarify this further, thank you.
Sample of the desired output:
      Action Return    Answer
 [1,]      0   0.00 100.00000
 [2,]      1   0.09 109.00000
 [3,]      1   0.08 117.72000
 [4,]      1  -0.05 111.83400
 [5,]      1  -0.03 108.47898
 [6,]      0  -0.02 108.47898
 [7,]      0   0.01 108.47898
 [8,]      0   0.06 108.47898
 [9,]      1  -0.03 105.22461
[10,]      0   0.10 105.22461
[11,]      1  -0.05  99.96338

Comment: Can you explain what SPY[2:n, "Hit"] is?
Comment: This is shifting the values such that it starts at the 2nd value of the SPY$Hit column. For example, as the data starts in October 1950, the second datapoint would be November 1950, that is what the SPY[2:n, "Hit"] indicates.
Answer: In Excel there are 2 ways to attain it,
1. Go to the Data command find Data Analysis, find Moving Average,,
In the dialog box you need to put Input data range, Interval (in yur case 10), then output cell addresses.
After finding Result write this formula,
=if(A2 >B2, "Buy", "Hold")
Where A2 hold Price, B2 holds 10 months Moving Average value.

Any where in sheet number cells horizontally 1 to 10 (month number).
Below row put month's value 1 to 10.
Below row calculate 10 months Average.

And finally write the Above written formula to find Buy or hold.
Answer: Here's my guess, let me know what you think.
# Looping
Hit <- matrix(100, nrow = nrow(SPY))
for(row in 11:nrow(SPY)){ # 11 since you have NA's from your moving average
  if(SPY$Action[row] == 1){
    Hit[row] = Hit[row-1] * (1 + SPY$log_ret[row]) # here we needed row-1
  } else {
    Hit[row] = Hit[row-1]
  }
}
SPY$Hit <- Hit

cbind(SPY$Action, SPY$Hit)

For your sample:
x <- data.frame(Action = c(0,1,1,1,1,0,0,0,1,0,1))
x$Return <- c(0,0.09,0.08,-0.05,-0.03,-0.02,0.01,0.06,-0.03,0.10,-0.05)

x$Answer <- matrix(100, nrow = nrow(x))
for(row in 2:nrow(x)){ # 11 since you have NA's from your moving average
  if(x$Action[row] == 1){
    x$Answer[row] = x$Answer[row-1] * (1 + x$Return[row])
  } else {
    x$Answer[row] = x$Answer[row-1]
  }
}
x
       Action Return    Answer
1       0   0.00 100.00000
2       1   0.09 109.00000
3       1   0.08 117.72000
4       1  -0.05 111.83400
5       1  -0.03 108.47898
6       0  -0.02 108.47898
7       0   0.01 108.47898
8       0   0.06 108.47898
9       1  -0.03 105.22461
10      0   0.10 105.22461
11      1  -0.05  99.96338

Comment: This is close but does not work. Seems when I run this code that it simply multiplies the row * (1 + SPY$log_ret) and resets the calculation for the initial matrix creation of 100. Same problem I was having as before.  I'm looking for the value of the "index" of 100 to capture cumulative returns when the Action == 1. Does this make sense?
Comment: Could you post a really small example, maybe 5 or 6 rows where I can see your desired output?
Comment: I posted my desired results as an edit to the original question, let me know if this works.
Comment: Please see the edits. I tried to edit the original code but was unable to run due to exceeding API calls... Let me know what you think.


Chebyshev's inequality to find probability of interval

Question:
Here is how I solved the problem:
$$
X\sim N(\mu=.13, \sigma^2=.005^2)\\
.12\le x\le .14 \\
\mu-2\sigma\le x \le \mu+2\sigma\\
$$
Using Tchebychev's inequality, I get
$$
P(|x-\mu|\le 2\sigma)=1-\frac 1 {4} =.75\\
$$
However, the proposed solution to this problem goes as follows:

Why do these 2 approaches give significantly different answers? is it because of the $\phi_z$ estimate? Thanks!
Comment: There is an arithmetical error in the first calculation. Note that $0.01$ ohms is $2$ standard deviation units, not $200$.
Comment: Thanks I corrected the statement.
Comment: The chebyshev inequality is an $\large{\color{red}{\texttt{in}}}$equality, not an equality. You know how the produced restistances are distributed. Thus you can use the normal distribution. See here: https://en.wikipedia.org/wiki/Chebyshev%27s_inequality
Answer: The key aspect is that Tchebyshev's Inequality gives an upper-bound for the probability while the solution uses the standard normal distribution to provide an approximate calculation of the probability that our random variable is within that given interval. In particular,
$$P(|x - \mu| \geq 2\sigma) \leq \frac{1}{4}$$
$$\implies 1-P(|x-\mu| \leq 2 \sigma) \leq \frac{1}{4}$$
$$\implies -P(|x-\mu| \leq 2 \sigma) \leq \frac{1}{4}-1 = \frac{-3}{4}$$
$$\implies P(|x-\mu| \leq 2 \sigma) \geq \frac{3}{4}.$$
If what you are looking for is a set of bounds, this is a (relatively poor) bound you can use. That being said, you may simply want to use the properties of the normal distribution to get a better approximation of the probability (as the solution suggests).
Answer: The Chebyshev Inequality is a very weak inequality. In your case, after the correction, it says that the probability a resistor is "within spec" is $\ge \frac{3}{4}$. (Note that it does not say that the probability is $\frac{3}{4}$, the Chebyshev Inequality is an inequality.)
If we know that the distribution is normal, we can get an essentially exact expression for the required probability. Note that the Chebyshev Inequality did not lie, the probability really is (a lot) greater than $\frac{3}{4}$.  When we know quite a bit about the distribution of a random variable, one should avoid using the Chebyshev Inequality.
Comment: Thanks for the explanation
Comment: @user1354784: You are welcome.


Prove the set $\left\{\vec{x}\in\mathbb{R}^n : 0 < x_i < 1, 1\leq i \leq n\right\}$ is open.

Question: I'm having a lot of difficulty with proving the set $S = \left\{\vec{x}\in\mathbb{R}^2 : 0 < x_1,x_2 < 1\right\}$ is open. I need to use the definition of an open set to prove this. At this point I mostly have "scratch work."
For any $\vec{a}\in S$,  $\Vert \vec{a}\Vert < 2$ since each component of the vector is between $0$ and $1$.
Let $\vec{y},\vec{a}\in S$ and let $r = 2-\Vert\vec{a}-\vec{y}\Vert>0$. If $\vec{x} \in B_r(\vec{a})$, then
$$\Vert\vec{x}-\vec{y}\Vert \leq \Vert\vec{x}-\vec{a}\Vert + \Vert\vec{a}-\vec{y}\Vert <2.$$
Thus $|x_1-y_1|-|x_2-y_2| \leq \Vert(x_1-y_1,x_2-y_2)\Vert<2$.
I have a hunch this is not the radius I should be using for the ball, but I'm not sure how to properly go about this problem.
Comment: what metric are you using?
Comment: All norms are equivalent on finite dimensional vector spaces, and as you want each component of the vector to have mod less than 1, use the sup (max) norm, then the norm of an arbitrary vector in your set would be $c$ for some $c < 1$ then a ball of radius $r<1-c$ should work?
Comment: Euclidean metric
Comment: Your attempted argument is confusing because you use $a,y,x$ without telling what they are supposed to mean. For example, it seems that $a$ is any point in $S$ and you want to prove that some ball around it is still in $S$. But I can't figure out what you need $y$ for, and how it is determined.
Comment: y and a are both in S, as stated. I was playing around with the triangle inequality to see if I could get somewhere useful. I tried googling what the sup (max) norm is but I'm still a bit confused. For reference, this is for a real analysis course covering the basics about topology of R^n.
Comment: @moofasa how fimiliar are you with product topologies?
Comment: @Riquelme, i only know that it R^n, the euclidean topology, is a product topology of R n times. otherwise my knowledge is minimal.
Answer: Consider $(a,b) \in (0,1)×(0,1)$;
$d_x:= \min (1-a,a)$; $d_y:= \min (1-b,b)$;
$r:=\min (d_x,d_y).$
$B_r(a,b)= $
{$(x,y)| \sqrt{(x-a)^2 +(y-b)^2}<r$}.
$(x,y) \in B_r(a,b)$ implies
$|x-a| < r \le d_x$, and $|y-b| <r \le d_y$, hence
$B_r(a,b) \subset (0,1)×(0,1)$.
Answer: Assume (a,b) in S = [0,1]^2.
Let r > 0 be less than a, 1-a, b, and 1-b.
Show B((a,b),r) is a subset of S.  (Euclidean metric)
Thus, as every point of S is inside an open subset S, S is open.
Alternatively, show S is the union of all the above described balls and conclude that as S is a union of open sets, it is open.
Comment: I'm not seeing how to relate these balls to showing that (x,y) in B((a,b),r) => 0<x<1 and 0<y<1.
Answer: Hint
Show that if $x=(x_1,x_2,\cdots,x_n)\in S$, then by defining $$y=(y_1,y_2,\cdots , y_n)\\|y_i-x_i|<\epsilon$$$y$ will also belong to $S$ for sufficiently small $\epsilon>0$.
Comment: Maybe I am overthinking this, but I don't see how showing that the distance is smaller than epsilon argues that $\vec{y}$ has components that are each between 0 and 1. Could you elaborate?
Comment: Sure. If any $x_i$ falls within $(0,1)$, then by definition $$x_i-\epsilon0$ sufficiently small such that $$00$ such that$$\epsilon<u<1-\epsilon$$


Minecraft crashes after opening my world that was viewed in NBTExplorer

Question: I used NBTExplorer to check my seed. I made no changes that I am aware of, however my save file now crashes when opening.
<code>---- Minecraft Crash Report ----
// Oh - I know what I did wrong!

Time: 11/22/13 12:09 PM
Description: Rendering screen

java.lang.RuntimeException: Failed to check session lock, aborting
    at ajt.h(SourceFile:45)
    at ajt.<init>(SourceFile:31)
    at ajp.<init>(SourceFile:16)
    at ajq.a(SourceFile:83)
    at net.minecraft.client.Minecraft.a(SourceFile:1363)
    at axu.e(SourceFile:166)
    at axv.a(SourceFile:218)
    at axt.a(SourceFile:175)
    at axu.a(SourceFile:191)
    at bfq.b(SourceFile:768)
    at net.minecraft.client.Minecraft.K(SourceFile:597)
    at net.minecraft.client.Minecraft.run(SourceFile:526)
    at java.lang.Thread.run(Unknown Source)

A detailed walkthrough of the error, its code path and all known details is as follows:
---------------------------------------------------------------------------------------

-- Head --
Stacktrace:
    at ajt.h(SourceFile:45)
    at ajt.<init>(SourceFile:31)
    at ajp.<init>(SourceFile:16)
    at ajq.a(SourceFile:83)
    at net.minecraft.client.Minecraft.a(SourceFile:1363)
    at axu.e(SourceFile:166)
    at axv.a(SourceFile:218)
    at axt.a(SourceFile:175)
    at axu.a(SourceFile:191)

-- Screen render details --
Details:
    Screen name: bkf
    Mouse location: Scaled: (152, 116). Absolute: (305, 247)
    Screen size: Scaled: (427, 240). Absolute: (854, 480). Scale factor of 2
Stacktrace:
    at bfq.b(SourceFile:768)
    at net.minecraft.client.Minecraft.K(SourceFile:597)
    at net.minecraft.client.Minecraft.run(SourceFile:526)
    at java.lang.Thread.run(Unknown Source)

-- System Details --
Details:
    Minecraft Version: 1.5.2
    Operating System: Windows 7 (x86) version 6.1
    Java Version: 1.7.0_45, Oracle Corporation
    Java VM Version: Java HotSpot(TM) Client VM (mixed mode), Oracle Corporation
    Memory: 474041104 bytes (452 MB) / 519110656 bytes (495 MB) up to 1037959168 bytes (989 MB)
    JVM Flags: 2 total; -Xms512m -Xmx1024m
    AABB Pool Size: 0 (0 bytes; 0 MB) allocated, 0 (0 bytes; 0 MB) used
    Suspicious classes: No suspicious classes found.
    IntCache: cache: 0, tcache: 0, allocated: 0, tallocated: 0
    LWJGL: 2.4.2
    OpenGL: GeForce 8300/PCI/SSE2/3DNOW! GL version 3.1.0, NVIDIA Corporation
    Is Modded: Probably not. Jar signature remains and client brand is untouched.
    Type: Client (map_client.txt)
    Texture Pack: Default
    Profiler Position: N/A (disabled)
    Vec3 Pool Size: ~~ERROR~~ NullPointerException: null
</code>
Answer: According to this beastnode article the problem is easy to fix.
Open the folder where your save is located (minecraft folder/saves/save name) and delete the session.lock file.
Comment: Ok, that worked, but now my world no longer has any of my structures?
Comment: As in stuff that you built?  If that's the case, it may have regenerated the terrain.
Comment: I think your NBTExplorer use is just coincidental.  It sounds like Minecraft shut down hard.  That could leave a session.lock lying around, and possibly corrupt one of your regions mid-write, which would cause that part of your map to regenerate.


Is it bad/unusual for an oil burner to turn off then immediately back on?

Question: We have an oil-fired hydronic heating system. The boiler is approximately 30-40 years old, and the system was checked and cleaned at the start of this winter. When the burner is running, you can hear it from the first floor. We've noticed that sometimes, after running for a few minutes, the burner will shut off for one or two seconds, and then immediately start up again.
This behavior doesn't really make sense to me, but I'm not sure if it's just a quirk or an indication of a problem. What could be causing the shutoff and then immediate re-ignition? Should we check it out or just stop worrying?
Answer: Get it checked.  Sudden stopping and reigniting can cause blowback.  Not real dangerous, but if it stops and loads up with enough fuel and lights, it can blow back smoke and soot.  What you are hearing is not normal, at least talk to your licensed tech about it.
Comment: blowback sucks ... I came home one day to a layer of soot coating everything in my basement.


What is the difference in efficiency between upflow and downflow furnaces?

Question: I have been doing a bit of research on HVAC systems, and recently learned about upflow vs downflow configurations, and understand that upflow is supposed to be more efficient for heating and downflow is more efficient for cooling; however, I can't seem to find any quantitative information about how much more/less efficient the configurations are.
I'm curious because we recently bought a house in a southern/warmer climate, and the HVAC units are in the attic. According to everything I've read, that would be best suited to downflow, yet both of the units in the house were upflow (and with 95% efficiency furnaces).
So does it make any meaningful difference? Are we talking large numbers of dollars on my gas/electric bill, or just a few cents? (I'm inclined to believe it's the latter, but I haven't been able to find anything to confirm or invalidate that)
Answer: The benefit of air rising (not heat*) is negligible in contrast to the powerful fan and the fact that the path of the duct likely has much more elevation change than the duct trunk at the furnace cabinet. It would be more convincing to argue that a furnace should be in a basement rather than an attic to benefit from convection, but ultimately the weight of the air (what we're really talking about when we say "rising") isn't that important. Many modern units can be installed in either orientation--upflow in a basement and downflow in an attic, for example, or even on their side in some cases.  I've always taken it to be a matter of installation space considerations and not efficiency.
In any orientation it's air over a heat exchanger. I don't think the air cares which way it's blowing. In all orientations the flame from the jet passes into an opening in the heat exchanger horizontally. Flipping the unit along its front panel plane doesn't change that.
Most of the articles a person comes across in searches seem to have been written by marketing departments or other people without much scientific expertise just to flesh out their websites for SEO (and which probably contain regurgitated false wisdom).

* Conduction, convection, radiation--the three primary modes of heat transfer. Only in convection is gravity involved, and the heat must be carried by its medium to move in that way (radiation and conduction are always happening, but are less important here). It doesn't go anywhere by itself. Therefore, warm air rises, not heat, and only when in a parcel surrounded by cooler air.
Comment: I wasn't asking you to do any research, just saying what I had found -- I suppose I should have said "when I searched". In any case, [here](https://www.milani.ca/blog/what-is-a-downflow-vs-an-upflow-furnace-1/) is literally the first result. It simply says upflow is good for heating because of hot air rising, etc etc. If one goes down the list of results, they are all basically different wordings of the same thing, eg *"Downflow furnaces are not as efficient as upflow furnaces because they're fighting against the natural tendency of heat to rise"*. But nothing lists any actual numbers.
Comment: That's what didn't make sense to me; the blower is forcing air through the system anyway, and it seems like whatever effect you might have from convection would be negligible. But if you search for "differences between upflow and downflow furnaces", the main (and pretty much only) thing highlighted is the supposed efficiency impact due to exactly that.
Answer: A person might assert that it's most efficient if the equipment works with natural convection rather than opposing it: blow cold air downward; blow warm air upward. I believe this doesn't really matter. Ultimately the job of the blower is to overcome not only convection forces but also duct friction to push the conditioned air to where it is needed.
There are whole-system advantages when a space is cooled by blowing in air through registers in the ceiling, or when a space is heated by blowing in air through registers in the floor. Mainly this is due to the fact that good mixing naturally occurs between existing room air and newly-conditioned room air. Cold air delivered at the ceiling is going to naturally settle downward toward the floor, mixing with and cooling existing room air on its way, and similar happens with warm air delivered at the floor. We generally prefer our heads to be in cooler air and our toes to be in warmer air. We might be able to set the thermostat a degree or two warmer or cooler than normal as a result, and that's an efficiency gain.
Furnaces exist for upflow, downflow, and horizontal flow mostly for practical reasons having to do with the duct system. A system in an attic would often be positioned horizontally partly so the ductwork can lay on the attic floor, but also because many attics are not tall enough to fit HVAC equipment vertically. Whether the furnace is upflow or downflow doesn't matter when it's on its side!
In some buildings it makes more sense to put the ductwork in the floor; we use downflow furnaces to make that possible.
There is one big drawback to downflow furnaces: the burner is at the "bottom" of the furnace but exhaust gas has to go up. The exhaust of a non-condensing furnace needs to rise; the liquid condensate of a condensing furnace needs to drain/fall back toward the furnace. In either case the flue has to pass in front of the blower, which makes future maintenance of the blower a little more difficult.
Comment: *"A person might assert that it's most efficient if the equipment works with natural convection rather than opposing it"* -- that's exactly what you find if you search for "differences between downflow and upflow furnaces". Many results repeating that same claim, but no information about how much it actually affects things, even when you add terms to make it about the energy costs and other variations. It seems like any effect from that would have to be so minuscule as to be basically non-existent.
Comment: I think it is also worth noting that once the HVAC has overcome the initial transitory period, where air coming in is significantly hotter/colder than air going out, the rather small difference in temperature would make the natural convection effect even less significant, if at all detectable.


iOS OpenGL ES Logical Buffer Loads

Question: Slogging through the list of OpenGL API usage performance warnings given by the Analyze instrument, I am finding that we are generating several logical buffer loads per frame - places where we are not clearing a buffer because a draw call completely overwrites it.
Counterintuitively, introducing glClear() calls for these cases simply moves the location of the warning to the glClear() calls. Apple implement GL_EXT_discard_framebuffer, however using this on its own is also not sufficient to stop the warning. A glDiscardFramebufferEXT() followed by a glClear() does stop the warning, and improves performance significantly, but the glClear() call itself takes time to clear the buffer, which in our use case is a redundant operation.
Do others also find they need to call both functions to avoid the reload cost or am I missing something? Is there a cheap way of hinting to OpenGL that the contents of the framebuffer is about to be completely overwritten and so does not need to be reloaded into tile memory?
Answer: The documentation implies that a fullscreen glClear() sets some magical flag, which is consistent with what I've seen while debugging the same issue. I wouldn't worry about doing a redundant glClear(), as this is the intended usage pattern from what I can tell.
Update: You may also be experiencing the same bug I had, where I was clearing the colour and depth buffers, but forgot to set glDepthMask(GL_TRUE) before calling glClear(). This resulted in a Logical Buffer Load warning.

iOS OpenGL ES Logical Buffer Loads


Backpressure mechanism in Spring Web-Flux

Question: I'm a starter in Spring Web-Flux. I wrote a controller as follows:
@RestController
public class FirstController
{
    @GetMapping("/first")
    public Mono<String> getAllTweets()
    {
        return Mono.just("I am First Mono")
    }
}

I know one of the reactive benefits is Backpressure, and it can balance the request or the response rate. I want to realize how to have backpressure mechanism in Spring Web-Flux.
Comment: @Andrew Tobilko RxJava is different from Reactor which is under the hood of spring WebFlux
Comment: how **to have** backpressure or how **to deal with** it? you already have built-in mechanisms to deal with it, so do you want to find out about them?
Comment: if so, check out [this page](https://github.com/ReactiveX/RxJava/wiki/Backpressure)
Comment: I didn't know that I already have it by default, so maybe how to deal with it is better. I want to know about the mechanism and its configuration in Spring Web-Flux.
Answer: Backpressure in WebFlux
In order to understand how Backpressure works in the current implementation of the WebFlux framework, we have to recap the transport layer used by default here. As we may remember, the normal communication between browser and server (server to server communication usually the same as well) is done through the TCP connection. WebFlux also uses that transport for communication between a client and the server.
Then, in order to get the meaning of the backpressure control term, we have to recap what backpressure means from the Reactive Streams specification perspective.

The basic semantics define how the transmission of stream elements is regulated through back-pressure.

So, from that statement, we may conclude that in Reactive Streams the backpressure is a mechanism that regulates the demand through the transmission (notification) of how many elements recipient can consume; And here we have a tricky point. The TCP has a bytes abstraction rather than logical elements abstraction. What we usually want by saying backpressure control is the control of the number of logical elements sent/received to/from the network. Even though the TCP has its own flow control (see the meaning here and animation there) this flow control is still for bytes rather than for logical elements.
In the current implementation of the WebFlux module, the backpressure is regulated by the transport flow control, but it does not expose the real demand of the recipient. In order to finally see the interaction flow, please see the following diagram:

For simplicity, the above diagram shows the communication between two microservices where the left one sends streams of data, and the right one consumes that stream. The following numbered list provides a brief explanation of that diagram:

This is the WebFlux framework that takes proper care for conversion of logical elements to bytes and back and transferring/receiving them to/from the TCP (network).
This is the starting of long-running processing of the element which requests for next elements once the job is completed.
Here, while there is no demand from the business logic, the WebFlux enqueue bytes that come from the network without their acknowledgment (there is no demand from the business logic).
Because of the nature of TCP flow control, Service A may still send data to the network.

As we may notice from the diagram above, the demand exposed by the recipient is different from the demand of the sender (demand here in logical elements). It means that the demand of both is isolated and works only for WebFlux <-> Business logic (Service) interaction and exposes less the backpressure for Service A <-> Service B interaction. All that means that the backpressure control is not that fair in WebFlux as we expect.
All that means that the backpressure control is not that fair in WebFlux as we expect.
But I still want to know how to control backpressure
If we still want to have an unfair control of backpressure in WebFlux, we may do that with the support of Project Reactor operators such as limitRate(). The following example shows how we may use that operator:
@PostMapping("/tweets")
public Mono<Void> postAllTweets(Flux<Tweet> tweetsFlux) {

    return tweetService.process(tweetsFlux.limitRate(10))
                       .then();
}

As we may see from the example, limitRate() operator allows defining the number of elements to be prefetched at once. That means that even if the final subscriber requests Long.MAX_VALUE elements, the limitRate operator split that demand into chunks and does not allow to consume more than that at once. The same we may do with elements sending process:
@GetMapping("/tweets")
public Flux<Tweet> getAllTweets() {

    return tweetService.retreiveAll()
                       .limitRate(10);
}

The above example shows that even if WebFlux requests more then 10 elements at a time, the limitRate() throttles the demand to the prefetch size and prevents to consume more than the specified number of elements at once.
Another option is to implement own Subscriber or extend the BaseSubscriber from Project Reactor. For instance, The following is a naive example of how we may do that:
class MyCustomBackpressureSubscriber<T> extends BaseSubscriber<T> {

    int consumed;
    final int limit = 5;

    @Override
    protected void hookOnSubscribe(Subscription subscription) {
        request(limit);
    }

    @Override
    protected void hookOnNext(T value) {
        // do business logic there

        consumed++;

        if (consumed == limit) {
            consumed = 0;

            request(limit);
        }
    }
}

Fair backpressure with RSocket Protocol
In order to achieve logical-elements backpressure through the network boundaries, we need an appropriate protocol for that. Fortunately, there is one called RScoket protocol. RSocket is an application-level protocol that allows transferring real demand through the network boundaries.
There is an RSocket-Java implementation of that protocol that allows to set up an RSocket server. In the case of a server to server communication, the same RSocket-Java library provides a client implementation as well. To learn more how to use RSocket-Java, please see the following examples here.
For browser-server communication, there is an RSocket-JS implementation which allows wiring the streaming communication between browser and server through WebSocket.
Known frameworks on top of RSocket
Nowadays there are a few frameworks, built on top of the RSocket protocol.
Proteus
One of the frameworks is a Proteus project which offers full-fledged microservices built on top of RSocket. Also, Proteus is well integrated with Spring framework so now we may achieve a fair backpressure control (see examples there)
Further readings

https://www.netifi.com/proteus
https://medium.com/netifi
http://scalecube.io/
Comment: Even though the answer is really good, I think OP is asking about programmatic (more high-level, API-related) approaches to deal with backpressure.
Comment: Let me add it. Just a moment
Comment: @OlehDokuka Thanks for your good explanation. Could you say to me it's a common way to extend `BaseSubscriber` or Spring Web-Flux's default behavior is better?
Comment: It is better to use the framework control. However, you may do some throttling with limitRate, and only in case if you need fine-grained control, you may extend `BaseSubscriber`. In many cases, it depends on what you really want to achieve. I would suggest you run a conversation at Reactor gitter chat room and have a normal chat there -> https://gitter.im/reactor/reactor
Comment: **This is a starting of long-running processing of the element which requests for next elements once the job is completed.** Could you rephrase it please? Which job are you speaking about?
Comment: Why service B requests 1 elements but  service A gets request of 10 elements ?
Comment: What is the meaninf of acknowledge messages on the diagram? Why does onle service A aknowledges service B ?
Comment: Also I can't understand whether it possible to force producer and consumer work in parrallel? According the text I understood that consumer handled chunk of elements and only after it requests the next element. So at one time works only whether consumer or producer or neither of them
Comment: @gstackoverflow
> This is a starting of long-running processing of the element which requests for next elements once the job is completed.

it basically means that there is some *generic* work that a generic service has to do. The next request to a Publisher could appear from the service (or a Subscriber) only when the generic work has completed.

To summarize - job in this context means some generic works (nothing certain)
Comment: @gstackoverflow

>Why service B requests 1 elements but service A gets request of 10 elements

As I mentioned, there is no proper request coordination in webflux. All backpressure happens over TCP flow control (https://www.brianstorti.com/tcp-flow-control/ and https://www.youtube.com/watch?v=EHaSQBOrYDI). Which means that  reactor-netty has its own buffers, underlying TCP has its own acknowledgment mechanisms so after all, it is possible to write 65K of ***bytes*** so it could be 10k of logical messages but in fact, our recipient may spend dozens of time to process at least one
Comment: @gstackoverflow

> What is the meaninf of acknowledge messages on the diagram? Why does onle service A aknowledges service B

see TCP flow control mechanism -> https://www.brianstorti.com/tcp-flow-control/
Comment: @gstackoverflow

>Also I can't understand whether it possible to force producer and consumer work in parrallel? According the text I understood that consumer handled chunk of elements and only after it requests the next element. So at one time works only whether consumer or producer or neither of them

They are working in parallel. All reactive streams are about non-blocking, asynchronous elements processing
Comment: **All reactive streams are about non-blocking, asynchronous elements processing** but it contradicts schema you provided.
Comment: The schema mentioned above is a kind of sequence diagram, which does not pretend to represent asynchronous/non-blocking behavior but exposes how events appear over time.
Comment: @Oleh Consumer requested 10 elements and said to WebFlux to notify after response. So Consumer won't work until notification. How can it be in parallel?
Comment: The consumer will not work until it gets the first element (nor blocking the thread nor spinning CPU -> https://www.reactivemanifesto.org/glossary#Non-Blocking). Since Stream means that elements could be emitted one by one, it means that once the producer can produce at least one item, the consumer will receive it and start processing it. While the processing on the consumer side is happening the producer is free to produce a few more, since it is clear that ten elements were requested and the consumer has enough capacity to handle 10.
Comment: How do you handle the server-side limit that was handled by libraries like Hystrix in the past? @OlehDokuka I was trying an approach like this one https://github.com/vladimir-bukhtoyarov/bucket4j/discussions/148
Comment: I start to realize that webflux did nothing about backpressure controll when transfering data to the client. All are done by the Transport Layer, is that right ?
Comment: @GuofengPan correct. look at https://rsocket.io/ if you need real backpressure over the network. https://docs.spring.io/spring-framework/docs/current/reference/html/rsocket.html


What is wrong with this program in c++ which states: Print the quantity rows of the matrix if the rows have more that two odd numbers?

Question: This is the main function which prints the quantity of the row which have 2 or more odd elements
#include <iostream>

using namespace std;
bool if_odd(int [], int);

int main()
{
    const int N = 3, M = 2;
    int i, j, a[N][M], k = 0;

    for (i = 0; i < N; i++)
        for (j = 0; j < M; j++)
            cin >> a[i][j];

This code block calls the function, checks whether the rows have 2 or more odd numbers
    for (i = 0; i < N; i++) {
        if(if_odd(a[i], M))
            k++;
    }
    cout << k << endl;
    return 0;
}

This function checks whether two or more elements of the row are odd
bool if_odd(int a[], int b) {
    int i, k = 0;
    for (i = 0; i = 2)
        return true;
    return false;
}

Comment: Why look for modulo 10? Surely, `if(a[i] % 10 != 0)` should be `if(a[i] % 2 != 0)`!
Answer: if(a[i] % 10 != 0)

That line in the is_odd_function will test whether a number can be evenly divided by 10, not by 2, since it is a decimal number.


Should programming languages be intuitive?

Question: What features could be added to a new programming language
to make it more "intuitive"? When it comes to websites and
desktops, we favor high usability, almost intuitive
usability. It is becoming increasingly expected that your
application should "just work". For a certain class of
applications the idea that one has to RTFM, is a mark
against the effectiveness of the application. People tend to
expect the application to just work the way they "think" it
should work. One could argue that this is a worthy standard
that designers should strive for.
Can the same usability rigor apply to programming languages
and developer environments? I realize there are tools like
IntelliSense that provide hints, and a good IDE provides a
lot of assist. But what about the core language itself? What
could be added (or removed) that makes certain programming
techniques or algorithms more obvious to implement? How does
one make regular expressions or recursion more intiutive? Or
is this just folly?
Take a more concrete example: liquid layouts in HTML, CSS,
or Flex and MXML. In HTML and CSS, the box model is anything
but intuitive given the different implementations of
Internet Explorer and the other browsers. And unless someone
reads the documentation or studies the concept of the box
model it would be difficult to "just get it" when designing
a layout on one's first stab at CSS. I would argue this is
why tables thrived in the early days. The box model was
implicit in the concept of a table cell. With the help of
tools like Dreamweaver one could get their mind around
percentage widths and layout within the constraints of table
cells. Then CSS came into maturity and a whole set of valid
reasons emerged for why tables are not for layout. But to
achieve the same effects designers had to really study the
CSS implementations and the box model, and inject a new
layer of abstraction into their thinking.
In another example, I find when programming lots of things
in ActionScript and MXML, the whole concept of fluid layouts
and percentage based widths of elements not very obvious and
doesn't always follow intuition. I understand the basic
problem in that the Adobe Flash player and the layout need
to understand things in absolute pixel terms. When it comes
to the potential width of a component, I understand why
percentages are not immediately obvious to implement at the
core level of the code. Theoretically speaking the Flash
Player needs to know (or calculate) the exact width of a
component so that it can provide the proper geometry to the
video card when doing a draw on the screen. But when you
introduce some concept of percentages then you introduce the
theoretical possibility of an infinite width. And to find
"infinity - 1" pixels is not something a computer can
directly do without some layer of abstraction and
calculation. The viewport must be referenced. The program
must know its boundaries. So absolute widths are the norm,
although humans might prefer to design in terms of
percentages.
When it comes to programming languages can there be
expressions and features that assist intuition when thinking
about a programming task. Or are we better off "thinking
like a computer" and just RTFM'ing the manual when we need
to understand how to implement some feature or layout in
code?
If you could change the syntax or semantics of your
programming language of choice what would you add, change,
or remove to improve the "intuitiveness" of it?
Addendum, the reason for asking this question is inspired by
seeing example of what "novices" were able to achieve in
Smalltalk in Alan Kay's lecture: Doing with Images Makes
Symbols.
Comment: On a side note, this is probably a subjective talk and should be marked "community wiki"
Answer: "If you could change the syntax or semantics of your programming language of choice what would you add, change, or remove to improve the "intuitiveness" of it?
"
Programming is hard.  Really hard.  Syntax changes don't matter much.  IDE's are irrelevant to the fundamental challenge of programming.
The thing that is often baffling is the semantics of the language.
I don't know what "intuitive" means with respect to a thing as abstract as a programming language.  Indeed, "intuition" is probably a bad thing.  Coming to a programming language with intuition means preconceived notions, biases and intellectual junk will take over.
I would never expect to "just get it" for anything on any level anywhere.  Programming requires clear thinking -- not "intuition" -- not "expectation".
The only thing we can ever do is read the manual and understand the unique, distinct, novel semantics of the new thing we're confronted with.
I do know this: elegant simplicity is essential.  Orthogonality of features.  Clarity.  Precision.  Absence of exceptions or special cases.  Above all, simplicity.
Layering on language features is fundamentally bad.
Covering language problems by layering in a complex IDE is worse.

See http://www.cs.utexas.edu/~EWD/transcriptions/EWD08xx/EWD854.html
"when faced with something new and unfamiliar we try to relate it to what we are familiar with. In the course of the process we invent the analogies that enable us to do so.
It is clear that the above way of trying to understand does not work too well when we are faced with something so radically new, so without precedent, that all analogies we can come up with are too weak and too shallow to be of great help. A radically new technology can create such circumstances and the wide-spread misunderstanding about programming strongly suggests that this has happened with the advent of the automatic computer. "
In short, "intuition" and "intellectual baggage" is the problem of the programmer.  The best way to understand a technology is to approach it as something fresh, new and otherwise unknown.

Bottom Line.
The complexity is inherent.
You have two choices.

Develop intellectual tools (i.e., abstraction, summarization, etc.) to cope with it.
Get a job in another field.

Asking for the inherently complicated world of computing to morph into something any one person finds "intuitive" can't happen.  Computing is too complicated to be "intuitive".
Comment: I agree with all of your points, S.Lott, but I must disagree with your conclusion. :) As someone who [attempts to be a] teacher to younger students in Computer Science, the only time I've ever made progress was with good analogies. Furthermore, having studied education (in a very limited, but still formal, sense), I have learned that many believe analogy is really the only way people can digest new ideas. Ultimately those ideas stand on their own, of course, but the analogy is a "key bridge". Such was my impression, at least. I certainly agree that it is unfortunate we cannot discard baggage.
Comment: I think I agree. That is why I also, asked what could be "removed" as well as added.

And you are right in that intuition is too fuzzy of a concept for the world of binary logic and programming. But how is this simplicity best achieved? Surely we don't expect everyone to be assembly programmers. Although there is probably value in understanding assembly to understand higher level implementation.  How does one make it so that the programming clears one's mind of the baggage and assumption that make it difficult?
Comment: Assembler isn't "simple".  Indeed, it's often too complex because of weird hardware special-cases and non-orthogonalities.  Some languages (e.g. Python) are pretty simple and easy to get a grip on.  Programming has no baggage -- it simply is.  If your mind has baggage, that's your problem to leave the baggage behind.  Indeed, that's your *obligation*: to come at a technology with a fresh, empty mind, free of preconceptions.
Comment: Interesting point. In a related note I feel like one aspect that has made me a better programmer is being more naive. Basically I call it my "think like a computer" mode. I know nothing about nothing until I am told explicitly. I find this helps in debugging. But it can be tedious, but ultimately effective strategy.
Answer: Another field I've seen that addresses the complexity of the "syntax" of a programming languages is that of Visual Programming Languages. The basic idea behind VPLs is to take the constructs of programming languages (decisions, subroutines, functions, etc.) and represent them graphically, typically as a data-flow diagram. One such language that's gaining popularity recently is the Microsoft Visual Programming Language. I have not used it, and cannot make claims as to its power, but I have used LabView to great effect and I can say that you can do pretty much anything you can think of even in LabView -- but you do have to think of it in a very different way.
That said, I find I have a personal preference for code rather than VPLs.
Comment: I figured I'd add an answer rather than edit my previous, as it's a different topic.
Answer: One step folks are taking that has as much to do with base class library as it does the language itself -- although to be honest, the two are often synonymous -- is the concept of a Fluent API. The basic idea is to make code "read like a sentence", the idea being that this makes the code more flexible and maintainable.
Comment: @Randolpho, thanks for the reference to Fluent API. Interesting stuff. This is why I ask somewhat broad questions because I get interesting answers like yours that help me learn. Thanks for the response.


Wrapping a method with Task.Run( ... ) hangs when called in a Static constructor

Question: I have a series of long-running functions. I want to wrap them in a Task so that I can run all of them concurrently, rather than waiting for each one to finish sequentially.
The method calls, and all relevant field values and methods and properties exist within a static class.
I'm having a problem wherein the static class constructor fails to complete because it is hanging when I wrap a method within with Task.Run.
In compliance with the requisite Mininmal, Complete and Verifiable example requirements...
using System;
using System.Linq;
using System.Threading.Tasks;

namespace MCVEAsyncHang
{
    class Program
    {
        private static readonly string[] _foo;

        static Program()
        {
            _foo = Task.WhenAll(Task.Run(new Func<string>(One))).Result;
        }

        private static string One()
        {
            return "Foo";
        }

        private static void Print()
        {
            Console.WriteLine(
                _foo.Aggregate((total, current) =>
                     total + string.Format("{0}{1}", Environment.NewLine, current)));
        }

        static void Main(string[] args)
        {
            Print();
            Console.WriteLine("Done");
            Console.ReadLine();
        }
    }
}

I understand I can just create some other method and call that ( and I will if I have to ( begrudgingly so ) ) but if it IS possible, I'd rather keep this within the static class constructor.
Comment: so you know what `Result` does?
Comment: Would you object if I reformatted your code in a rather more conventional way, without all the extra spaces, and using "brace on start of line" format? It may just be me, but the whitespace is making this much harder to read at the moment.
Comment: @JonSkeet Do whatever makes it less difficult to read.
Comment: Will do so in the morning - off to bed now.
Answer: Your task, which will be running in another thread, needs to call _one. That method can't execute until your Program type has been initialized.
The tasks's thread will see that the Program type is already being initialized in the main thread, and so will block until that thread has completed initializing the type. Unfortunately, that's not going to happen - because the type initializer is going to block until your task has finished. Deadlock.
Basically, you should avoid doing too much work in a static constructor. Launching tasks definitely feels like too much work. In this case the deadlock is obvious, but in other cases it could be much more subtle. (Before now I've spent hours debugging type initializer loops, and it's really, really not fun. That was single=threaded code - I dread to think how painful it would be in a multi-threaded environment.)
Comment: So then I don't really have a choice - I have to call these methods in another function. I'll have to bookmark this because I've seen this before but this is the first time I've been able to get an answer that I can understand. Thanks.