Post async method invalidate session using Spring Security

Question: I am trying to execute a @async method in a Spring Aplication. The controller even doesn't reach to execute and session is invalidated (I supuse the problem is in chain filtering) and the application is redirected to de login page (result URL: http://localhost:8080/auth/login?logout=true).
There isn't errors on the standar output.
I've intented many options but I haven't found someone that works.
Thanks.
CODE: The following code works when the login do de post on my custom Authentication Provider (/auth/dopost) but not /visor/publishenv who executes a async method.
Spring version: 5.4.2
JDK: OpenJdk 16
Controller:
<code>@Controller
@RequestMapping("/visor")
public class PublishController
{

    @Autowired
    private AmbienteClient ambienteClient;

    @Autowired
    private PublishAsyncService publishService;

    @PostMapping("/publishenv")
    public String publish(PublishData sala, Model model, RedirectAttributes redirectAttributes)
    {
        Ambiente ambiente = ambienteClient.getAmbbienteById(sala.getAmbienteid()).getBody();
        if (ambiente != null)
        {
            try
            {
                publishService.runTransmitStream(ambiente, sala.getPin());
                redirectAttributes.addFlashAttribute("test2", "Publicando " + ambiente.getNombre());
            }
            catch (InterruptedException ex)
            {
                redirectAttributes.addFlashAttribute("test2", "Ha ocurrido un error interno.");
            }
        }
        else
        {
            redirectAttributes.addFlashAttribute("test2", "Error al recuperar el ambiente.");
        }
        return "redirect:/visor/publicar";
    }
}
</code>
Service
<code>@Service
public class PublishAsyncService
{

    @Autowired
    private SalasRepository salasRepo;

    @Autowired
    private VisorParams vParams;

    @Async
    public void runTransmitStream(Ambiente ambiente, int pin) throws InterruptedException
    {
        try
        {
            DBSalas dbsala = null;
            Set<Integer> inUsePorts = new TreeSet<>();
            List<DBSalas> salasActivas = salasRepo.findByEstado(1);
            for (DBSalas dbs : salasActivas)
            {
                if (Objects.equals(dbs.getAmbienteid(), ambiente.getId()))
                {
                    dbsala = dbs;
                }
                inUsePorts.add(dbs.getPuerto());
            }

            if (dbsala == null)
            {
                dbsala = DBSalas.builder()
                        .ambienteid(ambiente.getId())
                        .ambiente(ambiente)
                        .usuarioid("test")
                        .fec_hora_inicio(new Date())
                        .estado(1)
                        .pin(pin)
                        .puerto(Ports.getAvailablePort(inUsePorts))
                        .build();
                dbsala = salasRepo.save(dbsala);
                List<String> lst = new LinkedList<>();
                lst.add(vParams.getCommand());
                lst.add(ambiente.getCamara().getStreamUri(vParams.getInputprotocol()));
                lst.add(":sout=#transcode{vcodec=theo,vb=800,acodec=vorb,ab=128,channels=2,samplerate=44100,scodec=none}:http{mux=ogg,dst=:" + dbsala.getPuerto() + "/" + dbsala.getPin() + "}");
                lst.add(":sout-all");
                lst.add(":sout-keep");

                ProcessBuilder pb = new ProcessBuilder();
                pb.command(lst);
                Process p = pb.start();
                Thread.sleep(3000);
                long pid = p.pid();
                dbsala.setPid(pid);
                dbsala = salasRepo.save(dbsala);
                salasRepo.flush();
                p.waitFor();
            }
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }
}
</code>
Async config
<code>@Configuration
@EnableAsync
public class PublishAsyncConfig implements AsyncConfigurer
{

    @Override
    public Executor getAsyncExecutor()
    {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(5);
        executor.setThreadNamePrefix("visor-");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return new DelegatingSecurityContextAsyncTaskExecutor(executor);
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler()
    {
        return new AsyncUncaughtExceptionHandler()
        {

            @Override
            public void handleUncaughtException(Throwable ex,
                    Method method, Object... params)
            {
                System.out.println("Exception: " + ex.getMessage());
                System.out.println("Method Name: " + method.getName());
                ex.printStackTrace();
            }
        };
    }
}
</code>
Auth config
<code>@Configuration
@EnableWebSecurity
public class AuthenticateConfig extends WebSecurityConfigurerAdapter
{

    @Autowired
    private PortalAuthProvider authProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.authenticationProvider(authProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        String[] publicUriAcces =
        {
            "/", "/auth/**", "/css/**", "/js/**", "/img/**"
        };

        String[] postAcces =
        {
            "/visor/publishenv", "/auth/dologin"
        };

        http.authorizeRequests()
                .antMatchers(publicUriAcces).permitAll()
                .antMatchers(HttpMethod.POST, "/visor/publishenv").hasAnyRole("ADMIN", "USER")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/auth/login")
                .defaultSuccessUrl("/visor/index", true)
                .failureUrl("/auth/login?error=true")
                .loginProcessingUrl("/auth/dologin")
                .permitAll()
                .usernameParameter("Usuario")
                .passwordParameter("SessionId")
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/auth/login?logout=true")
                .and()
                .csrf().disable()
                ;
    }
}
</code>
Comment: and what did your debug logs tell you after you enabled them? because surely you must have read the debug logs before posting on stack overflow.
Answer: Please check that for antmatchers "/visor/publishenv" has permitted to only admin and user make sure you have given correct access.
Comment: Hi Narasimha, thanks for replying. Yes, I've checked  the antmatchers and the user logged have the corrects roles and I've even tried set .permitAll() instead .hasAnyRole() without success
Comment: can you check the redirect url of  **/visor/publicar** in **/publishenv**. you have to give access to that end point also. @NicolásNavarro.


text jumps 1 pixel to the left after hover

Question: I made a jsfiddle and as you can see when you hover the div the text jumps 1 pixel to the left. As far as I can tell this is due to the border, but I'm not sure what to do to fix it. Any ideas?
Here is my code:
<code>#weather {
position: fixed;
top:10px;
right:35px;
transition: 0.5s ease;
cursor: pointer;
padding: 5px;
opacity:0.7;
}

#weather:hover {
opacity: 1;
border-left:1px solid #333;
border-right:1px solid #333;
}
</code>
Answer: CSS:
<code>#weather {
    position: fixed;
    top:10px;
    right:35px;
    transition: 0.5s ease;
    cursor: pointer;
    padding: 5px;
    border-left:1px solid transparent;
    border-right:1px solid transparent;
}
</code>

Since you were introducing the border on that time of hover it was behaving like that so have a border and make it visible only when hover.

JSFiddle
Comment: I suppose that works. Is that a conventional way of fixing such a problem?
Comment: 1px solid **transparent** - good choice +1
Comment: @Jamie You bet. Best solution.
Answer: It is caused by adding 1px borders to the css. to solve the problem, add 1px white borders to begin -- or, I just noticed Kawinesh has a better solution - use 1px solid transparent. +1 to Kawinesh.
<code>#weather {
    position: fixed;
    top:10px;
    right:35px;
    transition: 0.5s ease;
    cursor: pointer;
    padding: 5px;
    border-left:1px solid white;
    border-right:1px solid white;
}
</code>
jsFiddle Demo


Dado selecionado da tag  para passar ao Model C# - MVC

Question: Estou desenvolvendo uma aplicação com HTML e C# nos padrões MVC, e em um dos menus necessito colocar uma lista de opções em qual o usuário irá selecionar o que quer, esses dados são provenientes do banco de dados, então o que eu fiz foi o seguinte:
Criei um Model e lá criei uma lista.
public class NotasFiscaisModel
    {
        public virtual string usuarioLogado { get; set; }
        public virtual string dataUltimoLogin { get; set; }
        public virtual string unidadeInicio { get; set; }
        public virtual string unidadeFim { get; set; }
        public virtual string dataInicial { get; set; }
        public virtual string dataFinal { get; set; }
        public virtual string nome { get; set; }
        public virtual IList<NotasFiscaisModel> autorizados { get; set; }
    }

Com isso, faço um select para popular minha lista de autorizados
     foreach (DataRow linha in autoriz.RetornaAutorizados(LoginController._login.empresa).Rows)
  {
     NotasFiscaisModel nota = new NotasFiscaisModel();
     nota.nome = linha["nome"].ToString();
     _notas.autorizados.Add(nota);
  }

Dentro do HTML, possuo um trecho que lista as opções via tag option:

              <select class="form-control" id="sel1">
              <option>Todos</option>
              @foreach (var obj in Model.autorizados)
              {
              <option>@obj.nome</option>
              }
              </select>

Isso funciona, como mostra o que está acontecendo no print abaixo (nao liguem pros valores, é base de teste kkk):

Agora eu gostaria de pegar qual o usuário selecionou, retornando para meu Model, fazendo o Controller ter acesso a esse conteúdo e poder fazer mais operações, existe uma maneira?
Comment: Defina um name para seu select

Com isso você consegue pegar o valor por meio de uma propriedade do objeto que colocar no parâmetro da action pra onde enviar o form, ou pelo Request, assim: Request.Form["sel1"]).
https://stackoverflow.com/questions/2378338/how-to-get-selected-value-of-a-html-select-with-asp-net
Comment: @MarceloVieira funcionou, muito obrigado! =)
Comment: @MarceloVieira seria interessante  você adicionar a resposta, assim o Bruno consegue dar resposta aceita e a solução fica para a comunidade ;)
Answer: Defina um name para seu select
<select class="form-control" id="sel1" name="sel1">

Com isso você consegue pegar o valor por meio de uma propriedade do objeto que colocar no parâmetro da action pra onde enviar o form, ou pelo Request, assim:
Request.Form["sel1"])

Veja mais em: https://stackoverflow.com/questions/2378338/how-to-get-selected-value-of-a-html-select-with-asp-net


Regular expression to validate unique word in text

Question: I need regular expression to validate text for all words in text must be unique.
for example my text will be like
valid text->
"Advance|Paid|Regular|Next"
Invalid text->
"Advance|Paid|Paid|Regular|Next|Advance"
words are not fix it can be any thing.
Please help me how I can achieve it in .net
Comment: Regular expressions are not appropriate for this problem.
Comment: Do it HAVE to be a regex? I'd say it's easier to do it other ways. Split on | for instance.
Answer: I do not think you can achieve that with regular expressions, unless the list of words is explicitely known (like in enum).
However, in .Net, you can do it very easily in  multitude of other ways.
For starters, let's try C# and Linq:
using System;
using System.Linq;

string myText = "aaa|bbb|ccc|aaa";
var parts = myText.Split('|');
var uniques = parts.Distinct();
if(uniques.Count() != parts.Length) throw new ArgumentException("Not unique!");

Comment: correction - I forgot about backreferences. Indeed, see PeterNLewis answer and my comment to see how the detection could be achieved with regex. The idea in regex is that ANY duplication is a fault, so if the backreference hits any full token delimited by | - then the text is invalid.
Answer: I'm not sure about .net, but a regular expression that will find a word followed by another matching word would be:
\b(\w+)\b.*\b\1\b

That is, a word break, a sequence of word characters, a word break, any number of any characters (except line breaks) and then the word repeated, with word breaks around it.
Not all regular expression engines will allow \1 to reference a previous match within the same regular expression.
Comment: @quetzalcoatl Not quite, even if you change the backref to the correct `\2`, that would match e.g. `Sub|Submarine`.
Comment: hm.. that'd mean that `(^|\|)([^|]+)(\||$).+?\1` would detect exactly what the author wants?
Comment: yep, .Net's regex engine supports backrefs: http://msdn.microsoft.com/en-us/library/thwdfzxy.aspx
Comment: @veredesmarald: very true! I've mistaken backref-matching with regex-matching and had the idea that the middle group would not match when the last didn't - which of course is not true. The correct expresison would rather look like `((?<=^|\|)[^|]+(?=\||$)).+?\1` so the group is defined along with delimiters, but without capturing them. Thanks for the note!
Comment: FYI: on the .Net's lookahead/lookbehind: http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet
Answer: This is simple with LinQ
string curText = "Advance|Paid|Paid|Regular|Next|Advance";
string valid = string.Join("|", curText.Split('|').Distinct());
if(valid.Length != curText.Length)
    // error.....

