Proving the surface area and volume of revolution formula

Question: Title
Is there any way to prove the formula or surface area and volume of revolution of a function? The derivation of the formula I have found online does not really seem like a proof, but more like using intuition to explain it.
Thanks for your time and sorry if it is a stupid question lol
Comment: Hi, welcome to MSE. This is a cool problem. However, we might need some context to help us answer. Can you link the derivations you found online? What do you find unsatisfactory about them? Finally, what is your level of mathematics (what are the two recent courses you have taken)?
Comment: Hello, I am an IB student, taking Mathematics AA HL, meaning I am not into university yet. A video visualizing the concept around most derivations I found revolve around is this: https://www.youtube.com/watch?v=zUzan1Ma9nE&t=417s  Although logically it makes perfect sense, I am not sure if one could call upon said logic to actually prove the formulas.
Answer: I am trying to give a derivation of the two formula. Please let me know if you find any mistakes:
The proof of surface area is to divide the volumn into frustrums on $[x_{i-1},x_i]$, where the surface area is given by $$A=2\pi rl$$, where $l$ is length of slant of the frustrum, and $r=\frac{r_1+r_2}{2}$, where $r_1$ and $r_2$ are radius of left and right radius. Then we parametrize $r_1=f(x_i)$, $r_2=f(x_{i-1})$, and $$l=\sqrt{1+f'(x_i^*)^2}\Delta{x}$$, where $x_i^*\in[x_{i-1},x_i]$. Let $\Delta{x}\to 0$,
$$A_i=2\pi\frac{f(x_i)+f(x_{i-1})}{2}\sqrt{1+f'(x_i^*)^2}\Delta{x}\to 2\pi f(x_i^*)\sqrt{1+f'(x_i^*)^2}\Delta{x}$$
The whole surface area $S$ is given by
$$S=\lim_{n\to\infty}\sum_{i=1}^{n}A_i=\int_{a}^{b}2\pi f(x)\sqrt{1+f'(x)^2}dx$$
The proof of volumes under revolution starts from the volumns of cylinders, i.e.
$$\Delta{V}=\pi y^2\Delta{x}$$ (replacing $r^2$ with $y^2$). Then the volumn is just
$$V=\lim_{\Delta{x}\to 0}\sum_{x=a}^{b}\Delta{V}=\lim_{\Delta{x}\to 0}\sum_{x=a}^{b}\pi y^2\Delta{x}=\int_{a}^{b}\pi y^2dx$$
If you want to rotate around different axis, just switch the order of the functions, like replacing $y=f(x)$ to $x=h(y)$. Hope this helps.


Binding ComboBox.SelectedItem in Silverlight

Question: This one is driving me crazy. Here's the XAML:
    <UserControl x:Class="SilverlightApplication1.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Grid x:Name="LayoutRoot" Background="White">
    <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top">
      <ComboBox ItemsSource="{Binding Path=Thing.Stuff}"
                SelectedItem="{Binding Path=Thing.SelectedStuff}">
        <ComboBox.ItemTemplate>
          <DataTemplate>
            <TextBlock Text="{Binding Path=Name}" />
          </DataTemplate>
        </ComboBox.ItemTemplate>
      </ComboBox>
      <Button Content="Again" Click="Button_Click" />
    </StackPanel>
  </Grid>
</UserControl>

And the codebehind:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace SilverlightApplication1
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();

            Data data = new Data();
            data.Thing = new Thing();
            data.Thing.Stuff = new ObservableCollection<Stuff>();
            data.Thing.Stuff.Add( new Stuff { Name = "Stuff 1" } );
            data.Thing.Stuff.Add( new Stuff { Name = "Stuff 2" } );
            data.Thing.Stuff.Add( new Stuff { Name = "Stuff 3" } );
            data.Thing.SelectedStuff = data.Thing.Stuff.Last();
            DataContext = data;
        }

        private void Button_Click( object sender, RoutedEventArgs e )
        {
            Data data = ( DataContext as Data );
            data.Thing.Stuff.Clear();
            data.Thing.Stuff.Add( new Stuff { Name = "Stuff 4" } );
            data.Thing.Stuff.Add( new Stuff { Name = "Stuff 5" } );
            data.Thing.Stuff.Add( new Stuff { Name = "Stuff 6" } );
            data.Thing.SelectedStuff = data.Thing.Stuff.Last();
        }
    }

    public class Data : INotifyPropertyChanged
    {
        private Thing _Thing;

        public Thing Thing
        {
            get { return _Thing; }
            set { _Thing = value; NotifyPropertyChanged( "Thing" ); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged( string propertyName )
        {
            if ( PropertyChanged == null ) { return; }
            PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
        }
    }

    public class Thing : INotifyPropertyChanged
    {
        private ObservableCollection<Stuff> _Stuff;

        public ObservableCollection<Stuff> Stuff
        {
            get { return _Stuff; }
            set { _Stuff = value; NotifyPropertyChanged( "Stuff" ); }
        }

        private Stuff _SelectedStuff;

        public Stuff SelectedStuff
        {
            get { return _SelectedStuff; }
            set { _SelectedStuff = value; NotifyPropertyChanged( "SelectedStuff" ); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged( string propertyName )
        {
            if ( PropertyChanged == null ) { return; }
            PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
        }
    }

    public class Stuff : INotifyPropertyChanged
    {

        private string _Name;

        public string Name
        {
            get { return _Name; }
            set { _Name = value; NotifyPropertyChanged( "Name" ); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged( string propertyName )
        {
            if ( PropertyChanged == null ) { return; }
            PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
        }
    }
}

When the page loads, there is a ComboBox with "Stuff 3" selected. When the button is clicked, the items in the ComboBox change, but "Stuff 6" should be selected. Instead, nothing is selected.
Comment: If it's any consolation, it works for me in WPF (I'll see about Silverlight).
Answer: Try this:
 <ComboBox ItemsSource="{Binding Path=Thing.Stuff}"
      SelectedItem="{Binding Path=Thing.SelectedStuff, Mode=TwoWay}">

SelectedItem does not like to be bound OneWay. I haven't had a chance to try it out in Silverlight 2 but in Silverlight 3 you will even get the yellow triangle of death if you don't use TwoWay binding.
Comment: Just verified that this fixes it in SL2. Nice spotting
Comment: That does fix it in this example, but not in my larger project. Not sure what's going on there.
Comment: Hmmm, if you can provide more details around whats different in your larger project vs. the example that was provided here then we might be able to better diagnose the problem.
Comment: I posted a new question about this with more info: http://stackoverflow.com/questions/864322/binding-combobox-selecteditem-in-silverlight-more
Answer: Of course the binding has to be TwoWay. But setting a ItemsSource to a control doesn't means that the DataContext (where SelectedItem variable should point to) is set. Ensure that combo's DataContext is well set. (in my case, to Page. As selectedStuff is a Page property.
cmbStuff.DataContext = Me '(from  Page.Load)


RecyclerView ScrollListener - Animar visiblidade de view

Question: Quero que uma view contendo uns botões sumisse e aparecesse quando eu deslizo o recycleview como no coordinator layout:

mas atualmente esta assim, e ele n tem nenhuma animação, apenas some e aparece:

Código atual:
rv_noticas.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            y=dy;

            if (dy > 0) {
                Log.i(TAG, "onScrolled: " + "DOWN");
                //layoutbotoes.setVisibility(View.GONE);
                layoutbotoes.setVisibility(View.GONE);

            } else {
                Log.i(TAG, "onScrolled: " + "UP");
                layoutbotoes.setVisibility(View.VISIBLE);

                // Scrolling down
                //layoutbotoes.setVisibility(View.VISIBLE);

            }
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if(RecyclerView.SCROLL_STATE_IDLE ==newState){
                // fragProductLl.setVisibility(View.VISIBLE);
                if(y<=0){
                    layoutbotoes.setVisibility(View.VISIBLE);

                }
                else{
                    y=0;
                    layoutbotoes.setVisibility(View.GONE);
                }
            }
        }

    });

Comment: procure sobre animações https://developer.android.com/guide/topics/graphics/prop-animation.html
Answer: Tenta colocar isso no xml do layout, no topo essa parte
    xmlns:app="http://schemas.android.com/apk/res-auto"

Depois no layout em que os botões se encontram
app:layout_scrollFlags="scroll|enterAlways"

No caso utilizo isso para ficar igual a primeira imagem, onde o Toolbar esconde conforme o scroll
Comment: poderia detalhar mais sua resposta ? eu mecho em alguma coisa no java  ? adiciono só isso no xml? pois adicionei e nao alterou nada
Comment: Igor no caso o que falei seria para o Toolbar.
Mas acho que se você seguir este exemplo

http://blog.grafixartist.com/toolbar-animation-with-android-design-support-library/

Na parte que fala sobre a definição do XML, tem sobre CollapsingToolbarLayout, acredito que de para implementar o que você esta querendo.


How to effectively of use a lower tuned guitar

Question: I'm experimenting with the Open C tuning (CGCGCE) in my guitar and I'm facing some problems, namely that the strings don't stay in tune for too long and the sound is "weird". I then realized that maybe I'd have to make some adjustments in the guitar or choose different strings as to minimize the problems and make it sound better. At the moment I'm using D'Addario Nickel Wound .010 strings.
I'd like to understand better how the tension of the strings affects the overall sound and interacts with other parts of the guitar and what needs to be done to effectively use these lower tunings.
Comment: The answers here might help: http://music.stackexchange.com/q/3714/28
Answer: The lower you tune your guitar, the thicker you will want the strings. 10's are probably not going to cut it for going that low.
From what I heard at the music shop the other day, you want to go up a gauge for every whole step you go down, which by this formula, would mean you want 12's. Maybe 'Even Better Than Slinkys', which come ready packaged for downtuners.
Comment: Interesting, but this begs the question: seeing that not all strings in this tuning are downtuned, 1 and 3 remain the same and 2 is increased half-step, should I still get 12's?
Comment: You can buy a set, or single strings of the bigger gauge, and only change the ones you are down tuning. Your guitar store should be able to help you find the right ones.
Comment: Or you could by Mixed sets, like the Ernie Ball Skinny Top Heavy Bottom.
Answer: It shouldn't go out of tune even at low pitches as long as you have enough wraps on the post and you always tune up into a note (to lock the gears in the tuner).
But thicker strings will be less flabby. If the string guage is too small for the pitch, the act of striking the strings will noticeably change the tension, thus changing the pitch. So a note won't stay in tune with itself.
Comment: Yeah I know about tuning up into the notes and that should not be the problem. In fact sometimes I observed it going out of tune to a higher pitch and I suppose that may be due to the flabbiness you talk about.
Answer: There may also be issues with the intonation. I tried to turn a Tele into a baritone, and I could not get the saddle for the low string back far enough.


Apache reverse proxy - URL without / is refused

Question: I use reverse proxy to show backend server content for a subdomain.
The subdomain.mydomain.com (server A) should display content of server with IP 126.96.36.199 port 1111 (server B).
Virtual host of subdomain.mydomain.com (server A):
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName subdomain.mydomain.com

SSLEngine on
SecAuditEngine On
RewriteEngine On
SSLProxyEngine on
ProxyPreserveHost On
LogLevel warn

<Directory />
    Options -Indexes +FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

<Location />
    ProxyPass https://220.127.116.11:1111
    ProxyPassReverse https://18.104.22.168:1111
</Location>

ErrorLog /var/log/apache2/error.log

SSLProtocol             all -SSLv2 -SSLv3
SSLHonorCipherOrder     on
SSLVerifyClient none
SSLVerifyDepth 1

SSLCertificateFile /etc/apache2/cert.site/chain_wildcard_site_combined.crt
SSLCertificateKeyFile /etc/apache2/cert.site/key_wildcard_site.key

SetEnvIf User-Agent ".*MSIE.*" \
         nokeepalive ssl-unclean-shutdown \
         downgrade-1.0 force-response-1.0

</VirtualHost>
</IfModule>

Virtual host of 18.104.22.168:1111 (server B):
<IfModule mod_ssl.c>
    <VirtualHost 18.104.22.168:1111>
        DocumentRoot /srv/www/site/htdocs

SSLEngine on
RewriteEngine On
SSLProxyEngine on
ProxyPreserveHost On
LogLevel warn

<Location "/">
   Require ip 188.8.131.52
</Location>

<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>

<Directory /srv/www/site/htdocs>
    Options -Indexes +FollowSymLinks +MultiViews
    DirectoryIndex index.php
    AllowOverride None
    Require all granted
</Directory>

ErrorLog /srv/www/site/log/error.log
CustomLog /srv/www/site/log/access.log combined
CustomLog /srv/www/site/log/ssl_request_log \
            "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

SSLProtocol             all -SSLv2 -SSLv3
SSLHonorCipherOrder     on
SSLVerifyClient none
SSLVerifyDepth 1

SSLCertificateFile /etc/apache2/cert.site/chain_wildcard_site_combined.crt
SSLCertificateKeyFile /etc/apache2/cert.site/key_wildcard_site.key

        <Directory /usr/lib/cgi-bin>
                SSLOptions +StdEnvVars
        </Directory>

    </VirtualHost>
</IfModule>

If I load URL:
https://subdomain.mydomain.com/dir/
it loads successfully.
If I load URL (without trailing slash):
https://subdomain.mydomain.com/dir
it results error page: ERR_CONNECTION_REFUSED.
EDIT1:
I execute command:
curl -IL https://subdomain.mydomain.com/dir

and I get this result:
HTTP/1.1 301 Moved Permanently
Date: Mon, 23 Aug 2021 13:45:13 GMT
Server: Apache
Strict-Transport-Security: max-age=15768000; includeSubDomains
Strict-Transport-Security: max-age=15768000; includeSubDomains
Location: https://subdomain.mydomain.com:1111/dir/
Content-Type: text/html; charset=iso-8859-1

curl: (7) Failed to connect to subdomain.mydomain.com port 1111: Connection refused

EDIT2:
I added trailing slash
<Location />
    ProxyPass https://220.127.116.11:1111/
    ProxyPassReverse https://188.8.131.52:1111/
</Location>

But I still get the Connection refused error.
Any idea why is it resulting error, when trailing slash is missing?
Thanks!
Comment: I would try adding the trailing slash to the `ProxyPass`/`ProxyPassReverse` directives in your location block. From what I see in doc and own config, you can write `ProxyPass "/" "something_with_trailing_slash/"` or `ProxyPass "/url" "something_without_trailing_slash"`, while your location block is equivalent to `ProxyPass "/" "something_without_trailing_slash`
Comment: Earlier I used the `ProxyPass "/" "something_with_trailing_slash/"`with the same wrong result.
Comment: do both `curl -IL https://subdomain.mydomain.com/dir` and `curl -IL https://subdomain.mydomain.com/dir/` and edit the question to include the output.
Comment: @mforsetti added curl result into OP
Answer: Review your firewall settings and your server logs on server B and verify that server A is able to reach server B with the correct IP address as sender (I'm assuming that's 220.127.116.11). Your listings for server B are also missing a Listen 1111 https directive.
edit
The backend server is forcing a redirect:
HTTP/1.1 301 Moved Permanently
Location: https://subdomain.mydomain.com:1111/dir/

That the HSTS header is present and the absence of any rewrite rules makes me assume that it's the application that's issuing the redirect.
Verify which it is.
You stated that with the added '/' things work fine. Forcing the trailing '/' with mod_rewrite on the frontend server seems like an acceptable solution to me.
Comment: I missed to mention, that Listen 1111, 443 is set separately in ports.conf. I don't think it is a firewall problem, as it works for /dir/ but not works for /dir
Comment: Find out what triggers the redirect you experience according to `curl`'s output. It's very likely that it's the backend server (non-obvious from the config fragments you posted) or the application itself that's forcing it. Enforcing a trailing `/` with rewrite rules could be an acceptable workaround.
Answer: Looks like this was already answered here. Still to answer your question,
You are missing a forward-slash at the end of both the ProxyPass and ProxyPassReverse directives.
Read this if you need more details on why this is the case.
Comment: I tested your suggestion, but I still get the error. See the modified OP.
Answer: Your reverse proxy is not (probably should not be) listening on port 1111.
Yet, your 123 server is redirecting to port 1111 (assumption based on configs you posted).


R: Error in simple call to sum() that I cannot reproduce - how can I find what the problem object is?

Question: I am running these two simple lines of code:
vector <- c(2.5, 2.5, NA)
sum(vector, na.rm = TRUE)

And I get this error:
Error in sum(vector, na.rm = TRUE) : unused argument (na.rm = TRUE)

But if I run a reprex, then sum() works:
vector <- c(2.5, 2.5, NA)
sum(vector, na.rm = TRUE)
#> [1] 5

If I restart R I get the same error.
If I remove all objects, the function works.
How can I find which object is giving me this problem? Do I have to go through the file line by line and check the call to sum() every time I introduce a new object? I hope there is a better way.
Created on 2021-04-15 by the reprex package (v0.3.0)
Comment: In your environment are you overwriting/creating a new function with the same name `sum`?
Comment: Of course, that's what I did. Thank you @LMc
Comment: Is there a way of being warned when overwriting a function?
Answer: As @LMc noticed, I had created another function called sum():
sum <- function(a,b){a+b}
vector <- c(2.5, 2.5, NA)
sum(vector, na.rm = TRUE)
#> Error in sum(vector, na.rm = TRUE): unused argument (na.rm = TRUE)

Created on 2021-04-15 by the reprex package (v0.3.0)
Comment: just do  `rm(sum)` and your problem should be solved


Ansible - Intercept POST Request

Question: I'm looking to trigger an Ansible Playbook via a POST request.
For example, I want to make Ansible listen on some port so that it can intercept a POST request, parse the JSON, and inject the values into the variables with the same key name.
So far, everywhere I look I see that Ansible can use REST APIs, but not act as an endpoint.
Is this possible? If not, any alternate suggestions will be much appreciated
Comment: There are CI/CD tools to do this, Jenkins, RunDeck, etc. Their API endpoints/hooks get POSTed and that runs the desired ansible playbook.
Answer:
I want to make Ansible listen on some port so that it can intercept a POST request

You can't make Ansible listen on a port (yet "intercept"), because Ansible (called ansible as well as ansible-playbook) is just a user-executable Python script.
Write a service component listening on a designated port and execute the ansible-playbook command from it.

parse the JSON, and inject the values into the variables with the same key name.

You can pass the JSON object as a variable (dictionary) directly to ansible-playbook as an argument to the command.
Comment: I'll accept your answer if you explain what you mean by "Service Component". I assumed you meant something like @jscott mentioned above, but using a CI or CD tool wouldn't be writing my own.
Comment: component = a piece of software; service = running not in user space, but in background; don't expect CI/CD tools to wait for your POST requests by default; you would probably have to write the same thing whatever tool you choose.
Comment: Unfortunately, I work for a large company so simply writing some software to listen for a POST request and running it on their servers isn't going to be allowed, nor do I have the time to do that. Thank you though, for pointing me in the right direction.

Ansible - Intercept POST Request


Show that these two Eigenvalues are positive

Question:

In the course of a rather long calculation, I got two Eigenvalues, namely
    $$
\lambda_{1,2}=\frac{1}{2}(2+x^2+u\pm\sqrt{u^2-2ux^2+x^4+4x^2}).
$$
    I have to show, that these two Eigenvalues are positive. (Here x is out of a bounded domain $\Omega\subset\mathbb{R}^2$ and $u\in C^2(\Omega)\cap C^1(\overline{\Omega})$ is a non-negative function.)

Could you please help me to show, tha $\lambda_{1,2}$ are positive? I do not have an idea, how to show that.
Comment: Expression $u^2-2ux^2+x^4$ is factorable as a prefect square. How is that for a start?
Comment: What do you mean with prefect square?
Comment: I mean $(u-x^2)^2$
Comment: Please give us the characteristical polynomial;  I'm too tired to reconstruct it.
Comment: Ok, then I have $\lambda_{1,2}=\frac{1}{2}(2+x^2+u\pm\sqrt{(u-x^2)^2+4x^2})$. That says me that $\lambda_1=\frac{1}{2}(2+x^2+u+\sqrt{(u-x^2)^2+4x^2})$ is positive, right? Whats with $\lambda_2$?
Comment: @Michael Hoppe The characteristical polynomial is $\lambda^2+(-2-x^2-u)\lambda+1+u+ux^2=0$.
Answer: You need to just show that $2+x^2+u > \sqrt{u^2-2ux^2+x^4+4x^2}$
$$\iff (2+x^2+u)^2 > u^2-2ux^2+x^4+4x^2$$
$$\iff 4+4 u+u^2+4 x^2+2 u x^2+x^4 > u^2 - 2 ux^2 + x^4 + 4 x^2$$
$$\iff 4 + 4 u + 4 u x^2 > 0$$
which is true as $u \ge 0$.


How to add icon in subgroup

Question: I am newbie in Vuetify, and I want to change the "MP in front of the My Profile become an icon. " Anyone know how to change it become an icon?? Please Help me, Thank you!!
Item.vue
<v-list-item-icon
  v-if="text"
  class="v-list-item__icon--text"
  v-text="computedText"
/>

<v-list-item-icon v-else-if="item.icon">
  <v-icon v-text="item.icon" />
</v-list-item-icon>

<v-list-item-content v-if="item.title || item.subtitle">
  <v-list-item-title v-text="item.title" />

  <v-list-item-subtitle v-text="item.subtitle" />

</v-list-item-content>

ItemGroup.vue
<template v-slot:activator>
  <v-list-item-icon
    v-if="text"
    class="v-list-item__icon--text"
    v-text="computedText"
  />
  <v-list-item-avatar
    v-else-if="item.avatar"
    class="align-self-center"
    color="grey"
  >
    <v-img src="https://demos.creative-tim.com/material-dashboard-pro/assets/img/faces/avatar.jpg" />
  </v-list-item-avatar>

  <v-list-item-content>
    <v-list-item-title v-text="item.title" />
  </v-list-item-content>
</template>

<template v-for="(child, i) in children">
  <base-item-sub-group
    v-if="child.children"
    :key="`sub-group-${i}`"
    :item="child"
  />

  <base-item
    v-else
    :key="`item-${i}`"
    :item="child"
    text
  />
</template>

ItemSubGroup.vue
<base-item-group
:item="item"
text
sub-group

/>
Answer: May be this
<v-list-item-icon
  v-if="text"
  class="v-list-item__icon--text"
  v-text="computedText"
/>

is always true, so that the icon is not rendered.
Comment: how to change it? can you help me? Thanks @TDAK
Comment: ```
const defaultIcon = "mdi-home";

```
Comment: I had changed the code, and the UI doesn't look as expected, any suggestion? @TDAK
Comment: Can you update to show your `items` variables in the questions? May be the item.icon is not correct? Or maybe you haven't import material fonts?

How to add icon in subgroup


Where are SNMP MIBS evaluated? Can I make my own?

Question: You can monitor lots of different data points about a Linux system using SNMP, if you pick the correct MIB numbers (e.g. like .126.96.36.199.4.1.2021.9.1.2.1 on http://www.debianhelp.co.uk/linuxoids.htm).
Where is the code for each MIB test stored on a Linux machine?
Is it possible to add your own custom tests? (e.g. when a custom MIB is queried, run a python script and return the response)?
Answer: The location is probably dependent on your distribution; on Debian they live under /usr/share/snmp/mibs.  In addition to Antoine's answer on simple exec plugins for net-snmpd, you can also write more complicated plugins for net-snmpd that integrate more seamlessly; I've also written my own Ruby SNMP agent which is designed to make it trivial to handle custom SNMP data (it's the whole reason for it's existence).
Answer: I don't know where the MIB is stored on a Linux machine but you can add the result of scripts in the default MIB by using the following syntax :
exec railsversion "/bin/bash /etc/snmp/railsversion.sh"

It will show up in your MIB which you can test by using the following command.
snmpwalk -v 1 -c public localhost .188.8.131.52.4.1.2021.8

This is pretty well documented in the snmpd.conf file found in Debian and probably other distros.
I find this option very useful as it eliminates the need for a specific monitoring agent.


Is there any risk to sending emails to accounts that no longer exist?

Question: As mentioned in a previous question of mine, I send a lot of emails.
I have calculated that approximately 2% of them are coming back to me immediately with the general text reading:
<code>550-5.1.1 The email account that you tried to reach does not exist. Please try
550-5.1.1 double-checking the recipient's email address for typos or
550-5.1.1 unnecessary spaces. Learn more at
550 5.1.1 http://support.google.com/mail/bin/answer.py?answer=6596
</code>
That above text is from Gmail, but many other email providers respond with similar text.
My question is: Is it dangerous (in terms of being blacklisted) to send email to addresses that do not exist?
I plan on creating a cron job shortly that removes users who have not logged into the site in the past month from the newsletter, but perhaps I won't bother if there are no negative effects.
Answer: Yes it is, ISP's measure your performance on multiple levels. One is the amount of bad mailboxes you are trying to deliver to. Different ISP's of course measure different things but people like AOL and yahoo do use this as a metric.
Other metrics include whether you are using domain key or SPF authenticated mail. How many of your users report your mail as "spam". Some of the more technologically advanced ISP's are even looking at engagement metrics now (whether people open/click your emails) to decide whether they will deliver your email at all, to bulk or to the inbox.
2% bounce rate however is an acceptable level of bounces provided your other factors are good, make sure you keep it below 5% or you will have inbox delivery issues.
N.B If other people are using the same IP address to deliver their email they could also be impacting your delivery.
Comment: Hotmail also use old, abandoned email addresses as spam traps and share their results with SenderScore who handle reputation scoring (and blacklisting) for many other domains.  AOL seem to use these to throttle your sending rate rather than blocking your emails entirely.


Does "exclude from display" on views affect performance?

Question: I really wonder if it differs in calculation time to exclude an item from display.
For example:
I have 500 rows in a view.
Each row has two fields: title and author.
Does generating the same view with excluded "author" field takes the same time as displaying "author field"?
Answer: You should profile this and see.  It totally depends on your system.
Install the Devel and Performance modules.  Then enable the Query log (in the D7 version it is at "admin/config/development/devel").  Visit some view pages, and look at the queries at the bottom of the page.  Tweak your views and re-run.  Just be sure to disable caching (including MySQL query caching) when you do this, as it may skew results.
You can also copy/paste the SQL from the view config page (enable from "admin/structure/views/settings"), into Query Browser or another tool and look at the execution time.  If you do this, bypass the query cache, to make sure you get accurate results.
Also keep in mind that buffer sizes, etc, can affect results since data may or may not need to be read from disk.  You should really have an optimized MySQL instance before you profile.


Definir propriedade com base em outras durante criação de objeto

Question: Estou fazendo uma tentativa de popular 'nomecompleto' com o resultado das duas primeiras variaveis, porém sem êxito.
var pessoa = { nome: "Joao", sobrenome: "Silva", nomecompleto : nome + sobrenome };

alert(pessoa.nomecompleto);

Uncaught ReferenceError: nome is not defined

Existe alguma forma de obter o resultado esperado da variável 'nomecompleto' na definição inicial da var 'pessoa'?
Answer: Tem de fazer isso em passos.
Quando quer usar nome + sobrenome o objeto ainda não está defenido e essas propriedades ainda não existem. De qualquer maneira não seria possivel chamá-las assim. Desse modo o JavaScript pensa que são variáveis.
Use assim:
var pessoa = { nome: "Joao", sobrenome: "Silva" };
pessoa.nomecompleto = pessoa.nome + pessoa.sobrenome
alert(pessoa.nomecompleto);

Pode contudo fazer uma Classe e usar:
function Pessoa(nome, sobrenome) {
    this.nome= nome;
    this.sobrenome= sobrenome;
    this.nomeCompleto = this.nome + ', ' + this.sobrenome;
}

var novaPessoa = new Pessoa('Luis', 'Martins');
console.log(novaPessoa .nomeCompleto); // vai dar "Luis, Martins"

Exemplo: http://jsfiddle.net/3epeLuzL/
Answer: Conforme explicado pelo @Sergio, o objeto ainda não está construído na memória e, portanto, não há ponteiro para seu conteúdo ainda.
Caso seja realmente necessário fazer a declaração do atributo nome_completo dentro deste objeto literal ({ ... }), por exemplo: se você quer que, ao atualizar o nome, o nome_completo seja automaticamente "atualizado" junto, o mais próximo que se pode fazer é transformar o nome_completo em um método:
var pessoa = { nome: "Rui", sobrenome: "Pimentel", getNomeCompleto: function(){
    return this.nome + " " + this.sobrenome;
}};

Disponibilizo aqui um JSFiddle de exemplo.


Navbar Links not appearing when resizing screen

Question: I am trying to create a Navbar that hides the links and shows "fas fa-bars fa-1x" Icon (3 horizontal bars) the when smaller than an "md" size screen. When the screen becomes smaller, the button appears but does not work when it is clicked.
Fiddle:
https://jsfiddle.net/mmsyed/z8vg749t/6/#&togetherjs=MJCCM4wefa
I have removed all custom CSS and JS
Looked at the Bootstrap 4 reference pages
It works when the 2nd "" is removed,
Take a look at the fiddle...
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.9.0/css/all.css" integrity="sha384-i1LQnF23gykqWXg6jxC2ZbCbUMxyw5gLZY6UiUS98LYV5unm8GWmfkIS6jqJfb4E" crossorigin="anonymous"

   Navbar

<button class="navbar-toggler" type="button" data-toggle="collapse">

</button>

    About

    Pages

      Page 1
      Page 2
      Page 3

Comment: You're missing a closing tag on the `dropdown-menu` element.
Answer: Multiple things going wrong, which are:

you did't specify data-target in your <button class="navbar-toggler" >... </button>

 needs an ID which would be the same as data-target (from point 1 above)
you had disabled the dropdown using the class disabled in your code: ...
didn't include bootstrap.min.js
didn't close the script tag for Font Awesome
incorrect/incomplete quotes for multiple elements check nav-item for LinkedIn and Twitter

following snippet works with these specific fixes:

<link rel="stylesheet" type="text/css" href="MustaphaSyedDM.css" />

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.9.0/css/all.css" integrity="sha384-i1LQnF23gykqWXg6jxC2ZbCbUMxyw5gLZY6UiUS98LYV5unm8GWmfkIS6jqJfb4E" crossorigin="anonymous" />

     Navbar

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">

        </button>

        About

        Pages

          Example
          Example
          Example


Is there a way to insert "0000-00-00 00:00:00" in a datetime database field?

Question: Is there a way to insert "0000-00-00 00:00:00" datetime database field?
Should I change the database field's default value to "0000-00-00 00:00:00"?
I got replies on Stack Overflow, and it works with plain PHP, but it gives an error with Drupal.
Comment: Hello and welcome. Please tell us how you defined database column you want to insert data to, what PHP code you are trying to execute (and how you injected it to Drupal), and what error do you see.
Answer: In Drupal 7 DB API, support for the datetime type was removed. This means that you must use use mysql_type or pgsql_type if you want this functionality.  Below is an example of of to declare this schema provided your database is MySQL.  By setting not null to FALSE, you can store an empty value (''), which is equivelent to '0000-00-00 00:00:00':
'mydate_date' => array(
  'description' => t('My date field.'),
  'type' => 'varchar',
  'mysql_type' => 'datetime',
  'not null' => FALSE,
),

Note that to make the schema portable, you should provide a fallback type (varchar) for the case that the database is not mySQL.


Netbeans: COMMIT [HEAD] does not exist

Question: Using Netbeans (I just updated to v7.4 and I'm still having the problem), I have cloned a projet from a GIT repository. After it, when I do commit and push, everything is working fine. However, since Commit/Push via Netbeans can be very slow with big projects, sometime to save time, I do commit and puch directly from the command line. Here are the commands I'm using to commit/push manually:
git add -Av
git commit -avm "commit via command line"
git push -v origin

It works just fine. The only problem is that after it, it looks that Netbeans does not regognize my git project anymore. For example, if I change a file, the tab does not become blue anymore. Also, if I try to do a Commit via Netbeans, I'm receiving the following error
COMMIT [HEAD] does not exist

So, is it a bug with Netbeans?
Is there a way to manually reset/fix the Netbeans project so that it works fine with git even when I do git command via the command prompt? The only work arround I found is to do a new complete Clone of the project in a new blank folder via Netbeans.
Thanks in advance for any help somebody could provide me about this behaviour.
G. Plante
Answer: Purely using the Netbeans (V8) Git facility I initialised a local repository from my new Netbeans project and as you say when I tried to commit I received the COMMIT [HEAD] does not exist error.  Simply by stopping and starting Netbeans the commit then worked.  So if in doubt reboot !
Comment: Awesome! It is helpful.

Netbeans: COMMIT [HEAD] does not exist


Run a function constantly

Question: I'm using the excellent inView plugin to check if an element is visible in the viewport, using setInterval, but the function only runs once and only when the element IS visible, not otherwise (should run else statement).
var checkViewport = setInterval(function() {
    $('#colorbox').on('inview', function(event, visible) {
      if (visible) {
        console.log('YES');
      } else {
        console.log('NO');
      }
    });
}, 5000);

Comment: You're rebinding the event every iteration of the interval.
Comment: What is it that you expect to happen upon each interval?
Comment: @Pointy I need to check visibility on each interval.
Comment: @Nimbuz the plugin you're using already runs its own interval timer. You just need to bind the event handler.
Answer: Bind the event once, and check a separate variable. Try this:
var isVisible = false;

$('#colorbox').on('inview', function(event, visible) {
    isVisible = visible;
});

var checkViewport = setInterval(function() {
    if (isVisible) {
        console.log('YES');
    } else {
        console.log('NO');
    }
}, 5000);

You can structure this differently to make sure isVisible isn't a global variable and can be accessed by the setInterval still as well.
Answer: The code in your example only binds an event when the element's in the viewport. You're not actually executing anything, just repeatedly binding an event.
I would suggest instead checking the element colorbox every interval, then logging to the console whether the colorbox is visible.
Source (HTML DOM and JavaScript):
var checkViewport = setInterval(function() {
    myColorBox = document.getElementById("colorbox");
      if (myColorBox.style.visibility == "visible") {
        console.log('YES');
      } else {
        console.log('NO');
      }
    });
}, 5000);

Run a function constantly


D6 to D7 upgrade error Invalid datetime format Incorrect integer value

Question: After upgrading a D6 to D7 site. I get this error when trying to save an existing page on the site that has uploaded image files, and the page will not save. If I remove the uploaded files, the error goes away and I can save the page.

PDOException: SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect
  integer value: '' for column 'field_upload_inline_image_width' at row
  1: INSERT INTO {field_data_field_upload_inline_image} (entity_type,
  entity_id, revision_id, bundle, delta, language,
  field_upload_inline_image_fid, field_upload_inline_image_alt,
  field_upload_inline_image_title, field_upload_inline_image_width,
  field_upload_inline_image_height) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3, :db_insert_placeholder_4,
  :db_insert_placeholder_5, :db_insert_placeholder_6,
  :db_insert_placeholder_7, :db_insert_placeholder_8,
  :db_insert_placeholder_9, :db_insert_placeholder_10); Array (
  [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 37
  [:db_insert_placeholder_2] => 25955 [:db_insert_placeholder_3] => page
  [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und
  [:db_insert_placeholder_6] => 24 [:db_insert_placeholder_7] => NNSA
  Headquarters [:db_insert_placeholder_8] => [:db_insert_placeholder_9]
  => [:db_insert_placeholder_10] => ) in field_sql_storage_field_storage_write() (line 514 of
  /var/www/html/upgrade2a/modules/field/modules/field_sql_storage/field_sql_storage.module).

This is my table structure field_upload_inline_image, do i need to alter the Type or Null column?
<code>entity_type (Primary) varchar(128)  No The entity type this data is attached to
bundle varchar(128) No The field instance bundle to which this row belongs, used when deleting a field instance
deleted (Primary) tinyint(4)    No 0 A boolean indicating whether this data item has been deleted
entity_id (Primary) int(10) No The entity id this data is attached to
revision_id int(10) Yes NULL The entity revision id this data is attached to, or NULL if the entity type is not versioned
language (Primary) varchar(32)  No The language for this data item.
delta (Primary) int(10) No The sequence number for this data item, used for multi-value fields
field_upload_inline_image_fid int(10)   Yes NULL The file_managed.fid being referenced in this field.
field_upload_inline_image_alt varchar(512)  Yes NULL Alternative image text, for the image's 'alt' attribute.
field_upload_inline_image_title varchar(1024)   Yes NULL Image title text, for the image's 'title' attribute.
field_upload_inline_image_width int(10) Yes NULL The width of the image in pixels.
field_upload_inline_image_height int(10)    Yes NULL
</code>
I'm using Media 7.x-1.5 Bundled with File entity 7.x-1.5. I am not using UUID module.
maybe I need to then I will need
the file_managed table is missing the uuid column
Comment: We are seeing the same effect for migrated numeric CCK fields with no default under postgre, it must have something to do with the upgraded settings, because newly created fields are not affected. Happens when a form field is left empty, such that the backend tries to insert a empty string '' into a numeric database column. For postgres, trying to set value '' into an integer column causes the same error message. It must have something to do with the configuration mapping the input html-field to it's storage type in the backend, but we haven't found it yet.
Comment: Setting a default value in the field configuration for numeric fields is currently our workaround, but I don't know if that is possible in your case.
Comment: Thanks. This was my fault. I was editing a page that had attached images. But the images were not in the /files folder! That was the problem, as soon as added all of the newer images from the production site /files folder and added them into this test site. I could then edit and save a page and the error went away. What scary looking error, when it could just say -  image missing.
Answer: I should have posted the answer here instead, it may help someone. This is fixed. I had missing images in the /sites/default/files/ folder. This was a upgraded d6 to d7 site with 4000 nodes and many images. I did not have the latest images in my files folder. So saving a node with uploaded cck field images threw this error.
Comment: Hi, thank you for reporting the fix. I think that the error message is still revealing this issue: https://www.drupal.org/node/2679491 The fields backend should never attempt to insert an empty string for a missing value instead of NULL into a numeric column, Now I know that our issue is reproducible even under MySQL.


Is it valid to move a logarithm inside of an expectation?

Question: I have the following derivation for a latent variable model.
$$
\newcommand{\d}[1]{\mathrm{d}#1}
$$
$$
\begin{align*}
\mathbb{E}_{q(x_0)}\left[-\log p_\theta(x_0)\right]\\
&=^{1.} \mathbb{E}_{q(x_0)}\left[-\log \int p_\theta(x_{0:T}) \d{x}_{1:T}\right]\\
&= \mathbb{E}_{q(x_0)}\left[-\log \int \frac{q(x_{1:T})}{q(x_{1:T})}p_\theta(x_{0:T}) \d{x}_{1:T}\right]\\
&= \mathbb{E}_{q(x_0)}\left[-\log \mathbb{E}_{q(x_{1:T})}\left[\frac{p_\theta(x_{0:T})}{q(x_{1:T})}\right]  \right]\\
\end{align*}
$$

Pull in the latent variables by marginalizing $p_\theta(x_0)$ with respect to $x_{1:T}$

I'm wondering, is it a valid move to do the following:
$$
\mathbb{E}_{q(x_0)}\left[-\mathbb{E}_{q(x_{1:T})}\left[\log \frac{p_\theta(x_{0:T}}{q(x_{1:T})}\right]\right]
$$
I.e., I want to move the log inside of the expectation. It seems invalid because
<code>log(average(1, 2, 3)) != average(log(1), log(2), log(3))
</code>
But in the linked paper, the final equation is

so, I suspect it must be possible.
Comment: Switching log and expectation is hardly ever correct.
Comment: For a non-constant random variable $E[\log(X)] < \log(E[X])$ - assuming these exist
Comment: I see my mistake here, they are using Jensen's inequality and converting the equality into an less than.
Answer: No, it's not valid. We know this at least from Jensen's inequality which states that for a convex function $\varphi$, moving it outside of the expectation will make the result smaller or equal to transforming the random variable itself and taking expectation,
$$
\varphi(E[X]) \leq E\left[\varphi(X)\right].
$$
Notice that the last equation from the paper mentioned by you also makes the statement in terms of inequality.


Might accounting questions be on-topic?

Question: It appears that the Accounting Stack Exchange Beta failed to launch. Reviewing the business and personal finance stack exchanges, it seems the economics stackexchange is the the best place to ask accounting questions.
Numerous JEL classification codes cover accounting topics including M4 – Accounting and Auditing but also a number of accounting questions fit into corporate finance. The tricky part to admitting these questions is making sure that accounting questions that are more about business administration, legal, taxes, and personal finance than accounting are not posted. Suggestions and different opinions are welcome.
Here are some accounting questions that seem firmly on topic on Economics SE:

Depreciating companies intangible assets
What is "Stated-capital"?
How does depreciation affect the cash flow in a tax-paying company?
Comment: My guts say no, as I dont think there's many questions that "median economics" can answer/find interesting about accounting. If you want to make a better case, why dont you create a short list of questions from the failed beta that you'd like to see migrated?
Comment: How does one see the closed question queue?
Comment: I just noticed that the percentage of question answered "needs work" in area51. I don't know whether off-topic questions are counted in there. If not, we may want to get better at answering more questions before we jump to expanding the range of questions to be answered.
Answer: I will tend to agree with the OP. My angle is : what would be interesting and useful content and a match to econimics.se, is questions about contrasting/reconciling accounting and economics concepts (usually at the micro level but not only) that sometimes go under the same name. Examples:

Do accountants mean the same thing as economists when they talk about "profits"? What are the differences? Can the two be reconciled?
How does the "production function" concept of Economics connect (if at all) to the "Sales/Revenue" item we see in a Profit & Loss statement?
The most widely used depreciation method in a firm's accounting books is the "Straight-line" method, where a fix proportion of a fixed asset's acquisition cost (historic or re-estimated) is booked as depreciation charge every period. On the contrary, almost exclusively, economic models employ the equivalent of "Declining-Balance" method. Who is more to the mark? Doesn't this create misalignment problems in microeconometric studies?
Economics employ the concept of "adjustment-costs" in capital investment. Economists treat these costs as non-productive, as a dead-burden to increase the actually productive capital base. But Accounting principles prescribe that most of such costs are booked as an increase to the acquisition cost of the core asset (i.e. not as current expenses). What kind of problems may this create when we look to balance sheet data in order to test an economic theory?
Public sector finances of many countries are being nowadays presented using the approach and principles of internationally accepted accounting principles (like "Statement of Financial Position", "Cash Flow Statement", etc). In one of these I have seen negative "Cash available" at the beginning of a period. How is this possible? (It is never observed for private companies).
Also, when assets of a public sector are included in a "Statement of Financial Position", what assets are these? Do they include natural resources owned by the state?

My proposal :
a) Since the Accounting.se site failed to launch, remove "Accounting" from our "Off-topic" guidance.
b) Mention it in the "On topic but" category
either in the "Corporate Finance/Business economics" (with something like "Questions about Accounting theory fall in this category too"),
or separately as
"Accounting Theory: questions about Accounting Theory, especially as regards its relation to Economics may be posted here. Questions about tax legislation, or legal & administrative things that accountants have to deal with as professionals, will be closed as off-topic, and so will questions asking guidance about performing specific accounting tasks."
Comment: Among the types of questions to be closed as off-topic might be added: "questions asking guidance about the proper accounting treatment of particular items or circumstances under particular accounting jurisdictions".
Comment: In other words, I'm fine in *Accounting Theory: questions about Accounting Theory, **if and only if related to Economic**s may be posted here.*
Comment: I perceive a qualitative difference between "accounting theory" and "accounting questions that are related to economics / interesting to economists". The latter we already do, and it is on-topic. I don't see how accounting theory (that is not related to economics) is related to economics.
Comment: @FooBar Strengthening of the message, certainly won't hurt indeed.
Comment: @AdamBailey Thanks Adam. This is what I had in mind when I wrote "performing specific accounting tasks", but it never hurts to be as explicit as possible.
Answer: Now that we do have a list of questions, we can start discussing the matter.
Corporate Finance
Observation: These are all about corporate finance. So why not just include corporate-finance in economics?
If corporate finance, why not finance?
However, the intersection between corporate-finance and economics is pretty small. The intersection between corporate-finance and finance, however, is pretty large. If we were to go this way, it is only consequential to include the whole (academic) finance on this site. This however can only work if we rename into Economics and Finance, or something the like. This would not intersect with the non-academic money.stackexchange, but it would interfere with quant.stackexchange.
Summary
In the end, we are left with two choices:

Stay Economics-stackexchange
Become Economics-and-Finance-stackexchange.

Not that im completely against the latter, but we should be aware of what we're doing, and whether and why we want that.
Comment: Corporate Finance already appears in the "On topic but" category in our guidance. Also the questions I have listed in my answer have nothing to do with corporate finance. So I don't see as accurate your "two-choices" approach. We should by all means stay Economics.se, and, as regards accounting questions, not-close those that may be useful to economics.
Comment: @AlecosPapadopoulos I was referring to the questions in the opening post. Your questions are still economics questions, and qualitatively different from those linked. **If all you say is "Leave those open that are relevant to economics", then I guess, that's what we've been doing all along, and there is no reaction on our side w.r.t. the closing of the accounting beta.**
Comment: @FooBar Using JEL codes as a guide, Corporate Finance falls under category G, Financial Economics, and more specifically has the code G3. My instinct, however, makes me relate corporate finance to finance rather than economics. My hunch is that the majority of students in both subjects would share a similar view. It might be useful to think about typical University school / course structures and try to align economics se along with what students of economics kind of expect economics to be?! It's semi-arbitrary, but not as strict as using JEL, which might itself not be perfect.

Might accounting questions be on-topic?


Assigning average outcome values to categorical variables

Question: Let's say we have a regression problem in which we would like to predict some score $y_i$ for person $i$.
As predictor data we have two variables: country $c_i$ and gender $g_i$. If we now assume that gender has three different classes (male, female, miscellaneous) but we only have historical score data for males and females and also some of the existing countries, how do we make predictions for the genders with miscellaneous value?
I maybe have some (quite philosophical) idea (that I've personally never have seen applied before):
What if we replace the values male/female/miscellaneous with the average historical score values corresponding to the male/female/miscellaneous and in case we don't have any values for miscellaneous we replace it to the average score over all instance (we can also do the same for the variable countries)?
E.g. what is the effect if we replace the categorical variable in itself to a numerical variable which has as values the historical average scores per value in the 'thrown away categorical variable'? It seems to me that this is a efficient trick to convert the categorical variable to some numerical variable and making better future predictions (since, intuitively speaking, future score predictions will depend more on the historical scores for that type of person/country than the type of gender and country in itself).
Answer: I generally do not like to simply say something cannot be done...but in this case, it really can't be done.
The issue is with the categorical predictors in a multiple regression (MR) setting.  You may have a single variable coded with three options for a categorical variable, but when it is analyzed in the MR context, this "single" variable becomes 2 dummy variables.  And if there is complete missing data for one of those categories, then the model cannot be run.
If you think about having only two categories for a moment, then you only need one variable (say female, which is 1 if female and 0 if male).  In the regression model, you would have an intercept and a slope for this variable, female, and maybe other variables.  The coefficient for female is simply the difference between the males and the females (adjusting for the other variables in the model).  Another way to think about it is that the intercept is the average for the males, and the intercept plus the female slope is the average for the females.  Now, if you try to include two variables in the model (male and female), the regression will "crash" because your independent variables are linearly dependent.  Specifically, in this context, if you know the value of female (0 or 1), you automatically know the value of male (1-female).
Returning back to the scenario you are suggesting:  Now we have three categories.  Let's keep male and female, and then the intercept would represent the miscellaneous/other category you proposed.  If you have even one individual with this classification, then they will have male = female = 0 as their coded data.  And the model will run.  However, if you have none in this category, then you really only have two categories.  And the model won't run.
Lastly, without having any information about this subset of the population, you really can't make any guess as to what their data might look like.  Thus, any form of data imputation would be just short of impossible to justify.
I recognize this may not be the response you were looking for, but I do hope it is useful.
Comment: The issue that you are adressing is in fact the problem which I tried to solve by this method ;)! The method I was proposing is in fact to let the script, in which I'm running the regression analysis, assign, e.g., the historical average score for male/female as predictor data and replace this with "male/female" in the gender variable and assign the average of the overal scores to "miscelaneous" in the gender variable; now we've made the categorical variable into a numerical variable, but whats the effect of these systematics (maybe nothing but as benefit now we only can use "recent scores")?


Inserir vários html com ajax

Question: Tenho o seguinte código em jquery:
musicas: function(){
    $.ajax({
        url: 'assets/includes/oloco.php',
        type: 'GET',
        dataType: 'json',
        beforeSend: function(){
            efeito.inicio();
        },
        success: function(data){
            $('.texto').html(data[0].musica);
            efeito.fim();
        }
    }),
    setTimeout(function(){
        player.musicas();
    }, 15000);
}

E no html como visto tenho:

Porém, meu ajax atual só muda o texto da div, gostaria de adicionar 5 divs mudando o data[]!
A requisição oloco.php é em json e tem exatamente 5 valores como podem ver a seguir:
[
{
    "musica": "Luan Santana  Acordando o Pr\u00e9dio - Make U Sweat Remix (Lyric Video)"
},
{
    "musica": "Kygo ft. Parson James - Stole the show (Lyrics video)"
},
{
    "musica": "Justin Bieber Ft Daddy Yankee y Luis Fonsi - Pasito a Pasito Suave Suavecito (Letras)"
},
{
    "musica": "Jhef - Vida M\u00edtica (Official V\u00eddeo)"
},
{
    "musica": "Jhef - Pode ser n\u00f3s dois (Official Video)"
}
]

Como posso inserir várias divs com os valores diferentes e em ordem?
Answer: Basta você iterar sobre o resultado da requisição AJAX e utilizar a função append do jQuery para inserir o elemento no DOM. Deve ficar parecido com isso:
musicas: function(){
    $.ajax({
        url: 'assets/includes/oloco.php',
        type: 'GET',
        dataType: 'json',
        beforeSend: function(){
            efeito.inicio();
        },
        success: function(data){

            // Exclui possíveis músicas anteriores:
            $('.texto').html("");

            // Itera sobre todos os elementos de data:
            $(data).each(i => {
                // Cria um novo elemento p:
                let element = $("
");
                // Define o conteúdo de p:
                element.html(data[i].musica);
                // Adiciona o novo elemento ao DOM:
                $('.texto').append(element);
            });

            efeito.fim();
        }
    }),
    setTimeout(function(){
        player.musicas();
    }, 15000);
}

Comment: E como posso apenas atualizar no setTimeout invez de adicionar mais divs?
Comment: Como assim? Você quer que a cada 15 minutos seja adicionada uma música?
Comment: Dessa forma a cada 15 minutos adiciona novas  com as mesmas músicas, entende? Gostaria que adicionasse apenas ao entrar no site e depois só atualizar o conteudo das mesmas...
Comment: Não está suficientemente claro ainda. Você quer que, quando acessado a página, sejam inseridas as 5 músicas e depois de 15 minutos essas músicas mudem para as novas que retornarem da requisição AJAX?
Comment: É assim, são 5 músicas, porém elas atualizam os nomes a cada certo tempo... Com o append são adicionadas 5 divs a cada 15 segundos, resultando inúmeros textos... Quero que a partir da primeira vez adicionado apenas atualize o seu conteudo (html) invez de continuar acionando....
Comment: A cada 15s está inserindo novas divs ocasionando isso: http://prnt.sc/f5o0za
Comment: Depois de inserido ao entrar no site quero apenas atualizar os conteúdo das mesmas (ao invez de adicionar novas com o append)...
Comment: Entendido. Editei a resposta para corrigir isto.
Comment: Muito obrigado pela atenção amigo, vc é show.
Comment: Acredito que este código já fará isso, irá atualizar sem adicionar.
Esse trecho garante isso:
// Exclui possíveis músicas anteriores:
$('.texto').html("");

Inserir vários html com ajax


How to change access callback of user entity when entity module is installed? (how to make sure my alteration is the last)

Question: I want to change the 'access callback' of user entity to my own access function or at least alter the original function 'entity_metadata_user_access'.
The problem is that 'entity module' which I need because of others' module dependencies already alters the 'user entity information' and changes the 'access callback' to its own function 'entity_metadata_user_access' and so when I alter it with my module, the entity module re-alters it to 'entity_metadata_user_access'.
To make it more clear, the entity module is alters the entity info after me which causes that the final value of the callback is not mine (does not come from my alteration) but its and therefore the callback is wrong.
I know that I could modify the module itself but I honestly don't want to do that because it makes later updates painful.
Comment: By overriding the exact Entity Module hook in your module, you should be able to achieve what you are trying to do. Your hook will be called last. Can you paste your code?
Answer: Here is a complete working example of overriding entity_metadata_user_access:
/**
 * Implements hook_module_implements_alter().
 */
function YOURMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'entity_info_alter') {
    $group = $implementations['YOURMODULE'];
    unset($implementations['YOURMODULE']);
    $implementations['YOURMODULE'] = $group;
  }
}

/**
 * Implements hook_entity_info_alter().
 */
function YOURMODULE_entity_info_alter(&$entity_info) {
  $entity_info['user']['access callback'] = 'YOURMODULE_entity_metadata_user_access';
}

/**
 * Overrides entity_metadata_user_access function.
 */
function YOURMODULE_entity_metadata_user_access($op, $entity = NULL, $account = NULL, $entity_type = NULL) {
  // Include Entity API module's logic
  $return = entity_metadata_user_access($op, $entity, $account, $entity_type);

  // Do your own logic here:
  // $return = $return || ...

  return $return;
}

Comment: Above code is awesome, Save my Day :)
Answer: Take a look at hook_module_implements_alter, you can change the order of the hooks called by Drupal and make sure your alter hook is called as last one.
function YOURMODULE_module_implements_alter(&$implementations, $hook) {
    if($hook === 'entity_info_alter') {
    $group = $implementations['YOURMODULE'];
        unset($implementations['YOURMODULE']);
        $implementations['YOURMODULE'] = $group;
    }
}


Best process to learn a new song

Question: I have been wondering about the best way to learn playing a new song on guitar. For example, a lot of people try to pick a small part, practice and perfect it and then repeat the procedure for the rest of the song.
Any suggestions?
Comment: are you talking about the music, words or both? You've already mentioned to do it in small sections which may work, maybe you need to experiment to find out what suits your learning method. are you mostly visual or aural?
Comment: simply, playing guiutar. mostly visual. edited my Q.
Answer: Breaking pieces into small sections and practising them until you can play them well is probably the best way of learning a new piece.
However, you'll also need to work on linking these sections together so it doesn't sound too disjointed - you don't want to get too used to stopping at a certain point! To get around this, it's also a good idea to practise the entire piece all the way through slowly after you've got most of the sections right. Eventually you can speed up to get to the normal tempo.
Comment: To clarify: breaking pieces into smaller ones is a learning technique known as ***Chunking***. It is efficient for your brain and better for memory transference. I also want to add that you should play each chunk *as slowly as necessary to play it perfectly*. After a set number of perfect performances, increase the tempo gradually. Repeat this process for transitions between chunks.  Ideally, you know you've learned the piece when there are no more chunks left, just fluid, relaxed playing.
Answer: Nobody can answer this for you - everyone has a different learning style, and you are going to have to find out what works best for you.
Some people would prefer to be able to bluff their way through a whole song first - improvising approximate versions of riffs or just strumming chords - before picking out sections to refine.
Other people prefer to perfect bar 1 before moving on to bar 2, and so on.
Personally, I've had teachers who make you repeat a riff for a whole lesson, then never actually go on to perform the whole song. That drives me mad. I'd much prefer to play a whole song badly, than learn one riff and do nothing else with it.
Answer: If you can get or make a recording of it and listen to it over and over again, that's what helps me. When I'm actually playing, I usually hear the whole song or piece in my head - all the parts, all the sections, etc, and I just follow along with what's in my head.
Clearly that method breaks down when I'm working with others on writing a song. In those cases I count measures or repeats out loud and might even call changes out for everyone's benefit (including mine). Having a white board around to write the changes down on to have them large and clearly readable helps during writing (or learning). I'll also use software to make little demo versions which help me learn the structure and also see areas of weakness or come up with ideas.
In terms of how I learn right off the bat, I usually start at the beginning and work my way to the end. Tricky parts will get extra attention. I don't like to get in the habit of only working a section at a time because transitions are key so I like to try to keep it unified with smooth changes from section to section.
Answer: If you know how to read and write music, you can consider something like what Adam Neely demonstrated on his YouTube channel.
He suggests writing out the music as you listen to it. Then, you can save the PDF and refer to it if you ever forget how the song goes. As long as you get quick at this, it could be pretty effective in the long run—but it takes some focus and a bit of a learning curve. He's also doing it for bass, which is a little simpler than for guitar since bass is typically monophonic.
It also requires a pretty good ear and preferably a quality recording. If your ear isn't well developed, the bonus for this method is that it will get a lot better with practice, and should make your life in music a lot more smooth!
What other answers have mentioned is also relevant—especially focusing on sections that you find difficult. Playing a section because you find it enjoyable, for example, is… well, enjoyable, but it's not the same thing as practicing.
Answer: Okay- This is for someone that has a good ear rather than reading or copying someone else playing. so for me, I find it easiest to find the root scale of the song first. I play piano instead of the guitar but it works the same. If you have found in what scale the song is in, you can start listening for the chord progressions. Now you have the basic skeleton of the song,you know which notes to play and which ones not to, and you know how the chords progress. Now you can start focusing on the finer details of the song. Is there picking evolved or some palm mutings. Also, do you want to learn the chord strumming or do you want to play the lead part... Either way, this always works for me.  enjoy

Best process to learn a new song


How to change Android app name?

Question: I want to change android application name programatically. Is there any API to do this? Thanks.
Comment: You cant do that. But WHY?, follow the standards.
Comment: ignore, I don't know where I found a citation.
Answer: You can't change the app name programatically. It is in the manifest. Why do you want to do that anyways?
Comment: +1 ^^... just imagine the possibilities if it could be changed :D
Answer: You cant do it pragmatically.its static.Go to menifest file and add android:label="Your application name" in application tag like below
 <application
    android:icon="@drawable/ic_launcher"
    android:label="Your application name">

Answer: You could try to change the name using Antscripts, but this could just happen during devTime.
The appname itself does stand in the manifest.xml:
<application android:label="My App name">

Mostly its refered to the R.String file.
Otherwise as codeBegin already said, use setTitle("AppName") to change the title in the current activity.
If you really want to change the name of the WHOLE app, this would NOT be possible, just imagine what a chaos will be created if apps are renamed frequently ;)

