For which values of $\alpha \in \mathbb{R}$, does the series $\sum_{n=1}^\infty n^\alpha(\sqrt{n+1} - 2 \sqrt{n} + \sqrt{n-1})$ converge?

Question: How do I study for which values of $\alpha \in \mathbb{R}$ the following series converges?
(I have some troubles because of the form [$\infty - \infty$] that arises when taking the limit.)

$$\sum_{n=1}^\infty n^\alpha(\sqrt{n+1} - 2 \sqrt{n} + \sqrt{n-1})$$
Comment: Whenever you see roots - roots equaling an indeterminate form, try rationalizing
Answer: Hint: $\sqrt{n+1}-2\sqrt{n}+\sqrt{n-1} = \frac{-2}{(\sqrt{n}+\sqrt{n+1})(\sqrt{n-1}+\sqrt{n+1})(\sqrt{n}+\sqrt{n-1})}$
So, this term is for big n approximately $-2n^{-\frac{3}{2}}$
Answer: Using Taylor expansion $\sqrt{1+x} =_{x\to 0} 1 + \frac x 2 - \frac {x^2}{8} + O(x^3)$, we obtain for $n \to \infty$:
$$\begin{eqnarray}
n^\alpha(\sqrt{n+1} - 2 \sqrt{n} + \sqrt{n-1}) & = & n^\alpha \sqrt{n} \left(\sqrt{1+\frac 1 n} - 2 + \sqrt{1-\frac 1 n}\right) \\
& = & n^{\alpha + 1/2} \left(1 + \frac 1 {2n} - \frac 1 {8n^2} - 2 + 1 - \frac {1}{2n} - \frac 1 {8n^2} + O(\frac 1 {n^3}) \right) \\
& = & -n^{\alpha + 1/2} \left(\frac 1 {4n^2}  + O(\frac 1 {n^3})\right) \\
& \sim_{n\to\infty} & \frac{-1}{4 n^{3/2 - \alpha}}
\end{eqnarray}$$
Therefore, the series converges if and only if $\frac 3 2 - \alpha > 1$, ie $\alpha < \frac 1 2$
Answer: First hint: $$\sqrt{n+1}-2\sqrt{n}+\sqrt{n-1} = \sqrt{n+1}-\sqrt{n}+\sqrt{n-1}-\sqrt{n}$$
First term:
$$\sqrt{n+1}-\sqrt{n} = (\sqrt{n+1}-\sqrt{n})\frac{\sqrt{n+1}+\sqrt{n}}{\sqrt{n+1}+\sqrt{n}} = \frac{1}{\sqrt{n+1}+\sqrt{n}}$$
Second term:
$$\sqrt{n-1}-\sqrt{n} = (\sqrt{n-1}-\sqrt{n})\frac{\sqrt{n-1}+\sqrt{n}}{\sqrt{n-1}+\sqrt{n}} = \frac{-1}{\sqrt{n-1}+\sqrt{n}}$$
Plug in the first and the second result into the original term:
$$\begin{align}
\frac{1}{\sqrt{n+1}+\sqrt{n}}-\frac{-1}{\sqrt{n-1}+\sqrt{n}}&=\frac{\sqrt{n-1}-\sqrt{n+1}}{(\sqrt{n+1}+\sqrt{n})(\sqrt{n-1}+\sqrt{n})}\\
&=\frac{-2}{(\sqrt{n+1}+\sqrt{n})(\sqrt{n-1}+\sqrt{n})(\sqrt{n+1}+\sqrt{n-1})} \end{align}
$$
Thus $\sqrt{n+1}-2\sqrt{n}+\sqrt{n-1} = O\left(\frac{1}{\sqrt{n}^3}\right)$. This should help you...
Answer: Note that $\sqrt{n\pm 1}=n^{1/2}\left(1\pm \frac{1}{n}\right)^{1/2}=n^{1/2}\left(1\pm \frac{1}{2n}-\frac{1}{8n^2}+O(n^{-3})\right)$.
Thus, we have
$$\sqrt{n+1}-2\sqrt{n}+\sqrt{n-1}=n^{1/2}\left(-\frac{1}{4n^2}+O(n^{-3})\right)$$
so that
$$n^{\alpha}\left(\sqrt{n+1}-2\sqrt{n}+\sqrt{n-1}\right)=-\frac14 n^{\alpha -3/2}+O(n^{\alpha-5/2})$$
Thus the series converges for $\alpha<1/2$ and diverges elsewhere.


play a videojs from a given position

Question: I use videojs as player and I want if I restart the video for the second time to start reading from the last position before leaving it the last time
avant quitter le player je stocke la position
whereYouAt = player.currentTime();
var currentTime = localStorage.currentTime;
localStorage.currentTime = whereYouAt;

to restart it
playFilmVideo=function()
{

    if (player.readyState() < 1) {

        player.one("loadedmetadata", onLoadedMetadata);

    }
    else {
        // metadata already loaded
        onLoadedMetadata();

    }
}
function onLoadedMetadata() {

                var weAreAt = localStorage.currentTime;

                    var dri = weAreAt.split(".");
                    var LastTime= dri[0];
                player.currentTime(LastTime);

 }

when I launch the application for the first time the player starts reading from the position last.but when I leave the player without leaving the application and relaunch it again it starts reading from the beginning of the video
knowing that localStorage.currentTime  is still recovering the last position
Answer: you can set/seek current time of video on load using following snippet.
myPlayer.currentTime(120); // 2 minutes into the video
ref - docs
Comment: Thank you @AmitBhoyar for your   answer; in fact I have already tested setCurentTime (120) with a static  viariable: and gives me the same problem when I run all the application for the first time the video starts from the second 120 but when I leave the video without leaving the application then I restart the video for the second time it starts from the beginning .I don't understand why setCurentTime runs only the first time
Comment: @rajaa can u share a dummy example with sample url and your code so I can work on it quickly.
Comment: thank you so much; I solved the problem; I just removed  the listner "loadedmetadata" outside the function ready and it worked well, sorry for the late response .
Answer: My solution is to remove the fuction readyState() and it worked well:
player.on('loadedmetadata', function(msg) {

        player.play();
        onLoadedMetadata();

        });

function onLoadedMetadata() {

                var weAreAt = localStorage.currentTime;

                    var dri = weAreAt.split(".");
                    var LastTime= dri[0];
                player.currentTime(LastTime);

 }

play a videojs from a given position


AJAX populated filter breaks when Views Dependant Filter module added

Question: I have a view with two exposed filters and I want to make the second filter dependant on the first in 2 ways

A user has to select an option from the first filter before the second is available to use. Achieved using Views Dependant Filters
The options within the second filter are dynamically updated so only combinations that will return results are presented. Achieved following this Views AJAX Dynamic Dependent Exposed Filters tutorial and creating a custom module.

I have an example of this view available on this development server.
Select an option from filter one and the second filter becomes available and it's options are updated as expected.
The problem occurs when you select a second different option from the first filter. The AJAX does not fire and the second filter options are not updated.
Code for updating filter two with AJAX is below, but I believe the problem lies on the client side.
I appreciate your suggestions.
function dependant_keyword_filter_form_views_exposed_form_alter(&$form, &$form_state){
    if ($form['#id'] == 'views-exposed-form-annotated-bibliography-page') {

        $form['#after_build'][] = '_sort_alphabetically';

        if(!empty($form_state['values'])) {
            $form_state['input'] = array_merge($form_state['input'], $form_state['values']);
        }

        $selectedCommodity = $form_state['input']['field_commodity_tid'];
        $form['field_keywords_tid']['#options'] = _get_associative_array_from_view(
            'annotated_bibliography_dependant_keywords', // view id
            'default', // view display id
            'taxonomy_term_data_field_data_field_keywords_tid', // key field id
            'taxonomy_term_data_field_data_field_keywords_name',
            $selectedCommodity // term id of the selected shape
            );
        $form['field_commodity_tid']['#ajax'] = array(
            'callback' => '_update_keywords_callback',
            'wrapper' => 'keywords_wrapper',
            );
        $form['field_commodity_tid']['#ajax']['progress']['type'] = 'throbber';
        $form['field_commodity_tid']['#ajax']['progress']['message'] = 'Updating keywords';
        $form['field_keywords_tid']['#prefix'] = '
';
        $form['field_keywords_tid']['#suffix'] = '
';
    }
}

function _sort_alphabetically($form, $form_state) {
        foreach ($form_state['view']->filter as $field => $filter) {
            if ($filter->options['exposed']  && $filter->options['id'] == 'field_keywords_tid' ) {
                $field_id = $form['#info']["filter-field_keywords_tid"]['value'];
                asort($form[$field_id]['#options']);
            }
        }
        return $form;
}

function _update_keywords_callback($form, $form_state) {
    return $form['field_keywords_tid'];
}

function _get_associative_array_from_view($viewID, $viewDisplayID, $keyFieldID, $valueFieldID, $contextualFilter){
    $associativeArray = array();
    $associativeArray['All'] = t('- Any -');
    $viewResults = views_get_view_result($viewID, $viewDisplayID, $contextualFilter);
    foreach($viewResults as $viewRow) {
        $associativeArray[$viewRow->$keyFieldID] = $viewRow->$valueFieldID;
    }
    return $associativeArray;
}

Answer: I was able to make the second filter dependant in both ways without the need for Views Dependant Filters by adding additional logic to my hook_form_views_exposed_form_alter.
if($form_state['input']['field_commodity_tid'] === 'All')
    $form['field_keywords_tid']['#disabled'] = 1;
}

Here is the entire working code:
function dependant_keyword_filter_form_views_exposed_form_alter(&$form, &$form_state){
    if ($form['#id'] == 'views-exposed-form-annotated-bibliography-page') {

        $form['#after_build'][] = '_sort_alphabetically';

        if(!empty($form_state['values'])) {
            $form_state['input'] = array_merge($form_state['input'], $form_state['values']);
        }

        $selectedCommodity = $form_state['input']['field_commodity_tid'];
        $form['field_keywords_tid']['#options'] = _get_associative_array_from_view(
            'annotated_bibliography_dependant_keywords', // view id
            'default', // view display id
            'taxonomy_term_data_field_data_field_keywords_tid', // key field id
            'taxonomy_term_data_field_data_field_keywords_name',
            $selectedCommodity // term id of the selected shape
            );
        $form['field_commodity_tid']['#ajax'] = array(
            'callback' => '_update_keywords_callback',
            'wrapper' => 'keywords_wrapper',
            );
        $form['field_commodity_tid']['#ajax']['progress']['type'] = 'throbber';
        $form['field_commodity_tid']['#ajax']['progress']['message'] = 'Updating keywords';
        $form['field_keywords_tid']['#prefix'] = '
';
        $form['field_keywords_tid']['#suffix'] = '
';

        if($form_state['input']['field_commodity_tid'] === 'All')
            $form['field_keywords_tid']['#disabled'] = 1;
        }
}

function _sort_alphabetically($form, $form_state) {
        foreach ($form_state['view']->filter as $field => $filter) {
            if ($filter->options['exposed']  && $filter->options['id'] == 'field_keywords_tid' ) {
                $field_id = $form['#info']["filter-field_keywords_tid"]['value'];
                asort($form[$field_id]['#options']);
            }
        }
        return $form;
}

