Problemas ao retornar uma grande quantidade de dados pelo WCF

Question: Boa Tarde,
tenho um web service feito em WCF, quando faço uma consulta no banco e retorno uma grande quantidade de registros ele me da o seguinte erro:
An unhandled exception of type 'System.ServiceModel.CommunicationException' occurred in mscorlib.dll
Additional information: A cota máxima de tamanho de mensagens de entrada (65536) foi excedida. Para aumentar a cota, use a propriedade MaxReceivedMessageSize no elemento de associação apropriado.
alguém pode me ajudar?
Comment: Você deve aumentar a propriedade `maxReceivedMessageSize` no `binding` do seu cliente. Como o seu cliente é definido? Usando `ChannelFactory` diretamente, usando uma classe gerada pelo `Add Service Reference`, de alguma outra forma?
Comment: Carlos, está definida pela classe gerada pelo Add Service Reference
Comment: Aumentei a Propriedade maxReceivedMessageSize, maxBufferSiz,maxBufferPoolSize e deu Certo , Obrigado !
Answer: Quando você usa o "Add Service Reference" para gerar o cliente para o WCF service, essa ferramenta adiciona no seu arquivo de configuração (app.config ou web.config) as informações necessárias para o cliente se comunicar com o servidor. Uma delas é o binding a ser usado.
Você pode alterar a configuração do binding para aumentar esta quota que a mensagem de erro está dizendo que está sendo ultrapassada. Por exemplo:
<bindings>
  <basicHttpBinding>
    <binding
        name="BasicHttpBinding_MyService"
        maxReceivedMessageSize="1000000" />
  </basicHttpBinding>
</bindings>

Uma outra alternativa é fazer isso no código, antes de chamar uma função do cliente pela primeira vez, como no exemplo abaixo.
        var c = new ServiceReference1.MyServiceClient();
        var binding = c.Endpoint.Binding;
        if (binding is BasicHttpBinding)
        {
            ((BasicHttpBinding)binding).MaxReceivedMessageSize = 1000000;
        }
        else if (binding is WSHttpBinding)
        {
            ((WSHttpBinding)binding).MaxReceivedMessageSize = 1000000;
        }
        else
        {
            // outros tipos
            var newBinding = new CustomBinding(binding);
            for (var i = 0; i < newBinding.Elements.Count; i++)
            {
                if (newBinding.Elements[i] is TransportBindingElement) {
                    ((TransportBindingElement)newBinding.Elements[i]).MaxReceivedMessageSize = 1000000;
                }
            }

            c.Endpoint.Binding = newBinding;
        }

Comment: Resolvido , Obrigado carlosfigueira


How to convert JSON string to MTLModel - Mantle

Question: Is there any way in mantle to convert a JSON data to MTLModelObject directly, I have gone through the documentation and haven't found a simple way to do so.
It seems there is only support for converting NSDictionary to MTLModelObjects and vice versa.
Comment: I can do it, i am just wondering if there is a direct method to do it via mantle, it seems weird, also i have to convert it while rendering cells inside cellForRowAtIndexPath so i want a more optimised way to it if possible.
Comment: why cant you first parse your data to `NSDictionary` then convert it ..
Comment: Can you post an example of the JSON string you're working with?
Comment: It can be any JSON string, i don't want to convert the JSON string to dictionary and then to my model object.
Answer: Mantle can not convert JSON string to model automatically. Override JSONTransformerForKey method and implement ur own NSValueTransformer by using NSJSONSerialization convert JSON String to NSDictionary


Erro: Thymeleaf está desabilitando a responsividade do meu formulário Bootstrap. Como resolver?

Question: Estou criando uma pequena aplicação web para aprender mais sobre Spring Boot. Estou usando o Thymeleaf como engine HTML e o Bootstrap como framework front-end. O problema é que eu não sei o porquê, e não sei como resolver, ele está desabilitando a responsividade do meu formulário. Ele deveria ficar da largura do container, mas
Ele está assim:

Observação: Estou usando CDN Bootstrap ao invés de arquivos locais.
Alguém pode me ajudar? Desde já muito, obrigada!
Seguem os códigos:
Observação: Projeto completo no GitHub.
Arquivo layout.html:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" th:href="@{css/custom.css}">
        <link rel="stylesheet" th:href="@{https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css}" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
        <title>Amigos leitores</title>

              <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

              </button>

                    Home (current)

                    Sobre nós

                    Regras

                    Entre em Contato!

Cabeçalho falso

Conteúdo falso

Arquivo formContato.html:
<!DOCTYPE html>

        <meta charset="UTF-8" />

Fale conosco!

Dúvidas, críticas e sugestões. Esse é o lugar!

    <form id="contato" th:action="@{/(formContato)}" th:object="${contato}" action="#" method="post">

Erro de validação

        <input type="hidden" th:field="*{id}" th:class="${#fields.hasErrors('id')} ? 'field-error'" />

        Nome:*
        <input type="text" class="form-control" id="nome" placeholder="Digite seu nome..." th:field="*{nome}" th:class="${#fields.hasErrors('nome')} ? 'field-error'" />

        E-mail:*
        <input type="text" class="form-control" id="email" placeholder="Digite seu e-mail..."  th:field="*{email}" th:class="${#fields.hasErrors('email')} ? 'field-error'" />

        Assunto:*
        <input type="text" class="form-control" id="assunto" placeholder="Dê um breve título a sua mensagem..." th:field="*{assunto}" th:class="${#fields.hasErrors('assunto')} ? 'field-error'" />

            Mensagem:*
            <textarea class="form-control" id="mensagem" rows="3" placeholder="Mensagem..." th:field="*{mensagem}" th:class="${#fields.hasErrors('mensagem')} ? 'field-error'" >
            </textarea>

            <input type="button" class="btn btn-dark" value="Voltar" />
            <input type="reset" class="btn btn-dark" value="Limpar" />
            <input type="submit" class="btn btn-dark" value="Enviar" />

    </form>

Arquivo custom.css:
body{
    background-color: #fafafa !important;
}

Answer: Gente, o problema foi resolvido em outro fórum onde fiz a mesma pergunta. Mas vou deixar aqui, caso alguém esteja tendo a mesma dificuldade.
Como eu estava usando th:class ele estava "sobrescrevendo" o class="form-control" da tag <form>. Isso foi resolvido, conforme me foi sugerido nessa resposta aqui, lá no GUJ, substituindo th:class por th:classappend.


async task testing

Question: I just started using Rhino Mocks that test my async methods within the code. But while normally the code works just perfect but while mocking tests with Rhino Mocks there are some weird async problems.
Let's say I want to test the following code which calls multiple numberGenerators that all will run at the same time and wait till they are all done:
public async Task MyTask()
{
    List<Task<List<int>>> numberTasks = new List<Task<List<int>>>();

    foreach (var numberGenerator in numberGenerators)
    {
        // GetNumbers is an 'async Task<List<int>>'
        // As you can see I don't use 'await' so it should just add it and go on.
        numberTasks.Add(numberGenerator.GetNumbers());
    }

    try
    {
        await Task.WhenAll(numberTasks);
    }
    catch (Exception e)
    {
        // Log exception if something happens at 'GetNumbers' (like time-out or whatever)
    }

    var numbers = new List<int>();
    numbers.AddRange(numberTasks.Where(task => task.Status == TaskStatus.RanToCompletion).SelectMany(task => task.Result));

    // Do something with the numbers
}

Is tested with:
numberGenerator.Expect(x => x.GetNumbers())
    .WhenCalled(x => Thread.Sleep(10000))
    .Return(Task.FromResult(numbers));

I use two of the generators on 'mocked' in the code above. Now if I run the code with 'non-mocked' objects numberTasks.Add just adds the Task and moves on. But when I mock it with the WhenCalled sleep it waites for 10 seconds before going to the next one in the foreach loop.
How can I change my mock that it acts like a normal async Task that takes 10 seconds to complete?
Bonus question: Can want to be able to do the same with .Throw() so I can wait 10 seconds before throwing an Exception.
Update:
Although I thought the following would fix the problem:
numberGenerator.Expect(x => x.GetNumbers())
    .Return(Task.Delay(10000).ContinueWith(x => numbers));

This doesn't seem to be the case. The Task.Delay starts counting down at the moment this mock is created. So if I create this mock, wait 10 seconds and then run the test it will be done in 0 seconds.
So my question remains, how can I test an async method with a delay before returning the result.
Comment: Actually the original topic was okay, http://meta.stackexchange.com/help/tagging "The only time you should use tags in your title is when they are organic to the conversational tone of the title."
Comment: Please see ["Should questions include "tags" in their titles?"](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles), where the consensus is "no, they should not"!
Comment: @Tseng actually, even with tags, the original title was not okay - in no way ... It was just a catenation of some terms, and missing a clear question/title whatsoever. Please see: http://stackoverflow.com/help/how-to-ask. *Pretend you're talking to a busy colleague and have to sum up your entire question in one sentence*
Answer: An async method runs synchronously until an await is reached. That means if you wait before returning a task in the mocked operation this wait will be synchronous. What you want to do is return a task immediately that completes after some time.
You can do that with Task.Delay:
numberGenerator.Expect(x => x.GetNumbers()).
        Return(Task.Delay(10000).ContinueWith(t => numbers));

Task.ContinueWith is used to add the actual return value after the delay is completed.
If you would like to throw an exception instead of returning a value, that too can be done inside the continuation.
Since Task.Delay(10000).ContinueWith(t => numbers) is evaluated when you create the mock, each call would return the same task (which will be completed 10 seconds after the mock was created).
If you need to create a new task each time you need to pass a delegate. Return doesn't accept a delegate so you need to use WhenCalled:
numberGenerator.Expect(x => x.GetNumbers()).
        WhenCalled(mi => mi.ReturnValue = Task.Delay(10000).ContinueWith(x => numbers));

Now, while WhenCalled is used to set the return value using Return is still required in order to determine the type of the return result. It doesn't matter what value it gets as the return value will still be set by WhenCalled:
numberGenerator.Expect(x => x.GetNumbers()).
    WhenCalled(mi => mi.ReturnValue = Task.Delay(10000).ContinueWith(x => numbers)).
    Return(Task.FromResult(new List<int>()));