How to change Android app name?


Creation + Drag and drop of groups of fields with CCK

Question: I have an image field with unlimited number of values but they relate to each-others in sets like this:
1a
1b
1c
2a
2b
3a
3b
3c
3d

My goal would be to create a text field before the first image of each set and to be able to drag and drop each set without effecting the order inside each set.
It would look like this:
Header for 3
3a
3b
3c
3d
Header for 1
1a
1b
1c
Header for 2
2a
2b

Is there a module that provides a similar functionality?
Unfortunately multi-groups doesn't cut it for me because it just pairs the text field with the image field...
Answer: Take a look at field collection module.
You could create a field collection with a text field (Number of values: 1) and an image field (Number of values: Unlimited). Then you should set your field collection field also to unlimited values so you can add as many sets you want.
Nevertheless field collection is a little buggy, but give a try first.


Android Bot in notification tray instead of launcher icon - FCM

Question: I am using ionic3 to build a hybrid app and use this fcm push notification cordova plugin for receiving notification
I have been able to achieve the notifications landing on the device and app being triggered (with data like title, body, custom, etc.)
But whenever the notification is delivered the notification icon is displayed as android bot. like
My Launcher icon is a different icon, which works fine
To initiate the notification, I send a curl request to  https://fcm.googleapis.com/fcm/send with the following json:
{
    "to":"device_token",
    "priority":"high",
    "notification":{
        "title":"New Notification!",
        "body":"Test",
        "sound":"default",
        "click_action":"FCM_PLUGIN_ACTIVITY",
        "icon": "icon" //optional piece
    },
}