function _update_keywords_callback($form, $form_state) {
    return $form['field_keywords_tid'];
}

function _get_associative_array_from_view($viewID, $viewDisplayID, $keyFieldID, $valueFieldID, $contextualFilter){
    $associativeArray = array();
    $associativeArray['All'] = t('- Any -');
    $viewResults = views_get_view_result($viewID, $viewDisplayID, $contextualFilter);
    foreach($viewResults as $viewRow) {
        $associativeArray[$viewRow->$keyFieldID] = $viewRow->$valueFieldID;
    }
    return $associativeArray;
}


Finding parameter m in quadratic inequality

Question:
I can't find the solution to the following problem:
Find parameter m such that $2x^2+mx-5<0$ is true for $x\in(-1,1)$.
How to approach these kind of problems?
Answer: If this should for all $x$ with $x\in (-1,1)$ true,then you can plug in for instance $$x=\frac{1}{2}$$
You have two inequalities
$$-1<-\frac{m}{4}+\sqrt{\frac{m^2}{4}+\frac{5}{2}}<1$$ and
$$-1<-\frac{m}{4}-\sqrt{\frac{m^2}{4}+\frac{5}{2}}<1$$
Answer: If you were given the value of $m$ and were asked to find the possible range of values of $x$, how would you proceed?
Get an interval for $x$ so $2x^2 + mx - 5 \implies a<x<b$ where $a$ and $b$ depend upon the value of $m$ and then choose a value of $m$ that gives the range of values of $x$ as $-1<x<1$. Note that a larger interval like $2<x<1.5$ would also answer you question because the inequality $2x^2 + mx - 5<0$ would still be satisfied for $-1<x<1$.
Answer: This means one root of this quadratic $f(x)$ should be $<-1$ and the other one should be $>1$ and the roots should be real So we have three conditions:
$B^2 >4AC$, $f(-1)<0$ and $f(1)<0$. So we have $m^2>-10$ (always true as $m$ is real), then $f(-1)<0 \Rightarrow  m>-3$ and $f(1)<0 \Rightarrow m<3$. So the required domain of $m$ is $(-3,3).$
Comment: $f(\pm 1) \le 0$ is sufficient.
Comment: Yes, it is true.
Answer: The quadratic polynomial $p(x) = 2x^2+mx-5$ is negative on the open interval $(-1, 1)$ if and only if
$$
\begin{align}
 &p(-1) \le 0 \text{ and } p(1) \le 0 \\
\iff &m - 3 \le 0 \text{ and } -m - 3 \le 0 \\
\iff &-3 \le m \le 3 \, .
\end{align}
$$
Answer: $2x^2+mx-5<0$ for all $x$ in the interval $(-1,1)$ means that you must have $\Delta>0$ (since otherwise you'll either have only one root, or the function will be always positive or always negative for any real number $x$).
Now you can calculate $\Delta=b^2-4ac=m^2+40>0$
So this first condition ($\Delta>0$) is satisfied for all values of $m$.
The second condition is that the roots must be $\pm 1$, so $x=\frac{-m \pm \sqrt{\Delta}}{2(2)}=\pm 1$
This gives you that $\pm \sqrt{m^2+40}=m \pm 4$
Squaring both sides you get $m=\pm 3$
Comment: $m = \pm 3$ is not the correct solution.
Comment: There might be a mistake in the calculation sonewhere, I made it all in my head and so quickly, so you can check that up and correct it. Thank you @Martin R


implementar Interface IXmlSerializable em uma classe

Question: Tenho uma classe e preciso implementar a serialização e deserialização de dados em um estrutura XML usando IXmlSerializable, para isso na minha classe tenho que implementar os métodos, GetSchema(), ReadXml(XmlReader), WriteXml(XmlWriter), da Interface IXmlSerializable, alguém sabia me dizer como ficaria a implementação desses métodos com base na minha classe?
namespace XmlSerializationSample
{
    public class Order : IXmlSerializable
    {
        #region Local Variables

        private List<OrderDetails> _items = new List<OrderDetails>();

        #endregion

        #region Properties

        ///
        /// Identificador do pedido.
        ///
        public int OrderId { get; set; }

        ///
        /// Cliente associado.
        ///
        public Customer Customer { get; set; }

        ///
        /// Data do pedido.
        ///
        public DateTime OrderDate { get; set; }

        ///
        /// Itens do pedido.
        ///
        public List<OrderDetails> Items
        {
            get { return _items; }
        }

        public XmlSchema GetSchema() { return null; }

        public void WriteXml(XmlWriter writer)
        {

        }

        public void ReadXml(XmlReader reader)
        {

        }

        #endregion
    }
}

Comment: Você precisa realmente implementar os metodos ou apenas serializar as instâncias da classe?
Comment: serealizar as instâncias da classe.
Comment: ja ja te mando uma resposta, você precisa considerar cultura no xml?
Comment: opa, bacana. cultura no xml, não entendi !
Comment: A serialização é o ato de representar um objeto (deveras integralmente) em um formato serial, mas, muitas vezes se usa um XML para outras tarefas (enviar para um Webservice, etc) e nesses casos, é necessário que o XML reflita uma cultura específica, que vai contra o conceito de representar o objeto fielmente no formato de serialização escolhido (XML), ai está um problema.
Comment: ha entendi, precisa sim!
Comment: Da uma olhada na resposta e ve se te atende
Answer: Bem, primeiro temos que ter cuidado com o conceito de Serializar, afinal, XML é usado para muita coisa hoje em dia e as pessoas tendem a chamar de serializar qualquer ação que gere um XML, conceitualmente isto está meio errado.
Segundo a WikiPedia:

"...serialization is the process of translating data structures or
  object state into a format that can be stored"

Wikipedia
Em tradução livre:

"Serialização é o proceso de traduzir (ou transformar) o estado
  (geralmente em memória) de estruturas de dados ou objetos em um
  formato que possa ser armazenado."

Ou seja, você pode pegar um objeto e gerar um Array de Bytes para mandar pela rede, pode gerar array de bytes para guardar em um arquivo no disco, enviar parametros de um processo pela rede para executar em outro servidor ou simplesmente gerar um XML para guardar no disco ou enviar para um Webservice.
O MSDN possui outros exemplos das necessidades da serialização, dê uma olhada depois (MSDN), a questão importante aqui é que a serialização deveria ser um método de representar uma cópia do objeto.
Ai começa o problema em usar as classes de serialização do .net para outras coisas, também tem o problema de que muitas vezes os projetistas de sistemas falham em deixar claros alguns conceitos no lugar para onde você manda o objeto serializado (geralmente um subsistema que você tem que se comunicar mas, que não projetou).
Já vi casos em que o subsistema variava a cultura das datas de forma diferente em locais diferentes.
Vamos a um código de exemplo:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace serialTest
{
    [XmlRoot("Casa")]
    public class Casa
    {
        int? id;
        [XmlIgnoreAttribute]
        public int? ID
        {
            get { return id; }
            set { id = value; }
        }

        string cor;
        [XmlElement("cor")]
        public string Cor
        {
          get { return cor; }
          set { cor = value; }
        }

        //mesmo atributo, duas propriedades.
        DateTime dataConstrucaoPadrao;
        [XmlElement("dataConstrucaoPadrao")]
        public DateTime DataConstrucaoPadrao
        {
            get { return dataConstrucaoPadrao; }
            set { dataConstrucaoPadrao = value; }
        }

        [XmlElement("dataConstrucaoComCultura")]
        public string DataConstrucaoComCultura
        {
            get { return dataConstrucaoPadrao.ToString(); }
            set { dataConstrucaoPadrao = Convert.ToDateTime(value); }
        }
        //fim do teste de cultura

        [XmlElement("Sala")]
        public Sala sala;
    }
}

Agora uma classe menor para um elemento filho no XML da Casa:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace serialTest
{
    [XmlRoot("Sala")]
    public class Sala
    {
        int? id;
        [XmlIgnoreAttribute]
        public int? ID
        {
            get { return id; }
            set { id = value; }
        }

        int quantJanelas;
        [XmlElement("QuantJanelas")]
        public int QuantJanelas
        {
            get { return quantJanelas; }
            set { quantJanelas = value; }
        }
    }
}

Meu método Main da aplicação Console imprime na tela o XML:
using System;
using System.Collections.Generic;
using System.Text;
using serialTest;

namespace ConsoleTestSerial
{
    class Program
    {
        static void Main(string[] args)
        {
            Casa c;

            c = new Casa();

            c.Cor = "Vermelho";
            c.ID = 1;

            c.DataConstrucaoPadrao = DateTime.Now;

            c.sala = new Sala();
            c.sala.QuantJanelas = 2;
            c.sala.ID = 1;

            string resultSerial = UtilSerial.Serialize<Casa>(c);

            Console.WriteLine( resultSerial);
            Console.ReadLine();
        }
    }
}

E o XML gerado:
<Casa>
  <Sala>
    <QuantJanelas>2</QuantJanelas>
  </Sala>
  <cor>Vermelho</cor>
  <dataConstrucaoPadrao>2016-11-03T14:25:17.5677191-03:00</dataConstrucaoPadrao>
  <dataConstrucaoComCultura>03/11/2016 14:25:17</dataConstrucaoComCultura>
</Casa>

Falta o código que gera o XML, mas, vou deixar isso pro final porque basicamente não importa, já que uso um metodo genérico e estatico para serializar ou deserializar, o problema mesmo está forma como escrevi as classes e vamos focar nisso.
Começando com os problemas:
1. As classes de serialização foram feitas para serializar (gerar uma cópia) e tentam garantir que você nao se preocupe com o resto, logo, elas usam cultura invariante, se precisar variar a cultura, faça você mesmo.
Não adianta setar a cultura da aplicação e da thread se o código da classe que será serializada não tiver uma adaptação.
Veja por exemplo o atributo DateTime dataConstrucaoPadrao da Classe Casa, altere seu código para usar propriedades, você está usando os atributos de forma pública, além de ser um anti-padrão, você terá problemas para serializar porque vai precisar alterar o retorno sem alterar o tipo de dados. Aplique uma refatoração no seu código e leve isso para frente em outros projetos.
Repare eu eu gero duas interpretações do atributo no XML, usando proprieades, uma reflete a cultura e a outra não, no entanto, são o mesmo atributo.
Isso é possivel porque a cultura padrão é aplicada quando serializo um datetime, mas, eu crio uma propriedade do tipo string que retornar o .ToString da data, então será serializado o resultado do ToString e não a data, ai o ToString usa a cultura da Thread antes de serializar, no meu caso, pt-br.
Então, se precisar gerar o XML em cultura específica, use um atributo do tipo String e retorne o ToString do atributo.
Eu seto essa cultura na frente, espere um pouco.
2. Objetos muitas vezes tem atributos que você não quer enviar no XML se está gerando ele para ir pra outro sistema.
Perceba que o Atributo ID das minhas classes precisa existir para identificar o objeto no meu sistema (e provavelmente no banco de dados) mas, não é um atributo util no meu XML (eu nem coloco ele lá).
bom, ai é fácil, basta usar [XmlIgnoreAttribute] e ta tudo beleza, só que não.
Primeiro, existe um problema conceitual, o meu XML não é mais uma cópia do objeto que existia em memória, então, não posso mais garantir que consigo reproduzir o estado da aplicação antes de gerar o XML, se precisar inverter o processo, vai ter problemas em saber quem é quem no banco de dados ou em outros locais. Depois, o atributo ID vai precisar ser nulo na volta, logo, precisa ser anulável.
Geralmente, nessas situações existe algum campo que faz parte da regra de negócio que talvez possa ser usado como chave primária (CPF, RG, etc).
Mas, você está usando a serialização fora da definição de serialização.
Então porque eu devo usar essas classes? Bom, você que sabe se deve ou não usar.
É muito facil botar um atributo na classe e gerar um XML com o método genérico, logo, a facilidade as vezes é melhor do que a perfeição. Um aplicativo simples, que vai rodar apenas para uma tabela ou rotina pequena, pode ser feito em alguns minutos no lugar de dias.
O problema geralmente é a manutenção.
E por fim, a classe genérica para serializar:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Globalization;
using System.Threading;

namespace serialTest
{
    public class UtilSerial
    {
        public static string Serialize<T>(T dataToSerialize)
        {
            try
            {
                CultureInfo n = new CultureInfo("pt-br");
                Thread.CurrentThread.CurrentCulture = n;
                Thread.CurrentThread.CurrentUICulture = n;

                var serializer = new XmlSerializer(typeof(T));
                var stringwriter = new System.IO.StringWriter();

                var ns = new XmlSerializerNamespaces();
                ns.Add("", "");

                var xmlWriter = XmlWriter.Create(stringwriter, new XmlWriterSettings() { OmitXmlDeclaration = true });

                serializer.Serialize(xmlWriter, dataToSerialize, ns);

                return stringwriter.ToString();
            }
            catch(Exception e)
            {
                throw e;
            }
        }

        public static T Deserialize<T>(string xmlText)
        {
            try
            {
                CultureInfo n = new CultureInfo("pt-br");
                Thread.CurrentThread.CurrentCulture = n;
                Thread.CurrentThread.CurrentUICulture = n;

                var stringReader = new System.IO.StringReader(xmlText);
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(stringReader);
            }
            catch(Exception e)
            {
                throw e;
            }
        }
    }
}

Aqui muitos fatores já ficam claros quando olhamos o código, acho que apenas a questão da cultura vale um adendo.
Estes métodos vão gerar representações de atributos com culturas diferentes. Todos os atributos / propriedades que forem definidos na classe de forma a ter um retorno de um tipo padrão (int, string, datetime, etc) vão ser representados com cultura invariante, os que tiverem como retorno algum método que utiliza cultura para gerar a saída (geralmente ToString), terão sua saída na cultura que está sendo configurada na thread desses métodos, neste caso, pt-br.
O mesmo vale para a entrada.
Conceitos básicos:

[XmlRoot("Sala")] - Raiz do XML, use na definição da classe.
[XmlElement("cor")] - No do XML, use nos nós do XML.

Para atributos que forem Listas Genéricas de Objetos:

[XmlArray("Salas")] - Gera o atributo raiz da lista
[XmlArrayItem("Sala")] - gera cada item da lista

Neste caso, se nossa classe Casa tivesse uma lista de Salas:
private List<Sala> salas;
[XmlArray("Salas")]
[XmlArrayItem("Sala")]
public List<Sala> Salas
{
       get { return salas; }
       set { salas = value; }
}

Bom, pra finalizar, usando esta estrutura, todas as vezes que precisar gerar um XML de uma classe basta definir os atributos e chamar os metódos da classe UtilSerial e ja ta pronto.
Uma boa conversa sobre Serialização em C++ do Marshall Cline.
Answer: Na maioria dos casos não é necessário implementar IXmlSerializable.
Instâncias de classes relativamente simples como a sua podem ser serializadas diretamente por XMLSerializer sem problemas.
Caso o xml resultante da serialização padrão não atenda a sua necessidade, certos atributos podem ser aplicados nos elementos da sua classe para refinar o processo de serialização.
Comment: entendi, está classe é bem simples, neste caso é apenas um estudo para que eu possa serializar uma entidade inteira, de comlexidade bem maior, por isso queria entender como serealizar os atributos da minha classe, no método.
Comment: Será que ficaria algo do tipo?

    public void ReadXml(XmlReader reader)
    {
           this.OrderId = reader.GetAttribute("OrderId ")
    }
Comment: @fernandotso Leia a documentação do IxmlSerializable no [MSDN](https://msdn.microsoft.com/pt-br/library/system.xml.serialization.ixmlserializable(v=vs.110).aspx). Existem 2 raras situações onde é necessário implementar esta interface. Se de fato ainda for necessário implementá-la, use os parâmetros reader/writer dos métodos para ler/escrever o xml, respectivamente.
Answer: segue um exemplo que usei para
Serializar e Deserializar um XML usando C#
    [Serializable]
        [XmlRoot("Pessoa"), XmlType("Pessoa")]
        public class Pessoa
        {
            [XmlAttribute("id")]
            public string Id { get; set; }

            [XmlAttribute("Data")]
            public string Data { get; set; }

            [XmlElement("DadosPessoais")]
            public DadosPessoais DadosPessoais { get; set; }
        }

        public class DadosPessoais
        {
            [XmlElement("Nome")]
            public string Nome { get; set; }

            [XmlElement("Email")]
            public string Email { get; set; }

            [XmlElement("CPF")]
            public string Cpf { get; set; }

            [XmlElement("Endereco")]
            public Endereco Endereco { get; set; }
        }

        public class Endereco
        {
            [XmlElement("Bairro")]
            public string Bairro { get; set; }

            [XmlElement("Cidade")]
            public string Cidade { get; set; }

            [XmlElement("Estado")]
            public string Estado { get; set; }

            [XmlElement("Cep")]
            public string Cep { get; set; }
        }

    public class XmlWorkReader
        {
            private string _fullpath;

            public XmlWorkReader(string _fullpath)
            {
                this._fullpath = _fullpath;
            }

            public void ConvertXMltoClass<TXml>()
            {
                using (XmlReader reader = XmlReader.Create(_fullpath))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(TXml));
                    TXml txml = (TXml)xs.Deserialize(reader);
                }
            }
        }

 public class XmlWorkWriter
    {
        private XmlSerializer _xmlSerializer;
        private string _path;
        private string _filename;
        private string _fullpath;

        public XmlWorkWriter(string _path, string _filename)
        {
            this._path = _path;
            this._filename = _filename;
            _fullpath = Path.Combine(_path, _filename + ".xml");
        }

        public void XmlWrite<Txml>(Txml xml)
        {
            try
            {
                using (TextWriter writer = new StreamWriter(_fullpath))
                {
                    _xmlSerializer = new XmlSerializer(typeof(Txml));
                    _xmlSerializer.Serialize(writer, xml);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

    }

exemplo no github
https://github.com/EduardoSampaio/Projeto-Serializando-Deserializando-XML


Outlet is nil in UICollectionViewCell

Question: I have a UICollectionViewCell defined like so:
import UIKit

class GalleryCellCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var image: UIImageView!

}

Xcode put this in automatically when I added the outlet. In my UICollectionViewController's
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell

function, I then try to set an image. My code is
 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! GalleryCellCollectionViewCell
        let imagePackage = imagePackages?[indexPath.item]
        let uiImage = imagePackage?.getUIImage()
        cell.image.image = uiImage
        return cell
    }

In my variable viewer for the debugger, I can see that uiImage is not nil. However, cell.image is nil. Why would this be? Did I not link it up correctly in the storyboard?
Comment: meaning of this line `let uiImage = imagePackage?.getUIImage()`, show this method.
Comment: `@IBOutlet weak var image: UIImageView!` Never use same variable as it is declared in the apple framework, otherwise x-code get conflict and understands the code according to it.
Comment: As i see your code work, I seems to be perfect, so re-check your `reuseIdentifier ` spelling and whether it is perfectly allocated to the cell `dequeue` property or not.
Answer: You can access image with another approach using tag.
from Interface builder (IB) of the cell go to attribute tab (third tab) and set tag for the image (like 5)
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! GalleryCellCollectionViewCell
    let imagePackage = imagePackages?[indexPath.item]
    let uiImage = imagePackage?.getUIImage()
    var cellImg:UIImageView = cell!.viewWithTag(5) as! UIImageView;

    cellImg.image = uiImage
    return cell
}