Comment: One weird thing, if I add this code you wrote and instead of adding tasks in the foreach I await them in the foreach. It is still done in about 10 seconds. It looks like it just skips to the next in the foreach eventhough there is an await.
Comment: @Julian I don't think so. The task you create before passing to `Return` is the same task that will complete in 10 seconds. When the first item returns it it will wait for 10 seconds but the second will move on because the task already completed. If you want to return a new task each time you need a `Return` that accepts a delegate or something similar.
Comment: after testing alot the problem doesn't seem to be fixed because the `Task.Delay` starts running at the moment the `mock` is made.
Comment: @Julian of course. That's what my previous comment states. If you want to generate the task each time you need to pass in a delegate which will produce a new task each time. `Return` doesn't support that AFAIK but `WhenCalled` does: `WhenCalled(mi => mi.ReturnValue = Task.Delay(10000).ContinueWith(x => numbers))`
Comment: Ah sorry I completely misunderstood your comment than. If I only specify the `ReturnValue` in `WhenCalled` it tells me it doesn't have any return value. So it's working now with: `WhenCalled(mi => mi.ReturnValue = Task.Delay(10000).ContinueWith(x => numbers)).Returns(Task.FromResult(numbers));` Looks weird to me though but gives the right results. Thanks! (could you update your answer so I can accept it with this.
Answer: Personally I haven't worked with rhino mock, so I don't know if it supports async Method calls.
But Thread.Sleep(10000) is a synchronous code. If you want await in asynchronously you have to use Task.Delay(10000).
Or alternatively use Task.Run( () => Thread.Sleep(10000) ) though, Task.Delay(10000) is preferred way and best practice.

async task testing


Is there a wait-list functionality planned or already implemented?

Question: I just took a first look on the RNG Module. In the Readme, it is called the successor of the Drupal Entity Registration Module.
Is there a wait-list functionality planned or already implemented?
Maybe I'm not getting it right and its already implemented via Rules?
Any help would be welcome...
Answer: There is no support for wait lists at this time, however the API has a tagging system not exposed via UI, which is designed to support a list systems.
I encourage you to take a look at RNG Ecosystem, and give some feedback on your requirements for wait lists.


Why we need noinline in kotlin?

Question: I'm reading kotlin doc and can't understend one thing.
We can use noinline modifier to mark that lambda shouldn't be inline. But what is the real case when we really need it?
I understend what noinline does, but can't understand why.
Answer: Notice that when inline is added to a function/method declaration, all of its lambda parameters are inlined.
Also notice that there are some ways in which you can use a lambda parameter, that requires the lambda to be not inlined. For example, passing it to another, non-inlined function, or assigning it to a variable:
var func: (() -> Unit)? = null
inline fun foo(x: () -> Unit, y: () -> Unit) {
    notInlined(x) // x must be not inlined for this to work
    func = x // x must be not inlined for this to work
}

So what if I want to do notInlined(x), but I still want to inline y? This is where I use noinline:
inline fun foo(noinline x: () -> Unit, y: () -> Unit)

IntelliJ even gives this as a suggestion:
Answer: One thing I notice is that this for example is allowed, but "end of runLambda" is never reached then.
fun main() {
    runLambda {
        println("lambda")
        return
    }

}

inline fun runLambda(lambda: ()->Unit) {
    lambda.invoke()
    println("end of runLambda")
}

if you want to ensure that the function completely runs until the end noinline could fix it because then it won't allow the return

Although crossinline can do the same and I think that one is actually meant for that. I'm not sure what the difference is

Why we need noinline in kotlin?


From dataframe with values per min max to value per key

Question: I have a dataframe with values defined per bucket. (See df1 below)
Now I have another dataframe with values within those buckets for which I want to look up a value from the bucketed dataframe (See df2 below)
Now I would like to have the result df3 below.
df1 <- data.frame(MIN = c(1,4,8), MAX = c(3, 6, 10), VALUE = c(3, 56, 8))
df2 <- data.frame(KEY = c(2,5,9))
df3 <- data.frame(KEY = c(2,5,9), VALUE = c(3, 56, 8))

> df1
  MIN MAX VALUE
1   1   3     3
2   4   6    56
3   8  10     8
> df2
  KEY
1   2
2   5
3   9
> df3
  KEY VALUE
1   2     3
2   5    56
3   9     8

EDIT :
Extended the example.
> df1 <- data.frame(MIN = c(1,4,8, 14), MAX = c(3, 6, 10, 18), VALUE = c(3, 56, 3, 5))
> df2 <- data.frame(KEY = c(2,5,9,18,3))
> df3 <- data.frame(KEY = c(2,5,9,18,3), VALUE = c(3, 56, 3, 5, 3))
> df1
  MIN MAX VALUE
1   1   3     3
2   4   6    56
3   8  10     3
4  14  18     5
> df2
  KEY
1   2
2   5
3   9
4  18
5   3
> df3
  KEY VALUE
1   2     3
2   5    56
3   9     3
4  18     5
5   3     3

Comment: Is this a representative example of your real dataset, or just a simple case? Here it looks like each `KEY` in `df2` belongs in only one of the `MIN, MAX` ranges in `df1` and, also, it is `+1, -1` from `MIN, MAX` respectively.
Comment: This is a really simplified version. It should accomodate multiple values in each bucket and the value can be any value within, or on the boundaries of each bucket.
Answer: This solution assumes that KEY, MIN and MAX are integers, so we can create a sequence of keys and then join.
df1 <- data.frame(MIN = c(1,4,8, 14), MAX = c(3, 6, 10, 18), VALUE = c(3, 56, 3, 5))
df2 <- data.frame(KEY = c(2,5,9,18,3))

library(dplyr)
library(purrr)
library(tidyr)

df1 %>%
  group_by(VALUE, id=row_number()) %>%             # for each value and row id
  nest() %>%                                       # nest rest of columns
  mutate(KEY = map(data, ~seq(.$MIN, .$MAX))) %>%  # create a sequence of keys
  unnest(KEY) %>%                                  # unnest those keys
  right_join(df2, by="KEY") %>%                    # join the other dataset
  select(KEY, VALUE)

# # A tibble: 5 x 2
#     KEY VALUE
#   <dbl> <dbl>
# 1  2.00  3.00
# 2  5.00 56.0
# 3  9.00  3.00
# 4 18.0   5.00
# 5  3.00  3.00

Or, group just by the row number and add VALUE in the map:
df1 %>%
  group_by(id=row_number()) %>%
  nest() %>%
  mutate(K = map(data, ~data.frame(VALUE = .$VALUE,
                                   KEY = seq(.$MIN, .$MAX)))) %>%
  unnest(K) %>%
  right_join(df2, by="KEY") %>%
  select(KEY, VALUE)

Comment: Cool! Although it doesn't work when the VALUE of the first bucket equals the value of a latter bucket.
Comment: Can you post an example in your question? If I can replicate the problem I'll be able to fix it.
Comment: I got your point. I group by `VALUE` so having the same `VALUE` in another row will break the process. So, I'll add the row id/number in the grouping in order to have unique combinations.
Answer: A very good and well-thought-out solution from @AntioniosK.
Here's a base R solution implemented as a general lookup function given as arguments a key dataframe and a bucket dataframe defined as listed in the question. The lookup values need not be unique or contiguous in this example, taking account of @Michael's comment that values may occur in more than one row (though normally such lookups would use unique ranges).
lookup = function(keydf, bucketdf){
  keydf$rowid = 1:nrow(keydf)
  T = merge(bucketdf, keydf)
  T = T[T$KEY >= T$MIN & T$KEY <= T$MAX,]
  T = merge(T, keydf, all.y = TRUE)
  T[order(T$rowid), c("rowid", "KEY", "VALUE")]
}

The first merge uses a Cartesian join of all rows in the key to all rows in the bucket list. Such joins can be inefficient if the number of rows in the real tables is large, as the result of joining x rows in the key to y rows in the bucket would be xy rows; I doubt this would be a problem in this case unless x or y run into thousands of rows.
The second merge is done to recover any key values which are not matched to rows in the bucket list.
Using the example data as listed in @AntioniosK's post:
> lookup(df2, df1)
  rowid KEY VALUE
2     1   2     3
4     2   5    56
5     3   9     3
1     4  18     5
3     5   3     3

Using key and bucket exemplars that test edge cases (where the key = the min or the max), where a key value is not in the bucket list (the value 50 in df2A), and where there is a non-unique range (row 6 of df4 below):
df4 <- data.frame(MIN = c(1,4,8, 20, 30, 22), MAX = c(3, 6, 10, 25, 40, 24), VALUE = c(3, 56, 8, 10, 12, 23))
df2A <- data.frame(KEY = c(3, 6, 22, 30, 50))

df4
  MIN MAX VALUE
1   1   3     3
2   4   6    56
3   8  10     8
4  20  25    10
5  30  40    12
6  22  24    23

> df2A
  KEY
1   3
2   6
3  22
4  30
5  50

> lookup(df2A, df4)
  rowid KEY VALUE
1     1   3     3
2     2   6    56
3     3  22    10
4     3  22    23
5     4  30    12
6     5  50    NA

As shown above, the lookup in this case returns two values for the non-unique ranges matching the key value 22, and NA for values in the key but not in the bucket list.


Prob. 15, Chap. 6, in Baby Rudin: If $f$ is a real, continuously differentiable function on $[a, b]$, . . .

Question: Here is Prob. 15, Chap. 6, in the book Principles of Mathematical Analysis, by Walter Rudin, 3rd edition:

Suppose $f$ is a real, continuously differentiable function on $[a, b]$, $f(a) = f(b) = 0$, and $$ \int_a^b f^2 (x) \ \mathrm{d} x = 1. $$
  Prove that $$ \int_a^b x f(x) f^\prime (x) \ \mathrm{d} x = - \frac{1}{2} $$
  and that $$ \int_a^b \left[ f^\prime (x) \right]^2 \ \mathrm{d} x \cdot \int_a^b x^2 f^2 (x) \ \mathrm{d} x > \frac{1}{4}. $$

My Attempt:

As $f^\prime$ is continuous, so it is Riemann-integrable, by Theorem 6.8 in Rudin. Then by Theorem 6.22 in Rudin we can use integration by parts to obtain
  $$
\begin{align}
\int_a^b x f(x) f^\prime (x) \ \mathrm{d} x &= \int_a^b x \frac{\mathrm{d}}{\mathrm{d} x} \left[ \frac{f^2(x)}{2} \right] \ \mathrm{d} x \\
&=  b \frac{f^2(b)}{2}  - a \frac{ f^2(a) }{2} - \int_a^b \frac{\mathrm{d} x}{\mathrm{d} x} \frac{ f^2(x) }{2} \ \mathrm{d} x \\
& \qquad \mbox{ [ using Theorem 6.22 in Rudin with $F(x) = x$ and $G(x) = \frac{f^2(x)}{2}$ ] } \\
&= 0 - 0 - \int_a^b \frac{f^2(x)}{2} \ \mathrm{d} x \\
&= -\frac{1}{2} \int_a^b f^2(x) \ \mathrm{d} x \\
&= -\frac{1}{2} \cdot 1 \\
&= -\frac{1}{2}. \tag{0}
\end{align}
$$

Here is the link to my Math SE post on the Holder's inequality for integrals:
Probs. 10 (a), (b), and (c), Chap. 6, in Baby Rudin: Holder's Inequality for Integrals
And, for $p=2$, the Holder's inequality is the Schwarz inequality for integrals.

Thus if $u$ and $v$ are complex Riemann-Stieltjes integrable functions with respect to a monotonically increasing function $\alpha$ on $[a, b]$, then
  $$ \left\lvert  \int_a^b u v \ \mathrm{d} \alpha \right\rvert \leq \left( \int_a^b \lvert u \rvert^2 \ \mathrm{d} \alpha \right)^{1/2} \left( \int_a^b \lvert v \rvert^2 \ \mathrm{d} \alpha \right)^{1/2}.  $$
  Therefore, if $u$ and $v$ are real Riemann-Stieltjes integrable functions with respect to $\alpha$ on $[a, b]$, then we can rewrite the last inequality as
  $$ \left\lvert  \int_a^b u v \ \mathrm{d} \alpha \right\rvert \leq \left( \int_a^b u^2 \ \mathrm{d} \alpha \right)^{1/2} \left( \int_a^b v^2 \ \mathrm{d} \alpha \right)^{1/2}.  $$
  If we put $\alpha = x$ in the last inequality, we obtain
  $$ \left\lvert  \int_a^b u v \ \mathrm{d} x \right\rvert \leq \left( \int_a^b u^2 \ \mathrm{d} x \right)^{1/2} \left( \int_a^b v^2 \ \mathrm{d} x  \right)^{1/2},  $$
  and hence
  $$ \left\lvert  \int_a^b u v \ \mathrm{d} x \right\rvert^2 \leq  \int_a^b u^2 \ \mathrm{d} x \cdot \int_a^b v^2 \ \mathrm{d} x,  $$
  which is the same as
  $$ \left(   \int_a^b u v \ \mathrm{d} x \right)^2 \leq  \int_a^b u^2 \ \mathrm{d} x \cdot \int_a^b v^2 \ \mathrm{d} x,  $$
  which implies that
  $$ \int_a^b u^2 \ \mathrm{d} x \cdot \int_a^b v^2 \ \mathrm{d} x \geq
\left(   \int_a^b u v \ \mathrm{d} x \right)^2. \tag{1} $$
In (1) we put $u(x) = f^\prime(x)$ and $v(x) = x f(x)$ and obtain
  $$
\begin{align}
 \int_a^b \left[ f^\prime(x) \right]^2 \ \mathrm{d} x \cdot \int_a^b x^2 f^2(x) \ \mathrm{d} x &\geq \left( \int_a^b f^\prime(x) x f(x) \ \mathrm{d} x \right)^2  \\
&= \left( \int_a^b  x f(x) f^\prime(x) \ \mathrm{d} x \right)^2 \\
&= \left( - \frac{1}{2} \right)^2 \qquad \mbox{ [ using (0) above ] } \\
&= \frac{1}{4}.
\end{align}
$$

Is what I've done so far correct? If so, then why is it that, unlike what Rudin has asserted, I've not obtained the strict inequality in the second calculation?
How to obtain the strict inequality from where I've left off?
Comment: Equality in Cauchy-Schwarz can only occur if the functions are linearly dependent.
Comment: You lost a minus sign in (0).
Comment: @LordSharktheUnknown thank you so much! I've incorporated the correction. Can you please write out a detailed answer as to the necessary and sufficient condition under which the equality holds in the Holder's inequality and also the Schwarz inequality for the Riemann-Stieltjes Integrals of complex-valued functions?
Answer: If the equality was not strict, it is not to hard to prove that $$xf(x) = \lambda \cdot f'(x) \tag{1}$$ for some $\lambda \in \mathbb{R}$, i.e, the Cauchy-Schwarz inequality is an equality when the terms are linearly dependent.
Case 1 ($\lambda = 0 $)

Then $f = 0$ which leads to a contradiction with the fact that $$\int_a^b f^2 (x) \ \mathrm{d} x = 1.$$

Case 2 ($\lambda \neq 0$)

Since $\int_a^b f^2 (x) \ \mathrm{d} x = 1$, $\exists s \in [0,1] : f(s) \neq 0$. We can safely say that $s \in (0,1)$ due to the given condition that $f(0)=0=f(1)$.
Since $f$ is continuous, by the Extreme Value Theorem, $f$ has a
local max/min on the interval [0,1], and due to the preceding observation at
least one of these max/min values has to be non zero. In other words, $$\exists t \in (0,1) : f'(t) = 0 \text{ and } f(t) \neq 0$$
We arrived at this conclusion in this way because it is important that $f(t) \neq 0$ also, as we were already guaranteed a point where the derivative vanishes by Rolle's Theorem.
Evaluating what we have in (1) at $t$, $$f'(t) = 0 = \frac{1}{\lambda} \cdot t f(t)$$
This leads to a contradiction since $\frac{1}{\lambda},t,f(t)$ are all non zero.

In either case we have a contradiction. Thus the inequality is a strict one.


Why is my memory increasing dramatically in Python

Question: I don't know why my memory keeps dramatically increasing in this code. If I replace
"Value = random.choice(Training_Data)" with "Value = random.choice(Data_Matrix)" this issue goes away but I am interested why "Value = random.choice(Training_Data)" is causing a memory error. I see this memory error looking at task manager and if I iterate in a large enough range will exceed the amount of ram memory I have. I know what the problem is but I unfortunately don't know why the problem is happening.
import numpy as np
import random

Data_File = open("Data\even_mnist.csv", 'r')
Training_Data = np.loadtxt(Data_File)
num_rows = np.shape(Training_Data)[0]
Training_Data = np.array(Training_Data)
Testing_Data = []

##print(len((Data_Matrix)))

Data_Matrix = Training_Data

for i in range(500):
    Value = random.choice(Training_Data)
    Testing_Data.append(Value)

    count = 0
    for lines in Training_Data:
        count = count + 1
        if np.array_equal(lines, Value):
            Training_Data = np.delete(Training_Data, count, 0)

Answer: import sys
enter code hereprint(sys.getsizeof(1))
28
enter code hereprint(sys.getsizeof(2**30))
32
enter code hereprint(sys.getsizeof(2**60))
36
enter code hereprint(sys.getsizeof("a"))
50
enter code hereprint(sys.getsizeof("aa"))
51
enter code hereprint(sys.getsizeof("aaa"))
52
enter link description hereprint(sys.getsizeof([]))
56
enter code hereprint(sys.getsizeof(1))
64
enter code hereprint(sys.getsizeof([1, 2, 3, 4, 5]))
96, yet empty list is 56 and each value inside is 28.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


x-editable popup does not display in correct position

Question: I am trying to use divs instead of a table, and allow the user to comment on each "row".
An example of my div structure is like this:

    This is my whole entire line!

With the editable being defined like so:
$('#popup').editable({
    toggle: 'manual',
    mode: 'popup',
    title: 'Enter comment',
    type: 'text',
    emptytext: '',
    placement: 'right',
    display: function(value, response) {
        return false;   //disable this method
    },
    success: function(response, newValue) {
        alert("success saving: " + newValue);
    }
});

And for some reason the x-editable popup will not display relative to the correct div, it keeps defaulting to the top left corner. How can I fix this?
see jsfiddle here: http://jsfiddle.net/H9Drf/7/
Edit: I think that the problem has to do with the id of "popup" being the same in each div. As in, if I click on the third line, and write something into the textbox and hit "Save", I can tell that the effect happened to the first line, which has the first occurrence of "id=popup". Still not sure where to go from here...
Comment: Where do you want it to actually display?
Comment: @Travis I want it to display on the right of the line
Comment: As in, on/by the same line as the text.
Answer: I am not sure that this will work everywhere but this should work on your example. The plugin that you are using is adding inline style
try adding this to your style sheet
 .editable-popup{top:-61px !important;left:245px !important;}

Comment: I'm looking for a solution that will result in the popup appearing next to each SELECTED row. like, you can click on the icon in each row and each time the popup will appear next to it. This solution only shows the popup next to one specific row. I updated the jsfiddle to more clearly illustrate what i mean: http://jsfiddle.net/H9Drf/7/

Also, I believe that the top row is working, but the second and third are not. Still have no idea why.
Answer: If you want popup to display relatively to '#line1', add this to css:
#line1 {
   position: relative;
}