Answer: Why using RegEx for this at all? Simply check the number of occurences of string X in the input and check if it is at most 1. In your example splitting at "|" should be easy (could be done via RegEx, but simply tokenizing the string should be easier).
Answer: Yeah, it is possible using backreferences:
(?:^|\|)([a-z]+)\|.+\|\1(?:\||$)

That will match expressions with repeated words, with the first instance of the word as a group. Either negate it to see if words are repeated, or use a replace to remove the words.
To use spaces instead of |:
\b([a-z]+)\b.+\b\1\b


Popcorn.js not rewinding

Question: I'm using Popcorn.js and its extension Popcorn Capture.
I have the following code:
<code>function setVidPoster() {
    var video = Popcorn( '#bzm_video' ), poster;
        video.listen( "canplayall", function() {
        this.capture({at: 1});
        this.currentTime(0);
    });
}
</code>
I'm trying to capture the image 1 second in as the poster, however the video player actually moves to 1 second and says there.  From the Popcorn capture documentation I'm assuming this isn't meant to happen, but I can't figure out how to move the video to the beginning (currentTime should be working afaik from the documentation)
Answer: Not sure if you're still pursuing this, but I poked around in popcorn.capture, and pushed some changes to the capture repo, to get a poster captured at a certain time, and set back to 0. Might want to give it a try.
My final implementation looked like this:
<code>    document.addEventListener( "DOMContentLoaded", function() {

      var p = Popcorn( "#video" );
      p.listen( "canplayall", function() {

        this.capture({ at: 10 });

      });
      p.play().pause();

    }, false );
</code>
I could not find any problems in Popcorn rewinding, though. If you're still having problems, post a complete working case, and I'll take a look at it :)
Comment: I tried that with the most current version of popcorn.capture and the whole video was disabled. For now due to priorities, I've just gone back to capturing the first frame and staying there with the older version of the plugin, but I will post some actual code when I get a chance
Comment: @Damon, sorry to push you for the code... :) but have you managed something, Im quite stuck where you were 3 years ago.

Popcorn.js not rewinding


Centering vs standardizing in ridge regression

Question: I have read that to apply ridge regression, we first need to standardize the predictive variables. That is because the variables should be in a homogenous scale so that lambda has an effect of the same magnitude on all of them.
However, taking a look at the ridge regression implementation of the scikit-learn library, I see that the X variables are centered but not standardized. That is, the variables retain their scale.
I was wondering if you know why that is, and when is each technique (standardization vs centering) advised.
Comment: The centering is probably to make life easier by orthogonalizing the variables against the intercept. For better or worse, it seems they're trusting the user to specify the right scales for ridge. In my view, you should basically always center and scale.
Comment: Hi John, I missed the first part of your comment. Could you expand on what you mean?
Comment: Related:  https://stats.stackexchange.com/questions/201909/when-to-normalize-data-in-regression/202002#202002
Comment: @Paca there are little things that come up and bite your ankles if you're trying to write an algorithm and don't center your variables :)
Answer: Looking at the source code is not necessarily the best way of learning such things. If you look at this discussion at Scikit-learn's GitHub (and outgoing links) its developers decided to deprecate a misleading default argument, so instead users could explicitly scale the data, as they suggest, with StandardScaler, i.e. subtracting the mean and dividing by standard deviation. So what you see in the code is a bad design decision that is currently being reverted. You are applying the same penalty to all the variables, so if they have different scales the penalty would impact them at different force.
Comment: Does that mean that the X variables should always be standardized? Is merely centering a bad idea?
Comment: @Paca yes, I edited for more explanation.


Multithread e Concorrência de dados + Spring

Question: Estou reescrevendo um software que serve como ponte de comunicação entre dois serviços. A comunicação é feita via sockets.
O ambiente ele possui alta concorrência de dados, em especial uma lista com os sockets ativos. O software possui alguns problemas por causa que essa concorrência não foi tratada de maneira correta, fazendo com que algumas informações sejam mostradas erradas, ou não sejam entregues em determinada ponta da comunicação.
Como estou reescrevendo, tenho algumas dúvidas sobre o melhor e mais seguro cenário.
Imaginem o seguinte:
Várias threads acessando uma única lista, podendo adicionar, remover e iterar várias vezes no mesmo segundo.
Para resolver esse problema, eu criei a seguinte estrutura:
ServerService (Onde ficaria a lista que seria acessada por todas as threads)
<code>@Component
public class ServerService {

    private CopyOnWriteArrayList<String> lista = new CopyOnWriteArrayList(new ArrayList<String>());

    public void add(String string, String myThreadName){
            System.out.println(myThreadName+". ADICIONANDO VALOR: "+string);
            lista.add(string);
    }

    public void remove(String string, String myThreadName){
            System.out.println(myThreadName+". REMOVENDO VALOR: "+string);
            lista.remove(string);
    }

    void printAll(String myThreadName){
        synchronized (lista){
            lista.forEach(s -> System.out.println(myThreadName+". ITERANDO VALUE: "+s));
        }
    }

    List<String> getAll(){
       return lista;
    }
}
</code>
MyRunnable (Onde ficaria a parte de controle dos sockets que adicionariam, removeriam ou 'iterariam' a lista)
<code>public class MyRunnable implements Runnable{

    ServerService serverService;
    String myThreadName;

    @Autowired
    public MyRunnable(ServerService serverService, String myThreadName) {
        this.serverService = serverService;
        this.myThreadName = myThreadName;
    }

    @Override
    public void run() {
        while(true){
            String value = Double.toString(ThreadLocalRandom.current().nextInt(0, 10));
            serverService.add(value, myThreadName);
            serverService.printAll(myThreadName);
            serverService.remove(value, myThreadName);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
</code>
DemoApplication (Somente um main para dar inicio)
<code>@SpringBootApplication
public class DemoApplication implements ApplicationRunner {

    @Autowired
    ServerService serverService;

    @Autowired
    TaskExecutor taskExecutor;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        taskExecutor.execute(new MyRunnable(serverService, "THREAD 1"));
        taskExecutor.execute(new MyRunnable(serverService, "THREAD 2"));
    }
}
</code>
Dessa forma, terei o comportamento correto de concorrencia da lista?
Outra dúvida, como eu 'iteraria' a lista dentro da thread, de forma sincronizada, não podendo outra thread adicionar na lista quando outra estiver fazendo a iteração? Esse seria o jeito correto?
<code>@Override
public void run() {
    while(true){
        String value = Double.toString(ThreadLocalRandom.current().nextInt(0, 10));
        serverService.add(value, myThreadName);
        synchronized (serverService.getAll()){ --ALTERAÇÃO AQUI
            serverService.getAll().stream().forEach(System.out::println);
        }
        serverService.remove(value, myThreadName);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code>
Caso necessário, eu coloco mais detalhes.
Answer: Questões com thread sempre vai depender so cenário!
Porém, é importante conhecer um mecanismo batente util, o synchronized. Esse comando faz com que apenas 1 thread seja executada no mesmo tempo.
Com isso, podemos fazer uma lista synchronized afim de que a mesma só consiga ser modificada com uma thread por vez.
Use synchronized com sabedoria! Não é interessante coloca-la em tudo, pode comprometer seu software e muito.
Uma outra saída, seria criar controle estáticos, como id´s relacionados com thread, lista e operações... Mas essa não é a melhor opção.
Comment: Toda operação na lista, deverá ser sincronizada, por isso, as opções de adicionar, remover, e iterar, deveriam ser sincronizadas. Você comentou do syncronized, o `CopyOnWriteArrayList` faz esse trabalho.
Answer: -As operações que modificam o conteudo da lista têm de ser synchronized. Quando se coloca um método synchronized apenas permite que uma thread execute de cada vez. Daí ser importante que o seu codigo não seja todo synchronized porque seria sempre só uma thread a percorrer o codigo de cada vez. (Use/Veja a implementação da blocking queue)
-Porquê?
Por exemplo, quando se retira algo da lista e decrementa-se o tamanho da lista (i--), vamos supor que são precisas 3 sub-ações para decrementar o tamanho da lista (buscar o valor do i, decrementa-lo e atualizar o seu valor), caso duas threads façam esta ação ao mesmo tempo pode ser que enquanto uma está a retirar da lista, a outra ja fez as duas primeiras sub-ações e ainda não atualizou o novo valor do i e só vai atualizar após a outra buscar o valor do i o que não era correto (a thread ia buscar um valor desatualizado).


How can i make a list and click on item to navigate to a new route

Question: I know this code only displays title and i want to make a onTap method to navigate to a new route, but this is how fare i made it, any help, hint, tip, even shaming me for how stupid i am would be very much appreciated.
Edit: I did posted the whole code because something is going wrong even after help that i got here. maybe is a syntax problem or maybe i am just too stupid
Widget build(BuildContext context) {
return new Scaffold(
  body: new ListView.builder(
    itemCount: data == null ? 0 : 10,
    itemBuilder: (BuildContext context, int index){
      return new Card(
        child: new ListTile(
            onTap: _onTapped,
            title : new Text(data[index]["title"]),
        ),
      );
    },
  ),
);

}
}
Comment: It's surprising that in early 2020, the Flutter Cookbook still doesn't contain an example of this common navigation pattern, which is sometimes call "menu list  navigation".
Comment: Just a little bit of research : https://flutter.io/routing-and-navigation/
https://flutter.io/gestures/
Comment: Possible duplicate of [App navigation example using WidgetsApp](https://stackoverflow.com/questions/48024504/app-navigation-example-using-widgetsapp)
Answer: Just wrap your title in a GestureDecector to handle clicks.
Then call Navigator's pushNamed to redirect to a new route.
new GestureDetector(
  onTap: () {
    Navigator.pushNamed(context, "myRoute");
  },
  child: new Text("my Title"),
);

Comment: been trying since you comment it but still, one problem leads to another, anyway i appreciate your help and i will keep trying
Comment: If that does not solve your problem, please explain why. If it does, mark the answer as correct for future users. If another problem popped feel free to ask another question.
Comment: After i added the gesture detector and on tap **Too many positional arguments: 0 expected, but 1 found.**
Comment: Are you sure you used the correct syntax ? `onTap: function, child: widget` ?
Comment: i edited my post, can you take a look now the whole thing what is wrong
Answer: An easier approach I found is to just wrap the item inside the ListTile with a FlatButton (or some interactive widget). In your code, for example:
Widget build(BuildContext context) {
    return new Scaffold(
      body: new ListView.builder(
        itemCount: data == null ? 0 : 10,
        itemBuilder: (BuildContext context, int index){
          return new Card(
            child: new ListTile(
              title: FlatButton(
                child: new Text(data[index]["title"]),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => YourPage()),
                  );
                },
              ),
            ),
          );
        },
      ),
    );

Comment: I like the GestureDetector in the chosen answer.  It's simpler.  It doesn't introduce another component, the FlatButton.


Por que é possível definir dois ou mais métodos com o mesmo nome na mesma classe em C#?

Question: Estou iniciando meus estudos no C# com ASP.NET MVC hoje. Estou ainda me adaptando com algumas coisas que não estou acostumado a ver, pois conheço linguagens como PHP, Python e JavaScript.
Percebi que em um código que já veio pronto, ao iniciar um projeto ASP.NET MVC com Razor, que alguns métodos da classe AccountController.cs, por exemplo, são declarado duas vezes.
Não entendi por que é possível definir um método com o mesmo nome duas vezes.
Como eu estou acostumado com outras linguagens, gostaria de uma explicação sobre isso.
Exemplo do código que está no meu projeto:
  // GET: /Account/SendCode
    [AllowAnonymous]
    public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
    {
        var userId = await SignInManager.GetVerifiedUserIdAsync();
        if (userId == null)
        {
            return View("Error");
        }
        var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
        var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
        return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
    }

    //
    // POST: /Account/SendCode
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> SendCode(SendCodeViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View();
        }

        // Generate the token and send it
        if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
        {
            return View("Error");
        }
        return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
    }

Ou seja, a declaração de SendCode é feita duas vezes.
Qual é o significado dessa "duplicação" do nome dos métodos?
Isso tem alguma coisa a ver com polimorfismo ou algo semelhante?
Answer: Termo
Isto é chamado de sobrecarga de função (em inglês bem melhor). É algo bastante comum em linguagens estaticamente tipadas. Ele existe em linguagens de diversos paradigmas e não é uma característica da orientação a objeto, como muitos acreditam.
Talvez por override se "assemelhar" com overload as pessoas acham que é a mesma coisa. Conheço muito programador "experiente" que erra isso.
Outro motivo para a confusão é que também existe a sobrecarga de operador. É um mecanismo diferente do que está sendo tratado aqui. É um tipo de polimorfismo e costuma ser usado em orientação a objeto.
Funcionamento
Isto é uma característica geral dos métodos de todo tipo, normais, virtuais, estáticos, construtores, não importa que tecnologia ou aplicação esteja usando. Por isso a documentação costuma fornecer mais de uma versão dela.
Em geral os métodos de mesmo nome fazem algo muito semelhante e tem o mesmo objetivo. É só um facilitador para o programador lembrar das diversas formas possíveis e um IDE poder ajudar mostrando as diversas assinaturas dele.
As linguagens que não possuem esse recurso tem que dar um nome diferente para cada método que tenha parâmetros diferentes. O que dificulta nomear e até incentiva nomes ruins, chegando ao ponto de usarem fazAlgo1(), fazAlgo2(), etc.
Os métodos são desambiguados pela sua assinatura (os detalhes estão aí no link), ou seja, pelos tipos dos parâmetros. Por isso o recurso não faz sentido em linguagens dinamicamente tipadas.
Cada linguagem possui um mecanismo específico para selecionar qual é o método mais adequado. O C# não considera o tipo do retorno, tem linguagem que considera (até os nomes dos parâmetros ou outras características do contrato). O compilador decide qual opção destes métodos chamar dependendo do tipo de cada parâmetro. Essa escolha costuma ser chamada de betterness (o que melhor se encaixa) e é algo extremamente complexo por causa da hierarquia de tipos.
É claro que internamente o nome é modificado para facilitar o compilador. Não pode ter dois métodos com mesmo nome. Assim como já não poderia ter, mesmo em classes diferentes, que também tem seu nome modificado internamente. Já falei isso em algumas respostas.
Exemplo
SendCode("http://www.dominio.com", true)

chama o primeiro. Para chamar o segundo seria:
SendCode(new SendCodeViewModel()) //só pra exemplificar.

Coloquei no GitHub para referência futura.
No ASP.NET MVC tem uma importância extra porque o método pode ser uma ação do controlador, então parte da rota determinará qual método chamar, mas isso se dará pelo nome e pelos dados que está indo junto em uma requisição HTTP.
Olha só quantos construtores diferentes tem a classe String. Tudo o mesmo nome (claro), mas cada um opera de um jeito diferente). O mesmo vale para os métodos regulares. Veja a lista que tem vários nomes duplicados. Mas nenhum com a mesma assinatura. Note na lista da documentação que além do nome consta os tipos para diferenciá-los.
Por isso em uma herança ou implementação de uma interface é preciso cuidado porque o método a ser herdado não basta ter só o mesmo nome, tem que ter a exata assinatura que seu superior.
Alternativa
O C# possui o recurso de valor default para os parâmetros, o que torna a necessidade da sobrecarga bem menor. Ou seja, se for só para colocar um valor em um parâmetro não precisa fazer isso. Normalmente é necessário apenas nos casos onde há uma lógica diferente entre um método e outro.
Answer: Esta "duplicação" é o que chamamos de sobrecarga de métodos. Uma característica presente em linguagens orientadas a objeto.
Apesar do nome ser igual, como no seu exemplo SendCode, as assinaturas dos métodos são diferentes, com parâmetros específicos em cada declaração.
A partir dos parâmetros informados na chamada do método o compilador pode definir qual método executar.
Answer: Você pode definir o método com o mesmo nome se o método receber tipos de parâmetros diferente.
Perceba que o método SendCode(string returnUrl, bool rememberMe) recebe dois parâmetros, e o SendCode(SendCodeViewModel model) recebe outro tipo de parâmetro, sendo assim você pode ter mais de um método com o mesmo nome, porém se os dois métodos recebessem o mesmo tipo de parâmetros, você iria ter um erro.
Espero ter ajudado, abraço.