A icon.png is present in all android/res/mipmap* directories.
Also, I have added the following meta in my AndroidManifest.xml reference
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/icon" />

Also, I have tried to read logcat from the device. Whenever I have passed icon param in the json that I post to fcm, I see the following log
06-12 23:43:38.457 22257 22303 W FirebaseMessaging: Icon resource icon not found. Notification will use default icon.

But whenever I don't pass the icon in the json, I dont see the above message in logcat.
I think I am missing a simple thing somewhere but not able to figure it out
Please help me with some pointers, guidance on where i may be wrong
Thanks in advance
Answer: Finally I was able to figure the issue.
I had to dwell further into ADB logs to find the following:
06-18 20:46:59.898 11432 11470 E FirebaseMessaging: Icon with id: 2131165319 uses an invalid gradient. Using fallback icon.

Then I got a reference to this
On further investigation I found that my project.properties and FCMPlugin.gradle were pointing to firebase 11.8.0
Changing that to 11.0.1 at both the places and rebuilding the app, I was able to receive the notification with icon


How to send commands to USB line printer in Java

Question: I need to print some stuff via a thermal printer SK-21. I want to send command to control linefeed etc. I've written a simple test code to print a line and to eject the papier by command 0D. There's the piece of code it's just simple primitive for test:
FileOutputStream printer = new FileOutputStream("/dev/usb/lp0");
String text = "This is a test print performed by my application";
printer.write(text.getBytes());
printer.write(0x0D);
printer.flush();
printer.close();

