Spring Framework 4 & Apache Tiles 3 - no such definition error

Question: I have had a bit of a look around and can't seem to find a post with the scenario that i've come across.
I have written a small web app that utilises Spring MVC 4 and apache tiles 3. I am using apache tiles as I wanted to create a master page template in order to keep the application look and feel constant. I have been developing this in eclipse and running it on and apache 8 server through the IDE. This has all been running absolutely fine through eclipse and the templating was working well.
When I have exported the project as a .war file and run it up on the same apache 8 server outside of the IDE I am receiving the following stack trace when trying to view pages that use the tiles templating:
    2: <%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
3: <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
4:     pageEncoding="ISO-8859-1"%>
5: <tiles:insertDefinition name="defaultTemplate">
6:  <tiles:putAttribute name="body">
7:

8:  Hi <c:out value="${uacc_fname}"></c:out> <c:out value="${uacc_sname}"></c:out> welcome to the home page!!

Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:403)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:347)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:209)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:267)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1221)
    org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1005)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.SouthC.Messwich.WebApp.FilterAuthCheck.doFilter(FilterAuthCheck.java:80)
root cause

org.apache.tiles.definition.NoSuchDefinitionException: Unable to find the definition 'defaultTemplate'
    org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:218)
    org.apache.tiles.template.InsertDefinitionModel.renderDefinition(InsertDefinitionModel.java:132)
    org.apache.tiles.template.InsertDefinitionModel.execute(InsertDefinitionModel.java:99)
    org.apache.tiles.jsp.taglib.InsertDefinitionTag.doTag(InsertDefinitionTag.java:254)
    org.apache.jsp.webapp.home_jsp._jspx_meth_tiles_005finsertDefinition_005f0(home_jsp.java:105)
    org.apache.jsp.webapp.home_jsp._jspService(home_jsp.java:77)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:403)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:347)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:209)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:267)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1221)
    org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1005)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.SouthC.Messwich.WebApp.FilterAuthCheck.doFilter(FilterAuthCheck.java:80)

    org.apache.jasper.JasperException: An exception occurred processing JSP page /webapp/home.jsp        at line 5

I have checked that the server can definately read the tiles.xml definition file as when I remove it from the location that it is specified in, a different error comes up on start up. Below are my configuration files:
servlet.xml
    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="org.test.WebApp"/>

    <mvc:annotation-driven/>

   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
      <property name="prefix" value="" />
      <property name="suffix" value=".jsp" />
      <property name="order" value="1" />
   </bean>
    <bean id="tilesConfigurer"
        class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/tiles/tiles.xml</value>
            </list>
        </property>
    </bean>

    <mvc:resources mapping="/resources/**" location="/resources/" />

</beans>

web.xml
    <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Messwich</display-name>
  <servlet>
    <servlet-name>testWebApp</servlet-name>
    <servlet-class> org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>testhWebApp</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

tiles.xml
    <?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN" "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">

        <tiles-definitions>

    <definition id="defaultTemplate" name="defaultTemplate" template="/template/defaultTemplate.jsp">
        <put-attribute id="header" name="header" value="/template/header.jsp" />
        <put-attribute id="footer" name="footer" value="/template/footer.jsp" />
    </definition>

</tiles-definitions>

Any help with this would be much appriciated, I'm just not sure why it works through the IDE but not when it is exported.
Thanks in advance.
Phil
Answer: <value>/tiles/tiles.xml</value>

Is this correct? Often it's /WEB-INF/tiles.xml
Comment: Hi mck, thanks for your response. I have tried both ways and both work in the IDE but not when I deploy the app as a .war file. I'm really struggling to find any answers on the net. Any ideas?
Answer: Complete Tiles dependency with all supported technologies is achievable with the following      dependency declaration:
<dependency>
    <groupId>org.apache.tiles</groupId>
    <artifactId>tiles-extras</artifactId>
    <version>3.0.5</version>
</dependency>

Basic Tiles dependency with only servlet support can be added this way:
<dependency>
    <groupId>org.apache.tiles</groupId>
    <artifactId>tiles-servlet</artifactId>
    <version>3.0.5</version>
</dependency>

If you need a dependency to Tiles JSP support, declare the dependency this way:
<dependency>
    <groupId>org.apache.tiles</groupId>
    <artifactId>tiles-jsp</artifactId>
    <version>3.0.5</version>
</dependency>

Answer: I know that I am answering something a little old but maybe the right solution, and it could help others.
I think that the problem is that you have given order to the InternalResourceViewResolver and  you forgot to add the view resolver of the tiles that could be something like this:
<beans:bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <beans:property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView"/>
    <beans:property name="order" value="1" />
</beans:bean>

Giving to the other order value = 2


Panels with 4 or more columns

Question: Is it possible to create a panel with 4 or more columns? The sample templates in the Panel module only go as far as 3.
Answer: You could also define your own 4-column panel. There are instructions here: Panels 3: Creating a custom layout in your theme, and a more specific tutorial available here: Creating a four column layout for Panels 3 in Drupal 7.
Answer: You can create as many regions as you which and use CSS/HTML to place them where you want. You have to define the regions in the planel declaration to make it work.
Answer: Yes If panel setting restrict you to go beyond 3 column you can place panels in panels.
Comment: How stupid of me, of course. Sorry to have wasted your time, guys.

Panels with 4 or more columns


Drupal Commerce have customer choose how many items to buy

Question: I would like to give my customers an option of how many products to buy.
So I would like to have a page (or view) that gives the user the option to but 1, 3, or 6 items of my product each with a little more discount.
For example:
 1 for $3.50
 3 for $7.50
 6 for $10.00
And have those three options displayed next to each other.
Also, I would like to give the customer no other quantities. It is either 1, 3 or 6 items that they can buy.
Anyone knows how to do this?
Answer: You could just create 3 separate products in Commerce to represent each quantity. This makes sense especially if you only have a few like you describe. Each "bundle" product can have it's own SKU/model number, and it's own price. This also provides historical record, if you change your bundles in the future, you can keep the old SKU but archive it, and make a new one to represent your new pricing/quantities.
Answer: I think the easiest solution would be to edit the view commerce cart form and change the select box showing the quantity to contains just 1, 3 and 6.
<code>function yourmodule_form_alter(&$form, &$form_state, $form_id) {
   if (strpos($form_id, 'views_form_commerce_cart_form_') === 0 ) {
      //change the select option here
   }
}
</code>
For the discount option, I think you should change the checkout page and deduct the amount that you want to give concession on and show the user that you're giving this concession based on buying 1 or 3 or 6 products.


infinite dimensional supporting hyperplane theorem

Question: I keep seeing an "infinite-dimensional separating hyperplane theorem" stated (e.g. page 8 of this document), but I can't find a corresponding version of the supporting hyperplane theorem.
Here's the separation theorem from the above link:
Two disjoint nonempty convex subsets of a topological vector space can be properly separated by a closed hyperplane (or continuous linear functional) if one of them has a nonempty interior.
So now consider the (open) epigraph of a convex real-valued function $f$ defined on an infinite-dimensional topological vector space. It seems like we should be able to conclude that there exists a supporting hyperplane to the epigraph at any point $(x, f(x))$. This meets the conditions of the above theorem: the epigraph is the convex set with the non-empty interior, while the point $(x, f(x))$ is the other set, which is convex, non-empty, and disjoint from the (open) epigraph.
This would tell us that a subgradient exists at any point.
Am I right about this? It seems right, but then again it's strange that I haven't been able to find it stated anywhere.
EDIT: I should have said "strict" epigraph. I took for granted that the epigraph formed by strict inequality was an open set, which was a mistake. Thankfully, this was clarified when I asked a related question.
Answer: This is the convex support theorem and usually listed as one of the many versions of Hahn-Banach. You can find it stated as theorems HB17 in Section 28.4 and HB4 in Section 12.31 of Schechter's Handbook of Analysis and its Foundations.
Some remarks:
The theorem HB4 states

Any convex function from a real vector space to $\mathbb{R}$ is the pointwise maximum of the affine functions that lie below it. That is, if $X$ is a real vector space and $p:X\to\mathbb{R}$ is convex, then for every $x_0\in X$ there exists $f:X\to\mathbb{R}$ affine that satisfies $f(x) \leq p(x)$ for all $x\in X$, and $f(x_0) = p(x_0)$.