Outlet is nil in UICollectionViewCell


How to convert json output to array in jquery

Question: I have this JSON output:
[{"id":"15","title":"music"},{"id":"103","title":"movie"},{"id":"214","title":"book"}]

How can I convert it to an array like in Javascript:
items = array(
     15 => 'music',
     103 => 'movie',
     214 => 'book'
          );

Comment: do you mean an object?
Answer: You could use Object.assign with a destructed object and by building a new object.

var array = [{ id: "15", title: "music" }, { id: "103", title: "movie" }, { id:"214", title: "book" }],
    object = Object.assign(...array.map(({ id, title }) => ({ [id]: title })));

console.log(object);
Answer: You can use reduce(...):
var arr = [{"id":"15","title":"music"},{"id":"103","title":"movie"},{"id":"214","title":"book"}];
var obj = arr.reduce((acc, o) => { acc[o.id] = o.title; return acc; }, {});
console.log(obj);
// prints: {15: "music", 103: "movie", 214: "book"}

Answer: Seems you are looking for an object like this

var x = [{
  "id": "15",
  "title": "music"
}, {
  "id": "103",
  "title": "movie"
}, {
  "id": "214",
  "title": "book"
}];
let temp = {};
x.forEach(function(item) {
  temp[item.id] = item.title
})
console.log(temp)


how to get weight or delta of current field collection item that is being computed