It prints the text, but doesn't react at all to the command 0x0D which should eject the printed line. I have to eject the paper manually by pressing a button. If I do the following commands in terminal:
echo "text" >> lp0
echo -e \\x0d >> lp0

It prints "text" and ejects paper with printed line.
Any ideas how to do it in Java?
Answer: Your "echo" commands send a trailing \n  each, which is code 0x0A.
Try the following:
printer.write(0x0D);
printer.write(0x0A);


Windows: Determine number of cores from a performance monitor file?

Question: Is there any way to determine how many cores a particular machine's CPU has based on a Performance Monitor file I have?
Additionally, can we see if hyperthreading is enabled?
For a period of high usage, it seems the total % Processor Time is 94 which would suggest 1 core at nearly 100% usage - I believe, it would be  >100 for 2 cores etc?
Additionally, the % Process time is 196% which would suggests hyperthreading is enabled?
Thoughts?
Answer: 'ProcessorPerformance' will show a number of instances, usually called 'PPM_Processor_X' - that's the number of logical cores available to you. No way to tell if they're regular or HT threads though sorry.
Comment: Where can I find that, @Chopper3?
Comment: it's one of the perfmon root counters


Determine figure by binnary two-dimensional array

Question: i use c++
i've 2d array consisted with 0,1. The 1 draw a figure of circle/square/triangle(only this 3, and only 1 figure possible). The figure does not touch the borders. It does not exceed the bounds. Size of the biggest side or the radius of the figure is not less than 30px. The least angle of the triangle is not less than 10 degrees.
I tried to calculate frequencies of appearing black cells for every row and column. It should allow to recognize the figure i think.
If anyone can give any idea/code of solution, it will be very nice.
Comment: if you have (1 1 \n 1 1), would it be considered square or circle?
Comment: well, the issue is generally for >30px figures
Comment: are the shapes always centered and/or always the same size?
Comment: This sounds a bit like a homework task, so we're reluctant to spoil all the fun of finding your own solution by giving too many hints, but I guess the trick is to detect straight lines (or their absence)
Comment: no, not always centered. The main problem is to differ centered square from circle
Comment: Is the square axis aligned ?
Comment: http://rghost.ru/51520689/image.png  actually both are possible
Answer: Look for vertices, or corners.  A corner pixel is surrounded by fewer pixels than an edge pixel.  A square will have 4 corners, a triangle fewer, and a circle may have either many or none, depending on how you detect the corners.  Also, your minimum size and minimum angle guarantee that no two corners will be close together.  Fun problem.