and works for all (finite or infinite dimensional) vector spaces. The same theorem is also true if you work in the category of topological vector spaces. In particular, HB17 is simply a restatement of the above with "real vector space" replaced by "real topological vector space" and "function" replaced by "continuous function". The TVS version in fact follows immediately from the general version by noting that any convex function on a TVS that is bounded above on some open set is in fact continuous.
Comment: Just to clarify: the affine functional constructed in HB4 is not necessarily continuous (bounded). HB17 states that if the convex function is also continuous (which implies that the strict epigraph is open), then it has a continuous (bounded) supporting affine functional.
Comment: Thanks. Let me just make sure I've got this right, though. (I want to make sure I understand his definition of affine.) Assume $f$ is convex. Then given any $x_0$ in the vector space, there exists a bounded linear functional $p_0$ such that $f \leq f(x_0) + p_0$. Correct?
Comment: Sorry, let me revise that inequality to $f(x) \geq f(x_0) + p_0(x - x_0)$.
Comment: Oh, and apparently I've reversed the roles of $f$ and $p$ compared to the excerpt from Schechter.
Comment: What if the original function of interest is itself an unbounded linear functional? Then it is convex, and yet I don't see how there can exist a bounded linear functional "under" it.
Comment: Never mind. This was answered [elsewhere](http://math.stackexchange.com/questions/1890219/every-linear-functional-has-a-bounded-linear-functional-under-it).
Comment: @WillieWong I'm looking for a slightly stronger supporting hyperplane theorem: a hyperplane that *only* supports the maximizers of a convex functional on a set. Posted about it here: https://math.stackexchange.com/questions/4613690/separating-hyperplane-for-maximizers-of-a-convex-functional


Regenerate image styles

Question: I'm currently using Drupal 8.2.3 for my website design. My aim is to use it for publishing my blogs to social media sites, such as Facebook, Twitter, LinkedIN, etc. With that in mind, i'm using image styles to create OpenGraph and Twitter meta tags in my blog posts to properly display content on various platforms.
The problem comes when I make a change to the imagestyle. When I flush the contents, it doesn't automatically regenerate the imagestyle content for my metadata. Is there a way to automatically regenerate the imagestyles and content?
Any help much appreciated.
Answer: There is a setting to flush the image style at admin/config/media/image-styles:

Or you can use drush:
drush image-flush --all (flush all styles)
drush image-flush thumbnail (flush thumbnail style)

Comment: Also, don't forget about the browser cache ;) Ctrl+Shift+R to do a "hard" page reload.
Answer: If you are using Drupal Console (and let's face it, why not?) then you can use:
drupal image:styles:flush image_style

Documenation:
https://docs.drupalconsole.com/en/commands/image-styles-flush.html
Answer:
The problem comes when I make a change to the imagestyle. When I flush
  the contents, it doesn't automatically regenerate the imagestyle
  content for my metadata. Is there a way to automatically regenerate
  the imagestyles and content?

I have a couple of questions to you:

What kind of changes you make to the image style?
What does flushint the contents mean?
By imagestyle content you mean the derivated image from the original one? (so generated image file itself)
Answer: Sometimes - images are not showing, when seeing files in contents.
This mostly caused by server permissions.
For CentOS/Redhat/Fedora/Rocky Linux systems :
chown -R apache:apache /var/www/html/demodrupal/sites/default/
chcon -R -t httpd_sys_rw_content_t sites/default/

Two commands are required/
Answer: It seems you want to generate proper metatags for your node pages (blogs).
To generate them dynamically i propose to add to your module.module file next code with hook_entity_view function:
  function your_module_entity_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->getEntityTypeId() == 'node') {
      $bundle = $entity->bundle();
      switch ($bundle){
          case 'blog':
              $image = $entity->get('field_image');
              $image_id = $image->getValue()[0]['target_id'];
              $image_file = \Drupal\file\Entity\File::load($image_id);
              $uri = $image_file->uri->value;
              $facebook_image_url = Drupal\image\Entity\ImageStyle::load('your_facebook_style')->buildUrl($uri);
              $facebook_metatag = [
                  '#tag' => 'meta',
                  '#attributes' => [
                    'property' => 'og:image',
                    'content' => $facebook_image_url,
                  ],
                ];
               $build['#attached']['html_head'][] = [$facebook_metatag, 'facebook_metatag'];
// the same for other social networks:

$twitter_image_url = Drupal\image\Entity\ImageStyle::load('your_twitter_style')->buildUrl($uri);
//etc
                  break;

          }

      }

    }

And you get this metatag type meta property="og:image"              content="http://static01.nyt.com/images/2015/02/19/arts/international/19iht-btnumbers19A/19iht-btnumbers19A-facebookJumbo-v2.jpg"
Also you can add any metatag in such a manner:
 $facebook_metatag = [
    '#tag' => 'meta',
    '#attributes' => [
             'property' => 'og:title',
             'content' => $your_node_title,
          ],
   ];
   $build['#attached']['html_head'][] = [$facebook_metatag, 'facebook_metatag'];

Comment: I have no issue generating the metatags per se. The problem is regenerating the imagestyles (ie. thumbnails, etc.) so they will be visible for social media websites. I use the 'metatag' module and 'Share Message' module for this purpose.
Comment: As i know there is no aption in metatag module to generate different image styles. So that's why i propose to add metatags programmatically. You can generate dynamically any metatags you need including metatags with image styles. Of course it is a little more complicated without the UI of the metatag module.
Comment: token.module in 8.x has built in support for displaying images with a certaion image style.

Regenerate image styles


Can we use leave one out mean and standard deviation to reveal the outliers?

Question: Suppose I have normally distributed data. For each element of the data I want to check how many SDs it is away from the mean. There might be an outlier in the data (likely only one, but might be also two or three) or not, but this outlier is basically what I am looking for. Does it make sense to temporarily exclude the element I am currently looking at from the calculation of the mean and the SD? My thinking is that if it is close to the mean, it does not have any impact. If it is an outlier, it might bias the calculation of mean and SD and lower the probability that it is detected. I am not a statistician, so any help is appreciated!
Comment: It makes perfect sense and is the basis for many outlier-detection techniques. But rather than inventing your own method, which might or might not work (and the latter is far more likely even with methods newly invented by statisticians, which is why they need careful study), why don't you use one that has been theoretically checked and empirically tested?
Comment: Check out this page on Regression Deletion Diagnostics in R: http://stat.ethz.ch/R-manual/R-patched/library/stats/html/influence.measures.html
Comment: Thanks for pointing that out. I will look up those techniques and see whether they perform well on my data!
Comment: ....And [this](http://stats.stackexchange.com/a/50780/603) answer for illustration of why they can t be depended upon to find more than a single outlier.
Comment: Great thoughts above on the idea of flagging outliers. Sometime back, I had written an article on the idea of loss-pass filters on flagging anomalies. Hope this helps in extending the idea presented above.
Link to the article:
https://www.datascience.com/blog/python-anomaly-detection
Answer: It might seem counter-intuitive, but using the approach you describe doesn't make sense (to take your wording, I would rather write "can lead to outcomes very different from those intended") and one should never do it: the risks of it not working are large and besides, there exists a simpler, much safer and better established alternative available at no extra cost.
First, it is true that if there is a single outlier, then you will eventually find it using the procedure you suggest. But, in general (when there may be more than a single outlier in the data), the algorithm you suggest completely breaks down, in the sense of potentially leading you to reject a good data point as an outlier or keep outliers as good data points with potentially catastrophic consequences.
Below, I give a simple numerical example where the rule you propose breaks down and then I propose a much safer and more established alternative, but before this I will explain a) what is wrong with the method you propose and b) what  the usually preferred alternative to it is.
In essence, you cannot use the distance of an observation from the leave one out mean and standard  deviation of your data to reliably detect outliers because the estimates  you use (leave one out mean and standard  deviation) are still liable to being pulled towards the remaining outliers: this is called the masking effect.
In a nutshell, one simple way to reliably detect outliers is to use the general idea you suggested (distance from estimate of location and scale) but replacing the estimators you used (leave one out mean, sd) by robust ones--i.e., estimates designed to be much less susceptible to being swayed by outliers.
Consider this example, where I add 3 outliers to 47 genuine observations drawn from a Normal 0,1:
n    <- 50
set.seed(123)  # for reproducibility
x    <- round(rnorm(n,0,1), 1)
x[1] <- x[1]+1000
x[2] <- x[2]+10
x[3] <- x[3]+10

The code below computes the outlyingness index based on the leave one out mean and standard deviation (e.g. the approach you suggest).
out_1 <- rep(NA,n)
for(i in 1:n){  out_1[i] <- abs( x[i]-mean(x[-i]) )/sd(x[-i])  }

and this code produces the plot you see below.
plot(x, out_1, ylim=c(0,1), xlim=c(-3,20))
points(x[1:3], out_1[1:3], col="red", pch=16)

Image 1 depicts the value of your outlyingness index as a function of the value of the observations (the furthest away of the outliers is outside the range of this plot but the other two are shown as red dots). As you can see, except for the most extreme one, an outlyingness index constructed as you suggest would fail to reveal the outliers: indeed the second and third (milder)  outliers now even have a value (on your outlyingness index) smaller than all the genuine observations!...Under the approach you suggest, one would keep these two extreme outliers in the set of genuine observations, leading you to use the 49 remaining observations as if they were coming from the same homogeneous process, giving you a final estimate of the mean and sd based on these 49 data points of 0.45 and 2.32, a very poor description of either part of your sample!

Contrast this outcome with the results you would have obtained using an outlier detection rule based on the median and the mad where the outlyingness of point $x_i$ wrt to a data vector $X$ is
$$O(x_i,X)=\frac{|x_i-\mbox{med}(X)|}{\mbox{mad}(X)}$$
where $\mbox{med}(X)$ is the median of the entries of $X$ (all of them, without exclusion) and $\mbox{mad}(X)$ is their median absolute deviation times 1.4826 (I defer to the linked wiki article for an explanation of where this number comes from since it is orthogonal to the main issue here).
In R, this second outlyingness index can be computed as:
out_2 <- abs( x-median(x) )/mad(x)

and plotted (as before) using:
plot(x, out_2, ylim=c(0,15), xlim=c(-3,20))
points(x[1:3], out_2[1:3], col="red", pch=16)