Question: Is it possible to get weight(order index) of multi field "field collection".This weight is needed inside computed field which is inside field collection.I tried the following but it returns empty
<code>$wrapper = entity_metadata_wrapper('field_collection_item', $entity);
$instance = field_read_instance('field_collection_item',$wrapper, 'bundle_name');
dpm($instance['widget']['weight']);
</code>
Here is the structure
main_content-contains field collection (multi value)
------field collection(s)-contains 1 text field and 1 computed field
------|----item 0
------|-------|-------computed_field <---here how to get weight of field collection item ie 0
------|----item 1
------|-------|-------computed_field <---here how to get weight of field collection item ie 1
------|----item 2
------|-------|-------computed_field
------|----item n
------|-------|-------computed_field
Answer: I was searching in wrong path :( this is found at
http://drupalcontrib.org/api/drupal/contributions!field_collection!field_collection.module/class/FieldCollectionItemEntity/7
code for getting delta is
<code>$wrapper = entity_metadata_wrapper('field_collection_item', $entity);
$cur_delta=$wrapper->delta();
</code>
Comment: Thank you for referencing this method. Note that the "delta" method also works after using the function "field_collection_field_get_entity" which allows you to get the entity from the field collection. Cheers.


does a separation vertex imply a separation edge?

Question: The question:
Show that every graph with 3 or more vertices will have a separation edge on the condition that it also has a separation vertex.

I know that a graph of 3 vertices in the shape of a line has 2 separating edges and 1 separation vertex. So it's true for the smallest case.
A separation edge is in multiple biconnected components. But I'm not sure how to link equivalence classes to show that it's true in the general case. Is it enough to say that since a separation vertex belongs to multiple equivalence classes, then it must have a separation edge?
Answer: No. The implication that existence of a cut vertex implies existence of a cut edge is false.
Consider the example of the butterfly graph:

Then the center vertex is a cut vertex while there are no cut edges present in the graph.
Comment: Nope that is still true, if you have a separation edge then removing it disconnects the graph. If you then remove any of the endpoints on that edge then that edge is also removed, hence those two vertices becomes the separation vertices.
Comment: Does that mean that a separation/cut edge doesn't imply a separation vertex either?


How to get Youtube's Trending Music Feed using its API

Question: Basically, what I want to get is Youtube's Trending Music in UK. I want to get the videos that are recently uploaded and is trending starting with few views.
Example:
http://www.youtube.com/channel/HCp-Rdqh3z4Uc/videos?query=NErAuLQauvw&view=22&feature=g-logo
I am confused which one of the feeds below is more applicable to me.
https://gdata.youtube.com/feeds/api/channelstandardfeeds/most_viewed?time=today&v=2
https://gdata.youtube.com/feeds/api/standardfeeds/UK/on_the_web_Music
Please help me with this. Your answer and ideas will be greatly appreciated. Thanks
Answer: Youtube channels usually start with the prefix UC. In this case the channel starts with HC what for as for I know means hidden channel. This means that you can only access them via the api if you have the right credentials.
This channels are maintained by youtube and they do not share that info for third party apps.
So if you want to rip it you will have to make a own webservice that searches the youtube site and stores the video id's or build an html parser or something like that in your application.


Resgatar botão através do id

Question: Boa noite,
Estou desenvolvendo um grafo, trabalho acadêmico..
.. A ideia é fazer um "labirinto", então eu gero o mesmo em tempo de execução, e guardo uma "referência" de cada botão numa lista, mas cheguei num ponto onde preciso mudar a cor de um botão e surgiu a seguinte dúvida: se eu sei exatamente qual é o id do botão, como faço para que um método "pegue" esse botão para que eu possa manipular o mesmo? Segue o método que instancia a minha lista:
 private List<ListaVertices> CriarBotoes()
        {
        Point localizacao = new Point(0, 0);
        List<ListaVertices> lista = new List<ListaVertices>();
        int IdBtn = 0;
        int DimensaoBtn = 35;

        for (int y = 0; y < TamanhoY; y++)
        {

            Button b = new Button
            {
                Width = DimensaoBtn,
                Height = DimensaoBtn,
                Name = IdBtn.ToString(),
                Location = localizacao,

            };
            b.Text = b.Name;
            this.Controls.Add(b);
            ListaVertices ElementoY = new ListaVertices { IdVertice = IdBtn }; // adiciona novo elemento na lista.
            lista.Add(ElementoY); // adiciona novo elemento na lista.
            IdBtn++;

            localizacao.X += DimensaoBtn;

            for (int x = 0; x < TamanhoX; x++)
            {

                Button btn = new Button
                {
                    Width = DimensaoBtn,
                    Height = DimensaoBtn,
                    Name = IdBtn.ToString(),
                    Location = localizacao,
                };
                localizacao.X += DimensaoBtn;
                btn.Text = btn.Name;
                this.Controls.Add(btn);
                ListaVertices ElementoX = new ListaVertices { IdVertice = IdBtn }; // adiciona novo elemento na lista.
                lista.Add(ElementoX); // adiciona novo elemento na lista.
                IdBtn++;

            }
            localizacao.Y += DimensaoBtn;
            localizacao.X = 0;
        }

        return lista;
    }

Answer: Tente com um pouco de Linq:
this.Controls.OfType<Button>().FirstOrDefault(c => c.Name == "idButton");

Colocando em um método estático, como pediu:
public static Button GetButton(Form f, string id)
{
   return f.Controls.OfType<Button>().FirstOrDefault(c => c.Name == id);
}

Comment: E se eu quisesse acessar através de uma classe que não seja a do Form, é possível?
Comment: aí teria que passar o form como parâmetro... e no lugar do this o objeto do form. Qualquer coisa coloca um exemplo de como seria pra ver melhor
Comment: this.Controls é o meu form? eu tenho uma classe static que estão com meus métodos, só por organização
Comment: no caso desse comando estar dentro do seu form, o `this` é o próprio form. em um método estático, o this não funciona. Mas, basta colocar o form como parâmetro
Comment: alterei a resposta

Resgatar botão através do id


UnsatisfiableError: Conda Install Keras Fails

Question: I just had a new installation of Anaconda3 and, when I type conda install keras, I get this error:
(base) C:\Users\Tejas>conda install keras
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: \
Found conflicts! Looking for incompatible packages.
This can take several minutes.  Press CTRL-C to abort.
failed

UnsatisfiableError: The following specifications were found
to be incompatible with the existing python installation in your environment:

Specifications:

  - keras -> python[version='>=3.5,<3.6.0a0|>=3.6,<3.7.0a0']

Your python: python=3.8

If python is on the left-most side of the chain, that's the version you've asked for.
When python appears to the right, that indicates that the thing on the left is somehow
not available for the python version you are constrained to. Note that conda will not
change your python version to a different minor version unless you explicitly specify
that.

The following specifications were found to be incompatible with your system:

  - feature:/win-64::__cuda==11.0=0
  - feature:|@/win-64::__cuda==11.0=0

Your installed version is: 11.0

I have an external graphics card, a RTX 2080 Super. I would really appreciate it if you could guide me through the installing of this. Thanks a lot!
Answer: Just run:
conda update --all

After running this, Keras should install successfully.
Comment: @TheBossProSniper let me know the result.
Comment: While updating i got some import errors from some files
Comment: ImportErrors  from python with a traceback
Comment: The import errors are because the libraries you're implementing are not installed in the anaconda env (base). Use conda install to install them into the conda env.
Comment: @TheBossProSniper check this out: https://stackoverflow.com/questions/61072464/anaconda-integration-with-cuda-9-0-shows-incompatible-package-error


Is there any performance gain while incrementing char pointer over accessing elements by index?

Question: I'm in a process of refreshing my "C" knowledge. I get that Arrays decay to pointers and how that works. In string processing I keep running in to code that looks like this;
int count_spaces(const char *s)
{
    int count = 0;

    for(; *s != '\0'; s++){
        if(*s == ' '){
            count++;
        }
    }

return count;

}

What performance gain do I get out of my string processing code instead of writing my function as this?
int count_spaces(const char s[])
{
    int count = 0, i;

    for(i = 0; s[i] != '\0'; i++)
    {
        if(s[i] == ' '){
            count++;
        }
    }
return count;

}

Is there an easy lexicon to go by for when to use  a pointer and when not to?
Comment: Did you try checking the asm version?
Comment: plus missing important bracketing!
Comment: @ultrasounder you have a minor syntax error.  You need an extra single quote after \0 in the second code sample.
Comment: @DylanKirkby what important bracketing?
Comment: @DylanKirkby even just proper formatting would work :)
Comment: @ultrasounder it helps readability if you bracket your for loops.  For example in your second excerpt, it is not immediately clear that the `return count` happens outside of both the if and for control structures.
Comment: @DylanKirkby actually I find that unnecessary bracketing hinders readabilty, but proper indention improves readability.
Comment: @Dylan Kirkby I agree.  The intention of the code is obfuscated by the lack of curly braces and coherent indentation.  Fixing these problems should improve readability.
Comment: you should change `cont char *s` to `const char *s`
Comment: The prototype for your second function could be the same as your first, namely `int count_spaces(const char *s)` and you could still access it with `s[i]`
Answer: This is compiler dependent.  Some compilers may offer a performance gain for one method or the other.
However, it may be useful to look at a specific example.  Using gcc -S -O0, the lowest optimized assembly output on my machine gives 3 more instructions for the first function than the second function.
But using the -O3 flag they are optimized to identical assembly files.
Edit: also see bracketing that makes your code as readable and resistant to unlucky errors as possible :)
int count_spaces(const char s[]) {
    int count = 0, i;

    for(i = 0; s[i] != '\0'; i++) {
        if(s[i] == ' ') {
            count ++;
        }
    }
    return count;
}

Edit:
To answer your question clearly: use whichever is most clear to you and whoever may read your code.  The performance boost you may get is negligible compared to the benefit of readability and clarity of intention.  Leave it to the compiler to squeeze this kind of performance out of your code
Comment: @dylanKirby thanks for the pointers to the compiler optimization flags. I pad the price for using a text editor to write my code snippet instead of using a proper Editor with formatting. Fixed now.
Comment: Agree with the comment about clarity.  If performance was absolutely critical, this function would be written without branching, and possibly vectorised with SIMD instructions.  That would only make sense if the input `s` was a very long string.


Trouble finding limits at $-\infty$.

Question: I'm being asked to evaluate $\lim\limits_{x\rightarrow\infty}f(x)$ and $\lim\limits_{x\rightarrow -\infty}f(x)$ for the following funtion: $f(x)=\frac{4x^3+2}{x^3+\sqrt{4x^6+3}}$.
For the first limit I proceed as follows:
$\begin{align*}
\lim\limits_{x\rightarrow\infty}f(x)&=\lim\limits_{x\rightarrow\infty}\frac{4x^3+2}{x^3+\sqrt{4x^6+3}}\\&=\lim\limits_{x\rightarrow\infty}\frac{(4+\frac{2}{x^3})}{(1+\sqrt{4+\frac{3}{x^6})}}\\&=\frac{4}{3}
\end{align*}$
This is the horizontal asymptote as $x\rightarrow\infty$, however, when I work through it again for $-\infty$, I get the same answer, but I know that as $x\rightarrow -\infty$, $f(x)$ approaches $-4$. Obviously there is some hole in my understanding. Any clarification would be greatly appreiciated! Thank you.
Comment: You forgot that $\sqrt{4x^6}=2|x^3|=-2x^3$ if $x$ is negative.
Answer: When $x<0$ we have $x^{-3} \sqrt{4x^6+3} = -\sqrt{x^{-6}(4x^6+3)} = - \sqrt{4 + 3x^{-6}}$.
Answer: Hint
Setting limit to $0^+$ often helps me in limit
Set $-\dfrac1x=h\implies h\to0^+$
$$\sqrt{4x^6+3}=\sqrt{\dfrac{4+3h^6}{h^6}}=\dfrac{\sqrt{4+3h^6}}{|h^3|}$$
As $h>0,|h^3|=|h|^3=(+h)^3$
But $x^3=\left(-\dfrac1h\right)^3=-\dfrac1{h^3}$

Trouble finding limits at $-\infty$.


ANOVA: single or combined statements

Question: I want to test a hypothesis that states that country of origin significantly influences the consumers' price perception of electronics 'Made in Country X'.
In my data, i have four questions measuring this price perception. They are

How high would you estimate the price of this Country X laptop given the image above?
How high would you estimate the price of this National laptop given the image above?
What is the max. amount you would be willing to pay for this Country X laptop?
What is the max. amount you would be willing to pay for this National laptop?