Webpack concat output js file to wrap it in a library?

Question: I need to concat a webpack output with other files, like pre.js + bundle.js(the webpack output file) + after.js. I've tried the webpack concat plugin and also combining webpack with gulp, but I just can't figure out how to get the output file and pipeline it to concat task. The purpose of this is to wrap the output in a custom library.
webpack.config.js:
module.exports = {
    context: path.resolve(__dirname, 'src'),
    entry: './app.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [{
            test: /\.js$/,
            include: path.resolve(__dirname, 'src'),
            use: [{
                loader: 'babel-loader',
                options: {
                    presets: [
                        ['es2015', {modules: false}]
                    ]
                }
            }]
        }
    ]},
     plugins: [
        new ConcatPlugin({
            useHash: true,
            sourceMap: true,
            name: 'flxeible',
            fileName: '[name].bundle.js',
            filesToConcat: ['pre.js','dist/bundle.js','after.js']
        })
    ]
};

This concatenates the bundle.js that's been already been built, not the one that's being generated and updated by the webpack dev server.
using gulp:
var gulp = require('gulp');
var gutil = require('gulp-util')
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server')
var webpackConfig = require('./webpack.config.js')

gulp.task('default', [ "webpack-dev-server"])

var myDevConfig = Object.create(webpackConfig);

