exim configuration: 503 AUTH command used when not advertised

Question: I'm running a piece of software on a Windows server that sends email notifications via a remote SMTP server. It has very few configuration options, and only supports basic SMTP authentication without SSL/TLS. I have exim4 running on a Debian server that will be the SMTP server for this Windows program. It is set up with default configuration, plus allowing AUTH PLAIN and AUTH LOGIN unencrypted connections. I have successfully sent an email over telnet:
telnet servername 25
ehlo test
250-AUTH PLAIN LOGIN
...
auth plain XXX
235 Authentication succeeded
mail from: ...
...

However, the program I want to connect to this server fails to connect. To see why, I ran a packet sniffer during the connection, and see the following session:
C: HELO hostname
S: 250 Hello hostname
C: AUTH LOGIN XXX | XXX
S: 503 AUTH command used when not advertised | 500 unrecognized command
C: QUIT
S: 221 closing connection

I'm not familiar enough with the SMTP protocol to understand what's going on here. What do I need to change on my exim4 SMTP server to allow for this connection to be made?
Comment: This bypasses your question, but you could also set exim to allow relaying from the ip address of your windows server. This may be required if you can't get your application to do ehlo as Coding Gorilla mentions.
Comment: @Christopher: Thanks, that seems like an easier way to approach it. Although I believe this machine is on a dynamic IP...
Comment: Bad idea to set `allow_auth_unadvertised` on exim. The protocol explicitly requires advertising, and your client program is broken, period. This feature should never have got into exim. One server I'm responsible for doesn't advertise AUTH (it has alternative authentication) but occasionally gets attacked for days on end by automated clients who AUTH anyway, then just guess names/passwords. I've 'fixed' this by terminating clients who send unwanted AUTHs. IMO, unwanted AUTHs are a good indication that the client is a hacker.
Answer: The 503 AUTH command used when not advertised essentially explains itself, it didn't offer the client the option to use the AUTH command.  This is most likely because the client used HELO rather than EHLO (which I would note you used when you did your telnet test).
SMTP Authentication is part of Extended SMTP, which is initiated with the EHLO command; "plain old" SMTP did not support authentication and so it is technically an illegal command, even though some SMTP servers may still allow it.
Best possible solution is to tell your program to use Extended SMTP (EHLO) if possible, otherwise there might be an exim command to force it to allow AUTH on HELO type connections.
** UPDATE **
According to this post here: http://www.exim.org/lurker/message/20040901.063858.126f66ac.en.html

EHLO (not HELO) must be given by client before AUTH.
That is, AUTH command could not be used unless advertised (through
  EHLO,  according to auth_advertise, etc). This behavior was hardened
  in Exim
  4.20 and is not an option.

Looks like you need a differnt MTA if your can't get your application to do EHLO.  Or, do you require authentication, can you accomplish the same thing using IP based ACL's?
FINAL SOLUTION
Exim does have a work around for this, using allow_auth_unadvertised as described here, you can do something like this:
hosts   = *
control = allow_auth_unadvertised