Answer: I got it to work once I gave the different x-editable items (the links inside the popuplink divs in my code) different IDs. See working solution at jsfiddle.net/H9Drf/9/
Answer: I had this problem and it turns out I was not including the correct jquery-ui css. Changing the css version to match the ui version fixed it.


MERN App - React state in Render - TypeError: Cannot read property 'username' of undefined

Question: So, I've built the component Post for a forum. It is supposed to show the respective post and fill it with data according to its id. The file makes a get request via axios to mongodb, loads in all of the posts and the filters them according to the right id (which I get from the url).
Then, in componentWillMount, I
console.log(this.state.idUrl[0].username)

this.state.idUrl is basically an array. And since it always only has one object in it (which contains content for the respective post, with username, content, header, etc.), I feel comfortable using the 0 index. And the whole thing works fine, it shows me the username for the right post.
Now, I want to access this.state.idUrl[0] in render. But it only says "cannot read property 'username' of undefined". Does anyone know why that is?
import React, { Component } from 'react';
import axios from 'axios'

class Post extends Component {
    constructor(props)  {
        super(props)
        this.state={
            idUrl: "",

        }

    }
    componentWillMount() {
        let url = window.location.pathname
        var lastPartUrl = url.substr(url.lastIndexOf('/') + 1);
        //console.log(lastPartUrl);
        axios.get('http://localhost:5000/posts/all')
        .then(response => {

          let rightPost = response.data.filter(post => post._id === lastPartUrl)

          this.setState({idUrl: rightPost})
          //why does this work but ...
          console.log(this.state.idUrl[0].username)
        })
        .catch((error) => {
          console.log(error)
        })

    }

    render() {
        return (

                {/*... but this won't? */}

{this.state.idUrl[0].username}

        )
    }
}

export default Post

Answer: I would say that the request in axios takes long time thus this {this.state.idUrl[0].username} is not defined.
Try something like:
{this.state.idUrl && this.state.idUrl[0] && this.state.idUrl[0].username}

In addition, since you know isUrl is an array, I would suggest defining it as as array:
this.state={
    idUrl: [],
}

So you can do:{this.state.idUrl.length > 0 && this.state.idUrl[0].username}
Comment: I figured it had something to do with the code being asynchronous. But I didn't know how to adapt it accordingly. Your solution worked though, thanks :)
Comment: If you think my solution is the right one, please confirm it by clicking the check icon on my post. Thanks


Como ler dados de um SQL do postgresql?

Question: Olá, Boa tarde sou relativamente novo programando, estive trabalhando em um projeto que envolve o mapeamento de alguns equipamentos, fiz a minha parte sem problemas porem agora preciso inserir dados de um outro aplicativo que é meio que o projeto pai do meu.
O estado atual é esse:
1.Fiz meu banco de dados com o MongoDB, e o projeto antigo foi feito com o Django usando o postgresql como banco de dados.
2.Tenho o Arquivo Sql da aplicação antiga.
3.Consegui uma parte importante dos dados lendo os arquivos e pegando na mão mesmo
O problema em questão é o seguinte:
1.Não consigo pegar ou identificar no arquivo algo que possua a latitude e longitude que é o que preciso
Queria saber se alguém possui uma maneira de ler esse aquivo e visualizá-lo de maneira mais entendível (O que peguei foi no código mesmo )
Tentei importar mas não consegui, sou bem leigo mexendo com essa parte.
Comment: O PostGIS não é um banco de dados, é uma extensão espacial desenvolvida sobre o sistema de gerenciamento de banco de dados PostgreSQL, que permite o armazenamento e uso de objetos GIS em banco de dados. Veja: https://postgis.net/
Comment: Seria isto https://postgis.net/workshops/postgis-intro/loading_data.html ?
Comment: Mil desculpas amigo, realmente errei
Comment: Esse link ensina a fazer a conexão, existe algum modo de apenas observar os dados do sql que possuo ?
Comment: É impossível "observar" os dados de um banco de dados sem fazer uma conexão (entendo "observar" como "ler").
Answer: Galera obrigado mais meu problema era diferente,
Eu não resolvi pelo método convencional mas encontrei as coordenadas, estavam como geometry por isso estranhei,
Peguei o que precisava usando o código mesmo.
Obrigado

Como ler dados de um SQL do postgresql?


DNS/Nameserver problems & ISPConfig