gulp.task("webpack-dev-server", function(callback){

    new WebpackDevServer(webpack(myDevConfig), {
        stats: {
            colors: true
        }
    }).listen(8080, "localhost", function(err){
         if(err) throw new gutil.PluginError("webpack-dev-server", err);
         gutil.log("[webpack-dev-server]",
         "http://localhost:8080/webpack-dev-server/index.html");
     })
})

in the second case, not sure how to get the webpack output in gulp.
Answer: You're using gulp solely to run the webpack-dev-server? This is not necessary: https://webpack.js.org/guides/development/#using-webpack-dev-server
Without knowing the content+purpose of pre.js and after.js, it's hard to give good advice. You might want to adapt the BannerPlugin to also output a footer=after.js, or configure webpack to generate multiple targets (first dist/bundle.js, and pre.js+dist/bundle.js+after.js afterwards), or check the various ways for shimming, or combine the tree files to a new entry file via three subsequent imports (import 'pre.js'; import 'bundle.js'; import 'after.js'). Good luck.


How to remove hover function from top row in table

Question: I'm having trouble trying to remove the hover function I created from the top row in my table.
I'm trying to create a table that can be used to compare different products. I want to use a hover function for the whole table but the top row (where I will later put images). How can I remove the hover for top row only?
This is my code:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Compare Table</title>
    <link rel="stylesheet" href="index.css">

    Image
    Image
    Image

   TITLE
    &#x2714
    &#x2714
    &#x2714

  TITLE
    &#x2714
    &#x2714
    &#x2714

  TITLE
    &#x2716
    &#x2716
    &#x2716

  TITLE
    &#x2714
    &#x2714
    &#x2714