Examples of topological groups that are not metrizable.

Question: I am looking for examples of topological groups but most are metrizable likes real numbers etc. Then there are Lie groups that I am not familiar with. Are there any simple enough to understand examples of non metric topological groups, or topological rings? How about ordered square or long line, can they be turned into a  topological group?
Comment: How about taking a Cartesian product of a **lot** of copies of a standard example?
Comment: Can look at Linear Algebraic Groups, They come with the Zariski topology which is not Hausdorff.
Comment: @Brozovic Algebraic groups are mostly not algebraic groups. Indeed, the law is not continuous (it is continuous $G\to G\to G$ when $G\times G$ is equipped with the Zariski topology, which is **not** the product of Zariski topologies on factors, unless $G$ is finite). Actually, a topological group in which $\{1\}$ is closed is Hausdorff, which discards infinite algebraic groups.
Answer: $\mathbb{R}^I$ for any uncountable index set $I$ (pointwise addition), likewise $\{0,1\}^I$ (pointwise addition mod 2, compact as well), $C(X)$ (the continuous functions on an uncountable, completely regular topological space $X$, again with addition, with pointwise convergence topology), etc.
The ordered square and the long line are not homogeneous (the end points are distinct) so cannot be made into a topological group. Or if your versions of them are homogeneous, then they cannot be topological groups because thy're first countable and not metrisable (Birkhoff's theorem tells us that a first countable topological group is metrisable, which explains why my examples need to be "big").
Comment: @Mirko, for me it starts at $0$ and has no end point: $\omega_1 \times [0,1)$ ,ordered lexicographically, in the order topology. It's first countable but not metrisable, which shows it cannot be made into a topological group.
Comment: isn't the long line homogeneous? (It has different versions, going one way or going both ways, at any rate, take any version that has no endpoints, e.g. $(0,\omega_1)$ or $(-\omega_1,\omega_1)$.) So another argument might be needed to show it cannot be made into a topological group.
Comment: I'm not sure what you mean by $C_p(X)$ since you don't specify the topology; if so you probably have to make assumptions on $X$.
Comment: @YCor the pointwise (product) topology. Hence the $p$. The space $X$ must be uncountable that's all.
Comment: That's $C_p(X)$ as subset of $\mathbf{R}^X$. You need to assume that continuous real-valued functions on $X$ separate points (assuming $X$ Hausdorff is not enough).
Comment: @YCor We take $X$ completely regular and so is $C_p(X)$ of course. $\mathbb{R}^I$ is a special case ($I$ an uncountable index set in the discrete topology).
Answer: If you really just want some non-metrizable topological group without other properties, you can create some examples as follows:
Take some group $G$ with order $\text{ord}(G) \geq 2$ and equip it with the trivial topology (only the empty set $\emptyset$ and $G$ being open). As a topological space, $G$ cannot be metrizable then:
Suppose it is and let $d$ be a metric on $G$. As $\text{ord}(G) \geq 2$, we can choose $a,b \in G$ with $a \neq b$. If $\epsilon = d(a,b)$, then we have $b \not\in B_{<\epsilon}(a),$ the open ball around $a$ with radius $\epsilon$, which is a contradiction to $G$ being equipped with the trivial topology.
As every map into a space with trivial topology is continuous, $G$ is a topological group, which means we have a non-metrizable topological group.
Comment: maybe the OP wants $T_1$ examples.., a pretty standard assumption.
Comment: I totally agree. As the OP was asking for some easy examples I felt that a rather unnatural or stupid example might still be a good starting point.


Asymptotic Expectation of Ratio of Sample Averages