Comment: Ok, that's good to know!  I like this comment in that link, which seems to sum up your situation: "Furthermore, because there are apparently some really broken clients that do this, Exim will accept AUTH after HELO (rather than EHLO) when this control is set." =)
Comment: It actually looks like there is a solution in current versions of exim. See the description of  `allow_auth_unadvertised` [here](http://www.exim.org/exim-html-current/doc/html/spec_html/ch40.html#SECTcontrols).
Comment: Strange, sounds like it's breaking the protocol then. I'd be interested to hear if anyone has more information on advertising AUTH on a `HELO` connection.
Comment: @jrdioko Updated with additional info on Exim
Comment: Thanks for the clarification. As mentioned in a comment above the client is on a dynamic IP so ACL's won't work. My only other thought that I read somewhere is to make exim reject `HELO` commands to try to force the client to send `EHLO` instead.
Comment: What about basing the ACL on the `HELO` host name?  I'm guessing your application won't send the `EHLO` (although definitely try), it's probably a poorly written SMTP implementation, which I often find in older software.
Comment: Ah, didn't realize that was possible, that sounds like it could work, I'll look into it.
Comment: It's not the best solution, since if someone figured it out, it's obviously very easy to spoof; but if you don't mind the risk it should get you by.
Comment: True, but that's a risk of unencrypted authentication in general.
Comment: That worked like a charm. Could you post a quick update to your answer, for people that don't read through all these comments?
Comment: The link is not showing anything it's supposedly showing.
Answer: I had a similar problem. This message can occur even if EHLO is used, when the server is running Exim.
In WHM > Home > Service Configuration > Exim Configuration Manager, the option "Require clients to connect with SSL or issue the STARTTLS command before they are allowed to authenticate with the server" was set to the default (On). I'm not sure if I did this or not, and it is ordinarily a great idea for security, but forces the mailserver to enable (advertise) only the STARTTLS command, not AUTH. So when my script sends AUTH, the error message the server sends is correct. Further information is at http://blog.networkpresence.co/?p=8923 . Someday when I have time I will find out how to change my script to use TLS, so I can turn that Exim option On for security.
ADDED 11/19/19:
I have found how to change my local "send email" script to use TLS, and I have changed my server back to requiring either TLS or STARTTLS.
Why did I do this?
Because several websites I use require secure mailservers when sending email notifications. I had a devil of a time figuring out why they kept complaining about my email address: it was because my mailserver accepted insecure connections!
Thinking about it further, I realized that all Web operations should be secure (this is the basic idea behind the Let's Encrypt project, which was the first to provide free security certificates that renew automatically).
Two changes need to be made to a PHP "send email" application that uses the fsockopen function to change it from an insecure to a secure connection with the mailserver (this will eliminate the 503 error message the right way):

Change the fsockopen port argument from 25 to 465.
Change the fsockopen host argument scheme from (empty) to ssl:// . So, if the host was "mail.example.com", change it to "ssl://mail.example.com".

It may also be necessary to enable the line "LoadModule ssl_module modules/mod_ssl.so" in the httpd.conf file (for local Apache servers) or make some other local change to make PHP internet transports work. I'm not sure about this. Just these two changes worked for me right away.
Comment: Yes, making a mailserver accept insecure connections works like a charm, but it will allow lots more access by malicious users and increases the chances of getting your mailserver compromised. I've edited my answer to favor using secure connections. I apologize for my ignorance in advocating insecure access, but detailed mailserver security is not a well-documented topic and I was just trying to help in the only way I could at the time.
Comment: It works like a charm!


In Pearson Distribution System's range for $x$

Question: For some Type of the Pearson distribution system, the $x$ is bounded for a certain range.
Now if I want to get the probability of say certain $x$ value and yet it is out of the defined bounds of a specific Type of the Pearson system, does it mean that I can't use the Pearson Distribution system for this situation? (Because it only gives the value equal to zero.)
However, when I check using the Monte Carlo simulation, the probability is not equal to zero.
Is this a limitation of the Pearson distribution system?
Comment: It suggests that you are looking at the wrong distribution
Answer: The Pearson system is a location-scale family.
For example, consider the Pearson type I, which is a four parameter beta - while the standard beta family is on (0,1), the corresponding distribtuion in the Pearson system is on any finite interval you like.
You should be able to find suitable estimates for the boundary parameters (avoiding impossible values for estimates -- i.e.  estimates that don't leave data hanging outside the bounds). This may contradict matching the mean and variance, however -- method of moments type estimation won't necessarily pick values that do this.
Similar comments apply to the Pearson types that are bounded on one side.
If you're fitting the distributions to your data, you should be able to avoid this problem but it may involve considerably more effort than the usual method of moments -- and even directly attempting to maximize the likelihood without some form of regularization / modification may lead to problems (see the comments below).
So it's not that you can't use the Pearson system with your data -- but you might have to modify the way in which you're using it. Alternatively, you might consider using another system, such as the Johnson distributions.

Note on maximum likelihood with the four-parameter beta
[Some similar issues can come up with the three parameter gamma as well -- this is Pearson type III.]
There can be some issues with maximizing likelihood for the endpoints in the four parameter beta case, particularly in non-large sample sizes or for some values of the shape parameters. See for example Carnahan (1989) [1].
Wang (2005) [2] discusses a Bayesian approach, using a particular form of prior to regularize the problem.
McGarvey et al (2002) [3], discuss the poor performance even of Carnahan's suggested approach in small samples (n<80) and propose a heuristic they say has better performance.
[1] Carnahan J.V. (1989),
"Maximum Likelihood Estimation for the 4-Parameter Beta Distribution",  Communications in Statistics - Simulation and Computation, 18(2), 513-536
[2] Wang J. Z. (2005),
"A Note on Estimation in the Four-Parameter Beta Distribution",
Communications in Statistics - Simulation and Computation, 34(3), 495-501
[3] McGarvey, del Castillo, Cavalier & Lehtihet (2002),
"Four-parameter beta distribution estimation and skewness test,"
Quality and Reliability Engineering International, 18, 395–402


Post to django rest framework

Question: I'd like to post to my Django server using post so I can add a todo item. Here is the model:
class Todo(models.Model):
    title = models.CharField(max_length=200);
    text = models.TextField()
    completed = models.BooleanField(default=False)
    created_at = models.DateTimeField(default=datetime.now, blank = True )
    def __str__(self):
        return self.title

And serializers:
class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Todo
        fields = ("id", 'title','text', 'completed', 'created_at')

And view:
class TodoList(APIView):
    def get(self,request):
        todo=Todo.objects.all()
        serializer=TodoSerializer(todo,many=True)
        return Response(serializer.data)
    def post(self,request):
        Todo.objects.create(
            title=request.POST.get('title'),
            text=request.POST.get('text'))
        return HttpResponse(status=201)

My post request is
{ "title": "new title",
  "text": "a test text"}

And it told me
IntegrityError at /todos/
(1048, "Column 'title' cannot be null")

As a newbie at Django, I don't understand this error. Any ideas?
Comment: Instead of creating like this, You can always use serializers for the same.
Answer: You need to access request.data instead of request.POST,
def post(self,request):
    serializer = TodoSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Answer: Since you've asked about other methods besides post in the comments, I'll show an example of a ModelViewSet that will allow you to post to add a Todo, as well as provide support for retrieving, updating, and deleting your Todo's.
Recommended reading:
http://www.django-rest-framework.org/api-guide/viewsets/#modelviewset
from rest_framework.viewsets import ModelViewSet
from todo.models import Todo
from todo.serializers import TodoSerializer

class TodoViewSet(ModelViewSet):
    queryset = Todo.objects.all()
    serializer_class = TodoSerializer

The ModelViewSet class will provide you with a default implementation of view methods to list, create, retrieve, update (whole or partial update), and delete Todo's.  These actions are mapped to certain methods for different urls, get is mapped to list and retrieve, post is mapped to create, put and patch are mapped to update and partial_update, and delete is mapped to destroy.
Then in your urls.py, include the TodoViewSet using TodoViewSet.as_view(...):
from django.conf.urls import url
from todo.views import TodoViewSet

urlpatterns = [
    url(
        r'^todos/$',
        TodoViewSet.as_view({'get': 'list', 'post': 'create'}),
        name='todo-list',
    ),
    url(
        r'^todos/(?P<pk>\d+)/$',
        TodoViewSet.as_view({'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'}),
        name='todo-detail',
    )
]

Here we are explicitly stating the mapping of request methods to view actions that I mentioned before.
Comment: Thanks for your help. And what is (?p\d+) matching in the urls.py?
Comment: (?P\d+) is a regex placeholder to capture the Todo objects Primary Key in the url and lookup the object, which in this case should be an integer.  You can customize what field the view expects from the url and which field on the model it uses to lookup.  http://www.django-rest-framework.org/api-guide/generic-views/#genericapiview
Answer: Instead of creating like this, You can always use serializers for the same
data_serializer = TodoSerializer(data=request.data)
if data_Serializer.is_valid():
    data_Serializer.save()

Comment: Thanks this works well, can you please also show me how this can work with PUT and DELETE request?
Answer: for put request :
todo_item = Todo.objects.get(id=id) // Need to get that element
data_serializer = TodoSerializer(instance=todo_item,data=request.data, partial=True)
if data_Serializer.is_valid():
   data_Serializer.save()
else:
   print  data_Serializer.errors

for delete:
todo_item = Todo.objects.get(id=id) // Need to get that element
todo_item.delete()

Post to django rest framework


integration of $\int_0^{2\pi} cos^{2n}(t)dt$

Question: Show that for any $n \in \mathbb{N}$,
$$\frac{1}{2\pi}\int_0^{2\pi}\cos^{2n}(t)dt = \frac{1 \cdot 3 \cdot 5 \cdots(2n-1)}{2 \cdot 4 \cdot 6 \cdots 2n}$$
To solve this problem, I was thinking that I would let $\cos(t)= \frac{e^{it} + e^{-it}}{2}$, then the integral will have the form:
$$\frac{1}{2\pi}\int_0^{2\pi} \left (\frac{e^{it} + e^{-it}}{2} \right)^{2n}dt$$
From this point, I was stuck. So, would anyone please help me to walk through this problem.
Comment: Bad idea. A recursive formula linking your integrals for $n$ and $n-1$ is the usual approach. Also, check `Wallis integrals` in a search engine.
Comment: I disagree. This is actually a decent approach, as demanstrated by the simplicity of the answer.
Comment: Have you tried induction?
Comment: You can express it by Beta-function
Comment: Variants of this have appeared many times.  Here's a related problem: http://math.stackexchange.com/questions/1336903/definite-integral-of-even-powers-of-cosine
Comment: @Chanler You are right, I missed that, the integral being on (0,2pi), nearly every term in the binomial expansion disappears.
Comment: See http://math.stackexchange.com/questions/193435/prove-int-cosn-x-dx-frac1n-cosn-1x-sin-x-fracn-1n-int-cos
Comment: Expand the power.
Answer: You were heading in the correct direction.  Using the binomial theorem and the orthogonality of the basis functions $e^{imx}$ on $[0,2\pi]$, we have
$$\begin{align}
\frac{1}{2\pi}\int_0^{2\pi}\cos^{2n}x\,dx&=\frac{1}{2\pi}\int_0^{2\pi}\left(\frac{e^{ix}+e^{-ix}}{2}\right)^{2n}\,dx\tag 1\\\\
&=\frac{1}{2\pi}\frac{1}{2^{2n}}\,\sum_{k=0}^{2n}\binom{2n}{k}\int_0^{2\pi}e^{i(2k-2n)x}\,dx \tag 2\\\\
&=\frac{1}{2^{2n}}\binom{2n}{n}\tag 3\\\\
&=\frac{1\cdot 2\cdot 3\cdot 4 \cdots (2n-3)(2n-2)(2n-1)(2n)}{(2\cdot 4\cdot 6\cdots (2n-2)(2n))^2}\\\\
&=\frac{1\cdot 2\cdot 3\cdots (2n-1)}{2\cdot 4\cdot 6\cdots (2n-2)(2n)}\\\\
&=\frac{(2n-1)!!}{(2n)!!}
\end{align}$$
as was to be shown!
In arriving at $(1)$ we used Euler's Identity $\cos x = \frac{e^{ix}+e^{-ix}}{2}$
In going from $(1)$ to $(2)$, we used the binomial expansion $(x+y)^n=\sum_{k=0}^{n}\binom{n}{k}x^ky^{n-k}$ with $n\to 2n$, $x\to e^{ix}$, and $y\to e^{-ix}$.
In going from $(2)$ to $(3)$, we used the fact that $\int_0^{2\pi}e^{i(2k-2n)}\,dx=0$ for $k\ne n$ and $\int_0^{2\pi}e^{i(2k-2n)}\,dx=2\pi$ for $k=n$.
Answer: you can see that for $k \in \mathbb{Z}$ the integral of $e^{ikt}$ on $[0,2\pi]$ is zero unless $k=0$.
so from a binomial expansion of your integrand we obtain $\binom{2n}{n}2^{-2n}$
a little manipulation with the resulting fraction will give your result.
Answer: This should be a direct consequence of
$$
\cos^{2n}(x)
= \frac{1}{2^{2n}} \left[
\binom{2n}{n} + \sum\limits_{k=0}^{n-1} 2 \binom{2n}{k} \cos((2n-2k)x)
\right],
$$
which can be shown via induction and the equation
$$
\cos(\alpha)\cos(\beta)
= \frac{1}{2}\left[
\cos(\alpha-\beta) + \cos(\alpha+\beta)
\right].
$$
Answer: In arriving at  we used Euler's identity
Because here you have cos in 2 dimensional function but that identity stands for cosh which is in three dimensional I must suggest you to open the cos(power) 2n , which is equal to (1+ cos (2n))/2n and you will arrive on your answer
Answer: For $\gamma:[0,2 \pi] \rightarrow \mathbb{C}, \gamma(t):=\mathrm{e}^{\mathrm{i} t}$ and $f \in C\left(\partial U_{1}(0)\right)$ there is this nice equality
$$
\int_{0}^{2 \pi} f\left(\mathrm{e}^{\mathrm{i} t}\right) d t=\int_{\gamma} \frac{f(z)}{\mathrm{i} z} d z
$$
wich makes the computation after writing $\cos^{2n}(x)$ in terms of exponential functions much easier.
$
f(z)
$
becomes
$$
f(z) = \left(z+\frac{1}{z}\right)^{2n} = \frac{(z^2+1)^{2n}}{z^{2n}}
$$
Continuing from here with the binomial theorem is a little bit easier to see (it was for me atleast) and you then get your result with the Residue theorem.
Comment: can you please continue with your answer? I don't understand how you use the $f(z)=\left(z+\frac{1}{z}\right)^{2n}= \frac{\left( z^{2}+1 \right) ^{2n} }{z^{2n}}$


Calculate $\lim\limits_{(x,y)\to (0,0)} \dfrac{x^4}{(x^2+y^4)\sqrt{x^2+y^2}}$

Question: Calculate, $$\lim\limits_{(x,y)\to (0,0)} \dfrac{x^4}{(x^2+y^4)\sqrt{x^2+y^2}},$$ if there exist.
My attempt:
I have tried several paths, for instance: $x=0$, $y=0$, $y=x^m$. In all the cases I got that the limit is $0$. But I couldn't figure out how to prove it. Any suggestion?
Answer: Use $$0\leq  \dfrac{x^4}{(x^2+y^4)\sqrt{x^2+y^2}}\leq|x|.$$
Comment: Thank you very much, sir!
Comment: @Gerschgorin   You are welcome!
Answer: Assuming $y<1$ and using polar coordinates we have
$$\dfrac{x^4}{(x^2+y^4)\sqrt{x^2+y^2}} \le \dfrac{x^4}{(x^2+y^2)\sqrt{x^2+y^2}} =r \sin^4\theta \to 0$$


How can I receive the JSON by using setRequestMethod("GET")?

Question: I want to receive a JSON from server. So I used setRequestMethod("GET").
I already modified my code some times, but It doesn't work still now.
package com.example.myapplication;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

//"http://ec2-15-164-98-71.ap-northeast-2.compute.amazonaws.com:8888/code/list"

public class MainActivity extends AppCompatActivity {

    TextView tvData;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvData = findViewById(R.id.textView);
        btn = findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new JSONTask().execute();
            }
        });

    }

    public class JSONTask extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... urls) {
            URL url = null;
            try {
                //JSONObject를 만들고 key value 형식으로 값을 저장해준다.
                url = new URL("http://ec2-15-164-98-71.ap-northeast-2.compute.amazonaws.com:8888/code/list");
                JSONObject jsonObject = new JSONObject();
                //jsonObject.accumulate("user_id", "androidTest");
                //jsonObject.accumulate("name", "yun");

                HttpURLConnection con = null;
                BufferedReader reader = null;

                try{
                    con = (HttpURLConnection) url.openConnection();

                    con.setRequestMethod("GET");
                    con.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.146 Whale/22.214.171.124 Safari/537.36");
                    con.setRequestProperty("Accept", "application/json");

                    con.setConnectTimeout(3000);
                    con.setReadTimeout(3000);

                    con.setDoOutput(true);//Outstream으로 post 데이터를 넘겨주겠다는 의미
                    con.setDoInput(true);//Inputstream으로 서버로부터 응답을 받겠다는 의미
                    con.connect();

                    System.out.println(con.getResponseCode());
                    System.out.println(con.getResponseMessage());
                    //서버로 보내기위해서 스트림 만듬
                    OutputStream outStream = con.getOutputStream();
                    //버퍼를 생성하고 넣음
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outStream));
                    writer.write(jsonObject.toString());
                    writer.flush();
                    writer.close();//버퍼를 받아줌

                    //서버로 부터 데이터를 받음
                    InputStream stream = con.getInputStream();

                    reader = new BufferedReader(new InputStreamReader(stream));

                    StringBuffer buffer = new StringBuffer();

                    String line = "";
                    while((line = reader.readLine()) != null){
                        buffer.append(line);
                    }

                    return buffer.toString();//서버로 부터 받은 값을 리턴해줌 아마 OK!!가 들어올것임

                } catch (MalformedURLException e){
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if(con != null){
                        con.disconnect();
                    }
                    try {
                        if(reader != null){
                            reader.close();//버퍼를 닫아줌
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            tvData.setText(result);//서버로 부터 받은 값을 출력해주는 부
        }
    }
}