Question: My domain rscharts.com is suppose to connect to my VPS server, and the server is 126.96.36.199.
However, the domain rscharts.com simply won't work. I'm new to all of this; my first time having a VPS.
<code>Searching for rscharts.com. A record at M.ROOT-SERVERS.NET. [18.104.22.168] ...took 10 ms
Searching for rscharts.com. A record at d.gtld-servers.net. [22.214.171.124] ...took 116 ms
Searching for rscharts.com. A record at ns1.rscharts.com. [18.104.22.168] null
Searching for rscharts.com. A record at ns2.rscharts.com. [184.108.40.206] null
Searching for rscharts.com. A record at ns1.rscharts.com. [184.108.40.206] null
Searching for rscharts.com. A record at ns2.rscharts.com. [18.104.22.168] null
None of the nameservers responded correctly.
</code>
I'm not sure why it doesn't work (am I missing a record, do I have any records configured wrong?), as I've set up everything I needed in ISPConfig's DNS zone:
http://puu.sh/4wPlQ.png
http://puu.sh/4wPjG.png
puu.sh/4wPkz.png
Can anyone please help me with this? My website has been down for an entire week.
Comment: Who hosts and manages ns1.rscharts.com and ns2.rscharts.com? Is the rscharts.com zone set up and configured on those two servers?
Comment: My host manages ns1.rscharts.com and ns2.rscharts.com - they have assured me that the problem is not on their part, and that the problem is due to the server being "misconfigured." And I'm on an "unmanaged" server, so I cannot get any help regarding the issue.
Comment: Curiously, those two nameservers, which share the same IP and are really the same server apparently (Bad!  Don't do that!!) resolve IN A rscharts.com. just fine (and resolve it to the same IP they share, curiously).  So either your host is lying and has misconfigured them, or you control them and they are working fine.
Comment: Where does that diagnostic output you included in the question come from?  Both name servers work for me and the hierarchy down to them is working correctly.  I suspect the tool is broken.  The website itself is working fine.
Answer: looks like you are not running bind on that IP:
<code>; <<>> DiG 9.7.6-P1 <<>> @184.108.40.206 rscharts.com
; (1 server found)
;; global options: +cmd
;; connection timed out; no servers could be reached
</code>
check to make sure bind is running and listening on not just localhost, and that you dont have udp/53 closed by iptables.  also make sure that ip is actually what is assigned to your VPS.
Comment: I believe my host should already have binded my domain to the server.
Comment: let me clarify .... udp/53 is *not* open on 22.214.171.124  ... until that changes, your domain will not resolve on the internet

DNS/Nameserver problems & ISPConfig


Slider binding causes significant performance drop

Question: As the title says I have a custom slider declared like this:
<customControls:ThumbDragSlider IsEnabled="{Binding PlayerSourceState}"
                                Style="{StaticResource {x:Type Slider}}"
                                Value="{Binding CurrentMediaPlayer.MediaElement.Position, Mode=TwoWay, Converter={converters:SecondsToTimeSpanConverter}}"/>

There are couple more properties that being set, more events and some commands binding too, but I've omitted them, because I've narrowed down the performance issue to this specific line:
Value="{Binding CurrentMediaPlayer.MediaElement.Position, Mode=TwoWay, Converter={converters:SecondsToTimeSpanConverter}}"

Removing it also removes all the lag. On my PC it runs just fine, but when tested on an older machine without a GPU, using only the CPU as such, it doesn't run well. This slider is used to navigate through a MediaElement and the lag is most prevalent on the actual media file, it even shutters.
The converter is declared as follows:
[ValueConversion(typeof(double), typeof(TimeSpan))]
public class SecondsToTimeSpanConverter : BaseConverter, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {
        if (value is TimeSpan ts)
        {
            return ts;
        }
        return TimeSpan.FromSeconds((double)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {
        return TimeSpan.FromSeconds((double)value);
    }
}

And the custom slider like this:
public class ThumbDragSlider : Slider
{
    public event DragStartedEventHandler DragStarted;
    public event DragCompletedEventHandler DragCompleted;
    public event EventHandler<MouseEventArgs> ThumbMouseEnter;

    public new TimeSpan Value
    {
        get => TimeSpan.FromSeconds(base.Value);
        set => base.Value = value.TotalSeconds;
    }

    public ThumbDragSlider()
    {
        Loaded += OnLoaded;
    }

    private void OnLoaded(object sender, System.Windows.RoutedEventArgs e)
    {
        Loaded -= OnLoaded;
        var track = this.GetElementFromTemplate<Track>("PART_Track");
        track.Thumb.MouseEnter += (o, args) => ThumbMouseEnter?.Invoke(o, args);
    }

    protected override void OnThumbDragStarted(DragStartedEventArgs e)
    {
        base.OnThumbDragStarted(e);
        DragStarted?.Invoke(this, e);
    }

    protected override void OnThumbDragCompleted(DragCompletedEventArgs e)
    {
        base.OnThumbDragCompleted(e);
        DragCompleted?.Invoke(this, e);
    }
}

Every 250ms a timer event is being fired to synchronize the slider value with the MediaElement value, the binding cant do that because the MediaElement doesn't have a DependencyProperty responsible for the Position, nor there is INotifyPropertyChanged event that is being fired.
The eventhandler of the System.Timers.Timer:
Application.Current.Dispatcher.Invoke(() => sMovieSkipSlider.Value =
    ViewModel.CurrentMediaPlayer.MediaElement.Position);

What could be causing the problem and how can I fix it?
Comment: @glenebob Removing the binding causes problems such as whenever the slider's thumb is being dragged, the media element is not being updated.
Comment: Sorry, I was mistaken. Two way bindings are not removed by a direct property update as I suggested.
Comment: Since, both the slider value and the media element position are in TimeSpan, why is the converter required?
Comment: Also, I would suggest to set the value of Media Element position in the drag completed event and remove the binding all together.
Comment: @ShivaniKatukota see for your first comment [this](https://stackoverflow.com/q/50116192/5687778).
Comment: @Deadzone Did the second comment work?
Comment: @ShivaniKatukota it will work, but while dragging the media won't update and user won't know where is he dragging
Comment: @Deadzone, I believe the `ConvertBack` method of your `SecondsToTimeSpanConverter` is wrong. This might be unrelated to your problem but I still wanted to point this out. Shouldn't this method return a **double**?
Answer: I don't really see the need for creating a custom slider. I believe this could be achieved by using the regular slider.
You stated the following:

Every 250ms a timer event is being fired to synchronize the slider value with the MediaElement value, the binding cant do that because the MediaElement doesn't have a DependencyProperty responsible for the Position, nor there is INotifyPropertyChanged event that is being fired.

Then there is no point of using a binding, you can simply handle the MouseLeftButtonUpEventof your slider and set the Position of your MediaElement that way.
Perhaps a timer that updates every 250ms might also be too fast, of course this depends on your requirements. Like if you're planning to use this with high precision. But if you just want a simple player then an update every 1s should be more than enough.
Here is an example of initializing the timer that updates your slider:
private TimeSpan TotalTime;
private DispatcherTimer MediaTimer;

private void CurrentMediaPlayer_MediaOpened(object sender, RoutedEventArgs e)
{
    TotalTime = CurrentMediaPlayer.MediaElement.NaturalDuration.TimeSpan;
    MediaTimer = new DispatcherTimer();

    MediaTimer.Interval = TimeSpan.FromSeconds(1);
    //If 1 second is too slow, change this to: TimeSpan.FromMilliseconds(250)
    MediaTimer.Tick += new EventHandler(MediaTimer_Tick);
    MediaTimer.Start();
}

private void MediaTimer_Tick(object sender, EventArgs e)
{
    if (CurrentMediaPlayer.MediaElement.NaturalDuration.TimeSpan.TotalSeconds > 0)
    {
        if (TotalTime.TotalSeconds > 0)
        {
            sMovieSkipSlider.Value = CurrentMediaPlayer.MediaElement.Position.TotalSeconds /
                                   TotalTime.TotalSeconds;
        }
    }
}

Add the MouseLeftButtonUpEventHandler to your slider:
sMovieSkipSlider.AddHandler(MouseLeftButtonUpEvent, new MouseButtonEventHandler(sMovieSkipSlider_MouseLeftButtonUp), true);

Here is an example of handling the event to update the Position  of your MediaElement:
private void sMovieSkipSlider_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    if (TotalTime.TotalSeconds > 0)
    {
        CurrentMediaPlayer.MediaElement.Position = TimeSpan.FromSeconds(sMovieSkipSlider.Value * TotalTime.TotalSeconds);
    }
}

Comment: I've probabaly messed up some of your MVVM setup, but this should at least push you in the right direction. You can always work with the DataContext property of your view where needed.
Comment: I think handling the MouseLeftButtonUp will have the same problem as removing the binding. While dragging the media won't update and user won't know where is he dragging!
Answer: Have you tried setting a delay for the binding?
Value="{Binding CurrentMediaPlayer.MediaElement.Position, Mode=TwoWay, Converter={converters:SecondsToTimeSpanConverter}, Delay=50}"

Maybe you have to play a bit around with different values.
Answer: Doesn't setting the Value cause the binding to trigger and update the media player's position, but since a few milliseconds elapse until all this happens the media player jumps back just a little bit causing stutter? I would take steps to not update the media player position during the synchronization.


Access non-path WSLENV variable from WSL environment

Question: I'm new to WSL as a development environment, and I'm trying to set some environment variable to begin working on an open source project. In this case, a domain and secret key. I've followed the steps mentioned here https://devblogs.microsoft.com/commandline/share-environment-vars-between-wsl-and-windows/ and here https://medium.com/@kevinv92/how-to-use-wslenv-to-share-environment-variables-between-windows-and-wsl-c06099d5b901 and this is output:
Microsoft Windows [Version 10.0.19041.388]
(c) 2020 Microsoft Corporation. All rights reserved.

C:\Users\kyles>wsl -l -v
  NAME            STATE           VERSION
* Ubuntu-20.04    Running         2

C:\Users\kyles>echo %WSLENV%
MVC_FIREBASE_API_KEY/p:MVC_FIREBASE_DOMAIN/p

C:\Users\kyles>echo %MVC_FIREBASE_DOMAIN%
minimum-viable-ceremonies-dev

C:\Users\kyles>wsl
kylesnowschwartz@DESKTOP-VN55S9F:/mnt/c/Users/kyles$ echo $WSLENV
MVC_FIREBASE_API_KEY/p:MVC_FIREBASE_DOMAIN/p
kylesnowschwartz@DESKTOP-VN55S9F:/mnt/c/Users/kyles$ echo $MVC_FIREBASE_DOMAIN

Nothing is output when for the environment variable, as I am expecting. I would appreciate any help in understanding what I don't understand!
Answer: The Microsoft blog entry is a bit confusing. Fortunately your problem is quite simple: You are using path translation option /p but your environment variable is not a path!
Passing environment variable from Windows to WSL, use /u option:
Microsoft Windows [Version 10.0.19044.1706]
(c) Microsoft Corporation. All rights reserved.

C:\Users\arttu>set MVC_FIREBASE_DOMAIN=minimum-viable-ceremonies-dev

C:\Users\arttu>set WSLENV=%WSLENV%:MVC_FIREBASE_DOMAIN/u

C:\Users\arttu>wsl

$ echo $MVC_FIREBASE_DOMAIN
minimum-viable-ceremonies-dev


Auditing in linux

Question: I am trying to setup a robust auditing  mechanism on my centos 6.x boxes. I tried and tested various  auditing tools like

auditd
aide
psacct

But none is full filling my requirement. My requirement is quite simple and I know one auditing system will not serve all and i may have to use different audit systems all together. I want to

Monitor all the commands run by a user

psacct is doing this perfectly but it tells only command run by the user and not the arguments passed to the command. ie
if user runs vim /erc/passwd, then lastcomm  <username> will only tell that vim command was run but do not tell which file was actually edited.
And auditd tells that e.g. the vim command was run and a particular file was edited but do not tell who edited the file.
Suppose I run a command as a sudo user, then it won't tell me which user edited the particular file if there are 10 sudo users as gid and uid will be of superuser in output of the command:
time->Sat Jun 20 15:52:45 2015
type=PATH msg=audit(1434795765.057:54685): item=4 name="/etc/passwd" inode=152790 dev=fd:00 mode=0100644 ouid=0 ogid=0 rdev=00:00 nametype=CREATE
type=PATH msg=audit(1434795765.057:54685): item=3 name="/etc/passwd" inode=152786 dev=fd:00 mode=0100644 ouid=0 ogid=0 rdev=00:00 nametype=DELETE
type=PATH msg=audit(1434795765.057:54685): item=2 name="/etc/passwd+" inode=152790 dev=fd:00 mode=0100644 ouid=0 ogid=0 rdev=00:00 nametype=DELETE
type=PATH msg=audit(1434795765.057:54685): item=1 name="/etc/" inode=130562 dev=fd:00 mode=040755 ouid=0 ogid=0 rdev=00:00 nametype=PARENT
type=PATH msg=audit(1434795765.057:54685): item=0 name="/etc/" inode=130562 dev=fd:00 mode=040755 ouid=0 ogid=0 rdev=00:00 nametype=PARENT
type=CWD msg=audit(1434795765.057:54685):  cwd="/etc"
type=SYSCALL msg=audit(1434795765.057:54685): arch=c000003e syscall=82 success=yes exit=0 a0=7fffba897300 a1=7fd7cc94ece0 a2=7fffba8971c0 a3=0 items=5 ppid=14041 pid=14043 auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts1 ses=8494 comm="useradd" exe="/usr/sbin/useradd" key=(null)

Would Like to track actual changes made to the file

The aide tool tells that a file has been modified, but how can I get details of the content that is actually modified and which user did the modification?
Comment: You're asking a couple of different questions here. First user auditing through what commands are being run. I'm pretty sure we can do that with auditd but I'll have to do some research. The other question is a file auditing through a FIM.  I'd split these out for better results. Also check out pur sister site for Information Security folks at http://security. stackexchange.com
Comment: Commands call other commands. When a user runs a program or a script, often times, dozens of separate processes may run before the original command exits. Is it your desire to record all of these, or just the initial parent process?
Comment: @ScottPack yes i want to do both record file changes ans all commands run by a user.
Comment: @JeffG i  i am interested only in parent process.
Answer: You can implement this using auditd and a pam module. You need to load the pam module pam_tty_audit under session like
session required pam_tty_audit.so disable=testuser1 enable=testuser,root

in both /etc/pam.d/password-auth and /etc/pam.d/system-auth files.
and then the key stroke  of the enabled users will get logged into the audit log.
When generating the audit report use -i option with aureport to exactly get the username.
eg: aureport --tty -i  -ts today
One drawback of this method is all keystrokes will get logged including the passwords entered in the terminal.
For tracking file changed aide can be used. This uses a checksum verification method. But exact line changed in the file is not traceable.
Comment: Hi Bhuvanesh ! It is really inspiring! However, I got empty records with a trial on logging root activities with `session     required      pam_tty_audit.so enable=root` line in the two files you mentioned. What else should be done to enact the logging? I have already executed `service auditd restart`.

Auditing in linux


How to get-content with username & password

Question: How do I get-content from a text file from multiple remote PCs with username & password?
I want data from WSUS.txt from client computer and I have the IP address of the client computer on S.txt.  I wrote the Powershell script below, but it does not work:
<code>$computers = Get-Content -Path .\S.txt

$Credential= Get-Credential -Credential Whatusername?

foreach ($svr in $Computers) {
     Get-Content \\$svr\Upgrade\CUSTOMER-INV\WSUS.TXT -Credential $Credential >> d:\WSUS.log
}
</code>
Comment: What error message, if any, do you get? If you don't get an error message, what actually happens?
Comment: Is \\ServerX\Upgrade\CUSTOMER-INV\WSUS.TXT a valid path, meaning "\\ServerX\Upgrade" is a valid share?
Answer: Its not super pretty but you can use net use \server\ipc$ to authenticate if you dont want to use the current security context.
This only works if you have not already authenticated with the server (ie tried to access it with \\server\something)
so something like this:
<code>foreach ($svr in $Computers) {
     net use \\$server\ipc$ /user:$server\$user $password
     Get-Content \\$svr\Upgrade\CUSTOMER-INV\WSUS.TXT -Credential $Credential >> d:\WSUS.log
}
</code>


Negative notes in sheet music

Question: I am new in playing a violin, and in the recent sheet music that I got, there was a number over the music. Normally these are figuring charts, but the numbers were negative, that is, there was a minus sign in front of the numbers, for example -2, -3 and so on. I am confused on what they mean.
Answer: My guess is that these aren't negatives, but just dashes used to show that a shift is necessary to use the suggested fingering. For instance, maybe you are playing an F# on the E string and then need to play a C a tritone higher. I might give the fingering for the C as –2 to indicate that you should use the second finger, but that this will require a position shift. As always with such fingerings, it is optional, but it is generally worth considering.
Comment: Anecdote: I've seen these in some jazz guitar books used, as you've mentioned, as position shift indicators. Not sure how I feel about them, but I suppose enough people like them for them to have gained enough popularity to appear on our site! :)
Comment: If so, then just MHO that it's more of a distraction than a help.  Usually the choice of string is obvious from the indicated finger (plus the general set of notes before and after)

Negative notes in sheet music


identifer "Month" is undefined

Question: I'm trying to initialize a Date object using one of the enumerator Month variables, but the compiler is giving the error

identifier "Month" is undefined

Does anyone know what the problem is?
#include<iostream>
#include<string>

using namespace std;

class Year {
    static const int max = 1800;
    static const int min = 2200;
public:
    class Invalid {} ;
    Year(int x) : y(x){ if ( x < min || x >= max ) throw Invalid(); }
    int year() { return y; }
private:
    int y;
};

class Date {
private:
    Year y;
    Month m;  // ERROR HERE
    int d;
public:
    Date( Month m, int d, Year y) // ERROR HERE AT Mont m
        :m(m), d(d), y(y) {}
    void add_day(int n);
    int month() {return m; }
    int day() { return d; }
    Year year() { return y; }
    enum Month { jan =1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };
};

Date today(Date::sep, 24, Year(1989));

void main() {
    cout << today.day() << endl << today.month() << endl << today.year() << endl;
}

Comment: u r using `Month` enum before declaring it.
Comment: The compiler also gave the exact line and column where `Month` was found. Why didn't you include that? (Not that it mattered, we lot are good at crystal ball reading. ;-) ) As for sequence mattering... C/C++ were designed in a way that allows *single-pass* compilation. This requires "declaration before use", inside of classes as well as outside.
Comment: @Devsolar: as Matt McNabb mentions in his answer, inline member function bodies can use class members that haven't been declared yet. In fact `Year::year()` in the example does exactly that. So I can understand that this might be a confusing detail.
Comment: Where's Month declaration? I can see it after its use, not before...
Comment: @Rakibul Thanks, for some reason I thought it didn't matter what order you put things in in a class.
Comment: @MichaelBurr: Gee... yes, I never actually thought about that. :-D
Answer: You have to have enum Month before you can go Month m;.  It doesn't work quite like inline function bodies which do have access to other variables of the class that haven't been defined yet.
One option is just to move the whole definition up to before the private variables (or put the private variables at the end).
In C++11 you can also do:
class Date
{
    enum Month : int;    // forward-declaration; requires type spec
...
    enum Month : int { jan = 1, .....
};

Note that your cout line in main also needs work. today.year() cannot be sent to cout as it stands.
One options is to change it to today.year().year(). This is ungainly; I'd suggest that you change within class Year the function int year() to have a better name, e.g. year_as_int() const.
Also you can define a stream insertion operator (this is at file scope, not inside the class definition):
std::ostream &operator<<(std::ostream &os, Year const &y)
{
    return os << y.year_as_int();
}

Also, all member functions which do not modify the member variables should have a const qualifier.  Then they can be called from objects you only have a const reference to, as in my example here.
Answer: One way to fix it is to shift the definition of the enum Month to a location before the first usage:
#include <iostream>

using namespace std;

class Year {
    static const int max = 2200;
    static const int min = 1800;
public:
    class Invalid {} ;
    Year(int x) :
            y(x)
    {
        if ( x < min || x >= max ) throw Invalid();
    }
    int year() { return y; }
private:
    int y;
};

class Date {
public:
    enum Month { jan =1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };
private:
    Year y;
    Month m;  // ERROR HERE
    int d;
public:
    Date( Month m, int d, Year y) // ERROR HERE AT Mont m
        :m(m), d(d), y(y) {}
    void add_day(int n);
    int month() {return m; }
    int day() { return d; }
    Year year() { return y; }
};

int main() {
    Date today(Date::sep, 24, Year(1989));

    cout << today.day() << endl << today.month() << endl << today.year().year() << endl;
}

/*
    Local Variables:
    compile-command: "g++ -g test.cc"
    End:
 */

Note, that with your construction you need today.year().year() in the output or define << for Year. Furthermore, in Year the values for min and max were swapped.

identifer "Month" is undefined


JQuery Autocomplete Select Function Only Completes One Item

Question: I am using a jquery autocomplete function to grab items from a database and replace fields. Using the select function and some AJAX it replaces the current info with the needed info.
However, I need it to run twice, and the autocomplete seems to only run the last line in the select function:
 $(document).ready(function($){
    $('#client_name').autocomplete({
    source:'suggest_client.php',
    minLength:2,
    select: function (event, ui) {
        $("#client_name").val(ui.item.label); // display the selected text
        $("#client_nameID").val(ui.item.value); // save selected id to hidden input
        var clientValue = ui.item.value;
        getAjax(clientValue, 'client_replace', 'client_info.php?client_id=', "");
        getAjax(clientValue, 'client_contact_div', 'get_contact.php?client_key=', "");
        return false;
        }
    });
});

Code for getAjax:
function getAjax(seek, getId, destUrl, reset) {
    if (seek=="") {
        document.getElementById(getId).innerHTML=reset;
        return;
    }
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById(getId).innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET",destUrl+seek,true);
    xmlhttp.send();
}

Comment: I get the feeling this is a problem with the `getAjax()` function. Can you post its source?
Comment: Added the code for getAjax(), it works for several other purposes, but I have not tried to call it twice as in the above.
Answer: The problem is with the getAjax() function. At the very beginning of the function, you need to declare the xmlhttp variable:
function getAjax(seek, getId, destUrl, reset) {
    var xmlhttp;
    /* ... */
}

Explanation
The problem is with variable scope. In the getAjax() function, you assign a value to the xmlhttp variable without declaring it first (using the var keyword). According to MDN's documentation on the var keyword:

Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed.

So every time getAjax() is called, you're assigning a value (the XMLHttpRequest or ActiveXObject) to xmlhttp, which -- since it's never declared -- is treated as a global variable. So when that second call to getAjax() runs in the last line of your select callback, it's overwriting the xmlhttp variable from the first call before that first request has a chance to complete.
If you declare the variable with var xmlhttp at the beginning of your function, then every call to getAjax() will have its own instance of the xmlhttp variable, preventing it from being treated as a global variable and overwritten.
Comment: Nailed it. I owe you a beer. Thank you very much.


When will two fields have same ramification index over $\mathbb{Q}_p$

Question: My purpose is to decide whether two different field extensions $K_1, K_2$ of $\mathbb Q_p$ have same ramification index or not, provided $[K_1:\mathbb Q_p]=[K_2: \mathbb{Q}_p]$ and $K_2=\mathbb{Q}_p(\sqrt[n]{-p})$ for some natural number $n$.
For example, consider two field extensions $K_1:=\mathbb{Q}_3(\sqrt[9]{1})$ and $K_2:=\mathbb{Q}_3(\sqrt[6]{-3})$ over the $3$-adic field $\mathbb Q_3$.
Note that $K_1$ is cyclotomic field with degree of extension $\varphi(9)=6$ and it is totally ramified since $9=3^2$.
In other word, $K_1/\mathbb{Q}_p$ has ramification index $6$.
Now consider the field extension $K_2$. The minimal polynomial of $\sqrt[6]{-3}$ is $x^6+3$, which is Eisenstein at prime $p=3$. So it is also totally ramified.
Therefore, the ramification index of $K_2/\mathbb Q_3$ is also $6$.
So I have mentioned two field extensions $K_1$ and $K_2$ of $\mathbb Q_3$ which are different but both has same degree of extension and same ramification index.
Certainly, the information that the degree of extensions of $K_1$ and $K_2$, being equal, was not enough for conclude their ramification index same.
So the question: Why $K_1$ and $K_2$ has same ramification index ? What made it possible here ? I mean, was there any general criterion of looking at the ramification index without doing calculations as I did here ?
More generally,

how to decide whether two different fields extensions $K_1, K_2$ of $\mathbb Q_p$ have same ramification index or not ?

provided that we know $[K_1: \mathbb{Q}_p]=[K_2: \mathbb{Q}_p]$ and $K_2$ is always of the form $\mathbb{Q}_p(\sqrt[n]{-p})$.
So what is the general criteria that their ramification inde will be same ? What might be the possible forms of the other field $K_1$ ?
Thanks
Answer: Since @PaulGarrett has given me the prompt, I'll say something about higher ramification. This is a way of examining how close to each other the various roots $\lambda,\lambda'$ of the defining equation $f=0$ may be, when you choose $f$ so that one root $\lambda$ generates the ring of integers of the extension field $K$, $\mathcal O_K=\Bbb Z_p[\lambda]$. In the case of an unramified extension, as I recall, the differences between two roots will all be units. It's the totally ramified extensions where higher ramification theory comes into its own.
Then let $\lambda$ be a uniformizing element of $\mathcal O_K$, $K$ totally ramified over $k$, with $v_k(\lambda)=1/e$ where $e$ is the ramification index (and the degree of the extension). We take $v_k$ normalized so that $v_k(k^\times)=\Bbb Z$. And let $f(x)$ be the minimal polynomial for $\lambda$, necessarily an Eisenstein polynomial over $\mathcal O_k$. Then put $g(x)=f(x+\lambda)$, whose roots are the quantities $\lambda'-\lambda$. We want a good way of measuring the size(s) of the roots of $g$.
Well, you measure the size of the roots of a polynomial with the Newton Polygon, but if you encode the same information in a kind of dual convex body that's sometimes called the Newton Copolygon, you get something a little more useful. You can stretch this out horizontally by a factor of $e$ and consider the boundary to be the graph of a function, and thereby get the Hassse-Herbrand Transition Function $\psi^K_k$, which also has the wonderful property of being functorial: if $L\supset K\supset k$ is a chain of totally ramified extensions, then $\psi^L_k=\psi^K_k\circ\psi^L_K$.
Note that there are no Galois groups in this story. We can apply it to the two extensions mentioned at the beginning, $\Bbb Q_3(\zeta_9)$ and $\Bbb Q_3((-3)^{1/6})$. The two uniformizers are, respectively, $\tau=\zeta_9-1$ and $\pi=(-3)^{1/6}$. The minimal polynomial for $\zeta_9$ is $\frac{x^9-1}{x^3-1}$, so the minimal polynomial for $\tau$ is $f_1(x)=\frac{(x+1)^9-1}{(x+1)^3-1}$. The numerator and denominator have no constant, while the first-degree coefficient upstairs is $9$, downstairs is $3$, thus the quotient, known to be a polynomial, has constant coefficient $9/3=3$. Looking at the quotient modulo $3$, you see that there, the quotient is $x^6$. Thus $f_1$ is Eisenstein, which we already knew, didn't we?
Forming $g_1(x)=f_1(x+\tau)$, as above, we need to look closely at $g_1$ and its Newton Polygon (and Copolygon). It's somewhat of a pain to do the computation this way, but you find that the $v_p$-value of the first coefficient is $3/2$, the value of the third is $1/2$ and of the sixth is zero. This gives vertices of the Polygon at $(1,3/2)$, $(3,1/2)$, and $(6,0)$. The Copolygon (in the Cartesian $(\xi,\eta)$-plane) is described by the corresponding inequalities $\eta\le\xi+3/2$, $\eta\le3\xi+1/2$, and $\eta\le6\xi$. The vertices are where two half-planes' boundaries intersect, namely at $(1/6,1)$ and $(1/2,2)$. Stretch by a factor of six to get the points $(1,1)$ and $(3,2)$ (the "breaks" in traditional terminology), exactly what you'll find in Serre's Corps Locaux, except that my coordinatization of the Cartesian plane is off from Serre's by one in each direction.
If you do the corresponding computation for $\sqrt[6]{-3}$, you'll see that it's much less messy, giving $g_2(x)=(x+\pi)^6+3$ with the Polygon's vertices at $(1,11/6)$, $(3,1/2)$ and $(6,0)$. The Copolygon is defined by the corresponding inequalities $\eta\le\xi+11/6$, $\eta\le3\xi+1/2$, and $\eta\le6\xi$. Here, the half-planes' boundaries intersect at $(1/6,1)$
and $(2/3,5/2)$. Stretching by six gives the vertices of the polygonal Hasse-Herbrand function at $(1,1)$ and $(4,5/2)$. Here, the "breaks" are not at integer points, which is fine, because the Galois group of the normal closure of our field is not abelian.
Comment: Thank you Professor @Lubin
Comment: Great! Very illuminating! Thanks! :)
Answer: For abelian (Galois) extensions, understanding ramification is part of "local classfield theory". As a special case of that local classfield theory, the cyclic degree $n$ extensions $k$ are in natural bijection with the subgroups of index $n$ of $\mathbb Q^\times_p$, with Galois group isomorphic to the cyclic quotients $\mathbb Q_p^\times/N_{k/\mathbb Q^\times_p}(k^\times)$. In that case, the ramification degree is the index of the norms from the units of the bigger field in the units $\mathbb Z_p^\times$. So, in that special case, if we can "understand" the finite-index subgroups of $\mathbb Z_p^\times$ with cyclic quotient, we "understand" the ramifications of cyclic extensions.
Of course, the ground field doesn't have to be $\mathbb Q_p$, and abelian extensions are treatable as part of classfield theory.
Comment: The ramification filtrations of those two extensions are different. The *really* interesting conundrum is to distinguish between two extensions with the same (for instance) Hasse-Herbrand transition function.
Comment: Some of the audience here would be quite interested to hear more from Professor @lubin about further details and examples! :)  I myself am just an amateur at algebraic number theory, an "end user"... :)
Comment: Ramification degree _is_ an isomorphism invariant of local field extensions ... Your example is sort of a contrapositive, that two not-isomorphic field extensions of a common base field ($\mathbb Q_p$) have the same ramification _index_. Further, the ramification filtrations (upper and lower indices?) are preserved under isomorphism, since they, too, are instrinsically defined.
Comment: Oop, typo, let me repair it. :)
Comment: Thanks a lot. Does the isomorphism between the fields $K_1$ and $K_2$ preserve the ramification filtrations of their corresponding Galois groups ? In simple word, is ramification degree an invariant under isomorphism of fields ? I think it is not true as in my example, the two fields are not isomorphic but their ramification index is same. So the opposite question is-if two fields  are isomorphic, can their ramification index be unequal ?
Comment: thank you very much. Anyway, in the 3rd line of your answer, is it $\mathbb Q^p$ or  $\mathbb Q_p$ ?
Comment: do you have any working example in mind or helpful reference ?
Comment: Your quotient groups should involve $\mathbf Q_p$, not $\mathbf Q$.
Comment: @KCd, oops, thanks. :)