Image 2 plots the value of this alternative outlyingness index for the same data set. As you can see, now all three outliers are clearly revealed as such.
Furthermore, this outlier detection rule has some established statistical properties. This leads, among other things, to usable cut-off rules. For example, if the genuine part of the data can be assumed to be drawn from a symmetric distribution with finite second moment, you can reject all data points for which
$$\frac{|x_i-\mbox{med}(X)|}{\mbox{mad}(X)}>3.5$$
as outliers. In the example above, application of this rule would lead you to correctly flag observation 1,2 and 3. Rejecting these, the mean and sd of the remaining observations is 0.021 and 0.93 receptively, a much better description of the genuine part of the sample!
Comment: The phenomenon where several outliers make single-outlier-detection blind to any of them is often called *masking*. This may help people to locate more information relating to the issue.
Comment: +1 despite the first sentence, which you immediately contradict (the OP's proposal *does* make sense when at most one outlier is assumed; your objection concerns problems with this procedure when that assumption is violated).
Comment: +6, This is a really great answer--clearly & thoroughly explained, illustrated with code, figures & formulas. I tweaked the code formatting slightly to make it a little easier to read. If you don't like it, roll it back w/ my apologies.
Comment: Thank you.  In the meantime I deleted my previous comment, anticipating it will become obsolete after your edits.
Comment: @user603 Nice job creating an illustrative scenario but I think you're throwing out the baby with the bathwater. Regression deletion diagnostics aren't perfect but they are widely applicable and have stood the test of time. Taking the median is fine but I wonder how you'd extend your approach to more complex likelihood based models.
Comment: @whuber : Indeed "make sense" is so broad a characterization as to be useless as an assessment for any methodology. But given the risks (the OP maintains that there could be more than one outliers) the naive solution doesn't make sense from a risk/pay off point of view: the risk are non 0 and I hardly see a pay off over the more established solution I discuss.
Comment: @BenOgorek: 'stood the test of time': the approach illustrated in my example (using the MAD/median rule) was already used by Gauss around 1813. 'More complicated models': sure: you might want to check a recent textbook on the [subject](http://www.amazon.com/Robust-Statistics-Ricardo-A-Maronna/dp/0470010924/ref=pd_bxgy_b_img_y)
Comment: I do want to learn more about robust linear models, and thanks for the resource. I'm linking to one myself, "The Changing History of Robustness," by Stephen Stigler: https://files.nyu.edu/ts43/public/research/Stigler.pdf. According to Stigler, the field of Robust Statistics fully emerged in the 60s and seemed like it would be the new paradigm in the 70s, but it just didn't happen. He argues that the properties of, say, Least Squares, are just too appealing to give up.
Comment: @BenOgorek: I think of robust statistics in a dispassionate way, like I would of any other tool. Knowing what I know about the 'appealing properties of LS', I still wouldn t have used it in a situation like that illustrated above, for the reasons I tried to explain, just like I wouldn t use a fork to eat soup, despite the appealing properties of forks. Maybe Stigler would have, but it is immaterial to me. I really enjoyed reading his books tho and recommend them warmly to anyone interested in the history of statistics.
Comment: @user603 great answer. If I want to sample a value from such a univariate distribution, would a gaussian sample using median (in place of mean) and MAD (in place of stad deviation) be a better/robust sampler?
Comment: @Abhinav sorry for the late answer. What do you mean by a "Gaussian sample"?
Comment: @user603 I mean, sampling a value from distribution N(median, MAD) is better than N(mean, std-dev) ? Or this does not make sense?


How do I make a block that pulls the current node content?

Question: Ok, so I know blocks in Drupal 8 have these things called "contexts" which allow Core to clear cache on a fine-grained basis. I can't find any decent explanation  of how they work, or how to get page variables from them or whatever.
My goal is to have a block type that renders fields or a display mode of the current node into the block content. I have seen elsewhere how one would get the current node, but I don't entirely understand how it's supposed to feed back into cache contexts. I know #cache on render arrays exist, but there's also a bunch of methods from ContextAwarePluginInterface that I'm not sure what they do. Is there some documentation I'm missing?
Comment: You could create a view block and do it that way. I haven't played around much with D8 normal blocks. The only way would be if they allow you to pass some sort of contextual filter to the block.
Answer: There are two completely different kinds of contexts.
Cache contexts, which have nothing to do with this. They're not used to invalidate something, but vary by something (e.g. cache differently for different user permissions). Cache tags are for invalidation.
What you mean are plugin contexts. And yes, blocks are able to use them since a short while (They always could, but the block.module didn't support it properly). As @larowlan said, core uses them mostly for visibility conditions but it works the same for blocks.
One such example that you can look at is the NodeType condition. What you need to do is add the context annotation and then you can use it as $this->getContextValue('node'). The advantage of this is that your block is more flexible and doesn't need to know where the node is coming from exactly, that's up to the user configuring it.
Note that this is not visible in the UI currently unless there is actually more than one node to chose from.
Comment: Great explanation, the plugin context is about visibility. Libertardian should use a view block, as NoSssweat explained in the comment on the question. This will be invisible, if no node is in the current route, so context is not needed for the task.
Comment: No, plugin context is *not* only about visibility.Condition plugins are just one type of plugins that can use conditions. Any type of plugin can be made to work with them. Core just doesn't use it for that, but it works perfectly fine. I'm using it a lot together with page manager for example.
Comment: See https://www.drupal.org/node/2287073 for a core issue that adds context to views blocks. That for example allows the same views block to filter by a context, without hardcoding it to default to the current node. Again, very useful in page manager, where you can e.g. use the same views block to show content for different terms.
Comment: That is interesting, you can do a lot more with the plugin context. Coming from drupal 7 I would use a view block with a contextual filter to display fields of the current node. What is the drupal 8 way to do this?
Comment: I've read the core issue. Now I understand. The contextual filter in views is now based on the plugin context, so when the end user uses this in views, this is done with plugin context in the background. Otherwise it would not work in drupal 8 now. Great work.
Answer: For using node in block, i use context. For example: this block display links for edition and deleting current node:
<?php

    /**
     * @file
     * Contains \Drupal\my_module\Plugin\Block\NodeMenuBlock.
     */

    namespace Drupal\my_module\Plugin\Block;

    use Drupal\Core\Block\BlockBase;
    use Drupal\Core\Link;
    use Drupal\Core\Url;

    /**
     * @Block(
     *   id = "node_menu_block",
     *   admin_label = @Translation("Node Menu Block"),
     *   category = @Translation("My Group"),
     *   context_definitions = {
     *     "node" = @ContextDefinition(
     *       "entity:node",
     *       label = @Translation("Current Node")
     *     )
     *   }
     * )
     */
    class NodeMenuBlock extends BlockBase {

      /**
       * {@inheritdoc}
       */
      public function build() {
        $node = $this->getContextValue('node');
        $nid_fld = $node->nid->getValue();
        $nid = $nid_fld[0]['value'];

        $markup = '';
        $links = ['entity.node.edit_form' => 'Edit', 'entity.node.delete_form' => 'Delete', ];
        foreach($links as $rout=>$text) {
          $url = Url::fromRoute($rout, array('node' => $nid));
          $link = Link::fromTextAndUrl(t($text), $url)->toRenderable();
          $link['#attributes'] = array('class' => array('button', 'button-action'));
          $markup .= render($link).' ';
        }

        $block = [
          '#type' => 'markup',
          '#markup' => $markup,
        ];
        return $block;
      }

    }

More information on drupal.org
Comment: The `context` key is now `context_definitions`.
Answer: The context aware plugin stuff is mainly used by block visibility conditions. E.g see the node condition which takes the current node.
I'm not sure if blocks per-se can hook into this. I can say for certain that you can use the route match service and get the current node, should it exist, from that.
Answer: Check out the Block node contrib module: https://www.drupal.org/project/block_node

Introduction
This module provides a block which can display either the current node or a specified node in a given view mode.
Possible uses
I want to display a specific node in a sidebar region using a teaser view mode. I want to display a list of teaser nodes referenced by an entity reference field on the current node.
Installation
Install as usual, ideally with composer. Enable the module.
Configuration
Place the block using the block layout page as you normally would to place any block.
Configuration options:
Use current node

When checked the current node will be displayed in the block if the block is placed on a node page.

Node to display

Search for a node to display. When selected this node will be displayed in the block.

View mode

Choose the view mode from the available options. The node displayed in the block will be displayed in this view mode.
Other settings are the standard block settings.
Answer: For showing a specific field from the current node in a block, https://www.drupal.org/project/fieldblock


How to change hidden property onHover with useState?

Question: I have a card component and want to change the 'hidden' property on a div that acts as an overlay when you hover over the card.
I´m not sure how to change the class properties of a div when using useState and TailwindCSS. I realize the "const´s" I have in the code, don´t do anything but I was trying to figure it out.
** I´m using NextJS and TailwindCSS
import React from 'react'
import Image from 'next/Image'
import { useState } from 'react'

function TeamCard(props) {

    const [showOverlay, setshowOverlay]=useState(false);
    const hovering = () => setshowOverlay(true);
    const notHovering = () => setshowOverlay(false);

  return (

                {/* Main card content */}

                    <Image
                        src='/alex1.jpg'
                        width="350"
                        height="350"
                        objectFit='cover'
                    />

{props.fullName}

{props.jobTitle}

{props.department}

                {/* Overlay */}

{props.fullName}

{props.jobTitle}

{props.department}

                        LINKEDIN

  )
}

Answer: What you can try is with the use of a ternary operator.
showOverlay ? true(something you want to show) : false(show null);
...

                    <Image
                        src='/alex1.jpg'
                        width="350"
                        height="350"
                        objectFit='cover'
                    />

{props.fullName}

{props.jobTitle}

{props.department}

{
         showOverlay ?

{props.fullName}

{props.jobTitle}

{props.department}

                        LINKEDIN

                :
                null
...
}

Comment: @AnthoonyDev220 Perfect, got it working as intended, many thanks


Good teaching example for demonstrating debugging techniques?

Question: I'm going to be giving a presentation a little later to a student ACM chapter about how they can utilize debugging tools to solve problems in their code. Any ideas for a (preferably short) bit of example code I can use to demo breakpoints, variable inspection, etc.?
My main worry is that I don't want to patronize them by using "Hello World" but I don't want to show where I'm going wrong in a real-world (thousands-of-lines) program either. I'm trying to find that happy medium.
Answer: If feasible, I suggest you spend a few hours now writing a program of your choice of non-trivial complexity. Note down precisely how you used a debugger to iron out the real bugs that were introduced, and reproduce the bugs + debugger steps at the presentation. That way, you can be sure you won't be patronizing them with a toy example.
Answer: If it is all Powerpoint material and the likes of that, I suggest just writing something menial that just describes the essence of what you are trying to convey. Once it comes to applying the actual things you are teaching, you either:

very quickly get lengthy code listings that make it difficult to (ab)use as an example, or
you get code that is stripped to such an extent that it covers one situation perfectly... which in turn means the design of the code itself won't make much sense due to the lack of the bigger picture.

If you want to use some 'real' code, I guess that the example applications that I am sure .NET comes with can serve as an adequate example. Everybody will have those by default, and they are basic enough in nature that they will not be too difficult to understand for someone following a course at the level you are teaching at.
Answer: I always found re-creating mathematical functions to be a terrific learning example; this is especially true for debugging.
For example, create a function that takes a square root of the input, recreating the math.sqrt abstracted function in your language. This teaching technique was used in the iTunes U podcast for MIT Intro to Comp Science.
Answer: Well if you want to go for some simple demos you can try the following:

Debugging an infinite loop (always a fun demo)
Debugging a null reference exception
Debugging a index out of bounds exception
Debugging the order of events in a winform or webform (should be pretty educational)

Honestly if you stick with some of the simpler exceptions you should come up with some great material.


What is the most idiomatic Ruby way to step through a hash, updating values at each step?

Question: I want to step through a simple hash, showing the value for each key-value pair, and give the user the ability to update that value. Crucially, if the user just hits enter and doesn't provide a new value, the old value should survive. Here is my sample code, which works but does not seem particularly Ruby-idiomatic:
mydata = {"key1" => "value1", "key2" => "value2", "key3" => "value3"}

newdata = {}

mydata.each do |k, v|
    puts "current value is " + v.to_s
    input = gets.chomp
    if input.length == 0
        newdata[k] = mydata[k]
    else
        newdata[k] = input
    end
end

puts mydata
puts newdata

Comment: How do they know what they are updating if you are just telling them the value and not the key?
Answer: If you really don't care about the keys:
newdata = mydata.transform_values do |value|
   puts "Current: #{value.inspect}"
   updated = gets.chomp
   updated.empty? ? value : updated
end

That's all there is to it.
Comment: Thanks -- of course in the real application I do care about the keys, my code was simplified to show my question. "transform_values" is new to me, good stuff!
Comment: If you want to rework the whole thing `map` has you covered.


Where does jruby log to?

Question: I see a lot of config options like jit.logging=true, and I want to watch out for things like when the jvm gives CodeCache is full. Compiler has been disabled messages, where does jruby log this stuff? Better yet, how can I tell it which file to log to? Is it just STDOUT and STDERR?
Answer: By setting JRuby properties that affects JIT Runtime Properties ( such as: jruby.jit.logging, jruby.jit.logging, jruby.jit.logging ) you get log to standard error (commonly abbreviated stderr)
You could tell  which file to log to by redirecting stderr to a specific file; for example:
jruby -J-Djruby.jit.logging=true myscript.rb  2> myfile.log

beware, however, myfile.log receives even other stderr outputs; i.e if myscript.rb
executes statements such as:
$stderr.puts "print this in stderr"

you will see "print this in stderr" in myfile.log
Comment: awesome, thanks! and when i read all this stuff about the jvm writing to SystemOut.log and SystemErr.log, is that also just going to stderr and stdout?

Where does jruby log to?


open part of web page in android using uri intent

Question: I have an android app that lists items with url links and on clicking opens the pages using uri,
as below
<code>String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
</code>
I would like to open only for example a video or image in that page but not the whole of it.
Is that possible in android?
Answer: I got what you want to ask.
NO, it is not possible with Intent to open a part of a webpage, it will open entire page,
I suggest you to
1. download and save the image to your drawable folder.
2. create a new actvity , and in the xml associated with that activity add a imageview
3. place your image in that imageview
4. and on the click of the link start the activity with the intent
Answer: I would suggest to either use an ImageView (load the image into it - Download image for imageview on Android) or a VideoView (as stream - http://code.tutsplus.com/tutorials/streaming-video-in-android-apps--cms-19888).
It's not possible with an intent.


ASP.NET MVC form handling unknown number of inputs

Question: I'm building an internal page that allows trusted users to change a parameter setup manually through a form. The inputs to this setup are a list of setupparameters (of unknown size), each with a specific list of values. The user can then select a value for all or a subset of the parameters.
I have attempted to illustrate this with my current model for the view
    public class SetupModel
    {
        public List<SetupParameter> Parameters { get; set; }
    }

    public class SetupParameter
    {
        public string ParameterName { get; set; }

        // list with text=paramvalue, value=paramvalueid
        public SelectList ParameterValueList { get; set; }
        // id of the selected parametervalue if any
        public int? SelectedParameterValueID { get; set; }
    }

My current attempt at rendering a view for this:
<% using (Html.BeginForm("Update", "Parameters") {%>
...
<% foreach( var parameter in Model.Parameters ) { %>

<%: parameter.ParameterName %>

<%: Html.DropDownListFor(x => parameter.SelectedParameterValueID, parameter.ParameterValueList, "Please select") %>

<% } %>
...

My question is how can I render a view that allows me to submit the form and get a reasonably understandable model back to my form action that will allow me to obtain the list of selected parameter values. I'm not aware of the best practices or tricks here, so I will appreciate any feedback I get :)
Answer: You could try using a FormCollection:
public ActionResult Submit(FormCollection formCollection)
{
     //Iterate form collection to get fields

     return View();
}

Answer: You might find this post by Phil Haack useful: Model Binding To A List.
Also note that you'll need to post back an identifier (ParameterName, for example) for each parameter too, so you can indentify which value corresponds to a parameter back in the controller.


How does Windows actually detect LAN (proxy) settings when using Automatic Configuration

Question: When Windows Internet Properties -> Connections -> LAN Settings -> Automatic Configuration is set to "Automatically detect settings" how does Windows actually determine/discover what the settings are? Is it a network broadcast or some kind of targeted query to a server configured somewhere in the registry, or something else?
Comment: This is because in your organization proxy settings are probably distributed through DHCP (or maybe group policy), whereas Chrome only supports the discovery through DNS described in my answer.
Answer: Its simple: Browsers (Firefox works the same) query GET http://wpad/wpad.dat.
If a web server named wpad is resolveable, it should serve wpad.dat, a script file analog to netscape PAC files. MIME type must also be "application/x-ns-proxy-autoconfig".
Answer: This info about WPAD (Web Proxy Auto Discovery) seems to describe the process in detail, though I have confirmed that what Tomalak says is also actually occurring.
Answer: It's a network broadcast, usually using DHCP.
That there wikipedia page should tell you all you need to know.
Comment: I suppose the people who modded this down didn't know that this broken auto-configuration protocol first queries the DHCP server, and only then goes on to try the usual list of default wpad-like URLs.
Comment: Help! How can I see what the DHCP is broadcasting about proxies?
Comment: I believe in MS DHCP config you can specify the proxy server.
Comment: Yes, DHCP is/was used by Microsoft. Other implementations vary.
Answer: The IE configuration described enables a WPAD implementation. Here's the Microsoft explanation of the entire mechanism (probably too much detail for a single post).
Answer: •Go to Tools > Options > General > Connection Settings >
•Set to "Manual Proxy Configuration"


O que são códigos corretores de erros?

Question: O que são e como funcionam os códigos corretores de erros (error-correcting code)? Já vi esse conceito por exemplo no QR Code (em que um código parcialmente danificado e/ou imperfeitamente capturado ainda é legível) e também ouvi dizer que são usados em sondas espaciais, ao transmitir dados em longas distâncias com bastante interferência no sinal. Gostaria de saber mais sobre o conceito, e como/onde aplicá-lo:
(Esclarecimento: me refiro somente aos códigos, não a protocolos completos. A exemplo do QR Code, uma vez impresso ele não pode ser "reenviado", de modo que qualquer capacidade de correção precisa estar presente no código em si.)

Quais os princípios por trás da técnica? Se for algo muito extenso, fico satisfeito com apenas uma introdução seguida de algumas referências.
Quais as limitações? Voltando ao exemplo do QR Code, vi que é possível configurá-lo para tolerar até 30% de erro. Há algum ponto a partir do qual os códigos se tornam excessivamente longos (tendendo pro infinito, é claro[1]), qual a melhor taxa que se pode esperar na prática? E esses códigos corrigem erros em posições arbitrárias nos dados (ex.: início, meio, fim, 1 bit a cada 8, qualquer combinação das anteriores, etc) ou só alguns tipos de erro específicos? É possível o código "corrigir" pra algo diferente dos dados originais?
Em que cenários isso é usado na prática? Existem bibliotecas prontas pra fazer isso, ou é preciso implementar à mão, caso a caso (dependendo das particularidades de cada aplicação)?

Esclarecendo: não estou pedindo uma "lista de casos", apenas saber em linhas gerais se vale a pena usar esse tipo de coisa no dia-a-dia, ou só em circunstâncias excepcionais (noto que na prática se é erro de comunicação, retransmite, se é erro de armazenamento, usa-se backups; não vejo esse tipo de coisa sendo muito discutido, nem mesmo mencionado).

Obs.: já estou familiarizado com códigos detectores de erros (como paridade, checksums, hashes, MACs, etc), estou interessado em códigos que permitam recuperar os dados originais mesmo na presença de algum grau de erro nos mesmos. Naturalmente, para se corrigir um erro primeiro é preciso detectá-lo, mas meu senso comum diz que os mecanismos tradicionais citados acima não são suficientes - afinal, a própria tag de verificação também pode ser transmitida com erros...

[1]: Quando digo "tendendo pro infinito" me refiro ao fato de que é impossível se corrigir um código 100% errado, a menos que ele seja infinito. Minha dúvida é se ao aumentar o nível de tolerância a erros, se o tamanho do código cresce a uma taxa elevada (ex.: quadrática, exponencial...) ou a uma taxa mais baixa (ex.: linear, logarítmica) - permitindo por exemplo atingir tolerâncias de 90% ou mais.
Comment: Sobre a última pergunta, em geral essas técnicas são usadas quando o canal de comunicação é ruidoso (ondas de rádio, imagens de código de barra, etc). Para canais não ruidosos (como uma conexão de rede) normalmente não tem problema fazer um checksum simples e reenviar os dados se tiver problema. BTW a página da wkipédia sobre [Forward Error Correction](https://en.wikipedia.org/wiki/Forward_error_correction) tem mais detalhes do que a que está linkada na pergunta.
Comment: Já conseguiu esclarecer sua dúvida?
Comment: @drmcarvalho Já faz um tempo que fiz essa pergunta, e acabei me esquecendo do assunto hehe! Na verdade já tive algum contato com a parte teórica (embora continue com certa dificuldade de entendê-la), mas estou completamente perdido com a parte prática. Vou dar um "bump" na pergunta, de repente alguém que manja mais do assunto se manifesta...
Comment: Eu escrevi meu próprio codificador de QR, mas dava vontade de chorar ao ler a documentação. Para a parte polinomial eu fui cortando caminho em tudo quanto é lugar que deu (usando tabelas pré calculadas, e simplificando em alguns casos com array para indexar as potências). Eu sabia que eles tinham complicado na geração para simplificar a leitura, mas exageraram :) - Espero que alguém trate do assunto nas respostas, agora que tem o _bounty_, pois apesar de ser um treco chato de implementar, é bem rico em detalhes.
Comment: MelGibsonbr, kkk, o Computer Network do Tanenbaum, aborda esse assunto no cap 3, se é que entendi bem  sua pergunta...É bem interessante, mas não estou apto a explicar... Aliás, vou ficar ligadão, pra ver se alguém se habilita, pq é mais matemática binária do que código de alto nível... Dá pra fazer uma idéia-https://en.wikipedia.org/wiki/Cyclic_redundancy_check
Comment: @MagicHat CRC é bem mais simples, é mais para conferência dos dados. Error-correction em geral tem redundância de informação, pois o objetivo é você conseguir recuperar 100% da informação original sem retransmissão, mesmo perdendo parte dos dados.
Comment: @Bacco CRCs are based on the theory of cyclic error-correcting codes, isto posto, imagino que para se aprofundar em algo tão complexo, é necessário uma base... Mas no livro que citei aborda, outros termos também... Inclusive a recuperação dos dados ... Vale a pena dar uma, "fuçada"...
Comment: @mgibsonbr é uma pergunta boa, porém não manjo do assunto para dar uma resposta, mais vou esperar alguém responder, isso com certeza vai ajudar muito a comunidade.
Comment: @mgibsonbr vou tentar, faz um 10 ai....Trilha sonora necessária... https://www.youtube.com/watch?v=ZSAsI5pnAbc
Comment: Eis uma pergunta muito bacana. :) Ansioso pra ver o desenrolar. Enquanto isso, na sala de justiça: https://www.youtube.com/watch?v=KA8hDldvfv0
Comment: Peri vou precisar mais um tempinho.... https://www.youtube.com/watch?v=-jyTinxcKDg
Comment: @mgibsonbr espero que você ou qualquer outro usuário não tenha interpretado o "kkk" do meu 1º comentário, como sendo sarcástico a sua pergunta... Na verdade estou rindo do seu nick Mel Gibson BR ! x)
Comment: @MagicHat É engraçado que o dito cujo é provavelmente a razão do meu nick - mas não da maneira que parece! Quando criei meu e-mail no yahoo.com.br (sim, sou velho rsrs) queria "gibson", como meus amigos me chamam, mas já estava usado, então pus "mgibson". Quando troquei pro gmail.com, esse também já estava usado, então sem pensar muito (afinal quando é que esse tal de "Google" vai superar o todo-poderoso Yahoo?) passei o "br" que não tinha no domínio pro username. Agora que todo mundo me conhece assim, fiquei "amaldiçoado" com esse nick bizarro pro resto da vida! :P
Comment: @mgibsonbr heheh...faz parte, mas o dito cujo é legal, demonstra perspicácia, agilidade, não se sinta amaldiçoado.....kkkk
Answer: ¯\_(ツ)_/¯
Detecção e correção de erro (Error detection and correction)

O que são e como funcionam os códigos corretores de erros ?

Definição
São técnicas que permitem a entrega de dados de modo mais confiável através dos canais de comunicação.
Introdução
Detecção e Correção, são termos que caminham juntos sendo impossível a aplicação do segundo sem a eficácia do primeiro.
Os canais de comunicação no nível físico de modo geral são suscetíveis a sensíveis falhas, causando muitas vezes a perda ou fragmentação de dados.
"Funcionamento, quais os princípios por trás da técnica, é possível o código "corrigir" pra algo diferente dos dados originais ?"
Existem 2 métodos mais conhecidos para correção de erros:

Solicitação de repetição
automática (ARQ - Automatic repeat request):
Utiliza "acknowledgements" (confirmações através de mensagens enviadas pelo receptor indicando que recebeu corretamente um quadro de dados ou pacote )
e "timesout" (períodos de tempo que antecedem uma confirmação de recebimento) de modo a realizar uma transmissão de dados confiável. Caso o emissor não receba uma confirmação do receptor antes que o "timeout" complete seu ciclo, o pacote é retransmitido até a origem receber uma confirmação ou ultrapassar um número pré-definido de tentativas.

acknowledgements

timeout

Existem 3 protocolos principais que utilizam o método ARQ.

Stop-and-wait
Go-Back-N
Selective Repeat ARQ

Todos tem  base no Sliding window protocol.
2- O segundo método é o Forward error correction (Avançado corretor de
    erro):
O remetente codifica o código de forma redundante usando um código de correção de erros(ECC), através da redundância adicionada ao código o receptor recupera os dados originais, em geral os dados reconstruídos são considerados
"os mais prováveis" dados originais.
A base para esse método, são os trabalhos de Richar Hamming, autor do código de Hamming e  código Hamming(7,4).
Os 2 principais métodos (ARQ e FEC) quando combinados corrigem pequenos erros e evitam a retransmissão e os principais erros
são corrigidos através de 1 pedido de retransmissão : esse processo é chamado de  (HARQ) hybrid automatic repeat request.
Os principais princípios que fazem parte da base para a aplicação são:

o conjunto de códigos Reed-Solomon
código  BCH
MDPC
Algoritmo de Euclides e sua extensão Algoritmo de Euclides estendido
entre outros.

A explicação da lógica utilizada vai além do escopo dessa resposta, mas verificando os links, ou fazendo uma pesquisa aprofundada sobre as nomeações acima pode-se encontrar o total esclarecimento do funcionamento.

"Quais as limitações, qual a melhor taxa que se pode esperar na prática?"

Hoje em dia, devido ao avanço na confecção dos meios físicos, a tolerância em alguns meios é perto de 0 (fibra ótica), e pode ser conquistado
em alguns laboratórios especiais. No entanto a diversidade de meios, nos faz considerar por exemplo as transmissões via rádio
que dependem de um ambiente controlado, o que não é possível no dia dia, pois chuvas, ventos, topologia e outros detalhes naturais ou não, interferem
diretamente na comunicação.
Para quadros codificados pelo CCSDS código Reed-Solomon , menos de 1 em 40.000 quadros errados podem escapar da detecção.

"Há algum ponto a partir do qual os códigos se tornam excessivamente
longos (tendendo pro infinito, é claro)?"

Em tese, a teoria do algorítimo, afirma ser uma sequência finita de instruções. Os algorítimos de detecção e correção, são relativamente curtos, pois atuam sobre partes de tamanho definido (pacotes). No entanto, essa asserção é aplicada aos meios comerciais simples, e levando em consideração a criptografia militar, sondas espaciais e outras aplicações, creio que realmente podem tender pro "infinito", ou algumas milhões de linhas...  Apesar que o uso da lógica serve exatamente para inibir está ideia, eu acho...

"E esses códigos corrigem erros em posições arbitrárias nos dados
(ex.: início, meio, fim, 1 bit a cada 8, qualquer combinação das
anteriores, etc) ou só alguns tipos de erro específicos?"

Eles atuam sobre partes pré-determinadas dos pacotes, ou seja, sim, a arbitrariedade no caso não é o começo, meio ou fim, mas o erro detectado em si.
O Comité Consultivo para Sistemas Espaciais de Dados ( CCSDS ) define o protocolo utilizado para a transmissão de dados de instrumentos de nave espacial através do canal do espaço profundo. Segundo este padrão, uma imagem ou outros dados enviados a partir de um instrumento de nave espacial é transmitida utilizando um ou mais pacotes, variando de 7 a 65.542 bytes, incluindo o cabeçalho do pacote. Esses por sua vez são transmitidos através de quadros de até 2048 bytes.

"Em que cenários isso é usado na prática?"

Internet
Telecomunicações no espaço profundo
Radiodifusão via satélite
Armazenamento de dados
Memória com correção de erro

"Existem bibliotecas prontas pra fazer isso, ou é preciso implementar
à mão, caso a caso (dependendo das particularidades de cada aplicação)?"

O conjunto de códigos e protocolos utilizados para a construção de progrmas direcionados a essas tarefas é denominado Protocolos elementares de enlace de dados.
E o código do protocolo é por sua vez um conjunto de classes.
Algumas definições utilizadas nos protocolos apresentados são armazenadas no arquivo protocol.h
<code>#define MAX_PKT 1024  // Packet size in bytes
typedef enum {false,true} boolean;
typedef unsigned int seq_nr // seq or ack numbers
typedef struct {unsigned char data[MAX_PKT];} packet
typedef enum {data, ack,nak} frame_kind

typedef struct{
  frame_kind kind;
  seq_nr seq;
  seq_nr ack;
  packet info;
} frame;

void waif_for_event(event_type *event);
void from_network_layer(packet *p);
void to_network_layer(packet *p);
void from_physical_layer(frame *r);
void to_physical_layer(frame *s);
void start_timer(seq_nr k);
void stop_timer(seq_nr k);
void start_ack_timer(void);
void stop_ack_timer(void);
void enable_network_layer(void);
void disalbe_network_layer(void);
insira o código aqui
#define inc(k) if(k<MAX_SEQ) k++; else k=0
</code>
Exemplos de protocolos e códigos

Protocolo simplex para canal com ruído
Protocolo de janela deslizante que utiliza go back n
Protocolo de repetição seletiva

Pipelining e recuperação de erros. Efeito de um erro quando (a) o tamanho da janela receptora é igual a 1 e quando (b) o tamanho da janela receptora é grande

Nota sobre esclarecimento:
Na pratica esses protocolos são utilizados de forma embutida nos hardwares responsáveis pela transmissão e recepção dos dados, e são
abstraídos das camadas mais próximas do usuário final, por isso passa desapercebido.
Agradecimento especial a Tanenbaum
Comment: @MagicHat acho desnecessário [comentários como este](http://pt.stackoverflow.com/questions/71515/o-que-s%c3%a3o-c%c3%b3digos-corretores-de-erros/134461#comment278712_134481) a explicar o que didática é depois de já ter sido referido o que falta na resposta. Se deres uma olhada às respostas do mgibsonbr vais vêr que são didáticas e bem explicativas. Acho que, neste caso, se ele comenta que faltam coisas na resposta é de aproveitar e aprender com isso. Não é todos os dias que temos alguém bem experiente a sugerir melhorias no que fazemos. É assim que nos melhoramos, com desafios.
Comment: "Didática" é só uma das qualidades que uma resposta por ter, não necessariamente a melhor. Um manual de operações não é didático, um tutorial sim. Às vezes você precisa de um, às vezes de outro. Dito isso, vou parar por aqui, antes que isso se transforme num bate-boca...
Comment: Agora que a poeira baixou, deixe-me tentar de novo: quando um usuário faz uma pergunta, é prerrogativa dele qual resposta aceitar, ou nenhuma, se não estiver satisfeito. Idem pra quem concede uma recompensa. Os votos, por outro lado, são um reflexo da comunidade, e se sua resposta está sendo bem recebida pela mesma - como a sua está - é isso que realmente importa, não a opinião de um usuário particular como eu. Por fim, citando a Central de Ajuda, 'se a sua motivação for "eu gostaria que outros me expliquem ______", provavelmente está no lugar certo'. Se alguém se dispuser, ficarei agradecido.
Comment: Desculpe não ter respondido antes, mas deixei meu último comentário pouco antes de dormir e não pude responder apropriadamente. Por favor não leve pro lado pessoal. Vamos lá: 1) Lamento se minha pergunta não foi clara. Me referia especificamente ao *forward error correction*, tal como linkado pra Wikipedia, e não tenho interesse [nessa pergunta específica] em ARQ. Comentei "noto que na prática se é erro de comunicação, retransmite" e achei que tinha deixado claro que a pergunta não era sobre esse tipo de técnica. Vou tentar me comunicar melhor da próxima vez.
Comment: 2) Sua resposta original - citando e explicando a distância de Hamming e coisas assim - de fato foi muito relevante e direto no ponto que eu queria. Mas ainda assim, era cópia de conteúdo protegido, e isso é sério. Deixei aquele comentário justamente pra te dar a oportunidade de corrigir o problema você mesmo, antes de notificar à moderação, mas dado o momento que isso aconteceu (1:30 da madrugada no meu fuso horário) não tive como elaborar mais. Agradeço o esforço de pesquisa, e acho que o material citado é uma excelente referência (como link, não como cópia).
Comment: Eu vou dar uma lida mais com calma, depois te dou um feedback. Se a técnica de hamming é suficiente ou não, eu não sei, se eu soubesse exatamente qual é a resposta "certa" eu não precisaria ter feito a pergunta rsrs! Por isso preciso da opinião de pessoas mais experientes que eu. Pelo que eu entendi até agora, boa parte do que foi perguntado essa técnica responde (quase tudo que perguntei nos primeiros 2 itens). Somente quanto à parte prática que continuo no escuro (pois pelo que entendi da sua resposta até agora, na prática isso é usado em escala mínima, dando prioridade ao ARQ).
Comment: E já que você está pedindo opiniões pra aprimorar sua resposta, o que eu penso é o seguinte: apenas citar a técnica não é o suficiente, o ideal seria que ela fosse brevemente explicada ("fico satisfeito com apenas uma introdução seguida de algumas referências") e que pelo menos alguns dos pontos perguntados fossem diretamente abordados (Ex.: "esses códigos corrigem erros em posições arbitrárias nos dados (...) ou só alguns tipos de erro específicos? É possível o código "corrigir" pra algo diferente dos dados originais?" etc), não necessariamente todos, é claro, fica a seu critério.
Comment: Sem problemas! Se alguém se dispuser a dar uma resposta mais didática, isso será priorizado, do contrário não terei problemas em aceitar sua resposta (afinal no SOpt cada um contribui na medida que pode e quer, e toda contribuição é válida).
Comment: Do contrário, sugiro que mantenha sua resposta como está, não há necessidade de qualquer alteração (exceto um pequeno detalhe que eu mesmo sugerirei, favor reverter se não concordar com a edição). É uma boa resposta, bem abrangente, cujo escopo ainda extrapola o que foi pedido. O que é bom: a política do Stack Overflow é evitar jogar fora boas respostas, por isso seria uma pena que sua excelente resposta fosse alterada em demasia por conta de um "capricho" meu. E você sempre tem a opção de dar mais de uma resposta, se assim o desejar (e se não, suas contribuições já são mais que suficientes).
Comment: P.S. Eu vi suas últimas alterações, abordando mais o que foi pedido. Tem meu *upvote*, +1.

O que são códigos corretores de erros?


Ensemble learning with time-varying covariates and effects

Question: We are interested in replicating several duration studies in the literature using ensemble learning methods. After some experimentation, we opted for random survival forests (Ishwaran et al. 2008) for their simplicity and performance. However, the package randomForestSRC in R only allows for time-invariant covariates. As one might guess, many interesting theoretical problems usually involve parameters that take on different values over time. Does anyone know how to implement TVCs in R using machine learning? We would prefer sticking to random forests, but naturally would switch if there is a better alternative.
Answer: The most widely used approach for survival analysis of time-varying covariates (TVCs) are Cox models. There you need to create a dataset with TVCs which is described in this vignette
fit.cox <- coxph(Surv(time1, time2, event) ~ x), data = data)

However there is also the possibility to include TVCs in random survival forests. This paper by Wongvibulsin, Wu, and Zeger (2019) extends the randomForestSRC package to handle TVC, but you may need to contact the authors for any relevant code.
Comment: There appears to be an implementation of RF-SLAM (algorithm described in Wongvibulsin, Wu, and Zeger 2019) here: https://github.com/mattrosen/rfSLAM
Comment: See also: https://cran.r-project.org/web/packages/LTRCforests/


How to get kill command result in bash script

Question: I have a bash script which run a command to get its result and do something depends on the result. Here is the script:
#!/bin/bash
commandResult=$(($myCommand) 2>&1)
if [[ "$commandResult" == *Error* ]]; then
    x="failed"
else
    x="success"
fi
echo $x
exit 0;

There is no problem with this script, the issue is when I try to kill $myCommand in the middle of running the script via kill -9 $myCommand in command line, the $commandResult will be null and the "success" will be printed.
How could I put the kill result in the $commandResult or any other way to find out if process killed in this script?
Any help would be much appreciated.
Answer: You should be checking your command's exit code, not its output to standard error. myCommand should exit with 0 on success, and some non-zero code on failure. If it is killed via the kill command, it's exit code will automatically be 128+n, where n is the signal you used to kill it. Then you can test for success with
if myCommand; then
    echo success
    exit 0
else
    status=$?
    echo failure
    exit $status
fi

Also, you probably don't need to use kill -9. Start with kill (which sends the gentler TERM signal); if that doesn't work, step up to kill -2 (INT, equivalent of Ctrl-C).


visualizing confidence intervals in longitudinal models

Question: I have a longitudinal dataset with continuous variables for 6 different time points nested within each ID. I prepared a longitudinal Poisson model with ID as a random effect for the intercepts, which in itself is working fine. In preparing the figures for the report, I prepared a figure with the predicted values for each of the 6 timepoints and the confidence intervals derived from the model.
Then I grew uncertain and started looking in the literature. I could not really decipher what other people had done for their confidence intervals since it was not shared in the methods section or figure legend. Looking at some of these figures I am left wondering whether some have just reported either means or medians with 95%CI or IQR. I guess median/IQR could be defended, but if means and CI´s are reported, wouldn't the confidence interval be biased due to within-subject correlation?
So I guess my question is if I should use my calculated confidence intervals from the model (with ID as a random intercept) or if there is another universally accepted way of doing this that I have missed?
Thanks for the input regarding confidence and prediction intervals. What I am looking for is the most appropriate way of demonstrating the uncertainty of our measurements over time in three groups - see figure - whether I should include the fact that the measurements are correlated over time or not.

Left is Poisson based fitted population level values and to the right is means and confidence intervals for each time point disregarding the within-subject correlation
Comment: There are a few things in your question I'm not quite sure about. (1) You write that you show "predicted values" and CIs. But predictions are about not-yet-seen realizations, so a prediction interval would be more appropriate than a CI ([there is a difference](https://stats.stackexchange.com/tags/prediction-interval/info)). Or are you really talking about *fitted* values, not *predicted* ones? ...
Comment: ... (2) I am a bit confused about just what you want to show. You can show fitted/predicted values with CIs or PIs, per above. Or you could also show means or medians within groups or timepoints, together with CIs, or with quantiles (probably not IQRs, because these are just numbers - you are probably thinking of visualizing the 25th and the 75th percentile within groups). Either one can be informative. Which one you want to show depends on, well, what you want to show. But whether CIs are biased is only a question *subsequent* to that decision.
Comment: @StephanKolassa -- please see edits
Comment: Could you please share some reproducible data?
Comment: @Quinten - dont know how reproducible data would help in this question as the uncertainty revolves around the issue of whether to report model based confidence intervals that include the uncertainty related to the longitudinal data or disregard the latter and just report the quartiles etc-- however, the width of the confidence intervals are quite different
Comment: I think you might want to look into the distinction between simultaneous confidence intervals and individual confidence intervals. Aside that, what you have seems fine.
Comment: In the model, how did you deal with the intra-individual correlations? Did you treat individuals as fixed effects, random effects, or with some type of clustered variance estimate? The proper interpretation of the confidence intervals, and thus the best way to report them, would depend on your choice. Please edit the question to provide that information, as comments are easy to overlook and can be deleted.
Comment: @EdM please see edits-
Answer: The question is whether you want to display "the uncertainty of our measurements over time" (essentially the raw data) or the uncertainty of the model estimates over time.
If all you have is a simple Poisson model of counts versus time and random intercepts for individuals, and you have complete data, then it might make sense to take the original data and show means with standard errors. Boxplots can be even more useful for illustrating the variability among measurements. Then your model evaluates whether any differences apparent in the raw data are statistically reliable.
Particularly if there are other covariates in your model, however, plots of raw data alone can be misleading. Then you should report  means estimated from the model for each condition; showing 95% confidence intervals (CI) for those estimates is frequent practice. Those would be determined from the model coefficients and the variance-covariance matrix of the estimates. For your data, a logarithmic y-axis might make sense. Make it clear to your audience precisely what you are displaying.
A few warnings.
First, as comments indicate, a CI for a model estimate is not the same as a prediction interval. Use of the phrase "prediction interval" isn't always consistent, but it typically includes both the error in the model estimate and the additional error in sampling: for example the Poisson variance for observations here, or the residual variance in an ordinary least squares model.
Second, it's tempting to equate overlap of CI with lack of significance. That's incorrect. This page explains the relationship for simple t-tests, but the principles hold in general: non-overlap of CI is too stringent a test for "significance." The emmeans package can provide a visual display for which non-overlap of arrows is approximately related to significance of differences among model estimates.
Third, @usεr11852 raises an interesting point about displaying pointwise CI (like you seem to have) versus "simultaneous" CI. The latter involve a correction for multiple comparisons so that the CI represent the entire family of comparisons. Provided that you are clear in describing what you show, one could argue either way about what to plot.


Install k8s 1.26 with Kubespray skipping all Calico steps

Question: I am working on installing/upgrading k8s cluster to version 1.26 and I wonder if I can somehow skip all the steps which tests/installs/configures Calico. The reason - I want to use Tigera operator to manage calico and I want to skip the steps related to Calico. Is there any key/argument for Kubespray which can do this?
I want to run Kubespray so it will skip all the steps related to Calico.
Answer: You might want to check out this github issue, that recommends setting kube_network_plugin: cni and then use the tigera operator.
The documentation has a section on "Switch your Calico installation from manifest-based resources to an installation managed by the Calico operator." so that might work.
Alternatively, the users in the calico slack channel might be able to help.
Comment: that's awesome, thanks for the tip! I will try this tomorrow


vba update cell with data validation?

Question: I have 2 worksheets, Product Groups and Database:
My sheet, Product Groups has a layout like below:
A4
A5      {Button}
A6
A7
A8

A user can add values to column A4 onwards. Meaning this list could extend to A4- A8 or A4 to A100.
I have created a button that allows the user to run a macro after they have updated the values in column A.
This macro should insert the values from A4 to Last used row into my data validation in Cell T7 on my database sheet.
Here is my code:
Sub button()
Dim lastRow As Long
lastRow = ThisWorkbook.Worksheets("Product Groups").Range("A4" & Rows.Count).End(xlUp).Row

Dim ws As Worksheet
Dim ws2 As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Database")
Set ws2 = ThisWorkbook.Worksheets("Product Groups")

Set rng = ws.Range("T7")
Set range1 = ws2.Range("A1:A" & lastRow)

With rng.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & ws2.Name & "'!" & range1.Address
End With

End Sub

For some reason i get an error on this line:
lastRow = ThisWorkbook.Worksheets("Product Groups").Range("A4" & Rows.Count).End(xlUp).Row

Application undefined or object undefined error.
Please can someone show me where this is going wrong? THanks
Comment: nearly that; it's `LastRow = ThisWorkbook.Worksheets("Product Groups").Range("A" & ThisWorkbook.Worksheets("Product Groups").Rows.count).End(xlUp).row`
Comment: Try `lastRow = ThisWorkbook.Worksheets("Product Groups").Range("A4" & ThisWorkbook.Worksheets("Product Groups").Rows.Count).End(xlUp).Row` ...(You may not need the second `ThisWorkbook.` but you will need the worksheet.)
Comment: @user3598756 Beat me to it. You can't define row 4 using `Range("A4")` and then try to redefine the row. You would just use the Column A portion of `Range` and define the row portion using the `.Rows.Count`.
Answer: the solution has been given in comments
I use the answer that shows it again along with a possible refactoring of your code
Option Explicit

Sub button()
    Dim range1 As Range

    With ThisWorkbook.Worksheets("Product Groups")
        Set range1 = .Range("A1", .Cells(.Rows.count, 1).End(xlUp))
    End With

    With ThisWorkbook.Worksheets("Database").Range("T7").Validation
        .Delete 'delete previous validation
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Formula1:="='Product Groups!" & range1.Address
    End With
End Sub

Comment: Princess.Bell, you may also find the time to give feedbacks to answers to previous questions of yours!

vba update cell with data validation?


Ubuntu concurrent connections

Question: I'm behind a proxy that is "Enterprise DDoS Protected". On a normal day with normal connections to all my servers the concurrent connections on the proxy is 17,000. Yes 17,000 is normal for the nature of my sites. 90% of the traffic is requesting bytes of data then that's it, no need to connect again for a minute. The problem with the "Enterprise DDoS Protected" proxy they are telling me if I would reduce my concurrent connections It will stop hanging up or have faster latency times. They have tuned it on there end but my servers seem to keep the connections open to long.
I'm running on my servers
Ubuntu Linux 11.10
Linux 3.0.0-17-server on x86_64
Intel(R) Xeon(R) CPU E31230 @ 3.20GHz, 8 cores

on all my servers. My questions is how can I reduce the concurrent connections to where after it connects it closes the connection out like after 10 seconds on my servers?
Comment: What software is running on the server?  If you need a timeout, it should be implemented there.
Comment: Ubuntu Linux 11.10
Comment: I mean, what application software are the users connecting to?  I'm not talking about the OS, I'm talking about the service you're providing.
Comment: HTTP port 80 apache2
Comment: Ok - what is the HTTP server software that you're using?
Comment: It is apache2 on all the servers.
Answer: To force an HTTP keep-alive connection to close after a certain time in Apache, use the KeepAliveTimeout directive.
KeepAliveTimeout 5

Set this based on the expected time that the client needs to complete a set of requests to load a resource - you want to let the connection stay alive long enough for that to occur, then have the server close it when it's no longer needed.  5 seconds should be enough in most cases.
Comment: Also on the MaxKeepAliveRequests I had it set to 2. Now since I'm behind a protected proxy and the servers only see one IP should I set that to 0?
Comment: 0 makes it unlimited, but it'll still be limited by the timer - so either way is fine.

Ubuntu concurrent connections


EBCDIC unpacking comp-3 data returns 40404** in Java

Question: I have used the unpack data logic provided in below link for java
How to unpack COMP-3 digits using Java?
But for the null data in source it returns 404040404 like on Java unpack code. I understand this was space in ebcdic, but how to unpack by handling this space or to avoid it.
Comment: You could simply compare the field with 0x40 in each character then replace it with 0x00 for all except the last character and make that 0x0f.  So if its a 3 byte field you would search for 0x40 in [0], [1] and [2] and if its 0x40 in each then replace the fields with

[0] = 0x00
[1] = 0x00
[2] = 0x0f

and that will unpack to 0
Comment: I would not check every byte but just look at the last byte. If it contains a valid sign-nibble I would go along with trying to unpack the field and come up with some strategy for all other cases (return 0, throw an error,...?).
Comment: i tried it replaces the numeric value 4 as well.
char[] NON_PRINTABLE_EBCDIC_CHARS = new char[] { 0x00, 0x40 };

  for (int currentByteIndex = 0; currentByteIndex < packedData.length; currentByteIndex++) {
   //added for comp and comp3 datatype issue with null
   int character = packedData[currentByteIndex];
   boolean isBlank = false;
      for (char nonPrintableChar : NON_PRINTABLE_EBCDIC_CHARS) {
          if (nonPrintableChar == (char) character) {
           isBlank=true;
          }
      }
      if(!isBlank) {
Comment: if the source value is 444. Will it decode correctly? it wont replace with zero?
Comment: If you're seeing spaces, you likely have a input data error or misalignment. No well-designed COBOL program would ever place spaces in a COMP-3 field.
Answer: There are two problems that we have to deal with.  First, is the data valid comp-3 data and second, is the data considered "valid" by older language implementations like COBOL since Comp-3 was mentioned.
If the offests are not misaligned it would appear that spaces are being interpreted by existing programs as 0 instead of spaces.  This would be incorrect but could be an artifact of older programs that were engineered to tolerate this bad behaviour.
The approach I would take in a legacy shop (assuming no misalignment) is to consider "spaces" (which are sequences of 0x404040404040) as being zero.  This would be a legacy check to compare the field with spaces and then assume that 0x00000000000f as the actual default.  This is something an individual shop would have to determine and is not recognized as a general programming approach.
In terms of Java, one has to remember that bytes are "signed" so comparisons can be tricky based on how the code is written.  The only "unsigned" data type I
recall in java is char which is really two bytes (unit 16) basically.
This is less of a programming problem than it is recognizing historical tolerance and remediation.


Numbers with more than n divisors

Question:
Numbers with more than 4 divisors = multiples of numbers with exactly 4 divisors. This only applies to 4 (and 2, of course): e.g. numbers with more than 3 divisors != multiples of numbers with exactly 3 divisors.
Numbers with more than 5 divisors = multiples of OEIS A068993

My quick question is: are these two facts obvious and/or well-known?
I assume that the answer is "yes", but I know pretty much nothing about mathematics, so I wanted to ask this question. I would have asked it in the chat, but I have not enough reputation.
A simple yes/no answer is fine for me, but of course if you want to add an explanation, it's even better. :)
Edit: why I don't think this question was a duplicate. The answer is the same as the answer to Finding out the number of divisors (I have no reason to doubt it, even though I still have to understand the answer to my question!). But, as far as I can understand, "duplicate" applies to questions, not to answers. Otherwise, the following statement from the help wouldn't make sense:

[...] we love (some) dupes. There are many ways to ask the same question, and a user might not be able to find the answer if they're asking it a different way.

Now, my question is not the same as "finding out the number of divisors", so it isn't a duplicate.
Comment: I think the first is something that is a pretty routine reformation of the original statement. I'm kind of skeptical of statement 2; I think it's only a "subset" relation, rather than equality.
Comment: @Ross Millikan Don't see how this is a duplicate, sorry.
Comment: @pjs36 1. Could you please tell me what "the original statement" is? Thanks. 2. Based on my computations, it's equality, not just a subset.
Comment: @Ross Millikan I see that you have edited your comment, explaining why this is a duplicate. Thanks. I will read the Wikipedia page and reply as soon as possible (it won't be soon...).
Answer: The reason that numbers with more than four divisors are multiples of numbers with exactly four divisors are that the numbers exactly four divisors are of the form $pq$ for distinct primes $p,q$ or $p^3$ for prime $p$.  To have more than four, the number has to be of the form $p^4, p^2q, \text{ or } pqr$  for primes $p,q,r$ or more complex.  All of these are multiples of a number with exactly four factors.   Conversely, any multiple of a number $pq$ or $p^3$ will have more than four divisors.
A number with more than five divisors will be a multiple of a number in your OEIS sequence, because this sequence is all numbers of the form $pq$ or $p^4$.  As $pqr$ has eight divisors and $p^2q$ and $p^5$ have six, all multiples of the elements of this sequence will have more than five divisors.
Added:  for the fact that numbers with more that three divisors are not exactly the numbers that are multiples of numbers with exactly three divisors can be shown by example:  $6$ has four divisors, while $1,2,3$ do not have exactly three.  The general case is that a number of the form $pq$, with $p,q$ distinct primes, has factors $1,p,q,pq$ and none of $1,p,q$ have exactly three divisors.
Comment: There are 3 things I don't understand in the 1st answer (bet the problem is me!). 1) "All of these are multiples of a number with exactly four factors." This is the point to prove. Did you do it? 2) "Conversely, any multiple of a number pq or p^3 will have more than four divisors." Shouldn't we prove that "only multiples of [etc.]"? 3) You don't mention numbers with more than 3 or >4 divisors. Also, 2 questions about the 2nd answer: 4) "is all numbers of the form pqpq or p^4" Is this equivalent to the definition of the sequence? 5) Again, shouldn't "all multiples of" be "only multiples of"?
Comment: For 1, look at the factorization. If a number has any two distinct prime factors $p,q$, it is a multiple of $pq$, which has exactly four factors.  If it has only one prime factor, it is $p^k$ for $k \gt 3$, and is a multiple of $p^3$.  This proves more than four implies multiple of one with exactly four.  Then for 2 I am proving that multiple of a number with four implies more than four.  An even simpler way is to say a multiple of a number with four factors has those four plus itself (and maybe) more.
Comment: For the second question, yes, the sequence is all the numbers I  cited.  Multiplying by any number gives a result with a prime factorization that includes what I show, and then there will be more than five divisors.
Comment: For all these questions, you need to reflect on the divisor function given in the Wikipedia page I referenced above.  The number of divisors of a number is given by the pattern of exponents in its prime factorization.  If you want exactly $k$, you need to factor $k$ and establish the patterns that can do that.  That is where exactly 4 implies $p^3$ or $pq$ comes from and all the other claims I make.
Comment: I'm quite busy these days, but I plan to review the answers (and mark the best one) as soon as I can.
Comment: "For 1 [etc.]": OK. "Then for 2 I am proving that multiple of a number with four implies more than four": I still don't see how you proved it.
Comment: "yes, the sequence is all the numbers I cited": the equivalence is not explicited in the OEIS page; anyway, I accept your authority. "Multiplying by any number gives a result with a prime factorization that includes what I show, and then there will be more than five divisors": I still see this as "all multiples of the numbers in the sequence", not "only multiples [etc.]"; sorry. :(
Comment: To have more than four divisors means to have factors at least $pqr, p^2q,$ or $p^4$.  The first are multiples of $pq$, which has exactly four divisors.  The last is a multiple of $p^3$. I have shown an explicit divisor with exactly four factors for each number that has more than four.
Comment: As for my question 2-of-5: ...it was a very stupid question.
Comment: I _finally_ got why "numbers with more than 4 divisors = multiples of numbers with exactly 4 divisors". I still don't understand why this doesn't apply to any number >4. I'll get back at this.
Comment: For example, numbers with more than 5 divisors can be of the form $pqr$ and have eight divisors or $p^2q$ and have six divisors among other patterns.  The numbers with exactly 5 divisors are specifically of the form $p^4$, so numbers with more than 5 divisors may well not have a factor with exactly five divisors.
Comment: So there isn't a "general" reason for "numbers with more than n divisors = multiples of numbers with exactly n divisors" applying just to n=2 and n=4, right? If so, I can consider my question fully answered. Now I just have to check Sayantan Santra's answer and mark the "best" one for me.
Comment: While I appreciate both this answer and Sayantan Santra's, I've marked this as the best one because I feel this one is the most accessible to newbies like me, i.e. to the kind of people who could ask the questions I've asked.
Comment: It depends on the types of prime factorization that can give you more than $n$ divisors.  If you multiply by some prime that was not there before, you double the number of divisors, so generally those with more than $n$ may not be a multiple of one with exactly $n$.  $2$ and $4$ are small numbers, and that matters.
Comment: Yeah, I guess this is a quite general reason. :)
Answer: For starters, the $\tau$ function is multiplicative. That means, $\tau(mn)=\tau(m)\tau(n)$ where $(m, n) =1$. But, as you seek intuition, I won't use it in the discussion. Now, your claim is true for $4$. The numbers which have $2$ divisors are prime $p$. Now, if we multiply it by something that the product has more than $4$ integers, then the multiplier must be of the form $p_1 p_2$ where at most one can be $p$ itself. But, we can always represent it as a multiple of $p_1 p_2$ which has exactly $4$ divisors. Now, a similar argument can be stated about integers with exactly $3$ divisors, which must be of the form $p^2$. So, every integer that has more than $4$ divisors can be expressed as a multiple of an integer with exactly $4$ divisors. But, no similar argument can be presented for numbers with higher divisor counts. Hence your claim is indeed true.
For the second case, just use the algebraic form of the $\tau$ function. Although, some simple combinatorics can give you the intuition.
Comment: "Now, a similar argument can be stated about integers with exactly 3 divisors": you don't mean that numbers with more than 3 divisors = multiples of numbers with 3 divisors, do you? Also, a hint of what kind of combinatorics can give me the intuition about the second problem would be nice; but if you don't care about explaining it to someone who should study rather than asking questions, I understand, :)
Comment: @milivella No, I meant that it can be easily shown that the multiples of those numbers which have more than $4$ divisors can be written as a multiple of a number with exactly $4$ divisors in a similar manner.
Comment: @milivella And, it's some elementary combinatorics. Factorise a number into primes and then try to work out a general form for its divisors. See how many are possible. That will show you how the $\tau$ function works.
Comment: Sorry, I still don't understand where "integers with exactly 3 divisors" fit. As for the second case, I guess my problem is that I don't understand the definition of OEIS A068993. Thanks for the hint anyway.
Comment: @milivella Well, the problem could have been treated in a much more general way as some of the answers suggest but as you had requested insights, I decided to write it in the most informal way I could device. What I did is I simply showed that every integer with more than $4$ divisors can be expressed as the multiple of a number of exactly $4$ divisors which is equivalent to your claim.
Comment: @milivella You can take as a proof using contradiction. Suppose, I'm saying that the claim isn't true. So, there must be some exceptions. So, they must be multiples of numbers of exactly $2$ or $3$ divisors. Now, that makes them multiples of numbers of exactly $4$ divisors as we have shown. Contradiction!
Answer: If a number is product of distinct primes then it has a power of $2$ number of divisors (it has $2^{\omega(n)}$ divisors, where $\omega(n)$ is the number of prime divisors of $n$).
So if your number is product of distinct primes all of its divisors has a power of $2$ number of divisors.
From here we deduce if $k$ is not a power of $2$ then there is a number $n$ such that $n$ has more than $k$ divisors and no divisor of $n$ has exactly $k$ multiples. We just take $p_1p_2\dots p_r$, where $p_i$ is the $i$'th prime and $2^r>k$.
So now we just have to check $2$ and $4$ are the only such powers of $2$ that work. To see this just now that $p_1^2p_2^2\dots p_r^2$ has $3^r$ divisors, and any divisor of this number that has a power of $2$ number of divisors has at most $2^r$ divisors.
So we must now all we must prove is that given $2^n$ with $n>2$ there is an $r<n$ so that $3^r>2^n$ , so all we must prove is $3^{n-1}>2^{n}\iff \frac{3}{2}^{n-1}>1$, which of course is true when $n>2$. Since $\frac{3}{2}^2=\frac{9}{4}>2$.
Finally, to check $4$ works is easy, if the number is of form $p^k$ and has $4$ or more divisors then $k\geq 3$ and so $p^3$ is the divisor we wanted. Otherwise there are primes $p$ and $q$ dividing $n$ and so $pq$ is the desired divisor.
Proving it works for $2$ should be much easier.
Comment: Oh lol, I understood the problem as: prove that $2$ and $4$ are the only numbers that satisfy: every number with more than $n$ divisors has a divisor with exactly $n$ divisors.
Comment: So you didn't answer my question, did you? Sorry for not phrasing the question in an intelligible way.

Numbers with more than n divisors