Here's a logcat. 403 is a value of getResponseCode(), and Forbidden is getResponseMessage()'s result.
Some people said "(HTTPLog)-Static: isSBSettingEnabled false" problem can resolve by asyncTask. But I already used asyncTask in my code.
2020-02-17 16:00:12.480 9517-10273/? I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
2020-02-17 16:00:12.559 9517-10273/? I/System.out: 403
2020-02-17 16:00:12.560 9517-10273/? I/System.out: Forbidden

Answer: Instead of getOutputStream(), You need to use getInputStream() since you read input from connection.
PS. Don't know why you still use URLConnection. I reccommends you to use OKHttp Connection. It's much easier than this.
Comment: Oh thank you so much! I just know URLConnection in the past. I used OKHttp on your recommendation, and I resolved the problem:)


Karma tests are not loading AngularJS factory

Question: I have integrated karma with my existing project and I struggle to figure out why karma tests do not load the MathService factory (math.js).
Folder structure
/tests
/www
+ /js
   + app.js
   + /controllers
   + /services
      + math.js
+ /lib

math.test.js
describe('MathService Spec', function() {

    var OfficerValidationService;

    beforeEach(function() {
      angular.module('starter');
    });

    beforeEach(inject(function() {
      var $injector = angular.injector(['starter']);
      OfficerValidationService = $injector.get('MathService');
    }));

    it('is very true', function(){
      //var output = OfficerValidationService.something();
      expect(OfficerValidationService).toBeTruthy();
    });

  });

app.js module is defined as
var app = angular.module('starter', ['ionic', 'ngCordova', 'pascalprecht.translate', 'textAngular', 'jett.ionic.content.banner', 'barcodeListener'])
  .constant('ENV', {
    mode: 'prod'
  })
  .run(function ($ionicPlatform, $rootScope, $translate,
    $timeout, $localstorage, $ionicHistory, $location, DatabaseService, ModeService, ArrowsysService) { /* code */ })

MathService
app.factory('MathService', function () {
    return {
        roundNumber: function(toRound){
            if (toRound == 1) {
                return 1;
            } else {
                return 2;
            }
        }
    },
    function roundNumber(toRound) {
        if (toRound == 1) {
            return 1;
        } else {
            return 2;
        }
    }
});

karma.conf.js
files: [
  'https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js',
  'https://cdnjs.cloudflare.com/ajax/libs/angular-mocks/1.6.8/angular-mocks.js',
  'www/js/app.js',
  'www/js/services/math.js',
  'tests/*.test.js'
],

And the results saying MathService is undefined.
Chrome 63.0.3239 (Windows 10 0.0.0) MathService Spec is very true FAILED
        Error: [$injector:modulerr] http://errors.angularjs.org/1.6.7/$injector/modulerr?p0=starter&p1=Error%3A%20%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.6.7%2F%24injector%2Fmodulerr%3Fp0%3Dionic%26p1%3DError%253A%2520%255B%2524injector%253Anomod%255D%2520http%253A%252F%252Ferrors.angularjs.org%252F1.6.7%252F%2524injector%252Fnomod%253Fp0%253Dionic%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.7%252Fangular.min.js%253A7%253A76%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.7%252Fangular.min.js%253A26%253A408%250A%2520%2520%2520%2520at%2520b%2520(https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.7%252Fangular.min.js%253A25%253A439)%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.7%252Fangular.min.js%253A26%253A182%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.7%252Fangular.min.js%253A42%253A332%250A%2520%2520%2520%2520at%2520p%2520(https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.7%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.7%252Fangular.min.js%253A42%253A180)%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.7%252Fangular.min.js%253A42%253A364%250A%2520%2520%2520%2520at%2520p%2520(https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.7%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.7%252Fangular.min.js%253A42%253A180)%0A%20%20%20%20at%20https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.7%2Fangular.min.js%3A7%3A76%0A%20%20%20%20at%20https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.7%2Fangular.min.js%3A43%3A99%0A%20%20%20%20at%20p%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.7%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.7%2Fangular.min.js%3A42%3A180)%0A%20%20%20%20at%20https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.7%2Fangular.min.js%3A42%3A364%0A%20%20%20%20at%20p%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.7%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.7%2Fangular.min.js%3A42%3A180)%0A%20%20%20%20at%20Object.hb%20%5Bas%20injector%5D%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.7%2Fangular.min.js%3A46%3A250)%0A%20%20%20%20at%20UserContext.%3Canonymous%3E%20(http%3A%2F%2Flocalhost%3A9876%2Fbase%2Ftests%2Fmath.test.js%3Ff11444440ebffa5d88f933a1339ba01072b896ce%3A10%3A31)%0A%20%20%20%20at%20Object.invoke%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.7%2Fangular.min.js%3A44%3A390)
            at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js:7:76
            at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js:43:99
            at p (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js:8:7)
            at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js:42:180)
            at Object.hb [as injector] (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js:46:250)
            at UserContext.<anonymous> (tests/math.test.js:10:31)
            at Object.invoke (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js:44:390)ngularjs/1.6.7/angular.min.js:44:390)                                libs/angular-mocks/1.6.8/angular-mocks.js:3183:20)            at UserContext.WorkFn (https://cdnjs.cloudflare.com/ajax/libs/angular-mocks/1.6.8/angular-mocks.js:3183:20)                   flare.com/ajax/libs/angular-mocks/1.6.8/angular-mocks.js:3146:25)        Error: Declaration Location            at window.inject.angular.mock.inject (https://cdnjs.cloudflare.com/ajax/libs/angular-mocks/1.6.8/angular-mocks.js:3146:25)
            at Suite.<anonymous> (tests/math.test.js:9:16)
            at tests/math.test.js:1:1                                 (0.009 secs / 0 secs)
 Expected undefined to be truthy.            at UserContext.<anonymous> (tests/math.test.js:16:40)Chrome 63.0.3239 (Windows 10 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.009 secs / 0 secs)Terminate batch job (Y/N)?

Comment: Do you follow any guide? i.e. https://docs.angularjs.org/guide/unit-testing ? I guess way you get injector is just wrong.
Comment: @PetrAveryanov Hi. I followed this guide http://www.bradoncode.com/blog/2015/05/19/karma-angularjs-testing/ but implemented it to existing project.
Comment: Why the you write angular.module('starter'); instead of module('starter'), and angular.injector instead of _$injector_ as in that guide?
Comment: @PetrAveryanov I tried also without 'angular' but in both cases module and injector were defined in both cases. '$injector' without definition gives me undefined.
Answer: 1) You should use module function provided by angular-mocks and not angular.module, so all the tests will run in the scope of your module so injector will have proper info about the declarations and dependencies;
2) You can pass $injector service as one of the arguments in inject() method callback or something like var $injector = angular.injector();, but not the way you are doing it;
3) Better to declare own module for your MathService, since to run the tests in scope of starter module, you will have to provide / mock all the dependencies and I don't think your MathService should depend on ionic or ngCordova.
Taking the points above, here is a working example of how the service could be tested in your case:

angular.module('starter', ['ionic', 'ngCordova', 'pascalprecht.translate', 'textAngular', 'jett.ionic.content.banner', 'barcodeListener', 'starter.services'])
    .constant('ENV', {
        mode: 'prod'
    })
    .run(function ($ionicPlatform, $rootScope, $translate,
                   $timeout, $localstorage, $ionicHistory, $location, DatabaseService, ModeService, ArrowsysService, MathService) {
        /* code */
    });

angular.module('starter.services', [])
    .factory('MathService', function () {

        function roundNumber(toRound) {
            if (toRound === 1) {
                return 1;
            } else {
                return 2;
            }
        }

        return {
            roundNumber: roundNumber
        }

    });

describe('MathService Spec', function () {

    var MathService;

    beforeEach(module('starter.services'));

    beforeEach(inject(function ($injector) {
        MathService = $injector.get('MathService');
    }));

    it('is very true', function () {
        expect(MathService).toBeTruthy();
    });

    it('roundNumber test', function () {
        expect(MathService.roundNumber(1)).toBe(1);
        expect(MathService.roundNumber(10)).toBe(2);
    });

});
.as-console-wrapper {
  height:0;
}
<!DOCTYPE html>

    <link href="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.8.0/jasmine.css" rel="stylesheet" />

P.S.: As mentioned by @Petr Averyanov, going through https://docs.angularjs.org/guide/unit-testing will be a good starting point for you to get more familiar with AngularJS unit-testing.