And the CSS:
th,td {
    padding: 15px;
    text-align: center;
}

.hoverTable tr:nth-child(even) {
    background-color: #eee;
}
.hoverTable tr:nth-child(odd) {
   background-color:#fff;
}

.blankcell {
    background: none!important;
    border: none!important;
}

/* HOVER FUNCTION */
.hoverTable{
        width:100%;
        border-collapse:collapse;
    }
    .hoverTable td{
        padding:7px;
        border: #000000 1px solid;
    }
    /* Define the default color for all the table rows */
    .hoverTable tr{
        background: #ffffff;
    }
    /* Define the hover highlight color for the table row */
    .hoverTable tr:hover {
          background-color: #86D694;
    }

/* Check and X-Mark Coloring*/
#check {
    color: #1CF200;
}
#x01 {
    color: #ff6969;
}

Thank you for your time!:)
Answer: Try this:
.hoverTable tr:nth-child(n+2):hover {
      background-color: #86D694;
}

This only applies the hover to rows after the first row.
DEMO
Comment: I like this solution a lot. Note however, that depending on your requirements, IE 8 has limited [support](http://caniuse.com/#search=%3Anth-child) for _CSS3_ selectors like `:nth-child`. I know at this point, it's an older browser, but it's still worth consideration. Either way, +1
Answer: You need to override the hovering style for the first row only. Add the below code:
.hoverTable tr:first-child:hover {
    background: #fff;
}

after this snippet:
/* Define the hover highlight color for the table row */
.hoverTable tr:hover {
      background-color: #86D694;
}

Below is a full live snippet that show's the results:

th,td {
    padding: 15px;
    text-align: center;
}

.hoverTable tr:nth-child(even) {
    background-color: #eee;
}
.hoverTable tr:nth-child(odd) {
   background-color:#fff;
}

.blankcell {
    background: none!important;
    border: none!important;
}

/* HOVER FUNCTION */
.hoverTable{
        width:100%;
        border-collapse:collapse;
    }
    .hoverTable td{
        padding:7px;
        border: #000000 1px solid;
    }
    /* Define the default color for all the table rows */
    .hoverTable tr{
        background: #ffffff;
    }
    /* Define the hover highlight color for the table row */
    .hoverTable tr:hover {
          background-color: #86D694;
    }
    .hoverTable tr:first-child:hover {
        background: #fff;
    }

/* Check and X-Mark Coloring*/
#check {
    color: #1CF200;
}
#x01 {
    color: #ff6969;
}

    Image
    Image
    Image

   TITLE
    &#x2714
    &#x2714
    &#x2714

  TITLE
    &#x2714
    &#x2714
    &#x2714

  TITLE
    &#x2716
    &#x2716
    &#x2716

  TITLE
    &#x2714
    &#x2714
    &#x2714

Answer: .hoverTable tr:not(:nth-child(1)):hover {
      background-color: #86D694;
}

http://jsfiddle.net/ebvywkg5/
Answer: Add a "hov" class to all the table rows you want to be highlighted when hovered:

    Image
    Image
    Image

   TITLE
    &#x2714
    &#x2714
    &#x2714

  TITLE
    &#x2714
    &#x2714
    &#x2714

  TITLE
    &#x2716
    &#x2716
    &#x2716

  TITLE
    &#x2714
    &#x2714
    &#x2714

And then change this CSS to include the "hov" class:
.hoverTable tr.hov:hover {
      background-color: #86D694;
}

Answer: Here's my recommendation that would simplify your question and make your table more accessible: put the first row in a thead tag and the remaining rows in a tbody tag. Then you can use the tbody tr selector to target the rows that aren't in the header.


How to play the given part without the left and right hand clashing?

Question: How to play the 'E' note in bass clef (left hand)  without clashing with the 'D' note played in treble clef(right hand).
Key is C.
Comment: I would play it the same way as in the other bars.  Four eighths and a half. You shouldn't trust this arrangement anyway: This is no good notation. Look at the 2 bars the line below.
Answer: Do you mean clashing harmonically?  That's the composer's prerogative.  If you mean clashing physically, it is fine.  Play the 'E' with the left hand above the right hand.  Note that rhythmically the E comes between the C and D.


How do you choose the correct stem length for notes on a beam?

Question: Stems are supposed to be 3.5 stave spaces tall. When the notehead is on the 2nd line outside the staff or beyond, the stem should extend to touch the center line. When the 3rd flag (or beam) is added to a note, the stem is lengthened.
That part I get.

What I don't get is how to size all the stems attached to a beam. I've looked in a LOT of books and it's still unclear to me ... anybody know?
Is there any standard for how much to tilt the beam (if it should tilt)?
Comment: I'm not at all an expert on typesetting, but I suspect that the answer will be that stem lengths are dictated by ease of reading and aesthetics.
Comment: Sometimes the noteheads are found on both sides of the beam. Are there rules for that one might wonder?
Answer: Convention differs.  The 3.5 spaces thing isn't a fixed rule, either.  Remember that notation is arbitrary and you can twist it to suit your needs.  As Babu says that can include readability and aesthetics.
Personally, I just try to ensure the average is approximately 3.5 spaces.  A nice trill might be 4-3-4-3-4-3-4-3, for example.  Obviously in some cases you'll need to angle the beam to achieve that, and I'd basically follow luser droog's advice in that case (where possible).  In some cases you might want to forgo the beam as well — if they're really hard to connect it might (might) be an indication that they're not really part of the same phrase.
Comment: I think the 3.5 space stem length is VERY standard, except where there are reasons to modify the stem per #flags, reaching middle line for ledger notes, etc.  For hand written sheets, you can do what you want.  But if it's published, it probably needs to meet all engraving standards.  Which are PRETTY dang hard to work out :/
Comment: @Matthew Notation is a complex and nuanced subject. It's arbitrary by definition, but there are entire books written on the subject, and I do recall my theory professor at one point stating that beaming rules are incredibly complicated--but these rules DO exist. It's just less relevant for musicians to learn nowadays with the advent of Sibelius and Lilypond, unless you're actually _writing_ the software.
Comment: @NReilingh For sure. I view it like general typography -- definitely some science involved, but at the end of the day kerning and serifs and so on are all up to the font designer.
Answer: OK, it's much simpler than I thought.  I asked on pianoworld.com and you just find the shortest stem of all of them in the beam and shorten it down to 3 spaces if beam is within staff or 2.5 if it's beyond the staff.  If the notes in the beam are only one space apart, you don't shorten it at all, of course.  The outside 2 are only used to determine if the beam slants (in addition to all the other slant criteria).  How much to slant is not well defined from what I've found (I've read several engraving books) other than that slants should be slight as I've mentioned.
Answer: The beam should tilt or not depending on the relative direction of the two outer notes.
And again with the stems, make the outer two stems normal length (or as close as you can manage to maintain the proper tilt) and let the inner ones fall where they may.
Comment: Per the book "Behind Bars" (which is GREAT), the beam should be level if
a) outer 2 notes are the same
b) a repeating pattern of notes is beamed (say, b d f b d f)
c) an inner note has a shorter stem length than the outside 2

Also, beams should be .5 spaces thick with .25 spaces between.  They should either sit or hang on a line or be split evenly by a line, but NEVER be centered on a space.
This leads to adjusting the stem length by .25 space for level beams so this will occur.