Anomaly Detection over multivariate categorical and numerical predictors

Question: I am trying to implement Anomaly Detection over a multivariate dataset having categorical and numerical predictors.
If we consider the below sample records, product_type, company_type and currency are categorical variables(Nominal, to be precise), whereas price is a numerical variable.
My model is able to identify the anomaly in the price for product_id=10 because the price range for different products is between 10-500 EUR for given combination of (product-type, company-type, price, currency).
But it is not able to identify anomalies for product_id=5 or product_id=8 as they have unusual currency or product type.

I have tried different approaches like Multiple Correspondance Analysis(MCA) for categorical encoding and dimensionality reduction along with One class-SVM and Isolation Forest. I have even tried deep learning approaches using Autoencoders. But none of the models is able to identify anomalies in categorical predictor variables.
I have even referred other answers like:
Anomaly Detection with Dummy Features (and other Discrete/Categorical Features)
and
Outlier detection with data (which has categorical and numeric variables) with R
but could not resolve my problem.
I have recently started data science journey and would really appreciate any help.
Answer: It depends of what you call an outlier. If for you, an outlier for categorical data is a category that appear less than, say, 1% of the time then there is a really easy algorithm to detect those: just count the number of values for each category (for example with pandas value_counts) and threshold this to find which category are abnormal in your sense. This type of outliers is not detected by one class svm or isolation forest because they are not considered abnormally large data, in short algorithms will consider that your dataset is unbalanced but it will not detect YEN as abnormal in most cases.