Lowest-dimensional faithful representations of compact Lie groups

Question: Consider a compact Lie group $G$ of dimension strictly greater than 0. There is a theorem saying that $G$ admits a finite-dimensional faithful representation. Therefore, we can pick one of lowest dimension. Question:
is a lowest-dimension faithful representation of $G$ always irreducible?
If not, what is a counterexample and are there some conditions we can add (like $G$ to be simple for instance) that can make the statement become true?
At page 20, Section 3.6 of the file you can find at
https://ir.canterbury.ac.nz/bitstream/handle/10092/5943/joyce_thesis.pdf?sequence=1
the author says:
"For simple and semi-simple groups the primitive (i.e. lowest-dimension faithful) representations are irreducible"
but he doesn't explain nor give any reference.
On the other side, at
https://mathoverflow.net/questions/328138/non-faithful-irreducible-representations-of-simple-lie-groups?rq=1
they speak about irreducible representations of Lie algebras that induce non-faithful ones at the group level, and at a certain point they claim that the Lie groups $D_{2l}$ ($l\geq 2$) have the property that all irreducible representations are non-faithful, the center of these groups being non-cyclic. If so, is then the first source I have mentioned in the first link wrong or am I missing something about what these guys are doing in this last link?
Comment: If $G$ is simple, decompose a primitive representation in irreducible subrepresentations : one of them is nontrivial irreducible, so it is faithful by simplicity; by minimality it must be the whole represnetation.
Comment: @Max: thank you for the idea. I have a question on this process, that maybe relies on the definition of simple Lie group. Say we define $G$ to be a simple Lie group when it is connected, non-Abelian and it has no connected closed normal subgroups. Therefore any normal subgroup of $G$ is discrete, since the identity component is trivial by simplicity of $G$. Hence we know that the kernel of an irreducible representation of $G$ (being closed and normal) is discrete: is it also connected so to actually conclude that the considered irrep is faithful as you are saying?
Comment: I am saying that for $D_{\text{even}}$ all irreducible representations are non-faithful. This implies (and in classical logic is equivalent) that any faithful representation is reducible. Therefore, it doesn't exist a faithful irreducible representation, contradicting the claim in the first source I mentioned.
Comment: There's a logical glitch in your last paragraph. Earlier, you are asking whether certain faithful representations are necessarily irreducible. The fact that many irreducible representations are not faithful can never contradict that.
Comment: @TorstenSchoeneberg: yes sorry. I re-edited the last paragraph. Is it now clear?
Comment: Ah ! I was using the definition of simple groups from "non-Lie" group theory. A priori it is not clear (to me - I'm not an expert at all) that the kernel is connected.
Comment: No, it still mixes up the implications. Even if a certain type has no faithful representation at all, that does not contradict the statement that "all faithful rep's of least dimension are irreducible". It's just an empty statement for the simply connected (!) groups of type $D_{even}$, they have no faithful rep's. So what? Of course they still have tons of ("other") irreducible ones.
Comment: You're right, sorry; I was under the impression that those groups have *no faithful representations at all* (irreducible or not), in which case there would be no contradiction; but they do. I now believe that the first source is wrong in that case, a first counterexample would be a minimal faithful rep of $Spin(8)$, which is probably a sum of two distinct half-spin irreps mentioned here: https://math.stackexchange.com/a/3296484/96384
Answer: You definitely want some sort of simplicity condition: Consider $G =S^1 \times S^1$. It is abelian so any irreducible representation is one dimensional, but none of the one dimensional representations are faithful.


Coloring of overlaping graphs

Question: Let G1, G2, G3 be three (possibly overlapping) graphs on the same vertex set, and suppose that G1 can be properly colored with 2 colors, G2 can be properly colored with 3 colors, and G3 can be properly colored with 4 colors. Let G be the graph on the same vertex set, formed by taking the union of the edges appearing in G1, G2, G3. Prove that G can be properly colored with 24 colors.
Comment: Hint: $2\times3\times4=24.$
Answer: Let $A$ be the set of two colors for $G_1$, $B$ the set of colors for $G_2$, and $C$ the set of colors for $G_3$.
For $G$, we consider the set of colors $$A \times B \times C = \{(a, b, c) \mid a \in A, b \in B, c\in C\}.$$
Notice that $|A \times B \times C| = |A||B||C| = (2)(3)(4) = 24$ so it contains $24$ colors.
Now, for a vertex $v_0$ in $G$, we give it the color $(a_0, b_0, c_0)$ where $a_0$ is the color of $v_0$ in $G_1$, $b_0$ is the color of $v_0$ in $G_2$, and $c_0$ is the color of $v_0$ in $G_3$.
Now consider two vertices $v_1$ and $v_2$ that share an edge in $G$ with colors $(a_1, b_1, c_1)$ and $(a_2, b_2, c_2)$ respectively. Since $G$ is the union of edges in $G_1, G_2, G_3$, then that must be mean $v_1$ and $v_2$ share an edge in at least one of the $G_i$'s. Without loss of generality, suppose they share an edge in $G_1$. Since $G_1$ is properly colored, $v_1$ and $v_2$ have different colors in $G_1$, thus $a_1 \neq a_2$ and thus $(a_1, b_1, c_1) \neq (a_2, b_2, c_2)$ so $v_1$ and $v_2$ have different colors in $G$.
Answer: Hint. A proper coloring of a graph may be regarded as an equivalence relation on the vertex set, where the equivalence classes are independent sets; the number of colors is the number of equivalence classes. The intersection of those three equivalence relations is an equivalence relation, with (at most) how many equivalence classes?

Coloring of overlaping graphs


"The instance of entity type 'User' cannot be tracked because another instance with the key value '{x}' is already being tracked with UserManager

Question: I'm having a tracking issue when using the UserManager class. I want to update user data with roles.
var result = await _userManager.UpdateAsync(dest);

The code I wrote above gives me an error
error is
The instance of entity type 'User' cannot be tracked because another instance with the key value '{Id: 432d2e6c-387e-4238-8ad8-2ef6dc41ba2e}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

my command class is
namespace SharedNote.Application.CQRS.Commands
{
    public class UpdateUserRoleCommand :  IRequest<IDataResponse<UserDto>>
    {
        public string Id { get; set; }
        public string UserName { get; set; }
        public string Email { get; set; }
        public string Role { get; set; }
        public class UpdateUserRoleCommandHandler : IRequestHandler<UpdateUserRoleCommand, IDataResponse<UserDto>>
        {
            private readonly IMapper _mapper;
            private readonly UserManager<User> _userManager;

            public UpdateUserRoleCommandHandler(IMapper mapper, UserManager<User> userManager)
            {
                _mapper = mapper;
                _userManager = userManager;
            }
            public async Task<IDataResponse<UserDto>> Handle(UpdateUserRoleCommand request, CancellationToken cancellationToken)
            {
                var user = _userManager.Users.AsNoTracking().SingleOrDefault(p => p.Id == request.Id);
                if (user == null) return new ErrorDataResponse<UserDto>(null, "", 404);

                var dest = _mapper.Map<User>(request);
                dest.UpdateDate = DateTime.Now;
                var result = await _userManager.UpdateAsync(dest);

                if (!result.Succeeded) return new ErrorDataResponse<UserDto>(null, "", 400);
                var roles = await _userManager.GetRolesAsync(user);
                if (roles[0] != request.Role)
                {
                    await _userManager.RemoveFromRolesAsync(user, roles);
                    await _userManager.AddToRoleAsync(user, request.Role);
                }
                return new SuccessDataResponse<UserDto>(null, "", 200);

            }
        }
    }
}

Comment: Welcome to Stack Overflow.
Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question.
Then [edit] your question to include your source code as a working [mcve], which can be compiled and tested by others.
Answer: try this code, you shouldn create a new instance and try to update existing. You have to update existing user using Mapper or manually
Mapper.Map<UpdateUserRoleCommand,User>(dest, user);
var result = await _userManager.UpdateAsync(user);

Comment: Mapper.Map(dest, user);  ı added same code after                 dest.UpdateDate = DateTime.Now;  but it gives error
Comment: @notcontrol  I don't know how your mapper is configured, I never use mappers. Maybe it is better to do it manually,  but you should update user object that you get from context, not dest that was created.
Answer: Attach the user to your context and it will work
_context.Attach(user);
var result = await _userManager.UpdateAsync(user);


How to replace a mass old urls to new urls in blogspot with javascript

Question: I'm a user of blogger. And my blog have very much url links image and video from others site (their allow embed their links). And now their has change the domain so all old url links no longer works.
Now I need a script can replace all them, because my blog have too much posts (2000+ posts), I cant replace all them with manual edit.
So everyone can help me do a script to fix this?
The old URL is format is: 123456.com/abc
I want replace it to new url format is: 67890.com/abc
I really glad when everyone can help me, thanks and sorry my suck english.
A script can replace the old urlto new url in blogspot
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: The code selects all img and video elements on the page, replaces the url from "123456.com" to "67890.com" in each element's src attribute.

var elements = document.querySelectorAll('img, video');
elements.forEach(element => {
  var src = element.src;
  src = src.replace('123456.com', '67890.com');
  element.src = src;
});

<video src="123456.com/1"></video>
<video src="123456.com/2"></video>
<video src="123456.com/3"></video>
Comment: OMG, it really working, Thank you so much!! ^^ You really save me, sir. Thank you!


Closed set in metric space

Question: In $C\left( {\left[ {0,1} \right]} \right)$, we define metric
$$d\left( {f,g} \right) = \mathop {\max }\limits_{t \in \left[ {0,1} \right]} t\left| {f\left( t \right) - g\left( t \right)} \right|.$$
We define $A = \left\{ {f \in C\left( {\left[ {0,1} \right]} \right):f\left( 0 \right) = f\left( 1 \right)} \right\}$. Is $A$ an open or closed set in $C\left( {\left[ {0,1} \right]} \right)$ with metric $d$??
Comment: @SaucyO'Path: it's certainly not the case that every set must be either open or closed.
Comment: Yes, it is definitely either open or closed.
Comment: @SaucyO'Path: This claim is more than wrong. Subspaces are open if and only if they equal the entire space!
Comment: Hint: considering $f(t)=0$ and $g(x) = \epsilon t$ should enable you to answer one of your questions.
Comment: @GregMartin I agree, and it's all the more the case for vector subspaces, since vector subspaces are open only if they are closed.
Comment: @gerw Where are you negating the fact that they are open only if they are closed?
Comment: @SaucyO'Path: Because this "fact" is plainly wrong! Do you have a good reason to believe that subspaces are open iff they are closed?
Comment: "only if" is not the same as "if and only if". @gerw
Comment: If a subspace is open, then it is closed.  Some people were confused by "only if".
Comment: @SaucyO'Path: Oh, I always read "if and only if". Sorry for the noise.
Answer: $A$ is not open
Consider the sequence $(f_n)$ defined by
$$f_n(x)=\begin{cases}
1 -nx & 0 \le x \le 1/n\\
0 & 1/n \le x \le 1
\end{cases}$$
It is a sequence of continuous functions. You'll verify that $d(f_n,0) = 1/4n \to 0$, $0 \in A$ and $f_n \notin A$ for all $n \in \mathbb N$. Therefore $A$ can't be open.
$A$ is not closed in $\mathcal C([0,1])$
Consider the sequence:
$$g_n(x)=\begin{cases}
1 -nx & 0 \le x \le 1/n\\
\frac{n}{n-1}\left(x-\frac{1}{n}\right) & 1/n \le x \le 1
\end{cases}$$
of elements of $A$. It converges in $\mathcal C([0,1])$ to the identity map $i$ which does not belong to $A$. Hence $A$ is not close.
Comment: If $A$ would be open, as $0 \in A$, there would be an open ball centered on $0$ and included in $A$. This can't be as $f_n \notin A$ for all $n \in \mathbb N$.
Comment: I would appreciate explaining one aspect connected with the reason why the set $A$ is not open. I understand every step, but the idea isn't clear for me. We have shown that $f_n$ (which are not in the set $A$) converges to $0$ in our metric and its limit belongs to $A$. Intuitively it shouldn't be possible of course, but my main question is: how is this associated with checking if $A$ is an open set? I can't see here relationship with a definition of open set. Thanks in advance.
Comment: Yes, of course. Now everything is clear for me. Thanks a lot!
Comment: The part on the closedness of $A$ is not correct. The question asks if $A$ is a closed subset of the continuous functions, so giving a sequence that converges to a non-continuous function cannot answer that.
Comment: @MaoWao You're right and $A$ is in fact closed in $\mathcal C([0,1])$. Response updated.
Comment: But does convergence with respect to $d$ imply convergence at $0$? With the factor $t$ in the definition of $d$, this seems at least not clear.
Comment: Not good to come back after two years and two quickly on an answer. My initial answer is correct as the identity map is continuous. Your initial comment is wrong.
Comment: The initial version was correct, but then you somehow changed it to "converging to a non-continuous map". Anyway, everything is back to the correct version now, so that's fine.

Closed set in metric space


Validating UserControl's control by Window's ViewModel

Question: Suppose, I have created custom LoginForm as an UserControl, which consists of TextBox and PasswordBox. TextBox has installed custom ErrorTemplate. Naturally, I would like to have this LoginForm as reusable as can, therefore I want to separate validation logic from this LoginForm.
The problem is, that if I bind LoginForm's text property to the "validation-property" of the ViewModel : IDataErrorInfo, that is set as Window's DataContext, the ErrorTemplate is not being applied to LoginForm's TextBox even if I see debug logs from ViewModel's validator.
How can I validate child controls of reusable component via independent ViewModel?
Answer: After hours of struggling how to solve this, I came up with following solution which satisfies my requirements and so MVVM pattern:

Create in UserControl a DepdendencyProperty of type IDataErrorInfo which will be later implemented by your ViewModel (for my purposes, I used ISignUpValidator:IDataErrorInfo with UsernameValue property).
Lets say this property is registered under the name Validator (as default value I used "do-nothing" implementation of my interface).
Bind UserControl's TextBox.Text property to Validator property:
Lets say TextBox.Text property is exposed to UserControl under the name
Username:
Username="{Binding Path=Validator.UsernameValue, ElementName=UserControlName,
                                                 UpdateSourceTrigger=PropertyChanged,
                                                 ValidatesOnDataErrors=True}"