Now, when the beam tilts, it's recommended to keep it at 1 space on average.
I'm not sure your way will work..:/
Comment: I'm still trying to dig up the book I've got on this. I suppose I'll have to resort to the Amazon history; I'm just not finding it. But all of these rules carry an implicit "...unless it looks better to do it differently."
Comment: Ok, actually, i think you're right.  But since beams are pretty level even when tilted, the shorter of the 2 on the outside gets standard length of 3.5, or shortened to a min of 3 (2.5 if beam is off staff).  So if slant is low to hi with stems up, leftmost note gets 3.5 or slightly shorter length, and all other stems get lengths to hit the beam slant.  Ok, I think I get how it works now.  Thanks for the help yall - I appreciate it.  I'm beginning to REALLY regret adding standard notation to my sequencer - arrgh !
Comment: Hmmm, in my example, I think I chose the wrong note for the anchor stem.  Left note lower than right note, stems up, beam more level than the noteheads - would make the right note the shorter "anchor" note.  (I think?)
Comment: Yes. A sort of trapezoid. If the short stem is less than some threshold (maybe try 2 to start?) then stretch them all to bring it to the min. ... A couple threads I started on this in comp.lang.postscript are [here](https://groups.google.com/forum/?fromgroups#!topic/comp.lang.postscript/RmhlgKvtSTk) and [here](https://groups.google.com/forum/?fromgroups#!topic/comp.lang.postscript/8vAHBSLfgXs) (I hope the links work, googlegroups is a bit "transitional" right now).
Comment: argh!  postscript!  (kidding:)  I'll see what I can figure out.  Thanks for the help.  I think this is some of the most brutal code I've ever written in my life...


k8s ambassador ingress sample not working

Question: I'm currently on OSX (Catalina) with Docker Desktop (19.03.5) running k8s (v.14.8)
Following the ambassador getting started article, I've done the following:
Created a file called ambassador-ingress.yaml
---
apiVersion: v1
kind: Service
metadata:
  labels:
    service: ambassador
  name: ambassador
spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 80
  selector:
    service: ambassador
---
apiVersion: v1
kind: Service
metadata:
  name: google
  annotations:
    getambassador.io/config: |
      ---
      apiVersion: ambassador/v0
      kind:  Mapping
      name:  google_mapping
      prefix: /google/
      service: https://google.com:443
      host_rewrite: www.google.com
spec:
  type: ClusterIP
  clusterIP: None

And I've run the following
$ kubectl apply -f https://www.getambassador.io/yaml/ambassador/ambassador-rbac.yaml
$ kubectl apply -f ambassador-ingress.yaml

I can now look at kubectl get pods and kubectl get service
$ kubectl get pods
NAME                                         READY   STATUS    RESTARTS   AGE
ambassador-74fb8f5668-2b85z                  1/1     Running   0          20m
ambassador-74fb8f5668-r6jrf                  1/1     Running   0          20m
ambassador-74fb8f5668-vrmjg                  1/1     Running   0          20m

$ kubectl get service
NAME                 TYPE           CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
ambassador           LoadBalancer   10.97.166.229    localhost     80:31327/TCP     18m
ambassador-admin     NodePort       10.96.1.56       <none>        8877:30080/TCP   18m
google               ClusterIP      None             <none>        <none>           18m
kubernetes           ClusterIP      10.96.0.1        <none>        443/TCP          13d

Everything looks like it is setup correctly, however, whenever I attempt to curl k8s I can't get anything but an empty server response even though I can hit google directly:
$ curl localhost/google/
> curl: (52) Empty reply from server
$ curl www.google.com
> <!doctype html> ............

The question I have is, where do I begin troubleshooting?  I don't know where the failure lies or how to begin digging to find what has gone wrong. What is the right direction?
Answer: Based on "The Kubernetes network model" [1] there are 2 important rules:

pods on a node can communicate with all pods on all nodes without NAT
agents on a node (e.g. system daemons, kubelet) can communicate with    all pods on that node

So basically it says that since your K8s cluster is located on your machine, you can directly communicate to the service ip "10.97.166.229" and POD IP.
So, regarding how to begin your troubleshooting steps, since your PODs are up and running, most likely this is a network error. You can try this:
a) Try to connect to your pod directly. You can get your IP by executing the command:
kubectl get pod -o wide

b) Get the LOGs of your POD and search for any error:
kubectl logs ambassador-74fb8f5668-2b85z

c) Go inside your POD and check if you can test connectivity inside your POD. [2]
kubectl exec -it ambassador-74fb8f5668-2b85z -- /bin/bash

[1] https://kubernetes.io/docs/concepts/cluster-administration/networking/
[2] https://kubernetes.io/docs/tasks/debug-application-cluster/get-shell-running-container/


Sagemaker training job failed - having issues executing user script

Question: I am very new to AWS Sagemaker and am trying to deploy my SKLearn script to an endpoint so that I can call it from within an Android app. I am following the code here, and so far, getting each block to work with my script has worked. The block that is giving me issues is
sklearn_estimator.latest_training_job.wait(logs="None")
artifact = sm_boto3.describe_training_job(
    TrainingJobName=sklearn_estimator.latest_training_job.name
)["ModelArtifacts"]["S3ModelArtifacts"]

print("Model artifact persisted at " + artifact)

Specifically, the first line. When I run this block, I get this error:
UnexpectedStatusException                 Traceback (most recent call last)
<ipython-input-54-65920860bce1> in <module>
----> 1 sklearn_estimator.latest_training_job.wait(logs="None")
      2 artifact = sm_boto3.describe_training_job(
      3     TrainingJobName=sklearn_estimator.latest_training_job.name
      4 )["ModelArtifacts"]["S3ModelArtifacts"]
      5

/opt/conda/lib/python3.7/site-packages/sagemaker/estimator.py in wait(self, logs)
   1994             self.sagemaker_session.logs_for_job(self.job_name, wait=True, log_type=logs)
   1995         else:
-> 1996             self.sagemaker_session.wait_for_job(self.job_name)
   1997
   1998     def describe(self):

/opt/conda/lib/python3.7/site-packages/sagemaker/session.py in wait_for_job(self, job, poll)
   3217             lambda last_desc: _train_done(self.sagemaker_client, job, last_desc), None, poll
   3218         )
-> 3219         self._check_job_status(job, desc, "TrainingJobStatus")
   3220         return desc
   3221

/opt/conda/lib/python3.7/site-packages/sagemaker/session.py in _check_job_status(self, job, desc, status_key_name)
   3381                 message=message,
   3382                 allowed_statuses=["Completed", "Stopped"],
-> 3383                 actual_status=status,
   3384             )
   3385

UnexpectedStatusException: Error for Training job rf-scikit-2022-08-05-22-32-08-239: Failed. Reason: AlgorithmError: framework error:
Traceback (most recent call last):
  File "/miniconda3/lib/python3.7/site-packages/sagemaker_containers/_trainer.py", line 84, in train
    entrypoint()
  File "/miniconda3/lib/python3.7/site-packages/sagemaker_sklearn_container/training.py", line 39, in main
    train(environment.Environment())
  File "/miniconda3/lib/python3.7/site-packages/sagemaker_sklearn_container/training.py", line 35, in train
    runner_type=runner.ProcessRunnerType)
  File "/miniconda3/lib/python3.7/site-packages/sagemaker_training/entry_point.py", line 100, in run
    wait, capture_error
  File "/miniconda3/lib/python3.7/site-packages/sagemaker_training/process.py", line 291, in run
    cwd=environment.code_dir,
  File "/miniconda3/lib/python3.7/site-packages/sagemaker_training/process.py", line 208, in check_error
    info=extra_info,
sagemaker_training.errors.ExecuteUserScriptError: ExecuteUserScriptError:
ExitCode 1
ErrorMessage ""
Command "/miniconda3/bin/python SageMaker_Script.py"

ExecuteUse

SageMaker_Script.py is the name of my script. The relevant code in my script is:
if __name__ =='__main__':

print('extracting arguments')
parser = argparse.ArgumentParser()

# hyperparameters sent by the client are passed as command-line arguments to the script.
parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])

# Data, model, and output directories
parser.add_argument("--model-dir", type=str, default=os.environ.get("SM_MODEL_DIR"))
parser.add_argument("--train", type=str, default=os.environ.get("SM_CHANNEL_TRAIN"))
parser.add_argument("--test", type=str, default=os.environ.get("SM_CHANNEL_TEST"))
parser.add_argument("--train-file", type=str, default="jumpstrain.csv")
parser.add_argument("--test-file", type=str, default="jumpstest.csv")

args, _ = parser.parse_known_args()

print('reading data')
train_df = pd.read_csv(os.path.join(args.train, args.train_file))
test_df = pd.read_csv(os.path.join(args.test, args.test_file))

print('building training and testing datasets')
X_train = train_df[columns]
X_test = test_df[columns]
y_train = train_df[['Under-rotated']]
y_test = test_df[['Under-rotated']]

print('training model')
model = RandomForestClassifier(n_estimators = 100)
model.fit(X_train, y_train)

print('validating model')
pred_values = model.predict(X_test[columns])
print('f1-score:')
f1score = f1_score(y_test, pred_values)
print(f1score)

# persist model
path = os.path.join(args.model_dir, 'model.joblib')
joblib.dump(model, path)
print('model persisted at ' + path)
print(args.min_samples_leaf)

I am at a loss for what the issue is because, like I said, I am very new to AWS in general, and the error that it gives me is not super informative. Any help would be greatly appreciated.
Answer: Looks like there is an error in your training script, to get started I would recommend you follow this step to step guide to create your training script and job for an SKlearn Model - https://sagemaker.readthedocs.io/en/stable/frameworks/sklearn/using_sklearn.html#train-a-model-with-scikit-learn


Does Greens Theorem apply to the annulus?

Question: I realize that it does, but I can't prove it. If the region is of the form: $$ D = \{ (x,y) ) \ | \ x \in [a,b] , \ \mu(x) \le y \le v(x) \}$$
or, with $y$ and $x$ changing place (and especially if it holds both ways), then I can do it on my own..... but what about when we've got a shape like $$E = \{ (x,y) \in \mathbb{R}^2 \ | \ 1 \le x^2 + y^2 \le 2 \}$$
How would we 'cut' it, and why would that 'cut' work? Generally, I'm quite interested in how the proof where $E$ is a 'simple region/domain' can then be applied to more complicated regions.
Comment: Good to know! I'll edit... EDIT: It's already done. And it's "she" meant Annulus, editor man/woman.
Comment: Apologies! Welcome to math.stackexchange @Michelle
Comment: @columbus8myhw never heard of this term before. It was always "a ring". One can never stop learning something new, I guess.
Answer: Consider $E_+=\{ (x,y)\in E : x\geq 0\}$ and $E_-=\{ (x,y)\in E | x\leq 0\}$. You can now use Green's theorem on each of these domains and then add up the result.
$$\int _{\partial E_+} F\cdot dl + \int _{\partial E_-} F\cdot dl=\int_{E_+}(Q'_x-P'_y) \cdot dx \cdot dy + \int_{E_-}(Q'_x-P'_y) \cdot dx \cdot dy = \int_{E}(Q'_x-P'_y) \cdot dx \cdot dy$$
The union of the boundaries of $E_+$ and $E_-$ gives you the boundary of $E$ plus the two lines where we cut the annulus, namely $l=\{(x,0) | 1\leq x^2 \leq 2\}$. Since we use the anticlockwise direction for both boundaries, we get that for $E_+$ the direction on $l$ is from left to right, and on $E_-$ is from right to left. It follows that the two integrals on $l$ cancel each other and you are left only with the integral on the boundary of $E$ (this is easily seen if you draw this). Note also that if you set $\Gamma_r$ to be the curve of the circle of radius $r$ around the origin rotating anticlockwise, then you get that
$$\int_{E}(Q'_x-P'_y) \cdot dx \cdot dy = \int_{\Gamma_\sqrt{2}} F\cdot dl - \int_{\Gamma_1} F\cdot dl$$
or in other words on the boundary on the "outside" you go anticlockwise and on the "inside" you go in the clockwise direction.
Basically, this can be extended to all the "nice" regions you usually encounter. Just cut this regions to simple regions, use the theorem for each of these simple regions and then add up. The integrals on the curves where you cut will always cancel each other.