Is there a way to see free mem history on redhat?

Question: Is there a built-in way of checking free mem history or any other performance stat on redhat 6.5--e.g., the past hour, days, weeks etc..
On other systems, I have previously used orca which creates logs of performance stats.
If there is no built-in, is there a recommended way of doing it.
Comment: The recommended way is to use a monitoring software for it.
Comment: Such performance history recording isn't considered a requirement for base OS, therefore just a few or maybe no OS has that kind of system built-in. Also, product recommendations are off-topic here.
Comment: Thanks Tero. I was not asking for a product recommendation. I asked if there was a recommended way of doing it for redhat.
Answer: There isn't one that is always there. Such packages are in the default repos for engineers to set up, such as sar, but are not installed in a default installation.
Answer: yum install sysstat

This will add sar,sadf,sa1,sa2 utilities and default cron.
[root@node-2 cron.d]# pwd
/etc/cron.d
[root@node-2 cron.d]# cat sysstat
# Run system activity accounting tool every 10 minutes
*/10 * * * * root /usr/lib64/sa/sa1 1 1
# 0 * * * * root /usr/lib64/sa/sa1 600 6 &
# Generate a daily summary of process accounting at 23:53
53 23 * * * root /usr/lib64/sa/sa2 -A

By default sa1 will run every 10 minutes and will collect system performance data.
Once you have sar - you can analyze historical system performance like this.
Example 1. RAM stats for day 27 of the current month

sadf -d /var/log/sa/sa27 -t -- -r

Example 2. CPU stats for day 27 of the current month

sadf -d /var/log/sa/sa27 -t -- -u

Example 3. IO stats

sadf -d /var/log/sa/sa27 -t -- -b

Comment: needless to say - you won't be able to go and analyze performance data prior to date sysstat package was installed. Once it's installed - it starts to collect perf data.


Proof or Counterexample for $A - \lfloor A/B \rfloor - \lceil A/B \rceil \leq \lfloor A/B \rfloor \times (A+1)$

Question: Motivated by this post and specially suggested by @Clement Yung:
Let $A$ and $B$ are strictly positive integers such that $A \geq B$.
Question: How to prove or make a counterexample for the following statement.
$$
\boxed{A - \lfloor A/B \rfloor - \lceil A/B \rceil \leq \lfloor A/B \rfloor \times (A+1)}
$$
Thanks in advance.
Answer: Let $$\left\lfloor\frac AB\right\rfloor=k\ge1.$$
Then
$$A-k-\left\lceil\frac AB\right\rceil\le A-2k\le k(A+1).$$
is certainly true.
Comment: Now, it's clear. Thanks


POST Caspio API