Finally Bind your Viewmodel to your UserControl's Validator property
<Window.Resources>
    <local:ViewModel x:Key="ViewModel"/>
<Window.Resources>

<local:LoginForm Validator={StaticResource ViewModel}>

Or alternatively, if your ViewModel is already set as Window's DataContext:
<local:LoginForm Validator="{Binding DataContext, ElementName=WindowName}"}>

Answer: use this error template in application resource:

</Style>

Comment: Hi, I have already one custom ErrorTemplate that works on textbox if i perform validation on control level. My problem is, that i would like to move validation on higher level. It seems, that usercontrol's child control is not aware of it's parent's error. I'm searching for some solution how to accomplish this.


Loop through vector with Iterator vs. [] before C++11

Question: Which of the following method is better?
<code>vector<int> vecInts;
// initialize vecInts;
// method ONE
for( vector<int>::size_type szInd = 0; szInd < vecInts.size(); ++szInd )
{
  // process vecInts[szInd]
}

// method TWO
for( vector<int>::iterator iter = vecInts.begin(); iter != vecInts.end(); ++iter )
{
  // process *iter
}
</code>
During code review, I am always suggested by one person that I should replace the method one with iterator version and I argue that it doesn't matter. Am I right?
Thank you
Comment: It's a question of style.  I would be surprised if there were still compilers generating different code for the two loops.
Comment: There is a bigger problem than index vs iterator: the `size()` and `end()` are evaluated in each iteration. If the size of the vector is not changed, then they should be moved out of the loop
Comment: @Articuno That would depend on the implementation. But if the compiler is not sure if the size of the container would be changed during the loop, it has to evaluate it in each iteration
Comment: @Articuno The last time I measured (but that was some time ago), moving the call to `end()` out of the loop did make a difference.  But only for very, very tight loops; it's not something you should worry about until the profiler tells you to.
Comment: @YZ.learner The compiler actually yields code that calls those methods each time through the loop?
Comment: See also: http://stackoverflow.com/questions/linked/131241?lq=1
Answer: Use the more general, iterator version:

It can produce the same machine code on optimized builds (subject to quality of implementation).
It's a more general idiom, not specific to vectors. It removes emphasis of the vector nature of the container and concentrates on the loopy nature of the loop.
You can swap the container type later and won't need to touch your loop code (assuming you use a few more typedefs).
In debug builds you may gain access to debug iterators that allow for easier debugging.

Update: James makes a good point - I'm only referring to "when you want to iterate over a range". By contrast, if the numeric value of the indices, and thus the vector nature of the vector, is relevant, then you may like to use indices (e.g. for numeric algorithms; matrices, graphs, permutations, etc.). As a meta guideline, use the style that corresponds to the appropriate abstraction.
Comment: And as for point 4: the debug builds will also do bounds checking with an iterator.
Comment: Point one is far from guaranteed.  One may produced better code with one compiler, the other with another.
Comment: @JamesKanze: If your compiler or library produce less-than-efficient iteration code in an optimized build, that should probably be a bug report... (I reworded it, though.)
Comment: Generally, given the typical implementation, I expect that if there is a difference, the iterator version is slightly faster.  A lot depends on what happens in the loop, though; in many cases, the compiler will not be able to generate the same code (because indexing uses a pointer in the vector, but the iterator has its own pointer).
Answer: It depends on context.  Using iterators is more idiomatic in
the general C++, which means that they should be preferred, but
if you need to iterate in parallel through several identically
sized vector, then using the index allows you to use one
variable instead of several.  And there are communities where
the index is more idiomatic: people versed in numerics seem to
prefer it, for example.  If you're working in such a community,
then you should also use it.  (But if you're receiving
suggestions in code review to favor iterators, that's probably
not the case.)
Comment: +1 for the numeric algorithm point.
Answer: The difference is that in method two, the iterator gets invalidated if an element is inserted before the iterator. In method one, you will look at the same element twice.
On the other hand, when an element is inserted after the current position, with method two the iterator could get invalidated because of a reallocation, but method one will still work.


Dereference Operator when using with argv[i]

Question: #include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    if (isdigit(*argv[1]))
    {
        int x = atoi(argv[1]);
        printf("%d\n", x);
    }
    return 0;
}