Can I conduct a one-way ANOVA to compare the means btw. the two first questions and then another one-way ANOVA to compare the means btw. the 3. and 4. question in order to answer my hypothesis?
Or does it make more sense to combine these 4 questions into one factor using factor analysis? How would I compute this in Excel?
Thank you so much for your help.
Answer: If the same person answers to the 4 questions, then it's a repeated measurements settings we are studying to compare the answers to the 4 questions. (I hope I understood correctly what you wish to do.)
If the Normality assumption can be assumed, then you could do an ANOVA for repeated measures. If Normality can not be assumed, you can do a Friedman test.
Regarding Factor Analysis, I don't see how would it be useful here.
Comment: Thank you so much for your help! How can I test the normality distribution? I am not sure which variables I have to use for the histogram in excel in order to check it. Do i compute a histogram for each of the four questions? Is repeated ANOVA the same as Two Way ANOVA with repetition?
Comment: And would I do two repeated ANOVAs (question 1 vs question 2) and then another one (question 3 vs question 4) or can I compute a single ANOVA for all four to check if there are significant differences in outcomes?
Comment: If the sample is large enough (near 100 or more answers to each question) you can do a Q-Q plot and look at the skewness and kurtosis of each of the 4 questions. I don't know how to make Q-Q plots in excel, but I know it's possible to get the skewness and kurtosis. If both skewness and kurtosis are in $[-2; 2]$ the deviation from the normality is not too big. Regarding the ANOVA for repeated measures, I suggest that you only do one. You can compute later paired t-tests between the questions you want. The two way ANOVA with repetition may be a different thing in excel, I can't tell for sure.

ANOVA: single or combined statements


Possible to modify host in headers

Question: Whenever someone visits intern.old-company-name.example.com I would like it to get redirected to https://intern.new-company-name.example.com. One way to do it would be
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*) https://intern.new-company-name.example.com$1
#    RewriteRule ^(.*) https://%{HTTP_HOST}$1
</IfModule>

but I don't like that I hardcode the outer sub domain intern into the httpd.conf.
Question
Would it be possible to do a regex on %{HTTP_HOST} so old-company-name gets replaced with new-company-name before the redirection to https? Or perhaps something similar?
Update
# apachectl -S
VirtualHost configuration:
10.10.10.10:443     is a NameVirtualHost
         default server a.y.b.com (/etc/httpd/conf.d/ssl.conf:85)
         port 443 namevhost a.y.b.com (/etc/httpd/conf.d/ssl.conf:85)
Syntax OK

Comment: @ETL From what I can gather the link to point to does not explain how to modify the sub domain part.
Comment: Can we assume that your rewrite rules have `[R]` at the end?  The https rewrite won't create an SSL request any other way and it changes the meaning of the other rewrite rule significantly.
Comment: By the way, it's better to tag your questions with just the tags that are relevant.  Tagging with both [tag:ubuntu] and [tag:centos] is confusing and nothing about this question seems to be [tag:linux] specific.  A [tag:mod-rewrite] tag might have been more appropriate.
Comment: @JasmineLognnes This is doable, but can you give us more of an idea of what the expected inputs to be?  Is it always one subdomain on top of the same parent domain, or are there other scenarios to account for?
Comment: @Ladadadada `[R]` flag is fine. The rule I posted were just my current solution, which I would like to make more generic. I.e. without hardcoding the `intern` sub domain. Hard coding `new-company-name.example.com` is fine.
Comment: @ShaneMadden Yes, the task is to redirect `a.x.b.com` to `https://a.y.b.com` where hard coding `y.b.com` is fine. I would like to avoid `a` being hard coded.
Answer: Let's have the HTTP to HTTPS behavior handled by the HTTP listener, and the old name to new name behavior handled by the HTTPS listener.  (We could have the HTTP redirect also do the name change, but this keeps everything in one place and makes it simpler.)
So, in your main config file we'll put back your original config with a slight tweak:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://${HTTP_HOST}$1

Then inside the <VirtualHost> in /etc/httpd/conf.d/ssl.conf we'll do the name redirect:
RewriteCond %{HTTP_HOST} ^([^\.]+)\.old-company-name\.example\.com$
RewriteRule ^(.*)$ https://%1.new-company-name.example.com$1 [R,L]

Comment: @JasmineLognnes The `R` is implied by the fact that the destination of the rewrite is not the current virtualhost, and the `L` is to ensure that no other `RewriteRule` configuration somewhere else (say, in an `.htaccess` file) is able to fiddle with the redirect before it's sent.
Comment: @JasmineLognnes Actually, just noticed your edit to the answer.  Instead of using this same rule to point from HTTP to HTTPS, we'll need to split them up - one rule for the name correction, and one for the HTTPS redirect.  If that rule were being applied to the `https://a.y.b.com` requests, then the condition would still match and it'd be a redirect loop - so what that tells us is this rule isn't applying to the HTTPS requests at all.  Can you check the output of `apachectl -S`?  There should be a `` somewhere since there are both http and https listeners configured.
Comment: Why is `[R]` needed? Is `L` for security reasons?
Comment: If I visit `httpS://intern.old-company-name.example.com` then it stays on `old-company-name` instead of redirecting to `httpS://intern.new-company-name.example.com`
Comment: @JasmineLognnes Where are these rules located (virtual host? htaccess file?) - and is that `RewriteCond %{HTTPS} off` still in place?
Comment: No virtual hosts. I placed it as the bottom of `httpd.conf`, and I still have `RewriteCond %{HTTPS} off` but if needed it can be changed.
Comment: @JasmineLognnes Yeah, remove that - that condition is explicitly preventing the following rule from applying for https requests.
Comment: Even if I do that, then `httpS://a.x.b.com` is for some reason still not redirected to `httpS://a.y.b.com`. The 3 other cases works perfectly.
Comment: Hmm. That sounds very interesting! Updated OP.
Comment: @JasmineLognnes Edited answer with a different approach that should work in this case.
Comment: With the new approach both http and https on the old domain does not get redirected, but stays on the domain.
Comment: @JasmineLognnes Strange.  Is it redirecting to HTTPS?
Comment: Yes, `http://old...` -> `httpS://old...`, but not afterwards to `httpS://new...`.
Comment: @JasmineLognnes Are the rules inside the `` in `ssl.conf`?  And I forgot to mention you'll need a `RewriteEngine On` in that file if there isn't one already, can you check on that?
Answer: Modifying headers can be done with mod_headers - check http://httpd.apache.org/docs/2.2/mod/mod_headers.html for all the syntax and details. I can't say for sure you can acheive what you want - and I'm not sure really why you want to modify the header in this case.

Possible to modify host in headers


All nework interfaces hang for seconds while one interface goes up/down

Question: I am building a client/server application that uses several network interfaces in parallel for redundancy, and I have noticed that while one network interface goes down or goes up, the communication on other interfaces hangs for several seconds.
I could reproduce this behavior without my application in a simple way:

there are 2 interfaces available on computer 1 ( Ethernet and WiFi )
ping from computer 2 the IP address of the Ethernet connection of computer 1
disconnect the WiFi of computer 1
ping hangs for seconds, and then the packets are traveling again between the 2 computers.

The hanging happens as well if I turn back on the WiFi connection on computer 1.
It happens as well if I ping the WiFi IP, and turn off/on the Ethernet connection ( or unplug/plug the cable).
I am using Linux Ubuntu 12.04 on both computers.
Any ideas why is this happening, and if / how can it be avoided?
Comment: You may have configured your network such that some of the packets use one interface while some use the other. Before bringing down an interface check with `tcpdump` if there is any traffic on the interface. Bringing down an interface with traffic on it is expected to cause a brief interruption before this traffic gets routed the other way.
Comment: Thanks for the reply. I have checked the traffic with wireshark, and the traffic happens only between the expected IPs, not on both IPs. When I open the TCP socket, I bind it to on IP.  Claudiu
Comment: I was not suggesting the wrong IP was being used, I was suggesting the traffic may be going over a different interface from what you expect.
Comment: My application does not use the interface that I am closing, but other things are going on, like SSDP. Nevertheless, several seconds to re-route this, and even worse when I reconnect. And in this period all the network interfaces are blocked... There must be something wrong...
Answer: This is due to an interesting combination of Linux's "promiscuous ARP" behaviour, and ARP caching.  Essentially, what is happening is that the wifi, despite not having the IP address on itself, is receiving ARP requests, and is sending ARP responses.  If that is the ARP response the other machine on the local subnet (usually the router) receives first, that's what will go into the ARP cache.  The pause in traffic is resolved when the ARP entry goes stale and the ARP request is repeated, at which point the other interface gives the only response, and everything proceeds normally.
To stop Linux doing this "ARP on all interfaces for any address configured", you need to set the sysctl net.ipv4.conf.<interface>.arp_ignore to 1.


What is the minimum n to get a prime pythagorean n-tuple?

Question: I want the minimum n for the equation:
$$X_1^2 + X_2^2 + . . . X_{n-1}^2 = X_n^2$$
Such that the solution only has prime numbers. It easy to check that n > 3. But, what is the minimum n?
Answer: There is no solution for $n=4$ (hint: consider the equation mod $4$), but for $n=5$ there is
$$ 5^2 = 2^2 + 2^2 + 2^2 + 2^2 + 3^2 $$


MySQL wrap join condition with another condition?

Question: I've made a query that works as needed when there is at least 1 row in the url_status table where u.urlid = us.urls however it won't work if this isn't true. What could I do to overcome this?
SELECT u.*, COUNT(*) AS historySize
FROM host_urls u, url_status us
WHERE u.publicationid = 1
AND us.urlid = u.urlid
GROUP BY u.urlid

Answer: You could use an outer join, specifically a left join, which will return at least one result row for each row in host_urls, even if it has no corresponding rows in url_status.
SELECT u.*, COUNT(*) AS historySize
FROM host_urls u
LEFT JOIN url_status us
ON us.urlid = u.urlid
WHERE u.publicationid = 1
GROUP BY u.urlid

You can replace the COUNT(*) with COUNT(us.urlid) (or another column from url_status) if it's important that historySize be zero when there were no matching rows in url_status.


Linear Algebra - If A is invertible then A+I is invertible

Question: Prove the given statement true, or give a counterexample to show that it is false.
If $A$ is an $n*n$ invertible matrix, then $A+I_{n}$ is invertible.
I did some examples and found the statement to be true. But how do i prove it for general case.
Comment: Did you try $A = -I_n$?
Comment: You missed his point. Is the zero matrix invertible?
Comment: I think we can almost say that the opposite is true. if $A$ is invertible there exist a $\lambda$ such that $(A+\lambda I)$ is not invertable.
Comment: I am not aware of this equality
Comment: Another super important point, how can doing a few examples show a statement about infinitely many things to be true?
Comment: @david thanks for the tip. zero matrix is not invertible therefore statement is false.
Answer: The statement
"If $A$ is an $n*n$ invertible matrix, then $A+I_{n}$ is invertible"
is false.
Indeed it is easy to find a couterexample. Let assume $A=-I$ then, since $A^{-1}=A$, $A$ is invertible but $A+I=[0]$.
Comment: @amWhy what is your problem now? Please avoid useless comments and be polite. I've seen Robert's comments but it is not a full answer, indeed Hassan didn't understan his hint.
Comment: I thought you might want to know that she did the same thing to me some days ago.
Comment: @JoséCarlosSantos Well, together we can bear him better!