Question: I'm trying to post to Caspio's API - I've been able to perform POST & GET requests fine to get my token and retrieve data in XML from Caspio although having problems using the POST method to get data back into Caspio. In the example below I've encoded my body as {"First_Name":"John"}.
Currently I'm getting 415 Unsupported Media Type - The server cannot service the request because the media type is unsupported.
var requestPost = new XMLHttpRequest();

 function PostWebAPI() {
       requestPost.open("POST", "https://c2ezh542.caspio.com/rest/v1/tables/Patient/rows", true);
       requestPost.setRequestHeader("Authorization", "Bearer " + token_);
       requestPost.send("%7B%22First_Name%22%3A%22John%22%7D");

The table operations specify the following:
POST Table Rows
/tables/<name>/rows

Method: POST
Description: Inserts a row into the table
Parameters:
URL, Body, required – {"field1″:"value1″,"field2″:"value2"}
Result:
201 Created (if successful) + Location Header contains URL to
inserted row
Answer: Use Following
var params= {"field1″:"value1″,"field2″:"value2"};
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.send(JSON.stringify(params));

request.onreadystatechange = function () {`enter code here`
if (request.readyState == 4 && request.status== 201) {
     var obj = JSON.parse(response);
         }
}

}

POST Caspio API


Retornar para main() após usar método start()

Question: Após executar o comando gerenciador.start(), meu programa não retorna para a função main, e não imprime a mensagem acabou. Ele simplesmente executa o comando que falei. Alguém sabe por que isso acontece?
  public class Principal
{
    private static long startTime = System.currentTimeMillis();

    public static void main(String[] args)
    {
        Fila sharedLine = new Fila();

        Elevador elev = new Elevador(sharedLine);
        Esquiador gerenciador = new Esquiador(sharedLine);

        gerenciador.start();
        //elev.start();
        System.out.println("acabou");
        long endTime = System.currentTimeMillis();
        System.out.println("It took " + (int)(((endTime - startTime)/1000)/60) + " milliseconds");
    }
}

public class Esquiador extends Thread
{
     Fila sharedLine;
     static boolean todosEntraram = false;
    //String filaQuePertenco;
    //int idEsquiador;

    public Esquiador(Fila fila)
    {
        super("Esquiador");
        sharedLine = fila;
        //filaQuePertenco = filaQ;
        //idEsquiador=id;

    }

    public void run()
    {

        for(int i = 0; i < 30; i++)
        {

            try
             {
                System.out.println("O esquiador está dormindo.");
                Thread.sleep(500);
             }

            catch (InterruptedException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Esquiadores esquis = new Esquiadores(i);

            //System.out.println("O esquiador "+ esquis.idEsquiador+ " entrou em seu 'run'");
            //while(true)
            //{
                    //política do esquiador para decidir em qual fila ele irá entrar

                    //printando o tamanho de cada fila.
                    System.out.println("O esquiador "+esquis.idEsquiador+" chegou para ingressar numa fila.");
                    System.out.println("Tamanho LS"+sharedLine.elementosLS.size());
                    System.out.println("Tamanho RS"+sharedLine.elementosRS.size());
                    System.out.println("Tamanho LT"+sharedLine.elementosLT.size());
                    System.out.println("Tamanho RT"+sharedLine.elementosRT.size());
                    System.out.println("Esquiador operando ...");

                    if(sharedLine.elementosLS.size()<2*sharedLine.elementosLT.size() && sharedLine.elementosLS.size()<2*sharedLine.elementosRT.size() && sharedLine.elementosLS.size()<sharedLine.elementosRS.size())
                    {
                        //this.filaQuePertenco = "LS";
                        //System.out.println("add ls");
                        sharedLine.adicionaFilaLS(esquis);

                        //printando elementos da fila LS

                    }

                    else if(sharedLine.elementosRS.size()<2*sharedLine.elementosLT.size() && sharedLine.elementosRS.size()<2*sharedLine.elementosRT.size() && sharedLine.elementosRS.size()<=sharedLine.elementosLS.size())
                    {
                        //this.filaQuePertenco = "RS";
                        //System.out.println("add rs");
                        sharedLine.adicionaFilaRS(esquis);

                        //printando elementos da fila RS
                    }

                    else if(sharedLine.elementosLT.size()<=sharedLine.elementosRT.size())
                    {
                        //this.filaQuePertenco = "LT";
                        //System.out.println("add lt");
                        sharedLine.adicionaFilaLT(esquis);

                    }

                    else
                    {
                        //this.filaQuePertenco = "RT";
                        //System.out.println("add rt");
                        sharedLine.adicionaFilaRT(esquis);
                    }

                    System.out.println("Situação das filas após a operação:");
                    System.out.println("Tamanho LS"+sharedLine.elementosLS.size());
                    System.out.println("Tamanho RS"+sharedLine.elementosRS.size());
                    System.out.println("Tamanho LT"+sharedLine.elementosLT.size());
                    System.out.println("Tamanho RT"+sharedLine.elementosRT.size());
            //}
        }
        Esquiador.todosEntraram = true;
    }
}

Comment: O que é `gerenciador.start();`???
Comment: Existe uma classe que eu criei e coloquei um método run() nela. Esse gerenciador.start() eu chamei após instanciar um objeto da classe que falei, com o intuito de criar uma thread e executar o método run .
Comment: Coloque ela também na pergunta! [edite](http://pt.stackoverflow.com/posts/170956/edit)
Comment: Pronto, cara. Completei a Classe principal e Adicionei a classe que lhe disse.
Answer: A execução está retornando para o método main, mas diferente do que você imagina. A linha "acabou" é impressa antes da primeira iteração da thread Esquiador.
Acho que você estava esperando que o método start executasse o método run da thread e somente depois voltasse para o main, contudo, o propósito de uma thread é justamente executar em paralelo, ao mesmo tempo.
Neste caso, como você força uma pausa logo no início do for da thread, isto faz com que quase que invariavelmente, o método main termine antes do primeiro sleep.
Para aguardar a finalização de uma thread, use o método join, assim:
gerenciador.start();
gerenciador.join(); //somente continue depois que a thread finalizar

Além deste equívoco, há diversos outros problemas ou pelo menos problemas em potencial:

A exibição do tempo está dividindo o tempo que já está em milissegundos por 1000 e por 60, portanto o resultado será em horas, não ms.
Suas threads parecem estar compartilhando objetos e executando operações sem sincronização e sem mecanismos de proteção contra problemas de concorrência. Em sua implementação final, você deve se assegurar de que cada vez que você altera um objeto, isto ocorra de forma atômica.
É um pouco difícil de entender a intenção exata do código, mas se a ideia original era ter 30 esquiadores, a implementação está completamente errada. Você tem que criar 30 threads e não uma thread contendo um laço executado 30 vezes sequencialmente.
Comment: Isso, a minha intenção era criar 30 esquiadores. No caso , pra eu criar 30 threads, teria que instanciar todas elas na main, por exemplo dentro de um laço de repetição ?
Comment: Minha intenção era criar as 30 threads mesmo. No caso eu teria que instanciá-las na main, com um laço de repetição dentro do qual eu daria 30 starts ?
Comment: @RenandaSilvaAlves Isso mesmo. Coloca elas numa lista, dê 30 starts e DEPOIS 30 joins para esperar todas terminarem.
Comment: Meu amigo, muito obrigado ! Se não fosse esse seu conselho, eu iria tirar um belo 0 amanhã ! Complicado entregar um projeto pra disciplina de programação concorrente sem ter concorrência de threads neh kk. Abraço !!


Understanding statistical significance in variance and correlation?

Question: I have little background in statistics. For a dozen items, I have vectors of ratings for these items.
I have calculated the variance, and Pearson correlation for these items (using numpy). Now I would like to compare them.
My adviser asked me to see if the differences in variance and correlation were "statistically significant" using the 95% rule. How can I do this?
How does this statistical significance relate to scipy's p-value which is returned with Pearson correlation (it makes no mention of "95%")?

The p-value roughly indicates the probability of an uncorrelated system producing >datasets that have a Pearson correlation at least as extreme as the one computed from >these datasets. The p-values are not entirely reliable but are probably reasonable for >a datasets larger than 500 or so.
Answer: If difference between two numbers lies within two standard deviations above or below 0, then this result is not 95% statistically significant. Roughly 95% of normal distribution is covered by two std's, this is where it comes from. That is, if your values have standard deviations of $\sigma_1$ and $\sigma_2$, the joint is $\sigma = \sqrt{\sigma_1^2 + \sigma_2^2}$. If $|x_1 - x_2| > 2\sigma$, they are different with 95% probability. This all assumes normality.
p-value relates to the quality of one variable in predicting (correlating to) another, this is a different thing from what you are asked to do.
Comment: This seems to be mixing up standard deviation and standard error.


the least $m$ such that $a^m\equiv 1 \mod n $ for fixed $a,n$.

Question: Is there any known method for calculating $\lambda_a(n)$ which returns the smallest integer $m$ such that $a^m\equiv 1 \pmod n$ where $\gcd(a,n)=1$ ?
I searched but I found nothing, is there at least an algorithm that does not use bruteforce ?
Note : as you may note this is closely related to Carmichael function, the difference is that $a$ is fixed here.
Comment: @MichaelBurr thanks, I fixed it.
Comment: Depends on how large $n$ is. If we can factor $\lambda(n)$, we can start with that, and calculate $a^{\lambda(n)/p}$ modulo $n$ for the various prime factors of $\lambda(n)$.  As long as we get $1$, keep descending.
Comment: This is an instance of the discrete logarithm. Suffice it to say that finding a discrete logarithm is hard, in the sense that there is no classical algorithm that runs in polynomial time. https://en.wikipedia.org/wiki/Discrete_logarithm#Algorithms
Comment: I'm not looking for a really fast algorithm, just better than trying all $m$ or as I found out trying divisors of $\phi(n)$.
Answer: What you're asking for is known as the order of $a$ modulo $n$. The strongest result I know of is that $\text{ord}_n a\mid \phi(n)$.
Comment: Finding $\phi(n)$ is not easy.
Comment: I agree with vudu, take the pseudo prime numbers for example.
Comment: Right, which is why I specified that it was the strongest result I knew of - it's not incredibly helpful, but I don't think there's anything better.


MySQL - getting from random column but specifying amounts

Question: I would like to do this
  SELECT *
    FROM Thoughts
ORDER BY RAND()
 LIMIT 1 WHERE ups > 5

...but it is returning an error. Do you know an alternative around that? I'm a bit new to MySQL, thanks.
Answer: The order of the clauses is important.  Do
SELECT * FROM Thoughts WHERE ups > 5 ORDER BY RAND() LIMIT 1
Also, in the future, post the error you that you're getting.  "An error" is amazingly unspecific.
Comment: Thank you, and I didn't title it "An error", not sure what you're talking about?
Comment: @someWalri - "..but it is returning an error." ... This should have been the exact error message being returned.  "an error" gives no useful information.
Comment: Ah, sorry about that. Guess I was in a hurry! But thank you, it works now.
Comment: @someWalri - Yup, no worries.  Just trying to help your future questions.
Answer: order by rand() may cause performance issue, instead try to do in following way:
 // what NOT to do:
 $r = mysql_query("SELECT * FROM Thoughts WHERE ups > 5 ORDER BY RAND() LIMIT 1");

 // much better:

 $r = mysql_query("SELECT count(*) FROM Thoughts WHERE ups > 5 ");
 $d = mysql_fetch_row($r);
 $rand = mt_rand(0,$d[0] - 1);

  $r = mysql_query("SELECT * FROM Thoughts WHERE ups > 5  LIMIT $rand, 1");


Mb Mini Player for drupal7

Question: Is there is any modle avaibale for mini player like
<code>http://pupunzi.open-lab.com/mb-jquery-components/jquery-mb-miniaudioplayer/
</code>
I want to implement same player on my website
Comment: This question appears to be off-topic because it is about Implementing a functionality, or a layout seen in a site, for which only a screenshot or a site URL is provided
Answer: These are the players :

MP3 Player
AudioField
jPlayer - I think this is a player that you want.
Comment: I need same look and feel. but jPlayer doesnot provide dat
Comment: Ok. I don't think so you will get same look feel player.

Mb Mini Player for drupal7


if statement and call function for dataframe

Question: I know how to apply an IF condition in Pandas DataFrame. link
However, my question is how to do the following:
if (df[df['col1'] == 0]):
   sys.path.append("/desktop/folder/")
   import self_module as sm
   df = sm.call_function(df)

What I really want to do is when value in col1 equals to 0 then call function call_function().
def call_function(ds):
   ds['new_age'] = (ds['age']* 0.012345678901).round(12)
   return ds

I provide a simple example above for call_function().
Comment: Just curious, why are you reassign `df = sm.call_function(df)`? Do you mean `df = sm.call_function(df[df['col1']== 0])`, that is, to transform only part of the data?
Comment: I want to do the whole data for `call_function()` if `df['col1']== 0`, for those not equal to 0, leave `pd.NaT`.
Answer: Since your function interacts with multiple columns and returns a whole data frame, run conditional logic inside the method:
def call_function(ds):
   ds['new_age'] = np.nan
   ds.loc[ds['col'] == 0, 'new_age'] = ds['age'].mul(0.012345678901).round(12)

   return ds

df = call_function(df)

If you are unable to modify the function, run method on splits of data frame and concat or append together. Any new columns in other split will be have values filled with NAs.
def call_function(ds):
   ds['new_age'] = (ds['age']* 0.012345678901).round(12)
   return ds

df = pd.concat([call_function(df[df['col'] == 0].copy()),
                df[df['col'] != 0].copy()])

Comment: Whoops! `pd.concat` takes a list and not comma-separated objects. See edit.
Comment: I got the error with second way: `TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame"`


Query Professors and Salaries greater than the minimum of specific a department

Question: Given this Schema:
Professor_ID
Professor_Name
Dept_ID
Salary

Dept_ID
Dept_Name

A university uses 2 data tables, Professor and Departments, to store data about its professor and the departments associated with each major.
Write a query to print the name and salary for each professor:

Professor does not work in the Art department
Professor's salary is greater than smallest salary of any professor in the Art department

Sample Output:
Joe Smith  22066

Ken Doe 13411

Eliott Scott 19404

Scott Thompson 48299

I just tried something like this but it doesn't work:
SELECT Professor_ID, Professor_Name, Dept_ID, Salary
FROM Professors p
INNER JOIN Departments d
ON p.Dept_ID = d.Dept_ID
WHERE Dept_Name != 'Art'and Salary > (SELECT MIN(Salary))
   FROM Professors p
   INNER JOIN Departments d
   ON p.Dept_ID = d.Dept_ID
   WHERE Dept_Name = 'Arts and Humanities')

Comment: What have you tried to solve this on your own? Additionally, please specify sample input and expected output data
Comment: Work through [SQL Zoo](https://sqlzoo.net/) tutorial and you will be able to solve such problems.
Comment: 'Greater than smallest salary' is an odd request
Comment: @Strawberry- the problem compares salaries **outside** of Art department to the smallest  **in** Art.
Comment: @NicoHaase I tried using multiple JOINs because from my understanding, we will have to  grab all the salaries and another join to grab all the salaries larger from the Art department? Am I on the right track?
Comment: @Strawberry would I need to use a ON to link the p.department_id = d.department_id?
Answer: This will give you that
The portion of the final query tagged ---1 will give you all the salaries of professors that are not in art department
The portion of the final query tagged ---2 will compare the salaries of the professors selected in the first portion and compare it with the smallest salary of professors in Art using the query below:
select min(Salary) from From Professors p inner join Departments d on p.Dept_ID = d.Dept_ID  where Dept_Name = 'Art'

Final Query
--- 111
    select
    Professor_ID,
    Professor_Name,
    Dept_ID,
    Salary
    From Professors p  inner join Departments d on p.Dept_ID = d.Dept_ID
    where Dept_Name != 'Art'
--- 111
--- 222
    and Salary > (select min(Salary) From Professors p inner join Departments d on p.Dept_ID = d.Dept_ID  where Dept_Name = 'Art')
--- 222

Comment: Right Nico, I edited my answer to add explanations. Hope its better
Comment: @zip Can you explain the double from From in the query tagged 2?
Answer: Select p.name, p.salary from professor p inner join department d on p.department_id = d.id
where d.name <> 'Arts and Humanities' and p.salary > (
select min(p.salary) from professor p inner join department d on p.department_id = d.id
where d.name like '%Arts and Humanities%');


When does $az+b \bar z +c =0$ have one solution?

Question:
When does $az+b \bar z +c =0$ have one solution? $a,b,c \in \mathbb C$

What I did:
I rewrote:
$a=a_1+ia_2$,
$b=b_1+ib_2$,
$c=c_1+ic_2$, and
$z=z_1+iz_2$
Putting everything together we are solving:
$(a_1+ia_2)\times (z_1+iz_2) + (b_1+ib_2) \times (z_1-iz_2) +(c_1+ic_2)=0+i0$
To have one solution I assumed that the $i$ terms will cancel out.
$i(a_2z_1+z_2a_1-b_1iz_2+iz_1b_2)+i(c_2)=0$
$iz_1(a_2+b_2)+iz_2(a_1-b_1)+i(c_2)=0$
So $a_1=b_1$ which means that the real part should be the same?
I'm not sure if I am working correctly.
Thanks.
Answer: Your approach works. Setting $a=a_1+a_2i$, $b=b_1+b_2i$, $c=c_1+c_2i$ and $z=z_1+z_2i$, the equation becomes $(a_1+a_2i)(z_1+z_2i)+(b_1+b_2i)(z_1-z_2i)+(c_1+c_2i)=0$. This we can also write as $(a_1z_1-a_2z_2+b_1z_1+b_2z_2+c_1)+(a_1z_2+a_2z_1-b_1z_2+b_2z_1+c_2)i=0$. We now have an equation of the form $v+wi=0$, where $v,w\in\mathbb{R}$. For a complex number to be $0$, both the real and imaginary part must be zero; we may conclude $$a_1z_1-a_2z_2+b_1z_1+b_2z_2+c_1=0$$ $$a_1z_2+a_2z_1-b_1z_2+b_2z_1+c_2=0$$ Now we have two linear equations in $z_1$ and $z_2$, and we can solve this! We'll first write the equations to $$(a_1+b_1)z_1+(-a_2+b_2)z_2=-c_1$$ $$(a_2+b_2)z_1+(a_1-b_1)z_2=-c_2$$ Making the coefficient for $z_1$ in both equations equal and subtracting, we get $$(b_2^2-a_2^2-a_1^2+b_1^2)z_2=-c_1(a_2+b_2)+c_2(a_1+b_1)$$ Now if $b_2^2-a_2^2-a_1^2+b_1^2=0$, we have either no or infinitely many solutions for $z_2$, neither of which we want. Thus, a property our system must have is $b_1^2+b_2^2\neq a_1^2+a_2^2$, in other words $|a|\neq |b|$ (using the norm/length of the complex numbers). We can now divide by $|b|^2-|a|^2=b_1^2+b_2^2-a_1^2-a_2^2\neq 0$, and we get $$z_1=\frac{c_1(a_1-b_1)-c_2(-a_2+b_2)}{|b|^2-|a|^2}$$ $$z_2=\frac{(a_1+b_1)c_2-(a_2+b_2)c_1}{|b|^2-|a|^2}$$
The conclusion is, the system has exactly one solution only if $|a|\neq |b|$.
Hope this helps you!
Answer: An approach that does not involve using the "expanded" form of a complex number.
Let $w$ be a different solution than $z$, such that:
$aw+b \bar w +c=0$ and
$az + b \bar z + c= 0$.
By subtracting  we get: $a(z-w)+b(\bar z- \bar w)=0$ $⇒ a(z-w)=-b(\bar z- \bar w)$ (1)The conjucate of this expression must also equal zero, thus:
$\bar a(\bar z- \bar w)=-\bar b(z-w)$ (2)
By multyplying (1) and (2) we get:
$a \bar a(z-w)(\bar z- \bar w)=b\bar b (z-w)(\bar z- \bar w) ⇒ a \bar a=b\bar b  $  and finally we get: $|a|=|b|$
Comment: Thank you very much, I must say I much prefer this way.
Answer: It's easier than that. What you wrote is a linear system of two equations (collect the real and imaginary terms into separate equations):
$$\begin{align}
a_1 z_1-a_2 z_2 + b_1 z_1+b_2 z_2&=-c_1\\
a_2 z_1+a_1 z_2 + b_2 z_1-b_1 z_2&=-c_2
\end{align}$$
This has a single solution, if the rank of the matrix on the left is full (its determinant nonzero) - that's basics of linear algebra. If the determinant is zero, then you'll have infinite amount of solutions or no solutions at all. Collecting the terms into a matrix and computing the determinant gives you the condition
$$(a_1+b_1)(a_1-b_1)+(a_2-b_2)(a_2+b_2)\neq 0$$
This can be rewritten as
$$a_1^2-b_1^2+a_2^2-b_2^2\neq 0$$
or
$$|a|\neq |b|$$
Comment: Why would that yield a single solution? Wouldn't there be a multiple of such $a$ and $b$ to make it non-zero?
Comment: Also, is the last line the solution of my problem?


How does setTextIsSelectable prevent the keyboard from appearing?

Question: If I create a simple app with single Activity that contains a single EditText, and I do
EditText editText = (EditText) findViewById(R.id.editText);
editText.setTextIsSelectable(true);

then this prevents the keyboard from appearing (in my tests on Android 5.0 and 7.1). This is what I want, as requested in these questions:

Disable soft-keyboard from EditText but still allow copy/paste?
How to disable Android Soft Keyboard for a particular activity?
Android: Disable soft keyboard at all EditTexts
How to disable keypad popup when on edittext?
Disable keyboard on EditText

The source code is
public void setTextIsSelectable(boolean selectable) {
    if (!selectable && mEditor == null) return; // false is default value with no edit data

    createEditorIfNeeded();
    if (mEditor.mTextIsSelectable == selectable) return;

    mEditor.mTextIsSelectable = selectable;
    setFocusableInTouchMode(selectable);
    setFocusable(selectable);
    setClickable(selectable);
    setLongClickable(selectable);

    // mInputType should already be EditorInfo.TYPE_NULL and mInput should be null

    setMovementMethod(selectable ? ArrowKeyMovementMethod.getInstance() : null);
    setText(mText, selectable ? BufferType.SPANNABLE : BufferType.NORMAL);

    // Called by setText above, but safer in case of future code changes
    mEditor.prepareCursorControllers();
}

But I don't see what about this disables the Input Method from appearing.
Calling the following methods all return true whether I set setTextIsSelectable or not.
editText.isFocusable();             // true
editText.isFocusableInTouchMode();  // true
editText.isClickable();             // true
editText.isLongClickable();         // true

I'm partly asking because I'm curious, but also because I need to disable the system keyboard in my app. I want to understand what is happening so that I can be sure that it is really doing what I think it is doing.
Update
Follow-up question and answer:

How to enable keyboard on touch after disabling it with setTextIsSelectable
Comment: @adneal, So it appears to be because of `!mTextView.isTextSelectable()`. Feel free to add this as an answer. I'm a little curios why making sure that text is not selectable would be a determining factor in showing the keyboard (but that information is not necessary to answer my question).
Comment: [Editor.startSelectionActionModeInternal](https://github.com/android/platform_frameworks_base/blob/master/core/java/android/widget/Editor.java#L2009)
Answer: The keyboard isn't shown when you call TextView.setTextIsSelectable(true) and then select text as a result of Editor.startSelectionActionModeInternal, which checks if TextView.isTextSelectable is false before showing the text selection ActionMode.
    final boolean selectionStarted = mTextActionMode != null;
    if (selectionStarted && !mTextView.isTextSelectable() && mShowSoftInputOnFocus) {
        // Show the IME to be able to replace text, except when selecting non editable text.
        final InputMethodManager imm = InputMethodManager.peekInstance();
        if (imm != null) {
            imm.showSoftInput(mTextView, 0, null);
        }
    }

My guess to why it's implemented this way is probably because the framework team decided they wanted text Editor could predict to be selectable to not jump around the screen as a result of the keyboard moving it around. It was probably just a UI decision. According to git it's been that way since 2012, but the commit doesn't mention anything specifically regarding that implementation.


Single Domain Controller Getting Event Errors 4013, 1844, 2886

Question: I am trying to set up a new domain with only one domain controller.
My DNS role seems to be getting event warning 4013 and my Active Directory role is getting events 2886, 1844, 1463 and 614. I have tried just about everything I could search for and think of for getting rid of these errors. I would appreciate any suggestions.
Comment: It looks like I'm only receiving events 4013 and 2886 now. Any ideas would help.
Answer: For events 4013 you should not see this error at all, I run one domain controller with DNS also.  This is stating that you have an issue with the way DNS was configured.  You only see this if DNS has issues.  As for 2886 it has to do with LDAP you can ignore this event if you wish or you can make the changes to have the warning go away.
Check out this forum for help what 2886.
http://social.technet.microsoft.com/Forums/en-US/winserverDS/thread/57f4048a-2743-453f-93a3-765de01d0ad0
Answer: If I am correct, I will always get these 2 warnings occasionally since it is only a single domain controller on the domain hosting its own DNS service. These warnings do not seem to impede any performance on the server itself.