I don't get why asterisk sign need when using isdigit() and why asterisk sign is not needed when using atoi()
Comment: Read the [isdigit](https://linux.die.net/man/3/isdigit) and [atoi](https://linux.die.net/man/3/atoi) man pages. What are the types of the arguments to each?
Comment: FYI, `isdigit(*argv[1])` should be `isdigit((unsigned char) *argv[1])`, because the C standard does not guarantee that `isdigit` works for a `char` except for a base set of characters.
Answer: argv[1] is a string, and so *argv[1] is the first character in the string.  Same thing as argv[1][0].  Calling isdigit(*argv[1]) therefore checks if the first character in the string is a digit.
That test is being used to check if the argument is (probably) a number, after which the entire string is passed into atoi() to get the whole value.


Playing arpeggio on black notes with white note third

Question: I cannot figure out how I should play the left-hand arpeggio in beats 3-4 of this bar:

(Nuvole bianche Bar 54)
Currently I use this fingering for the first arpeggio:

But I have no idea how to play the second arpeggio. What fingering should I use to be able to perform this arpeggio at speed?
Comment: I'm not a great piano player, so I'll just comment that I think my personal take would be 5-1-3-1-3-1-5.
Comment: @ToddWilcox Thank you for your comment. I have tried similar fingerings (as well as the one you suggested), and although they may be the correct way to finger such an arpeggio I don't feel very confident that I can play them in this way especially quickly, however that may be due to my lack of piano prowess instead of the fingering. I'm really looking for an answer that shows "common practices" or an agreed upon "best way" to finger this type of arpeggio, and it may end up being your suggestion but until I see evidence of some consensus among musicians I will leave the question open.
Comment: The placement of piano keys in the second arpeggio is virtually identical to the first one, so why wouldn't you use the exact same fingering?
Answer: Your proposed 5 2 1 2 1 2 breaks the basic "rule" of scale and arpeggio fingering, which is your thumb always plays a white note - unless there are no white notes at all, of course.
Note: of course that rule doesn't apply to the right hand - the Eb Ab C is not really an arpeggio, it's just a 3-note chord, and there is no problem fingering it 5-1-3, 4-1-2, or something similar (4-1-2 might be appropriate if the top note of the preceding bar was higher than Eb).
So the LH "top notes" C and G should definitely be played with your thumb. The easiest way to play the rest is not to worry about trying to play the notes perfectly "legato" with your fingers. Press the sustain pedal as you play the first note of each chord (the low Ab and Eb). It's up to you whether you release the pedal as soon as it's no longer needed, keep it down for the whole of each half-bar, or something in between those extremes.
With the pedal, the fingering will be 5-x-y 1-y-x  5-x-y 1-y-x, where "x" and "y" depend on the size of your hand.
If your hands are very small, you might want to play 5-5-3 1-3-5  5-5-3 1-3-5, moving your hand and arm to play the consecutive notes with 5. That is a better way than trying to twist your hand about to play the notes legato with your fingers.
With an average adult-sized hand and reasonably flexible fingers, 5-3-2 1-2-3 5-3-2 1-2-3 would be good, again not trying to play the 5-3's and 3-5's legato but using the sustain pedal. In between those limits, experiment with 5-3/4-2/3 1-2/3-3/4 to find what suits you best.
Answer: While there is a "rule" that one shouldn't play black notes with the thumb, it isn't a hard-and-fast rule.  The hard-and-fast rule is that you should use whatever fingering most easily plays the music you're trying to play.  The reason that the scales (and all the arpeggios that don't have all black keys) never use the thumb on black keys is because there are always easier fingerings available.
In general, you should avoid passing the fingers and thumbs over one another in broken chord passages when possible, since (as alephzero also mentions) it's more awkward than stretching or even jumping a bit to make notes.
In a widely-spaced figure such as the one in the left hand, don't try too hard to connect all the notes.  As you have found, you can't without a lot of awkward reaching around, and that gets in the way of playing at any kind of fast tempo.  So, I simply finger them 532123 532123, and suggest that you try it as well.  You'll have to get proficient at jumping an octave between 3 and 5 as part of your technical repertoire anyway, so you might as well get started.  (If your hands are too small to reach a 4th with 23, then jump a little there as well.)
It's easy to get caught up in trying to work out fingerings that allow you to connect all the notes without using the pedal.  While this is a good idea up to a point, it can be taken too far, and obviously limits the things that you can play to things that you can reach in this manner.  (During my student years, I worked out some pretty tortuous fingerings to some of Bach's fugues with this ideal in mind, with decidedly mixed results.)  Also, as tempos get faster, legato becomes less of a goal.
For an advanced example of the fingering I'm suggesting, have a look at this, from the last movement of Beethoven's Sonata Op. 31 No. 3 (look at measure 239, right after the trill in the right hand):

This is to be played quite quickly (the tempo marking is presto con fuoco).  You can see that the suggested fingering at measure 239 is 532123.  You'll also notice that the fingering at measure 243 has the same suggestion, despite the leap of an entire octave.  I can tell you from personal experience that I tried (starting at measure 238) 532121 513231 first, and wasn't able to get it up to tempo.  So, I took the "leap of faith" (well, my teacher told me to, so I did it) and learned how to hit that Db octave using 353.  Once I had the distance down, it went a lot smoother.
Now, here is Daniel Barenboim playing the passage, and it's not too hard to see that he uses exactly this fingering (and makes it look very easy, of course, which it isn't).

Finally, lest you get the idea that such fingerings are reserved for people with Barenboim-sized hands, here's a young lady clearly using the same fingering.  In fact, if you go on a bit, you'll notice that she doesn't pass thumb under finger (or finger over thumb) at all in the entire passage:

So, you'll want to learn how to do this.  Your example piece is a good one to get started developing a good legato broken chord technique, connecting notes through proper use of the pedal.
Answer: Since the next set of arpeggios is basically a mirror of the previous set, I would suggest moving your hand down, and using the same fingering if you are comfortable with it.As in: 5 2 1 2 1 2 shift 5 2 1 2 1 2
Answer: As Kilian Foth states, the arpeggio is the same spacing as the Ab one earlier in the bar. If that fingering works, then the same fingering will work for the Eb arp. in the second half. Because they are arps, the sustain pedal will help the lower note, and also make the part sound better.
However, I'd spread my hand to play 5-3-2-1-2-3.
Answer: I have a big hand, so I wouldn't cross the thumb at all. Chopin is another good source for pedaling ideas. And he often didn't follow "the rules" regarding fingering and pedaling.


Create a 960px style with two solid bars that are 100% of page width?

Question: I am trying to create a wordpress style for a project site I am working on. I am an experience designer, but there is a concept that I can't figure out. I'd like to be able to have the width of the site set at 960px, but have two bars at the top. You can see what I mean in the picture below.
https://i.stack.imgur.com/pSShB.png
I really want to be able to use the blue bar as a menu system and keep all the content within the main 960px overall width. The logo image, needs to start at the very beginning of the content beginning(where the 960px starts). The image is just a mock up, but that's how I want my users to be able to see it. I want the whole site to be able to scale to look the same on any sized monitor.
I have been trying to come up with a solution to do this effectively all day, but haven't managed to think of anything.
Does anyone have an ideas for me? Something that'll work in all browsers?
Comment: A good start for solid CSS system is http://960.gs/
Answer: You would have to create a relative container, and inside of in absolute containers, something like this:

{logo goes here float it right or something}

{menu structure goes here, float left or something}

Your Style:
#header_struct{
 position: relative;
 width: 960px;
}
#green_area{
 position: absolute;
 right: 700px; // makes it start 260px in from the left side
 width: 1000px; // makes it go off the left side of the screen for instance
 background-color: green;
}
#blue_area {
 position: absolute;
 left: 260px; // makes it start 260px in from the left side
 width: 1000px; // makes it go off the left side of the screen for instance
 background-color: blue;
}

Basically you need nested abosolute positioning divs inside the relative container #header_struct. I haven't tested this, but I recall doing something similar. I hope that gets you started.
Here is a cleaned up JSFIDDLE of it working:
http://jsfiddle.net/37Fmh/
Comment: This is what I was thinking, but the problem is that it doesn't scale hardly at all, and there were quite a few problems I had with positioning when I tried it. I ended up using the other method with zero problems, but thank you for this nevertheless.
Answer: something like this should get you started.
http://jsfiddle.net/pxfunc/DxW47/1/
css:
body {background:#eee url('http://files.me.com/pwb3/lo1t09') repeat 0 0;margin:0;padding:0;}

#greenBg {background:#00cb00;height:50px;width:50%;top:40px;right:50%;position:absolute;}
#blueBg {background:#00b8de;height:50px;width:50%;top:40px;left:50%;position:absolute;}

.clear {clear:both;}

#container {width:960px;margin:40px auto 0 auto;position:relative;}
#header {background-color:#00cb00;width:220px;float:left;padding:15px;}
#nav {background-color:#00b8de;width:678px;border-left:solid 2px #fff;float:left;padding:15px;}

#content {margin-top:10px;border:solid 1px #ddd;background-color:#fff;padding:15px;height:400px;}

html:

        site logo

nav

content

Comment: Thank you so much, this is just what I needed. It's simple, but works perfectly, and scales without fault. Thank you so much!


Estimating the duration of a computationally-intensive process

Question: I'm not sure if it's even possible to create a mathematical model given the data I have, but I'll post this question with optimistic hope.
I'm running a computational process for which I do not have access to the source code (it uses Microsoft's closed source code).
The process finds duplicate lines (rows) in a text file and reports the duplicates along with the count of the number of occurrences for each duplicate.
Specifically, the command to do this, in Windows PowerShell, is:
<code> Get-Content .\input.txt | Group-Object | Select Name, Count > output.txt
</code>
I performed a test with a small sample, and I found that 5,000 lines (with the median length of each line being 50 characters) takes approximately 1 second to complete.
I then performed a test with a larger sample, and I found that 50,000 lines (with the same median line length) takes approximately 2 minutes to complete.
I then performed a test with a larger sample, and I found that 75,000 lines (with the same median line length) takes approximately 3.5 minutes to complete.
I then performed another test with an even larger sample, and I found that 100,000 lines (with the same median line length) takes approximately 8 minutes to complete.
I'm now running the same process on a file with 2,000,000 lines (with the same median line length).
It appears that PowerShell is limited to 4GB RAM, so the threads performing this task are using the maximum memory possible for PowerShell.
This process has been running for over 19 hours.  There is no progress indicator.
I'm trying to estimate the time it will take for this process to complete.
The challenge is the duration of such a process is not linearly dependent on the size of the input.
I'm trying to make a reasonable guesstimate, and I'm struggling to settle on an appropriate mathematical expression to use to provide such an estimate.
I'm hoping someone here will be able to recommend their suggested expression, and perhaps explain their reason why they think their recommendation is a good choice.
Comment: With one data point it is impossible to determine. You'd need to determine the run length for several sized inputs to make an estimate
Comment: @Aphyd Thanks. I agree, but I am/was hoping someone would be able to provide a useful expression based on the likely computational complexity of the process.  BTW, how many data points do you think will be sufficient, especially given the 4GB of usable RAM becomes a factor at some point?
Comment: There's a world of difference (like factors of 1,000) once all your data no longer fits in memory, and starts using disk to back your virtual memory. It might not be quite so bad if you've got SSD instead of magnetic disk storage, but it's still going to make prediction impossible.
Comment: That said, this smells roughly like sorting, where lots of good algorithms hit a best case complexity of $n \log(n)$. Don't know how you can make sure, or check, that PowerShell will do so.
Comment: @JonathanZsupportsMonicaC Thanks for your feedback.  Regarding using disk as virtual memory, I might be mistaken, but I think the process has a maximum addressable memory space of 4GB, and since there is more than 4GB of available RAM on that box, that issue is not present in this specific case.  In other cases, yes, definitely, I agree with you 100%.
Comment: @JonathanZsupportsMonicaC Regarding your second comment (very helpful BTW... thanks!), I was thinking along the lines of *n* log(*n*) as well.  I think estimating the case complexity is key, and that's where I could really use some help right now.
Comment: Okay. And I'll guess this is out of scope, but I'd switch to something like Linux+Perl for this task. It doesn't seem like something PowerShell is optimized for. It might be that your anti-virus is adding a bunch of time on Windows.
Comment: @JonathanZsupportsMonicaC Very long story short, I agree.  After 48 hours, I had to repurpose that CPU core, and thus stop PowerShell.  I then wrote my own optimized code, and it was able to get the job done in under an hour.  Still, I welcome additional answers, because I find this topic intriguing.
Answer: You don't have many sample points, but I'll still share some speculations, just know that they're credibility may be jeopardized by lack of data.
I plotted your data on a log-log time (sec) vs. size plot, and noticed that the first point is abnormally large, but the other three form a nice line. I suspect that there's a large amount of overhead (pre-sorting?) being done, that dominates the running time until the input grows large enough. Ignoring this data point, I can draw a linear regression line through the remaining three points, which fits extremely nicely, with a $R^2$ value of $0.99$ The equation of the line is
$$
Y = 1.98 X - 7.24
$$
However, remember that this is a log-log plot, so $Y = \log(y)$ and $X = \log(x)$. Substituting that in, we get:
$$
\begin{align}
\log(y) &= 1.98 \log(x) - 7.24 \\
\log(y) &= \log(x^{1.98}) - 7.24 \\
y &= 10^{\log(x^{1.98}) - 7.24} \\
y &= 10^{\log(x^{1.98})}10^{-7.24} \\
y &= 10^{-7.24}x^{1.98}
\end{align}
$$
That means our running time is dominated by a term of order $1.98$. Likely, this means the algorithm dominating the running time is quadratic.
Plugging into this (very rough) estimate, I get that for $x = 2,000,000$, the runtime is estimated around $2$ days ($47.8$ hours). Bear in mind that that's estimated from three data points.
Comment: Thank you Dillon. Upvoted! I played around with things too, and the median of my estimates were similar to your estimate (median was 58 hours).  I have a question regarding your post.  The equation you presented is linear, but you mentioned that "likely... the algorithm dominating the running time is quadratic".  Can you add to your answer why this makes sense?  BTW, I actually used quadratic equations for most of my estimates, so your conclusion correlates with my primary hypothesis.
Comment: @RockPaperLz-MaskitorCasket updated - let me know if anything else needs cleared up