Compactness implies countably compactness

Question: Let X be compact. Then X is countably compact.
My thinking is like this:
Let X be a topological space. Since compact, then every open cover hava a finite subcover. Hence it is true for countable open cover.
Is this proof true?
Comment: @Zest : True, but why do you mention it? Was it mentioned in a comment that was deleted? "Countably compact" means "every countable open cover has a finite subcover", not "every open cover has a countable subcover" -- is that what you were thinking? That's the Lindelof property.
Comment: a finite set is always countable.
Answer: You are exactly correct.
In particular, countable compactness follows from compactness because every countable open cover is an open cover.


Como importar um arquivo com extensão .er1 no CA Data Modeling

Question: Preciso importar um arquivo .er1 de uma versão antiga do Erwin no CA Data Modeling (Community Edition).
Isto é possível ?
Tentei abrir direto e as opções de "Import" sem sucesso.
Grato por qualquer ajuda ?
Answer: Segundo a pesquisa efectuada a resposta é Não, o CA Data Modeling (Community Edition)  deixou de suportar o formato .er1.
Fonte é esta thread:
Link
mais propriamente este comentário:

Unfortunately, CA ERwin Data Modeler Community Edition (CE) cannot
  open ".er1" files. That is one of the limitations in this product
  version. You'll have to convert the file to a ".erwin" file using the
  commercial version of the product. Another approach is to FE the
  ".er1" model using an appropriate version of CA ERwin Data Modeler and
  then RE using CA ERwin Data Modeler CE. More information on CA ERwin
  Data Modeler CE is located at: www.ca.com/erwin/community.

Pelo que li, deverás de arranjar algum programa que consiga abrir essa extensão, salvar como xml e depois sim tentar importar CA Data Modeling (Community Edition).
Link 1
Link 2
Comment: Parece mesmo jsantos , terei de pensar outra alternativa , preciso recuperar a documentação de um sistema legado da empresa em que trabalho. Quando o SO liberar repasso seus pontos. []´s


How do I override superfish styles?

Question: Do I copy the css files I want to override to a theme I am using?
Comment: This will help you http://drupal.stackexchange.com/questions/23729/superfish-menu-override-css
Answer: This depends the implementation. If the super-fish functionality is already included in a theme (Example: Danland, Danblog), there is most probably already a .css section in the style sheet or a separate .css file related to superfish. If you modify these files, they might be overwritten if you make an update. Thus you optimally make the modification in a local file (local.css in our Example) by copying and modifying the css code.
If you install superfish separately you find all the instructions in the readme.txt of the module:
"How to style
If you know CSS, even basics of it, designing won't be a big challenge.
Here are some tips and tricks:
A) Always use a DOM inspector utility (such as Firebug).
B) Set the "Menu delay" option to a very high number such as 99999999. This will give you enough time to work with sub-menus.
C) If you are not using the built-in styles, set the "Style" option to "None".
D) Utilise the "Simple" style as reference; add the newly-created CSS file either to your theme CSS or as a new CSS file under the styles directory in the Superfish library (probably "sites/all/libraries/superfish/style"); putting it in the styles folder will automatically add it to the styles list in the block configuration."
More information can be found in the Superfish documentation at http://drupal.org/node/1125896"
i.p. 4. within the Installation section
"Upgrade users need to delete the module folder (sites/all/modules/superfish) before uploading the new one. Also, if having any modified CSS files, just move them from sites/all/modules/superfish/css/extra to sites/all/libraries/superfish/style"

How do I override superfish styles?


How to change data-sap-ui-theme of Certain control SAPUI5

Question: I've set them of my sapui5 application data-sap-ui-theme="sap_belize_plus" but for listview I want to change the theme  to data-sap-ui-theme="sap_belize". Is it possible to change theme for certain control ?
Answer: No. The theme parameter is across the application.
But nevertheless you can achieve this using UI Theme Designer.
You can read more here SAP Fiori Theme designer Wiki
These designs will be applied across all the applications.
If you don't want to deal with designer and you are good at CSS then override the specific CSS classes accordingly and add that Custom CSS to your application. Read more here


Get the value of a custom entity field

Question: How can I get the value of a custom field added to user profiles?
I read and tested everything I found on Google, including the following code.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$custom_field_value = $user->field_custom_field->value;
// $custom_field_value = $user->get('field_custom_field')->value;

It does not work, though.
How can I get the value of a custom field in user profiles?
Comment: Does this answer your question? [Get the value of a custom user field](https://drupal.stackexchange.com/questions/195238/get-the-value-of-a-custom-user-field)
Comment: Your field is named custom_field or field_custom_field. You can't refer to the same field by two names.
Comment: hi cilefen, your thread and the code provided doenst work. i have already test it.  i fixed my message and copy/paste error for the field name, sorry for the mistake
Comment: What happens when it doesn't work? The Question does not say. You should add this information to the Question. There is nothing here to distinguish your question from https://drupal.stackexchange.com/questions/195238/get-the-value-of-a-custom-user-field except "doesn't work", but that isn't anything to go on.
Comment: You've added the field to the user profile, but you are looking for it in the user entity. It's possible you mean the same thing, but since there is a popular module Profile it's not necessarily the same.
Answer: If you've added a new field through admin/config/people/accounts/fields and wish to retrieve its value, try the below code:
use Drupal\Core\Session\AccountInterface;

// Get the current user.
$current_user = \Drupal::currentUser();

// Load the user entity.
$user = \Drupal::entityTypeManager()->getStorage('user')->load($current_user->id());

// Check if the user entity exists and has the specified field.
if ($user && $user->hasField('field_custom_field')) {
  // Access the value of the 'field_custom_field' field.
  $custom_field_value = $user->get('field_custom_field')->value;

  // Now $custom_field_value contains the value of the field.
  // You can use it as needed.

}
else {
  // The user entity or the specified field doesn't exist.
}

Comment: This code is not materially different from the OP's example.
Comment: Hey @cilefen, I'm not sure what's ( OP's example). In this code I used `getStorage`.
Comment: They haven't explained what "doesn't work" means. Possibly they haven't loaded a user object, which is what you are insinuating.
Comment: Correct. Based on the assumption that a new field was added via `admin/config/people/accounts/fields`, the goal is to retrieve the value of this field

Get the value of a custom entity field


Delete duplicate values within single worksheet, for multiple worksheets in workbook

Question: I have a workbook with 102 worksheets.  I want to cycle through each worksheet independently and remove duplicates within that worksheet (not across the workbook as a whole).
I currently have this code:
Sub DeleteDuplicates()
Set ws = ThisWorkbook.Worksheets

    For Each X In ws
        X.Range("A:B").RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
    Next

End Sub

I believe it is deleting duplicates that appear anywhere in the workbook, not just within a single worksheet.  Is there a way to limit this code so that it only removes duplicates from within the specific worksheet it is operating on?
Comment: I guarantee you this is operating on X only.
Comment: The code certainly does what I would expect when I run it.  Why do you believe it is deleting duplicates across worksheets?
Comment: Ah - thank you.  I was trying to test it on my original data source and was forgetting to select only the column I was interested in.  Formula works as posted - I guess I shouldn't be so quick to assume I am incorrect.  Appreciate your responses.
Comment: use option explicit at top as well so all variables are declared and becomes clearer what objects are being used where.
Answer: This cycles through each worksheet in your workbook. You can specify worksheets if you need to skip any by adding IF statements.
Public Sub DeleteDuplicates()

    Dim ws as Worksheet
    Dim wb as Workbook

    Set wb = ThisWorkbook

    For Each ws In wb.Worksheets
        ws.Range("A:B").RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
    Next ws

End Sub

Comment: ws is declared as a Worksheet in your code so this will fail Set ws = ThisWorkbook.Worksheets   Also, mixing ThisWorkbook with ActiveWorkbook i think.
Comment: Good catch on the Active/This workbook! I made the change. Cheers


Canonical reference for Naive Bayes classifier

Question: I'm looking for a reference for the Naive bayse classifier to put in my work. Not sure what I'm missing but a scholar search  didn't yield any meaningful results. any idea ?
update: I meant for a reference to put in the bibliography...
Comment: That's a terrible way to write a bibliography.

I suggest *An Essay towards solving a Problem in the Doctrine of Chances*, Philosophical Transactions of the Royal Society of London, Thomas Bayes, 1763. But **read it**.
Comment: If your paper is very technical and unlikely to be read by someone who doesn't master EM, refering to Dempster is merely proving that you know the rules and codes of the community. But if your paper is an application to EM to a particular problem, in e.g. genetics or ecology, refering to Dempster is of no practical use. Some of our readers won't know this algorithm, and what they need to read is not the princeps paper (that you refered without reading it!) but a good and pedagogical introduction.
Comment: I really don't like when some references are always quoted but no one never take the time to read them. I think you should quote your favorite textbook about classification, instead of a "princeps paper" that you don't really care about.
Comment: If you look at [Bayes classifier](http://stats.stackexchange.com/search?q=Bayes+classifier) on this forum, you will find a considerable number of entries.
Comment: @Xi'an. thanks. I know what NB is. I just  looking for for a reference to put in the bibliography...
Comment: @Elvis. thanks - but why this is so terrible  ? :)
Comment: @Elvis my advisor told me, that one should reference always the original paper of an algorithm ... how does the tradeoff graph for read-it and first-reference looks like ;) ? Anways, should make an anwser !
Comment: @steffen In some cases, your advisor is right: for example, when dealing with an EM algorithm, you always refer to Dempster, Laird and Rubin (1977). However in my opinion this means that people dealing with EM should take the time to at least have a look on this paper... But I appreciate when people, besides Dempster et al, have the honesty to refer to one of the textbooks they actually prefer. .../...
Answer: The answer is in the comments to the question (by @Elvis)..."t An Essay towards solving a Problem in the Doctrine of Chances, Philosophical Transactions of the Royal Society of London, Thomas Bayes, 1763"
Comment: I don't think this is an appropriate reference; my understanding is that the Naive Bayes classifier is something different than Bayes law.


count values of a list variable of an object in java

Question: I have an object Student
public class Student {
    protected final String name;
    protected final String[] classes;

    public Student(String name; String[] classes) {
        this.name = name;
        this.classes = classes;
    }

    //getter & setters
}

Student a = new Student("A", new String[]{"math", "physics"});
Student b = new Student("B", new String[]{"math", "chemistry"});
Student c = new Student("C", new String[]{"physics", "chemistry"});

List<Student> students = new ArrayList<Student>();

I want to count how many students have a particular class. Something look like
math: 2
physics: 2
chemistry: 2

I tried to use stream but it's still array of strings thus the wrong answer, I wonder if I can get single string? Thank you.
Map<String[], Long> map = students.stream()
    .collect(Collectors.groupingBy(Student::getClasses,
    Collectors.counting()))

Answer: flatten it then group.
students.stream()
        .flatMap(s -> Arrays.stream(s.getClasses()))
        .collect(Collectors.groupingBy(Function.identity(),
                            Collectors.counting()));


Node ID from hook_comment_insert

Question: I need the ID of the node the inserted comment is attached to. This is what I have tried:
function my-module_comment_insert(Drupal\Core\Entity\EntityInterface $entity)
{

   // According to https://drupal.stackexchange.com/questions/145823/how-do-i-get-the-current-node-id
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
        $nid = $node->id();
    }
    drupal_set_message("The vaue is " . print_r($nid), 'warning');
}