Question: I have two random variables: $X$ and $Y$. I know that:
\begin{equation}
E[X]=E[Y]=\mu>0
\end{equation}
I know that variance of both can be bounded:
\begin{equation}
\operatorname{Var}[X]<k, \quad
\operatorname{Var}[Y]<k
\end{equation}
The variables might be correlated.
Suppose I create a statistic:
\begin{equation}
Z_n=\frac{ \overline{x}-\overline{y}}{ \overline{y}}=\frac{\frac{1}{n}\sum x_{i}-\frac{1}{n}\sum y_{i}}{\frac{1}{n}\sum y_{i}}.
\end{equation}
Clearly:
\begin{equation}
\overline{x}-\overline{y}\rightarrow0 \quad and \quad \overline{y} \rightarrow\mu \quad as \quad n\rightarrow\infty \quad
\end{equation}
My suspicion is that:
\begin{equation}
Z_{n}\rightarrow0 \quad as \quad n\rightarrow\infty \quad?
\end{equation}
(in some statistical sense - in probability, almost surely, etc.)
I am an economist and reasonably decent at statistics, but this is stretching my abilities. It seems obvious in some sense, but I need to provide a proof for paper. My intuition is that E[x-y] is going to 0 and E[y] is always bounded from 0, and it seems as if the averages are getting tighter and tighter so that correlations between X and Y can't matter much as n rises. But, I worry that there are weird cases I need to exclude for X and Y (which are pretty simple variables in actuality).
I was thinking that one way forward is to do a Taylor Expansion (http://www.stat.cmu.edu/~hseltman/files/ratio.pdf) and then show all of the extra terms must go to zero. But, it seems like there must be an easier way? Like, maybe this is a very obvious and simple?
Comment: See https://en.m.wikipedia.org/wiki/Slutsky%27s_theorem
Answer: By the Strong Law of Large Numbers, $\bar{X}_n$ and $\bar{Y}_n$ converge almost surely to $\mu$. For $\mu \neq 0$, $g(x,y) = \frac{x - y}{y}$ is continuous at $(\mu, \mu)$ hence by the Continuous Mapping Theorem, $g(X_n, Y_n) \xrightarrow[a.s.]{}g(\mu, \mu) = 0$.
Answer: Slutsky's theorem will do the trick (expanding on comment by hejseb).
Let
$$Z_n = \frac{\bar{x}_n - \bar{y}_n}{\bar{y}_n}$$
By the Weak Law of Large Numbers, we have
\begin{align*}
\bar x_n &\stackrel{p}{\rightarrow} \mu \\
\bar y_n &\stackrel{p}{\rightarrow} \mu
\end{align*}
Since convergence in probability is stronger than in distribution, we trivially have $\bar x_n \stackrel{d}{\rightarrow} \mu$. Also define $c_n = \bar x_n - \bar y_n$. You state that "clearly"
$$c_n \stackrel{d}{\rightarrow} 0$$
This is true, but it is actually an application of Slutsky's theorem. A second application of Slutsky's theorem gives you
$$Z_n = \frac{c_n}{\bar y_n} \stackrel{d}{\rightarrow} \frac{0}{\mu} = 0$$
Convergence in probability implies convergence and distribution. Although the converse is not true in general, it is true when we have convergence to a constant. Thus $Z_n \stackrel{p}{\rightarrow} 0$ as desired.


Solve $(4 + \sqrt15)^x + (4 - \sqrt15)^x =62$

Question:
Solve $(4 + \sqrt15)^x + (4 - \sqrt15)^x =62$

I was able to solve this equation by considering $(4 + \sqrt15)^x$ as some $y$. I got the quadratic equation
$y^2-62y+1=0$.
Therefore, $y = 31 \pm 8 \sqrt15  = (4 + \sqrt15)^x$
I am very close to getting the answer but I dont know how to compare both sides and obtain $x$. Should I just use trial and error (because it works when $x = 2$), but I want to know whether there is a more concrete way yof doing this.
Comment: Forgive me if I'm missing something, but isn't it just $\log_{4+\sqrt{15}}\left(31 \pm 8 \sqrt{15} \right)$? The plus will give you 2, and working through to simplify the minus will give you the other solution.
Answer: One way is to observe that $31 \pm 8\sqrt{15} = (\sqrt{15})^2 \pm (2)(4)\sqrt{15} + 4^2 = (4 \pm \sqrt{15})^2$, a "sort of" complete the square process.
But that's a bit unsatisfactory since you're basically making a guess (albeit a justified one) that the expression is the square of the surd you want.
You might as well have started by "guessing" $x=2$ to begin with in the original equation.
Either way, you still have to figure out that $x=-2$ is also a valid solution based on the fact that $4 + \sqrt{15}$ is the reciprocal of $4-\sqrt{15}$.
A perhaps more satisfying solution is to use logarithms.
You have $(4 + \sqrt{15})^x = 31 \pm 8\sqrt{15}$
Take logarithms of both sides, it doesn't matter which base as long as it's the same on both sides. Natural logs are fine.
$\log (4 + \sqrt{15})^x = \log(31 \pm 8\sqrt{15})$
$x\log (4 + \sqrt{15}) =  \log(31 \pm 8\sqrt{15})$
$x = \frac{\log(31 \pm 8\sqrt{15})}{\log(4 + \sqrt{15})} = \pm 2$
And you get both valid solutions immediately.
The only unsatisfying part about this is that you're forced to use a calculator. But no "leaps of insight" are required - the use of logarithms to solve this form of equation is very standard.
Answer: Hint;
$$31+8\sqrt{15}=2\cdot4\sqrt{15}=(4+\sqrt{15})^2$$
$$\sqrt{31+8\sqrt{15}}=4+\sqrt{15}$$
$$\implies\sqrt{31-8\sqrt{15}}=|4-\sqrt{15}|=4-\sqrt{15}$$ as $4-\sqrt{15}=\dfrac1{4+\sqrt{15}}>0$
Answer: Let $(4+\sqrt{15})^x=y$, then the Eq. becomes $$y^2-62 y+1=0 \implies y=(31\pm 8\sqrt{15})=(4 \pm\sqrt{15}) \implies x=-2,2.$$
Because $$(4 +\sqrt{15})(4-\sqrt{15})=1$$
Answer: $$\begin{align}(4+\sqrt{15})^x+(4-\sqrt{15})^x&=(4+\sqrt{15})^x+(4+\sqrt{15})^{-x}\\
&=e^{x\ln(4+\sqrt{15})}+e^{-x\ln(4+\sqrt{15})}=2\cosh\left(x\ln(4+\sqrt{15})\right)\\
&=62\end{align}$$
So
$$\begin{align}x\ln(4+\sqrt{15})&=\pm\cosh^{-1}31=\pm\ln\left(31+\sqrt{31^2-1}\right)\\
&=\pm\ln\left(31+8\sqrt{15}\right)=\pm\ln\left(\left(4+\sqrt{15}\right)^2\right)=\pm2\ln\left(4+\sqrt{15}\right)\end{align}$$
So $x=\pm2$.
Answer: A bit late answer but maybe worth mentioning it.

Let $a= 4+\sqrt{15} \stackrel{4-\sqrt{15}=\frac 1{4+\sqrt{15}}}{\Rightarrow} f(x) = a^x + a^{-x}$ is even $(f(x) =f(-x))$, hence we only need to consider $x> 0$, since if $x_0$ is a solution iff $-x_0$ is one.
$f'(x) = \ln a\left(a^x - a^{-x}\right)\stackrel{a>1}{>}0 \Rightarrow f'$ is strictly increasing on $(0,+\infty)$. Hence, any solution on $(0,+\infty)$ is unique.

The following part might show how such problems are constructed with other $a$'s and other exponents, as well:

Using Vieta you see that $t_1 = a$ and $t_2 = a^{-1}$ are the solutions of $t^2-8t+1 = 0$. Hence,
$r_n = a^n + \frac 1{a^n}$ is the solution to the linear recurrence

$$r_{n+2}=8r_{n+1}-r_n \text{ with } r_0 = a^0+\frac 1{a^0}=2, r_1=a+\frac 1a=8$$
$$r_2 = 8\cdot 8-2 = 62 \stackrel{x>0}{\Rightarrow} \boxed{x=2} \text{ is the unique positive solution.}$$
And, because of $f(-x) = f(x)$, the other corresponding unique negative solution is $\boxed{x=-2}$.


TinyMCE - stripping tags and then adding tags - weird behavior

Question: I have a tinyMCE textarea on my page.  I'm trying to create a "quote and reply" function for a forum program and this portion looks like this:
if ($special == 'quote') {
        $dataContent['message'] = strip_tags($dataContent['message'], '
');
        echo ''.$post->authorName.' said:
'.$dataContent['message'].'

';
        }
    echo '</textarea>';

Alright, simple.  So, it should strip all tags except the line formatting (
 tags) and then add an  tag to the entire thing to italicize it, I have em set up in the styling to always be font-style: italic.
Okay, so here's what's happening - the $post->authorName said: portion is displaying in italics but the $dataContent['message'] part is not.  Both are enclosed in the  tag.  Now, if I take the allowing of
 tags away from the strip tags call, it all italicizes.  I'm stumped - what would cause this to happen?  I just want to keep the basic formatting of line breaks and still italicize the entire thing.
Answer: I just checked that
 inside  is not 'italicized' :) but inside  does. Try it.
Comment:  is a deprecated tag, correct?  I'd rather not use it, there should be a way to accomplish this without using deprecated tags you would think, no?  I tried adding p em and em p font-style: italic; to my stylesheet and that didn't cut it either.  Thanks for the help, though.
Comment: I can't find  is deprecated, but anyway I agree is a much better idea to enclose those  in a container and assign the style using css.


Custom page with panels in two languages

Question: I created two pages with panels in Drupal 7; they have different names and different languages, but only one can be active as home page.
Comment: You don't actually have a question up there. :)
Answer: You can only have one page as the front page, which I assume is what you want. The way to do this, is using a "Selection rule" on language, and two variants, not two pages.
See Learn Page manager for a deeper introduction to Page manager.


problemas controles HTML em uma pagina web com VBA

Question: estou tentando preencher os controles em uma pagina web com uma interação entre VBA e o IE, não estou conseguindo encontrar e popular os campos referentes a data de vigência da ata.

URL Da Pagina: http://comprasnet.gov.br/acesso.asp?url=/Livre/Ata/ConsultaAta00.asp
Codigo VBA:
Sub x()
    Dim ie As InternetExplorer
    Dim C
    Dim ULogin As Boolean, ieForm
    Dim MyPass As String, MyLogin As String

    Set ie = New InternetExplorer
    ie.Visible = True
    ie.Navigate "http://comprasnet.gov.br/acesso.asp?url=/Livre/Ata/ConsultaAta00.asp"

    Do Until ie.ReadyState = READYSTATE_COMPLETE
    Loop

    ie.Document.getElementsByName("dt_ini").Value = "12/12/2012" 'o erro ocorre aqui
    ie.Document.getElementsByName("dt_fim").Value = "12/11/2011" 'o erro ocorre aqui

End Sub

Sub Referencia()
    Dim ObRef
    On Error Resume Next
    ' Adiciona Controles da Net
    ThisWorkbook.VBProject.References.AddFromGuid "{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 1, 1
End Sub

Comment: gente descobri que as tags em questão estão dentro de um frame chamado **main2**
Comment: se achou útil vote na resposta! rs
Answer: o erro estava acontecendo pois as tags estavam dentro de uma Frame, a solução ficou assim:
Sub x()
    Dim ie As InternetExplorer
    Dim objCollection
    Dim ULogin As Boolean, ieForm
    Dim MyPass As String, MyLogin As String

    Set ie = New InternetExplorer
    ie.Visible = True
    ie.Navigate "http://comprasnet.gov.br/acesso.asp?url=/Livre/Ata/ConsultaAta00.asp"

    Do Until ie.ReadyState = READYSTATE_COMPLETE
    Loop

    Set objCollection = ie.Document.frames(1).Document.getElementsByTagName("input")

    i = 0

    Do While i < objCollection.Length
        If objCollection(i).Name = "dt_ini" Then
            objCollection(i).Value = "12/12/2015"
        End If

        If objCollection(i).Name = "dt_fim" Then
            objCollection(i).Value = "11/12/2016"
        End If
        i = i + 1
    Loop

End Sub

Sub Referencia()
    Dim ObRef
    On Error Resume Next
    ' Adiciona Controles da Net
    ThisWorkbook.VBProject.References.AddFromGuid "{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 1, 1
End Sub


Xamarin iOS Could not AOT the assembly Microsoft.EntityFrameworkCore.Migrations.Migration

Question: We've added migrations to our xamarin forms project and ever since then we can't deploy it to an iOS device. It will run on the simulator fine but will fail with AOT errors on deploying to device.
It seems to be a fairly wide spread topic over the web but none of the ideas so far have made a difference. We're using EntityFrameworkCore v2.2.6 along with xamarin.forms v4.1.0.
I've tried adding the -v -v -v for more details on the build log but still just get:
Error       Could not AOT the assembly '/Users/MyUser/Library/Caches/Xamarin/mtbs/builds/MyCompany.Mobile.iOS/8fcd0a31c7f6e1a671890e2462fe729f/obj/iPhone/Debug/mtouch-cache/3-Build/MyCompany.Data.Persistence.dll'    MyCompany.Mobile.iOS

Any ideas what else I should try?
Comment: Are you by any chance using macOS Catalina?
Comment: Could you tell us what you've tried?
Comment: @TimoSalomäki im running MacOS Mojave
Comment: @ColeXia-MSFT have tried, deleting all my bins/obj, clean and rebuilds, reboots of both mac and windows box, rebooted the iOS device, added the -v -v -v monto touch arguments to check additional logs, I also removed the migration file from the project that as is failing and it no longer errored (but that file is needed), i just removed the migrations designer file and that worked so it looks like something in the designer file that AOT doesn't like.I also went to install the new xamarin ios interpreter to see if that fixes it but the visx failed to install.
Comment: Maybe, https://github.com/xamarin/xamarin-macios/issues/6700#issuecomment-519959628
Answer: Xamarin.Android applications use a linker to reduce the size
The default value is SdkOnly
None: No linking will be attempted.
SdkOnly: Linking will be performed on the base class libraries only, not user's assemblies.
Full: Linking will be performed on base class libraries and user assemblies. For more details refer here.. Note: if you are facing an issue with linking such as
"GetAdditionalResourcesFromAssemblies" task failed unexpectedly. System.IO.FileNotFoundException: . Perhaps it doesn't exist in the Mono for Android profile?
then recheck your xamarin.Android project settings and set the below tag,
true
It Should Solve Your Problem.
Answer: I haven't try these but it could fix your issue

IOS Build -> General -> and uncheck the option Incremental Build.
Disable LLVM.
Remove all unnecesary classes, methods from your MyCompany.Data.Persistence.dll so it wont generate heavy code.
Change Linking to Link All Assemblies
Comment: Incremental Build is already disabled along with LLVM. Changing the Linker Behaviour to Link All allows us to deploy to device but it starts causing other errors throughout the project with 3rd party dll's (telerik-UI)
Comment: What option have you selected in Linker `Sdk assemblies` or `Sdk and user assemblies`?


about $\int \cos^q(x)\sin^p(x) dx$

Question: for all $n$ and $m$ from $\mathbb{N}$ we define $H_{m,n}$ by :
$$H_{m,n}=\int_{0}^{\frac{\pi }{2}}\cos ^{m}(x)\sin^{n} (x)dx$$

find relation between $H_{m,n}$ and $H_{m,n-2}$
find relation between $H_{m,n}$ and $H_{m-2,n}$
Calculate $H_{m,n}$

Thanks
Comment: For the first two, try integration by part twice.
Answer: If you let me, I add just some points about the third one. I hope you be inspired to defeat the problem by yourself. We know that $$B(m,n)=\int_0^1x^{m-1}(1-x)^{n-1}dx~~~~~~~\text{Beta Function}$$ By a proper substitution $x=\sin^2t$, we get $$B(m,n)=\int_0^{\pi/2}(\sin^2 t)^{m-1}(\cos^2 t)^{n-1}\times 2\sin t\cos tdt=2\int_0^{\pi/2}(\sin t)^{2m-1}(\cos t)^{2n-1}dt$$
Comment: Nicely done $+ 1\quad \ddot\smile \quad$
Answer: we have $b\left ( m,n \right )=\frac{m!\times n!}{(n+m+1)!} $ and  $ \forall (m,n) \in \mathbb{N}^{2}$
With $B(m,n)=\int_{0}^{1}t^m(1-t)^ndt$ and by a proper substitution $x=sin^2(t)$ we get :
$B(m,n)=2\int_{0}^{1}sin(x)^{2m+1}cos(x)^{2n+1}dx$
we put : $\alpha=2m+1$ and $\beta=2n+1$ so we get  $B(m,n)=b\left ( m,n \right )=\frac{(\frac{\alpha-1}{2})!\times (\frac{\beta-1}{2})!}2{(\frac{\alpha + \beta -2}{2}+1)!}$
I notice that $\alpha$ and $\beta$ are odd numbers ($\alpha=2k+1$ and $\beta=2k+1$ )

about $\int \cos^q(x)\sin^p(x) dx$


Automatic Apple TestFlight upload

Question: Now that Apple is shutting down (the old) TestFlight, I've started to look at their own TestFlight implementation.
Is there any way to submit a binary to Apple via a script? Maybe via "Application Loader"? I'd like to integrate this into a CI system.
Edit: I was able to control Application Loader via AppleScript and an unfinished version of the script is here: https://gist.github.com/maciekish/88fb6935c3d2a213b1d2
The new question is how can i build an .ipa file to give to Application Loader in a post archive script?
Comment: Regarding your edit to produce an .IPA file - have you taken a look at the `xcodebuild` command line tool?
Comment: You should be able to do something with AppleScript and Application Loader.
Comment: I can't speak to the functionality or workability, but I did find [this](http://diegopeinador.blogspot.dk/2013/10/automatic-app-creation-and-binary-upload.html)  Let us know how it works in a comment :)
Comment: Reading the article referred by @David there's a link to http://fastlane.tools/ in the comments which seems to do what you want and more...
Answer: I struggled a lot and finally I configured TeamCity and TestFlight and uploaded generated IPA from team city onto test flight using following script. This is Application Loader command line tool
<code>/Applications/Xcode.app/Contents/Applications/Application\ Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/Support/altool --upload-app -f %system.teamcity.build.workingDir%/Build/IPA/**IPA_NAME**.ipa -u '**TESTFLIGHT_USER_NAME**' -p '**TESTFLIGHT_PASSWORD**'
</code>
Comment: This should be marked as the correct answer, `altool` is build-in and supported by Apple, various 3rd party tools add a lot of complexity for very little benefit.
Answer: Both fastlane and nomad provide excellent command-line resources for building & uploading binaries (among other things).
Comment: Fastlane is the best option these days.
Comment: One year on, are these still the best options? It looks like they are still in active development so thanks for the original answer :)
Answer: I know it's completely outdated, but for those who come across this post in the future.
Yes you can automate the upload process by using the Application Loader command-line tool called altool:
http://help.apple.com/itc/apploader/#/apdATD1E53-D1E1A1303-D1E53A1126
The syntax for uploading the .ipa file is:
altool --upload-app -f [path_to_file] -u [username] -p [password]
This tool requires a Mac, but you can always rent a mac from macincloud.com (not related) and automate the process with a CI server like Jenkins or so.
Comment: This is not outdated. `altool` is the correct and Apple-supported command. You can read about it [under "Upload tools" in the App Store Connect documentation](https://developer.apple.com/help/app-store-connect/reference/upload-tools), as well as Apple's [detailed `altool` usage guide](https://help.apple.com/asc/appsaltool/).
Answer: Apple has published APIs for app store connect. By using these APIs you can automate TestFlight related operations like add/delete testers or submit build for review etc. You can find more details here:
https://developer.apple.com/documentation/appstoreconnectapi/testflight

Automatic Apple TestFlight upload


Ordenar lista de objetos com PHP

Question: Boa tarde, eu estou fazendo uma atividade para pegar um pouco mais de jeito com PHP, e resolvi pegar os dados de um arquivo cvs, e mostra-los na tela... até aí ok, consegui. Mas tive a ideia depois de tentar ordenar esses dados atraves de um calculo que eu faço no proprio código, usando dados do arquivo CSV, mas nao estou conseguindo ordena-los, vou deixar o código a seguir.
<?php

    $delimitador = ',';
    $cerca = '"';

    // Abrir arquivo para leitura
    $f1 = fopen('$ cat dataset1.csv', 'r');
    $f2 = fopen('$ cat dataset2.csv', 'r');

    if ($f1 && $f2) {

        // Ler cabecalho do arquivo
        $cabecalho1 = fgetcsv($f1, 0, $delimitador, $cerca);
        $cabecalho2 = fgetcsv($f2, 0, $delimitador, $cerca);

        echo "
";
        // Enquanto nao terminar o arquivo
        while (!feof($f1) && !feof($f2)) {

            // Ler uma linha do arquivo
            $linha1 = fgetcsv($f1, 0, $delimitador, $cerca);
            if (!$linha1) {
                continue;
            }
            $linha2 = fgetcsv($f2, 0, $delimitador, $cerca);
            if (!$linha2) {
                continue;
            }

            // Montar registro com valores indexados pelo cabecalho
            $registro1 = array_combine($cabecalho1, $linha1);
            $registro2 = array_combine($cabecalho2, $linha2);

            // Verifica quais dos dinossauros são bípedes
            if($registro2['STANCE'] == 'bipedal'){
                // Faz o calculo da velocidade de cada um dos dinossauros bípedes
                $g = 9.8;
                $velocidade = (($registro2['STRIDE_LENGTH'] / $registro1['LEG_LENGTH']) - 1) * SQRT($registro1['LEG_LENGTH']) * $g;

                // Obtendo o nome
                echo "
".$registro2['NAME'].PHP_EOL." -> ".$velocidade." m/s²
";
            }
        }
        echo "
";
        fclose($f2);
    }
?>

Como eu poderia fazer de maneira dinâmica a lista ordenada ?
EDIT1: Oque eu quero fazer, sendo direto, é ordenar os valores do arquivo .csv para que estejam em ordem da maior velocidade até a menor, que seria feito dentro do if($registro2['STANCE'] == 'bipedal').
Estou começando a aprender a linguagem e não tenho ideia de como fazer essa ordenação.
EDIT 2: Vou deixar abaixo exatamento com eu estou fazendo atualmente para voces tentarem reproduzir.
index.php
<?php

    $delimitador = ',';
    $cerca = '"';

    // Abrir arquivo para leitura
    $f1 = fopen('$ cat dataset1.csv', 'r');
    $f2 = fopen('$ cat dataset2.csv', 'r');

    if ($f1 && $f2) {

        // Ler cabecalho do arquivo
        $cabecalho1 = fgetcsv($f1, 0, $delimitador, $cerca);
        $cabecalho2 = fgetcsv($f2, 0, $delimitador, $cerca);

        echo "
";
        // Enquanto nao terminar o arquivo
        while (!feof($f1) && !feof($f2)) {

            // Ler uma linha do arquivo
            $linha1 = fgetcsv($f1, 0, $delimitador, $cerca);
            if (!$linha1) {
                continue;
            }
            $linha2 = fgetcsv($f2, 0, $delimitador, $cerca);
            if (!$linha2) {
                continue;
            }

            // Montar registro com valores indexados pelo cabecalho
            $registro1 = array_combine($cabecalho1, $linha1);
            $registro2 = array_combine($cabecalho2, $linha2);

            // Verifica quais dos dinossauros são bípedes
            if($registro2['STANCE'] == 'bipedal'){
                // Faz o calculo da velocidade de cada um dos dinossauros bípedes
                $g = 9.8;
                $velocidade = (($registro2['STRIDE_LENGTH'] / $registro1['LEG_LENGTH']) - 1) * SQRT($registro1['LEG_LENGTH']) * $g;

                $array = array("nome" => $registro2['NAME'], "velocidade" => $velocidade);

            }
        }
        echo "
";
        fclose($f2);
    }
?>

$ cat dataset1.csv
NAME,LEG_LENGTH,DIET
Hadrosaurus,1.2,herbivore
Struthiomimus,0.92,omnivore
Velociraptor,1.0,carnivore
Triceratops,0.87,herbivore
Euoplocephalus,1.6,herbivore
Stegosaurus,1.40,herbivore
Tyrannosaurus Rex,2.5,carnivore

$ cat dataset2.csv
NAME,STRIDE_LENGTH,STANCE
Euoplocephalus,1.87,quadrupedal
Stegosaurus,1.90,quadrupedal
Tyrannosaurus Rex,5.76,bipedal
Hadrosaurus,1.4,bipedal
Deinonychus,1.21,bipedal
Struthiomimus,1.34,bipedal
Velociraptor,2.72,bipedal

Comment: Importante você [edit] seu post e explicar detalhadamente o problema, descrevendo o que tentou e onde está a dificuldade atual. Pedidos de refatoração completa ou código pronto, tutoriais e/ou coisas que envolvem mais de um assunto no mesmo post geralmente não se encaixam no [escopo do site](/help/on-topic). Links para entender melhor o funcionamento do SOpt: [Tour], [Ask], [Manual de como NÃO fazer perguntas](https://pt.meta.stackoverflow.com/q/5483/70) e [Help]. Se tem dúvida em algum detalhe específico, reduzir o código a um [MCVE] pode ajudar bastante.
Comment: Obrigado pela critica, @Bacco♦, acabei de editar o post, poderia me dar uma ajuda ?
Comment: Tente fazer um [mcve], só com a parte que está com dificuldade. Com esse código todo a gente primeiro teria que entender ele pra depois ver como fazer o que quer, e ainda um baita tutorial explicando o código modificado, o que nao funciona bem no escopo do site. Com um [mcve] e um exemplo de como você tem os dados e como devem ficar, dá para a comunidade entender melhor para talvez viabilizar uma resposta.
Comment: Outra coisa, para ordenar no lugar que disse, do if (ou seja, antes de ter lido todos os registros), teria que buscar a posição certa a todo momento, o que não é uma coisa simples de fazer, envolve várias partes, talvez uma busca binária ou qq outro tipo de indexação (achar o lugar certo pra por o elemento, talvez usando uma lista linkada), complicado para pergunta simples e resposta simples
Comment: entao se eu montasse um array dentro do if e tentasse ordenar depois seria melhor? @Bacco
Comment: Não necessariamente. Se o CSV for longo, ou se for rodar muitos processos em paralelo, vai ter problema de memória. Se for CSV curtinho, o array pode ser uma boa. Se conseguisse fazer um [mcve] com um set de dados de exemplo ajudaria a viabilizar o post.
Comment: @Bacco, voce consegue reproduzir da forma que eu deixei na pergunta? nao consegui fazer um exemplo minimo e virificavel pra deixar aí...
Comment: Reabri, mas sinceramente sem o [mcve] fica complicado pq tem que analisar seu código e tentar entender tudo. Se vc tirasse todas as partes nao importantes, e só deixasse a parte que tem duvida (a que processa o array), facilitaria. Quanto menos código e ruído, melhor.
Comment: Peço desculpas pela forma que deixei @Bacco , sou iniciante, mas acredito que o códgo nao esta tao grande assim. Se puder me dar uma ajuda nisso agradeço. Nas próximas perguntas eu vou tentar colocar um exemplo minimo, agradeço a critica
Comment: Obrigado @AugustoVasques, agradeço a colaboração amigo ;)
Answer: Para fazer a ordenação que você quer, ordenar os valores do arquivo .csv para que estejam em ordem da maior velocidade até a menor(ordem descendente), eu tive que inicialmente criar duas funções.
1 - velocity($bipedal) que calcula a velocidade de um bípede com relação entre tamanho do passo, o tamanho da perna e a gravidade, conforme foi dado no exemplo.
2 - compare_bibedals($a, $b) que compara a velocidade de dois bípede, e somente bípedes, retornando um inteiro comparativo em ordem descendente, ou seja:

$a == $b =>  0
$a  < $b =>  1
$a  > $b => -1

Também usei a função usort que ordena um array pelos valores utilizando uma função de comparação definida pelo usuário, no caso compare_bibedals.
Mudei a disposição lógica do código. Inicialmente o código se concentra apenas em extrair os dados dos .csv, os arquivos foram lidos de forma independente visando minimizar o uso de recursos. Depois a atividade é focada em trabalhar, separar e ordenar os dados obtidos e então finalizar construindo uma tabela de HTML.
<?php

    //Calcula a velocidade de um dinossauro bípede
    function velocity($bipedal){
        return (($bipedal['STRIDE_LENGTH'] / $bipedal['LEG_LENGTH']) - 1) * SQRT($bipedal['LEG_LENGTH']) * 9.8;
    }

    //Compara as velocidades de dois dinossauros de forma descendente
    function compare_bibedals($a, $b)
    {
        // Se as velocidades forem iguais retorna 0
        // Se a velocidade $a < $b retorna  1
        // Se a velocidade $a < $b retorna -1
        if ($a['VELOCITY'] == $b['VELOCITY']) return 0;
        return ($a['VELOCITY'] < $b['VELOCITY']) ? 1 : -1;
    }

    $delimitador = ',';
    $registro = []; // Registro geral onde todos os dados serão mesclados.
    $registro1 = []; // Registro qual será armazenado dataset1
    $registro2 = []; // Registro qual será armazenado dataset2

    // Trabalha individualmente o arquivos dataset1.csv
    $f1 = fopen('dataset1.csv', 'r');
    if ($f1){
       $cabecalho1 = fgetcsv($f1, 0, $delimitador);
        while (!feof($f1)){
            $linha1 = fgetcsv($f1, 0, $delimitador);
            if (!$linha1) {
                continue;
            }
            $registro1[] = array_combine($cabecalho1, $linha1);
        }

    }
    // Terminada as operações com os arquivos eles são fechados para poupar recursos do sistema.
    fclose($f1);

    // Trabalha individualmente o arquivos dataset2.csv
    $f2 = fopen('dataset2.csv', 'r');
    if ($f2){
       $cabecalho2 = fgetcsv($f2, 0, $delimitador);
        while (!feof($f2)){
          $linha2 = fgetcsv($f2, 0, $delimitador);
            if (!$linha2) {
                continue;
            }
            $registro2[] = array_combine($cabecalho2, $linha2);
        }

    }
    // Terminada as operações com os arquivos eles são fechados para poupar recursos do sistema.
    fclose($f2);

    //Mescla os dados obtidos em $registro1 e $registro1 pelo nome
    foreach($registro1 as $dino_info1){
      foreach($registro2 as $dino_info2){
        //Compara ambos registros pelo nome
        if ($dino_info1['NAME'] == $dino_info2['NAME']){
          //Somente os bipedes
          if ($dino_info2['STANCE']!='bipedal') continue 2;
          //Mescla os dois registros
          $bibedal = array_merge((array) $dino_info1, (array) $dino_info2);
          //Adiciona velocidade
          $bibedal['VELOCITY'] = velocity($bibedal);
          //Coloca o resultado no registro geral
          $registro[] = $bibedal;
          continue 2;
        }
      }
    }
    //Ordena o registro geral usando a função compare_bibedals
    usort($registro, "compare_bibedals");

    //Imprime uma lista comum com os dados dos dinossauro já ordenada pelo PHP
    echo "
";
    foreach($registro as $dino){
      echo "
";
      echo "Nome: " . $dino['NAME'] . "
";
      echo "Dieta: " . $dino['DIET'] . "
";
      echo "Comprimento do passo: " . $dino['STRIDE_LENGTH'] . "
";
      echo "Posição: " . $dino['STANCE'] . "
";
      echo "Comprimento da perna: " . $dino['LEG_LENGTH'] . "
";
      echo "Velocidade: " . $dino['VELOCITY'] . "
";
      echo "
";
    }
    echo "
";

?>

Cujo o resultado é :

Nome: Tyrannosaurus Rex
Dieta: carnivore
Comprimento do passo: 5.76
Posição: bipedal
Comprimento da perna:2.5
Velocidade: 20.205689337412

Nome: Velociraptor
Dieta: carnivore
Comprimento do passo: 2.72
Posição: bipedal
Comprimento da perna: 1.0
Velocidade: 16.856

Nome: Struthiomimus
Dieta: omnivore
Comprimento do passo: 1.34
Posição: bipedal
Comprimento da perna: 0.92
Velocidade: 4.2912266412946

Nome: Hadrosaurus
Dieta: herbivore
Comprimento do passo: 1.4
Posição: bipedal
Comprimento da perna: 1.2
Velocidade: 1.7892270211835

Link funcionando no Repl.it

Ordenar lista de objetos com PHP


Solve: $\cos(\theta + 25^\circ) + \sin(\theta +65^\circ) = 1$

Question: This afternoon I've been studying the pythagorean identities & compound angles. I've got a problem with a question working with 2 sets of compound angles:

Solve, in the interval $0^\circ \leq \theta \leq 360^\circ$, $$\cos(\theta + 25^\circ) + \sin(\theta +65^\circ) = 1$$

I've attempted expanding but reach a point with no common factors & see how to manipulate the trig ratios to move on; is there a solution without expanding?
$$\cos\theta\cos 25^\circ-\sin\theta \sin 25^\circ+\sin\theta\cos 65^\circ+\sin 65^\circ\cos\theta=1$$
$$\cos \theta\;\left(\cos 25^\circ+\sin 65^\circ\right) +\sin\theta\;\left(\cos 65^\circ-\sin 25^\circ\right)=1$$
Could you tell me if I've made a mistake or how I could continue;
thanks
coffee is wearing out
Comment: 65 and 25 are difficult angles to work with.  Maybe there is some number in between that is nicer.  You can carry that difference all the way to the end.
Comment: One can change a sine to a cos or vice-versa. For example $\sin(\theta+65)=\cos(90-(\theta+65))=\cos(25-\theta)$.
Comment: $\cos(65)=\sin(25)$ so the 2nd and 3rd terms just cancel out.
Comment: Yeah, changing into a single trig ratio worked; I reached $2\cos(\theta)\cos(25)=1$, then isolating $\cos(\theta)$ gives $\theta$ = 56.5. Thank you
Answer: "Solve, in the interval 0≤θ≤360, cos(θ+25)+sin(θ+65)=1"
$\cos(\theta+25)+\cos(25-\theta)=1$
∵ $\sin(\theta+65)=\cos(90-(\theta+65))=\cos(25-\theta)$
$\cos(\theta)\cos(25)- \sin(\theta)\sin(25)+\cos(25)\cos(\theta)+\sin(\theta)\sin(25)=1$
$2\cos(\theta)\cos(25)=1$
$\cos(\theta)=\frac{1}{2\cos(25)}$
∴$\theta≈55.6°,  326.5°$
Answer: $\cos(\theta + 25) + \sin(\theta+65) = 1$
$\cos(\theta + 25) + \cos(25-\theta) = 1$
$\cos(\theta + 25) + \cos(\theta-25) = 1$
$2\cos\theta \cos(25) = 1$
$\cos \theta = (1/2) \sec 25$
$\theta$ ~ 57 degrees, 303 degrees
Answer: Since you've reduced it down to $X\sin(\theta)+Y\cos(\theta)=Z$, the solution may be found with some trigonometric identities:
$$\sin(\theta+\alpha)=\sin(\theta)\cos(\alpha)+\cos(\theta)\sin(\alpha)$$
$$\frac{\sin(\theta+\alpha)}{\cos(\alpha)}=\sin(\theta)+\tan(\alpha)\cos(\theta)$$
Returning to the original problem,
$$X\sin(\theta)+Y\cos(\theta)=Z$$
$$\sin(\theta)+\frac{Y}X\cos(\theta)=\frac{Z}X$$
Looking at this, we want $\frac{Y}X=\tan(\alpha)$, which would allow this to reduce down to a single trig function that we can take the inverse of.


How can I improve my ball handling?

Question: I play football (soccer) for my community traveling team. Our usual ball handling exercise is getting the ball around a course of cones.
What other ways can I improve my ball handling abilities?
Comment: That's a very common drill, you can make it a bit more difficult by setting the cones closer and/or trying to complete the course faster.
Answer: There is great site http://www.playsportstv.com/soccer that has alot of tricks try it!
Cones are the best way but you can also use rope:
taken from http://voices.yahoo.com/soccer-drills-speed-agility-ball-handling-drills-for-893859.html

2 Foot Ladder Drill
In this drill the coach will lay out a rope ladder and the soccer
  players will line up at one end. The first player will run to the side
  of the first box and quickly step into the both with both feet, one at
  a time, and then step out of the box to the other side with both feet,
  one at a time. As soon as both feet are out of the first box they will
  cross into the second box with both feet and cross out and so forth.
  Once the first player has moved up a few boxes the next player will
  start.
Ball Tap Drill
In this drill each soccer player stands in front of a soccer ball.
  When the coach blows the whistle, the players will quickly tap the top
  of the ball with one foot and then the other, switching as quickly as
  possible. This drill can be done for number of taps (25, 50 or 100) or
  for time (30-60 seconds).
Comment: Please write about your own experience where possible rather than "just" quoting maeterials from Yahoo, WikiPedia, etc
Answer: Buy a football and keep it at home - then just take it around with you (ok, stairs may be an issue).  You'll either get annoyed with it or really good at control.
Then ask what you're trying to improve - close ball control is great if you're looking to run with the ball, dribble, take on players, etc. You should also be concentrating on quick control of fast passes, keeping your head up while in possession, etc etc.
Answer: One particular thing that has been fun and useful for me and most of my friends, is to get a smaller ball and play around with it. You can get a size 3 ball (regular size is 5), and try to get fully familiar with it. Once you are comfortable playing with a smaller ball, try out new tricks that you might have seen on TV etc. Since the ball is smaller/lighter it will most likely be easier in the beginning, get used to that and next time you play with a regulation size ball, try and see if you can do the same tricks.
As a player who's never been great in skill dribbling, I should also remind you that it is quite overrated. Once you learn to control the ball and use your body to shield the ball when under pressure the rest is just reading your opponents weakness and having the acceleration to dribble past him when you get him off the wrong foot. In my experience, fancy dribblers have always been a pain for their teammates, since they do tend to lose the ball in tough spots in every once in a while. Likewise most of the dribbling skills you see talented professionals do will put them in situations that are risky in terms of injuries. That's my personal opinion of course...

How can I improve my ball handling?


I want to make a loop of this code so that if the ord(message) entered is more than 124 it comes back to 0 and if the ord(message)

Question: message = input("Enter a message: ")
list1 = []
for i in range(len(message)):
if ord(message[i])>124 then +3-127
list1.append(chr(ord(message[i])+3))
print("".join(list1))

I want to make a loop of this code so that if the ord(message) entered is more than 124 it comes back to 0 and if the ord(message) is less than 124 then the loop will break. How can I make this loop?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: What you asked for :
message = "example : ~"
#                    ^ 126
result = "".join(
    chr(0) if ord_c > 124 else chr(ord_c + 3)
    for ord_c in map(ord, message)
)
print(message)
print(result)

example : ~
h{dpsoh#=#�

In the ASCII table, h is 3 after e, { is 3 after x, ...
And 0 is not a printable character, so you get tofu : �


Fatou: Reverse?

Question: Attention
The usual problems are about absolute convergence:
$$\int|g_n|\mathrm{d}\mu\quad(g_n=f_n,f-f_n,s_m-s_n,\ldots)$$
(There Fatou may help out!)
But as proceeding with Fatou one encounters that one can't distort to the limessuperior:
$$\int\limsup_n|g_n|\mathrm{d}\mu\nleq\int\liminf_n|g_n|\mathrm{d}\mu\leq\liminf_n\int|g_n|\mathrm{d}\mu\leq\limsup\int|g_n|\mathrm{d}\mu$$
So the real question is about the analogue for limessuperior!!
(And not the analogue for negative functions...)
Problem
Given a measure space $\Omega$.
The lemma of Fatou states:
$$f_n\geq0:\quad\int\liminf_nf_n\mathrm{d}\mu\leq\liminf_n\int f_n\mathrm{d}\mu$$
Does the reverse hold true:
$$f_n\geq0:\quad\int\limsup_nf_n\mathrm{d}\mu\leq\limsup_n\int f_n\mathrm{d}\mu$$
Certainly, for convergent examples this holds true:
$$f_n\geq0:\quad\int\limsup_nf_n\mathrm{d}\mu=\int\lim_nf_n\mathrm{d}\mu\leq\lim_n\int f_n\mathrm{d}\mu=\limsup_n\int f_n\mathrm{d}\mu$$
So one needs to dig deeper to find an honest counterexample!!!!
(I intend to answer my own question!)
(I have to admit that my earlier answer was lame!)
Comment: @mookid [Can I answer my own question?](http://math.stackexchange.com/help/self-answer) Yes! Stack Exchange has always explicitly encouraged users to answer their own questions. If you have a question that you already know the answer to, and you would like to document that knowledge in public so that others (including yourself) can find it later, it's perfectly okay to ask and answer your own question on a Stack Exchange site.
Comment: what is the point of asking a question and posting the answer right afterwards
?
Comment: @mookid: The point is to remind myself (and others). But please have a look on: [Answer own Question](http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/)
Comment: @mookid: You're welcome. ;) Unfortunately, many people don't ask about it before judging. :(
Comment: about your question: this is the whole point of the hypothesis $f\ge 0$ in the original Fatou lemma.
Comment: @mookid: That is not the only point; Fatou involves two choices: Either $f_n\geq0$ or $f_n\leq0$ as well as either $\liminf_nf_n$ or $\limsup_nf_n$. *(Wikipedia discusses only one other choice namely what if it where say negative.)*
Comment: Yes it is. Distinguishing $f_n\ge 0$ or $f_n\le 0$ is not a "choice". There is only one version, with $\liminf$ and $f_n\ge 0$ (or $f_n\ge -g$ with $g$ integrable, as it is trivially equivalent).
Comment: @mookid: You're right. ^^ *(Taking limsup on negativ ones is just equivalent to the usual.)*
Comment: @mookid: this sort of self-answered non-question is strongly discouraged on this particular SE site, although it is allowed by the software.
Comment: @Behaviour: answering your own question is permitted, but *this* particular kind has always been discouraged on math.SE. If a user discovers the answer *after* asking, then writing an answer is reasonable. If they know the answer before asking, there is no reason to ask. See http://meta.math.stackexchange.com/questions/4680/is-answering-own-question-okay for a longer discussion about a user who was asking questions only to answer them himself
Comment: @CarlMummert: We had this discussion already. The upshot was that you couldn't or didn't offer any reference for that!!
Comment: @Freeze_S: http://meta.math.stackexchange.com/questions/4680/is-answering-own-question-okay
Comment: @CarlMummert: Good, that's finally some reference. :) Anyway, in my opinion this thread is positive for stack exchange as wikipedia misses considering it and the only other post here containing this doesn't adress to directly to the positive nondominated case. Thus my proposal, leave it open! *(Before, I always first try to find an answer via google, wiki and SE.)*
Answer: Attention
The problematic examples are the divergent ones: $\liminf\neq\limsup$
Counterexamples
On the one hand, it holds by the usual Fatou:
$$f_n:=\chi_{(n,n+1]}:\quad0=\int\limsup_nf_n\mathrm{d}\mu\leq\limsup_n\int f_n\mathrm{d}\mu=1$$
On the other hand, it fails the reverse Fatou:
$$f_{1\leq k\leq n}:=\chi_{(\frac{k}{n},\frac{k}{n}]}:\quad1=\int\limsup_nf_n\mathrm{d}\mu\nleq\limsup_n\int f_n\mathrm{d}\mu=0$$
(So while the former forces the direction of the inequality the latter shows it can't hold.)
Comment: I don't understand your indexing of $f_n$ in $$f_{1\leq k\leq n}:=\chi_{(\frac{k}{n},\frac{k}{n}]}$$
Comment: In general, as you will hopefully learn later on, one is not limited to only take the natural numbers as indexing set (sequences) but any (directed) preordered set (net) will do a job too. This *veeery* often turns technical matters into natural ones. Also it comes in very handy in many constructions and applications as for example defining arbitrary sums/integrals.
Comment: The $\{1\leq k\leq n\}:=\{(k,n):1\leq k\leq n\}$ run as $(k,n)=(1,1),(1,2),(2,2),\ldots,(1,5),\ldots(5,5),(1,6),\ldots,(6,6),\ldots$
Comment: So, in my language, it is $$g_n=\sum_{1\leq k\leq n}\chi_{[\dfrac{k}{n},\dfrac{k}{n}]}$$. Is what you want to define ?
Comment: No, the indexing here does not consist of only a single "number" $\lambda:=n$ but really of tuples of "numbers" $\lambda:=(nk)$. You can think of it is a diagonally counting the tuples similar to the proof that the rationals are countable: $1'=(11), 2'=(12), 3'=(22), 4'=(13),\ldots$.
Comment: Sorry to insist. If you have time, could you elaborate these mysterious notations (i) $f_{1\leq k\leq n}:=\chi_{(\frac{k}{n},\frac{k}{n}]}$, how can we compute $f(t)$ for $0\leq t\leq 1$ (ii) $1=\int\limsup_nf_n\mathrm{d}\mu\nleq\limsup_n\int f_n\mathrm{d}\mu=0$ then index $f_\lambda$ ($\lambda$, compositions ?). To end with, I agree that nets (together with subnets) are elegant for questions where non-linearly ordered (neither non-cofinal-countable) limits are involved (+1).
Comment: For example [this question][1] can be naturally (and elegantly) treated with nets and subnets. [1]:http://math.stackexchange.com/questions/515496/sum-of-closed-and-compact-set-in-a-tvs
Comment: Oh no worries I'm always in for conceptual math questions :D
Comment: Oh no no it is not *always* a good idea to use nets. In this particular MSE question nets may be a bad Ansatz. A strong indicator against nets in there is the ingredient compact set. Generally speaking, in any branch of mathematics matters become trivial in the *right* language. That is compactness becomes very natural in terms of neighborhood systems and filters! That is a subnet in terms of filters becomes simply set inclusion. However, I'll have to think about that particular MSE question..
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/51033/discussion-between-duchamp-gerard-h-e-and-freeziis).
Comment: @Duchamp Gérard H. E.  I don't understand this notation either what does indicator $f_{1\le k \le n} = \chi_{(n,n+1]}$means can you write the example such as $f_2$,$f_3$,$f_4$ in the integral?
Answer: Here's a simpler counterexample.
For $x \in [0,1]$, $f_{n}(x) = 1$ if $n$ is odd, and $0$ otherwise.
For $x \in (1,2]$, $f_{n}(x)=1$ if $n$ is even, and $0$ otherwise.
For any other $x$, $f_{n}(x) = 0$.
In this case
$$
\int \limsup_{n} f_{n}(x) dx = 2,\\
\limsup_{n} \int f_{n}(x) dx = 1.
$$
Comment: Very nice one, thank you!
Comment: I didn't expect any response after five years. Thanks.
Comment: Ya, I can imagine. :) You're welcome!

Fatou: Reverse?


Can I use multiple chaincode using a single Bluemix blockchain service?

Question: I'm new to IBM Bluemix Blockchain service. I wonder if I can create multiple chain code. This is because I got the following error.
! looks like an error loading the chaincode or network, app will fail
{ name: 'register() error',
code: 401,
details: { Error: 'rpc error: code = 13 desc = \'server closed the stream without sending trailers\'' } }

Here is what I did:

Create a blockchain serivce, and nameded as 'blockchain'.
Run cp-web example => Success
Run marbles demo using existing blockchain service ('blockchain'). => Gives me the above error
Newly create a blockchain service, names as 'mbblochchain'
Repush marbles demo with new service name => Success

So I wonder if I can put multiple chaincode into peer's network or not. It is likely I may be misunderstanding how it works or should behave.
Answer: Yes you can deploy multiple chaincodes on the same network. The issue you are having is because each app is registering users differently.
Currently only 1 username (aka enrollID) can be registered against 1 peer. If you try to register the same username against two peers, the 2nd registration will fail.  This is what is happening to you.
The Bluemix blockchain service is returning two type1 usernames (type1 is the type of enrollID these apps want to use).

cp-web will register the first and second enrollID against peer vp1
marbles will register the first enrollID against vp1 and the 2nd enrollID against vp2

Therefore when you ran marbles after cp-web it tried to register the 2nd enrollID against vp2 when it had already been registered with vp1.  Thus giving  you an error.
Comment: Thanks. This explains the error message I saw. I'll try not to register the same usernames somehow to see if I can register two chaincode.
Answer: In general, you can deploy multiple chaincode apps to a single instance of the Bluemix Blockchain service and more broadly speaking multiple chaincode apps to a single peer network.
Were you deploying the web apps directly using "cf push" and trying to bind to existing Blockchain service instance or where you trying to use the "deploy to Bluemix" functionality?
Comment: I had a similar issue using the "deploy to bluemix" button. Was able to redeploy successfully. There may be a timeout affecting some.


Prove that eigenvalue of matrix A is the same as the eigenvalue of $BAB^{-1}$

Question: So let $\lambda$ be an eigenvalue of $A$ and let $B$  be invertible. How do I prove that $\lambda$ is also an eigenvalue for $BAB^{-1}$
Comment: Ask Google about *Similar Matrices*.
Comment: Try showing that both $A$ and $B$ have the same characteristic polynomial.
Answer: Hint:
$$ \det( \lambda I -BAB^{-1})= \det(B( \lambda I -A)B^{-1}).$$
Comment: From here I get to $\det( \lambda I -BAB^{-1})= \det(( \lambda I -A)BB^{-1})=\det(\lambda I - A)$ so thanks!
Answer: By definition of $\lambda$, $\exists x\neq 0$ such that $Ax=\lambda x$
$BAB^{-1}(Bx)$
$=BAB^{-1}Bx$
$=BAIx$
$=BAx$
$=B \lambda x$
$=\lambda Bx$
$=\lambda (Bx)$
If $BAB^{-1}(Bx)=\lambda (Bx)$ then clearly $\lambda$ is an eigenvalue of $BAB^{-1}$ (with $Bx$ is an eigenvector; invertibility of $B$ ensures $Bx$ is not zero).
Answer: Suppose we have
$$ AX = \lambda X.$$
We show that  $Y= BX$  is an eigenvector of $ BAB^{-1}$ associated to the eigenvalue $\lambda.$
$$ BAB^{-1}(BX) = BAX = B(\lambda. X)= \lambda BX.$$


Seperate Video Streams in TS file

Question: I have multiple steams in a TS MPEG2 file  but when I try to open it, it only opens 1 specific video within a file. (WMP)
When I open another it with another program it opens a different stream. Is there a program that allows me to split them and keep them in TS?
Thank you so much
General
ID                                       : 1283 (0x503)
Complete name                            : G:\TV Shows\x\x.ts
Format                                   : MPEG-TS
File size                                : 15.8 GiB
Duration                                 : 1h 38mn
Start time                               : UTC 2012-05-30 11:02:45
End time                                 : UTC 2012-05-30 12:40:54
Overall bit rate mode                    : Constant
Overall bit rate                         : 23.0 Mbps
Network name                             : Seven Network
Country                                  : AUS (2) / AUS (3) / AUS (4) / AUS (5) / AUS (6) / AUS (7) / AUS (8)
Timezone                                 : +10:00:00 / +10:00:00 / +10:00:00 / +09:30:00 / +08:00:00 / +10:00:00 / +09:30:00

Video #1
ID                                       : 769 (0x301)
Menu ID                                  : 1332 (0x534) / 1329 (0x531) / 1328 (0x530)
Format                                   : MPEG Video
Format version                           : Version 2
Video #2
ID                                       : 801 (0x321)
Menu ID                                  : 1330 (0x532)
Format                                   : MPEG Video
Format version                           : Version 2
Video #3
ID                                       : 817 (0x331)
Menu ID                                  : 1331 (0x533)
Format                                   : MPEG Video
Format version                           : Version 2
Video #4
ID                                       : 881 (0x371)
Menu ID                                  : 1335 (0x537)
Format                                   : MPEG Video
Format version                           : Version 2
Audio #1
ID                                       : 770 (0x302)
Menu ID                                  : 1332 (0x534) / 1329 (0x531) / 1328 (0x530)
Format                                   : MPEG Audio
Format version                           : Version 1
Audio #2
ID                                       : 802 (0x322)
Menu ID                                  : 1330 (0x532)
Format                                   : MPEG Audio
Format version                           : Version 1
Audio #3
ID                                       : 819 (0x333)
Menu ID                                  : 1331 (0x533)
Format                                   : AC-3
Format/Info                              : Audio Coding 3
Audio #4
ID                                       : 882 (0x372)
Menu ID                                  : 1335 (0x537)
Format                                   : MPEG Audio
Format version                           : Version 1
Text #1
ID                                       : 772 (0x304)-801
Menu ID                                  : 1332 (0x534) / 1329 (0x531) / 1328 (0x530)
Format                                   : Teletext Subtitle
Language                                 : English
Text #2
ID                                       : 804 (0x324)-801
Menu ID                                  : 1330 (0x532)
Format                                   : Teletext Subtitle
Language                                 : English
Text #3
ID                                       : 821 (0x335)-801
Menu ID                                  : 1331 (0x533)
Format                                   : Teletext Subtitle
Language                                 : English
Comment: Can someone please edit the code above so it looks nice! tried playing around with it but no idea :(
Comment: Did you find any solution?! If TS contain multiple programs (TV programs that captured by DVB-T), how can split it? For example I have a TS file that contain football + cooking + cartoon .How can i split this TS file to 3 mpg files?
Answer: To simply extract streams for TS (i.e. demux) you can use ffmpeg. The following command will create output.mpeg with the program of index 1:
ffmpeg -i input.ts -y -c copy -map p:1 output.mpeg

Note that you can also remux it into a .ts file...
Another alternative is VLC's duplicate command line.
Comment: The comment is to get a `.MPEG` from a `.TS`. If I understand correctly you want to generate 3 `.TS` from the MPTS, unfortunately idk how to do this. I assume that you can extract the 3 program and for each of them generate a `.TS`. Maybe have a look at http://stackoverflow.com/q/23964980/3194340
Comment: If TS contain multiple programs (TV programs that captured by DVB-T), how can split it? For example I have a TS file that contain football + cooking + cartoon .How can i split this TS file to 3 mpg files?
Comment: You have to identify the program you want to extract via their PMT (Program Map Table) then, use the matching index in the command example.
Comment: Yea, to convert MPTS to SPTS, your comment worked. But to seperate programs in SPTS, how can I do?
Comment: Output extension is not important for me. I just want to extract each program(music,football,cooking) from a SPTS. About that link, there is no documentation to how to use that tools!

Seperate Video Streams in TS file


Express app inside docker. Restricting access to host localhost only

Question: I am trying to restrict access to my express/nodejs app so that it can only be accessed from it's domain url. Currently if I go to http://ip-address-of-server:3000, the app gets served directly, bypassing nginx.
I have tried adding 'localhost' in the app.listen --
app.listen(4000, 'localhost' ,  () => console.log('Server running'));
but this ends up making the app completely inaccessible. Even through nginx.
The app is running inside a docker container. And nginx is running on the host. I think this might be causing it but don't know how to fix this.
Comment: You could firewall all ports other than the one served by nginx.
Comment: Is your nginx on the same machine as node.js or on a different ip?
Comment: @MohitMutha Both on same machine but node is running inside a docker container. Nginx is on the host.
Answer: Looks like you want to do IP based filtering i.e. you want the node.js program to be accessible only from nginx (localhost or remote) and locally.
There are two ways

Use express-ipfilter middleware. https://www.npmjs.com/package/express-ipfilter to filter requests based on ips
Let node.js listen to everything but change the iptables on the host to restrict port access to specific ips. Expose the port of the node.js container to the host using -p and close the iptable for that port to the outside world

I prefer the second way as it is more robust and restricts traffic at the network level
Comment: In that case expose the port of the node.js container to the host using -p and close the iptable for that port to the outside world
Comment: Can't see how the 2nd method would work. Node.js is running inside docker. So that is where I need to control the access?
Comment: With the second method what you would do is let the node.js listen from all addresses but do not expose any port of the node.js container on the host machine (do not do any port mapping). Add a link between node.js and nginx container https://docs.docker.com/docker-cloud/apps/service-links/. For the nginx container point to the service name of the node.js container. Also expose the port of the nginx to the host that way nginx will be accessible outside
Comment: nginx is running on the host not inside a container. I am aware in that scenario it is possible to just refer to the app without exposing any ports.
Comment: Thanks. That sounds like a workable solution. Edit the answer please?
Answer: You can use Docker host mode networking for your app since you mentioned that "The app is running inside a docker container. And nginx is running on the host.".
Ref - https://docs.docker.com/network/host/
This way, it will be reachable via nginx on the same network. Your "localhost" settings will start working as usual after launching the container in docker host mode networking.
Comment: Thanks. Haven't tried this yet but looks like this this would do the trick.


Can I start playing on this clarinet?

Question: Me: no money at all and no experience with wind instruments.
Goal: learn how to play clarinet and to read music.
Found this "French-styled clarinet from URSS" for 40 dollars.

Is it completed? Can I just start playing on it? I guess I need to buy a monthpice or something. How do I know the model. Seems there are different variations of clarinet.
Comment: You're good to go.  I agree with the advice about buying a new reed, and would also recommend having it looked at by a professional.  If something isn't working right, If you're trying to learn on a broken instrument, you'll get nothing be frustration.
Comment: Instead of answering the question, I have some advice: get at least one lesson with a teacher and make the first (only?) lesson about what to buy for your first instrument. I did that for French horn and it helped me a lot. It can be a remote lesson
Comment: You might edit to clarify whether you've already bought it, or are asking whether you should. If you have it, or are buying locally, I'd take it to a local music shop to check whether everything's in working order. A $40 clarinet that needs $100 of work to be playable is a $140 clarinet.
Answer: This is a standard Boehm system B-flat clarinet (also known as French system). If it works properly you can start playing on it right away. Check that all the keys move and the pads look as if they are sealing properly. To really tell if it works properly you would need to have an experienced player test it.
The clarinet looks complete. There are even a couple of reeds in the case but you'll probably want to buy fresh ones. You might need to buy softer ones to start on.
There seems to be no manufacturer's mark on the instrument - it would be stamped at the top front of the left-hand joint (bottom right in the photo) and maybe on the bell, so it's likely to be a cheap beginner's instrument.
Comment: The one thing that I'd add to this is that there may be mechanical and/or pad sealing issues that are impossible to diagnose through a picture. Find a band instrument repair shop (someone that's a member of NAPBIRT in the U.S.; I don't know what the international equivalents are) and have them take a look. Warning: it may be $100 US or more to fix. Remember: just because you can't get a sound out of an instrument doesn't mean that there's something wrong with YOU; it might be the horn.
Comment: @JohnDoe I did suggest that the poster have an experienced player check the instrument. If they think it's okay then there's no need to go to a repair shop.
Comment: 100% disagree. I wouldn't take a used car to a race car driver to see if the car was okay. The experienced player already knows how to make a sound on the horn. If the repair tech is honest, and most that I've come across are, then you'll also get the added benefit of whether or not it's worth it to fix that instrument, e.g., spending $100 to fix an instrument that isn't worth $50.
Answer: It looks complete - all it needs is a reed fitting. Be careful - they're quite easy to damage.
Without handling (and playing) it, it's impossible to say what it'll be like, but it's certainly worth a punt. My first clarinet was £15 from a car boot sale - didn't have the nerve to knock down any more - and I'm still playing it 8 yrs on. On the assumption there are no leaks on joints etc., let a proper player try it out, and, good luck!
Answer: I'm not a woodwind player but it looks like you have everything you need to start playing there. There is already a mouthpiece. It is attached the barrel and has a ligature for securing the reed and a cap for protecting it. It is in the right center of the case. You have 2 reeds in plastic sleeves at the top. You also have some cork grease to be able to assemble and take it apart easily. I'm sure you can find some photos or a tutorial on how to assemble the pieces together correctly.
Whether or not the instrument is playable remains to be seen. Hopefully the pads seal well and the springs for the keys work properly. If you know a woodwind player with some experience have them look it over for you.

Can I start playing on this clarinet?