Core dumped trying to create newVector(array 2D) in a struct

Question: So I'm trying to create a simple array 2D inside a struct, and to read the values of some coordinates that are in a file.
At this moment I've got all inside functions and i get a segmentation fault when i try to get the coordinates on the 'get_coords' function. If I write all the exactly same code on a 'int main' instead of using functions it works.
code:
            #include <stdio.h>
            #include <stdlib.h>

            // structure
            typedef struct coordinates{
                double **a;
            } coord;

            // counts the nmbr of points
            int count(){
                int i;
                int a1, a2, a3;
                FILE *fp;
                fp = fopen("abc.txt", "r+");
                while (fscanf(fp, "%d %d %d", &a1, &a2, &a3) != EOF){
                    i++;
                    if (feof(fp)){
                        break;
                    }
                }
                fclose(fp);
                return(i);
            }

            // creates new structure with the right size of memory allocated
            coord *newVector(size_t s){
                coord *v;
                int j;
                v = malloc(sizeof(coord));

                v->a = malloc(sizeof(double*)*3);

                for (j=0; j<3; j++){
                    v->a[j] = malloc(sizeof(double)*s);
                }

            }

            void get_coords(coord *points){
                int i=0;
                FILE *fp;
                fp = fopen("abc.txt", "r+");
                while (fscanf(fp, "%le %le %le", &points->a[i][0], &points->a[i][1], &points->a[i][2]) != EOF){
                    i++;
                }
                fclose(fp);
            }

            int main(){
                int i = 0, j=0;

                coord *points;

                i = count();

                points = newVector(i);

                get_coords(points);

                for (i=0; i<3; i++){
                        printf("%lf %lf %lf\n", points->a[i][0], points->a[i][1], points->a[i][2]);
                }
            }

abc.txt:
1 2 3
4 5 6
7 8 9