But... The value I get is "1", while it should be (according to node URL) "55". Or am I using drupal_set_message for debugging the wrong way?
I also tried $entity->get('entity_id')->target_id (according to:  How to get the node id the comment is attached to in hook_comment_insert?) or \Drupal::routeMatch()->getRawParameter('node'), but I always get "1" and I'm positive that the website cache has been cleared.
Comment: I saw that, but "$entity->get('entity_id')->value" gives me back "1" too.
Comment: Have you cleared cache?
Comment: Yes, I did clear cache
Answer: print_r($variable) does not return anything useful, it just outputs text (which it does successfully, so it returns boolean TRUE [which is rendered as 1 when printed]). Your drupal_set_message basically does something like echo ($string . $boolean . $string)
Use print_r($variable, true) to return the output of the print_r to the calling function, instead of rendering it.
See https://www.php.net/manual/function.print-r.php
Answer: Look here https://git.drupalcode.org/project/drupal/blob/8.8.x/core/modules/comment/src/Entity/Comment.php#L369
https://api.drupal.org/api/drupal/core%21modules%21comment%21src%21Entity%21Comment.php/function/Comment%3A%3AgetCommentedEntity/8.2.x
and... =) How to get the node id the comment is attached to in hook_comment_insert?
Comment: https://api.drupal.org/api/drupal/core%21includes%21bootstrap.inc/function/drupal_set_message/8.7.x

in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\Messenger\MessengerInterface::addMessage() instead. `\Drupal::messenger()->addStatus('Message');`

Node ID from hook_comment_insert


Saving form data of forms modified with form_alter hook

Question: I understand how to add stuff like checkboxes and fieldsets to existing forms (e.g. the form displayed on the node edit page) using _form_alter. But what I don't understand is how to collect the input and store it in a database table of my choosing (ideally with db_insert). Let's say I've added a checkbox to the fieldsets at the bottom of article_node_form (the form which appears when editing content type article):
<code>$form["Email Notifications"] = array(
    '#type' => 'fieldset',
    '#title' => 'Email Notifications',
    '#collapsible' => 'true',
    '#group' => 'additional_settings',
    '#required' => FALSE,
    'email_notify' => array (
        '#type' => 'checkbox',
        '#title' => 'Notify users of changes to this page',
        '#default_value' => 0,
        '#required' => FALSE,
)
</code>
How do I collect this data an store it in a database?
Answer: Exactly like you alter a form to add custom fields, you alter it to add custom validation and submit handlers.
It should be:
<code>$form['#validate][] = 'custom_validate';
$form['#submit'][] = 'custom_submit';
</code>
use those function to control the additional user input and store them later.
Comment: how would I name my submission handler in my module, supposing my module is called "my_module," the form has the id of "the_form" and the custom submit field is "custom_submit"? It's information like this I can't find anywhere. it seems nothing is ever explicit in the drupal documentation...
Comment: Well, basically, choose the name you want, as long as is not in use... that means it's considered best practice for your module to use name like mymodule_anynameilike. However, i wouldn't call a field "custom_submit", in your case i would call it "email_notification", because it's another best practice to use names that are... self-describing.
Comment: Think about it, you try to alter a form, and you find a field called "custom_submit". And you'll be like: what the hell is this?
Comment: hmm, well the problem I am running into now is that I get an infinite recursion when I try to access $form["Email Notifications"]["email_notify"] in the submission handler. Any ideas? I just want to be able to see if the checkbox is checked within my module.
Comment: I'm an idiot. Just needed to do: $form["Email Notifications"]["email_notify"]['#value']


Defining a spiral in polar coordinates

Question: I'm trying to find a general form for a spiral that fits the following criteria: the inner radius is $N$, and for any point $q$ on the spiral, the arc length from the start of the spiral to $q$ is twice the change in radius from the beginning to that point. For example, if the arc length from the start to point $h$ is $p$, the radius should have change $p/2$ units from the start to $h$, and the radius at $h$ should be $N + p/2$. These properties need to hold for at least the first complete turn of the spiral. I would like to represent the spiral in terms of polar coordinates. How would I go about doing this? An explanation of why the equation is as it is would be great too. Thanks.
Comment: What do you mean by the inner radius? As in the nearest point to the origin on the spiral?
Comment: @DevinMurray Yes, that's what I meant.
Answer: Denote the spiral in polar coordinates by $r=r(\theta)$. Your literal conditions translate into the following equations:
$$r(0)=N $$
$$\int_0^\theta \sqrt{r(\phi)^2+r'(\phi)^2} \mathrm{d}\phi=2(r(\theta)-r(0))=2(r(\theta)-N) $$
(Clearly, there is nothing special about the choice $\theta=0$ as the closest point).
Differentiating the second equation gives $$\sqrt{r(\theta)^2+r'(\theta)^2}=2r'(\theta). $$
If we square both sides we can solve for $r'$:
$$r'(\theta)^2=\frac{1}{3} r(\theta)^2 $$ taking square roots we find $$\frac{\mathrm{d} r}{\mathrm{d} \theta}=\frac{1}{\sqrt{3}} r, $$ so that $$r(\theta)=C \mathrm{e}^{\frac{1}{\sqrt{3}} \theta }.$$ The initial condition shows that $C=N$, and the final solution is $$r(\theta)=N \mathrm{e}^\frac{\theta}{\sqrt{3}}. $$

Defining a spiral in polar coordinates


Can I install and run Redis server with Python?

Question: I am going through Django channel documentation(https://channels.readthedocs.io/en/latest/tutorial/part_2.html), at some point it advise to start redis server with docker as mention below,
We will use a channel layer that uses Redis as its backing store. To start a Redis server on port 6379, run the following command:

$ docker run -p 6379:6379 -d redis:5

However I skipped using docker so I dont know how to run above command.
Is there any way I can start redis server in virtualenv /pip ?
Comment: where do you installed redis server ? are you working on AWS or any other cloud services  or local server ?
Comment: I am working in Localserver
Comment: then download and install it and run it  - https://redis.io/download
Answer:
Is there any way I can start redis server in virtualenv /pip ?

Well, no.
Redis (itself) is not a python package, therefore it can't be installed from pip (a python package manager).
From Redis' official website:

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker

Here is a very detailed guide on how to run and config a working Redis server on Ubuntu and CentOS (select the one suitable for you).
And if you're on Arch (I use Arch, btw), you can always visit the Wiki
Good luck!


How to integrate custom task into aiogram executor?

Question: import asyncio
from threading import Thread
from datetime import datetime
from aiogram import Bot, Dispatcher, executor, types

API_TOKEN = ''

bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)

chat_ids = {}

@dp.message_handler()
async def echo(message: types.Message):
    # old style:
    # await bot.send_message(message.chat.id, message.text)

    chat_ids[message.message_id] = message.from_user
    text = f'{message.message_id} {message.from_user} {message.text}'
    await message.reply(text, reply=False)

async def periodic(sleep_for, queue):
    while True:
        await asyncio.sleep(sleep_for)
        now = datetime.utcnow()
        print(f"{now}")
        for id in chat_ids:
            queue.put_nowait((id, f"{now}"))
            # await bot.send_message(id, f"{now}", disable_notification=True)

def run_tick(queue):
    newloop = asyncio.new_event_loop()
    asyncio.set_event_loop(newloop)
    asyncio.run(periodic(3, queue))

if __name__ == '__main__':
    queue = asyncio.Queue()
    Thread(target=run_tick, args=(queue,), daemon=True).start()
    executor.start_polling(dp, skip_updates=True)

I want to send messages to registered users by bot.send_message when there is a event but failed for now.
Here are what I tried.

bot.send_message crashes because it is called from another thread. (Timeout context manager should be used inside a task)
So, I tried to workaround this by using queue, but there is no way to add my own task into executor.

Is there any simple way to do this?

Edit: 2020-1-3
Here's working example as per @user4815162342.
import asyncio
from datetime import datetime
from aiogram import Bot, Dispatcher, executor, types

API_TOKEN = ''

bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)

chat_ids = {}

@dp.message_handler()
async def echo(message: types.Message):
    chat_ids[message.from_user.id] = message.from_user
    text = f'{message.message_id} {message.from_user} {message.text}'
    await message.reply(text, reply=False)

async def periodic(sleep_for):
    while True:
        await asyncio.sleep(sleep_for)
        now = datetime.utcnow()
        print(f"{now}")
        for id in chat_ids:
            await bot.send_message(id, f"{now}", disable_notification=True)

if __name__ == '__main__':
    dp.loop.create_task(periodic(10))
    executor.start_polling(dp)

Answer: The initial problem was that you tried to call asyncio code from a different thread. To fix the resulting error you have created a new event loop while keeping the additional thread. As the saying goes, now you have two problems.
The queue idea looks unfinished because there is no code that reads from the queue; and even if there were, it wouldn't work because asyncio queues are not designed to be shared between event loops or between threads. To untangle the mess, you need to find a way to run your periodic updates from within the event loop, i.e. re-examine this assumption:

but there is no way to add my own task into executor.

Looking at the source of Executor, it appears to pick up the event loop from the dispatcher, which holds it in the publicly accessible loop attribute. That means that you can create a task simply by invoking the create_task method on that loop. For example:
if __name__ == '__main__':
    dp.loop.create_task(periodic())
    executor.start_polling(dp, skip_updates=True)

Now periodic can be formulated as in your initial attempt:
async def periodic(sleep_for, queue):
    while True:
        await asyncio.sleep(sleep_for)
        now = datetime.utcnow()
        for id in chat_ids:
            await bot.send_message(id, f"{now}",
                                   disable_notification=True)

Please note that I haven't tested this because I do not use aiogram. A potential issue that you might need to address is that your chat_ids dict appears to contain message.message_id as key, whereas bot.send_message accepts a message.chat.id.
Comment: Thank you so much. I totally misunderstood how asyncio works. Now it works as expected due to your thoughtful explanation.
Answer: This code works for aiogram 2.24 version
import asyncio
from aiogram import Bot, Dispatcher

...
dp = Dispatcher(bot)

async def periodical_task():
    while True:
        await asyncio.sleep(15)
        logging.info("Start periodic")

dp._loop_create_task(periodical_task())

Answer: In the new versions the provded methods aren't working anymore, I have the following version:
CPython: 3.9.15 (main, Oct 25 2022, 06:48:03) [GCC 10.2.1 20210110]
OS: Linux-5.15.0-1029-oracle-aarch64-with-glibc2.31
aiogram: 2.23.1
aiohttp: 3.8.3
uvloop: 0.16.0
JSON mode: json

start_pooling function in the executor executes the asyncio.get_event_loop() function, then loop.run_forever(), I found this code in the Aiogram package.
The idea is to create async tasks using the Asyncio module instead of Aiogram.
The following worked for me, I created a function that will be executed on startup, then I created asyncio tasks in that function. When the we call the executor.start_pooling() function, it will run also those async tasks that we created:

from aiogram import Bot, Dispatcher, executor

async def loop_fun_1():
    while True:
        logging.debug("FUN1")
        await asyncio.sleep(5)

async def loop_fun_2():
    while True:
        logging.debug("FUN2")
        await asyncio.sleep(5)

async def on_startup_launch():
    asyncio.create_task(loop_fun_1())
    asyncio.create_task(loop_fun_2())

bot = Bot(token="***")
dp = Dispatcher(bot=bot)
executor.start_polling(
        dispatcher=dp,
        skip_updates=True,
        on_startup=on_startup_launch
    )


Looping background image in Ruby side-scrolling game

Question: I want to loop the background image in a Ruby gosu side scrolling game.I have problem with the counters @k and @p which are used to translate the background image and the duplicated background image.I can't think of a good way to plus them.Here's the code to make it more clear.
require 'gosu'

class GameWindow < Gosu::Window
attr_accessor :x, :y

SHIFT = 700

 def initialize
  super 640,440
  @background  = Gosu::Image.new("./images/bg.png")
  @player      = Gosu::Image.new("./images/000.png")
  @x1, @y1 = 0, 0
  @player_x, @player_y = 50, 50
  @k = 0    #counter
  @p = 1    #counter
 end

 def update
  @x1 -= 3
  @player_y += 1 if @player_y <= 375
  @player_y -= 3 if button_down?(Gosu::KbSpace) and @player_y >= 0

  @coordinates = Gosu::Image.from_text(
    self, "#{@x1},#{@k}", Gosu.default_font_name, 30)
  #here should be the code for @k and @p
 end

 def draw
  @background.draw(@x1  + @k*SHIFT, @y1, 0)
  @background.draw(@x1 +  @p*SHIFT, @y1, 0)
  @player.draw(@player_x, @player_y, 0)
  @coordinates.draw(0, 0, 1)
 end

 def button_down(id)
  $window.close if id == Gosu::KbEscape
 end

end

window = GameWindow.new
window.show

So how do I plus the counters @k and @p.Tried this
if @x1 > -(SHIFT+5)*@p and @x1 < -SHIFT*@p  #705 and 700
  @k += 2
end

if @k > 0 and @x1 > -SHIFT*@k - 5 and @x1 < -SHIFT*@k - 3  #1405 and 1403
  @p += 2
end

but it works only in the beginning(2-3 image shifts).
Also tried this
if @x1 == -SHIFT*@p
  @k += 2
end

and it did not work.
Comment: Okay, this looks overly complicated, and the generic variable names don't help. I'm going to try to detangle what you have and figure it out.
Comment: The "short answer" part of me wants to recommend that you use modulo operators (which you're not using right now) to calculate the offset/wrapping of the screen and just store a single horizontal offset, then take that in your `draw` step, calculate true image offsets there, and render the two backgrounds using those offsets.
Comment: Are you doing vertical scroll as well?
Comment: Also, do you need two `Gosu::Image` instances, or can you just call `draw` twice on the same one with different coordinates?
Comment: Only horizontal.Left to right.Thanks about the gosu::image instances.Did not know that.Gonna fix it.
Answer: Assumptions & Analysis
I'm assuming that @x1 and @y1 are the offset of the left-most background's origin relative to the screen. You also have @player_x and @player_y, which denote the player's position on the screen. Your player is kept horizontally in the center of the screen, moving vertically when jumping or falling, and your background only scrolls horizontally. Also, your window size is 640x440, and your background image is 700px wide and at least 440px tall.
Your update step handles things like jumping (but only to the top of the screen) and simple, constant-velocity gravity, both by modifying the player's screen coordinates. It also provides a constant horizontal scroll by subtracting 3 units per frame from @x1, the horizontal camera coordinate in world-space.
Your draw step then takes the background image and draws two of them, offsetting them by the camera offset @x1 plus the shift for which image is which. This shift, however, isn't important, because we can calculate it fairly simply, and we're left without having to manipulate the additional state of remembering which one is which.
Code Solution
Instead of remembering the counter values @k and @p, we're going to just modulo by the image width to eliminate the excess in @x1 and get it where we need it to be. @k and @p are useless, so delete those. SHIFT can be deleted as well.
Instead, we need to do the following:

Calculate the screen offset of the left-most image
Determine if two images need to be drawn instead of just one
Draw the image(s)

Our goal looks something like this:

Our new code:
require 'gosu'

class GameWindow < Gosu::Window
  attr_accessor :x, :y # side note - are these used at all?

  def initialize
    super 640,440
    @background  = Gosu::Image.new("./images/bg.png")
    @player      = Gosu::Image.new("./images/000.png")
    @x1, @y1 = 0, 0
    @player_x, @player_y = 50, 50
  end

  def update
    @x1 -= 3
    @player_y += 1 if @player_y <= 375
    @player_y -= 3 if button_down?(Gosu::KbSpace) and @player_y >= 0

    @coordinates = Gosu::Image.from_text(
      self, "#{@x1}", Gosu.default_font_name, 30)
  end

  def draw
    # the important bits!
    @local_x = @x1 % -@background.width
    @background.draw(@local_x, @y1, 0)
    @background.draw(@local_x + @background.width, @y1, 0) if @local_x < (@background.width - self.width)

    @player.draw(@player_x, @player_y, 0)
    @coordinates.draw(0, 0, 1)
  end

  def button_down(id) # Side note: Does this work correctly?
    $window.close if id == Gosu::KbEscape
  end

end

window = GameWindow.new
window.show

What this does is, it takes @x1 and modulos it with the (negative) width of the image. This means, it gives the remainder of an integer division of the two numbers. Modulo is very useful when trying to ensure that an integer value "wraps around" after exceeding a limit in either direction; it effectively maps it to between 0 (inclusive) and the given number (exclusive). The results of this are illustrated in the graphic above.
Keep in mind this solution only works as-is for your circumstances; vertical scrolling will require more code, and this will break pretty quickly if your window becomes wider than your background image.
Comment: This is what I was looking for.Thank you!


Understanding the class of all convergent sequences in a discrete space.

Question: Prove: $X$  with the discrete metric $d$ where,
$d(x,y)=\begin{cases} 1,&x\ne y\\0,& x=y\end{cases}$
$ (x_n)$  is convergent if and only if it is constant for a sufficiently large $ n$.
I figured that the best way to prove this is by finding a/the Cauchy sequence(s) since that would prove it is convergent, I am just unsure of how to fully complete this as we have not touched on this in depth in the class as of yet.
Please note: This question is for practice. Not part of an assignment for anything for marks. $d(x,y) $ is supposed to be formatted like a piecewise function, I just do not know how to do that formatting in math stack exchange. Thank you for any help.
Comment: yes, sorry, that is exactly what I meant. Thank you for noticing my error
Comment: What does "it is convergent for a sufficiently large $n$" mean? Perhaps that you meant "constant" here.
Answer: $(X, d_{discrete}) $ be a discrete space.
A sequence $(x_n) $ in $(X, d) $ is convergent iff $(x_n) $ is eventually constant.
$(x_n) $ is eventually constant if $\exists N\in\mathbb{N}$ such that $ x_n= constant $ [for all $n>N$]
Proof:  If $(x_n) $ is eventually constant then it must converge and converges to the constant term.
Now if $(x_n) $ is convergent to $x$ in $(X, d) $
Then given any $\epsilon >0$ $\exists N\in\mathbb{N}$
such that $d(x_n , x) <\epsilon $ for all $n>N$
Since the above inequality is true for any $\epsilon $ as long as it is positive, we can set $\epsilon =1$
Then, $d(x_n, x) <1 , \forall n>N$
Since, $d$ is discrete metric, only possible choice is $d(x_n , x) =0$ for all $n>N$
Hence, $x_n = x $ for all $n>N$
And the sequence is of the form :
$\{x_1 ,x_2 , ...,x_N,x, x, x,...\}$
And hence $(x_n ) $ is eventually constant.
Comment: Thank you! This makes things a lot more clear; I appreciate the help!


How to connect to a nodejs express server through proxy

Question: We have a nodejs http server running on port 8090 on IP 126.96.36.199 and we want to connect to this server via proxy 22.214.171.124:56220.
Our client code is

 this.socket = require('socket.io-client').connect(url,
 {
  // This line ensures that each client connection will have different client.id
  'force new connection': true,
 });

 this.socket.once('connect', function()
 {
 })
 .on('disconnect', function()
 {
 })
 .on('error', function(e)
 {
  console.error("(storetalk.js) ASL: Unable to connect to garuda gateway:- " + e);
 });
Comment: Have you consider using nginx?
Comment: We have a nodejs http server running on AWS on port 8090 and we have a windows desktop client connected to this server via socket.io-client. Now the problem is the client is not working when it is on a LAN a connected to a proxy server
Answer: I have solved this issue using NGinx.
Installed nginx on my red hat server on ip 192.168.10.238
 My node application server is running on same ip on port 8090
 configured nginx to listen on 8020 and configured it with to support socket.io
 my nodejs client is connected to application server via this nginx proxy
Below is my /etc/nginx/nginx.conf configuration file
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events
{
    worker_connections  1024;
}

http
{
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;

    map $http_upgrade $connection_upgrade
    {
        default upgrade;
        '' close;
    }

    server
    {
        listen 8020;

        location /
        {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header X-NginX-Proxy true;
            proxy_pass  http://192.168.10.238:8090;
            proxy_redirect off;

            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            }
    }
}


Find the second order differential equation with given the solution and appropriate initial conditions

Question:
Find the second order differential equation with appropriate initial conditions $y(0)$ and $y'(0)$ and a given solution
  $$y(x) = 5e^{3x} + 4e^{2x} + 6x + 56.$$

How can I find the linear second order differential equation?
(The constants are not the same as the exercise I have to solve, I just need some help understanding a general way of finding the differential equation starting with a solution that looks like the one I've written up there!)
Comment: Please, before submitting questions take some time to work on $LaTeX$, which is the mathematics language code used in this forum ! Here's a [MathJax Tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :). Also, what are your thoughts on the given problem ? What does the symbol $\times$ represent on the final part of your expression ? Seems weird to be there in any case.
Comment: Are there other restrictions? In this generality, also $y''=45e^{3x}+16e^{2x}$ is a valid second order linear DE.
Answer: Hint. Recall the definition of characteristic equation and note that $(z-3)(z-2)=z^2-5z+6$. Then try the following linear second order differential equation
$$y''(x)-5y'(x)+6(y)=Ax+B$$
where $A$ and $B$ are two real numbers to be found. Can you take it from here?
P.S. There are more examples of linear second order differential equation satisfied by the given function. See for example LutzL's comment.
Comment: I'm so sorry, could you please explain me how to find A  and B?
Comment: Since $5e^{3x} + 4e^{2x}$ satisfies the homogeneous equation, it suffices to plug $y(x)=6x+56$ in the LHS and compare the result with the RHS $Ax+B$.