Thanks all for your help.
Cumps,
Dylan.
PS: This is just a prototype for what i want.
Comment: Compile with all warnings and debug info (`gcc -Wall -Wextra -g` with [GCC](http://gcc.gnu.org/)...). Improve your code to get no warnings. Read [how to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). Use [the `gdb` debugger](https://sourceware.org/gdb/current/onlinedocs/gdb/). Give an [MCVE]
Comment: abc.txt file is just a txt with some coordinates (just an example of it)
Comment: @Yunnosch thanks for your comment. As i said in question, the program works whe i've got everything in a 'int main', but once i separate the code into functions it stops working
Comment: what is abc.txt file?
Comment: @BasileStarynkevitch it's almost an MCVE!
Comment: thanks @Basilestarynkevitch ill try
Comment: 2D arrays (even if you call them simple) and input reading are two different non-trivial problems. Separate them. Try to solve one first, then start on the other.
Comment: Would you like to show the working code before the refactoring? It would make finding the problematic change easier than looking for the problem in the shown code.
Comment: Also, your comment does not seem to actually answer mine. Split the two parts. Solve each. Identify the one which makes the problem. Ask about that one. Demonstrate that one in a [mcve], exclude the other one from the question.
Comment: @Yunnosch OP has already provided a very good attempt for an MCVE.
Comment: See [Correctly allocating multi-dimensional arrays](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays)
Comment: @gsamaras No has not. Code has been provided to demonstrate a problem with 2D array or reading. For "M" only the code whith the part which demonstrates the problem should be provided. Removing the rest is part of making the CVE minimal.
Answer: In count(), you are incrementing an uninitialized variable, invoking Undefined Behavior (UB).
Change this:
int count() {
  int i;

to this:
int count() {
  int i = 0;

newVector() is not returning the dynamic allocated memory.
Change this:
coord *newVector(size_t s) {
  ...
}

to this:
coord *newVector(size_t s) {
  ...
  return v;
}

After fixing these issues, you should see this output:
1.000000 2.000000 3.000000
4.000000 5.000000 6.000000
7.000000 8.000000 9.000000

Not the problem, but I would use %lf as the format specifiers in fscanf(), instead of %le.
Moreover, in count(), this return(i); is the same as this return i;. The parentheses are redundant.
TODO: Free the dynamically allocated memory (I assume that you skipped that part for providing the MCVE).

Pro-tip: Compile with warning flags enabled next time. They would have already found the issue for you in this case. In GCC for example, I would get this:
gsamaras@myPc:~$ gcc -Wall  main.c
main.c: In function 'main':
main.c:51:28: warning: unused variable 'j' [-Wunused-variable]
                 int i = 0, j=0;
                            ^
main.c: In function 'newVector':
main.c:37:13: warning: control reaches end of non-void function [-Wreturn-type]
             }
             ^

where the last warning is the second point in my answer.
Comment: Ok i got it wrong, i was allocatting memory for unlimited collumns instead of rows, i just changed that and it works, that for everything @gsamaras
Comment: You're right thanks, but still it doesn't solve my segmentation fault. Edited the question
Comment: OK @DylanLopes, answer updated, problem solved. I rolled back your edit, since it invalidates my answer. :) Let me know if you have any problems..
Comment: You are welcome @DylanLopes. I think this edit with compiler warnings was really helpful... PS: Not a great fail, just a mistake that might trigger new knowledge for you (like compiling with warnings enabled next time!) ;) PPS: Your MCVE was perfect,  except from the fact that wasn't intended.
Comment: Thanks for your tips ;) now i've the problem that if i try read coordinates from this file: https://ufile.io/k1iap. i get a segmentation fault. if you can help please ;) PS: sorry for uploading the file, but it a really long one.
Comment: I cannot open the file from my work @DylanLopes, it's not a trusted file. How many columns, and how many rows? Because in your code, you have 3 hardcoded.
Comment: 19352 rows and 3 columns, i've hardcoded 3 columns, but unlimited rows right?
Comment: No @DylanLopes, as I explain in my [2D dynamic array(C)](https://gsamaras.wordpress.com/code/2d-dynamic-array-c/), you are allocating dynamically memory for 3 rows and `s` columns. Glad I helped!
Answer: You forgot to return v in newVector function:
        // creates new structure with the right size of memory allocated
        coord *newVector(size_t s){
            coord *v;
            int j;
            v = malloc(sizeof(coord));

            v->a = malloc(sizeof(double*)*3);

            for (j=0; j<3; j++){
                v->a[j] = malloc(sizeof(double)*s);
            }

            return v;

        }


Email all Organic Group members when a subgroup is created

Question: I have an Organic Groups / subgroups structure where an Organisation is a group, a Property is a child group of an Organisation, and a claim is a child group of a property. So:
Organisation > Property > Claim
Each subgroup is set to inherit its parents users
When a new Property is created, I can use rules to 'Get group members from group audience' to email all of the members of the group:
However when a new Claim is created the same rule only emails the user who created the Claim. I think that this might be because inherited users are handled differently from normal users. You can see this by going into the 'group' tab on the claim and then clicking on people:

We can see in the screenshot above that there are three inherited users, but only the user who created the node will be emailed, the other two will not.
How should I email the inherited users when subgroups like Claim are created?
-- Addition --
og_subgroups.views.inc is used to create the view shown above. The contents of this file are:
function og_subgroups_views_pre_render(&$view) {
  if ($view->name == 'og_members_admin') {
    // Add an overview of the users that are inherited from parent groups.
    $inherited_users = _og_subgroups_get_inherited_users($view->args[0], $view->args[1]);
    $header = array('Name', 'Inherited from');
    $rows = array();
    $membership_states = og_group_content_states();
    if (!empty($inherited_users)) {
      foreach ($inherited_users as $inherited_uid => $data) {
        $row = array();
        $row[] = l($data[0]['user']->name, 'user/' . $inherited_uid);
        $inherited_from = array();
        foreach ($data as $inheritance) {
          $inherited_from[] = t('!parent (@roles)', array(
            '!parent' => l(entity_label($inheritance['inherited_from']['type'], $inheritance['inherited_from']['entity']), 'group/' . $inheritance['inherited_from']['type'] . '/' . $inheritance['inherited_from']['id'] . '/admin/people'),
        '@roles' => implode(', ', $inheritance['roles']),
      ));
    }
    $row[] = implode(', ', $inherited_from);
    $rows[] = $row;
  }
}
$view->attachment_after = theme('table', array(
  'caption' => t('Inherited users'),
  'header' => $header,
  'rows' => $rows,
  'empty' => t('No inherited users.'),
));
  }
}

It would be great if someone could suggest how I might be able to use the above code in rules. It would be great if I could use'Execute custom PHP code' and use something like
$inherited_users = _og_subgroups_get_inherited_users($view->args[0], $view->args[1]);

but that doesn't work in a custom PHP block in Rules. I can see the function _og_subgroups_get_inherited_users in og_subgroups.common.inc and am not sure if I can use this code to help.
Using Organic Groups 7.x-2.7 and Organic groups subgroups 7.x-2.0-beta1
Comment: Have you tried [Views Rules](https://www.drupal.org/project/views_rules) to create a view that lists all the people you want to send an email to?
Comment: I am considering doing that, but am struggling so far to create a view of all the users. The issue is that on a property the view of user would only show the creating author as the other users are inherited from the parent group rather than associated with the current group
Comment: sorry, I didn't really understand your comment. Do you want to expand it into a separate question, and link it here? Also, I advise not using "Execute custom PHP code". It's one of the ways of quickly creating security loopholes.
Comment: Good suggestion @Turion. Here is a sperate question on the difficulty of creating a view that shows users inherited from the parent group: http://drupal.stackexchange.com/questions/191881/create-view-of-members-inherited-from-og-subgroups
Answer: I managed to use make a custom rules file for OG Subgroups that achieves what I need it to. It adds the rule 'Get subgroup group members from group audience' to a 'Custom' rule group:

This makes the users of the subgroup available to rules. You can then loop through the users and send an email to each of them:

In order to do this I created  custom 'og_subgroups.rules.inc' file in the root of the OG subgroups module. This is the code I used inside it:
<?php

/****************
Adds the ability to get the members of the parent group from a subgroup using rules
/****************

/**
 * Implements hook_rules_action_info().
 */
function og_subgroups_rules_action_info() {
  $items = array();

  $items['og_subgroups_get_members'] = array(
    'label' => t('Get subgroup group members from group audience'),
    'group' => t('Custom'),
    'parameter' => array(
      'group_content' => array(
        'type' => 'entity',
        'label' => t('Group content'),
        'description' => t('The group content determining the group audience.'),
      ),
    ),
    'provides' => array(
      'group_members' => array('type' => 'list<user>', 'label' => t('List of subgroup members')),
    ),
    'base' => 'og_subgroups_rules_get_members',
    'access callback' => 'og_subgroups_rules_integration_access',
  );

  return $items;
}

/* NEW FUNCTION ************************************************/

// This callback creates the hashed string by using the parameters provided through rules' UI
function og_subgroups_rules_get_members($group_content) {

// get the nid from the passed value of the content being added
$nid = $group_content->nid->value();

// trying to manually call the get inherited users function from og_subgroups.common.inc
$inherited_users = _og_subgroups_get_inherited_users("node", $nid);

$members = array();

foreach ($inherited_users as $inherited_uid => $data) {
  // Get the group members the group content belongs to.

  $user=user_load($inherited_uid);

  // push the returned user to the array of members
  array_push($members, $user);

}

// return the users
  return array('group_members' => $members);

}

/**
 * OG Rules integration access callback.
 */
function og_subgroups_rules_integration_access($type, $name) {
  // Grant everyone access to conditions.
  return $type == 'condition' || user_access('administer group');
}

For those of you who prefer patches here is the patch I created: Patch on drupal.org


OS X network stack ignores IGMP membership queries

Question: We have a remote site where the Macs are not responding to IGMP membership queries, but the Windows boxes do respond. Consequently, after about 10 minutes, the IGMP-aware network switch cuts off the multicast stream to the Macs.
Here is a screen shot of Wireshark showing the problem:

The first packet is the app requesting that the network begin allowing the IGMP packets from 126.96.36.199 through to the Mac. Then you see, about every 125 seconds thereafter, the network switch configured as the IGMP querier (10.1.254.254) ask if we're still interested in that stream. Notice the conspicuous lack of response.
Here is what happens here on the local network, for comparison:

Here, about every 95 seconds the IGMP querier (172.20.0.2) asks if we still want that stream, and the Mac in question (172.20.0.144) says, "Yes, keep sending it."
The firewall is turned off on the problem Macs in the GUI, and I've verified it at the command line:

$ /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate
Firewall is disabled. (State = 0)
$ /usr/libexec/ApplicationFirewall/socketfilterfw --getblockall
Block all DISABLED!
$ /usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode
Stealth mode disabled
$ /usr/libexec/ApplicationFirewall/socketfilterfw --getappblocked /Applications/mumblemutter.app/...
The application is not part of the firewall

The app doesn't matter, since the stack handles IGMP queries after the group has been joined.
The problem Macs are running 10.11.5, but I cannot believe the problem would be fixed by upgrading to the absolute latest, since that would mean that a BSD-based OS is fixing serious bugs in its network stack in 2016. Possible, but extremely low probability.
Comment: Did you check for `pf` firewall on OS X side explicitly - we have some users that are going ahead with apps like Murus and LittleSnitch that are rolling custom firewall configurations that you won't see at the system level from Apple's default firewall. Add to that Cisco, Kaspersky, trusteer and all the other "tools" that try to manage connectivity, security, network stacks, etc...
Comment: @bmike: Thanks, I should have thought of that, but we don't have admin passwords on the remote Macs, so we can only do this while someone is sitting in front of it and can answer `sudo`'s demand for us. I don't expect that this will end up being the problem, though, since the `igmp.c` snippet I pointed to is so clear on this point.
Answer: The problem is shown in the first packet capture, where you will notice that the IGMP group join packet is an IGMPv2 packet, but the responses from the IGMP querier are all v3.
This may seem fine, since macOS has supported IGMPv3 for a very long time now, but if you dig into the IGMP implementation in the Darwin open source kernel, down in igmp_input_v3_query(), you find this enlightening bit of code:
/*
 * Discard the v3 query if we're in Compatibility Mode.
 * The RFC is not obviously worded that hosts need to stay in
 * compatibility mode until the Old Version Querier Present
 * timer expires.
 */
if (igi->igi_version != IGMP_VERSION_3) {
    ...etc...

What this means is that macOS is obeying the IGMPv3 spec and putting any network interface where it has seen IGMPv2 packets into "compatibility mode," meaning that it will neither acknowledge IGMPv3 packets nor speak IGMPv3 on that network interface. In terms of the code above, it marks the interface as igi_version = 2, so we'll hit this test and ignore the v3 group membership query on the theory that it is unsafe to speak v3 on this network, lest the v2 devices be unable to understand what's going on.
I see three workable remedies:

Get those in charge of the network to reconfigure their switches to send back IGMPv2 queries to clients that asked for an IGMPv2 group join.

Turn off IGMPv3 support in the IGMP-aware network switches entirely, so that they will only send out IGMPv2 membership queries.

Monitor the network for IGMPv2 packets, find their source, and fix, upgrade, or remove them. If the network can't be made to speak v3 thru-and-thru, go with #1 or #2.

This is not something you can fix with an application code change. The IP_ADD_MEMBERSHIP option to setsockopt() doesn't include a version number, so the app is not in a position to demand IGMPv3. That decision is up to the stack.
While it is possible that there is an OS setting that would affect this, that could only be the case if the macOS IGMP implementation differs from what we see in the igmp.c linked above.
If you sniff the network for IGMP on a Windows box, you will see that it responds to IGMPv3 membership queries with v3 responses, despite the presence of v2 on the network. It is therefore in violation of the RFC; while some network admins who will say, "Well, it works, doesn't it?," the proper response must be that because you cannot force macOS to also disregard the RFC, the solution remains to fix the network.
Answer: This basically breaks IGMPv3, permanently, on most networks. Why? Because some very common implementations of mDNS (like the iPhone) frequently and gratuitously leave and rejoin 220.127.116.11 (the mDNS group) faster than the IGMP version timeout. If even a single device issues an IGMPv2 leave for 220.127.116.11, the querier will issue a group-specific ICMPv2 query for 188.8.131.52 to see if anybody is left. Everybody else in that group (which is most hosts these days) will see it and flip the interface to v2, keeping IGMPv3 queries from ever being answered by MacOS.
All this even though the IGMP spec says that hosts should not explicitly leave and join the 18.104.22.168/24 block, and snooping switches should always forward it. And good luck getting Apple to fix this gratuitous leave/join problem on its zillions of devices.
You can sort of work around it by rebooting all your iOS devices after switching the querier to IGMPv3, and waiting. But if any device should ever issue an IGMPv2 message, MacOS multicast breaks again.
This is a clear bug that cannot be blamed on anything but MacOS ignoring IGMPv3 messages when it thinks an interface is v2.